// Notifications API - Check if enabled
var notifyEnabled = false;
var showNotifications = false;

var btn_showNotifications = "Show notifications";
var title_showNotifications = "Start displaying notifications about new news items for current tab.";
var btn_stopNotifications = "Stop notifications";
var title_stopNotifications = "Stop displaying notifications.";

var notifyTimeout;
var notifyTimeoutInterval = 300000;  // 300 sec 

var notify;

$(function() {
    // Check if notifications supported
    if(window.webkitNotifications) {
        notifyEnabled = true;
    }
    
    $("#showNotifications").prop("title", title_showNotifications);
    
    // If notifications not supported hide notification button
    if(!notifyEnabled) {
        $("#showNotifications").hide();
        return;    
    }
    
    notify = new Notify();
    
    //
    $("#showNotifications").bind("click", function(event) {
        event.preventDefault();
        btn = $("#showNotifications");
        
        // Toggle between enabling and disabling notifications
        if(showNotifications) {
            // Stop showing notifications
            showNotifications = false;
            btn.html(btn_showNotifications);
            btn.prop("title", title_showNotifications);
            
            // Stop timeout
            clearInterval(notifyTimeout);
        }
        else {
            if(0 != window.webkitNotifications.checkPermission()) {
                window.webkitNotifications.requestPermission();    
            }
            
            // Start showing notifications
            showNotifications = true;
            btn.html(btn_stopNotifications);
            btn.prop("title", title_stopNotifications);
            
            // Start timeout
            notifyTimeout = setInterval(pollAjax, notifyTimeoutInterval);
        }
    });
});

// Try to get updated news items for current tab via ajax polling
function pollAjax() {
    sendSiteID(activeTab);
}

// Notify class
function Notify() {
    var prop;
}

// Create notification based on notification type                                  
Notify.prototype.createNotificationInstance = function(options) {
    if (options.notificationType == 'simple') {
        return window.webkitNotifications.createNotification(
            'portal/images/avfav32.png', options.title, options.content);
    } else if (options.notificationType == 'html') {
        return window.webkitNotifications.createHTMLNotification('http://zabkar.net');
    }
}

// Show notification
Notify.prototype.fireNotification = function(options) {
    if(0 == window.webkitNotifications.checkPermission()) {        
        this.createNotificationInstance(options).show();
    } 
    else {    
        alert("You need to permit notifications");    
    }
}
