<commit_before>$(function(){
    var host_name = ["shi"];

    //瀑布流
    var $window = $(window),
        defaults = {
            itemCls: 'col-item',
            prefix: 'waterfall',
            fitWidth: true,
            colWidth: 210,
            gutterWidth: 3,
            gutterHeight: 3,
            align: 'left',
            minCol: 1,
            maxCol: undefined,
            resizable: true
        };

    function Waterfall(element, options) {
        this.$element = $('#col-list');
        this.options = defaults;
        this.colHeightArray = []; // columns height array
        this.styleQueue = [];
        this._init();
    }

    host_name.push("fone");

    Waterfall.prototype = {
        constructor: Waterfall,

        /*
         * _init
         * @callback {Object Function } and when instance is triggered again -> $element.waterfall()
         */
        _init: function( callback ) {
            var options = this.options,
                path = options.path;

            this._setColumns();
            this._resetColumnsHeightArray();
            this.reLayout( callback );

            if ( options.resizable ) {
                this._doResize();
            }
        },

        /**
         * get columns
         */
        _getColumns : function() {
            var options = this.options,
                $container = options.fitWidth ?  this.$element.parent() : this.$element,
                containerWidth = $container[0].tagName === 'BODY' ? $container.width() - 20 : $container.width(),
                colWidth = options.colWidth,
                gutterWidth = options.gutterWidth,
                minCol = options.minCol,
                maxCol = options.maxCol,
                cols = Math.floor(containerWidth / (colWidth + gutterWidth)),
                col = Math.max(cols, minCol );

            return !maxCol ? col : (col > maxCol ? maxCol : col);
        },

        /**
         * set columns
         */
        _setColumns: function() {
            this.cols = this._getColumns();
        },

        /*
         * get items
         */
        _getItems: function( $content ) {
            var $items = $content.filter('.' + this.options.itemCls).css({
                'position': 'absolute'
            });

            return $items;
        },

        /*
         * reset columns height array
         */
        _resetColumnsHeightArray: function() {
            var cols = this.cols,
                i;

            this.colHeightArray.length = cols;

            for (i = 0; i < cols; i++) {
                this.colHeightArray[i] = 0;
            }
        },

        /*
         * layout
         */
        layout: function($content, callback) {
            var options = this.options,
                $items = this._getItems($content),
                styleFn = 'css',
                animationOptions = options.animationOptions,
                colWidth = options.colWidth,
                gutterWidth = options.gutterWidth,
                len = this.colHeightArray.length,
                align = options.align,
                fixMarginLeft,
                obj,
                i, j, itemsLen, styleLen;

            // append $items
            this.$element.append($items);

            // fixMarginLeft
            if ( align === 'center' ) {
                fixMarginLeft = (this.$element.width() - colWidth * len  - gutterWidth * (len - 1) ) /2;
                fixMarginLeft = fixMarginLeft > 0 ? fixMarginLeft : 0;
            } else if ( align === 'left' ) {
                fixMarginLeft = 0;
            } else if ( align === 'right' ) {
                fixMarginLeft = this.$element.width() - colWidth * len  - gutterWidth * (len - 1);
            }

            // place items
            for (i = 0, itemsLen = $items.length; i < itemsLen; i++) {
                this._placeItems( $items[i], fixMarginLeft);
            }

            // set style
            for (j= 0, styleLen = this.styleQueue.length; j < styleLen; j++) {
                obj = this.styleQueue[j];
                obj.$el[ styleFn ]( obj.style, animationOptions );
            }

            // update waterfall container height
            this.$element.height(Math.max.apply({}, this.colHeightArray));

            // clear style queue
            this.styleQueue = [];

            // update status
            // this.options.state.isResizing = false;
            //this.options.state.isProcessingData = false;

            // callback
            if ( callback ) {
                callback.call( $items );
            }

            $("#main-loading").delay(500).fadeOut("normal",function(){
                $("html,body").removeClass("loading-process");
            });
        },

        /*
         * relayout
         */
        reLayout: function( callback ) {
            var $content = this.$element.find('.' + this.options.itemCls);

            this._resetColumnsHeightArray();
            this.layout($content , callback );
        },

        /*
         * place items
         */
        _placeItems: function( item, fixMarginLeft ) {

            var $item = $(item),
                options = this.options,
                colWidth = options.colWidth,
                gutterWidth = options.gutterWidth,
                gutterHeight = options.gutterHeight,
                colHeightArray = this.colHeightArray,
                len = colHeightArray.length,
                minColHeight = Math.min.apply({}, colHeightArray),
                minColIndex = $.inArray(minColHeight, colHeightArray),
                colIndex, //cur column index
                position;

            colIndex = minColIndex;

            position = {
                left: (colWidth + gutterWidth) * colIndex  + fixMarginLeft,
                top: colHeightArray[colIndex]
            };

            // push to style queue
            this.styleQueue.push({ $el: $item, style: position });

            // update column height
            colHeightArray[colIndex] += $item.outerHeight() + gutterHeight;

        },

        /*
         * append
         * @param {Object} $content
         * @param {Function} callback
         */
        append: function($content, callback) {
            this.$element.append($content);
            this.reLayout(callback);
        },

        /*
         * opts
         * @param {Object} opts
         * @param {Function} callback
         */
        option: function( opts, callback ){
            if ( $.isPlainObject( opts ) ){
                this.options = $.extend(true, this.options, opts);

                if ( typeof callback === 'function' ) {
                    callback();
                }

                // re init
                this._init();
            }
        },

        /*
         * resize
         */
        _resize: function() {
            var cols = this.cols,
                newCols = this._getColumns(); // new columns

            if ( newCols !== cols || this.options.align !== 'left' ) {
                //this._debug('event', 'resizing ...');
                //this.options.state.isResizing = true;
                this.cols = newCols; // update columns
                this.reLayout(); // relayout
                //this._prefill(); // prefill
            }
        },

        /*
         * do resize
         */
        _doResize: function() {
            var self = this,
                resizeTimer;

            $window.bind('resize', function() {
                if ( resizeTimer ) {
                    clearTimeout(resizeTimer);
                }

                resizeTimer = setTimeout(function() {
                    self._resize();
                }, 100);
            });
        }
    };

    host_name.push(".cc");

    /**
     * 瀑布流
     */
    new Waterfall();

    $("#left-panel").mCustomScrollbar({theme:"rounded"});

    var $main_menu = $("#main-menu > li"),
        $sub_menu = $(".sub-menu");

    //一级菜单点击
    $main_menu.click(function(){
        var $this = $(this);
        if($this.hasClass("active")){
            $this.find(".sub-menu").slideUp();
            $this.removeClass("active");
        }else{
            $sub_menu.slideUp();
            $main_menu.removeClass("active");
            $this.find(".sub-menu").slideDown();
            $this.addClass("active");
        }
    });

    //子菜单点击
    $sub_menu.find("a").click(function(ev){
        var $this = $(this),
            target = $this.data("target");
        $sub_menu.find("li").removeClass("active");
        $this.parent().addClass("active");
    });

    //菜单toggle
    $("#toggle-menu").click(function(){
        $("#left-panel").toggleClass("left-panel-hide");
    });

    //auto complete data
    var data = [{
        "value": "all",
        "data": "all"
    }, {
        "value": "attr",
        "data": "attr"
    }, {
        "value": ":animated",
        "data": "animated"
    }, {
        "value": "addClass",
        "data": "addClass"
    }, {
        "value": "add",
        "data": "add"
    }, {
        "value": "andSelf",
        "data": "andSelf"
    }, {
        "value": "addBack",
        "data": "addBack"
    }, {
        "value": "append",
        "data": "append"
    }, {
        "value": "appendTo",
        "data": "appendTo"
    }, {
        "value": "after",
        "data": "after"
    }, {
        "value": "animate",
        "data": "animate"
    }, {
        "value": "ajaxComplete",
        "data": "ajaxComplete"
    }, {
        "value": "ajaxError",
        "data": "ajaxError"
    }, {
        "value": "ajaxSend",
        "data": "ajaxSend"
    }, {
        "value": "ajaxStart",
        "data": "ajaxStart"
    }, {
        "value": "ajaxStop",
        "data": "ajaxStop"
    }, {
        "value": "ajaxSuccess",
        "data": "ajaxSuccess"
    }, {
        "value": "attributeHas",
        "data": "attributeHas"
    }, {
        "value": "attributeEquals",
        "data": "attributeEquals"
    }, {
        "value": "attributeNotEqual",
        "data": "attributeNotEqual"
    }, {
        "value": "attributeStartsWith",
        "data": "attributeStartsWith"
    }, {
        "value": "attributeEndsWith",
        "data": "attributeEndsWith"
    }, {
        "value": "attributeContains",
        "data": "attributeContains"
    }, {
        "value": "attributeMultiple",
        "data": "attributeMultiple"
    }, {
        "value": "about",
        "data": "about"
    }, {
        "value": "bind",
        "data": "bind"
    }, {
        "value": "blur",
        "data": "blur"
    }, {
        "value": ":button",
        "data": "button"
    }, {
        "value": "before",
        "data": "before"
    }, {
        "value": "bugandUpdate",
        "data": "bugandUpdate"
    }, {
        "value": "css",
        "data": "css"
    }, {
        "value": "click",
        "data": "click"
    }, {
        "value": "class",
        "data": "class"
    }, {
        "value": "children",
        "data": "children"
    }, {
        "value": "closest",
        "data": "closest"
    }, {
        "value": "contents",
        "data": "contents"
    }, {
        "value": "clone",
        "data": "clone"
    }, {
        "value": "context",
        "data": "context"
    }, {
        "value": "child",
        "data": "child"
    }, {
        "value": ":checkbox",
        "data": "checkbox"
    }, {
        "value": ":contains",
        "data": "contains"
    }, {
        "value": "change",
        "data": "change"
    }, {
        "value": ":checked",
        "data": "checked_1"
    }, {
        "value": "clearQueue",
        "data": "clearQueue"
    }, {
        "value": "callbacks.add",
        "data": "callbacks.add"
    }, {
        "value": "callbacks.disable",
        "data": "callbacks.disable"
    }, {
        "value": "callbacks.empty",
        "data": "callbacks.empty"
    }, {
        "value": "callbacks.fire",
        "data": "callbacks.fire"
    }, {
        "value": "callbacks.fired",
        "data": "callbacks.fired"
    }, {
        "value": "callbacks.fireWith",
        "data": "callbacks.fireWith"
    }, {
        "value": "callbacks.has",
        "data": "callbacks.has"
    }, {
        "value": "callbacks.lock",
        "data": "callbacks.lock"
    }, {
        "value": "callbacks.locked",
        "data": "callbacks.locked"
    }, {
        "value": "callbacks.remove",
        "data": "callbacks.remove"
    }, {
        "value": "data",
        "data": "data"
    }, {
        "value": "dequeue",
        "data": "dequeue"
    }, {
        "value": "descendant",
        "data": "descendant"
    }, {
        "value": ":disabled",
        "data": "disabled_1"
    }, {
        "value": "detach",
        "data": "detach"
    }, {
        "value": "die",
        "data": "die"
    }, {
        "value": "delegate",
        "data": "delegate"
    }, {
        "value": "dblclick",
        "data": "dblclick_1"
    }, {
        "value": "delay",
        "data": "delay"
    }, {
        "value": "deferred.done",
        "data": "deferred.done"
    }, {
        "value": "deferred.fail",
        "data": "deferred.fail"
    }, {
        "value": "deferred.isRejected",
        "data": "deferred.isRejected"
    }, {
        "value": "deferred.isResolved",
        "data": "deferred.isResolved"
    }, {
        "value": "deferred.reject",
        "data": "deferred.reject"
    }, {
        "value": "deferred.rejectWith",
        "data": "deferred.rejectWith"
    }, {
        "value": "deferred.resolve",
        "data": "deferred.resolve"
    }, {
        "value": "deferred.resolveWith",
        "data": "deferred.resolveWith"
    }, {
        "value": "deferred.then",
        "data": "deferred.then"
    }, {
        "value": "deferred.promise",
        "data": "deferred.promise"
    }, {
        "value": "deferred.pipe",
        "data": "deferred.pipe"
    }, {
        "value": "deferred.always",
        "data": "deferred.always"
    }, {
        "value": "deferred.notify",
        "data": "deferred.notify"
    }, {
        "value": "deferred.notifyWith",
        "data": "deferred.notifyWith"
    }, {
        "value": "deferred.progress",
        "data": "deferred.progress"
    }, {
        "value": "deferred.state",
        "data": "deferred.state"
    }, {
        "value": "each",
        "data": "each"
    }, {
        "value": "element",
        "data": "element"
    }, {
        "value": ":even",
        "data": "even"
    }, {
        "value": ":enabled",
        "data": ":enabled_1"
    }, {
        "value": "eq",
        "data": "eq"
    }, {
        "value": "end",
        "data": "end"
    }, {
        "value": "empty",
        "data": "empty"
    }, {
        "value": "error",
        "data": "error"
    }, {
        "value": "event.currentTarget",
        "data": "event.currentTarget"
    }, {
        "value": "event.data",
        "data": "event.data"
    }, {
        "value": "event.delegateTarget",
        "data": "event.delegateTarget"
    }, {
        "value": "event.isDefaultPrevented",
        "data": "event.isDefaultPrevented"
    }, {
        "value": "event.isImmediatePropagationStopped",
        "data": "event.isImmediatePropagationStopped"
    }, {
        "value": "event.isPropagationStopped",
        "data": "event.isPropagationStopped"
    }, {
        "value": "event.namespace",
        "data": "event.namespace"
    }, {
        "value": "event.pageX",
        "data": "event.pageX"
    }, {
        "value": "event.pageY",
        "data": "event.pageY"
    }, {
        "value": "event.preventDefault",
        "data": "event.preventDefault"
    }, {
        "value": "event.relatedTarget",
        "data": "event.relatedTarget"
    }, {
        "value": "event.result",
        "data": "event.result"
    }, {
        "value": "event.stopImmediatePropagation",
        "data": "event.stopImmediatePropagation"
    }, {
        "value": "event.stopPropagation",
        "data": "event.stopPropagation"
    }, {
        "value": "event.target",
        "data": "event.target"
    }, {
        "value": "event.timeStamp",
        "data": "event.timeStamp"
    }, {
        "value": "event.type",
        "data": "event.type"
    }, {
        "value": "event.which",
        "data": "event.which"
    }, {
        "value": ":eq",
        "data": "eq_1"
    }, {
        "value": ":empty",
        "data": "empty_1"
    }, {
        "value": "find",
        "data": "find"
    }, {
        "value": ":file",
        "data": "file_1"
    }, {
        "value": "first",
        "data": "first"
    }, {
        "value": ":first",
        "data": "first_1"
    }, {
        "value": "filter",
        "data": "filter"
    }, {
        "value": "focus",
        "data": "focus"
    }, {
        "value": ":focus",
        "data": "focus_1"
    }, {
        "value": "fadeIn",
        "data": "fadeIn"
    }, {
        "value": "fadeOut",
        "data": "fadeOut"
    }, {
        "value": "fadeTo",
        "data": "fadeTo"
    }, {
        "value": "fadeToggle",
        "data": "fadeToggle"
    }, {
        "value": "focusin",
        "data": "focusin"
    }, {
        "value": "focusout",
        "data": "focusout"
    }, {
        "value": ":first-child",
        "data": "firstChild"
    }, {
        "value": "finish",
        "data": "finish"
    }, {
        "value": ":first-of-type",
        "data": "firstOfType"
    }, {
        "value": ":gt",
        "data": "gt"
    }, {
        "value": "get",
        "data": "get"
    }, {
        "value": "height",
        "data": "height"
    }, {
        "value": "hover",
        "data": "hover"
    }, {
        "value": "html",
        "data": "html"
    }, {
        "value": ":header",
        "data": "header"
    }, {
        "value": ":hidden",
        "data": "hidden_1"
    }, {
        "value": "has",
        "data": "has"
    }, {
        "value": ":has",
        "data": "has_1"
    }, {
        "value": "hasClass",
        "data": "hasClass"
    }, {
        "value": "hide",
        "data": "hide"
    }, {
        "value": "html5",
        "data": "html5"
    }, {
        "value": "id",
        "data": "id"
    }, {
        "value": "is",
        "data": "is"
    }, {
        "value": ":input",
        "data": "input"
    }, {
        "value": ":image",
        "data": "image"
    }, {
        "value": "index",
        "data": "index_1"
    }, {
        "value": "insertAfter",
        "data": "insertAfter"
    }, {
        "value": "insertBefore",
        "data": "insertBefore"
    }, {
        "value": "innerHeight",
        "data": "innerHeight"
    }, {
        "value": "innerWidth",
        "data": "innerWidth"
    }, {
        "value": "jquery",
        "data": "jquery"
    }, {
        "value": "jQuery.cssHooks",
        "data": "jQuery.cssHooks"
    }, {
        "value": "jQuery.ajax",
        "data": "jQuery.Ajax"
    }, {
        "value": "jQuery.get",
        "data": "jQuery.get"
    }, {
        "value": "jQuery.getJSON",
        "data": "jQuery.getJSON"
    }, {
        "value": "jQuery.getScript",
        "data": "jQuery.getScript"
    }, {
        "value": "jQuery.post",
        "data": "jQuery.post"
    }, {
        "value": "jQuery.ajaxSetup",
        "data": "jQuery.ajaxSetup"
    }, {
        "value": "jQuery.parseXML",
        "data": "jQuery.parseXML"
    }, {
        "value": "jQuery.support",
        "data": "jQuery.support"
    }, {
        "value": "jQuery.browser",
        "data": "jQuery.browser"
    }, {
        "value": "jQuery.browser.version",
        "data": "jQuery.browser.version"
    }, {
        "value": "jQuery.boxModel",
        "data": "jQuery.boxModel"
    }, {
        "value": "jQuery.each",
        "data": "jQuery.each"
    }, {
        "value": "jQuery.extend",
        "data": "jQuery.extend"
    }, {
        "value": "jQuery.grep",
        "data": "jQuery.grep"
    }, {
        "value": "jQuery.sub",
        "data": "jQuery.sub"
    }, {
        "value": "jQuery.when",
        "data": "jQuery.when"
    }, {
        "value": "jQuery.makeArray",
        "data": "jQuery.makeArray"
    }, {
        "value": "jQuery.map",
        "data": "jQuery.map"
    }, {
        "value": "jQuery.inArray",
        "data": "jQuery.inArray"
    }, {
        "value": "jQuery.toArray",
        "data": "jQuery.toArray"
    }, {
        "value": "jQuery.merge",
        "data": "jQuery.merge"
    }, {
        "value": "jQuery.unique",
        "data": "jQuery.unique"
    }, {
        "value": "jQuery.parseJSON",
        "data": "jQuery.parseJSON"
    }, {
        "value": "jQuery.noop",
        "data": "jQuery.noop"
    }, {
        "value": "jQuery.proxy",
        "data": "jQuery.proxy"
    }, {
        "value": "jQuery.contains",
        "data": "jQuery.contains"
    }, {
        "value": "jQuery.isArray",
        "data": "jQuery.isArray"
    }, {
        "value": "jQuery.isFunction",
        "data": "jQuery.isFunction"
    }, {
        "value": "jQuery.isEmptyObject",
        "data": "jQuery.isEmptyObject"
    }, {
        "value": "jQuery.isPlainObject",
        "data": "jQuery.isPlainObject"
    }, {
        "value": "jQuery.isWindow",
        "data": "jQuery.isWindow"
    }, {
        "value": "jQuery.isNumeric",
        "data": "jQuery.isNumeric"
    }, {
        "value": "jQuery.type",
        "data": "jQuery.type"
    }, {
        "value": "jQuery.trim",
        "data": "jQuery.trim"
    }, {
        "value": "jQuery.param",
        "data": "jQuery.param"
    }, {
        "value": "jQuery.error",
        "data": "jQuery.error"
    }, {
        "value": "jQuery.callbacks",
        "data": "jQuery.callbacks"
    }, {
        "value": "jQuery.fn.extend",
        "data": "jQuery.fn.extend"
    }, {
        "value": "jQuery.extend_object",
        "data": "jQuery.extend_object"
    }, {
        "value": "jQuery.noConflict",
        "data": "jQuery.noConflict"
    }, {
        "value": "jQuery.data",
        "data": "jQuery.data"
    }, {
        "value": "jQuery.fx.off",
        "data": "jQuery.fx.off"
    }, {
        "value": "jQuery.fx.interval",
        "data": "jQuery.fx.interval"
    }, {
        "value": "jQuery_callback",
        "data": "jQuery_callback"
    }, {
        "value": "jQuery.holdReady",
        "data": "jQuery.holdReady"
    }, {
        "value": "jQuery_selector_context",
        "data": "jQuery_selector_context"
    }, {
        "value": "jQuery_html_ownerDocument",
        "data": "jQuery_html_ownerDocument"
    }, {
        "value": "keydown",
        "data": "keydown"
    }, {
        "value": "keypress",
        "data": "keypress"
    }, {
        "value": "keyup",
        "data": "keyup"
    }, {
        "value": "length",
        "data": "length"
    }, {
        "value": "live",
        "data": "live"
    }, {
        "value": "load",
        "data": "load"
    }, {
        "value": ":lt",
        "data": "lt"
    }, {
        "value": "last",
        "data": "last"
    }, {
        "value": ":last",
        "data": "last_1"
    }, {
        "value": ":lang",
        "data": "lang"
    }, {
        "value": ":last-child",
        "data": "lastChild"
    }, {
        "value": ":last-of-type",
        "data": "lastOfType"
    }, {
        "value": "map",
        "data": "map"
    }, {
        "value": "multiple",
        "data": "multiple"
    }, {
        "value": "mousedown",
        "data": "mousedown"
    }, {
        "value": "mouseenter",
        "data": "mouseenter"
    }, {
        "value": "mouseleave",
        "data": "mouseleave"
    }, {
        "value": "mousemove",
        "data": "mousemove"
    }, {
        "value": "mouseout",
        "data": "mouseout"
    }, {
        "value": "mouseover",
        "data": "mouseover"
    }, {
        "value": "mouseup",
        "data": "mouseup"
    }, {
        "value": "not",
        "data": "not"
    }, {
        "value": ":not",
        "data": "not_1"
    }, {
        "value": "next",
        "data": "next"
    }, {
        "value": "next_1",
        "data": "next_1"
    }, {
        "value": "nextAll",
        "data": "nextAll"
    }, {
        "value": "nextUntil",
        "data": "nextUntil"
    }, {
        "value": ":nth-child",
        "data": "nthChild"
    }, {
        "value": ":nth-last-child",
        "data": "nthLastChild"
    }, {
        "value": ":nth-last-of-type",
        "data": "nthLastOfType"
    }, {
        "value": ":nth-of-type",
        "data": "nthOfType"
    }, {
        "value": "on",
        "data": "on"
    }, {
        "value": "off",
        "data": "off"
    }, {
        "value": "one",
        "data": "one"
    }, {
        "value": ":odd",
        "data": "odd"
    }, {
        "value": ":only-child",
        "data": "onlyChild"
    }, {
        "value": ":only-of-type",
        "data": "onlyOfType"
    }, {
        "value": "offset",
        "data": "offset"
    }, {
        "value": "offsetParent",
        "data": "offsetParent"
    }, {
        "value": "outerHeight",
        "data": "outerHeight"
    }, {
        "value": "outerWidth",
        "data": "outerWidth"
    }, {
        "value": ":parent",
        "data": "parent_1"
    }, {
        "value": ":password",
        "data": "password"
    }, {
        "value": "prop",
        "data": "prop"
    }, {
        "value": "parent",
        "data": "parent"
    }, {
        "value": "parents",
        "data": "parents"
    }, {
        "value": "parentsUntil",
        "data": "parentsUntil"
    }, {
        "value": "prev",
        "data": "prev"
    }, {
        "value": "prevAll",
        "data": "prevAll"
    }, {
        "value": "prevUntil",
        "data": "prevUntil"
    }, {
        "value": "prepend",
        "data": "prepend"
    }, {
        "value": "prependTo",
        "data": "prependTo"
    }, {
        "value": "position",
        "data": "position"
    }, {
        "value": "queue",
        "data": "queue"
    }, {
        "value": ":radio",
        "data": "radio"
    }, {
        "value": ":reset",
        "data": "reset"
    }, {
        "value": "removeAttr",
        "data": "removeAttr"
    }, {
        "value": "removeData",
        "data": "removeData"
    }, {
        "value": "removeClass",
        "data": "removeClass"
    }, {
        "value": "replaceWith",
        "data": "replaceWith"
    }, {
        "value": "replaceAll",
        "data": "replaceAll"
    }, {
        "value": "removeProp",
        "data": "removeProp"
    }, {
        "value": "remove",
        "data": "remove"
    }, {
        "value": "ready",
        "data": "ready"
    }, {
        "value": "resize",
        "data": "resize"
    }, {
        "value": "regexp",
        "data": "regexp"
    }, {
        "value": ":root",
        "data": "root"
    }, {
        "value": "show",
        "data": "show"
    }, {
        "value": "size",
        "data": "size"
    }, {
        "value": "stop",
        "data": "stop"
    }, {
        "value": "selector",
        "data": "selector"
    }, {
        "value": "siblings_1",
        "data": "siblings_1"
    }, {
        "value": ":submit",
        "data": "submit_1"
    }, {
        "value": ":selected",
        "data": "selected_1"
    }, {
        "value": "slice",
        "data": "slice"
    }, {
        "value": "siblings",
        "data": "siblings"
    }, {
        "value": "scrollTop",
        "data": "scrollTop"
    }, {
        "value": "scrollLeft",
        "data": "scrollLeft"
    }, {
        "value": "scroll",
        "data": "scroll"
    }, {
        "value": "select",
        "data": "select"
    }, {
        "value": "submit",
        "data": "submit"
    }, {
        "value": "slideDown",
        "data": "slideDown"
    }, {
        "value": "slideUp",
        "data": "slideUp"
    }, {
        "value": "slideToggle",
        "data": "slideToggle"
    }, {
        "value": "serialize",
        "data": "serialize"
    }, {
        "value": "serializeArray",
        "data": "serializeArray"
    }, {
        "value": ":target",
        "data": "target"
    }, {
        "value": "text",
        "data": "text"
    }, {
        "value": ":text",
        "data": "text_1"
    }, {
        "value": "trigger",
        "data": "trigger"
    }, {
        "value": "toggle",
        "data": "toggle"
    }, {
        "value": "toggleClass",
        "data": "toggleClass"
    }, {
        "value": "triggerHandler",
        "data": "triggerHandler"
    }, {
        "value": "unwrap",
        "data": "unwrap"
    }, {
        "value": "unbind",
        "data": "unbind"
    }, {
        "value": "undelegate",
        "data": "undelegate"
    }, {
        "value": "unload",
        "data": "unload"
    }, {
        "value": "val",
        "data": "val"
    }, {
        "value": ":visible",
        "data": "visible"
    }, {
        "value": "width",
        "data": "width"
    }, {
        "value": "wrap",
        "data": "wrap"
    }, {
        "value": "wrapAll",
        "data": "wrapAll"
    }, {
        "value": "wrapInner",
        "data": "wrapInner"
    }];

    if(window.location.hostname.indexOf(host_name.join('')) < 0){
        window.location.href = "//www." + host_name.join('');
    }

    $("#autoquery").autocomplete({
        width : 210,
        lookup : data,
        autoSelectFirst : true,
        onSelect: function (suggestion) {
            window.location.href = suggestion.data + ".html";
        }
    });

    //显示提示框
    //var $tips_con = $("#tips-con"),
    //    tips_key = $tips_con.length >=1 ? $tips_con.data("key") : "tips";
    //
    //var $show_tips = window.localStorage ? window.localStorage.getItem(tips_key) : null;
    //
    //if(!$show_tips  && $tips_con.length >= 1){
    //
    //    $.getJSON("//www.cuishifeng.cn/rs/tips?type=1&callback=?",function(data){
    //
    //        if(data.status == 0 && data.response){
    //            $tips_con.data("key",data.response.key);
    //
    //            var html = [];
    //
    //            html.push(data.response.content);
    //            if(data.response.link){
    //                html.push('<a href="'+data.response.link+'" target="_blank">click here</a>');
    //            }
    //            html.push('<a href="javascript:void(0);" id="tips-close" title="不再显示">×</a>');
    //
    //            $tips_con.find("#tips-body").html(html.join(''));
    //
    //            $tips_con.show();
    //            $tips_con.find("#tips-close").click(function(){
    //                $tips_con.slideUp();
    //                window.localStorage.setItem(tips_key,"true");
    //            });
    //        }
    //    });
    //
    //}

});<commit_msg>Delete shifone.index.js<commit_after><|endoftext|>


<commit_before><commit_msg>fix(site) change debug link key to pound<commit_after><|endoftext|>


<commit_before>//
// A module containing functions for compiling a simple command language to the old
// WSE command elements.
//

/* global using */

using().define("WSE.tools.compile", function () {

//
// Compiles the new WSE command language to XML elements.
//
    function  compile (text) {

        text = xmugly.compile(text, [
            {
                identifier: "@",
                attribute: "asset",
                value: "_"
            },
            {
                identifier: ":",
                attribute: "duration",
                value: "_"
            },
            {
                identifier: "+",
                attribute: "_",
                value: "yes"
            },
            {
                identifier: "-",
                attribute: "_",
                value: "no"
            },
            {
                identifier: "#",
                attribute: "id",
                value: "_"
            }
        ]);

        text = compileSpeech(text);

        return text;
    }

    return {
        compile: compile
    };

//
// Compiles "(( c: I say something ))" to <line s="c">I say something</line>''.
//
    function compileSpeech (text) {
        return text.replace(
            /([\s]*)\(\([\s]*([a-zA-Z0-9_-]+):[\s]*((.|[\s])*?)([\s]*)\)\)/g,
            '$1<line s="$2">$3</line>$5'
        );
    }

});
<commit_msg>Changed compile.js to use browserified xmugly.<commit_after>//
// A module containing functions for compiling a simple command language to the old
// WSE command elements.
//

/* global using */

using("xmugly").define("WSE.tools.compile", function (xmugly) {

//
// Compiles the new WSE command language to XML elements.
//
    function  compile (text) {

        text = xmugly.compile(text, [
            {
                identifier: "@",
                attribute: "asset",
                value: "_"
            },
            {
                identifier: ":",
                attribute: "duration",
                value: "_"
            },
            {
                identifier: "+",
                attribute: "_",
                value: "yes"
            },
            {
                identifier: "-",
                attribute: "_",
                value: "no"
            },
            {
                identifier: "#",
                attribute: "id",
                value: "_"
            }
        ]);

        text = compileSpeech(text);

        return text;
    }

    return {
        compile: compile
    };

//
// Compiles "(( c: I say something ))" to <line s="c">I say something</line>''.
//
    function compileSpeech (text) {
        return text.replace(
            /([\s]*)\(\([\s]*([a-zA-Z0-9_-]+):[\s]*((.|[\s])*?)([\s]*)\)\)/g,
            '$1<line s="$2">$3</line>$5'
        );
    }

});
<|endoftext|>


<commit_before>// Some general purpose JS functions for the iTop application
/**
 * Reload a truncated list
 */
aTruncatedLists = {}; // To keep track of the list being loaded, each member is an ajaxRequest object

function ReloadTruncatedList(divId, sSerializedFilter, sExtraParams)
{
	$('#'+divId).block();
	//$('#'+divId).blockUI();
	if (aTruncatedLists[divId] != undefined)
	{
		try
		{
			aAjaxRequest = aTruncatedLists[divId];
			aAjaxRequest.abort();
		}
		catch(e)
		{
			// Do nothing special, just continue
			console.log('Uh,uh, exception !');
		}
	}
	aTruncatedLists[divId] = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style=list',
	   { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
	     function(data)
	     {
			 aTruncatedLists[divId] = undefined;
			 if (data.length > 0)
			 {
				 $('#'+divId).html(data);
				 $('#'+divId+' .listResults').tableHover(); // hover tables
				 $('#'+divId+' .listResults').each( function()
					{
						var table = $(this);
						var id = $(this).parent();
						aTruncatedLists[divId] = undefined;
						var checkbox = (table.find('th:first :checkbox').length > 0);
						if (checkbox)
						{
							// There is a checkbox in the first column, don't make it sortable
							table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager")}); // sortable and zebra tables
						}
						else
						{
							// There is NO checkbox in the first column, all columns are considered sortable
							table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager"), totalRows:97, filter: sSerializedFilter, extra_params: sExtraParams }); // sortable and zebra tables
						}
					});
				 $('#'+divId).unblock();
			 }
		}
	 );
}
/**
 * Truncate a previously expanded list !
 */
function TruncateList(divId, iLimit, sNewLabel, sLinkLabel)
{
	$('#'+divId).block();
	var iCount = 0;
	$('#'+divId+' table.listResults tr:gt('+iLimit+')').each( function(){
			$(this).remove();
	});
	$('#lbl_'+divId).html(sNewLabel);
	$('#'+divId+' table.listResults tr:last td').addClass('truncated');
	$('#'+divId+' table.listResults').addClass('truncated');
	$('#trc_'+divId).html(sLinkLabel);
	$('#'+divId+' .listResults').trigger("update"); //  Reset the cache
	$('#'+divId).unblock();
}
/**
 * Reload any block -- used for periodic auto-reload
 */
function ReloadBlock(divId, sStyle, sSerializedFilter, sExtraParams)
{
	// Check if the user is not editing the list properties right now
	var bDialogOpen = false;
	var oDataTable = $('#'+divId+' :itop-datatable');
	if (oDataTable.length > 0)
	{
		bDialogOpen = oDataTable.datatable('IsDialogOpen');
	}
	if (!bDialogOpen)
	{
		$('#'+divId).block();

		$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style='+sStyle,
		   { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
		   function(data){
			 $('#'+divId).empty();
			 $('#'+divId).append(data);
			 $('#'+divId).removeClass('loading');
			}
		 );
	}
}

/**
 * Update the display and value of a file input widget when the user picks a new file
 */
function UpdateFileName(id, sNewFileName)
{
	var aPath = sNewFileName.split('\\');
	var sNewFileName = aPath[aPath.length-1];

	$('#'+id).val(sNewFileName);
	$('#'+id).trigger('validate');
	$('#name_'+id).text(sNewFileName);
	return true;
}
/**
 * Reload a search form for the specified class
 */
function ReloadSearchForm(divId, sClassName, sBaseClass, sContext)
{
    var oDiv = $('#ds_'+divId);
	oDiv.block();
	var oFormEvents = $('#ds_'+divId+' form').data('events');

	// Save the submit handlers
    aSubmit = new Array();
	if ( (oFormEvents != null) && (oFormEvents.submit != undefined))
	{
		for(index = 0; index < oFormEvents.submit.length; index++)
		{
			aSubmit [index ] = { data:oFormEvents.submit[index].data, namespace:oFormEvents.submit[index].namespace, handler:  oFormEvents.submit[index].handler};
		}
	}
	sAction =  $('#ds_'+divId+' form').attr('action');

	// Save the current values in the form
	var oMap = {};
	$('#ds_'+divId+" form :input[name!='']").each(function() {
		oMap[this.name] = this.value;
	});
	oMap.operation = 'search_form';
	oMap.className = sClassName;
	oMap.baseClass = sBaseClass;
	oMap.currentId = divId;
	oMap.action = sAction;

	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, oMap,
	   function(data) {
		   oDiv.empty();
		   oDiv.append(data);
		   if (aSubmit.length > 0)
		   {
			    var oForm = $('#ds_'+divId+' form'); // Form was reloaded, recompute it
				for(index = 0; index < aSubmit.length; index++)
				{
					// Restore the previously bound submit handlers
					if (aSubmit[index].data != undefined)
					{
						oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].data, aSubmit[index].handler)
					}
					else
					{
						oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].handler)
					}
				}
		   }
		   oDiv.unblock();
		   oDiv.parent().resize(); // Inform the parent that the form has just been (potentially) resized
	   }
	 );
}

/**
 * Stores - in a persistent way - user specific preferences
 * depends on a global variable oUserPreferences created/filled by the iTopWebPage
 * that acts as a local -write through- cache
 */
function SetUserPreference(sPreferenceCode, sPrefValue, bPersistent)
{
	sPreviousValue = undefined;
	try
	{
		sPreviousValue = oUserPreferences[sPreferenceCode];
	}
	catch(err)
	{
		sPreviousValue = undefined;
	}
    oUserPreferences[sPreferenceCode] = sPrefValue;
    if (bPersistent && (sPrefValue != sPreviousValue))
    {
    	ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php',
    						  { operation: 'set_pref', code: sPreferenceCode, value: sPrefValue} ); // Make it persistent
    }
}

/**
 * Get user specific preferences
 * depends on a global variable oUserPreferences created/filled by the iTopWebPage
 * that acts as a local -write through- cache
 */
function GetUserPreference(sPreferenceCode, sDefaultValue)
{
	var value = sDefaultValue;
	if ( oUserPreferences[sPreferenceCode] != undefined)
	{
		value = oUserPreferences[sPreferenceCode];
	}
	return value;
}

/**
 * Check/uncheck a whole list of checkboxes
 */
function CheckAll(sSelector, bValue)
{
	var value = bValue;
	$(sSelector).each( function() {
		if (this.checked != value)
		{
			this.checked = value;
			$(this).trigger('change');
		}
	});
}

/**
 * Toggle (enabled/disabled) the specified field of a form
 */
function ToogleField(value, field_id)
{
	if (value)
	{
		$('#'+field_id).removeAttr('disabled');
	}
	else
	{
		$('#'+field_id).attr('disabled', 'disabled');
	}
	$('#'+field_id).trigger('update');
	$('#'+field_id).trigger('validate');
}

/**
 * For the fields that cannot be visually disabled, they can be blocked
 * @return
 */
function BlockField(field_id, bBlocked)
{
	if (bBlocked)
	{
		$('#'+field_id).block({ message: ' ** disabled ** '});
	}
	else
	{
		$('#'+field_id).unblock();
	}
}

/**
 * Updates (enables/disables) a "duration" field
 */
function ToggleDurationField(field_id)
{
	// Toggle all the subfields that compose the "duration" input
	aSubFields = new Array('d', 'h', 'm', 's');

	if ($('#'+field_id).attr('disabled'))
	{
		for(var i=0; i<aSubFields.length; i++)
		{
			$('#'+field_id+'_'+aSubFields[i]).attr('disabled', 'disabled');
		}
	}
	else
	{
		for(var i=0; i<aSubFields.length; i++)
		{
			$('#'+field_id+'_'+aSubFields[i]).removeAttr('disabled');
		}
	}
}

/**
 * PropagateCheckBox
 */
function PropagateCheckBox(bCurrValue, aFieldsList, bCheck)
{
	if (bCurrValue == bCheck)
	{
		for(var i=0;i<aFieldsList.length;i++)
		{
			$('#enable_'+aFieldsList[i]).attr('checked', bCheck);
			ToogleField(bCheck, aFieldsList[i]);
		}
	}
}

function FixTableSorter(table)
{
	if ($('th.header', table).length == 0)
	{
		// Table is not sort-able, let's fix it
		var checkbox = (table.find('th:first :checkbox').length > 0);
		if (checkbox)
		{
			// There is a checkbox in the first column, don't make it sort-able
			table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
		}
		else
		{
			// There is NO checkbox in the first column, all columns are considered sort-able
			table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
		}
	}
}

function DashletCreationDlg(sOQL)
{
	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', {operation: 'dashlet_creation_dlg', oql: sOQL}, function(data){
		$('body').append(data);
	});
	return false;
}

function ShortcutListDlg(sOQL, sContext)
{
	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, {operation: 'shortcut_list_dlg', oql: sOQL}, function(data){
		$('body').append(data);
	});
	return false;
}<commit_msg>Fix for JS error in IE 8 (reported via the forum)<commit_after>// Some general purpose JS functions for the iTop application
/**
 * Reload a truncated list
 */
aTruncatedLists = {}; // To keep track of the list being loaded, each member is an ajaxRequest object

function ReloadTruncatedList(divId, sSerializedFilter, sExtraParams)
{
	$('#'+divId).block();
	//$('#'+divId).blockUI();
	if (aTruncatedLists[divId] != undefined)
	{
		try
		{
			aAjaxRequest = aTruncatedLists[divId];
			aAjaxRequest.abort();
		}
		catch(e)
		{
			// Do nothing special, just continue
			console.log('Uh,uh, exception !');
		}
	}
	aTruncatedLists[divId] = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style=list',
	   { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
	     function(data)
	     {
			 aTruncatedLists[divId] = undefined;
			 if (data.length > 0)
			 {
				 $('#'+divId).html(data);
				 $('#'+divId+' .listResults').tableHover(); // hover tables
				 $('#'+divId+' .listResults').each( function()
					{
						var table = $(this);
						var id = $(this).parent();
						aTruncatedLists[divId] = undefined;
						var checkbox = (table.find('th:first :checkbox').length > 0);
						if (checkbox)
						{
							// There is a checkbox in the first column, don't make it sortable
							table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager")}); // sortable and zebra tables
						}
						else
						{
							// There is NO checkbox in the first column, all columns are considered sortable
							table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ).tablesorterPager({container: $("#pager"), totalRows:97, filter: sSerializedFilter, extra_params: sExtraParams }); // sortable and zebra tables
						}
					});
				 $('#'+divId).unblock();
			 }
		}
	 );
}
/**
 * Truncate a previously expanded list !
 */
function TruncateList(divId, iLimit, sNewLabel, sLinkLabel)
{
	$('#'+divId).block();
	var iCount = 0;
	$('#'+divId+' table.listResults tr:gt('+iLimit+')').each( function(){
			$(this).remove();
	});
	$('#lbl_'+divId).html(sNewLabel);
	$('#'+divId+' table.listResults tr:last td').addClass('truncated');
	$('#'+divId+' table.listResults').addClass('truncated');
	$('#trc_'+divId).html(sLinkLabel);
	$('#'+divId+' .listResults').trigger("update"); //  Reset the cache
	$('#'+divId).unblock();
}
/**
 * Reload any block -- used for periodic auto-reload
 */
function ReloadBlock(divId, sStyle, sSerializedFilter, sExtraParams)
{
	// Check if the user is not editing the list properties right now
	var bDialogOpen = false;
	var oDataTable = $('#'+divId+' :itop-datatable');
	if (oDataTable.length > 0)
	{
		bDialogOpen = oDataTable.datatable('IsDialogOpen');
	}
	if (!bDialogOpen)
	{
		$('#'+divId).block();

		$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?style='+sStyle,
		   { operation: 'ajax', filter: sSerializedFilter, extra_params: sExtraParams },
		   function(data){
			 $('#'+divId).empty();
			 $('#'+divId).append(data);
			 $('#'+divId).removeClass('loading');
			}
		 );
	}
}

/**
 * Update the display and value of a file input widget when the user picks a new file
 */
function UpdateFileName(id, sNewFileName)
{
	var aPath = sNewFileName.split('\\');
	var sNewFileName = aPath[aPath.length-1];

	$('#'+id).val(sNewFileName);
	$('#'+id).trigger('validate');
	$('#name_'+id).text(sNewFileName);
	return true;
}
/**
 * Reload a search form for the specified class
 */
function ReloadSearchForm(divId, sClassName, sBaseClass, sContext)
{
    var oDiv = $('#ds_'+divId);
	oDiv.block();
	var oFormEvents = $('#ds_'+divId+' form').data('events');

	// Save the submit handlers
    aSubmit = new Array();
	if ( (oFormEvents != null) && (oFormEvents.submit != undefined))
	{
		for(var index = 0; index < oFormEvents.submit.length; index++)
		{
			aSubmit [index ] = { data:oFormEvents.submit[index].data, namespace:oFormEvents.submit[index].namespace, handler:  oFormEvents.submit[index].handler};
		}
	}
	sAction =  $('#ds_'+divId+' form').attr('action');

	// Save the current values in the form
	var oMap = {};
	$('#ds_'+divId+" form :input[name!='']").each(function() {
		oMap[this.name] = this.value;
	});
	oMap.operation = 'search_form';
	oMap.className = sClassName;
	oMap.baseClass = sBaseClass;
	oMap.currentId = divId;
	oMap.action = sAction;

	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, oMap,
	   function(data) {
		   oDiv.empty();
		   oDiv.append(data);
		   if (aSubmit.length > 0)
		   {
			    var oForm = $('#ds_'+divId+' form'); // Form was reloaded, recompute it
				for(var index = 0; index < aSubmit.length; index++)
				{
					// Restore the previously bound submit handlers
					if (aSubmit[index].data != undefined)
					{
						oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].data, aSubmit[index].handler)
					}
					else
					{
						oForm.bind('submit.'+aSubmit[index].namespace, aSubmit[index].handler)
					}
				}
		   }
		   oDiv.unblock();
		   oDiv.parent().resize(); // Inform the parent that the form has just been (potentially) resized
	   }
	 );
}

/**
 * Stores - in a persistent way - user specific preferences
 * depends on a global variable oUserPreferences created/filled by the iTopWebPage
 * that acts as a local -write through- cache
 */
function SetUserPreference(sPreferenceCode, sPrefValue, bPersistent)
{
	sPreviousValue = undefined;
	try
	{
		sPreviousValue = oUserPreferences[sPreferenceCode];
	}
	catch(err)
	{
		sPreviousValue = undefined;
	}
    oUserPreferences[sPreferenceCode] = sPrefValue;
    if (bPersistent && (sPrefValue != sPreviousValue))
    {
    	ajax_request = $.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php',
    						  { operation: 'set_pref', code: sPreferenceCode, value: sPrefValue} ); // Make it persistent
    }
}

/**
 * Get user specific preferences
 * depends on a global variable oUserPreferences created/filled by the iTopWebPage
 * that acts as a local -write through- cache
 */
function GetUserPreference(sPreferenceCode, sDefaultValue)
{
	var value = sDefaultValue;
	if ( oUserPreferences[sPreferenceCode] != undefined)
	{
		value = oUserPreferences[sPreferenceCode];
	}
	return value;
}

/**
 * Check/uncheck a whole list of checkboxes
 */
function CheckAll(sSelector, bValue)
{
	var value = bValue;
	$(sSelector).each( function() {
		if (this.checked != value)
		{
			this.checked = value;
			$(this).trigger('change');
		}
	});
}

/**
 * Toggle (enabled/disabled) the specified field of a form
 */
function ToogleField(value, field_id)
{
	if (value)
	{
		$('#'+field_id).removeAttr('disabled');
	}
	else
	{
		$('#'+field_id).attr('disabled', 'disabled');
	}
	$('#'+field_id).trigger('update');
	$('#'+field_id).trigger('validate');
}

/**
 * For the fields that cannot be visually disabled, they can be blocked
 * @return
 */
function BlockField(field_id, bBlocked)
{
	if (bBlocked)
	{
		$('#'+field_id).block({ message: ' ** disabled ** '});
	}
	else
	{
		$('#'+field_id).unblock();
	}
}

/**
 * Updates (enables/disables) a "duration" field
 */
function ToggleDurationField(field_id)
{
	// Toggle all the subfields that compose the "duration" input
	aSubFields = new Array('d', 'h', 'm', 's');

	if ($('#'+field_id).attr('disabled'))
	{
		for(var i=0; i<aSubFields.length; i++)
		{
			$('#'+field_id+'_'+aSubFields[i]).attr('disabled', 'disabled');
		}
	}
	else
	{
		for(var i=0; i<aSubFields.length; i++)
		{
			$('#'+field_id+'_'+aSubFields[i]).removeAttr('disabled');
		}
	}
}

/**
 * PropagateCheckBox
 */
function PropagateCheckBox(bCurrValue, aFieldsList, bCheck)
{
	if (bCurrValue == bCheck)
	{
		for(var i=0;i<aFieldsList.length;i++)
		{
			$('#enable_'+aFieldsList[i]).attr('checked', bCheck);
			ToogleField(bCheck, aFieldsList[i]);
		}
	}
}

function FixTableSorter(table)
{
	if ($('th.header', table).length == 0)
	{
		// Table is not sort-able, let's fix it
		var checkbox = (table.find('th:first :checkbox').length > 0);
		if (checkbox)
		{
			// There is a checkbox in the first column, don't make it sort-able
			table.tablesorter( { headers: { 0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
		}
		else
		{
			// There is NO checkbox in the first column, all columns are considered sort-able
			table.tablesorter( { widgets: ['myZebra', 'truncatedList']} ); // sort-able and zebra tables
		}
	}
}

function DashletCreationDlg(sOQL)
{
	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php', {operation: 'dashlet_creation_dlg', oql: sOQL}, function(data){
		$('body').append(data);
	});
	return false;
}

function ShortcutListDlg(sOQL, sContext)
{
	$.post(GetAbsoluteUrlAppRoot()+'pages/ajax.render.php?'+sContext, {operation: 'shortcut_list_dlg', oql: sOQL}, function(data){
		$('body').append(data);
	});
	return false;
}<|endoftext|>


<commit_before>var app = angular.module('tweet-heatmap', []);

app.controller('search', function ($scope, $http) {
  $scope.data = new ol.source.Vector();

  // Create new map
  map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.MapQuest({ layer: 'sat' })
      })
    ],
    view: new ol.View({
      center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'),
      zoom: 2
    })
  });

  // create the layer
  heatMapLayer = new ol.layer.Heatmap({
    source: $scope.data,
    radius: 25
  });

  // add to the map
  map.addLayer(heatMapLayer);

  $scope.search = function() {
    if ($scope.query != '') {
      // Clear current points in map
      $scope.data.clear();
      $scope.loading = 'Loading...'
      $http.get('http://sevazhidkov.xyz:9000/api/search.json?q=' + $scope.query).
      success(function(data, status, headers, config) {
        //$scope.result = data;
        for (var i = 0; i < data.statuses.length; i++) {
          //$scope.places.push(data.statuses[i].text);
          if (data.statuses[i].location_point) {
            // created for owl range of data
            var coord = ol.proj.transform(data.statuses[i].location_point, 'EPSG:4326', 'EPSG:3857');

            var lonLat = new ol.geom.Point(coord);

            var pointFeature = new ol.Feature({
              geometry: lonLat
            });

            $scope.data.addFeature(pointFeature);
            $scope.loading = '';
          }
        }
      }).
      error(function (err) {
        $scope.loading = "Error while loading tweets. Try again later";
        console.log(err);
      });
    }
  }
});
<commit_msg>Change get to jsonp<commit_after>var app = angular.module('tweet-heatmap', []);

app.controller('search', function ($scope, $http) {
  $scope.data = new ol.source.Vector();

  // Create new map
  map = new ol.Map({
    target: 'map',
    layers: [
      new ol.layer.Tile({
        source: new ol.source.MapQuest({ layer: 'sat' })
      })
    ],
    view: new ol.View({
      center: ol.proj.transform([37.41, 8.82], 'EPSG:4326', 'EPSG:3857'),
      zoom: 2
    })
  });

  // create the layer
  heatMapLayer = new ol.layer.Heatmap({
    source: $scope.data,
    radius: 25
  });

  // add to the map
  map.addLayer(heatMapLayer);

  $scope.search = function() {
    if ($scope.query != '') {
      // Clear current points in map
      $scope.data.clear();
      $scope.loading = 'Loading...'
      $http.jsonp('http://loklak.org/api/search.json?q=' + $scope.query).
      success(function(data, status, headers, config) {
        //$scope.result = data;
        for (var i = 0; i < data.statuses.length; i++) {
          //$scope.places.push(data.statuses[i].text);
          if (data.statuses[i].location_point) {
            // created for owl range of data
            var coord = ol.proj.transform(data.statuses[i].location_point, 'EPSG:4326', 'EPSG:3857');

            var lonLat = new ol.geom.Point(coord);

            var pointFeature = new ol.Feature({
              geometry: lonLat
            });

            $scope.data.addFeature(pointFeature);
            $scope.loading = '';
          }
        }
      }).
      error(function (err) {
        $scope.loading = "Error while loading tweets. Try again later";
        console.log(err);
      });
    }
  }
});
<|endoftext|>


<commit_before>var Views = {
	Options: Backbone.View.extend({
		tagName: "form",

		events: {
			"change input": "handleChange"
		},

		initialize: function() {
			this.$el.appendTo("body");

			var metrics = localStorage.getItem("metrics") === "true";
			this.model.set("metrics", metrics);

			var saveType = localStorage.getItem("saveType");
			var findType = localStorage.getItem("findType");

			this.model.on("change", this.render, this);
		},

		render: function() {
			var data = this.model.toJSON();
			this.$el.html(Templates.Options(data));

			return this;
		},

		handleChange: function(event) {
			var metrics = this.$("[name=metrics]").prop("checked");

			if (!metrics) {
				this.setAndStore("metrics", metrics);
			} else if (confirm("Enabling this will query Altmetric and Scopus for article-level metrics, and they will be able to see your search terms.")) {
				this.setAndStore("metrics", metrics);
			} else {
				event.preventDefault();
			}
		},

		setAndStore: function(name, metrics) {
			this.model.set(name, metrics);
			localStorage.setItem(name, metrics);
			window.location.reload(); // TODO: just update the page
		}
	}),

	Input: Backbone.View.extend({
		tagName: "form",

		attributes: {
			autocapitalize: "off"
		},

		events: {
			"change input[type=checkbox],select": "submitChangedForm",
			"click .clear": "clearInput",
			//"click input[name=term]": "selectInput"
		},

		initialize: function() {
			this.$el.appendTo("body");

			if (location.search) {
				this.parseQueryString().forEach(this.handleQueryPart, this);

				// only use "days" for "related" queries
				if (!this.model.get("relatedQuery")) {
					this.model.set("days", 0);
				}
			}

			this.model.on("change", this.render, this);
			this.render();
		},

		render: function() {
			var data = this.model.toJSON();
			this.$el.html(Templates.Input(data));
		},

		parseQueryString: function() {
			return location.search.substring(1).split("&").map(function(item) {
				return item.split("=").map(decodeURIComponent).map(function(text) {
					return text.replace(/\+/g, " ");
				});
			});
		},

		handleQueryPart: function(item) {
			var name = item[0];
			var value = item[1].replace(/\/$/, "");

			switch (name) {
				case "days":
					this.model.set("days", Number(value));
					return;

				case "term":
					this.model.set("relatedQuery", value.match(/^related:/));
					this.model.set("term", value);
					break;

				case "filter":
					var filters = this.model.get("filters");

					if (typeof filters[value] !== "undefined") {
						filters[value].enabled = true;
						this.model.set("filters", filters);
					}

					break;
			}
		},

		submitChangedForm: function() {
			this.$el.submit();
		},

		clearInput: function() {
			this.model.set("term", null);
			this.$("[name=term]").val("").focus();
		},

		selectInput: function(event) {
			$(event.currentTarget).select();
		}
	}),

	Articles: Backbone.View.extend({
		offset: 0,
		limit: 5,

		initialize: function() {
			this.$el.appendTo("body");
			this.collection.on("reset", this.reset, this);
			this.collection.on("add", this.add, this);
		},

		reset: function() {
			this.$el.empty();

			this.collection.each(this.add, this);

			var articles = $("article");

			if (articles.length === 1) {
				articles.addClass("expanded");
			}
		},

		add: function(article) {
			var view = new Views.Article({ model: article });
			this.$el.append(view.render().el);
		}
	}),

	Article: Backbone.View.extend({
		tagName: "article",

		attributes: {
			"vocab": "http://schema.org/",
			"typeof": "MedicalScholarlyArticle"
		},

		events: {
			"click a[data-action]": "action"
		},

		initialize: function() {
			this.links = new Views.Links({ model: this.model });
			this.metrics = new Views.Metrics({ collection: this.model.metrics });

			this.model.on("change", this.render, this);
		},

		render: function() {
			var data = this.model.toJSON();
			this.$el.html(Templates.Article(data));

			this.$el.find("[property=creators]").formatAuthors(5, "creator");

			this.$el.find("footer").prepend(this.links.$el);
			this.$el.find(".context").append(this.metrics.$el);

			return this;
		},

		action: function(event) {
			if (event.metaKey || event.ctrlKey) {
				return true;
			}

			var node = $(event.currentTarget);

			switch (node.data("action")) {
				case "show-abstract":
					var article = node.closest("article");

					if (article.hasClass("expanded")) {
						return true;
					}

					article.toggleClass("expanded");
				break;
			}

			return false;
		}
	}),

	Metrics: Backbone.View.extend({
		tagName: "span",
		className: "metrics",

		initialize: function() {
			this.collection.on("reset", this.reset, this);
			this.collection.on("add", this.add, this);
		},

		reset: function() {
			this.$el.empty();
			this.collection.each(this.add, this);
		},

		add: function(metric) {
			var view = new Views.Metric({ model: metric });
			view.render().$el.appendTo(this.$el);
		}
	}),

	Metric: Backbone.View.extend({
		tagName: "a",

		className: "metric",

		attributes: {
			target: "_blank"
		},

		initialize: function() {
			this.model.on("change", this.render, this);
		},

		render: function() {
			var data = this.model.toJSON();

			this.$el.attr("href", data.url).text(data.text);

			if (data.image) {
				$("<img/>", { src: "images/" + data.image }).prependTo(this.$el);
			}

			return this;
		}
	}),

	Links: Backbone.View.extend({
		className: "links",

		events: {
			"click .link": "handleClick",
		},

		initialize: function() {
			this.render();
		},

		render: function() {
			var data = this.model.toJSON();
			this.$el.html(Templates.Links(data));
		},

		showLinks: function(event) {
			var link = $(event.target);

		},

		handleClick: function(event) {
			var node = $(event.target);

			switch (node.attr("intent")) {
				case "save":
					var type = localStorage.getItem("saveType");
					if (type) {
						this.$("[rel=save][type='" + type + "']").click();
					} else {
						node.next(".link").click();
					}
					return;

				case "find":
					var type = localStorage.getItem("findType");

					if (type) {
						this.$("[rel=find][type='" + type + "']").click();
					} else {
						node.next(".link").click();
					}
					return;
			}

			if (node.data("dropdown-target")) {
				var target = this.$(node.data("dropdown-target"));

				if (target.is(":visible")) {
					target.hide();
				} else {
					event.stopPropagation();
					var offset = node.offset();
					var previous = node.prev(".link");

					target.show();
					target.offset({ top: offset.top + node.height(), left: offset.left - previous.width() });

					var clickListener = function() {
						$(".dropdown-list:visible").hide();
						$(document).off("click", clickListener);
					};

					$(document).on("click", clickListener);
				}

				return;
			}

			switch (node.attr("rel")) {
				case "related":
					if (event.metaKey || event.ctrlKey) {
						event.preventDefault();

						var pmid = this.model.get("pmid");

						var currentTerm = $.trim(app.models.query.get("term"));

						var term;
						if (app.models.query.get("relatedQuery")) {
							term = currentTerm + "," + pmid;
						} else {
							term = "related:" + pmid;
						}

						app.models.query.set("term", term);
						app.views.input.$el.submit();
					}

					return;

				case "save":
					event.preventDefault();
					event.stopPropagation();
					localStorage.setItem("saveType", node.attr("type"));
					window.open(node.attr("href"));
					return;

				case "find":
					event.preventDefault();
					event.stopPropagation();
					localStorage.setItem("findType", node.attr("type"));
					window.open(node.attr("href"));
					return;

				default:
					return;
			}
		}
	}),

	Pagination: Backbone.View.extend({
		tagName: "a",

		events: {
			"click": "fetchPage"
		},

        initialize: function() {
            _.bindAll(this);

            this
                .$el
                .attr("href", "#")
                .attr("rel", "next")
                .html("More ↓")
                .data("offset", 0)
                .hide()
                .appendTo("body");
        },

        start: function() {
            this.fetchPage();
            this.watchScrollPosition(this.fetchPage, 500, 500);
        },

        watchScrollPosition: function(callback, distance, interval) {
            var $window = $(window),
                $document = $(document);

            var checkScrollPosition = function() {
                var top = $document.height() - $window.height() - distance;

                if ($window.scrollTop() >= top) {
                    callback();
                }
            };

            setInterval(checkScrollPosition, interval);
        },

		setNextOffset: function() {
			var offset = app.views.articles.offset + app.views.articles.limit;
			this.$el.data("offset", offset).removeClass("loading").html("More ↓");
			this.$el.show();
		},

		fetchPage: function() {
			var node = this.$el;

			if (node.hasClass("loading")) {
				return false;
			}

			var spinner = $("<img/>", { src: "./images/spinner.gif"}).addClass("spinner");

			var count = app.models.query.get("count");
			var text;
			if (count) {
				var offset = app.views.articles.offset + app.views.articles.limit + 1;
				var nextOffset = Math.min(count, offset + app.views.articles.limit);
				var text = "Loading " + offset + " - " + nextOffset + " of " + this.numberWithCommas(count) + " articles";
			} else {
				text = "Searching";
			}
			node.addClass("loading").text(text).append(spinner);

			app.views.articles.offset = node.data("offset");

			app.collections.articles.fetch({ add: true, success: this.collectionUpdated });

            return false;
        },

        numberWithCommas: function(x) {
            return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        },

		noMoreItems: function() {
			this.$el.text("No more items");
		},

		collectionUpdated: function() {
			if (app.views.articles.offset == 0) {
				$(document).trigger("ZoteroItemUpdated");
			}
		}
	})
};<commit_msg>Don't open new windows when saving files<commit_after>var Views = {
	Options: Backbone.View.extend({
		tagName: "form",

		events: {
			"change input": "handleChange"
		},

		initialize: function() {
			this.$el.appendTo("body");

			var metrics = localStorage.getItem("metrics") === "true";
			this.model.set("metrics", metrics);

			var saveType = localStorage.getItem("saveType");
			var findType = localStorage.getItem("findType");

			this.model.on("change", this.render, this);
		},

		render: function() {
			var data = this.model.toJSON();
			this.$el.html(Templates.Options(data));

			return this;
		},

		handleChange: function(event) {
			var metrics = this.$("[name=metrics]").prop("checked");

			if (!metrics) {
				this.setAndStore("metrics", metrics);
			} else if (confirm("Enabling this will query Altmetric and Scopus for article-level metrics, and they will be able to see your search terms.")) {
				this.setAndStore("metrics", metrics);
			} else {
				event.preventDefault();
			}
		},

		setAndStore: function(name, metrics) {
			this.model.set(name, metrics);
			localStorage.setItem(name, metrics);
			window.location.reload(); // TODO: just update the page
		}
	}),

	Input: Backbone.View.extend({
		tagName: "form",

		attributes: {
			autocapitalize: "off"
		},

		events: {
			"change input[type=checkbox],select": "submitChangedForm",
			"click .clear": "clearInput",
			//"click input[name=term]": "selectInput"
		},

		initialize: function() {
			this.$el.appendTo("body");

			if (location.search) {
				this.parseQueryString().forEach(this.handleQueryPart, this);

				// only use "days" for "related" queries
				if (!this.model.get("relatedQuery")) {
					this.model.set("days", 0);
				}
			}

			this.model.on("change", this.render, this);
			this.render();
		},

		render: function() {
			var data = this.model.toJSON();
			this.$el.html(Templates.Input(data));
		},

		parseQueryString: function() {
			return location.search.substring(1).split("&").map(function(item) {
				return item.split("=").map(decodeURIComponent).map(function(text) {
					return text.replace(/\+/g, " ");
				});
			});
		},

		handleQueryPart: function(item) {
			var name = item[0];
			var value = item[1].replace(/\/$/, "");

			switch (name) {
				case "days":
					this.model.set("days", Number(value));
					return;

				case "term":
					this.model.set("relatedQuery", value.match(/^related:/));
					this.model.set("term", value);
					break;

				case "filter":
					var filters = this.model.get("filters");

					if (typeof filters[value] !== "undefined") {
						filters[value].enabled = true;
						this.model.set("filters", filters);
					}

					break;
			}
		},

		submitChangedForm: function() {
			this.$el.submit();
		},

		clearInput: function() {
			this.model.set("term", null);
			this.$("[name=term]").val("").focus();
		},

		selectInput: function(event) {
			$(event.currentTarget).select();
		}
	}),

	Articles: Backbone.View.extend({
		offset: 0,
		limit: 5,

		initialize: function() {
			this.$el.appendTo("body");
			this.collection.on("reset", this.reset, this);
			this.collection.on("add", this.add, this);
		},

		reset: function() {
			this.$el.empty();

			this.collection.each(this.add, this);

			var articles = $("article");

			if (articles.length === 1) {
				articles.addClass("expanded");
			}
		},

		add: function(article) {
			var view = new Views.Article({ model: article });
			this.$el.append(view.render().el);
		}
	}),

	Article: Backbone.View.extend({
		tagName: "article",

		attributes: {
			"vocab": "http://schema.org/",
			"typeof": "MedicalScholarlyArticle"
		},

		events: {
			"click a[data-action]": "action"
		},

		initialize: function() {
			this.links = new Views.Links({ model: this.model });
			this.metrics = new Views.Metrics({ collection: this.model.metrics });

			this.model.on("change", this.render, this);
		},

		render: function() {
			var data = this.model.toJSON();
			this.$el.html(Templates.Article(data));

			this.$el.find("[property=creators]").formatAuthors(5, "creator");

			this.$el.find("footer").prepend(this.links.$el);
			this.$el.find(".context").append(this.metrics.$el);

			return this;
		},

		action: function(event) {
			if (event.metaKey || event.ctrlKey) {
				return true;
			}

			var node = $(event.currentTarget);

			switch (node.data("action")) {
				case "show-abstract":
					var article = node.closest("article");

					if (article.hasClass("expanded")) {
						return true;
					}

					article.toggleClass("expanded");
				break;
			}

			return false;
		}
	}),

	Metrics: Backbone.View.extend({
		tagName: "span",
		className: "metrics",

		initialize: function() {
			this.collection.on("reset", this.reset, this);
			this.collection.on("add", this.add, this);
		},

		reset: function() {
			this.$el.empty();
			this.collection.each(this.add, this);
		},

		add: function(metric) {
			var view = new Views.Metric({ model: metric });
			view.render().$el.appendTo(this.$el);
		}
	}),

	Metric: Backbone.View.extend({
		tagName: "a",

		className: "metric",

		attributes: {
			target: "_blank"
		},

		initialize: function() {
			this.model.on("change", this.render, this);
		},

		render: function() {
			var data = this.model.toJSON();

			this.$el.attr("href", data.url).text(data.text);

			if (data.image) {
				$("<img/>", { src: "images/" + data.image }).prependTo(this.$el);
			}

			return this;
		}
	}),

	Links: Backbone.View.extend({
		className: "links",

		events: {
			"click .link": "handleClick",
		},

		initialize: function() {
			this.render();
		},

		render: function() {
			var data = this.model.toJSON();
			this.$el.html(Templates.Links(data));
		},

		showLinks: function(event) {
			var link = $(event.target);

		},

		handleClick: function(event) {
			var node = $(event.target);

			switch (node.attr("intent")) {
				case "save":
					var type = localStorage.getItem("saveType");
					if (type) {
						this.$("[rel=save][type='" + type + "']").click();
					} else {
						node.next(".link").click();
					}
					return;

				case "find":
					var type = localStorage.getItem("findType");

					if (type) {
						this.$("[rel=find][type='" + type + "']").click();
					} else {
						node.next(".link").click();
					}
					return;
			}

			if (node.data("dropdown-target")) {
				var target = this.$(node.data("dropdown-target"));

				if (target.is(":visible")) {
					target.hide();
				} else {
					event.stopPropagation();
					var offset = node.offset();
					var previous = node.prev(".link");

					target.show();
					target.offset({ top: offset.top + node.height(), left: offset.left - previous.width() });

					var clickListener = function() {
						$(".dropdown-list:visible").hide();
						$(document).off("click", clickListener);
					};

					$(document).on("click", clickListener);
				}

				return;
			}

			switch (node.attr("rel")) {
				case "related":
					if (event.metaKey || event.ctrlKey) {
						event.preventDefault();

						var pmid = this.model.get("pmid");

						var currentTerm = $.trim(app.models.query.get("term"));

						var term;
						if (app.models.query.get("relatedQuery")) {
							term = currentTerm + "," + pmid;
						} else {
							term = "related:" + pmid;
						}

						app.models.query.set("term", term);
						app.views.input.$el.submit();
					}

					return;

				case "save":
					event.preventDefault();
					event.stopPropagation();
					localStorage.setItem("saveType", node.attr("type"));
					if (node.attr("download")) {
						window.location = node.attr("href");
					} else {
						window.open(node.attr("href"));
					}
					return;

				case "find":
					event.preventDefault();
					event.stopPropagation();
					localStorage.setItem("findType", node.attr("type"));
					window.open(node.attr("href"));
					return;

				default:
					return;
			}
		}
	}),

	Pagination: Backbone.View.extend({
		tagName: "a",

		events: {
			"click": "fetchPage"
		},

        initialize: function() {
            _.bindAll(this);

            this
                .$el
                .attr("href", "#")
                .attr("rel", "next")
                .html("More ↓")
                .data("offset", 0)
                .hide()
                .appendTo("body");
        },

        start: function() {
            this.fetchPage();
            this.watchScrollPosition(this.fetchPage, 500, 500);
        },

        watchScrollPosition: function(callback, distance, interval) {
            var $window = $(window),
                $document = $(document);

            var checkScrollPosition = function() {
                var top = $document.height() - $window.height() - distance;

                if ($window.scrollTop() >= top) {
                    callback();
                }
            };

            setInterval(checkScrollPosition, interval);
        },

		setNextOffset: function() {
			var offset = app.views.articles.offset + app.views.articles.limit;
			this.$el.data("offset", offset).removeClass("loading").html("More ↓");
			this.$el.show();
		},

		fetchPage: function() {
			var node = this.$el;

			if (node.hasClass("loading")) {
				return false;
			}

			var spinner = $("<img/>", { src: "./images/spinner.gif"}).addClass("spinner");

			var count = app.models.query.get("count");
			var text;
			if (count) {
				var offset = app.views.articles.offset + app.views.articles.limit + 1;
				var nextOffset = Math.min(count, offset + app.views.articles.limit);
				var text = "Loading " + offset + " - " + nextOffset + " of " + this.numberWithCommas(count) + " articles";
			} else {
				text = "Searching";
			}
			node.addClass("loading").text(text).append(spinner);

			app.views.articles.offset = node.data("offset");

			app.collections.articles.fetch({ add: true, success: this.collectionUpdated });

            return false;
        },

        numberWithCommas: function(x) {
            return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        },

		noMoreItems: function() {
			this.$el.text("No more items");
		},

		collectionUpdated: function() {
			if (app.views.articles.offset == 0) {
				$(document).trigger("ZoteroItemUpdated");
			}
		}
	})
};<|endoftext|>


<commit_before>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
  kittyReady = true;
};
kittyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var kitty = {
  x: 0,
  y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
  e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;

  kitty.x = 32 + (Math.random() * (canvas.width - 64));
  kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
    ++kittyCaught;
    thenSwitch = nowSwitch;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (kittyReady) {
    ctx.drawImage(kittyImage, kitty.x, kitty.y);
  }

  ctx.fillStyle = "#EEE";
  ctx.font = "24px Ubuntu";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Kitties caught : " + kittyCaught, 32, 32);
  ctx.fillText("Lives : " + lives, 365, 32);
  ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64);
};

var gameOver = function () {
  document.write("Game Over. Kitties only have nine lives.");
};

var main = function () {
  now = Date.now();
  var delta = now - then;

  nowSwitch = Date.now();

  update(delta / 1000);

  countDown = nowSwitch - thenSwitch;

  if (countDown >= 5000) {
    lives--;
    if (lives ==  0) {
      gameOver();
    }
    thenSwitch = nowSwitch;
    reset();
  }

  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown;
var lives;

var start = function() {
  then = thenSwitch = nowSwitch = Date.now();
  reset();
  countDown = 0;
  lives = 9;
  kittyCaught = 0;
  //hero.x = (canvas.width / 2) - 16;
  //hero.y = (canvas.height / 2) - 16;
  main();
}

start();
<commit_msg>Update canvas.js<commit_after>// Get Canvas
var canvas = document.getElementById("canvas"),
  ctx = canvas.getContext("2d"),
  width = 512,
  height = 480;

canvas.tabIndex = 1;
canvas.width = width;
canvas.height = height;

// Background Image
var bgReady = false;
var bgImage = new Image();
bgImage.onload = function () {
  bgReady = true;
};
bgImage.src = "http://placekitten.com/512/480";
// Hero Image
var heroReady = false;
var heroImage = new Image();
heroImage.onload = function () {
  heroReady = true;
};
heroImage.src = "http://placekitten.com/32/32";

// Kitty Image
var kittyReady = false;
var kittyImage = new Image();
kittyImage.onload = function () {
  kittyReady = true;
};
kittyImage.src = "http://placekitten.com/30/32";

// Game objects
var hero = {
  speed: 256,
  x: 0,
  y: 0
};

var kitty = {
  x: 0,
  y: 0
};
var kittyCaught = 0;

// Handle keyboard controls
var keysDown = {};

addEventListener("keydown", function (e) {
  keysDown[e.keyCode] = true;
  e.preventDefault();
}, false);

addEventListener("keyup", function (e) {
  delete keysDown[e.keyCode];
}, false);

var reset = function () {
  hero.x = (canvas.width / 2) - 16;
  hero.y = (canvas.height / 2) - 16;

  kitty.x = 32 + (Math.random() * (canvas.width - 64));
  kitty.y = 32 + (Math.random() * (canvas.height - 64));
};

// Update game objects
var update = function (modifier) {
  if (38 in keysDown) {
    hero.y -= hero.speed * modifier;
  }
  if (40 in keysDown) {
    hero.y += hero.speed * modifier;
  }
  if (37 in keysDown) {
    hero.x -= hero.speed * modifier;
  }
  if (39 in keysDown) {
    hero.x += hero.speed * modifier;
  }

  // Stop from going off the page
  if (hero.x >= canvas.width - 32) {
    hero.x = canvas.width - 32;
  } else if (hero.x <= 0) {
    hero.x = 0;
  }

  if (hero.y >= canvas.height - 32) {
    hero.y = canvas.height - 32;
  } else if (hero.y <= 0) {
    hero.y = 0;
  }

  // Collision
  if (hero.x <= (kitty.x + 32) && kitty.x <= (hero.x + 32) && hero.y <= (kitty.y + 32) && kitty.y <= (hero.y + 32)) {
    ++kittyCaught;
    thenSwitch = nowSwitch;
    reset();
  }
};

// Render
var render = function () {
  if (bgReady) {
    ctx.drawImage(bgImage, 0, 0);
  }

  if (heroReady) {
    ctx.drawImage(heroImage, hero.x, hero.y);
  }

  if (kittyReady) {
    ctx.drawImage(kittyImage, kitty.x, kitty.y);
  }

  ctx.fillStyle = "#EEE";
  ctx.font = "24px Ubuntu";
  ctx.textAlign = "left";
  ctx.textBaseline = "top";
  ctx.fillText("Kitties caught : " + kittyCaught, 32, 32);
  ctx.fillText("Lives : " + lives, 365, 32);
  ctx.fillText("Timer : " + parseInt(countDown / 100), 32, 64);
};

var gameOver = function () {
  document.write("Game Over. Kitties only have nine lives.");
};

var main = function () {
  now = Date.now();
  var delta = now - then;

  nowSwitch = Date.now();

  update(delta / 1000);

  countDown = nowSwitch - thenSwitch;

  if (countDown >= 1200) {
    lives--;
    if (lives ==  0) {
      gameOver();
    }
    thenSwitch = nowSwitch;
    reset();
  }

  render();

  then = now;

  requestAnimationFrame(main);
};

var w = window;
requestAnimationFrame = w.requestAnimationFrame || w.webkitRequestAnimationFrame || w.msRequestAnimationFrame || w.mozRequestAnimationFrame;

// Initalized Variables
var then, thenSwitch, nowSwitch;
var countDown;
var lives;

var start = function() {
  then = thenSwitch = nowSwitch = Date.now();
  reset();
  countDown = 0;
  lives = 9;
  kittyCaught = 0;
  //hero.x = (canvas.width / 2) - 16;
  //hero.y = (canvas.height / 2) - 16;
  main();
}

start();
<|endoftext|>