// Warn before discarding gmail v1.3
// By David James, http://www.cs.toronto.edu/~james/greasemonkey

// v1.0 -- Initial version
// v1.1 -- Update to be more robust when google updates
// v1.2 -- Update to avoid private APIs
// v1.3 -- Update to avoid warnings
// v1.4 -- Added mail.google.com to list of URLs

// ==UserScript==
// @name    Warn before discarding gmail
// @namespace   http://www.cs.toronto.edu/~james/google
// @description Warn before discarding gmail
// @include http://gmail.google.com/gmail?view=page&name=js*
// @include https://gmail.google.com/gmail?view=page&name=js*
// @include http://mail.google.com/mail?view=page&name=js*
// @include https://mail.google.com/mail?view=page&name=js*
// ==/UserScript==

(function() {
    
    // Check whether we have unsaved changes
    function hasUnsavedChanges() {
        if (top.js && top.js._IF_GetVisibleWindow) {
            // Get current window and document
            var win = top.js._IF_GetVisibleWindow();
            var doc = win.document;
            
            // Look through draft buttons
            var buttons = document.evaluate("//button[@id='d']", doc, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);            
            for (var i = 0; i < buttons.snapshotLength; i++) {                
                if (!buttons.snapshotItem(i).disabled) {
                    // We have unsaved changes
                    return true;
                }
            }
        }
        return false;
    }
    
    // Warn the user before he or she closes the browser
    if (top.js && this == top.js && top.js._IF_GetVisibleWindow) {
        top.window.onbeforeunload = function() {
            if (hasUnsavedChanges()) {
                var message = 'You have unsaved changes';
                if (typeof evt == 'undefined') {
                    evt = window.event;
                }
                if (evt) {
                    evt.returnValue = message;
                }
                return message;  
            }
        };
    }
})()

