var ceTeamStatus;
	
teamstatus = {};

Ext.onReady(function(){
    teamstatus.statusField = new Ext.form.TextArea({
        id:         "statusField",
        border:     false,
        hideLabel:  true,
        anchor:     '100%',
        grow:       true,
        name:       'statusField'
    });
    teamstatus.statusWin = new Ext.Window({
        id:           "statusWindow",
        x:            400,
        y:            200,
        labelAlign:   'right',
        layout:       'form',
        width:        400,
        autoHeight:   true,
        defaultType:  'textfield',
        modal:        true,
        closeAction:  'hide',
        title:        lang("Your status:"),
        plain:        true,
        closable:     true,
        buttonAlign:  'right',
        items:        [
            teamstatus.statusField
        ],
        buttons:      [
            btnAddStatus = new Ext.Button(
                {
                    id:       'btnAddStatus',
                    text:     lang("Add Status"),
                    disabled: false,
                    hidden:   false,
                    handler:  function(){
                        teamstatus.sendTeamStatus();
                    }
                }
            )
        ]
    });
});

function timeElapsed(secondsElapsed)
{
    var TimeDifference = 0;
    var TimeScale = "";
    
    if(secondsElapsed < 60){
        TimeDifference = secondsElapsed;
        TimeScale = "sec";
    }else{
        if(secondsElapsed < (60 * 60)){
            TimeDifference = Math.floor(secondsElapsed / 60);
            TimeScale = "min";
        }else{
            if(secondsElapsed < (24 * 60 * 60)){
                TimeDifference = Math.floor(secondsElapsed / (60 * 60));
                TimeScale = "hr";
            }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 = "mth";
                    }else{
                        TimeDifference = Math.floor(secondsElapsed / (365 * 24 * 60 * 60));
                        TimeScale = "yr";
                    }
                }
            }
        }
    }
    
    if(TimeDifference > 1 || TimeDifference == 0){
        TimeScale += "s";
    }
    
    var TimeElapsed = TimeDifference + " " + TimeScale + " ago";
    
    return (TimeElapsed);
}

CETeamStatus =function()
{
    /* 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=\'teamstatus.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=\'teamstatus.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=\'teamstatus.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="teamstatus.deleteTeamStatus(\'{id}\',\'{userid}\');"><span style="color: red">delete</span>',
                            '</a>&nbsp;-&nbsp;',
                        '<a onClick="teamstatus.addTeamStatus(\'{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(teamstatus.pollStatus.baseParams.start > 0 &&  e.teamstatus.length == 0){
        teamstatus.paginate('newer');
    }
    
    var displayNewerLink = '';
    var displayPaginationSeparator = '';
    var displayOlderLink = '';
    
    if(teamstatus.pollStatus.baseParams.start == 0){
        displayNewerLink = 'none';
        displayPaginationSeparator = 'none';
    }
    
    if((teamstatus.pollStatus.baseParams.start + teamstatus.pollStatus.baseParams.limit) >= this.statusCount){
        displayOlderLink = 'none';
        displayPaginationSeparator = 'none';
    }
    
    document.getElementById('newest_link').style.display = displayNewerLink;
    document.getElementById('pagination_separator_n').style.display = displayNewerLink;
    document.getElementById('newer_link').style.display = displayNewerLink;
    document.getElementById('pagination_separator').style.display = displayPaginationSeparator;
    document.getElementById('older_link').style.display = displayOlderLink;
    document.getElementById('pagination_separator_o').style.display = displayOlderLink;
    document.getElementById('oldest_link').style.display = displayOlderLink;
    
    // If there are no items, then show a message
    var displayNoItems = 'none';
    
    if(this.statusCount == 0){
        displayNoItems = '';
    }
    
    document.getElementById('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
            document.getElementById("teamStatus" + this.statusList[i].id).parentNode.removeChild(document.getElementById("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);
            }
            
            document.getElementById('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 != ''){
                document.getElementById('inreplyto' + this.statusList[i].id).qtip = e.teamstatus[index].reply_details;
                document.getElementById('inreplyto' + this.statusList[i].id).style.display = '';
                document.getElementById('replieduser' + this.statusList[i].id).style.display = '';
            }else{
                document.getElementById('inreplyto' + this.statusList[i].id).qtip = '';
                document.getElementById('inreplyto' + this.statusList[i].id).style.display = 'none';
                document.getElementById('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];
    }
}

// Moved the loading of the team status away from the ext.onload to a seperate function
teamstatus.PluginTeamStatus = function()
{
    // Clear any previous instance of ceTeamStatus to avoid duplicate data being displayed
    ceTeamStatus = undefined;
    ceTeamStatus = new CETeamStatus();
    
    teamstatus.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(teamstatus.pollStatus);
    
    Ext.Direct.on('teamStatus', function(e) {
        ceTeamStatus.process(e);
    });
}

teamstatus.addTeamStatus = function(replyid)
{
    if(replyid != undefined){
        teamstatus.statusWin.replyid = replyid;
        teamstatus.statusWin.setTitle(lang("Your reply:"));
        btnAddStatus.setText(lang("Reply"));
    }else{
        teamstatus.statusWin.replyid = '';
        teamstatus.statusWin.setTitle(lang("Your status:"));
        btnAddStatus.setText(lang("Add Status"));
    }
    
    teamstatus.statusField.reset();
    teamstatus.statusWin.show();
    teamstatus.statusField.focus('',300);
}

teamstatus.sendTeamStatus = function()
{
    if(teamstatus.statusField.getValue() != ""){
        Ext.Ajax.request({
            url: 'index.php?fuse=home&action=SaveTeamStatus',
            method: 'post',
            params: {
                message: teamstatus.statusField.getValue(),
                replyid : teamstatus.statusWin.replyid
            },
            success : function(){
                teamstatus.pollStatus.disconnect();
                teamstatus.pollStatus.connect();
            }
        });
    }
    
    teamstatus.statusWin.hide();
}

teamstatus.saveTeamStatus = function()
{
    if(document.forms['newmessage'].elements['message'].value != ""){
        Ext.Ajax.request({
            url: 'index.php?fuse=home&action=SaveTeamStatus',
            method: 'post',
            params: {
                message: document.forms['newmessage'].elements['message'].value
            },
            success : function(){
                teamstatus.pollStatus.disconnect();
                teamstatus.pollStatus.connect();
            }
        });
        
        document.forms['newmessage'].elements['message'].value = "";
    }
}

teamstatus.deleteTeamStatus = function(id, userid)
{
    if(confirm(lang('Are you sure you want to delete this message?'))){
        Ext.Ajax.request({
            url: 'index.php?fuse=home&action=DeleteTeamStatus',
            params: { id: id, userid: userid},
            success : function(){
                teamstatus.pollStatus.disconnect();
                teamstatus.pollStatus.connect();
            }
        });
    }
}

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

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

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

teamstatus.updateDropdown = function(what, displaytext, id)
{
    // Load the dropdown
    var elSel = document.getElementById('teamstatusgroups');
    
    // Determine if we are adding or removing
    if(what == 1){
        teamstatus.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);
        }
    }
}