var in_notifications_popup = false;
var c_n;//current notification
$(document).ready(function() {
    $('#notifications-friend-trigger').live('click', function(event) {
        event.preventDefault(); // prevent 'href' loading
        event.stopPropagation(); // prevent 'click' event propagation to whole page
        topobj.toggleNotifications('friend', this);
    });
    $('#notifications-notice-trigger').live('click', function(event) {
        event.preventDefault(); // prevent 'href' loading
        event.stopPropagation(); // prevent 'click' event propagation to whole page
        topobj.toggleNotifications('notice', this);
    });
    $('#notifications-popup').live('mouseenter', function(event) {
        in_notifications_popup = true;
    });
    $('#notifications-popup').live('mouseleave', function(event) {
        in_notifications_popup = false;
    });
    $('.unread').live('mouseenter', function() {
       $(this).removeClass('unread');
    });
    $('html').click(function() {
        if (!in_notifications_popup) {
            $('.h-menu-em #notifications-popup').remove();
            $('.notifications-trigger').removeClass('active_trigger');
        }
    });
});

if (typeof topobj == 'undefined') {
    var topobj = {};
}

/**
 *
 * @access public
 * @return void
 **/
topobj.countUsersNotifications = function(count) {
    var s_counter = '';
    var count = parseInt(count - 1);
    if (count > 0) {
        re = /[^-]{0,2}$/i;
        t1 = count.toString().match(re);
        t1 = parseInt(t1);
        re = /[^-]{0,1}$/i;
        t2 = count.toString().match(re);
        t2 = parseInt(t2);
        if (t1==1) {
            pref = user;
        } else if (t1 > 5 && t1 <= 20) {
            pref = users;
        } else if (t2 == 1) {
            pref = users21;
        } else if (t2 >= 2 && t2 <= 4) {
            pref = users22;
        } else {
            pref = users;
        }
        s_counter = ' '+and_more+' ' + count + ' ' + pref;
    }
    return s_counter;
}

topobj.clearLinks = function(html) {
    var div =document.createElement("div");
    $(div).html(html);
    $(div).find('a.convtospan').each(function(){
        $(this).replaceWith("<span>" + $(this).html() + "</span>");
    });
    return $(div).html();
}

topobj.toggleNotifications = function(c, em) {
    $('.h-menu-em #notifications-popup').remove();
    $('.notifications-trigger').removeClass('active_trigger');
    if (c_n != c) {
        c_n = c;
        $(em).after('<div id="notifications-popup"></div>');
        $("#notifications-popup").html('<img class="loading" src="/img/loading.gif" width="16" />').show();
        $('#notifications-'+c+'-trigger').addClass('active_trigger');
        $('#notifications-popup').attr('nc', c).css({top:37, left:-1}).html('<img class="loading" src="/img/loading.gif" width="16" />').show();
        //$('#notifications-popup').css('position', 'fixed');
        var unread, q;
        if(c=='notice'){
            unread='';
            q=5;
        }else{
            unread='&unread=1';
            q=5;
        }
        //$('#notifications-popup').html('');
 
    $.getJSON('/notifications?c='+c+'&view=json'+unread+'&q='+q+'&compact=true', function(data) {
            var h = '';
            var set_read_id = '';
            $('#notifications-popup').append('<div id="notification_shadow"></div>');
            $.each(data, function(key, val) {
                var ignore_button = '<div class="markasread-trigger" data-key="'+key+'">&times;</div>';
                var avatar_img = val.avatar_img;
                var text = topobj.clearLinks(val.text);
                var url = val.url;
                var onclick = '';
                if(typeof val.onclick != 'undefined'){
                    onclick = val.onclick;
                }
                if (text.length > 103 && c!='friend') {
                    text = text.substr(0, 100) + '...';
                }
                var title = topobj.clearLinks(val.title);
                var classname = val.is_read == 1 ? 'notification_wrap' : 'notification_wrap unread';
                h = '<div data-url="'+url+'" '+onclick+' class="'+classname+'" id="notification-' + key + '">'
                      + '<div class="imageBlock"><div style="float:left;background-image:url(\'' + avatar_img + '\')" class="imageBlockImage"></div><div style="float:left;width:74%;">' + title + '<br />' + text + '</div>'
                      + ignore_button + '</div></div>'
                     
                $("#notifications-popup img").remove();
                $('#notifications-popup').append(h);
                set_read_id = key + ',' + set_read_id;
             
            });
           

            if (h.length < 1) {
                $("#notifications-popup img").remove();
                $('#notifications-popup').append('<div class="notification_wrap"><i>'+no_new_messages+'</i></div>');
                $('#notifications-popup').append('<div id="notifications-popup-footer"><a href="/notifications?c=' + c + '" class="right">'+show_more+'</a></div>');
            } else {
                $('#notifications-popup').append('<div id="notifications-popup-footer"><a onclick="topobj.clearNotifications(this);return false;" href="/notifications?a=del&c=' + c + '" class="left">'+clear_+'</a><a href="/notifications?c=' + c + '" class="right">'+show_more+'</a></div>');
            }
            //загруженные отметить как прочитанные
            if (c == 'notice') {
                $('#notifications-notice-unread-count').remove();
                //topobj.markNotificationAsReadSilent(set_read_id);
            }
        });
    }  else {
       c_n = undefined;
    }
}

topobj.addFriendFromNotification = function(notification_id, friend_id) {
    topobj.markNotificationAsRead(notification_id);
    addToFriends(true, friend_id);
}

topobj.markNotificationAsReadSilent = function(id) {
    $.getJSON('/notifications?action=markasread&id=' + id, function(data) {
        $.each(data, function(key, val) {
            if (val > 0) {
                $('#notifications-' + key + '-unread-count').html(val).show();
            } else {
                $('#notifications-' + key + '-unread-count').hide();
            }
        });
    });
}

topobj.markNotificationAsRead = function(id) {
    $('#notification-' + id + '').hide('slow', function() {
        $(this).remove();
    });
    $.getJSON('/notifications?action=markasread&id=' + id, function(data) {
        $.each(data, function(key, val) {
            if (val > 0) {
                $('#notifications-' + key + '-unread-count').html(val).show();
            } else {
                $('#notifications-' + key + '-unread-count').hide();
                /*if ($('#notifications-popup').attr('nc') == key) {
                    $('#notifications-popup').attr('nc', '').html('').hide();
                }*/
            }
        });
    });
}

topobj.clearNotifications = function(elem) {
    href = $(elem).attr('href');
    found = href.match(/c\=([a-z]+)/i);
    var type = found[1];
    $.get('/notifications/?a=del&c=' + type);
    $('#notifications-' + type + '-unread-count').text('').hide();
    $('#notifications-popup .notification_wrap').slideUp(500, function () {
        //$('#notifications-popup .notification_wrap').remove();
    });
    $('#notifications-popup #notification_shadow').after('<div class="notification_wrap"><i>'+no_new_messages+'</i></div>');
    return false;
}

topobj.toggleProfilePopup = function() {
    var offset = $('#profile-popup-trigger').offset();
    $('#profile-popup').css({top: offset.top + 20, left: offset.left - 250 + 11}).toggle();
}

$(document).ready(function() {
    $('#profile-popup-trigger').click(function(event) {
        event.preventDefault(); // prevent 'href' loading
        event.stopPropagation(); // prevent 'click' event propagation to whole page
        topobj.toggleProfilePopup();
    });
    $('#profile-popup').click(function(event) {
        event.stopPropagation(); // prevent 'click' event propagation to whole page
    });
    $('html').click(function() {
        $('#profile-popup').hide();
    });
    $('.notification_wrap').live('click', function(){
        window.location.href = $(this).data('url');
    });                
    $('.markasread-trigger').live('click', function(){
        topobj.markNotificationAsRead($(this).data('key'));
        return false;
    }); 
    $('.pf-item-add').live('click', function(){
        topobj.addFriendFromNotification($(this).data('notif-id'), $(this).data('friend-id')); return false;
        return false;
    });     
});

