﻿/**
 * Copyright (c) 2009, Nathan Bubna
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * This plugin exists to make it trivial to notify your users that
 * things are in progress.  The typical case is waiting for an
 * AJAX call to finish loading.  Just call:
 * 
 *   $.loading();
 *
 * to toggle a page-wide message on and off, or you can call:
 *
 *   $('#foo').loading()
 *
 * to do the same, but locate the message within a specific element(s).
 *
 * If you want to ensure that a call doesn't errantly toggle on when
 * you meant to toggle off (or vice versa), then put a boolean value
 * as your first argument.  true is on, false is off.
 *
 *   $.loading(false); // will only ever toggle off
 *   $.loading(true, {align: 'bottom-right'});  // will only ever toggle on
 *
 * If you just want a page-wide message to go on and off while your
 * AJAX stuff is happening, there's a convenience method to set that
 * up properly for you. Just do:
 *
 *   $.loading.onAjax({text: 'Waiting...'});
 *
 * You can change any of the default options by altering the $.loading
 * properties (or sub-properties), like this:
 *
 *  $.loading.classname = 'loadMsg';
 *  $.loading.css.border = '1px solid #000';
 *  $.loading.working.time = 5000;
 *
 * All options can also be overridden per-call by passing in
 * an options object with the overriding properties, like so:
 *
 *  $.loading({ element:'#cancelButton', mask:true });
 *  $('#foo').loading(true, { img:'loading.gif', align:'center'});
 *
 * Be sure to check out the provided demo for an easy overview of the most
 * commonly used options!! Of course, everything in this plugin is easy to
 * configure and/or override with those same techniques.
 *
 * Of particular note here is that it is easy to plug in additional
 * "pulse" effects.  Just add an object with a 'run' function to $.loading
 * under the desired effects name, like this:
 *
 *  $.loading.moveLeft = {
 *      time: 500,
 *      run: function(opts) {
 *          var self = this, box = opts.box;
 *          opts.interval = setInterval(function() {
 *              box.left += 1;
 *              self.animate(box);
 *          }, opts.moveLeft.time);
 *      }
 *  }
 *
 * then use it by doing something like:
 * 
 *  $.loading({ pulse: 'moveLeft', align:{top:0,left:0} });
 *
 * If you add an 'end' function to that same object, then the end function
 * will be called when the loading message is turned off.
 *
 * Speaking of turning things on and off, this plugin will trigger 'loadingStart'
 * and 'loadingEnd' events when loading is turned on and off, respectively.
 * The options will, of course, be available as a second argument to functions
 * that are bound to these events.  See the demo source for an example. In
 * future versions, this plugin itself may use those events, but for now they
 * are merely notifications.
 *
 * Contributions, bug reports and general feedback on this is welcome.
 *
 * @version 1.3.2
 * @name loading
 * @cat Plugins/loading
 * @author Nathan Bubna
 */
;(function($) {

    // the main interface...
    var L = $.loading = function(show, opts) {
        return $('body').loading(show, opts, true);
    };
    $.fn.loading = function(show, opts, page) {
        opts = toOpts(show, opts, page);
        return this.each(function() {
            L.toggle.call($(this), $.extend({}, opts));
        });
    };

    // convenience method
    L.onAjax = function(opts) {
        if (!opts) opts = {};
        opts._active = 0;
        return (this.jquery ? this : $(document)).ajaxStart(function() { 
            if (opts._active == 0) L(true, opts);
            opts._active += 1;
        }).ajaxStop(function() {
            opts._active -= 1;
            if (opts._active == 0) L(false, opts);
        });
    };

    // all that's extensible and configurable...
    $.extend(L, {
        version: "1.3.2",
        // commonly-used options
        align: 'top-left',
        pulse: 'working',
        mask: false,
        img: null,
        element: null,
        text: 'Loading...',
        // less commonly-used options
        classname: 'loading',
        imgClass: 'loading-img',
        elementClass: 'loading-element',
        maskClass: 'loading-mask',
        css: { position:'absolute', whiteSpace:'nowrap', zIndex:1001 },
        maskCss: { position:'absolute', opacity:.15, background:'#333',
                   zIndex:101, display:'block', cursor:'wait' },
        cloneEvents: true,
        pageOptions: { page:true, align:'top-center' },
        // rarely-used options
        html: '<div></div>',
        maskHtml: '<div></div>',
        maskedClass: 'loading-masked',
        maskEvents: 'mousedown mouseup keydown keypress',

        // pulse plugin properties
        working: {
            time: 10000,
            text: 'Still Working...',
            run: function(opts) {
                var w = opts.working, self = this;
                opts.timeout = setTimeout(function() {
                    self.height('auto').width('auto').text(w.text);
                    opts.place.call(opts.display, opts);
                }, w.time);
            }
        },
        fade: {
            time: 700,
            speed: 'slow',
            run: function(opts) {
                var s = opts.fade.speed, self = this;
                opts.interval = setInterval(function() {
                    self.fadeOut(s).fadeIn(s);
                }, opts.fade.time);
            }
        },
        ellipsis: {
            time: 300,
            run: function(opts) {
                var t = opts.text, x = t.indexOf('.'), i = x<0 ? t.length : x, self = this;
                opts.interval = setInterval(function() {
                    var et = self.text();
                    self.text((et.length - i) < 3 ? et + '.' : t.substring(0,i));
                }, opts.ellipsis.time);
            }
        },
        type: {
            time: 100,
            run: function(opts) {
                var t = opts.text, self = this;
                opts.interval = setInterval(function() {
                    var e = self.text(), el = e.length;
                    self.text(el == t.length ? t.charAt(0) : t.substring(0, el+1));
                }, opts.type.time);
            }
        },

        // functions
        toggle: function(opts) {
            var old = this.data('loading');
            if (old) {
                if (opts.show !== true) old.off.call(this, old, opts);
            } else {
                if (opts.show !== false) opts.on.call(this, opts);
            }
        },
        on: function(opts) {
            opts.parent = this;
            if (opts.mask) opts.mask = opts.createMask.call(this, opts);
            opts.display = opts.create.call(this, opts);
            if (opts.img) {
                opts.initImg.call(this, opts);
            } else if (opts.element) {
                opts.initElement.call(this, opts);
            } else {
                opts.init.call(this, opts);
            }
            this.trigger('loadingStart', [opts]);
        },
        initImg: function(opts) {
            var self = this;
            opts.img = $('<img src="'+opts.img+'"/>').bind('load', function() {
                opts.init.call(self, opts);
            });
            opts.display.addClass(opts.imgClass).append(opts.img);
        },
        initElement: function(opts) {
            opts.element = $(opts.element).clone(opts.cloneEvents)
            opts.display.addClass(opts.elementClass).append(opts.element);
            opts.init.call(this, opts);
        },
        init: function(opts) {
            opts.place.call(opts.display, opts);
            this.data('loading', opts);
            if (opts.pulse) {
                opts[opts.pulse].run.call(opts.display, opts);
            }
        },
        create: function(opts) {
            var el = $(opts.html).addClass(opts.classname).css(opts.css).appendTo(this);
            if (opts.text && !opts.img && !opts.element) el.text(opts.text);
            $(window).bind('resize', opts.resizer = function() { opts.resizeHandler(opts) });
            return el;
        },
        resizeHandler: function(opts) {
            opts.parent.box = null;
            opts.place.call(opts.display, opts);
            if (opts.mask) opts.mask.css(opts.parent.box);
        },
        createMask: function(opts) {
            var box = opts.measure.call(this.addClass(opts.maskedClass), opts);
            opts.handler = function(e) { return opts.maskHandler(e, opts); };
            $(document).bind(opts.maskEvents, opts.handler);
            return $(opts.maskHtml).addClass(opts.maskClass)
                .css(box).css(opts.maskCss).appendTo(this);
        },
        maskHandler: function(e, opts) {
            var $els = $(e.target).parents().andSelf();
            if ($els.filter('.'+opts.classname).length != 0) return true;
            return !opts.page && $els.filter('.'+opts.maskedClass).length == 0;
        },
        place: function(opts) {
            var box = opts.align, v = 'top', h = 'left';
            if (typeof box == "object") {
                box = $.extend(opts.calc.call(this, v, h, opts), box);
            } else {
                if (box != 'top-left') {
                    var s = box.split('-');
                    if (s.length == 1) {
                        v = h = s[0];
                    } else {
                        v = s[0]; h = s[1];
                    }
                }
                if (!this.hasClass(v)) this.addClass(v);
                if (!this.hasClass(h)) this.addClass(h);
                box = opts.calc.call(this, v, h, opts);
            }
            this.css(opts.box = box);
        },
        calc: function(v, h, opts) {
            var box = $.extend({}, opts.measure.call(opts.parent, opts)),
                H = $.boxModel ? this.height() : this.innerHeight(),
                W = $.boxModel ? this.width() : this.innerWidth();
            if (v != 'top') {
                var d = box.height - H;
                if (v == 'center') {
                    d /= 2;
                } else if (v != 'bottom') {
                    d = 0;
                } else if ($.boxModel) {
                    d -= css(this, 'paddingTop') + css(this, 'paddingBottom');
                }
                box.top += d;
            }
            if (h != 'left') {
                var d = box.width - W;
                if (h == 'center') {
                    d /= 2;
                } else if (h != 'right') {
                    d = 0;
                } else if ($.boxModel) {
                    d -= css(this, 'paddingLeft') + css(this, 'paddingRight');
                }
                box.left += d;
            }
            box.height = H;
            box.width = W;
            return box;
        },
        measure: function(opts) {
            if (!this.box) this.box = opts.page ? opts.pageBox() : opts.elementBox(this);
            return this.box;
        },
        elementBox: function(e) {
            var box = e.position();
            box.top += css(e, 'marginTop');
            box.left += css(e, 'marginLeft');
            box.height = e.outerHeight();
            box.width = e.outerWidth();
            return box;
        },
        pageBox: function() {
            return { top:0, left: 0,
                     height: document.body.clientHeight || window.innerHeight,
                     width: document.body.clientWidth || window.innerWidth };
        },
        off: function(old, opts) {
            this.data('loading', null);
            if (old.pulse && old[old.pulse].end) {
                old[old.pulse].end.call(this, old, opts);
            }
            if (old.interval) clearInterval(old.interval);
            if (old.timeout) clearTimeout(old.timeout);
            if (old.mask) {
                this.removeClass(opts.maskedClass);
                $(document).unbind(old.maskEvents, old.handler);
                old.mask.remove();
            }
            $(window).unbind('resize', old.resizer);
            old.display.remove();
            old.parent.trigger('loadingEnd', [old]);
        }
    });

    // a few private functions...
    function toOpts(s, o, p) {
        if (o === undefined) {
            o = (typeof s == "boolean") ? { show: s } : s;
        } else {
            o.show = s;
        }
        // default pulse to off if doing an img
        if (o && (o.img || o.element) && !o.pulse) o.pulse = false;
        return $.extend(true, {}, L, (p ? L.pageOptions : null), o);
    }
    function css(el, prop) {
        var val = el.css(prop);
        return val == 'auto' ? 0 : parseFloat(val, 10);
    }
})(jQuery);
