<commit_before>(function () {

    "use strict";

    /**
     Quick-and-dirty utility for debugging XEO {{#crossLink "Scene"}}Scenes{{/crossLink}}.

     The utility has fluent builder API that lets you create and update simple objects to help you
     debug or demo things on XEO.

     The utility does not clean up any components it created with your {{#crossLink "Scene"}}Scenes{{/crossLink}}.

     ## Example

     Drawing a red triangle:

     ```` javascript
     XEO.debug
     .id("myTriangle")  // Supply an ID when you want to update the line if already existing
     .color([1,0,0])
     .pos([-10, -10, 0])
     .pos([10, -10, 0])
     .pos([0, -4, 0])
     .line();

     ````

     Updating the triangle to change it's color and position:

     ```` javascript
     XEO.debug
     .id("myTriangle")
     .pos([-15, -15, 0])
     .pos([15, -15, 0])
     .pos([0, 5, 0])
     .color([0,1,0])
     .line();

     ````

     Creating a label at a Given World position:

     ```` javascript
     XEO.debug
     .pos([-10, 34, 2])
     .text("Check this out!")
     .label();

     ````
     @class XEO.debug
     @static
     @author xeolabs / http://xeolabs.com/
     */
    XEO.debug = new (function () {

        // Converts XEO color to CSS
        function cssColor(color) {
            return "rgb(" +
                Math.floor(color[0] * 255) + "," +
                Math.floor(color[1] * 255) + "," +
                Math.floor(color[2] * 255) + ")";
        }

        var scene;
        var id;
        var color;
        var fillColor;
        var opacity;
        var lineWidth;
        var diffuse;
        var pos;
        var posi;
        var text;
        var radius;

        this.scene = function (_scene) {
            scene = _scene;
            return this;
        };

        function getScene() {
            return scene || XEO.scene;
        }

        this.id = function (value) {
            id = value;
            return this;
        };

        this.color = function (value) {
            color = value;
            return this;
        };

        this.fillColor = function (value) {
            fillColor = value;
            return this;
        };

        this.lineWidth = function (value) {
            lineWidth = value;
            return this;
        };

        this.pos = function (value) {
            pos[posi++] = value;
            return this;
        };

        this.text = function (value) {
            text = value;
            return this;
        };

        this.radius = function (value) {
            radius = value;
            return this;
        };

        this._reset = function () {
            scene = undefined;
            color = [1, 0.4, 0.4];
            fillColor = [0, 0, 0];
            diffuse = [1, 0.4, 0.4];
            opacity = 1.0;
            lineWidth = 2.0;
            id = undefined;
            pos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            posi = 0;
            text = "";
            radius = 1.0;
        };

        this.line = function () {

            if (posi < 2) {
                console.error("[XEO.debug.line] Not enough calls to XEO.debug.pos() for XEO.debug.line() - need at least two.");
                return;
            }

            var _id = id || "__debugLine";

            var positions = [];
            var indices = [];

            for (var i = 0; i < posi; i++) {
                positions.push(pos[i][0]);
                positions.push(pos[i][1]);
                positions.push(pos[i][2]);

                indices.push(i);
                if (i < (posi - 1)) {
                    indices.push(i + 1);
                }
            }

            var object = getScene().objects[_id];

            if (!object) {
                new XEO.GameObject(getScene(), {
                    id: _id,
                    geometry: new XEO.Geometry({
                        primitive: "lines",
                        positions: positions,
                        indices: indices
                    }),
                    material: new XEO.PhongMaterial({
                        emissive: color,
                        opacity: opacity,
                        lineWidth: lineWidth
                    }),
                    modes: new XEO.Modes({  // This GameObject should not be pickable
                        picking: false,
                        transparent: opacity < 1.0
                    })
                });
            } else {
                object.geometry.positions = positions;
                object.geometry.indices = indices;
                object.material.emissive = color;
                object.material.opacity = opacity;
                object.modes.transparency = opacity < 1.0;
                object.material.lineWidth = lineWidth;
            }

            this._reset();

            return this;
        };

        /**
         * Creates or updates a floating CSS label
         *
         * @returns {XEO.debug}
         */
        this.label = function () {

            var _id = id || "__debugLabel";

            var object = getScene().objects[_id];

            if (!object) {

                object = new XEO.GameObject(getScene(), {
                    id: _id,
                    transform: new XEO.Translate({
                        xyz: pos[0]
                    }),
                    geometry: new XEO.SphereGeometry({
                        radius: 0.001
                    }),
                    modes: new XEO.Modes({  // This GameObject should not be pickable
                        picking: false,
                        transparent: true
                    }),
                    material: new XEO.PhongMaterial({ // Hides the sphere while still rendering it
                        opacity: 0
                    })
                });

                var body = document.getElementsByTagName("body")[0];

                var boxDiv = document.createElement('div');
                boxDiv.innerText = text;
                var style = boxDiv.style;
                style.color = cssColor(color);
                style.position = "absolute";
                style.padding = "10px";
                style.margin = "0";
                style.background = fillColor ? cssColor(fillColor) : "black";
                style.opacity = opacity;
                style.border = lineWidth + "px solid " + cssColor(color);
                style["z-index"] = "1000";
                style.width = "auto";
                style.height = "auto";
                style["border-radius"] = "5px";
                style.font = "bold 12px arial,serif";
                body.appendChild(boxDiv);

                var pointDiv = document.createElement('div');
                style = pointDiv.style;
                style.color = "white";
                style.background = "white";
                style.position = "absolute";
                style.padding = "3px";
                style.margin = "0";
                style.background = "white";
                style.opacity = 1.0;
                style.border = lineWidth + "px solid " + cssColor(color);
                style.width = "2px";
                style.height = "2px";
                style["border-radius"] = "5px";
                style["z-index"] = "1001";
                body.appendChild(pointDiv);

                object.canvasBoundary.on("updated",
                    function () {

                        var center = object.canvasBoundary.center;

                        boxDiv.style.left = center[0] + "px";
                        boxDiv.style.top = center[1] + "px";

                        pointDiv.style.left = center[0] - 2 + "px";
                        pointDiv.style.top = center[1] - 2 + "px";

                        var zIndex = 10000 + Math.floor(object.viewBoundary.center[2]);

                        boxDiv.style["z-index"] = zIndex;
                        pointDiv.style["z-index"] = zIndex + 1;
                    });

                object.boxDiv = boxDiv; // Dirty, but all is encapsulated by the debug utility
                object.pointDiv = boxDiv;

            } else {
                object.transform.xyz = pos[0];

                object.boxDiv.innerText = text;
                object.boxDiv.style.opacity = opacity;
                object.boxDiv.style.background = cssColor(fillColor);
                object.boxDiv.style.color = cssColor(color);

                var border = lineWidth + "px solid " + cssColor(color);
                object.boxDiv.style.border = border;
                object.pointDiv.style.border = border;
            }

            this._reset();

            return this;
        };

        this._reset();
    })();

})();
<commit_msg>Debug utility tweaks<commit_after>(function () {

    "use strict";

    /**
     Quick-and-dirty utility for debugging XEO {{#crossLink "Scene"}}Scenes{{/crossLink}}.

     The utility has fluent builder API that lets you create and update simple objects to help you
     debug or demo things on XEO.

     The utility does not clean up any components it created with your {{#crossLink "Scene"}}Scenes{{/crossLink}}.

     ## Example

     Drawing a red triangle:

     ```` javascript
     XEO.debug
     .id("myTriangle")  // Supply an ID when you want to update the line if already existing
     .color([1,0,0])
     .pos([-10, -10, 0])
     .pos([10, -10, 0])
     .pos([0, -4, 0])
     .line();

     ````

     Updating the triangle to change it's color and position:

     ```` javascript
     XEO.debug
     .id("myTriangle")
     .pos([-15, -15, 0])
     .pos([15, -15, 0])
     .pos([0, 5, 0])
     .color([0,1,0])
     .line();

     ````

     Creating a label at a Given World position:

     ```` javascript
     XEO.debug
     .pos([-10, 34, 2])
     .text("Check this out!")
     .label();

     ````
     @class XEO.debug
     @static
     @author xeolabs / http://xeolabs.com/
     */
    XEO.debug = new (function () {

        // Converts XEO color to CSS
        function cssColor(color) {
            return "rgb(" +
                Math.floor(color[0] * 255) + "," +
                Math.floor(color[1] * 255) + "," +
                Math.floor(color[2] * 255) + ")";
        }

        var scene;
        var id;
        var color;
        var fillColor;
        var opacity;
        var lineWidth;
        var diffuse;
        var pos;
        var posi;
        var text;
        var radius;

        this.scene = function (_scene) {
            scene = _scene;
            return this;
        };

        function getScene() {
            return scene || XEO.scene;
        }

        this.id = function (value) {
            id = value;
            return this;
        };

        this.color = function (value) {
            color = value;
            return this;
        };

        this.fillColor = function (value) {
            fillColor = value;
            return this;
        };

        this.lineWidth = function (value) {
            lineWidth = value;
            return this;
        };

        this.pos = function (value) {
            pos[posi++] = value;
            return this;
        };

        this.text = function (value) {
            text = value;
            return this;
        };

        this.radius = function (value) {
            radius = value;
            return this;
        };

        this._reset = function () {
            scene = undefined;
            color = [1, 0.4, 0.4];
            fillColor = [0, 0, 0];
            diffuse = [1, 0.4, 0.4];
            opacity = 1.0;
            lineWidth = 2.0;
            id = undefined;
            pos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            posi = 0;
            text = "";
            radius = 1.0;
        };

        this.line = function () {

            if (posi < 2) {
                console.error("[XEO.debug.line] Not enough calls to XEO.debug.pos() for XEO.debug.line() - need at least two.");
                return;
            }

            var _id = id || "__debugLine";

            var positions = [];
            var indices = [];

            for (var i = 0; i < posi; i++) {
                positions.push(pos[i][0]);
                positions.push(pos[i][1]);
                positions.push(pos[i][2]);

                indices.push(i);
                if (i < (posi - 1)) {
                    indices.push(i + 1);
                }
            }

            var object = getScene().objects[_id];

            if (!object) {
                new XEO.GameObject(getScene(), {
                    id: _id,
                    geometry: new XEO.Geometry({
                        primitive: "lines",
                        positions: positions,
                        indices: indices
                    }),
                    material: new XEO.PhongMaterial({
                        emissive: color,
                        opacity: opacity,
                        lineWidth: lineWidth
                    }),
                    modes: new XEO.Modes({  // This GameObject should not be pickable
                        picking: false,
                        transparent: opacity < 1.0
                    })
                });
            } else {
                object.geometry.positions = positions;
                object.geometry.indices = indices;
                object.material.emissive = color;
                object.material.opacity = opacity;
                object.modes.transparency = opacity < 1.0;
                object.material.lineWidth = lineWidth;
            }

            this._reset();

            return this;
        };

        /**
         * Creates or updates a floating CSS label
         *
         * @returns {XEO.debug}
         */
        this.label = function () {

            var _id = id || "__debugLabel";

            var object = getScene().objects[_id];

            if (!object) {

                object = new XEO.GameObject(getScene(), {
                    id: _id,
                    transform: new XEO.Translate({
                        xyz: pos[0]
                    }),
                    geometry: new XEO.SphereGeometry({
                        radius: 0.1
                    }),
                    modes: new XEO.Modes({  // This GameObject should not be pickable
                        picking: false,
                        transparent: true
                    }),
                    material: new XEO.PhongMaterial({ // Hides the sphere while still rendering it
                        opacity: 0
                    })
                });

                var body = document.getElementsByTagName("body")[0];

                var boxDiv = document.createElement('div');
                boxDiv.innerText = text;
                var style = boxDiv.style;
                style.color = cssColor(color);
                style.position = "absolute";
                style.padding = "10px";
                style.margin = "0";
                style.background = fillColor ? cssColor(fillColor) : "black";
                style.opacity = opacity;
                style.border = lineWidth + "px solid " + cssColor(color);
                style["z-index"] = "1000";
                style.width = "auto";
                style.height = "auto";
                style["border-radius"] = "5px";
                style.font = "bold 12px arial,serif";
                body.appendChild(boxDiv);

                var pointDiv = document.createElement('div');
                style = pointDiv.style;
                style.color = "white";
                style.background = "white";
                style.position = "absolute";
                style.padding = "3px";
                style.margin = "0";
                style.background = "white";
                style.opacity = 1.0;
                style.border = lineWidth + "px solid " + cssColor(color);
                style.width = "2px";
                style.height = "2px";
                style["border-radius"] = "5px";
                style["z-index"] = "1001";
                body.appendChild(pointDiv);

                object.canvasBoundary.on("updated",
                    function () {

                        var center = object.canvasBoundary.center;

                        boxDiv.style.left = center[0] - 3 + "px";
                        boxDiv.style.top = center[1] - 3 + "px";

                        pointDiv.style.left = center[0] - 5 + "px";
                        pointDiv.style.top = center[1] - 5 + "px";

                        var zIndex = 10000 + Math.floor(object.viewBoundary.center[2]);

                        boxDiv.style["z-index"] = zIndex;
                        pointDiv.style["z-index"] = zIndex + 1;
                    });

                object.boxDiv = boxDiv; // Dirty, but all is encapsulated by the debug utility
                object.pointDiv = boxDiv;

            } else {
                object.transform.xyz = pos[0];

                object.boxDiv.innerText = text;
                object.boxDiv.style.opacity = opacity;
                object.boxDiv.style.background = cssColor(fillColor);
                object.boxDiv.style.color = cssColor(color);

                var border = lineWidth + "px solid " + cssColor(color);
                object.boxDiv.style.border = border;
                object.pointDiv.style.border = border;
            }

            this._reset();

            return this;
        };

        this.label3d = function () {

            var _id = id || "__debugLabel3d";

            var object = getScene().objects[_id];

            if (!object) {

                object = new XEO.GameObject(getScene(), {
                    id: _id,
                    transform: new XEO.Translate({
                        xyz: pos[0]
                    }),
                    geometry: new XEO.VectorTextGeometry({
                        text: text
                    }),
                    modes: new XEO.Modes({  // This GameObject should not be pickable
                        picking: false,
                        transparent: true
                    }),
                    material: new XEO.PhongMaterial({ // Hides the sphere while still rendering it
                        emissive: color,
                        opacity: opacity,
                        lineWidth: lineWidth
                    }),
                    billboard: new XEO.Billboard({
                        spherical: true
                    })
                });

            } else {
                object.transform.xyz = pos[0];
                object.geometry.text = text;
                object.material.emissive = color;
                object.material.opacity = opacity;
                object.modes.transparency = opacity < 1.0;
                object.material.lineWidth = lineWidth;
            }

            this._reset();

            return this;
        };

        this._reset();
    })();

})();
<|endoftext|>


<commit_before>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var igv = (function (igv) {

    igv.ga4gh = {

        providerCurrent: undefined,
        datasetCurrent: undefined,

        providerChangeHandler: undefined,
        datasetChangeHandler: undefined,

        providers: [
            {
                name: "Google",
                url: "https://www.googleapis.com/genomics/v1beta2",
                supportsPartialResponse: true,
                datasets: [
                    {name: "Platinum Genomes", id: "3049512673186936334"},
                    {name: "1000 Genomes", id: "10473108253681171589"},
                    {name: "Simons Foundation", id: "461916304629"},
                    {name: "DREAM SMC Challenge", id: "337315832689"},
                    {name: "PGP", id: "383928317087"}
                ]
            }
        ],

        initialize: function () {

            var providerElement = $("#provider"),
                datasetElement = $("#dataset"),
                inputSearchElement = $("#setName"),
            /*containerModal = $("#setSearch"),*/
            containerModal = $("#setSearch").find(".modal-dialog");

            igv.ga4gh.providers.forEach(function (p, index, ps) {

                var optionElement = $('<option>');
                optionElement.val(index);
                optionElement.text(p.name);
                providerElement.append(optionElement);
            });

            // provider
            igv.ga4gh.providerChangeHandler = function () {

                var optionElement = $("#provider option:selected").first();

                igv.ga4gh.providerCurrent = igv.ga4gh.providers[parseInt(optionElement.val())];

                datasetElement.empty();
                igv.ga4gh.providerCurrent.datasets.forEach(function (d, index, ds) {

                    var optionElement = $('<option>');
                    optionElement.val(index);
                    optionElement.text(d.name);
                    datasetElement.append(optionElement);

                });

                igv.ga4gh.datasetChangeHandler()
            };

            providerElement.change(igv.ga4gh.providerChangeHandler);

            // dataset
            igv.ga4gh.datasetChangeHandler = function () {

                var optionElement = $("#dataset option:selected").first(),
                    searchResultsElement = $("#searchPaneREADSET").find("ul.list-group");

                igv.ga4gh.datasetCurrent = igv.ga4gh.providerCurrent.datasets[parseInt(optionElement.val())];

                igv.startSpinnerAtParentElement(containerModal[ 0 ]);

                igv.ga4ghSearchReadAndCallSets({
                    url: igv.ga4gh.providerCurrent.url,
                    datasetId: igv.ga4gh.datasetCurrent.id,
                    success: function (results) {

                        igv.stopSpinnerAtParentElement(containerModal[ 0 ]);

                        searchResultsElement.empty();

                        results.forEach(function (result) {

                            var rowElement = $('
');
                            rowElement.text(result.name);

                            searchResultsElement.append(rowElement);

                            rowElement.click(function () {

                                if (result.callSetId && result.variantSetIds) {
                                    result.variantSetIds.forEach(function (variantSetId) {
                                        igv.browser.loadTrack({
                                            sourceType: 'ga4gh',
                                            type: 'variant',
                                            url: 'https://www.googleapis.com/genomics/v1beta2',
                                            variantSetId: variantSetId,
                                            callSetIds: [result.callSetId],
                                            name: result.name + " variants",
                                            datasetId: result.datasetId
                                        })
                                    })
                                }

                                if (result.readGroupSetId) {
                                    igv.browser.loadTrack(
                                        {
                                            sourceType: 'ga4gh',
                                            type: 'alignment',
                                            url: igv.ga4gh.providerCurrent.url,
                                            readGroupSetIds: result.readGroupSetId,
                                            label: result.name + " alignments",
                                            datasetId: result.datasetId
                                        }
                                    );
                                }

                                $("#setSearch").modal("hide");

                            });

                        });

                    }
                });

            };

            datasetElement.change(igv.ga4gh.datasetChangeHandler);

            inputSearchElement.keyup(function () {

                if ("" === $(this).val()) {

                    igv.ga4gh.filterTrackList("reset");
                } else {

                    igv.ga4gh.filterTrackList($(this).val());

                }

            });

            containerModal[ 0 ].appendChild( igv.spinner("64px") );

            // trigger handlers to pre-populate selects
            igv.ga4gh.providerChangeHandler();

        },

        filterTrackList: function (searchTerm) {

            var st = searchTerm.toLowerCase(),
                rows = $("#searchPaneREADSET").find("ul.list-group li");

            rows.each(function () {

                var term = $(this).text().toLowerCase();

                if ("reset" === st) {

                    $(this).show();
                } else {

                    if (term.indexOf(st) > -1) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }

                }

            });

        }

    };

    return igv;

})(igv || {});<commit_msg>Tweak google demo<commit_after>/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Broad Institute
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

var igv = (function (igv) {

    var trackOrder = 10;

    igv.ga4gh = {

        providerCurrent: undefined,
        datasetCurrent: undefined,

        providerChangeHandler: undefined,
        datasetChangeHandler: undefined,

        providers: [
            {
                name: "Google",
                url: "https://www.googleapis.com/genomics/v1beta2",
                supportsPartialResponse: true,
                datasets: [
                    {name: "Platinum Genomes", id: "3049512673186936334"},
                    {name: "1000 Genomes", id: "10473108253681171589"},
                    {name: "Simons Foundation", id: "461916304629"},
                    {name: "DREAM SMC Challenge", id: "337315832689"},
                    {name: "PGP", id: "383928317087"}
                ]
            }
        ],

        initialize: function () {

            var providerElement = $("#provider"),
                datasetElement = $("#dataset"),
                inputSearchElement = $("#setName"),
            /*containerModal = $("#setSearch"),*/
            containerModal = $("#setSearch").find(".modal-dialog");

            igv.ga4gh.providers.forEach(function (p, index, ps) {

                var optionElement = $('<option>');
                optionElement.val(index);
                optionElement.text(p.name);
                providerElement.append(optionElement);
            });

            // provider
            igv.ga4gh.providerChangeHandler = function () {

                var optionElement = $("#provider option:selected").first();

                igv.ga4gh.providerCurrent = igv.ga4gh.providers[parseInt(optionElement.val())];

                datasetElement.empty();
                igv.ga4gh.providerCurrent.datasets.forEach(function (d, index, ds) {

                    var optionElement = $('<option>');
                    optionElement.val(index);
                    optionElement.text(d.name);
                    datasetElement.append(optionElement);

                });

                igv.ga4gh.datasetChangeHandler()
            };

            providerElement.change(igv.ga4gh.providerChangeHandler);

            // dataset
            igv.ga4gh.datasetChangeHandler = function () {

                var optionElement = $("#dataset option:selected").first(),
                    searchResultsElement = $("#searchPaneREADSET").find("ul.list-group");

                igv.ga4gh.datasetCurrent = igv.ga4gh.providerCurrent.datasets[parseInt(optionElement.val())];

                igv.startSpinnerAtParentElement(containerModal[ 0 ]);

                igv.ga4ghSearchReadAndCallSets({
                    url: igv.ga4gh.providerCurrent.url,
                    datasetId: igv.ga4gh.datasetCurrent.id,
                    success: function (results) {

                        igv.stopSpinnerAtParentElement(containerModal[ 0 ]);

                        searchResultsElement.empty();

                        results.forEach(function (result) {

                            var rowElement = $('
');
                            rowElement.text(result.name);

                            searchResultsElement.append(rowElement);

                            rowElement.click(function () {

                                if (result.callSetId && result.variantSetIds) {
                                    result.variantSetIds.forEach(function (variantSetId) {
                                        igv.browser.loadTrack({
                                            sourceType: 'ga4gh',
                                            type: 'variant',
                                            url: 'https://www.googleapis.com/genomics/v1beta2',
                                            variantSetId: variantSetId,
                                            callSetIds: [result.callSetId],
                                            name: result.name + " variants",
                                            order: trackOrder++,
                                            datasetId: result.datasetId
                                        })
                                    })
                                }

                                if (result.readGroupSetId) {
                                    igv.browser.loadTrack(
                                        {
                                            sourceType: 'ga4gh',
                                            type: 'alignment',
                                            url: igv.ga4gh.providerCurrent.url,
                                            readGroupSetIds: result.readGroupSetId,
                                            label: result.name + " alignments",
                                            order: trackOrder++,
                                            datasetId: result.datasetId
                                        }
                                    );
                                }

                                $("#setSearch").modal("hide");

                            });

                        });

                    }
                });

            };

            datasetElement.change(igv.ga4gh.datasetChangeHandler);

            inputSearchElement.keyup(function () {

                if ("" === $(this).val()) {

                    igv.ga4gh.filterTrackList("reset");
                } else {

                    igv.ga4gh.filterTrackList($(this).val());

                }

            });

            containerModal[ 0 ].appendChild( igv.spinner("64px") );

            // trigger handlers to pre-populate selects
            igv.ga4gh.providerChangeHandler();

        },

        filterTrackList: function (searchTerm) {

            var st = searchTerm.toLowerCase(),
                rows = $("#searchPaneREADSET").find("ul.list-group li");

            rows.each(function () {

                var term = $(this).text().toLowerCase();

                if ("reset" === st) {

                    $(this).show();
                } else {

                    if (term.indexOf(st) > -1) {
                        $(this).show();
                    } else {
                        $(this).hide();
                    }

                }

            });

        }

    };

    return igv;

})(igv || {});<|endoftext|>


<commit_before>/*
 * 不枝雀
 * 2017-3-18 16:16:20
 */
//main
var body = document.body;
var onbacks = [];
var window_history = window.history;
var window_history_length = window_history.length;
var sessionSavedHashKey = "__zimoli_session_init_hash" + location.pathname;
var sessionInitHash = sessionStorage.getItem(sessionSavedHashKey);
var hostoryStorage = sessionStorage;
var pagehash_reg = /#([\/\w\:@\.\_\(\)\+\-\*\$@!~_'\?,&~%]+)$/;
var locationInitHash = location.hash;
var hashchangecount = 0;
var isFirstTimeLoad = sessionInitHash === null;
var isSimpleRefresh = sessionInitHash === locationInitHash;
var isWithHashLoad = !!location.hash;
var preventNextHashChange = false;
window_history.scrollRestoration = 'manual'
if (isWithHashLoad && !isSimpleRefresh) {
    //带hash加载，吃掉hash
    location.replace("#");
}

if (/MSIE\s*[2-7]/.test(navigator.userAgent)) {
    window.onhistorychange = function (url) {
        hashchangecount++;
        // 如果是返回事件，一定不是第一次改变hash
        // 这里刚好可以屏蔽首次手动改变url可能产生的hashchange事件
        if (hashchangecount < 2) return;
        if (preventNextHashChange) return preventNextHashChange = false, window_history.go(-1);
        if (preventNextHashChange === void 0 ? onback && onback() === true : preventNextHashChange = void 0) { }
    };
    onselectstart(body, function (e) {
        return e.preventDefault();
    });
    var frame = createElement("iframe");
    css(frame, "display:none");
    appendChild(body, frame);
    var doc = frame.contentWindow.document;
    var backman = function (isloaded) {
        doc.open();
        doc.write(isloaded !== false ? "" : "<script>result=parent.onhistorychange();onload=function(){history.forward()}</script>");
        doc.close();
    };
    backman(false);
    backman();
} else {
    onhashchange(window, function (event) {
        hashchangecount++;
        // 如果是返回事件，一定不是第一次改变hash
        // 这里刚好可以屏蔽首次手动改变url可能产生的hashchange事件
        var targetHash = location.hash;
        sessionStorage.setItem(sessionSavedHashKey, targetHash);
        if (pagehash_reg.test(targetHash)) {
            var currentHash = getCurrentHash();
            if (currentHash && currentHash === targetHash) return;
            var targetHashIndex = targetHash.indexOf("#" + current_history);
            if (targetHashIndex < 0) return;
            var targetpath = targetHash.slice(targetHashIndex + current_history.length + 1);
            go(targetpath);
            return;
        }
        if (preventNextHashChange) return preventNextHashChange = false;
        event.preventDefault();
        onback();
    });
}
// body
css("html", {
    height: "100%",
    fontFamily: `"SF Pro SC","SF Pro Text","SF Pro Icons","PingFang SC","Helvetica Neue","Helvetica","Arial",sans-serif`,
    backgroundColor: "#f2f4f9"
});
css("body", {
    border: "none",
    margin: "0",
    padding: "0",
    height: "100%",
    overflow: "hidden",
});
var location_pathname = location.pathname;
var _zimoli_params_key = `_zimoli_parameters:${location_pathname}#`;
var _zimoli_state_prefix = `_zimoli_page_state:${location_pathname}#`;

function getReverseStyle(style) {
    if (!(style instanceof Object)) {
        style = parseKV(style, ";", ":");
    }
    var dest = {};
    var replacer = function (m, d, t) {
        if (t) return -d + t;
        return +d ? 1 / d : m;
    };
    //如要是对放大系数进行求倒，对位移进行反向
    for (var k in style) {
        if (/transform|left|top|right|bottom|margin/i.test(k)) {
            dest[k] = String(style[k]).replace(/(\-?\d*\.?\d+)(deg|p[xt]|r?em|[cm]m|%|)/ig, replacer);
        } else {
            dest[k] = style[k];
        }
    }
    return dest;
}

function go(url, args, history_name, oldpagepath) {
    if (!history_name)
        history_name = current_history;
    if (isNumber(url)) {
        if (isString(history_name)) {
            var _history = history[history_name] || [];
            url = _history[url < 1 ? _history.length + url - 1 : url];
            oldpagepath = _history[_history.length - 1];
        }
    }
    if (!url) return true;
    var stringified_args = JSON.stringify({ data: args, from: oldpagepath });
    if (stringified_args.length === 2) hostoryStorage.removeItem(_zimoli_params_key + url);
    else hostoryStorage.setItem(_zimoli_params_key + url, stringified_args);
    if (!page_generators[url]) {
        return zimoli(url, args, history_name, oldpagepath);
    }
    var { pg, with: _with_elements, state, onback: _pageback_listener, prepares } = page_generators[url];
    _with_elements = [].concat(_with_elements);
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.onback = function (handler) {
        _pageback_listener = handler;
    };
    if (undefined === args || null === args) args = {};
    var _page = pg.call(state, args, oldpagepath);
    if (_page) {
        if (pg.className) _page.className = pg.className;
        _page.with = _with_elements;
        if (args.initialStyle) _page.initialStyle = args.initialStyle;
        if (args.holdupStyle) _page.holdupStyle = args.holdupStyle;
        if (_page.initialStyle && !_page.holdupStyle) {
            _page.holdupStyle = getReverseStyle(_page.initialStyle);
            _page.backupStyle = _page.initialStyle;
        }
        _page.onback = _pageback_listener;
    }
    var isDestroy = pushstate(url, history_name, oldpagepath);
    if (isNode(history_name)) {
        if (history_name.activate === url && history_name.activateNode === _page) return;
        else remove(history_name.activateNode);
        history_name.activate = url;
        history_name.activateNode = _page;
    }
    addGlobal(_page, history_name, isDestroy);
    prepares.forEach(function (url) {
        if (isNumber(url)) {
            url = _history[url < 1 ? _history.length + url - 1 : url];
        }
        if (isString(url)) prepare(url);
    });
    return _page;
}
var page_generators = {};
/**
 * 加载一个页面到document.body
 * 如果args是一个字符串，那么当下次指定一个相同的字符串时，此对象被新对象代替
 * 如果args是bool值true，那么当执行history.back()时，此对象被清除
 */
function prepare(pagepath, ok) {
    if (page_generators[pagepath]) return isFunction(ok) && ok();
    var _zimoli_state_key = _zimoli_state_prefix + pagepath;
    var state = function state(condition, setAsAdditional = condition !== null) {
        var state_string = hostoryStorage.getItem(_zimoli_state_key);
        var state_object;
        if (state_string) {
            try {
                state_object = JSON.parse(state_string);
            } catch (e) {
                state_object = {};
            }
        } else {
            state_object = {}
        }
        if (condition instanceof Object && setAsAdditional) {
            if (!(state_object instanceof Object)) {
                state_object = {
                    toString() {
                        return String(this.valueOf());
                    },
                    valueOf: new Function(`return ${state_object}`),
                };
            }
            state_object = extend(state_object, condition);
        } else if (arguments.length) {
            state_object = condition;
        }
        if (arguments.length) {
            hostoryStorage.setItem(_zimoli_state_key, JSON.stringify(state_object) || null);
        }
        return state_object;
    };
    state.state = state;
    var _with_elements = [];
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.path = function (url) {
        if (isString(url) && /^[^\\\/]/.test(url)) {
            url = pagepath.replace(/[^\/]*$/, url);
        }
        return url;
    }
    state.go = function (url, args, _history_name) {
        // if (arguments.length === 1 && isFinite(url)) return window_history.go(url | 0);
        return go(state.path(url), args, _history_name, isString(history_name) ? pagepath : oldpagepath);
    };
    var prepares = [];
    state.prepare = state.go.prepare = function (urls) {
        prepares.push.apply(prepares, [].concat(urls).map(state.path));
    };
    var _pageback_listener = [];
    state.onback = state.onrelease = state.ondestroy = function (handler) {
        //只能在page上使用
        _pageback_listener = handler;
    };
    state.titlebar = function () {
        var realTitleBar = titlebar.apply(null, arguments);
        state.with(realTitleBar);
        return realTitleBar;
    };
    return init(pagepath, function (pg) {
        if (!pg) return;
        page_generators[pagepath] = {
            pg,
            state,
            with: _with_elements,
            onback: _pageback_listener,
            prepares
        };
        return isFunction(ok) && ok();
    }, state);
}

function zimoli(pagepath, args, history_name, oldpagepath) {
    if (arguments.length === 0) {
        history_name = current_history;
        var _history = history[history_name] || [];
        pagepath = _history[_history.length - 1] || "/main";
        try {
            var saveddata = JSON.parse(hostoryStorage.getItem(_zimoli_params_key + pagepath)) || {};
        } catch (e) {
            var saveddata = {};
        }
        var { data, from } = saveddata;
        args = data;
        oldpagepath = from;
    }
    if (page_generators[pagepath]) return go(pagepath, args, history_name, oldpagepath);
    return prepare(pagepath, function () {
        return go(pagepath, args, history_name, oldpagepath);
    });
}
var global = {};
var history = {};
var current_history = "";
history[current_history] = [];
var history_session_object_key = `_zimoli_history_key:${location_pathname}`;
try {
    history = JSON.parse(hostoryStorage.getItem(history_session_object_key)) || history;
} catch (e) {
}
var pushstate = function (path_name, history_name, oldpagepath) {
    var isDestroy = false;
    if (!history_name) {
        history_name = current_history;
    }
    if (!isString(history_name)) return;
    if (!history[history_name]) {
        history[history_name] = [path_name];
    } else {
        var _history = history[history_name];
        if (_history.indexOf(oldpagepath) < 0) {
            _history.splice(_history[0] === ":empty", _history.length);
            isDestroy = true;
        }
        for (var cx = 0, dx = _history.length; cx < dx; cx++) {
            if (_history[cx] === path_name) {
                _history.splice(cx, dx - cx);
                isDestroy = true;
                break;
            }
        }
        _history.push(path_name);
        if (_history.length) fixurl();
    }
    hostoryStorage.setItem(history_session_object_key, JSON.stringify(history) || null);
    return isDestroy;
};
var getCurrentHash = function () {
    var _historylist = history[current_history];
    if (_historylist.length < 2) return "";
    var targeturl = `#${current_history}${_historylist.length ? _historylist[_historylist.length - 1] : ""}`;
    return targeturl;
};

var fixurl = function () {
    if (fixurl.ing) return;
    fixurl.ing = setTimeout(function () {
        fixurl.ing = false;
        var targeturl = getCurrentHash();
        if (pagehash_reg.test(targeturl)) {
            if (!pagehash_reg.test(location.href)) location.href = targeturl;
            else if (location.hash !== targeturl) location.replace(targeturl);
        } else if (pagehash_reg.test(location.href)) {
            preventNextHashChange = true;
            window_history.go(-1);
        }
    }, 0);
};
var checkonback = function (elements) {
    for (var cx = 0, dx = elements.length; cx < dx; cx++) {
        var element = elements[cx];
        var onback = element && element.onback;
        if (isFunction(onback)) {
            onback = element.onback();
        }
        if (onback === false || isString(onback)) {
            break;
        }
    }
    return onback;
};
put(":empty", function () {
    return null;
});

var onback = function () {
    if (rootElements.length) {
        fixurl();
        remove(rootElements.pop());
        return;
    }
    var onback = checkonback([
        global[current_history],
    ]);
    if (onback === false) {
        fixurl();
        return;
    }
    if (isString(onback)) {
        return go(onback);
    }
    if (go(-1) === true) {
        try {
            navigator.app.exitApp();
        } catch (e) {
        };
    } else { };
};

function addGlobal(element, name, isDestroy) {
    if (!name) {
        name = current_history;
    }
    if (isString(name)) {
        if (global[name] === element) return;
        var oldElement = global[name];
        if (oldElement) {
            oldElement.initialStyle = isDestroy ? oldElement.backupStyle : oldElement.holdupStyle;
        }
        if (isFunction(body.layer)) {
            body.layer(element, oldElement, history);
        } else {
            remove(oldElement);
            appendChild(body, element);
        }
        global[name] = element;
    } else if (isNode(name)) {
        appendChild(name, element);
    } else if (isFunction(name)) {
        name(element);
    } else if (element) {
        popup(element);
        fixurl();
    }
}
var _switch = zimoli.switch = function (history_name, target_body, emptyState) {
    if (history_name)
        current_history = history_name;
    if (target_body)
        body = target_body;
    if (emptyState !== false && !history[history_name]) history[history_name] = [emptyState || ":empty"];
};
zimoli.global = addGlobal;
popup.go = zimoli.go = go;
rootElements.push = function () {
    [].push.apply(this, arguments);
    fixurl();
};
appendChild.transition = transition;
remove.transition = transition;
window.modules = modules;
zimoli.setStorage = function (storage) {
    hostoryStorage = storage;
    try {
        history = JSON.parse(hostoryStorage.getItem(history_session_object_key)) || history;
    } catch (e) {
    }
};
zimoli.inithash = locationInitHash;<commit_msg>解决一些不能跳转的问题<commit_after>/*
 * 不枝雀
 * 2017-3-18 16:16:20
 */
//main
var body = document.body;
var onbacks = [];
var window_history = window.history;
var window_history_length = window_history.length;
var sessionSavedHashKey = "__zimoli_session_init_hash" + location.pathname;
var sessionInitHash = sessionStorage.getItem(sessionSavedHashKey);
var hostoryStorage = sessionStorage;
var pagehash_reg = /#([\/\w\:@\.\_\(\)\+\-\*\$@!~_'\?,&~%]+)$/;
var locationInitHash = location.hash;
var hashchangecount = 0;
var isFirstTimeLoad = sessionInitHash === null;
var isSimpleRefresh = sessionInitHash === locationInitHash;
var isWithHashLoad = !!location.hash;
var preventNextHashChange = false;
window_history.scrollRestoration = 'manual'
if (isWithHashLoad && !isSimpleRefresh) {
    //带hash加载，吃掉hash
    location.replace("#");
}

if (/MSIE\s*[2-7]/.test(navigator.userAgent)) {
    window.onhistorychange = function (url) {
        hashchangecount++;
        // 如果是返回事件，一定不是第一次改变hash
        // 这里刚好可以屏蔽首次手动改变url可能产生的hashchange事件
        if (hashchangecount < 2) return;
        if (preventNextHashChange) return preventNextHashChange = false, window_history.go(-1);
        if (preventNextHashChange === void 0 ? onback && onback() === true : preventNextHashChange = void 0) { }
    };
    onselectstart(body, function (e) {
        return e.preventDefault();
    });
    var frame = createElement("iframe");
    css(frame, "display:none");
    appendChild(body, frame);
    var doc = frame.contentWindow.document;
    var backman = function (isloaded) {
        doc.open();
        doc.write(isloaded !== false ? "" : "<script>result=parent.onhistorychange();onload=function(){history.forward()}</script>");
        doc.close();
    };
    backman(false);
    backman();
} else {
    onhashchange(window, function (event) {
        hashchangecount++;
        // 如果是返回事件，一定不是第一次改变hash
        // 这里刚好可以屏蔽首次手动改变url可能产生的hashchange事件
        var targetHash = location.hash;
        sessionStorage.setItem(sessionSavedHashKey, targetHash);
        if (pagehash_reg.test(targetHash)) {
            var currentHash = getCurrentHash();
            if (currentHash && currentHash === targetHash) return;
            var targetHashIndex = targetHash.indexOf("#" + current_history);
            if (targetHashIndex < 0) return;
            var targetpath = targetHash.slice(targetHashIndex + current_history.length + 1);
            go(targetpath);
            return;
        }
        if (preventNextHashChange) return preventNextHashChange = false;
        event.preventDefault();
        onback();
    });
}
// body
css("html", {
    height: "100%",
    fontFamily: `"SF Pro SC","SF Pro Text","SF Pro Icons","PingFang SC","Helvetica Neue","Helvetica","Arial",sans-serif`,
    backgroundColor: "#f2f4f9"
});
css("body", {
    border: "none",
    margin: "0",
    padding: "0",
    height: "100%",
    overflow: "hidden",
});
var location_pathname = location.pathname;
var _zimoli_params_key = `_zimoli_parameters:${location_pathname}#`;
var _zimoli_state_prefix = `_zimoli_page_state:${location_pathname}#`;

function getReverseStyle(style) {
    if (!(style instanceof Object)) {
        style = parseKV(style, ";", ":");
    }
    var dest = {};
    var replacer = function (m, d, t) {
        if (t) return -d + t;
        return +d ? 1 / d : m;
    };
    //如要是对放大系数进行求倒，对位移进行反向
    for (var k in style) {
        if (/transform|left|top|right|bottom|margin/i.test(k)) {
            dest[k] = String(style[k]).replace(/(\-?\d*\.?\d+)(deg|p[xt]|r?em|[cm]m|%|)/ig, replacer);
        } else {
            dest[k] = style[k];
        }
    }
    return dest;
}

function go(pagepath, args, history_name, oldpagepath) {
    if (!history_name)
        history_name = current_history;
    if (isNumber(pagepath)) {
        if (isString(history_name)) {
            var _history = history[history_name] || [];
            pagepath = _history[pagepath < 1 ? _history.length + pagepath - 1 : pagepath];
            oldpagepath = _history[_history.length - 1];
        }
    }
    if (!pagepath) return true;
    var stringified_args = JSON.stringify({ data: args, from: oldpagepath });
    if (stringified_args.length === 2) hostoryStorage.removeItem(_zimoli_params_key + pagepath);
    else hostoryStorage.setItem(_zimoli_params_key + pagepath, stringified_args);
    if (!page_generators[pagepath]) {
        return zimoli(pagepath, args, history_name, oldpagepath);
    }
    var page_object = page_generators[pagepath];
    var { pg, with: _with_elements, state, onback: _pageback_listener, prepares } = page_object;
    page_object.go = function (_url, args, _history_name) {
        return go(state.path(_url), args, _history_name, isString(history_name) ? pagepath : oldpagepath);
    };
    _with_elements = [].concat(_with_elements);
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.onback = function (handler) {
        _pageback_listener = handler;
    };
    if (undefined === args || null === args) args = {};
    var _page = pg.call(state, args, oldpagepath);
    if (_page) {
        if (pg.className) _page.className = pg.className;
        _page.with = _with_elements;
        if (args.initialStyle) _page.initialStyle = args.initialStyle;
        if (args.holdupStyle) _page.holdupStyle = args.holdupStyle;
        if (_page.initialStyle && !_page.holdupStyle) {
            _page.holdupStyle = getReverseStyle(_page.initialStyle);
            _page.backupStyle = _page.initialStyle;
        }
        _page.onback = _pageback_listener;
    }
    var isDestroy = pushstate(pagepath, history_name, oldpagepath);
    if (isNode(history_name)) {
        if (history_name.activate === pagepath && history_name.activateNode === _page) return;
        else remove(history_name.activateNode);
        history_name.activate = pagepath;
        history_name.activateNode = _page;
    }
    addGlobal(_page, history_name, isDestroy);
    prepares.forEach(function (url) {
        if (isNumber(url)) {
            url = _history[url < 1 ? _history.length + url - 1 : url];
        }
        if (isString(url)) prepare(url);
    });
    return _page;
}
var page_generators = {};
/**
 * 加载一个页面到document.body
 * 如果args是一个字符串，那么当下次指定一个相同的字符串时，此对象被新对象代替
 * 如果args是bool值true，那么当执行history.back()时，此对象被清除
 */
function prepare(pagepath, ok) {
    if (page_generators[pagepath]) return isFunction(ok) && ok();
    var _zimoli_state_key = _zimoli_state_prefix + pagepath;
    var state = function state(condition, setAsAdditional = condition !== null) {
        var state_string = hostoryStorage.getItem(_zimoli_state_key);
        var state_object;
        if (state_string) {
            try {
                state_object = JSON.parse(state_string);
            } catch (e) {
                state_object = {};
            }
        } else {
            state_object = {}
        }
        if (condition instanceof Object && setAsAdditional) {
            if (!(state_object instanceof Object)) {
                state_object = {
                    toString() {
                        return String(this.valueOf());
                    },
                    valueOf: new Function(`return ${state_object}`),
                };
            }
            state_object = extend(state_object, condition);
        } else if (arguments.length) {
            state_object = condition;
        }
        if (arguments.length) {
            hostoryStorage.setItem(_zimoli_state_key, JSON.stringify(state_object) || null);
        }
        return state_object;
    };
    state.state = state;
    var _with_elements = [];
    state.with = function (element) {
        element && _with_elements.push(element);
        return _with_elements;
    };
    state.path = function (url) {
        if (isString(url) && /^[^\\\/]/.test(url)) {
            url = pagepath.replace(/[^\/]*$/, url);
        }
        return url;
    }
    state.go = function (url, args, _history_name) {
        // if (arguments.length === 1 && isFinite(url)) return window_history.go(url | 0);
        var go = page_generators[pagepath].go;
        isFunction(go) && go(url, args, _history_name);

    };
    var prepares = [];
    state.prepare = state.go.prepare = function (urls) {
        prepares.push.apply(prepares, [].concat(urls).map(state.path));
    };
    var _pageback_listener = [];
    state.onback = state.onrelease = state.ondestroy = function (handler) {
        //只能在page上使用
        _pageback_listener = handler;
    };
    state.titlebar = function () {
        var realTitleBar = titlebar.apply(null, arguments);
        state.with(realTitleBar);
        return realTitleBar;
    };
    return init(pagepath, function (pg) {
        if (!pg) return;
        page_generators[pagepath] = {
            pg,
            state,
            with: _with_elements,
            onback: _pageback_listener,
            prepares
        };
        return isFunction(ok) && ok();
    }, state);
}

function zimoli(pagepath, args, history_name, oldpagepath) {
    if (arguments.length === 0) {
        history_name = current_history;
        var _history = history[history_name] || [];
        pagepath = _history[_history.length - 1] || "/main";
        try {
            var saveddata = JSON.parse(hostoryStorage.getItem(_zimoli_params_key + pagepath)) || {};
        } catch (e) {
            var saveddata = {};
        }
        var { data, from } = saveddata;
        args = data;
        oldpagepath = from;
    }
    if (page_generators[pagepath]) return go(pagepath, args, history_name, oldpagepath);
    return prepare(pagepath, function () {
        return go(pagepath, args, history_name, oldpagepath);
    });
}
var global = {};
var history = {};
var current_history = "";
history[current_history] = [];
var history_session_object_key = `_zimoli_history_key:${location_pathname}`;
try {
    history = JSON.parse(hostoryStorage.getItem(history_session_object_key)) || history;
} catch (e) {
}
var pushstate = function (path_name, history_name, oldpagepath) {
    var isDestroy = false;
    if (!history_name) {
        history_name = current_history;
    }
    if (!isString(history_name)) return;
    if (!history[history_name]) {
        history[history_name] = [path_name];
    } else {
        var _history = history[history_name];
        if (_history.indexOf(oldpagepath) < 0) {
            _history.splice(_history[0] === ":empty", _history.length);
            isDestroy = true;
        }
        for (var cx = 0, dx = _history.length; cx < dx; cx++) {
            if (_history[cx] === path_name) {
                _history.splice(cx, dx - cx);
                isDestroy = true;
                break;
            }
        }
        _history.push(path_name);
        if (_history.length) fixurl();
    }
    hostoryStorage.setItem(history_session_object_key, JSON.stringify(history) || null);
    return isDestroy;
};
var getCurrentHash = function () {
    var _historylist = history[current_history];
    if (_historylist.length < 2) return "";
    var targeturl = `#${current_history}${_historylist.length ? _historylist[_historylist.length - 1] : ""}`;
    return targeturl;
};

var fixurl = function () {
    if (fixurl.ing) return;
    fixurl.ing = setTimeout(function () {
        fixurl.ing = false;
        var targeturl = getCurrentHash();
        if (pagehash_reg.test(targeturl)) {
            if (!pagehash_reg.test(location.href)) location.href = targeturl;
            else if (location.hash !== targeturl) location.replace(targeturl);
        } else if (pagehash_reg.test(location.href)) {
            preventNextHashChange = true;
            window_history.go(-1);
        }
    }, 0);
};
var checkonback = function (elements) {
    for (var cx = 0, dx = elements.length; cx < dx; cx++) {
        var element = elements[cx];
        var onback = element && element.onback;
        if (isFunction(onback)) {
            onback = element.onback();
        }
        if (onback === false || isString(onback)) {
            break;
        }
    }
    return onback;
};
put(":empty", function () {
    return null;
});

var onback = function () {
    if (rootElements.length) {
        fixurl();
        remove(rootElements.pop());
        return;
    }
    var onback = checkonback([
        global[current_history],
    ]);
    if (onback === false) {
        fixurl();
        return;
    }
    if (isString(onback)) {
        return go(onback);
    }
    if (go(-1) === true) {
        try {
            navigator.app.exitApp();
        } catch (e) {
        };
    } else { };
};

function addGlobal(element, name, isDestroy) {
    if (!name) {
        name = current_history;
    }
    if (isString(name)) {
        if (global[name] === element) return;
        var oldElement = global[name];
        if (oldElement) {
            oldElement.initialStyle = isDestroy ? oldElement.backupStyle : oldElement.holdupStyle;
        }
        if (isFunction(body.layer)) {
            body.layer(element, oldElement, history);
        } else {
            remove(oldElement);
            appendChild(body, element);
        }
        global[name] = element;
    } else if (isNode(name)) {
        appendChild(name, element);
    } else if (isFunction(name)) {
        name(element);
    } else if (element) {
        popup(element);
        fixurl();
    }
}
var _switch = zimoli.switch = function (history_name, target_body, emptyState) {
    if (history_name)
        current_history = history_name;
    if (target_body)
        body = target_body;
    if (emptyState !== false && !history[history_name]) history[history_name] = [emptyState || ":empty"];
};
zimoli.global = addGlobal;
popup.go = zimoli.go = go;
rootElements.push = function () {
    [].push.apply(this, arguments);
    fixurl();
};
appendChild.transition = transition;
remove.transition = transition;
window.modules = modules;
zimoli.setStorage = function (storage) {
    hostoryStorage = storage;
    try {
        history = JSON.parse(hostoryStorage.getItem(history_session_object_key)) || history;
    } catch (e) {
    }
};
zimoli.inithash = locationInitHash;<|endoftext|>


<commit_before>(function($){

	var game_in_progress = false;
	var field_size = {
		rows: 4, cols: 6, col_size: 2
	}
	var cards_flipped = 0;
	var pair_flips = 0;
	var pairs_left = 0;
	var first_card = second_card = '';
	var tileset = [];

	var decks = {
		upper_lower_alphabet: {
			init: function(){
				codeset = [];

				total_pairs = (field_size.rows * field_size.cols) >> 1;
				for(idx = 0; idx < total_pairs; idx++){
					tile = {id: idx, code: Math.random().toString(36).substr(4, 1)};
					if(!isNaN(tile.code) || codeset.indexOf(tile.code) >= 0){
						idx--;
					} else {
						codeset.push(tile.code);
						tileset.push(tile);
					}
				}

				for(idx = 0; idx < total_pairs; idx++){
					tile = {id: tileset[idx].id, code: tileset[idx].code.toUpperCase()};
					tileset.push(tile);
				}

				idx = total_pairs << 1;
				while(idx != 0){
					random_idx = Math.floor(Math.random() * idx);
					idx--;

					temp = tileset[idx];
					tileset[idx] = tileset[random_idx];
					tileset[random_idx] = temp;
				}
			}
		}
	}

	$(document).ready(function(){
		$('.deal').click(function(){
			if(game_in_progress){
				$('.concentration-overlay .modal-dialog').addClass('modal-sm');
				$('.concentration-overlay .modal-content').html(
					"
Hmmm, Your game is already in progress. Are you sure you want to deal a new game?
"
					+ "
<button class='deal-confirm btn btn-success btn-lg'>Yes, deal!</button>
"
					+ "
<button class='dismiss btn btn-default btn-lg'>No, keep playing</button>
"
				);
				$('.deal-confirm').click(function(){
					$('.concentration-overlay').modal('hide');
					init();
				});
				$('.dismiss').click(function(){
					$('.concentration-overlay').modal('hide');
				});
				$('.concentration-overlay').modal();

				return;
			}
			init();
		});
	});

	function init(){
		game_in_progress = true;
		pair_flips = 0;
		pairs_left = (field_size.rows * field_size.cols) >> 1;
		tileset = [];

		//TODO(cjw) support more decks
		decks[$('#deck-select').val()].init();

		$field = $('.field');
		$field.empty();
		var even_odd_toggle = false;
		for(idx = 0; idx < field_size.rows; idx++){
			var row = $(document.createElement('div')).addClass('row');
			for(idy = 0; idy < field_size.cols; idy++){
				tile = tileset.pop();
				var col = $(document.createElement('div'))
					.addClass('col-xs-' + field_size.col_size);
				col.append(
					$(document.createElement('div'))
					.addClass('card')
					.addClass((even_odd_toggle ? 'card-even' : 'card-odd'))
					.addClass('card-' + idx + '-' + idy)
					.attr('data-card-id', idx + '-' + idy)
					.attr('data-tile-id', tile.id)
					.html(
						"
?
"
						+ "
" + tile.code + "
"
					)
					.flip({
						autosize: [true, true],
						trigger: 'manual'}
					)
				);
				row.append(col);
				even_odd_toggle = !even_odd_toggle;
			}
			$field.append(row);
		}
		$('.card').each(function(){
			$(this).on('flip:done', function(){
				if(cards_flipped == 2){
					if(cardsMatch()){
						setTimeout(function(){
							$('.card-' + first_card).addClass('match');
							$('.card-' + second_card).addClass('match');
						}, 125);
						setTimeout(function(){
							$('.card-' + first_card).removeClass('match');
							$('.card-' + second_card).removeClass('match');
							triedAPair(true);
						}, 550);
					} else {
						setTimeout(function(){
							$('.card-' + first_card).addClass('no-match');
							$('.card-' + second_card).addClass('no-match');
						}, 550);
						setTimeout(function(){
							$('.card-' + first_card).removeClass('no-match');
							$('.card-' + second_card).removeClass('no-match');
							$('.card-' + first_card).flip(false);
							$('.card-' + second_card).flip(false);
							triedAPair();
						}, 1150);
					}
				}
			});
		});
		$('.card').click(function(){
			if(cards_flipped < 2){
				if(cards_flipped == 0){
					first_card = $(this).attr('data-card-id');
					$(this).flip(true);
				} else {
					second_card = $(this).attr('data-card-id');
					$(this).flip(true);
				}
				cards_flipped++;
			}
		});
	}

	function triedAPair(matched = false){
		pair_flips++;
		cards_flipped = 0;
		if(matched && (--pairs_left == 0)){
			gameOver();
		}
		console.log(pairs_left);
	}

	function gameOver(){
		$('.concentration-overlay .modal-dialog').removeClass('modal-sm');
		$('.concentration-overlay .modal-content').html(
			"
You win!
"
			+ "
You found all " + (field_size.rows * field_size.cols) + " pairs in " + pair_flips + " tries.
"
		);
		$('.concentration-overlay').modal();
		game_in_progress = false;
	}

	function cardsMatch(){
		return $('.card-' + first_card).attr('data-tile-id')
			== $('.card-' + second_card).attr('data-tile-id');
	}

})(jQuery);<commit_msg>Removed a 'console.log' leftover.<commit_after>(function($){

	var game_in_progress = false;
	var field_size = {
		rows: 4, cols: 6, col_size: 2
	}
	var cards_flipped = 0;
	var pair_flips = 0;
	var pairs_left = 0;
	var first_card = second_card = '';
	var tileset = [];

	var decks = {
		upper_lower_alphabet: {
			init: function(){
				codeset = [];

				total_pairs = (field_size.rows * field_size.cols) >> 1;
				for(idx = 0; idx < total_pairs; idx++){
					tile = {id: idx, code: Math.random().toString(36).substr(4, 1)};
					if(!isNaN(tile.code) || codeset.indexOf(tile.code) >= 0){
						idx--;
					} else {
						codeset.push(tile.code);
						tileset.push(tile);
					}
				}

				for(idx = 0; idx < total_pairs; idx++){
					tile = {id: tileset[idx].id, code: tileset[idx].code.toUpperCase()};
					tileset.push(tile);
				}

				idx = total_pairs << 1;
				while(idx != 0){
					random_idx = Math.floor(Math.random() * idx);
					idx--;

					temp = tileset[idx];
					tileset[idx] = tileset[random_idx];
					tileset[random_idx] = temp;
				}
			}
		}
	}

	$(document).ready(function(){
		$('.deal').click(function(){
			if(game_in_progress){
				$('.concentration-overlay .modal-dialog').addClass('modal-sm');
				$('.concentration-overlay .modal-content').html(
					"
Hmmm, Your game is already in progress. Are you sure you want to deal a new game?
"
					+ "
<button class='deal-confirm btn btn-success btn-lg'>Yes, deal!</button>
"
					+ "
<button class='dismiss btn btn-default btn-lg'>No, keep playing</button>
"
				);
				$('.deal-confirm').click(function(){
					$('.concentration-overlay').modal('hide');
					init();
				});
				$('.dismiss').click(function(){
					$('.concentration-overlay').modal('hide');
				});
				$('.concentration-overlay').modal();

				return;
			}
			init();
		});
	});

	function init(){
		game_in_progress = true;
		pair_flips = 0;
		pairs_left = (field_size.rows * field_size.cols) >> 1;
		tileset = [];

		//TODO(cjw) support more decks
		decks[$('#deck-select').val()].init();

		$field = $('.field');
		$field.empty();
		var even_odd_toggle = false;
		for(idx = 0; idx < field_size.rows; idx++){
			var row = $(document.createElement('div')).addClass('row');
			for(idy = 0; idy < field_size.cols; idy++){
				tile = tileset.pop();
				var col = $(document.createElement('div'))
					.addClass('col-xs-' + field_size.col_size);
				col.append(
					$(document.createElement('div'))
					.addClass('card')
					.addClass((even_odd_toggle ? 'card-even' : 'card-odd'))
					.addClass('card-' + idx + '-' + idy)
					.attr('data-card-id', idx + '-' + idy)
					.attr('data-tile-id', tile.id)
					.html(
						"
?
"
						+ "
" + tile.code + "
"
					)
					.flip({
						autosize: [true, true],
						trigger: 'manual'}
					)
				);
				row.append(col);
				even_odd_toggle = !even_odd_toggle;
			}
			$field.append(row);
		}
		$('.card').each(function(){
			$(this).on('flip:done', function(){
				if(cards_flipped == 2){
					if(cardsMatch()){
						setTimeout(function(){
							$('.card-' + first_card).addClass('match');
							$('.card-' + second_card).addClass('match');
						}, 125);
						setTimeout(function(){
							$('.card-' + first_card).removeClass('match');
							$('.card-' + second_card).removeClass('match');
							triedAPair(true);
						}, 550);
					} else {
						setTimeout(function(){
							$('.card-' + first_card).addClass('no-match');
							$('.card-' + second_card).addClass('no-match');
						}, 550);
						setTimeout(function(){
							$('.card-' + first_card).removeClass('no-match');
							$('.card-' + second_card).removeClass('no-match');
							$('.card-' + first_card).flip(false);
							$('.card-' + second_card).flip(false);
							triedAPair();
						}, 1150);
					}
				}
			});
		});
		$('.card').click(function(){
			if(cards_flipped < 2){
				if(cards_flipped == 0){
					first_card = $(this).attr('data-card-id');
					$(this).flip(true);
				} else {
					second_card = $(this).attr('data-card-id');
					$(this).flip(true);
				}
				cards_flipped++;
			}
		});
	}

	function triedAPair(matched = false){
		pair_flips++;
		cards_flipped = 0;
		if(matched && (--pairs_left == 0)){
			gameOver();
		}
	}

	function gameOver(){
		$('.concentration-overlay .modal-dialog').removeClass('modal-sm');
		$('.concentration-overlay .modal-content').html(
			"
You win!
"
			+ "
You found all " + (field_size.rows * field_size.cols) + " pairs in " + pair_flips + " tries.
"
		);
		$('.concentration-overlay').modal();
		game_in_progress = false;
	}

	function cardsMatch(){
		return $('.card-' + first_card).attr('data-tile-id')
			== $('.card-' + second_card).attr('data-tile-id');
	}

})(jQuery);<|endoftext|>


<commit_before>/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015 Clinton Health Access Initiative (CHAI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

angular.module('vaccine-inventory', ['openlmis', 'ngTable','ui.bootstrap.accordion','angularCombine','ui.bootstrap.modal','ui.bootstrap.pagination'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.
            when('/stock-on-hand', {controller:StockOnHandController, templateUrl:'partials/stock-on-hand.html',reloadOnSearch:false,resolve:StockOnHandController.resolve}).
//  TODO    when('/stock-adjustment', {controller:StockAdjustmentController, templateUrl:'partials/stock-adjustment.html',resolve:StockAdjustmentController.resolve}).
            otherwise({redirectTo:'/stock-on-hand'});
    }]).run(function ($rootScope, AuthorizationService) {

     }).config(function(angularCombineConfigProvider) {
        angularCombineConfigProvider.addConf(/filter-/, '/public/pages/reports/shared/filters.html');
    }).filter('positive', function() {
               return function(input) {
                   if (!input) {
                       return 0;
                   }

                   return Math.abs(input);
               };
    });<commit_msg>Update  angular vaccine inventory module<commit_after>/*
 * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
 *
 * Copyright (C) 2015 Clinton Health Access Initiative (CHAI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
 *
 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

angular.module('vaccine-inventory', ['openlmis', 'ngTable','ui.bootstrap.accordion','angularCombine','ui.bootstrap.modal','ui.bootstrap.pagination'])
    .config(['$routeProvider', function ($routeProvider) {
        $routeProvider.
            when('/stock-on-hand', {controller:StockOnHandController, templateUrl:'partials/stock-on-hand.html',reloadOnSearch:false,resolve:StockOnHandController.resolve}).
            when('/stock-adjustment', {controller:StockAdjustmentController, templateUrl:'partials/stock-adjustment.html',resolve:StockAdjustmentController.resolve}).
            otherwise({redirectTo:'/stock-on-hand'});
    }]).run(function ($rootScope, AuthorizationService) {

     }).config(function(angularCombineConfigProvider) {
        angularCombineConfigProvider.addConf(/filter-/, '/public/pages/reports/shared/filters.html');
    }).filter('positive', function() {
               return function(input) {
                   if (!input) {
                       return 0;
                   }

                   return Math.abs(input);
               };
    });<|endoftext|>


<commit_before>/**
 * Certain functions of ui.sortable need to be extended for better performance within OpenCms Advanced Direct Edit.

 *
 * First of all the _uiHash function is replaced by a version that will grant access to the private plugin-functions and properties.
 * The other extended functions deal with special cases and scenarios of the Advanced Direct Edit use-case.

 *
 */
$.extend($.ui.sortable.prototype, {
    /**
     * Returns the ui-object used with event-handlers.

     *
     * @param {Object} inst
     */
   _uiHash: function(inst) {
      var self = inst || this;

      /* cms-addition:
       * return the sortable-plugin-object as self */
      return {
         helper: self.helper,
         placeholder: self.placeholder || $([]),
         position: self.position,
         absolutePosition: self.positionAbs, //deprecated
         offset: self.positionAbs,
         item: self.currentItem,
         sender: inst ? inst.element : null,
         self: self
      };
   },
   /**
    * Internal event-handler for the mouse-stop-event. Adjusted to show a reverting animation to the original position of the item
    * in case of a canceled sorting indicated by a hidden placeholder.
.
    *
    * @param {Object} event
    * @param {Object} noPropagation
    */
   _mouseStop: function(event, noPropagation) {

      if (!event)
         return;

      //If we are using droppables, inform the manager about the drop
      if ($.ui.ddmanager && !this.options.dropBehaviour)
         $.ui.ddmanager.drop(this, event);

      if (this.options.revert) {
         var self = this;
         var cur;

         /* cms-addition:
          * in case the placeholder is hidden use the initial offset for reverting */
         if (self.placeholder.css('display') == 'none') {
            cur = self.cmsStartOffset;
         } else {
            cur = self.placeholder.offset();
         }

         self.reverting = true;

         $(this.helper).animate({
            left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
            top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
         }, parseInt(this.options.revert, 10) || 500, function() {
            self._clear(event);
         });
      } else {
         this._clear(event, noPropagation);
      }

      return false;

   },
   /**
    * Check whether the pointer intersects with a certain item.

    *
    * @param {Object} item
    */
   _intersectsWithPointer: function(item) {

      var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth;

      /* cms-addition:
       *  verify if item parent matches the container the pointer intersect with */
      var isOverElementOld = isOverElement;

      if (isOverElement) {
         isOverElement = false;
         for (var i = this.containers.length - 1; i >= 0; i--) {
            if (this._intersectsWith(this.containers[i].containerCache)) {
               if (this.containers[i].element[0] == item.item.parent().get(0)) {
                  isOverElement = true;
                  break;
               }
            }
         }
      }

      if (!isOverElement)
         return false;

      var verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection();

      return this.floating ? (((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1) : (verticalDirection && (verticalDirection == "down" ? 2 : 1));

   },
   /**
    * Refreshes the list of sortable items.

    *
    * @param {Object} event
    */
   _refreshItems: function(event) {
        /*
         * cms-addition:
         * the arrays this.containers and queries are filled in a different order to avoid problems with favorites-dropzone
         */
        this.items = [];
        this.containers = [];
        var items = this.items;
        var self = this;
        var queries = [];
        var connectWith = this._connectWith();

        if(connectWith) {
            for (var i = connectWith.length - 1; i >= 0; i--){
                var cur = $(connectWith[i]);
                for (var j = cur.length - 1; j >= 0; j--){
                    var inst = $.data(cur[j], 'sortable');
                    if(inst && !inst.options.disabled) {
                  		queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, {
                     		item: this.currentItem
                  		}) : $(inst.options.items, inst.element), inst]);
                        this.containers.push(inst);
                    }
                };
            };
        }else{
            this.containers = [this];
         	queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, {
            	item: this.currentItem
         	}) : $(this.options.items, this.element), this]];
        }

		for (var i = queries.length - 1; i >= 0; i--) {
			var targetData = queries[i][1];
			var _queries = queries[i][0];

			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				var item = $(_queries[j]);

				item.data('sortable-item', targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
               		width: 0,
              		height: 0,
               		left: 0,
               		top: 0
				});
			};
		};

	}
})

/**
 * Application entry point.
 */
$('document').ready(function() {

   // TODO: may be it is better to load the toolbar after successfully loading the data
   $('.cms-item a.ui-icon').live('click', cms.toolbar.toggleAdditionalInfo);
   cms.toolbar.addToolbar();
   $('.cms-item-list div.cms-additional div').jHelperTip({
      trigger: 'hover',
      source: 'attribute',
      attrName: 'alt',
      topOff: -30,
      opacity: 0.8,
      live: true
   });

   cms.data.loadAllData(function(ok) {
      if (ok) {
         cms.data.fillContainers();
         cms.toolbar.resetNewList();
         if (!cms.data.allowEdit) {
            if (cms.data.lockedBy) {
               cms.util.dialogAlert('You can\'t edit this page. It is locked by the user "' + cms.data.lockedBy + '"', 'Page locked');
            } else {
               cms.util.dialogAlert('You do not have the necessary permissions to edit this page.', 'Can\'t edit');
            }
            var $buttons = $(cms.util.makeCombinedSelector(['Move', 'Delete', 'Add', 'New', 'Favorites', 'Recent'], 'button[name="%"]'));
            $buttons.unbind('click').unbind('mouseover').css('color', '#aaaaaa');
            if (cms.data.lockedBy) {
               $buttons.attr('alt', 'Page locked by ' + cms.data.lockedBy);
               $buttons.jHelperTip({
                  trigger: "hover",
                  source: "attribute",
                  attrName: "alt",
                  autoClose: true
               });
            }
         }
         cms.toolbar.toolbarReady=true;
         if (cms.util.isFirebugActive()) {
            cms.util.dialogAlert('The Firefox Firebug plug-in is active. It is advised to deactivate it, as it may degrade the performance of OpenCms Advanced Direct Edit.', 'Firebug is active')
         }

         $(document).trigger("cms-data-loaded");

      } else {
            // TODO
      }
   });
});
<commit_msg>Improved _mouseStop function.<commit_after>/**
 * Certain functions of ui.sortable need to be extended for better performance within OpenCms Advanced Direct Edit.

 *
 * First of all the _uiHash function is replaced by a version that will grant access to the private plugin-functions and properties.
 * The other extended functions deal with special cases and scenarios of the Advanced Direct Edit use-case.

 *
 */
$.extend($.ui.sortable.prototype, {
    /**
     * Returns the ui-object used with event-handlers.

     *
     * @param {Object} inst
     */
   _uiHash: function(inst) {
      var self = inst || this;

      /* cms-addition:
       * return the sortable-plugin-object as self */
      return {
         helper: self.helper,
         placeholder: self.placeholder || $([]),
         position: self.position,
         absolutePosition: self.positionAbs, //deprecated
         offset: self.positionAbs,
         item: self.currentItem,
         sender: inst ? inst.element : null,
         self: self
      };
   },
   /**
    * Internal event-handler for the mouse-stop-event. Adjusted to show a reverting animation to the original position of the item
    * in case of a canceled sorting indicated by a hidden placeholder.
.
    *
    * @param {Object} event
    * @param {Object} noPropagation
    */
   _mouseStop: function(event, noPropagation) {

      if (!event)
         return;

      //If we are using droppables, inform the manager about the drop
      if ($.ui.ddmanager && !this.options.dropBehaviour)
         $.ui.ddmanager.drop(this, event);

      if (this.options.revert) {
         var self = this;
         var cur;

         /* cms-addition:
          * in case the placeholder is hidden use the initial offset for reverting */
         if (self.cmsStartOffset && self.placeholder.css('display') == 'none') {
            cur = self.cmsStartOffset;
         } else {
            cur = self.placeholder.offset();
         }

         self.reverting = true;

         $(this.helper).animate({
            left: cur.left - this.offset.parent.left - self.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft),
            top: cur.top - this.offset.parent.top - self.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop)
         }, parseInt(this.options.revert, 10) || 500, function() {
            self._clear(event);
         });
      } else {
         this._clear(event, noPropagation);
      }

      return false;

   },
   /**
    * Check whether the pointer intersects with a certain item.

    *
    * @param {Object} item
    */
   _intersectsWithPointer: function(item) {

      var isOverElementHeight = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth;

      /* cms-addition:
       *  verify if item parent matches the container the pointer intersect with */
      var isOverElementOld = isOverElement;

      if (isOverElement) {
         isOverElement = false;
         for (var i = this.containers.length - 1; i >= 0; i--) {
            if (this._intersectsWith(this.containers[i].containerCache)) {
               if (this.containers[i].element[0] == item.item.parent().get(0)) {
                  isOverElement = true;
                  break;
               }
            }
         }
      }

      if (!isOverElement)
         return false;

      var verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection();

      return this.floating ? (((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1) : (verticalDirection && (verticalDirection == "down" ? 2 : 1));

   },
   /**
    * Refreshes the list of sortable items.

    *
    * @param {Object} event
    */
   _refreshItems: function(event) {
        /*
         * cms-addition:
         * the arrays this.containers and queries are filled in a different order to avoid problems with favorites-dropzone
         */
        this.items = [];
        this.containers = [];
        var items = this.items;
        var self = this;
        var queries = [];
        var connectWith = this._connectWith();

        if(connectWith) {
            for (var i = connectWith.length - 1; i >= 0; i--){
                var cur = $(connectWith[i]);
                for (var j = cur.length - 1; j >= 0; j--){
                    var inst = $.data(cur[j], 'sortable');
                    if(inst && !inst.options.disabled) {
                  		queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, {
                     		item: this.currentItem
                  		}) : $(inst.options.items, inst.element), inst]);
                        this.containers.push(inst);
                    }
                };
            };
        }else{
            this.containers = [this];
         	queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, {
            	item: this.currentItem
         	}) : $(this.options.items, this.element), this]];
        }

		for (var i = queries.length - 1; i >= 0; i--) {
			var targetData = queries[i][1];
			var _queries = queries[i][0];

			for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) {
				var item = $(_queries[j]);

				item.data('sortable-item', targetData); // Data for target checking (mouse manager)

				items.push({
					item: item,
					instance: targetData,
               		width: 0,
              		height: 0,
               		left: 0,
               		top: 0
				});
			};
		};

	}
})

/**
 * Application entry point.
 */
$('document').ready(function() {

   // TODO: may be it is better to load the toolbar after successfully loading the data
   $('.cms-item a.ui-icon').live('click', cms.toolbar.toggleAdditionalInfo);
   cms.toolbar.addToolbar();
   $('.cms-item-list div.cms-additional div').jHelperTip({
      trigger: 'hover',
      source: 'attribute',
      attrName: 'alt',
      topOff: -30,
      opacity: 0.8,
      live: true
   });

   cms.data.loadAllData(function(ok) {
      if (ok) {
         cms.data.fillContainers();
         cms.toolbar.resetNewList();
         if (!cms.data.allowEdit) {
            if (cms.data.lockedBy) {
               cms.util.dialogAlert('You can\'t edit this page. It is locked by the user "' + cms.data.lockedBy + '"', 'Page locked');
            } else {
               cms.util.dialogAlert('You do not have the necessary permissions to edit this page.', 'Can\'t edit');
            }
            var $buttons = $(cms.util.makeCombinedSelector(['Move', 'Delete', 'Add', 'New', 'Favorites', 'Recent'], 'button[name="%"]'));
            $buttons.unbind('click').unbind('mouseover').css('color', '#aaaaaa');
            if (cms.data.lockedBy) {
               $buttons.attr('alt', 'Page locked by ' + cms.data.lockedBy);
               $buttons.jHelperTip({
                  trigger: "hover",
                  source: "attribute",
                  attrName: "alt",
                  autoClose: true
               });
            }
         }
         cms.toolbar.toolbarReady=true;
         if (cms.util.isFirebugActive()) {
            cms.util.dialogAlert('The Firefox Firebug plug-in is active. It is advised to deactivate it, as it may degrade the performance of OpenCms Advanced Direct Edit.', 'Firebug is active')
         }

         $(document).trigger("cms-data-loaded");

      } else {
            // TODO
      }
   });
});
<|endoftext|>