/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


var useConsole = false;

var eventPool = new EventsPool();
var eventMngr = new EventsManager(eventPool, "#actV");

$(document).ready(function(){
    //      init data pulling
    eventPool.run(eventPool);
    setInterval("eventPool.run(eventPool)", 10000);

    //init pooler
    setInterval("eventMngr.run()", 3000);
    
    window.onfocus = function(){ 
        eventMngr.setFocused(true);  
        setTimeout("eventMngr.resetTitle()", 1500);
    };
    document.onblur = function(){ 
        eventMngr.setFocused(false);
    };
})



function EventsPool(){


    this.qEvents = new Array();
    this.lastRemoteEventId = -1;
    this.poolUrl = "/ajax/getActions.jsp?limit=15";
    this.sysInfo = {};

    this.isEmpty = function(){
        return this.qEvents.length == 0
    };
    this.getNextEvent = function(){
        return this.qEvents.shift()
    };
    this.run = function(evtPoolInstance){
        $.ajax({
            url: evtPoolInstance.poolUrl,
            //                url: "/ajax/getActions.jsp?last="+this.lastRemoteEventId,
            dataType: "json",
            data:{
                antiCache : Math.random()
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
                handleError(XMLHttpRequest, textStatus, errorThrown)
            },
            success: function(data, textStatus){
                handleSuccess(data, textStatus, evtPoolInstance)
            }
        });
    };

    function handleSuccess(data, textStatus, evtPoolInstance) {
        var isNewStuff = data.actions.length > 0;

        for(i=0; i< data.actions.length ; i++){
            evtPoolInstance.qEvents.push(data.actions[i]);
            evtPoolInstance.lastRemoteEventId  = data.actions[i].id;
        }

        evtPoolInstance.sysInfo = data.sysinfo;
        evtPoolInstance.poolUrl = "/ajax/getActions.jsp?last="+evtPoolInstance.lastRemoteEventId,
        log("after ajax success, " + (isNewStuff ? "was NEW arrival: "+data.actions.length+" ":""));
    };

    function handleError(XMLHttpRequest, textStatus, errorThrown) {
        log('EPAJXERR: '+textStatus);
    };

    this.toString = function () {
        return "[events pool, size: " + this.qEvents.length + ", lastRemoteEventId: " + this.lastRemoteEventId+"]";
    }
}






function EventsManager(argEventPool, argC){
    //constans
    this.controllerUrl = '/cmnty';

    this.containerAddr = argC;
    this.eventPool = argEventPool;
    this.origTitle = document.title;
    this.unseenMsgCnt = 0;
    this.isFocused = true;
    this.beepInited = false;
    this.beepEnabled = false;
    this.beepWarningShown = false;    

    this.actionsMap = {};
    
    this.commentSendOnKey = false;
    this.popupOnAlert = true;

    this.resetTitle = function(){
        document.title = this.origTitle;
        this.unseenMsgCnt = 0;
    };
    
    this.setFocused = function(isF){ 
        log("fcsd: " + isF); 
        this.isFocused = isF
    };

    this.run = function(){
        var addOddClass = false;

        if(!this.eventPool.isEmpty()){
            var action = this.eventPool.getNextEvent();

            if(! $(this.containerAddr+"_list > p:first").hasClass("odd"))
                addOddClass = true;

            //extra decoration
            var extraS = "";
            if(action.t == 'ADD_COMMENT')
                extraS = "<a class='reply' href='javascript:;' onclick='eventMngr.doClick(\""+action.id+"\")' title='Odpowiedz'><img src='/img/em/reply.png' alt='reply'/></a>";

            $(this.containerAddr+"_list").prepend("<p id='actn_"+action.id+"' class='new' style='display:none'>"+action.msg+extraS+"</p>");

            if(addOddClass)
                $(this.containerAddr+"_list > p:first").addClass("odd");

            $(this.containerAddr+"_list > p:first").addClass("aType_" + action.t);
            
                
            $(this.containerAddr+"_list > p:first").show("slow");

            if(!this.isFocused)
                this.unseenMsgCnt = this.unseenMsgCnt+1;
            
            this.doBeep();
                        
            if(action.notify){
                this.doAlert(action);
            }
            
            this.actionsMap[action.id] = action;
            
        }

        if( !this.isFocused && this.unseenMsgCnt > 0)
            document.title = "("+this.unseenMsgCnt +" nowych akcji) "+this.origTitle;

        this.updateLoggedInfo(eventPool.sysInfo.logged, eventPool.sysInfo.points);
        
        var arrLU  = eventPool.sysInfo.loggedUsers.split(',');
        var domUserList = $("<div />");
        for( var uNick in arrLU ) {
            var currUnick = arrLU[uNick];
            domUserList.append("<p><a class='usr' href='javascript:;' onclick='eventMngr.doClick(123, \"NICK\", \""+currUnick+"\")'>"+currUnick+"</a></p>");
        }
        $("#userList > div").replaceWith(domUserList);
            
        log("...loop: "+this.eventPool);
    };
    
    
    this.doBeep = function(){
        if(  this.beepEnabled)
            document.musicApp.beep();
    };


    this.toggleBeep = function(){
        if(!this.beepInited){
            alert('Uwaga - aby dzwiek byl dostepny musi byc zainstalowana Java.')
            document.getElementById('actVsnd').innerHTML='<applet codebase="/img/em/" code="Beep.class" width="0" height="0" name="musicApp" MAYSCRIPT />';
            this.beepInited = true;
        }

        if(!this.beepEnabled){
            this.beepEnabled = true;
            $("#beepSwitch img").attr("src", "/img/em/beep-on.png");
        }
        else{
            this.beepEnabled = false;
            $("#beepSwitch img").attr("src", "/img/em/beep-muted.png");
        }

        $("#beepSwitch").toggleClass("beepOn");

    };

    this.toggleUserList = function(){
        $(this.containerAddr+" #userList").toggle("slow");
    };

    this.doAlert = function(action){
        
        if(false && this.popupOnAlert){
            var msgT = "Powiadomienie (id:"+action.id+"):\n\n";
            if(action.t == 'ADD_COMMENT'){
                msgT +="Do Twojej fotki wlasnie dodano nowy komentarz.";
            }
          
            msgT += "\n\nKliknij aby zobaczyc.";
          
            alert(msgT);
        }
        $(this.containerAddr+" #actn_"+(action.id)).focus();
        $(this.containerAddr+" #actn_"+(action.id)).addClass("alerted");
    };

    this.doClick = function(actionId, what, val1){
        if(what != null){
            alert("Chat z Autorem '" + val1 +"'\n\nW przygotowaniu...");
            return;
        }
        
        log('doClick ' + actionId);
        var currAct = this.actionsMap[actionId];
        if(currAct.t == "ADD_COMMENT"){
            this.initComment(currAct.fId);
        }
    };

    this.updateLoggedInfo = function(nick, _points){
        this.logged = nick;
        this.points = parseFloat(_points);
        
        var txt = "Niezalogowany";
        if(nick){
            txt = "Zalogowany " +nick;
        }
        $(this.containerAddr+" #loggedInfo").text(txt);
    }

    this.initComment = function(fId){
        if(!this.logged){
            this.showMsg("Aby wysylac komentarze trzeba byc zalogowanym do FG. Zaloguj sie i sprobuj ponownie.", this.containerAddr, true, null);
            return;
        }
        if(this.points<3){
            this.showMsg("Aby wysylac komentarze musisz miec 3 punkty.", this.containerAddr, true, null);
            return;
        }
        if( typeof eventPool.sysInfo.cmntBan != 'undefined'){
            this.showMsg("Brak uprawnien do komentowania.", this.containerAddr, true, null);
            return;
        }
        
        $(this.containerAddr+" #addcmnt #continr").show();
        $(this.containerAddr+" #addcmnt #progress").hide();
        $(this.containerAddr+" #addcmnt textarea").val('');
        $(this.containerAddr+" #addcmnt").fadeIn("fast");
        $(this.containerAddr+" #addcmnt textarea").focus();
        this.commentToggleSendOnKeyEvent();
        this.currfId = fId;
    };

    this.destroyComment = function(){
        $(this.containerAddr+" #addcmnt").fadeOut("fast");
    };

    this.postComment = function(){
        var cmntBdy=$(this.containerAddr+" #addcmnt textarea").val();
        var eventsMngrInstance = this;
        try{
            if("" ==  jQuery.trim(cmntBdy) )
                throw "Brak komentarza!";

            $(this.containerAddr+" #addcmnt #continr").toggle();
            $(this.containerAddr+" #addcmnt #progress").toggle();

            $.ajax({
                type: "POST",
                url: this.controllerUrl,
                data: {
                    _cmd :"addComment",
                    body : cmntBdy,
                    fId : this.currfId,
                    vPlus:'-',
                    l : this.getLoginNick(),
                    pa : this.getLoginPasswd()
                },
                success: function(msg){
                    eventsMngrInstance.eventPool.run(eventsMngrInstance.eventPool);
                    $(eventsMngrInstance.containerAddr+" #addcmnt #progress").toggle();
                    eventsMngrInstance.showMsg("Komentarz wyslany", eventsMngrInstance.containerAddr+" #addcmnt", false, function(){
                        eventsMngrInstance.destroyComment();
                    });
                },
                error:function (XMLHttpRequest, textStatus, errorThrown) {
                    $(eventsMngrInstance.containerAddr+" #addcmnt #progress").toggle();
                    
                    var respT = XMLHttpRequest.responseText;
                    var msg="Problem: " +respT  ;
                    //                    if("401" == XMLHttpRequest.status){
                    //                            msg="Błąd autoryzacji. Sprawdź ustawienia loginu i hasła - kliknij ustawienia. (" +respT+ ")";
                    //                    }
                        
                    
                    eventsMngrInstance.showMsg(msg, eventsMngrInstance.containerAddr+" #addcmnt", true, function(){
                        $(eventsMngrInstance.containerAddr+" #addcmnt #continr").toggle();
                    } );
                }
            });
    
        }
        catch(exc){
            this.showMsg(exc, this.containerAddr+" #addcmnt", true);
        }
      
    };
    
    this.commentToggleSendOnKey = function(){
        if(this.commentSendOnKey){
            this.commentSendOnKey=false;
        }
        else
            this.commentSendOnKey=true;
        
        this.commentToggleSendOnKeyEvent();
    };
    
    this.commentToggleSendOnKeyEvent = function(){
        $(this.containerAddr+" #addcmnt textarea").unbind();        
        if(this.commentSendOnKey){
            var eventsMngrInstance = this;
            $(this.containerAddr+" #addcmnt textarea").keypress( function(e){
                if(e.which == 13)
                    eventsMngrInstance.postComment();
            });
            log('send on enter - enabled');
        }
    };
   
    this.showMsg = function(msgText, containerAddr, ifErr, onClose){
        log(containerAddr);
        var cellAddr="msg_"+(new Date()).getTime();
        $(containerAddr).prepend("<div id='"+cellAddr+"' style='display:none' class='statusMsg'></div>");
        if(ifErr){
            $("#"+cellAddr).addClass("errMsg");
            msgText = "<img src='/img/em/dialog-warning.png' style='vertical-align: middle' /> "+msgText;
        }
        else
            msgText = "<img src='/img/em/dialog-information.png' style='vertical-align: middle' /> "+msgText;

        $("#"+cellAddr).html(msgText);
        $("#"+cellAddr).fadeIn("fast", function(){
            $(this).fadeOut(ifErr ? 5555 : 2222, function(){
                $(this).remove();
                if(onClose != null)
                    onClose();
            } );
        });
    };
    
    this.getLoginNick = function(){ 
        return $(this.containerAddr+" #settngs #l").val();
    };
    this.getLoginPasswd = function(){ 
        return $(this.containerAddr+" #settngs #p").val();
    };
}
function goTo(loc){
    
    if(window.opener){
        window.opener.location=loc;
        window.opener.focus();
    }
    else{
        var newW =  window.open(loc);
        newW.focus();
    }
}

function log(msg){
    if(useConsole != undefined && useConsole)
        console.log(msg);
};

function formatDuration(durationInSecs){
    if(durationInSecs < 60 )
        return "+"+durationInSecs+" sek.";
    else if(durationInSecs < 120)
        return "+1 minuta";
    else if(durationInSecs < 180)
        return "+2 minuty";
    else if(durationInSecs < 240)
        return "+3 minuty";
    else if(durationInSecs < 300)
        return "+4 minuty";
    else if(durationInSecs < 360)
        return "+5 minut";
    else if(durationInSecs < 3600)
        return "+"+parseInt(durationInSecs/60)+ " minut";
    else if(durationInSecs < 3600*2)
        return "+1 godz.";
    else if(durationInSecs < 3600*2)
        return "+2 godz.";
    else
        return "+3 godz.";
    
}
