/**
 * Created by JetBrains PhpStorm.
 * User: silver
 * Date: 22.07.11
 * Time: 15:12
 * To change this template use File | Settings | File Templates.
 */
var GSMail = {
    template: '<li style="display: none"><div class="gs-gui-mail-%TYPE%">%TEXT%</div></li>',
    templateError: '<li style="display: none"><div class="gs-gui-mail-error" onclick="$(this).parent().remove();"><div class="gs-gui-mail-exit">x</div>%TEXT%</div></li>',
    intervalTimer:false,
    intervalDelay:15000,
    flashMessages:[],
    show: function(text, type) {
        if(type != 'error')
            var html = this.template.replace(/%TYPE%/i, type);
        else
            var html = this.templateError.replace(/%TYPE%/i, type);
        html = html.replace(/%TEXT%/i, text);
        html = $(html);
        if(type != 'error') {
            setTimeout(function(){
                html.fadeOut('slow', function() { html.remove(); })
            }, 5000);
        }
        html.hover(function(){ html.css('opacity', '1'); }, function(){ html.css('opacity', '0.7'); });
        $('.gs-gui-mail-window').append(html);
        html.css('opacity', '0.7');
        html.fadeIn('slow');
    },
    flash: function() {
        for(var i = 0; i < this.flashMessages.length; i++) {
            GSMail.show(this.flashMessages[i].text, this.flashMessages[i].type);
        }
    },
    add:function(text, type) {
        GSMail.flashMessages.push({text:text, type:type});
    },
    check: function() {
        this.request();
        this.intervalTimer = setInterval(function(){
            GSMail.request();
        }, this.intervalDelay);
    },
    request: function() {
        core.action('checkMail', {}, function(text){
                if(!text) return;
                text = jQuery.parseJSON(text);
                if(text.error) {
                    return GSMail.show(text.error, 'error');
                } else {
                    for(var i = 0; i < text.length; i++) {
                        GSMail.show(text[i], 'message');
                    }
                }
            });
    },
    stop: function() {
        clearInterval(this.intervalTimer);
    }
}
