var ceTeamStatus;
var pollStatus;
var replyWin;
var replyField;

Ext.onReady(function(){
    replyField = new Ext.form.TextArea({
        id:         "replyfield",
        border:     false,
        hideLabel:  true,
        anchor:     '100%',
        grow:       true,
        name:       'replyfield'
    });
    
    replyWin = new Ext.Window({
        id:           "replyWindow",
        x:            400,
        y:            200,
        labelAlign:   'right',
        layout:       'form',
        width:        400,
        autoHeight:   true,
        defaultType:  'textfield',
        closeAction:  'hide',
        title:        lang("Your reply:"),
        plain:        true,
        closable:     true,
        buttonAlign:  'right',
        items:        [
            replyField
        ],
        buttons:      [
            {
                id:       'btnReply',
                text:     lang("Reply"),
                disabled: false,
                hidden:   false,
                handler:  function(){
                    sendReplyTeamStatus();
                }
            }
        ]
    });
});

function timeElapsed(secondsElapsed)
{
    var TimeDifference = 0;
    var TimeScale = "";
    
    if(secondsElapsed < 60){
        TimeDifference = secondsElapsed;
        TimeScale = "second";
    }else{
        if(secondsElapsed < (60 * 60)){
            TimeDifference = Math.floor(secondsElapsed / 60);
            TimeScale = "minute";
        }else{
            if(secondsElapsed < (24 * 60 * 60)){
                TimeDifference = Math.floor(secondsElapsed / (60 * 60));
                TimeScale = "hour";
            }else{
                if(secondsElapsed < (31 * 24 * 60 * 60)){
                    TimeDifference = Math.floor(secondsElapsed / (24 * 60 * 60));
                    TimeScale = "day";
                }else{
                    if(secondsElapsed < (365 * 24 * 60 * 60)){
                        TimeDifference = Math.floor(secondsElapsed / (31 * 24 * 60 * 60));
                        TimeScale = "month";
                    }else{
                        TimeDifference = Math.floor(secondsElapsed / (365 * 24 * 60 * 60));
                        TimeScale = "year";
                    }
                }
            }
        }
    }
    
    if(TimeDifference > 1 || TimeDifference == 0){
        TimeScale += "s";
    }
    
    var TimeElapsed = TimeDifference + " " + TimeScale + " ago";
    
    return (TimeElapsed);
}

function CETeamStatus ()
{
    /* Team Status List */
    this.statusList  = [];
    this.statusCount = 0;
    this.statusTpl   = new Ext.Template(
        '<div id="teamStatus{id}" class="teamstatusmsg">',
            '<table width="100%">',
                '<tr>',
                    '<td width="48px" style="padding-top: 10px; padding-bottom: 10px" valign="top">',
                            '<a onclick=\'clickTeamUser("{userid}", "{fullname}");\'>',
                                '<div class="teamspeakprofileimg"> <img width="48px" height="48px" src="{pictureurl}" qtip="Filter by this user. Group: {group}. Email: {email}" /></div',
                            '</a>',
                    '</td>',
                    '<td style="padding-top: 10px; padding-left: 10px; padding-bottom: 10px">',
                        '<a style="text-decoration: none" onclick=\'clickTeamUser("{userid}", "{fullname}");\'>',
                            '<span style="font-weight:bold" qtip="Filter by this user. Group: {group}. Email: {email}">{fullname}</span>',
                        '</a>',
                        '<span id="inreplyto{id}" style="color: green; font-weight:bold; display: {displayInReplyTo}" qtip="{reply_details}"> in reply to </span>',
                        '<a style="text-decoration: none; display: {displayInReplyTo}" onclick=\'clickTeamUser("{useridreplied}", "{fullnamereplied}");\'>',
                            '<span id="replieduser{id}" style="color: blue; font-weight:bold" qtip="Filter by this user. Group: {groupreplied}. Email: {emailreplied}">{fullnamereplied}</span>',
                        '</a>',
                        '&nbsp;',
                        ' (<span id="status_datetime{id}" style="color: green; font-size:10px" qtip="{status_datetime}">{status_datetime_string}</span>)',
                        '&nbsp;&nbsp;',
                        '<div style="margin-bottom:3px;">{userstatus}</div>',
                        '<div class="teamstatusmsgfooter">',
                            '<a style="display: {displayDelete}" onClick="deleteTeamStatus(\'{id}\',\'{userid}\');"><span style="color: red">delete</span>',
                            '</a>&nbsp;-&nbsp;',
                        '<a onClick="replyTeamStatus(\'{id}\');"><span style="color: blue">reply</span></a></div>',
                    '</td>',
                '</tr>',
            '</table>',
        '</div>'
    );
}

CETeamStatus.prototype.process = function(e){
    // Update the count if it has changed
    if(this.statusCount != e.totalcount){
        this.statusCount = e.totalcount;
    }
    
    if(pollStatus.baseParams.start > 0 &&  e.teamstatus.length == 0){
        paginate('newer');
        exit;
    }
    
    var displayNewerLink = '';
    var displayPaginationSeparator = '';
    var displayOlderLink = '';
    
    if(pollStatus.baseParams.start == 0){
        displayNewerLink = 'none';
        displayPaginationSeparator = 'none';
    }
    
    if((pollStatus.baseParams.start + pollStatus.baseParams.limit) >= this.statusCount){
        displayOlderLink = 'none';
        displayPaginationSeparator = 'none';
    }
    
    $('newest_link').style.display = displayNewerLink;
    $('pagination_separator_n').style.display = displayNewerLink;
    $('newer_link').style.display = displayNewerLink;
    $('pagination_separator').style.display = displayPaginationSeparator;
    $('older_link').style.display = displayOlderLink;
    $('pagination_separator_o').style.display = displayOlderLink;
    $('oldest_link').style.display = displayOlderLink;
    
    // If there are no items, then show a message
    var displayNoItems = 'none';
    
    if(this.statusCount == 0){
        displayNoItems = '';
    }
    
    $('no_items').style.display = displayNoItems;
    
    var statusLowerUpdatedTimeStamp = -1;
    
    // Loop through the statusList to see if they are in poll result
    // NOTE: looping backwards so the indices aren't broken when we remove from the list
    for(i = this.statusList.length - 1; i >= 0 ; i--){
        var index = -1;
        
        for(j = 0; j < e.teamstatus.length; j++){
            if(e.teamstatus[j].id == this.statusList[i].id){
                index = j;
                break;
            }
        }
        
        if(index == -1){
            // if they are not in the poll result, remove them
            $("teamStatus" + this.statusList[i].id).parentNode.removeChild($("teamStatus" + this.statusList[i].id));
            this.statusList.splice(i, 1);
        }else{
            if(parseInt(this.statusList[i].status_datetime_stamp) < statusLowerUpdatedTimeStamp
              || statusLowerUpdatedTimeStamp == -1){
                statusLowerUpdatedTimeStamp = parseInt(this.statusList[i].status_datetime_stamp);
            }
            
            $('status_datetime' + this.statusList[i].id).innerHTML = timeElapsed(e.teamstatus[index].seconds_elapsed);
            
            if(e.teamstatus[index].reply_details != undefined
              && e.teamstatus[index].reply_details != ''){
                $('inreplyto' + this.statusList[i].id).qtip = e.teamstatus[index].reply_details;
                $('inreplyto' + this.statusList[i].id).style.display = '';
                $('replieduser' + this.statusList[i].id).style.display = '';
            }else{
                $('inreplyto' + this.statusList[i].id).qtip = '';
                $('inreplyto' + this.statusList[i].id).style.display = 'none';
                $('replieduser' + this.statusList[i].id).style.display = 'none';
            }
            
            e.teamstatus.splice(index, 1);
        }
    }
    
    // Now process the oldest remaining teamstatus in the poll result
    // These are new teamstatus.
    if(statusLowerUpdatedTimeStamp > -1){
        // NOTE: looping backwards to add the oldest status at the end
        //       and to avoid the indices to be broken when we remove from the list
        for(i = e.teamstatus.length - 1; i >= 0; i--){
            if(parseInt(e.teamstatus[i].status_datetime_stamp) < statusLowerUpdatedTimeStamp){
                e.teamstatus[i].status_datetime_string = timeElapsed(e.teamstatus[i].seconds_elapsed);
                
                if(e.teamstatus[i].userid == e.self){
                    e.teamstatus[i].displayDelete = '';
                    e.teamstatus[i].spaces = '&nbsp;&nbsp;';
                }else{
                    e.teamstatus[i].displayDelete = 'none';
                    e.teamstatus[i].spaces = '';
                }
                
                if(e.teamstatus[i].reply_details != undefined
                  && e.teamstatus[i].reply_details != ''){
                    e.teamstatus[i].displayInReplyTo = '';
                }else{
                    e.teamstatus[i].displayInReplyTo = 'none';
                }
                
                this.statusTpl.append("teamstatus", e.teamstatus[i]);
                
                this.statusList[this.statusList.length] = e.teamstatus[i];
                
                e.teamstatus.splice(i, 1);
            }
        }
    }
    
    // Now process any remaining teamstatus in the poll result
    // These are new teamstatus.
    for(i = 0; i < e.teamstatus.length; i++){
        e.teamstatus[i].status_datetime_string = timeElapsed(e.teamstatus[i].seconds_elapsed);
        
        if(e.teamstatus[i].userid == e.self){
            e.teamstatus[i].displayDelete = '';
            e.teamstatus[i].spaces = '&nbsp;&nbsp;';
        }else{
            e.teamstatus[i].displayDelete = 'none';
            e.teamstatus[i].spaces = '';
        }
        
        if(e.teamstatus[i].reply_details != undefined
          && e.teamstatus[i].reply_details != ''){
            e.teamstatus[i].displayInReplyTo = '';
        }else{
            e.teamstatus[i].displayInReplyTo = 'none';
        }
        
        this.statusTpl.insertFirst("teamstatus", e.teamstatus[i]);
        
        this.statusList[this.statusList.length] = e.teamstatus[i];
    }
    
    Ext.QuickTips.init();
}

// Moved the loading of the team status away from the ext.onload to a seperate function
function PluginTeamStatus()
{
    // Clear any previous instance of ceTeamStatus to avoid duplicate data being displayed
    ceTeamStatus = undefined;
    ceTeamStatus = new CETeamStatus();
    
    pollStatus = new Ext.direct.PollingProvider({
        type:       'polling',
        url:        'index.php?fuse=home&action=GetTeamStatus',
        baseParams: {
            start:  parseInt(document.forms['pagination_form'].elements['start'].value),
            limit:  parseInt(document.forms['pagination_form'].elements['limit'].value),
            group:  parseInt(document.forms['pagination_form'].elements['group'].value),
            user:   parseInt(document.forms['pagination_form'].elements['user'].value)
        },
        interval:   60000
    });
    
    Ext.Direct.addProvider(pollStatus);
    
    Ext.Direct.on('teamStatus', function(e) {
        ceTeamStatus.process(e);
    });
}

function replyTeamStatus(replyid)
{
    // Calculate the offset from the top of the page to show the reply window
    var elementpanel = document.getElementById('panel_teamstatus');
    var element = document.getElementById('teamStatus'+replyid);
    
    // Add 200 for the header, the offset of the main panel div and the individual reply text
    var totaloffset = element.offsetTop + elementpanel.offsetTop+200;
     
    // Update the reply window information
    replyWin.y = totaloffset;
    replyWin.replyid = replyid;
    replyField.reset();
    replyWin.show();
    replyField.focus(); // for some reason the focus get lost
}

function sendReplyTeamStatus()
{
    if(replyWin.replyid != "" && replyField.getValue() != ""){
        new Ajax.Request(
            'index.php?fuse=home&action=SaveTeamStatus',
            {
                parameters: 'message=' + encodeURIComponent(replyField.getValue())
                         + '&replyid=' + encodeURIComponent(replyWin.replyid),
                onComplete: saveTeamStatus_Callback
            }
        );
    }
    
    replyWin.hide();
}

function saveTeamStatus()
{
    if(document.forms['newmessage'].elements['message'].value != ""){
        new Ajax.Request(
            'index.php?fuse=home&action=SaveTeamStatus',
            {
                parameters: 'message=' + encodeURIComponent(document.forms['newmessage'].elements['message'].value),
                onComplete: saveTeamStatus_Callback
            }
        );
        
        document.forms['newmessage'].elements['message'].value = "";
    }
}

function saveTeamStatus_Callback(responseObj)
{
    pollStatus.disconnect();
    pollStatus.connect();
}

function deleteTeamStatus(id, userid)
{
    if(confirm(lang('Are you sure you want to delete this message?'))){
        new Ajax.Request(
            'index.php?fuse=home&action=DeleteTeamStatus',
            {
                parameters: 'id=' + encodeURIComponent(id)
                         + "&userid=" + encodeURIComponent(userid),
                onComplete: deleteTeamStatus_Callback
            }
        );
    }
}

function deleteTeamStatus_Callback(responseObj)
{
    pollStatus.disconnect();
    pollStatus.connect();
}

function paginate(direction)
{
    switch(direction){
        case 'newest':
            pollStatus.disconnect();
            pollStatus.baseParams.start = 0;
            pollStatus.connect();
            break;
        case 'newer':
            pollStatus.disconnect();
            pollStatus.baseParams.start = pollStatus.baseParams.start - pollStatus.baseParams.limit;
            pollStatus.connect();
            break;
        case 'older':
            pollStatus.disconnect();
            pollStatus.baseParams.start = pollStatus.baseParams.start + pollStatus.baseParams.limit;
            pollStatus.connect();
            break;
        case 'oldest':
            pollStatus.disconnect();
            var pages = ceTeamStatus.statusCount / pollStatus.baseParams.limit;
            var correction = 0;
            
            if(pages <= Math.floor(pages)){
                correction = -1;
            }
            
            pollStatus.baseParams.start = (Math.floor(pages) + correction) * pollStatus.baseParams.limit;
            pollStatus.connect();
            break;
        default:
            break;
    }
}

// Function to handle updating what is viewed
function clickTeamUser(userid, fullname)
{
    // Update the form field
    document.forms['pagination_form'].elements['user'].value = userid;
    document.forms['pagination_form'].elements['group'].value = 0;
    
    pollStatus.disconnect();
    pollStatus.baseParams.start = 0;
    pollStatus.baseParams.group = 0;
    pollStatus.baseParams.user = parseInt(userid);
    pollStatus.connect();
    
    // Update the dropdown
    updateDropdown(1, "---------", '-1');
    updateDropdown(1, fullname, '-2');
}

//Function to handle updating what is viewed when a group is selected
function clickTeamGroup(groupid)
{
    // Update the form field
    document.forms['pagination_form'].elements['user'].value = 0;
    document.forms['pagination_form'].elements['group'].value = groupid;
    
    pollStatus.disconnect();
    pollStatus.baseParams.start = 0;
    pollStatus.baseParams.group = parseInt(groupid);
    pollStatus.baseParams.user = 0;
    pollStatus.connect();
    
    // Update the dropdown
    updateDropdown(2,'','');
}

function updateDropdown(what, displaytext, id)
{
    // Load the dropdown
    var elSel = document.getElementById('teamstatusgroups');
    
    // Determine if we are adding or removing
    if(what == 1){
        updateDropdown(2,'','');
        
        // Adding
        if(elSel.selectedIndex >= 0){
            // Make the new option
            var elOptNew = document.createElement('option');
            elOptNew.text = displaytext;
            elOptNew.value = id;
            var elOptOld = elSel.options[0];
            
            try{
              elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
            }catch(ex){
              elSel.add(elOptNew, elSel.selectedIndex); // IE only
            }
            
            elSel.selectedIndex = 0;
        }
    }else{
        // Removing the user info that has been added, if any.
        elSel = document.getElementById('teamstatusgroups');
        
        // Check if anything has been added
        if(elSel.options[0].value == '-2'){
            elSel.remove(0);
            elSel.remove(0);
        }
    }
}