/**
    XoxoOutliner.Startup:
*/

// Prepare the namespace.
if (!window.XoxoOutliner) window.XoxoOutliner = {};

XoxoOutliner.Startup = function() {

    // Convenience shortcuts to YUI packages.
    var Dom      = YAHOO.util.Dom;
    var Evt      = YAHOO.util.Event;

    return {
        AUTOSAVE_INTERVAL: 25000,
        LOG_ID: "outliner_yui_log",
        log_reader: null,
        
        /**
            init(): Initialize startup sequence.
        */
        init: function() { 
            var log = this.getLog("init"); 
            this.log_reader.hide();
            YAHOO.widget.Logger.enableBrowserConsole();

            log("Starting up...");

            // some very basic browser detection for the stupid keypress events		
            var ua = navigator.userAgent.toLowerCase();
            var isOpera = (ua.indexOf('opera') != -1);
            var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof
            var isSafari = (ua.indexOf("safari") != -1);
            window.browser = {
                isOpera: isOpera,
                isIE: isIE,
                isSafari: isSafari
            };
            
            Evt.on("outliner_help_title", "click", function(e) {
                var body = Dom.get("outliner_help_body");
                if (Dom.hasClass(body, 'outliner_hidden')) {
                    Dom.replaceClass(body, 'outliner_hidden', 'outliner_shown');
                } else {
                    Dom.replaceClass(body, 'outliner_shown', 'outliner_hidden');
                }
                Evt.stopEvent(e);
                return false;
            }, this, true);

            // Step 1: Dig up all the outlines from the DOM.  Make no
            // modifications that might disturb the DOM.
            var lists = [];
            forEach(document.body.childNodes, function(n) {
                if (Node.ELEMENT_NODE == n.nodeType && Dom.hasClass(n, "xoxo")) 
                    lists.push(n);
            }, this);

            // Step 2: Wire each of the outlines up with outliners.
            forEach(lists, function(n) { 
                new XoxoOutliner.Outliner(n); 
            }, this);
            
            lists = null;

            Evt.on("button_save", "click", this.saveDocument, this, true);

            this.autosave_interval = setInterval(function() {
                if (!Dom.get("check_autosave")) return;
                if (Dom.get("check_autosave").checked == true) {
                    this.saveDocument();
                } else {
                    //Dom.get("status_msg").value = "autosave disabled.";
                }
            }.bind(this), this.AUTOSAVE_INTERVAL);
        },

        saveDocument: function() {
            var log    = this.getLog("saveDocument"); 
            var status = Dom.get("status_msg");
            var ol     = document.getElementsByTagName('html')[0];
            var xoxo   = XoxoOutliner.Conversions.fromDOMtoXOXO(ol);

            status.value = "checking etag...";
            
            var url = location.href;
            var handler = {
                success: function(o) {
                    
                    // Grab the Etag from the remote document and the local document.
                    var remote_etag = o.getResponseHeader['Etag'];
                    var local_etag  = '';
                    forEach(document.getElementsByTagName("meta"), function(m) {
                        if (/etag/i.test(m.getAttribute('http-equiv')))
                            local_etag = m.getAttribute('content');
                    }, this);

                    if (remote_etag == local_etag) {
                        this._reallySaveDocument();
                    } else {
                        status.value = "ERROR: Remote document changed during local edits. "+local_etag+" != "+remote_etag;
                    }
                    status = null;

                }.bind(this),

                failure: function(o) {
                    status.value = "FAILED TO CHECK ETAG!";
                    status = null;
                }.bind(this)

            };

            // HACK: Safari is PUT-crippled.  So, here's a hacky fix.
            var req = (!browser.isSafari) ?  
                YAHOO.util.Connect.asyncRequest('HEAD', url, handler, xoxo) :
                YAHOO.util.Connect.asyncRequest('POST', url+"?REQUEST_METHOD=HEAD", handler, xoxo);
        },

        _reallySaveDocument: function() {
            var log    = this.getLog("_reallySaveDocument"); 
            var status = Dom.get("status_msg");
            var ol     = document.getElementsByTagName('html')[0];
            var xoxo   = XoxoOutliner.Conversions.fromDOMtoXOXO(ol);

            status.value = "saving...";
            
            var url = location.href;
            var handler = {
                
                success: function(o) {

                    // Update the local Etag with remote header results.
                    var remote_etag = o.getResponseHeader['Etag'];
                    forEach(document.getElementsByTagName("meta"), function(m) {
                        if (/etag/i.test(m.getAttribute('http-equiv')))
                            m.setAttribute('content', remote_etag);
                    }, this);

                    status.value = "last saved at "+(new Date().toString());
                    status = null;

                }.bind(this),

                failure: function(o) {
                    status.value = "FAILED!";
                    status = null;
                }.bind(this)

            };

            // HACK: Safari is PUT-crippled.  So, here's a hacky fix.
            var req = (!browser.isSafari) ?  
                YAHOO.util.Connect.asyncRequest('PUT', url, handler, xoxo) :
                YAHOO.util.Connect.asyncRequest('POST', url+"?REQUEST_METHOD=PUT", handler, xoxo);
        },

        getLog: function(cat) {
            if (!this.log_reader) {
                if (!Dom.get(this.LOG_ID))
                    document.body.appendChild( DIV({'id':this.LOG_ID}));
                this.log_reader = new YAHOO.widget.LogReader(this.LOG_ID);
            }
            return function(msg, lvl) {
                YAHOO.log(msg, (lvl || "debug"), "Startup.js:"+cat);
            };
        },

        EOF:null 
    };

}();

YAHOO.util.Event.addListener(window, "load", 
    XoxoOutliner.Startup.init, XoxoOutliner.Startup, true);

