/*!
 * DLsite.com JavaScript Library.
 *
 * Copyright (C) 1996-2011 DLsite.com. All rights reserved.
 * http://www.dlsite.com/
 */

var Trigger = (function () {
    function isArray (obj) {
        return Object.prototype.toString.call(obj) == "[object Array]";
    }

    function each (obj, callback) {
        for ( var i in obj ) {
            callback(i, obj[i], obj);
        }
    }

    function map (ary, callback, thisObject) {
        var res = [];
        each(ary, function (i, val) {
            res[i] = callback.call(thisObject,val,i,this);
        });
        return res
    }

    function every (ary, callback, thisObject) {
        for(var i=0,len=ary.length;i<len;i++) {
            if(!callback.call(thisObject,ary[i],i,ary)) return false;
        }
        return true
    }

    var tid = null;
    function COND (statement, callback) {
        if ( tid != null ) clearInterval(tid), tid = null;
        tid = setInterval(function () {
            (isArray( statement ) ? every(statement, function (_cond) {
                 return _cond();
            }) : statement()) && ( clearInterval(tid), tid = null, setTimeout(callback, 0) );
        }, 200);
    };

    var events = {
        allAnimated: function () {
            return !$.timers.length;
        },
        ajaxFullComplete: function () {
            return !$.active;
        }
    }, triggers = {
        multi: function (names, callback) {
            return COND
            (
                isArray( names ) ? map(names, function (name) {
                    return events[name] || function () { return true };
                }) : names, callback
            );
        },
        util: {
            regist: function (name, statement) {
                triggers[name] = function (callback) {
                    COND(statement, callback);
                }
                return {
                    after: function (callback) {
                        triggers[name](callback);
                    }
                }
            }
        }
    };

    each(events, function (name, statement) {
        triggers.util.regist.apply(null, arguments);
    });

    return triggers;
})();
