
Youmail.vm.inboxAjax = function()
{
    this.singleRequestTypes = new Array();
    
    // methods
    
    this.simpleRequest = simpleRequest;
    this.simpleRequestWithPost = simpleRequestWithPost;
    
    /*
    Initiates an async request to the server, with a simple result of success or failure.
    
    asyncUrl - the url to send the request to
    singleRequestType - the unique request type, null if no request type.  If this is 
         set, only one request with this type maybe executed at a time (an alert() 
         if multiple request is attempted of this type)
    passThrus - any params that need to passed thru to the success or failure message
    */
    function simpleRequest(asyncUrl, singleRequestType, passThrus)
    {
        this.simpleRequestWithPost(asyncUrl, singleRequestType, passThrus, null);
    }
    
    
    function simpleRequestWithPost(asyncUrl, singleRequestType, passThrus, postData)
    {
        if (singleRequestType != null && this.singleRequestTypes[singleRequestType] == true) {
            alert("Processing previous request, please wait ...");
            return;
        }

        if (singleRequestType != null) {
            this.singleRequestTypes[singleRequestType] = true;
        }

        var args = {inboxAjax: this, singleRequestType: singleRequestType, passThrus : passThrus};

        var callback = { success:handleSimpleSuccess, failure:handleSimpleFailure, argument:args};
        var request = YAHOO.util.Connect.asyncRequest('POST', asyncUrl, callback, postData);

    }


    var handleSimpleSuccess = function (o)
    {
        if (o != undefined && o.responseText != undefined) {
            var ajax = o.argument.inboxAjax;
            var singleRequestType = o.argument.singleRequestType;
        
            if (singleRequestType != null) {
                ajax.singleRequestTypes[singleRequestType] = false;
            }
        
            var ajaxResp = eval('(' + o.responseText + ')');
            processAjaxResponse(ajaxResp);
        } else {
            handleAjaxFailure(o);
        }
    }
    
    var handleSimpleFailure = function(o)
    {
        var ajax = o.argument.inboxAjax;
        var singleRequestType = o.argument.singleRequestType;
        
        if (singleRequestType != null) {
            ajax.singleRequestTypes[singleRequestType] = false;
        }
        alert("Error when contacting server, refresh this page and please try again.");
    }
    
    function processAjaxResponse(ajaxResp)
    {
        if (!ajaxResp.successful) {
            if (ajaxResp.errorMsg == null || ajaxResp.errorMsg == "") {
                alert("Error occurred when servicing request, please try again.");
            } else {
                alert(ajaxResp.errorMsg);
            }
            return;
        }
        
        if (ajaxResp.shouldRefresh) {
            Youmail.vm.refreshInboxTable();
            return;
        }
        
        if (ajaxResp.fullRefresh) {
            window.location = window.location;
            return;
        }
        
        if (ajaxResp.redirectUrl != null && ajaxResp.redirectUrl != "" ) {
            window.location = ajaxResp.redirectUrl;
            return;
        }
        
        var type = ajaxResp.type;
        
        var msg = ajaxResp.successMsg;
        var shouldUpdateCount = false;
        
        if (type == null)
            type = "";
        
        if (type == "delete" || type == "purge" || (type.indexOf("move") >= 0) || type=="spam" || type=="unspam") {
            // data entry removed
            
            var length = ajaxResp.entryIds.length;
            var messages = Youmail.vm.data.messageBox.messages;
            var msgLength = messages.length;
            var removedTotal = 0;
            var removedNewMsgCount = 0;
            
            // go thru all the entryIds and remove them from the current messages array
            // also update removedNewMsgCount and removedTotal
            
            for (var i = length - 1; i >= 0; i--) {
                // assuming the last entryId is the bigger row index
                var entryId = ajaxResp.entryIds[i];
                for (var j = msgLength - 1; j >= 0; j--) {
                    // delete in reverse order so that rowIndex is preserved
                    var message = messages[j];
                    if (message != null) {
                        if (message.XID == entryId) {
                            inTb.removeRowUI(j);
                            messages[j] = null;  // removed later, assuming the last entryId is the biggest row index
                            if (message.isNew) {
                                removedNewMsgCount++;
                            }
                            removedTotal++;
                            break;  // go to next entryId
                        }
                    }
                }
            }

            // copy all non-null entry to new message array (workaround for not being able to remove inner array element)
            var newMessages = new Array(msgLength - removedTotal);
            var oldIndex = 0;
            var newIndex = 0;
            while (oldIndex < msgLength) {
                if (messages[oldIndex] != null) {
                    // copy over
                    newMessages[newIndex] = messages[oldIndex];
                    newIndex++;
                }
                // else has been removed, nothing to copy
                oldIndex++;
            }
            Youmail.vm.data.messageBox.messages = newMessages;

            inTb.updateOddEvenUI();


            // if moving then update counts of new
            if (removedNewMsgCount > 0 && type != "purge") {
                var newFolderId = null;
                
                
                if (type == "delete") {
                    newFolderId = "Trash";
                } else if (type == "spam") {
                    newFolderId = "Spam";
                } else if (type == "unspam") {
                    newFolderId = "Inbox";
                } else if (type.indexOf("move") >= 0) {
                    newFolderId = type.substring(4);
                }
                
                if (newFolderId != null) {
                    var newFolderCount = Youmail.vm.getFolderCount(newFolderId);
                    Youmail.vm.updateFolderCount(newFolderId, newFolderCount + removedNewMsgCount);
                }
            }
            
            if (type == "delete" || type == "moveTrash") {
                msg = "Moved to Trash folder successfully.";
            } else if (type == "spam") {
                msg = "Spam has been reported and moved to Spam folder.";
            } else if (type == "unspam") {
                msg = "Moved back to Inbox and caller(s) removed from your spam list.";
            } else if (type.indexOf("move") >= 0) {
                msg = "Message(s) successfully moved.";
            } else if (type == "purge") {
                msg = "Message(s) completely removed.";
            }
            
            selectNone();
            shouldUpdateCount = true;
            
        } else if (type == "simple") {
            // simple transcription rating stuff, check for error and undo rating
            rated = newRated;
            currentRating = newCurrentRating;
            showCurrentTransRating();
        } else if (type == "transcribe" || type == "clearCache") {
            // do nothing for now
        } else {
            // updates to rows
            var length = 0;
            if (ajaxResp.entryIds != null) {
                length = ajaxResp.entryIds.length;
            }
            var messages = Youmail.vm.data.messageBox.messages;
            var msgLength = messages.length;
            for (var i = length - 1; i >= 0; i--) {
                var entryId = ajaxResp.entryIds[i];
                for (var j = msgLength - 1; j >= 0; j--) {
                    var message = messages[j];
                    if (message.XID == entryId) {
                        if (type == "share") {
                            message.share = true;
                        } if (type == "unshare") {
                            message.share = false;
                        } if (type == "skip") {
                            message.isNew = false;
                        } if (type == "makeNew") {
                            message.isNew = true;
                        } if (type == "flag") {
                            message.flagged = true;
                        } if (type == "unflag") {
                            message.flagged = false;
                        }
                        Youmail.vm.updateRowUIByIndex(j);
                        break;
                    }
                }
            }
            if (length == 1) {
                if (type == "share") {
                    msg = "Message sharing has been enabled.";
                } if (type == "skip") {
                    shouldUpdateCount = true;
                    msg = "Message has been marked heard.";
                } if (type == "makeNew") {
                    shouldUpdateCount = true;
                    msg = "Message has been marked as new.";
                } if (type == "unshare") {
                    msg = "Message sharing has been disabled.";
                } if (type == "flag") {
                    msg = "Message has been flagged for follow-up.";
                } if (type == "unflag") {
                    msg = "Message follow-up flag has been removed.";
                }
            } else {
                if (type == "share") {
                    msg = "Sharing has been enabled for all selected messages.";
                } if (type == "skip") {
                    shouldUpdateCount = true;
                    msg = "All selected messages have been marked heard.";
                } if (type == "makeNew") {
                    shouldUpdateCount = true;
                    msg = "All selected messages have been marked as new.";
                } if (type == "unshare") {
                    msg = "Sharing has been disabled for all selected messages.";
                } if (type == "flag") {
                    msg = "All selected messages have been flagged for follow-up";
                } if (type == "unflag") {
                    msg = "Follow-up flag has been removed from all selected messages.";
                }
            }

        } 

        if (shouldUpdateCount) {
            Youmail.vm.updateHeaderCount();
        }

        // if warning then don't display confirmation
        if (ajaxResp.warnMsg == null) {
            if (ajaxResp.successMsg != null) {
                msg = ajaxResp.successMsg;  // server message if any
            }
            // use confirmation from above
        } else {
            msg = null;
            alert(ajaxResp.warnMsg);
        }

        if (!(type == "simple" || type == "transcribe" || type == "clearCache")) {
            clearPreview(msg);
        }
    }
    
    
};

var inAjax = new Youmail.vm.inboxAjax();

