Notify = function(notices) {
    if (window.notificationSettings) {
        var newNotices=[];
        for (var i=0;notices[i];i++) {
            var n = notices[i];
            if ((notificationSettings.text && n.type=='chat')||
                (notificationSettings.video && n.type=='videochat')||
                (notificationSettings.video && n.type=='imlive_notificator')||
                notificationSettings[n.type]
            ) newNotices.push(n);
        }
        notices = newNotices;
    }
    
    var time = Math.floor((+new Date)/1000);
    var w = {
        videochat: 30,
        talk_live: 25,
        chat: 20,
        mail: 20,
        ask_photo: 17,
        askedinfo: 17,
        admin_mail: 16,
        wink: 15,
        browse: 10,
        logged: 5,
        photo: 5,
        enter_room: 5,
        enter_chat: 5,
        active_video: 5,
        description: 5,
        physical: 5,
        forum_post: 5,
        blog_post: 5,
        new_trusted: 5,
        accept_ft_invite: 5,
        send_ft_invite: 5,
        active_freetonight: 5,
        change_moodline: 5,
        photo_voting: 5,
        try_chat: 5,
        imlive_notificator: 25,
        try_video_chat: 5,
        games_use: 5
    };
    
    notices.sort(function(a, b){
        return (w[a.type] > w[b.type])-(w[a.type] < w[b.type]) || (a.timestamp > b.timestamp)-(a.timestamp < b.timestamp);
    });
    
    var storage = {};
    for(var i=0;notices[i];i++){
        if (w[notices[i].type] === void(0) || notices[i].removed) continue;
        var h = notices[i].type+notices[i].user.id;
        storage[h]=notices[i];
    }
    
    var list = toolbarNotices();
    if (list) {
        var notices = {};
        for (var i=0;list.notices[i];i++) {
            var n = list.notices[i];
            notices[n.type+n.user.id] = n;
        }
        
        for (var h in notices) {
            if (notices[h].type=='chat' && (window.Chat || advChatWindow())) continue;
            if (!storage[h] && notices[h]) notices[h].autoremove();
            else delete storage[h];
        }
    } else {
        for (var h in notifications.storage) {
            if (
                (
                       notifications.storage[h].type=='chat'
                    && (window.Chat || advChatWindow())
                ) ||
                ((
                       notifications.storage[h].type=='chat'
                    || notifications.storage[h].type=='videochat'
                    || notifications.storage[h].type=='fbchat'
                ) && softchat())
            ) continue;
            if (!storage[h])
                notifications.storage[h].remove();
            else delete storage[h];
        }
    }
    
    for(var h in storage) {
        if (
            softchat() &&
            (storage[h].type=='chat' || storage[h].type=='videochat')) continue;
        notifications.add(storage[h]);
    }
    
    if (softchat()) {
        if (jQuery.isEmptyObject(notifications.storage))
            desktopchatNotification.hide();
        else {
            if (desktopchatNotification.needToResize())
                desktopchatNotification.resize();
            desktopchatNotification.show();
        }
    }
}

function toolbarNotices(){
    // toolbarAlerts must be set in toolbar.js
    if (window.toolbarAlerts) return toolbarAlerts.noticeList;
    return false;
}

function softchat (action) {
    var softchat = (window.desktopchatNotification !== void(0)),
        action   = (action || '');
    if (softchat && action) return desktopchatNotification.isNewVersion(action);
    else return softchat;
}


notifications = {
    storage: {},
    container: function() {
        if (!this._container) {
            var c = $('<div id="fixed-container">'+
                '<i class="tl"></i><i class="tr"></i><i class="bl"></i><i class="br"></i>' +
                '<div class="notice-sh">'+
                    '<a class="button-disable" href="/management.notifications.asp">'+T('disable_popups')+'</a>'+
                    '<div class="notice-sh-wrap">'+
                        '<div class="notice-count"></div>'+
(softchat('minimize') ? '<div class="minimize" title="minimize"></div>' : '') + 
                        '<div class="close" title="'+T('closeTitle')+'"></div>'+
                        '<div class="notice-container"></div>'+
                        '<div class="notice-sh-cn notice-sh-tl"></div>'+
                        '<div class="notice-sh-cn notice-sh-tr"></div>'+
                    '</div>'+
                    '<div class="notice-sh-cn notice-sh-bl"></div>'+
                    '<div class="notice-sh-cn notice-sh-br"></div>'+
                '</div>'+
            '</div>').appendTo('body');
            c.elm = c.find('.notice-container');
            c.elm.scrollable = false;
            c.elm.count = c.find('.notice-count');
            c.find('.close').click(function(){
                notifications.clear();
            });
            if (softchat('minimize'))
                c.find('.minimize').click(function () {
                    desktopchatNotification.minimize();
                });
            this._container = c;
        }
        return this._container.elm;
    },
    refreshCount: function() {
        if (!this._container) return;
        var count = 0;
        for(var i in this.storage) count++;
        this._container.elm.count.text(count+' '+T('new_events'));
    },
    onBeforeRemove: function(){
        this._scrollTop = this.container()[0].scrollTop;
    },
    onDestroy: function(h) {
        this.onChange();
        
        var isTop = false;
        var nextActive = false;
        for (var i in this.storage) {
            if (i!=h) {
                nextActive = this.storage[i];
                if (isTop) break;
            }
            if (i==h) {
                if (nextActive) break;
                else isTop = true;
            }
        }
        
        var n = this.storage[h];
        delete this.storage[h];
        
        if (nextActive) {
            var minimizable = true;
            for (var i in this.storage)
                minimizable = minimizable && !this.storage[i]._hover;
            if (minimizable) {
                nextActive.maximize();
                this.container()[0].scrollTop = this._scrollTop;
            }
        }
        
        if (this._container && !is(this.storage)) {
            this._container.remove();
            delete this._container;
        }
    },
    setActive: function(n) {
        if (this.autoHover) {
            clearTimeout(this.autoHover);
            delete this.autoHover;
        }
        var hash = n.type+n.user.id;
        for(var h in this.storage){
            if (h==hash) continue;
            this.storage[h].minimize();
        }
        n.maximize();
    },
    onChange: function(){
        if (!this._container) return;
        var elm = this._container.elm;
        var h = elm[0].clientHeight;
        if (!elm.scrollable && h>220) {
            elm.scrollable = true;
            elm.addClass('scrollable');
            h = 220;
        }
        if (elm.scrollable) {
            var s = elm[0].scrollHeight;
            if (s<=h) {
                elm.scrollable = false;
                elm.removeClass('scrollable');
                elm.count.hide();
            } else {
                this.refreshCount();
                elm.count.show();
            }
        }
    },
    clear: function(){
        var chatsCount = 0;
        var notices = [];
        for (var h in this.storage) {
            var n = this.storage[h];
            notices.push({
                id: n.user.id,
                type: n.type
            });
            if (n.type=='chat') chatsCount++;
        }
        
        if (notices.length > 1
            && chatsCount >= 1
            && !confirm(T('closeConfirm'))
        ) return;
        
        this.storage={};
        this._container.remove();
        delete this._container;
        
        if (typeof desktopchatNotification != 'undefined') {
            desktopchatNotification.hide();
            for (var i=0, l=notices.length; i<l; i++) {
                desktopchatNotification.cancel(notices[i].id, notices[i].type);
            }
        }
        
        $.post('http://'+document.location.host+'/chat/decline.php', $.toJson(notices));
    },
    add: function(o){
        var list = toolbarNotices();
        if (list) {
            list.add(o);
            return;
        }
        var h = o.type+o.user.id;
        if (this.storage[h]) return;
        var minimizable = true;
        for(var i in this.storage)
            minimizable = minimizable && this.storage[i].minimize();
        var n = this.storage[h] = new this.notification(o);
        if (minimizable) {
            n.show();
            this.container()[0].scrollTop = 0;
        } else {
            n.minimize().show();
            this.container()[0].scrollTop += 23;
        }
    },
    remove: function(o) {
        var list = toolbarNotices();
        if (list) {
            for (var i=0;list.notices[i];i++) {
                var n = list.notices[i];
                if (n.type==o.type && n.user.id==o.user.id) {
                    n.autoremove();
                    return;
                }
            }
            return;
        }
        
        var h = o.type+o.user.id;
        var notice = this.storage[h];
        if (notice) notice.remove();
    }
};

notifications.notification = function(opts) {//constructor
    if (typeof opts != 'object') opts = {};
    
    var A = this;
    A.type = opts.type;
    A.timestamp = opts.timestamp;
    A.user = opts.user;
    A.text = opts.text || '';
    A.data = opts.data || {};
    
    var nick = escapeHtml(A.user.nick);
    var for_site = A.user.for_site || '';
    var for_site_id = A.user.for_site_id || '';
    var location = [];
    if (A.user.city) location.push(escapeHtml(A.user.city));
    if (A.user.country) location.push(escapeHtml(A.user.country));
    location = location.join(', ');
    var description = T('sex_'+A.user.sex)+', '+A.user.age+'<br>'+location;
    var who_sex_abr = ((A.user.sex=='f' || A.user.sex=='m')? A.user.sex : 'c');
    
    var title = ({
        videochat: T('video_chat_invitation'),
        chat: T('chat_message_from'),
        mail: T('new_mail_from'),
        ask_photo: T(who_sex_abr+'_AsksYourPhoto'),
        askedinfo: T(who_sex_abr+'_AsksYourInfo'),
        wink: T(who_sex_abr+'_winked_at_you'),
        browse: T(who_sex_abr+'_browsed_you'),
        logged: T(who_sex_abr+'_just_logged'),
        photo: T(who_sex_abr+'_added_photo'),
        enter_room: T(who_sex_abr+'_enter_room'),
        enter_chat: T(who_sex_abr+'_enter_chat'),
        active_video: T(who_sex_abr+'_active_video'),
        description: T(who_sex_abr+'_added_descr'),
        physical: T(who_sex_abr+'_added_physical'),
        forum_post: T(who_sex_abr+'_forum_post'),
        blog_post: T(who_sex_abr+'_blog_post'),
        new_trusted: T('new_trusted'),
        admin_mail: T('new_mail_from'),
        talk_live: T(who_sex_abr+'_talk_live'),
        accept_ft_invite: T(who_sex_abr+'_accept_ft_invite'),
        send_ft_invite: T(who_sex_abr+'_send_ft_invite'),
        active_freetonight: T(who_sex_abr+'_active_freetonight'),
        change_moodline: T(who_sex_abr+'_change_moodline'),
        photo_voting: T('photo_voting'),
        try_chat: T(who_sex_abr+'_try_chat'),
        imlive_notificator: T('video_chat_invitation'),
        try_video_chat: T(who_sex_abr+'_try_video_chat')
    })[A.type];
    
    A._text = ({
        videochat: T('video_chat_invitation_from_nick', {'nick':nick}),
        imlive_notificator: T('video_chat_invitation_from_nick', {'nick':nick}),
        talk_live: T('talk_live_invitation_from_nick', {'nick':nick}),
        chat: T('chat_message_from_nick', {'nick':nick}),
        admin_mail: T('new_mail_from_nick', {'nick':nick}),
        mail: T('new_mail_from_nick', {'nick':nick})
    })[A.type] || '';
    
    if (A.type == 'chat')
        description = opts.text? escapeHtml(opts.text) : '';
    else if ((A.type=='mail' || A.type=='admin_mail') && opts.text)
        description = escapeHtml(opts.text);
    
    var acceptText = ({
        videochat: T('Accept'),
        talk_live: (A.data.type=='confirm'? T('Agree') : T('go_to_inbox')),
        chat: free_trial_split_enabled ? T('Reply_FREE') : T('Reply'),
        mail: free_trial_split_enabled ? T('go_to_inbox_free') : T('read'),
        admin_mail: T('read'),
        ask_photo: T('add_photo'),
        askedinfo: T('askedinfo'),
        send_ft_invite: T('accept_ft_invite'),
        photo_voting: T('Yes'),
        try_chat: T('start_chat'),
        imlive_notificator: T('Video Chat'),
        try_video_chat: T('start_video_chat')
    })[A.type] || (free_trial_split_enabled ? T('text_chat_free') : T('text_chat'));

    var user_data = '<a href="/profiles/'+A.user.id+'" title="'+T('view_profile')+'" class="notice-photo">'+
                    '<img width="80" height="99" alt="'+T('view_profile')+'" src="'+A.user.photo+'"></a>'+ 
                    '<h2>'+title+' <br><a href="/profiles/'+A.user.id+'" title="'+T('view_profile')+'">'+nick+'</a></h2>';

    var site_data = '';
    if (for_site != '' && for_site_id != '') {
        site_data = '<div class="multi_icon multi_icon_small multi_icon_notification"><span class="site_name" title="' +
                        for_site + '"><i class="multi_icon_logo_' + for_site_id + '"/></i></span></div>';
    }

    A.elm = $(
    '<div class="event-notice '+A.type+'-notice">' + site_data + user_data +
        '<div class="notice-text">'+description+'</div>'+
        '<div style="clear:both"></div>'+
        '<div class="notice-buttons">'+
            '<div class="button-accept">'+acceptText+'</div>'+
            '<div class="button-decline">'+(
                A.type=='mail'||A.type=='admin_mail'||A.type=='imlive_notificator'?
                T('Close'):T('no_thanks')
            )+'</div>'+
        '</div>'+
    '</div>');
    A.elm.photo = A.elm.find('.notice-photo img');
    
    A.elm.click(function(e) {
        var t = $(e.target);
        if (t.hasClass('button-decline')) {
            if (this.type=='imlive_notificator') {
                $.post('http://'+document.location.host+'/chat/decline.php', {type:A.type});
            }
            else if (A.type=='videochat') {
                if (advChatWindow()) advChatWindow().cancelVideoChat(A.user.id);
                else $.post('http://'+document.location.host+'/chat/video.php', {action:'cancel', to:A.user.id});
            } 
            else if (A.type=='chat') {
                if (window.Chat) Chat.declineChat(A.user.id);
                else if (advChatWindow()) advChatWindow().declineChat(A.user.id);
            }
            else $.post('http://'+document.location.host+'/chat/decline.php', {id:A.user.id, type:A.type});
            A.close();
        } else if (t.hasClass('button-accept')) {
            var source = A.type+'_notice';
            if (A.type == 'mail') $.gotoUrl(A.data.destination + '&mail_to=' + A.user.chat_to);
            else if (A.type == 'admin_mail') $.gotoUrl(A.data.destination);
            else if (A.type == 'videochat') videochat(A.user.id, source);
            else if (A.type == 'ask_photo') $.gotoUrl('/my_photos.php');
            else if (A.type == 'askedinfo') $.gotoUrl('/myaccountmanagement.asp');
            else if (A.type == 'talk_live') {
                if (A.data.type=='confirm')
                    $.gotoUrl('/talk_live_confirm.php?'+
                        'call_id='+A.data.call_id+
                        '&from_id='+A.user.id+
                        '&source='+source
                    );
                else
                    $.gotoUrl('/email.asp');
            }
            else if (A.type == 'photo_voting') {
                if (A.data.action == 'admirers') {
                    $.gotoUrl('/photo.voting.php?action=show_admirers_profiles');
                }
                else if (A.data.action == 'mutual') {
                    $.gotoUrl('/photo.voting.php?action=show_mutual_profiles');
                }
            }
            else if (A.type == 'try_chat') {
                if (A.data.redirect_to_paymentpage == 1){
                    $.gotoUrl(A.data.upgrade_url, true);
                }
                else {
                    textchat(A.user.id, source);
                }
            }
            else if (this.type == 'imlive_notificator') {
                open('/live.signup.php?promocode='+this.data+'&nickname='+this.user.nick, "_blank");
            }
            else if (A.type == 'try_video_chat') {
                if (A.data.redirect_to_paymentpage == 1){
                    $.gotoUrl(A.data.upgrade_url, true);
                }
                else {
                    videochat(A.user.id, source);
                }
            }
            else textchat(A.user.id, source, A.user.chat_to);
            A.close();
        }
    }).hover(function() {
        A._hover=true;
        notifications.setActive(A);
    }, function(){
        A._hover=false;
    });
    
    A._minimized = false;
    
    notifications.container().prepend(A.elm);
};
notifications.notification.prototype = {
    show: function() {
        var A = this;
        A.elm.show();
        notifications.onChange();
        if (A._text) titleBar.scrollText(A._text);
        return this;
    },
    close: function() {
        if (this._closed) return this;
        this._closed = true;
        notifications.onBeforeRemove();
        this.elm.remove();
        this.destroy();
        notifications.onChange();
        return this;
    },
    remove: function() {
        if (this._hover) return false;
        return this.close();
    },
    destroy: function() {
        this.onDestroy();
        titleBar.restore();
        return this;
    },
    minimize: function(){
        if (this._minimized) return this;
        if (this._hover) return false;
        this._minimized = true;
        this.elm.addClass('minimized');
        return this;
    },
    maximize: function(){
        if (!this._minimized) return this;
        this._minimized = false;
        this.elm.removeClass('minimized');
        notifications.onChange();
        return this;
    },
    removeable: function() {
        return !this._hover;
    },
    onDestroy: function(){
        notifications.onDestroy(this.type+this.user.id);
        return this;
    }
};

window.onload = function() {
    var focus = function(){hasFocus = true;};
    var blur = function(){hasFocus = false;};
    if (typeof window.onfocus != 'undefined' && typeof window.onblur != 'undefined') {
        window.onfocus = function(){hasFocus = true;};
        window.onblur = function(){hasFocus = false;};
    } else {
        document.onfocus = function(){hasFocus = true;};
        document.onblur = function(){hasFocus = false;};
    }

    document.onmouseover = function(){hasFocus = true;};
};
titleBar = {
    scrollText: function(text){
        if (!this.scrolls)
            this._text = document.title;
        if (!text) text = document.title;
        text = '. '+text;
        this.scrolls = true;
        clearInterval(this.scrollInterval);
        this.scrollInterval = setInterval(function(){
            text = text.slice(1)+text.charAt(0);
            if (window.hasFocus)
                titleBar.restore();
            else document.title = text;
        }, 300);
    },
    restore: function(){
        clearInterval(this.scrollInterval);
        if (this._text) document.title = this._text;
        this.scrolls = false;
    }
};
