<commit_before>/**
 * Underhand solution for reading Json on time without worrying about loadings not being on correct time.
 *
 */

function getJson(){
	//Think if sizeMultiplier should be set instead of the zoom as playerPref
	var x=
{
	"sizeMultiplier": 1.5,
	"nations":
	[
		{
			"name": "Venaja",
			"x": " ,Border:Right",
			"y": 600,
			"width": 187,
			"height": 348,
			"rotation": 0,
			"sprite": "Venaja"

		},
		{
			"name": "Norja",
			"x": "Left:Venaja,Percent:19",
			"y": "Same:Venaja,Percent:-45",
			"width": 258,
			"height": 207,
			"rotation": 0,
			"sprite": "Norja"

		},
		{
			"name": "Suomi",
			"x": "Left:Venaja,Percent:38",
			"y": "Same:Venaja,Percent:-60",
			"width": 120,
			"height": 159,
			"rotation": 0,
			"sprite": "Suomi"
		},
		{
			"name": "Ruotsi",
			"x": "Same:Suomi,Percent:-57.5",
			"y": "Same:Suomi,Percent:19",
			"width": 129,
			"height": 191,
			"rotation": 0,
			"sprite": "Ruotsi"

		},
		{
			"name": "Viro",
			"x": "Left:Venaja,Percent:17",
			"y": "Down:Suomi,Percent:-17",
			"width": 66,
			"height": 34,
			"rotation": 0,
			"sprite": "Viro"
		},
		{
			"name": "Latvia",
			"x": "Same:Viro,Percent:-8",
			"y": "Down:Viro,Percent:-37",
			"width": 69,
			"height": 28,
			"rotation": 0,
			"sprite": "Latvia"
		},
		{
			"name": "Valko-Venaja",
			"x": "Same:Latvia,Percent:36",
			"y": "Down:Latvia,Percent:-13",
			"width": 91,
			"height": 50,
			"rotation": 0,
			"sprite": "Valko-Venaja"
		},
		{
			"name": "Liettua",
			"x": "Same:Latvia,Percent:-11",
			"y": "Down:Latvia,Percent:-30",
			"width": 55,
			"height": 29,
			"rotation": 0,
			"sprite": "Liettua"
		},
		{
			"name": "Ukraina",
			"x": "Same:Valko-Venaja,Percent:15.5",
			"y": "Down:Valko-Venaja,Percent:-13",
			"width": 176,
			"height": 75,
			"rotation": 0,
			"sprite": "Ukraina"
		},
		{
			"name": "Puola",
			"x": "Left:Valko-Venaja,Percent:7",
			"y": "Same:Valko-Venaja,Percent:33",
			"width": 92,
			"height": 58,
			"rotation": 0,
			"sprite": "Puola"
		},
		{
			"name": "Saksa",
			"x": "Left:Puola,Percent:9",
			"y": "Same:Puola,Percent:11",
			"width": 84,
			"height": 72,
			"rotation": 0,
			"sprite": "Saksa"
		},
		{
			"name": "Tanska",
			"x": "Same:Saksa,Percent:15",
			"y": "Up:Saksa,Percent:16",
			"width": 71,
			"height": 39,
			"rotation": 0,
			"sprite": "Tanska"
		},
		{
			"name": "Alankomaat",
			"x": "Left:Saksa,Percent:43",
			"y": "Same:Saksa,Percent:-32",
			"width": 38,
			"height": 25,
			"rotation": 0,
			"sprite": "Alankomaat"
		},
		{
			"name": "Ranska",
			"x": "Left:Saksa,Percent:27",
			"y": "Down:Saksa,Percent:-40",
			"width": 120,
			"height": 82,
			"rotation": 0,
			"sprite": "Ranska"
		},
		{
			"name": "Belgia",
			"x": "Left:Saksa,Percent:10",
			"y": "Same:Saksa,Percent:50",
			"width": 28,
			"height": 18,
			"rotation": 0,
			"sprite": "Belgia"
		},
		{
			"name": "Italia",
			"x": "Same:Saksa,Percent:15",
			"y": "Down:Saksa,Percent:0",
			"width": 102,
			"height": 86,
			"rotation": 0,
			"sprite": "Italia"
		},
		{
			"name": "Romania",
			"x": "Same:Ukraina,Percent:-69",
			"y": "Down:Ukraina,Percent:-86",
			"width": 89,
			"height": 40,
			"rotation": 0,
			"sprite": "Romania"
		},
		{
			"name": "Moldova",
			"x": "Same:Ukraina,Percent:-89",
			"y": "Down:Ukraina,Percent:-135",
			"width": 33,
			"height": 29,
			"rotation": 0,
			"sprite": "Moldova"
		},
		{
			"name": "Sveitsi",
			"x": 400,
			"y": 400,
			"width": 88,
			"height": 36,
			"rotation": 0,
			"sprite": "Sveitsi"
		}
	]
};
return x;
}<commit_msg>Maiden testailua<commit_after>/**
 * Underhand solution for reading Json on time without worrying about loadings not being on correct time.
 *
 */

function getJson(){
	//Think if sizeMultiplier should be set instead of the zoom as playerPref
	var x=
{
	"sizeMultiplier": 1.5,
	"nations":
	[
		{
			"name": "Venaja",
			"x": " ,Border:Right",
			"y": 600,
			"width": 518,
			"height": 694,
			"rotation": 0,
			"sprite": "Venaja"

		},
		{
			"name": "Norja",
			"x": "Left:Venaja,Percent:19",
			"y": "Same:Venaja,Percent:-45",
			"width": 258,
			"height": 207,
			"rotation": 0,
			"sprite": "Norja"

		},
		{
			"name": "Suomi",
			"x": "Left:Venaja,Percent:38",
			"y": "Same:Venaja,Percent:-60",
			"width": 120,
			"height": 159,
			"rotation": 0,
			"sprite": "Suomi"
		},
		{
			"name": "Ruotsi",
			"x": "Same:Suomi,Percent:-57.5",
			"y": "Same:Suomi,Percent:19",
			"width": 129,
			"height": 191,
			"rotation": 0,
			"sprite": "Ruotsi"

		},
		{
			"name": "Viro",
			"x": "Left:Venaja,Percent:17",
			"y": "Down:Suomi,Percent:-17",
			"width": 66,
			"height": 34,
			"rotation": 0,
			"sprite": "Viro"
		},
		{
			"name": "Latvia",
			"x": "Same:Viro,Percent:-8",
			"y": "Down:Viro,Percent:-37",
			"width": 69,
			"height": 28,
			"rotation": 0,
			"sprite": "Latvia"
		},
		{
			"name": "Valko-Venaja",
			"x": "Same:Latvia,Percent:36",
			"y": "Down:Latvia,Percent:-13",
			"width": 91,
			"height": 50,
			"rotation": 0,
			"sprite": "Valko-Venaja"
		},
		{
			"name": "Liettua",
			"x": "Same:Latvia,Percent:-11",
			"y": "Down:Latvia,Percent:-30",
			"width": 55,
			"height": 29,
			"rotation": 0,
			"sprite": "Liettua"
		},
		{
			"name": "Ukraina",
			"x": "Same:Valko-Venaja,Percent:15.5",
			"y": "Down:Valko-Venaja,Percent:-13",
			"width": 176,
			"height": 75,
			"rotation": 0,
			"sprite": "Ukraina"
		},
		{
			"name": "Puola",
			"x": "Left:Valko-Venaja,Percent:7",
			"y": "Same:Valko-Venaja,Percent:33",
			"width": 92,
			"height": 58,
			"rotation": 0,
			"sprite": "Puola"
		},
		{
			"name": "Saksa",
			"x": "Left:Puola,Percent:9",
			"y": "Same:Puola,Percent:11",
			"width": 84,
			"height": 72,
			"rotation": 0,
			"sprite": "Saksa"
		},
		{
			"name": "Tanska",
			"x": "Same:Saksa,Percent:15",
			"y": "Up:Saksa,Percent:16",
			"width": 71,
			"height": 39,
			"rotation": 0,
			"sprite": "Tanska"
		},
		{
			"name": "Alankomaat",
			"x": "Left:Saksa,Percent:43",
			"y": "Same:Saksa,Percent:-32",
			"width": 38,
			"height": 25,
			"rotation": 0,
			"sprite": "Alankomaat"
		},
		{
			"name": "Ranska",
			"x": "Left:Saksa,Percent:27",
			"y": "Down:Saksa,Percent:-40",
			"width": 120,
			"height": 82,
			"rotation": 0,
			"sprite": "Ranska"
		},
		{
			"name": "Belgia",
			"x": "Left:Saksa,Percent:10",
			"y": "Same:Saksa,Percent:50",
			"width": 28,
			"height": 18,
			"rotation": 0,
			"sprite": "Belgia"
		},
		{
			"name": "Italia",
			"x": "Same:Saksa,Percent:15",
			"y": "Down:Saksa,Percent:0",
			"width": 102,
			"height": 86,
			"rotation": 0,
			"sprite": "Italia"
		},
		{
			"name": "Romania",
			"x": "Same:Ukraina,Percent:-69",
			"y": "Down:Ukraina,Percent:-86",
			"width": 89,
			"height": 40,
			"rotation": 0,
			"sprite": "Romania"
		},
		{
			"name": "Moldova",
			"x": "Same:Ukraina,Percent:-89",
			"y": "Down:Ukraina,Percent:-135",
			"width": 33,
			"height": 29,
			"rotation": 0,
			"sprite": "Moldova"
		},
		{
			"name": "Sveitsi",
			"x": 400,
			"y": 400,
			"width": 88,
			"height": 36,
			"rotation": 0,
			"sprite": "Sveitsi"
		}
	]
};
return x;
}<|endoftext|>


<commit_before>pc.extend(pc.resources, function () {

    function onTextureAssetChanged (asset, attribute, newValue, oldValue) {
        if (attribute !== 'resource') {
            return;
        }

        var cubemapAsset = this;
        var cubemap = cubemapAsset.resource;
        if (!cubemap)
            return;

        var sources = cubemap.getSource();
        var dirty = false;

        if (oldValue) {
            var oldImage = oldValue.getSource();
            for (var i = 0; i < sources.length; i++) {
                if (sources[i] === oldImage) {
                    sources[i] = newValue.getSource();
                    dirty = true;
                }
            }
        }

        if (dirty) {
            cubemap.setSource(sources);
            // fire 'change' event so dependent materials can update
            var old = cubemapAsset.resources.slice(0);
            cubemapAsset.fire('change', cubemapAsset, 'resources', cubemapAsset.resources, old);
        } else {
            asset.off('change', onTextureAssetChanged, cubemap);
        }
    }

    var CubemapResourceHandler = function (device, assets, loader) {
        this._device = device;
        this._assets = assets;
    };
    CubemapResourceHandler = pc.inherits(CubemapResourceHandler, pc.resources.ResourceHandler);

    CubemapResourceHandler.prototype.load = function (request, options) {
        var self = this;
        var promise = null;
        var asset = self._getAssetFromRequest(request);

        if (pc.string.startsWith(request.canonical, "asset://")) {
            // Loading from asset (platform)
            promise = new pc.promise.Promise(function (resolve, reject) {
                if (!asset) {
                    reject(pc.string.format("Can't load cubemap, asset {0} not found", request.canonical));
                }

                var promises = [];

                // load 6 images
                promises.push(self._loadCubemapImages(asset));

                // load prefiltered data
                var url = asset.getFileUrl();
                if (url && pc.string.endsWith(url.toLowerCase(), '.dds')) {
                    promises.push(self._assets.loader.request(new pc.resources.TextureRequest(url)));
                }

                pc.promise.all(promises).then(function (resources) {
                    var data = pc.extend({}, asset.data);

                    // images
                    data.loadedTextures = resources[0];

                    // prefiltered
                    if (resources.length > 1) {
                        var prefiltered = resources[1][0];
                        data.loadedTextures.push(prefiltered);
                    }

                    resolve(data);
                }, function (error) {
                    reject(error);
                });
            });
        } else {
            // Loading from URL (engine-only)
            // Load cubemap data from a file (as opposed to from an asset)
            promise = new pc.promise.Promise(function (resolve, reject) {
                // load .json file
                pc.net.http.get(request.canonical, function(response) {
                    var data = pc.extend({}, response);

                    var textures = data.textures;
                    if (textures.length) {
                        // Create and load all referenced textures
                        var assets = [];
                        textures.forEach(function (path) {
                             var filename = pc.path.getBasename(path);
                             var url = pc.path.join(pc.path.split(request.canonical)[0], path);
                             assets.push(new pc.asset.Asset(filename, 'texture', {
                                 url: url
                             }));
                        });

                        var promises = [];

                        promises.push(self._assets.load(assets));

                        if (data.prefiltered) {
                            var url = pc.path.join(pc.path.split(request.canonical)[0], data.prefiltered);
                            promises.push(self._assets.loader.request(new pc.resources.TextureRequest(url)));
                        }

                        pc.promise.all(promises).then(function (resources) {
                            data.loadedTextures = resources[0];
                            data.loadedTextures.push(resources[1][0]);
                            resolve(data);
                        }, function (error) {
                            reject(error);
                        });

                    } else {
                        resolve(data);
                    }
                }, {
                    error: function (error) {
                        reject('Could not load cubemap json: ' +  error);
                    }
                });
            });
        }

        return promise;
    };

    CubemapResourceHandler.prototype.open = function (data, request, options) {
        var self = this;

        var asset = self._getAssetFromRequest(request);

        var resources = [];

        // load plain cubemap
        var cubemap = new pc.Texture(self._device, {
            format: pc.PIXELFORMAT_R8_G8_B8,
            cubemap: true,
            autoMipmap: true,
            fixCubemapSeams: true
        });

        cubemap.name = data.name;
        cubemap.minFilter = data.minFilter;
        cubemap.magFilter = data.magFilter;
        cubemap.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
        cubemap.addressV = pc.ADDRESS_CLAMP_TO_EDGE;
        cubemap.anisotropy = data.anisotropy;

        if (data.loadedTextures) {
            cubemap.setSource(data.loadedTextures.slice(0, 6).map(function (texture) {
                return texture.getSource();
            }));
        }

        resources.push(cubemap);

        // load prefiltered cubemap
        if (data.loadedTextures && data.loadedTextures.length > 6) {
            var prefiltered = data.loadedTextures[6];
            var mipSize = 128;

            for (i = 0; i < 6; i++) {
                // create a cubemap for each mip in the prefiltered cubemap
                var mip = new pc.gfx.Texture(self._device, {
                    cubemap: true,
                    fixCubemapSeams: true,
                    autoMipmap: true,
                    format: prefiltered.format,
                    rgbm: prefiltered.rgbm,
                    width: mipSize,
                    height: mipSize
                });

                mipSize *= 0.5;
                mip._levels[0] = prefiltered._levels[i];
                mip.upload();
                resources.push(mip);
            }
        }

        asset.off('change', self._onCubemapAssetChanged, self);
        asset.on('change', self._onCubemapAssetChanged, self);

        return resources;
    };

    CubemapResourceHandler.prototype._onCubemapAssetChanged = function (asset, attribute, value, oldValue) {
        var self = this;

        // make sure we update the cubemap if the asset changes
        // if a cubemap changes we fire a 'change' event for
        // the cubemapAsset.resource property so materials who reference
        // this cubemap can update
        if (attribute === 'data') {
            var texturesChanged = false;
            if (value.textures.length !== oldValue.textures.length) {
                texturesChanged = true;
            } else {
                for (var i = 0; i < value.textures.length; i++) {
                    if (value.textures[i] !== oldValue.textures[i]) {
                        texturesChanged = true;
                        break;
                    }
                }
            }

            if (texturesChanged) {
                self._loadCubemapImages(asset).then(function (resources) {
                    // copy array
                    var old = asset.resources.slice(0);

                    if (resources) {
                        asset.resource.setSource(resources.map(function (texture) {
                            return texture.getSource();
                        }));
                        asset.fire('change', asset, 'resources', asset.resources, old);
                    }
                });
            }

            asset.resource.minFilter = value.minFilter;
            asset.resource.magFilter = value.magFilter;
            asset.resource.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
            asset.resource.addressV = pc.ADDRESS_CLAMP_TO_EDGE;
            asset.resource.anisotropy = value.anisotropy;
            asset.resource.upload();

        } else if (attribute === 'file') {

            // Clean up asset registry. Not very nice to this this here
            if (oldValue) {
                url = oldValue.url;
                delete self._assets._urls[url];
                self._assets.loader.removeFromCache(url);
                self._assets.loader.unregisterHash(url);
            }

            if (value) {
                // Get new asset url
                url = asset.getFileUrl();

                // Register new url. Clearly asset registry stuff
                // but do it here for now.
                self._assets._urls[url] = asset.id;
                self._assets.loader.registerHash(value.hash, url);

                // reload prefiltered cubemaps
                self._assets.loader.request(new pc.resources.TextureRequest(url)).then(function (resources) {
                    var prefiltered = resources[0];

                    var mipSize = 128;

                    var old = asset.resources.slice(0);

                    asset.resources = [asset.resource];

                    for (i = 0; i < 6; i++) {
                        // create a cubemap for each mip in the prefiltered cubemap
                        var mip = new pc.gfx.Texture(self._device, {
                            cubemap: true,
                            fixCubemapSeams: true,
                            autoMipmap: true,
                            format: prefiltered.format,
                            rgbm: prefiltered.rgbm,
                            width: mipSize,
                            height: mipSize
                        });

                        mipSize *= 0.5;
                        mip._levels[0] = prefiltered._levels[i];
                        mip.upload();
                        asset.resources.push(mip);
                    }

                    asset.fire('change', asset, 'resources', asset.resources, old);
                }, function (error) {
                    console.error('Could not load prefiltered cubemap: ' + error);
                });
            } else {
                // clear old prefiltered cubemaps
                var old = asset.resources.slice(0);
                asset.resources = [asset.resource];
                asset.fire('change', asset, 'resources', asset.resources, old);
            }
        }
    };

    // Checks if there are 6 non-null images with the correct dimensions in the specified array
    CubemapResourceHandler.prototype._areValidImages = function (images) {
        var result = images && images.length === 6;
        var error;

        if (result) {
            var width = images[0] ? images[0].width : null;
            var height = images[0] ? images[0].height : null;

            for (var i = 0; i < 6; i++) {
                if (!images[i]) {
                    result = false;
                    break;
                }

                if ((!images[i] instanceof HTMLCanvasElement) ||
                    (!images[i] instanceof HTMLImageElement) ||
                    (!images[i] instanceof HTMLVideoElement)) {
                    error = 'Cubemap source is not an instance of HTMLCanvasElement, HTMLImageElement or HTMLVideoElement.';
                    result = false;
                    break;
                }

                if (images[i].width !== width  || images[i].height !== height) {
                    error = 'Cubemap sources do not all share the same dimensions.';
                    result = false;
                    break;
                }
            }

        }

        if (error) {
            alert(error);
        }

        return result;
    };

    // Loads the images of the cubemap - Returns a promise
    CubemapResourceHandler.prototype._loadCubemapImages = function (cubemapAsset) {
        var data = cubemapAsset.data;

        var self = this;

        var promise = new pc.promise.Promise(function (resolve, reject) {
            if (data.textures) {
                var assets = [];

                // check if we have 6 assets
                for (var i = 0; i < 6; i++) {
                    var id = parseInt(data.textures[i], 10);
                    if (id >= 0) {
                        var asset = self._assets.getAssetById(id);
                        if (!asset) {
                            reject(pc.string.format('Could not load cubemap - Texture {0} not found', data.textures[i]));
                            return;
                        }

                        assets.push(asset);
                    } else {
                        // one texture is missing so just return
                        resolve(null);
                        return;
                    }
                }

                self._assets.load(assets).then(function (resources) {
                    resolve(resources);

                    assets.forEach(function (asset) {
                        asset.off('change', onTextureAssetChanged, cubemapAsset);
                        asset.on('change', onTextureAssetChanged, cubemapAsset);
                    });
                }, function (error) {
                    reject(error);
                });
            } else {
                // no textures provided so just return
                resolve(null);
                return;
            }
        });

        return promise;
    };

    CubemapResourceHandler.prototype._getAssetFromRequest = function (request) {
        if (pc.string.startsWith(request.canonical, "asset://")) {
            return this._assets.getAssetById(parseInt(request.canonical.slice(8)));
        } else {
            return this._assets.getAssetByUrl(request.canonical);
        }
    };

    var CubemapRequest = function (identifier) {
    };
    CubemapRequest = pc.inherits(CubemapRequest, pc.resources.ResourceRequest);
    CubemapRequest.prototype.type = "cubemap";
    CubemapRequest.prototype.Type = pc.Texture;

    return {
        CubemapResourceHandler: CubemapResourceHandler,
        CubemapRequest: CubemapRequest
    };
}())    ;
<commit_msg>Convert texture paths to asset ids<commit_after>pc.extend(pc.resources, function () {

    function onTextureAssetChanged (asset, attribute, newValue, oldValue) {
        if (attribute !== 'resource') {
            return;
        }

        var cubemapAsset = this;
        var cubemap = cubemapAsset.resource;
        if (!cubemap)
            return;

        var sources = cubemap.getSource();
        var dirty = false;

        if (oldValue) {
            var oldImage = oldValue.getSource();
            for (var i = 0; i < sources.length; i++) {
                if (sources[i] === oldImage) {
                    sources[i] = newValue.getSource();
                    dirty = true;
                }
            }
        }

        if (dirty) {
            cubemap.setSource(sources);
            // fire 'change' event so dependent materials can update
            var old = cubemapAsset.resources.slice(0);
            cubemapAsset.fire('change', cubemapAsset, 'resources', cubemapAsset.resources, old);
        } else {
            asset.off('change', onTextureAssetChanged, cubemap);
        }
    }

    var CubemapResourceHandler = function (device, assets, loader) {
        this._device = device;
        this._assets = assets;
    };
    CubemapResourceHandler = pc.inherits(CubemapResourceHandler, pc.resources.ResourceHandler);

    CubemapResourceHandler.prototype.load = function (request, options) {
        var self = this;
        var promise = null;
        var asset = self._getAssetFromRequest(request);

        if (pc.string.startsWith(request.canonical, "asset://")) {
            // Loading from asset (platform)
            promise = new pc.promise.Promise(function (resolve, reject) {
                if (!asset) {
                    reject(pc.string.format("Can't load cubemap, asset {0} not found", request.canonical));
                }

                var promises = [];

                // load 6 images
                promises.push(self._loadCubemapImages(asset));

                // load prefiltered data
                var url = asset.getFileUrl();
                if (url && pc.string.endsWith(url.toLowerCase(), '.dds')) {
                    promises.push(self._assets.loader.request(new pc.resources.TextureRequest(url)));
                }

                pc.promise.all(promises).then(function (resources) {
                    var data = pc.extend({}, asset.data);

                    // images
                    data.loadedTextures = resources[0];

                    // prefiltered
                    if (resources.length > 1) {
                        var prefiltered = resources[1][0];
                        data.loadedTextures.push(prefiltered);
                    }

                    resolve(data);
                }, function (error) {
                    reject(error);
                });
            });
        } else {
            // Loading from URL (engine-only)
            // Load cubemap data from a file (as opposed to from an asset)
            promise = new pc.promise.Promise(function (resolve, reject) {
                // load .json file
                pc.net.http.get(request.canonical, function(response) {
                    var data = pc.extend({}, response);

                    var textures = data.textures;
                    if (textures.length) {
                        // Create and load all referenced textures
                        var assets = [];
                        textures.forEach(function (path) {
                             var filename = pc.path.getBasename(path);
                             var url = pc.path.join(pc.path.split(request.canonical)[0], path);
                             assets.push(new pc.asset.Asset(filename, 'texture', {
                                 url: url
                             }));
                        });

                        // convert textures to asset ids
                        data.textures = assets.map(function (asset) {
                            return asset.id;
                        });

                        var promises = [];

                        promises.push(self._assets.load(assets));

                        if (data.prefiltered) {
                            var url = pc.path.join(pc.path.split(request.canonical)[0], data.prefiltered);
                            promises.push(self._assets.loader.request(new pc.resources.TextureRequest(url)));
                        }

                        pc.promise.all(promises).then(function (resources) {
                            data.loadedTextures = resources[0];
                            data.loadedTextures.push(resources[1][0]);
                            resolve(data);
                        }, function (error) {
                            reject(error);
                        });

                    } else {
                        resolve(data);
                    }
                }, {
                    error: function (error) {
                        reject('Could not load cubemap json: ' +  error);
                    }
                });
            });
        }

        return promise;
    };

    CubemapResourceHandler.prototype.open = function (data, request, options) {
        var self = this;

        var asset = self._getAssetFromRequest(request);

        var resources = [];

        // load plain cubemap
        var cubemap = new pc.Texture(self._device, {
            format: pc.PIXELFORMAT_R8_G8_B8,
            cubemap: true,
            autoMipmap: true,
            fixCubemapSeams: true
        });

        cubemap.name = data.name;
        cubemap.minFilter = data.minFilter;
        cubemap.magFilter = data.magFilter;
        cubemap.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
        cubemap.addressV = pc.ADDRESS_CLAMP_TO_EDGE;
        cubemap.anisotropy = data.anisotropy;

        if (data.loadedTextures) {
            cubemap.setSource(data.loadedTextures.slice(0, 6).map(function (texture) {
                return texture.getSource();
            }));
        }

        resources.push(cubemap);

        // load prefiltered cubemap
        if (data.loadedTextures && data.loadedTextures.length > 6) {
            var prefiltered = data.loadedTextures[6];
            var mipSize = 128;

            for (i = 0; i < 6; i++) {
                // create a cubemap for each mip in the prefiltered cubemap
                var mip = new pc.gfx.Texture(self._device, {
                    cubemap: true,
                    fixCubemapSeams: true,
                    autoMipmap: true,
                    format: prefiltered.format,
                    rgbm: prefiltered.rgbm,
                    width: mipSize,
                    height: mipSize
                });

                mipSize *= 0.5;
                mip._levels[0] = prefiltered._levels[i];
                mip.upload();
                resources.push(mip);
            }
        }

        asset.off('change', self._onCubemapAssetChanged, self);
        asset.on('change', self._onCubemapAssetChanged, self);

        return resources;
    };

    CubemapResourceHandler.prototype._onCubemapAssetChanged = function (asset, attribute, value, oldValue) {
        var self = this;

        // make sure we update the cubemap if the asset changes
        // if a cubemap changes we fire a 'change' event for
        // the cubemapAsset.resource property so materials who reference
        // this cubemap can update
        if (attribute === 'data') {
            var texturesChanged = false;
            if (value.textures.length !== oldValue.textures.length) {
                texturesChanged = true;
            } else {
                for (var i = 0; i < value.textures.length; i++) {
                    if (value.textures[i] !== oldValue.textures[i]) {
                        texturesChanged = true;
                        break;
                    }
                }
            }

            if (texturesChanged) {
                self._loadCubemapImages(asset).then(function (resources) {
                    // copy array
                    var old = asset.resources.slice(0);

                    if (resources) {
                        asset.resource.setSource(resources.map(function (texture) {
                            return texture.getSource();
                        }));
                        asset.fire('change', asset, 'resources', asset.resources, old);
                    }
                });
            }

            asset.resource.minFilter = value.minFilter;
            asset.resource.magFilter = value.magFilter;
            asset.resource.addressU = pc.ADDRESS_CLAMP_TO_EDGE;
            asset.resource.addressV = pc.ADDRESS_CLAMP_TO_EDGE;
            asset.resource.anisotropy = value.anisotropy;
            asset.resource.upload();

        } else if (attribute === 'file') {

            // Clean up asset registry. Not very nice to this this here
            if (oldValue) {
                url = oldValue.url;
                delete self._assets._urls[url];
                self._assets.loader.removeFromCache(url);
                self._assets.loader.unregisterHash(url);
            }

            if (value) {
                // Get new asset url
                url = asset.getFileUrl();

                // Register new url. Clearly asset registry stuff
                // but do it here for now.
                self._assets._urls[url] = asset.id;
                self._assets.loader.registerHash(value.hash, url);

                // reload prefiltered cubemaps
                self._assets.loader.request(new pc.resources.TextureRequest(url)).then(function (resources) {
                    var prefiltered = resources[0];

                    var mipSize = 128;

                    var old = asset.resources.slice(0);

                    asset.resources = [asset.resource];

                    for (i = 0; i < 6; i++) {
                        // create a cubemap for each mip in the prefiltered cubemap
                        var mip = new pc.gfx.Texture(self._device, {
                            cubemap: true,
                            fixCubemapSeams: true,
                            autoMipmap: true,
                            format: prefiltered.format,
                            rgbm: prefiltered.rgbm,
                            width: mipSize,
                            height: mipSize
                        });

                        mipSize *= 0.5;
                        mip._levels[0] = prefiltered._levels[i];
                        mip.upload();
                        asset.resources.push(mip);
                    }

                    asset.fire('change', asset, 'resources', asset.resources, old);
                }, function (error) {
                    console.error('Could not load prefiltered cubemap: ' + error);
                });
            } else {
                // clear old prefiltered cubemaps
                var old = asset.resources.slice(0);
                asset.resources = [asset.resource];
                asset.fire('change', asset, 'resources', asset.resources, old);
            }
        }
    };

    // Checks if there are 6 non-null images with the correct dimensions in the specified array
    CubemapResourceHandler.prototype._areValidImages = function (images) {
        var result = images && images.length === 6;
        var error;

        if (result) {
            var width = images[0] ? images[0].width : null;
            var height = images[0] ? images[0].height : null;

            for (var i = 0; i < 6; i++) {
                if (!images[i]) {
                    result = false;
                    break;
                }

                if ((!images[i] instanceof HTMLCanvasElement) ||
                    (!images[i] instanceof HTMLImageElement) ||
                    (!images[i] instanceof HTMLVideoElement)) {
                    error = 'Cubemap source is not an instance of HTMLCanvasElement, HTMLImageElement or HTMLVideoElement.';
                    result = false;
                    break;
                }

                if (images[i].width !== width  || images[i].height !== height) {
                    error = 'Cubemap sources do not all share the same dimensions.';
                    result = false;
                    break;
                }
            }

        }

        if (error) {
            alert(error);
        }

        return result;
    };

    // Loads the images of the cubemap - Returns a promise
    CubemapResourceHandler.prototype._loadCubemapImages = function (cubemapAsset) {
        var data = cubemapAsset.data;

        var self = this;

        var promise = new pc.promise.Promise(function (resolve, reject) {
            if (data.textures) {
                var assets = [];

                // check if we have 6 assets
                for (var i = 0; i < 6; i++) {
                    var id = parseInt(data.textures[i], 10);
                    if (id >= 0) {
                        var asset = self._assets.getAssetById(id);
                        if (!asset) {
                            reject(pc.string.format('Could not load cubemap - Texture {0} not found', data.textures[i]));
                            return;
                        }

                        assets.push(asset);
                    } else {
                        // one texture is missing so just return
                        resolve(null);
                        return;
                    }
                }

                self._assets.load(assets).then(function (resources) {
                    resolve(resources);

                    assets.forEach(function (asset) {
                        asset.off('change', onTextureAssetChanged, cubemapAsset);
                        asset.on('change', onTextureAssetChanged, cubemapAsset);
                    });
                }, function (error) {
                    reject(error);
                });
            } else {
                // no textures provided so just return
                resolve(null);
                return;
            }
        });

        return promise;
    };

    CubemapResourceHandler.prototype._getAssetFromRequest = function (request) {
        if (pc.string.startsWith(request.canonical, "asset://")) {
            return this._assets.getAssetById(parseInt(request.canonical.slice(8)));
        } else {
            return this._assets.getAssetByUrl(request.canonical);
        }
    };

    var CubemapRequest = function (identifier) {
    };
    CubemapRequest = pc.inherits(CubemapRequest, pc.resources.ResourceRequest);
    CubemapRequest.prototype.type = "cubemap";
    CubemapRequest.prototype.Type = pc.Texture;

    return {
        CubemapResourceHandler: CubemapResourceHandler,
        CubemapRequest: CubemapRequest
    };
}())    ;
<|endoftext|>


<commit_before>function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof(window.onload) != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function buildMapIt(map_div, points, options) {
  buildLatLng(points);
  var map_type = options['map_type'] || google.maps.MapTypeId.ROADMAP
  var myOptions = {
    zoom: 10,
    center: points[0]["latlng"],
    mapTypeId: map_type
  };

  var map = new google.maps.Map(document.getElementById(map_div), myOptions);

  var markers = buildMarkers(points, map)
  var bounds = findCenterPoint(points)
  map.fitBounds(bounds);
}

function buildLatLng(map_points) {
  for(i = 0; i < map_points.length; i++) {
    map_points[i]["latlng"] = new google.maps.LatLng(map_points[i]["latitude"],map_points[i]["longitude"]);
  }
}

function findCenterPoint(map_points) {
  bounds = new google.maps.LatLngBounds();
  for(i = 0; i < map_points.length; i++) {
    bounds.extend(map_points[i]["latlng"]);
  }
  return bounds
}

function buildMarkers(map_points, map) {
  var markers = new Array();
  for(i = 0; i < map_points.length; i++) {
    name = map_points[i]["info"];
    markers[i] = new google.maps.Marker({
        position: map_points[i]["latlng"],
        map: map,
        title: name
    });
    addInfoWindow(name, markers[i], map_points[i]["id"], map);
  }
  return markers;
}

function addInfoWindow(name, marker, id, map) {
  eval("infoWindow_" + id + "= function() { infowindow = new google.maps.InfoWindow({content: name}); infowindow.open(map, marker); }" );
  google.maps.event.addListener(marker, "click", eval("infoWindow_" + id) );
}<commit_msg>Add label support to the js side.<commit_after>function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof(window.onload) != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

function buildMapIt(map_div, points, options) {
  buildLatLng(points);
  var map_type = options['map_type'] || google.maps.MapTypeId.ROADMAP;
  var label = options['labels'] || false;
  var map_type_control = options['map_type_control'] || true
  var map_type_control_options_style = options['map_type_control_options']['style'] || google.maps.MapTypeControlStyle.DROP_DOWN
  var myOptions = {
    zoom: 10,
    center: points[0]["latlng"],
    mapTypeId: map_type,
    mapTypeControl: map_type_control,
    mapTypeControlOptions: {
      style: map_type_control_options_style
    }
  };

  var map = new google.maps.Map(document.getElementById(map_div), myOptions);

  var markers = buildMarkers(points, map, label)
  var bounds = findCenterPoint(points)
  map.fitBounds(bounds);
}

function buildLatLng(map_points) {
  for(i = 0; i < map_points.length; i++) {
    map_points[i]["latlng"] = new google.maps.LatLng(map_points[i]["latitude"],map_points[i]["longitude"]);
  }
}

function findCenterPoint(map_points) {
  bounds = new google.maps.LatLngBounds();
  for(i = 0; i < map_points.length; i++) {
    bounds.extend(map_points[i]["latlng"]);
  }
  return bounds
}

function buildMarkers(map_points, map, label) {
  var markers = new Array();
  for(i = 0; i < map_points.length; i++) {
    name = map_points[i]["info"];
    options = {
        position: map_points[i]["latlng"],
        map: map,
        title: name,
        icon: addLabels(map_points[i], label),
        shadow: addShadows(map_points[i], label)
    }
    markers[i] = new google.maps.Marker(options);
    addInfoWindow(name, markers[i], map_points[i]["id"], map);
  }
  return markers;
}

function addLabels(map_point, label) {
  if (label == true) {
    url = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld="+ map_point["letter"] +"|f97569|000000",
            new google.maps.Size(20, 34),
            new google.maps.Point(0, 0),
            new google.maps.Point(10, 34)
          );
  } else {
    url = null
  }
  return url
}

function addShadows(map_point, label) {
  if (label == true) {
    url = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
            new google.maps.Size(40, 37),
            new google.maps.Point(0, 0),
            new google.maps.Point(10, 37)
          );
  } else {
    url = null
  }
  return url
}

function addInfoWindow(name, marker, id, map) {
  eval("infoWindow_" + id + "= function() { infowindow = new google.maps.InfoWindow({content: name}); infowindow.open(map, marker); }" );
  google.maps.event.addListener(marker, "click", eval("infoWindow_" + id) );
}<|endoftext|>


<commit_before>$(function() {
  var canvas = $('#canvas')[0];
  var ctx = canvas.getContext('2d');
  var bgURL = 'https://images6.alphacoders.com/392/392895.jpg';
  redraw();

  function redraw() {
    var drawbg = bgURL ? drawImage(bgURL, { opacity: 0.4 }) : function(){ return $.Deferred().resolve().promise() };
    var drawlogo = drawImage('assets/images/fbpost_overlay.png');

    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, 1920, 1080);

    drawbg().then(drawlogo).done(function() {
      var centerX = 960;
      ctx.save();
      ctx.font = "bold 80px '微軟正黑體'";
      ctx.fillStyle = 'white';
      ctx.textAlign = 'center'
      ctx.textBaseline = 'top';
      //ctx.fillText('TACL S4 9/20 賽程表', centerX, 50);

      textGlow('TACL S4 9/20 賽程表', centerX, 50, 'white', '#00ccff', 50, 1);

      var halfSpace = -70;
      var playerSpace = 80;
      var halfCenters = [480 - halfSpace, 1440 + halfSpace];

      for (var half = 0; half < 2; half++) {
        centerX = halfCenters[half];
        var clans = getClans();
        ctx.font = "bold 75px '微軟正黑體'";
        ctx.textAlign = 'right';
        textGlow(clans[0], centerX-80, 180, 'white', '#00ccff', 50, 1);
        ctx.textAlign = 'left';
        textGlow(clans[1], centerX+80, 180, 'white', '#00ccff', 50, 1);
        ctx.textAlign = 'center';
        ctx.fillStyle = '#11cfff';
        textGlow('vs', centerX, 180, '11ccff', '#00ccff', 50, 1);

        for (var i = 0; i < 4; i++) {
          var players = getPlayers();
          ctx.fillStyle = 'white';
          ctx.font = "45px '微軟正黑體'";
          ctx.textAlign = 'right';
          textGlow(players[0], centerX - playerSpace, 320 + i * 150, 'white', '#00ccff', 50, 1);
          drawImage(getRaceImg(), { left: centerX - playerSpace, top: 320 + i * 150, width:65, height: 65, opacity: 0.75, glow: '#00ccff'})();
          ctx.textAlign = 'left';
          textGlow(players[1], centerX + playerSpace, 320 + i * 150, 'white', '#00ccff', 50, 1);
          drawImage(getRaceImg(), { left: centerX + playerSpace - 65, top: 320 + i * 150, width:65, height: 65, opacity: 0.75, glow: '#00ccff'})();

          ctx.textAlign = 'center';

          ctx.font = "35px '微軟正黑體'";
          var map = getMap();
          textGlow(map.name + ' ' + map.en, centerX, 390 + i * 150, '#11ccff', '#000', 50, 1);
        }
      }
    });
  }
  function textGlow(text, x, y, color, glowColor, blur, level) {
    ctx.save();
    ctx.shadowColor = glowColor;
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = 0;
    ctx.shadowBlur = blur;
    for (var i = 0; i < level; i++) {
      ctx.fillText(text, x, y);
    }
    ctx.fillStyle = color;
    ctx.fillText(text, x, y);
    ctx.restore();
  }
  function getClans() {
    var clans = ['Rush', 'StroM', 'TDT', 'Milles', 'SPTS'];
    var c1 = Math.floor(Math.random() * clans.length);
    do {
      var c2 =  Math.floor(Math.random() * clans.length);
    } while (c1 === c2);
    return [clans[c1], clans[c2]];
  }
  function getMap() {
    var maps = [
      { name: '銀河天堂路', en: 'Galactic Process' },
      { name: '新蓋茨堡', en: 'New GettysBurg' },
      { name: '世宗研究站', en: 'King Sejong Station' },
      { name: '茶山科學研究站', en: 'Dason Station' },
      { name: '冰霜之地', en: 'Frost' },
      { name: '冰凍神殿', en: 'Frozen Temple' }
    ];
    var n = Math.floor(Math.random() * maps.length);
    return maps[n];
  }
  function getRaceImg() {
    var races = ['T', 'P', 'Z', 'R'];
    return 'assets/images/race' + races[Math.floor(Math.random() * races.length)] + '.png';
  }
  function getPlayers() {
    var players = ['KevinLiu', 'Shang', 'AntiRush', 'AzureRush', 'Yuin', '台中神秘力量', 'LolitaLife', '無盲點披薩',
      '老爺不要', '宋兄', 'AaCcEe', 'Ryuk', '煌無', '風夜影', '丁丁科', 'ImReady', '新手', 'groundbeef', 'top', 'LoTTo', 'Smile',
      '你少來給我這套', 'Gogokoey', 'TNLRush', 'StarATT', '秋雨梧桐葉落時'];
      var c1 = Math.floor(Math.random() * players.length);
      do {
        var c2 =  Math.floor(Math.random() * players.length);
      } while (c1 === c2);
      return [players[c1], players[c2]];
  }
  function drawImage(url, options) {
    return function() {
      var deferred = $.Deferred();
      var img = new Image;
      if (!options) options = {};
      img.onload = function(){
        ctx.save();
        if (options.opacity) {
          ctx.globalAlpha = options.opacity;
        }
        if (options.glow) {
          ctx.shadowColor = options.glow;
          ctx.shadowOffsetX = 0;
          ctx.shadowOffsetY = 0;
          ctx.shadowBlur = 20;
        }
        ctx.drawImage(img, options.left || 0, options.top || 0, options.width || 1920, options.height || 1080);
        ctx.restore();
        deferred.resolve();
      };
      img.src = url;
      return deferred.promise();
    }
  }
});
<commit_msg>fix style<commit_after>$(function() {
  var canvas = $('#canvas')[0];
  var ctx = canvas.getContext('2d');
  var bgURL = 'https://images6.alphacoders.com/392/392895.jpg';
  redraw();

  function redraw() {
    var drawbg = bgURL ? drawImage(bgURL, { opacity: 0.4 }) : function(){ return $.when(); };
    var drawlogo = drawImage('assets/images/fbpost_overlay.png');

    ctx.fillStyle = 'black';
    ctx.fillRect(0, 0, 1920, 1080);

    drawbg().done(function() {
      var centerX = 960;
      ctx.save();
      ctx.font = "bold 80px '微軟正黑體'";
      ctx.fillStyle = 'white';
      ctx.textAlign = 'center'
      ctx.textBaseline = 'top';
      //ctx.fillText('TACL S4 9/20 賽程表', centerX, 50);

      textGlow('TACL S4 9/20 賽程表', centerX, 50, 'white', '#00ccff', 50, 1);

      var halfSpace = -70;
      var playerSpace = 80;
      var halfCenters = [480 - halfSpace, 1440 + halfSpace];

      for (var half = 0; half < 2; half++) {
        centerX = halfCenters[half];
        var clans = getClans();
        ctx.font = "bold 75px '微軟正黑體'";
        ctx.textAlign = 'right';
        textGlow(clans[0], centerX-80, 180, 'white', '#00ccff', 30, 1);
        ctx.textAlign = 'left';
        textGlow(clans[1], centerX+80, 180, 'white', '#00ccff', 30, 1);
        ctx.textAlign = 'center';
        ctx.fillStyle = '#11cfff';
        textGlow('vs', centerX, 180, '11ccff', '#00ccff', 50, 1);

        for (var i = 0; i < 4; i++) {
          var players = getPlayers();
          ctx.fillStyle = 'white';
          ctx.font = "45px '微軟正黑體'";
          ctx.textAlign = 'right';
          textGlow(players[0], centerX - playerSpace, 320 + i * 150, 'white', '#00ccff', 20, 0);
          drawImage(getRaceImg(), { left: centerX - playerSpace, top: 320 + i * 150, width:65, height: 65, opacity: 0.75, glow: '#00ccff'})();
          ctx.textAlign = 'left';
          textGlow(players[1], centerX + playerSpace, 320 + i * 150, 'white', '#00ccff', 20, 0);
          drawImage(getRaceImg(), { left: centerX + playerSpace - 65, top: 320 + i * 150, width:65, height: 65, opacity: 0.75, glow: '#00ccff'})();

          ctx.textAlign = 'center';

          ctx.font = "35px '微軟正黑體'";
          var map = getMap();
          textGlow(map.name + ' ' + map.en, centerX, 390 + i * 150, '#11ccff', '#00ffff', 20, 0);
        }
      }
      drawlogo();
    });
  }
  function textGlow(text, x, y, color, glowColor, blur, level) {
    ctx.save();
    ctx.shadowColor = glowColor;
    ctx.shadowOffsetX = 0;
    ctx.shadowOffsetY = 0;
    ctx.shadowBlur = blur;
    ctx.fillStyle = color;
    for (var i = 0; i < level; i++) {
      ctx.fillText(text, x, y);
    }
    ctx.fillText(text, x, y);
    ctx.restore();
  }
  function getClans() {
    var clans = ['Rush', 'StroM', 'TDT', 'Milles', 'SPTS'];
    var c1 = Math.floor(Math.random() * clans.length);
    do {
      var c2 =  Math.floor(Math.random() * clans.length);
    } while (c1 === c2);
    return [clans[c1], clans[c2]];
  }
  function getMap() {
    var maps = [
      { name: '銀河天堂路', en: 'Galactic Process' },
      { name: '新蓋茨堡', en: 'New GettysBurg' },
      { name: '世宗研究站', en: 'King Sejong Station' },
      { name: '茶山科學研究站', en: 'Dason Station' },
      { name: '冰霜之地', en: 'Frost' },
      { name: '冰凍神殿', en: 'Frozen Temple' }
    ];
    var n = Math.floor(Math.random() * maps.length);
    return maps[n];
  }
  function getRaceImg() {
    var races = ['T', 'P', 'Z', 'R'];
    return 'assets/images/race' + races[Math.floor(Math.random() * races.length)] + '.png';
  }
  function getPlayers() {
    var players = ['KevinLiu', 'Shang', 'AntiRush', 'AzureRush', 'Yuin', '台中神秘力量', 'LolitaLife', '無盲點披薩',
      '老爺不要', '宋兄', 'AaCcEe', 'Ryuk', '煌無', '風夜影', '丁丁科', 'ImReady', '新手', 'groundbeef', 'top', 'LoTTo', 'Smile',
      '你少來給我這套', 'Gogokoey', 'TNLRush', 'StarATT', '秋雨梧桐葉落時'];
      var c1 = Math.floor(Math.random() * players.length);
      do {
        var c2 =  Math.floor(Math.random() * players.length);
      } while (c1 === c2);
      return [players[c1], players[c2]];
  }
  function drawImage(url, options) {
    return function() {
      var deferred = $.Deferred();
      var img = new Image;
      if (!options) options = {};
      img.onload = function(){
        ctx.save();
        if (options.opacity) {
          ctx.globalAlpha = options.opacity;
        }
        if (options.glow) {
          ctx.shadowColor = options.glow;
          ctx.shadowOffsetX = 0;
          ctx.shadowOffsetY = 0;
          ctx.shadowBlur = 20;
        }
        ctx.drawImage(img, options.left || 0, options.top || 0, options.width || 1920, options.height || 1080);
        ctx.restore();
        deferred.resolve();
      };
      img.src = url;
      return deferred.promise();
    }
  }
});
<|endoftext|>


<commit_before>/*

Slinky
A light-weight, responsive, mobile-like menu plugin for jQuery
Made by Ali Zahid
Published under the MIT license

*/

;(function ($) {
	$.fn.slinky = function (options) {
		// Setup plugin defaults

		var settings = $.extend({
			label: 'Back',
			speed: 300,
			resize: true
		}, options);

		// Convenience method for navigation animation

		var move = function (menu, next, callback) {
			var width = menu.outerWidth(),
				left = Math.round(Math.abs(parseInt(menu.css('left'))) / width) || 0;

			// Use multiples of 100% for responsive animation

			menu.stop(true, true).animate({
				left: -Math.abs((next ? ++left : --left) * 100) + '%'
			}, settings.speed, function () {
				// Callback after animation is finished

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

		// Convenience method for resizing menu

		var resize = function (menu, content) {
			menu.stop(true, true).animate({
				height: content.outerHeight()
			}, settings.speed);
		};

		return this.each(function () {
			// The root node is where animation happens

			var menu = $(this),
				root = menu.children().first();

			// Add .next class to links with sub menus

			$('a + ul', menu).prev().addClass('next');

			// Add back links with correct labels

			if (settings.label === true) {
				// Create a link with label from parent

				$('li > ul', menu).each(function () {
					var label = menu.parent().find('a').first().text(),
						backLink = $('<a>').text(label).prop('href', '#').addClass('back');

					menu.prepend(backLink);
				});
			} else {
				// Create a link with the label from settings

				var backLink = $('<a>').text(settings.label).prop('href', '#').addClass('back');

				$('li > ul', menu).prepend(backLink);
			}

			// Setup navigation

			$('a', menu).on('click', function (e) {
				var a = $(this);

				// Disable navigation if link has hash
				// else proceed to URL

				if (/#/.test(this.href)) {
					e.preventDefault();
				}

				// Animate forward or backward
				// Resize menu height to match content, if required

				if (a.hasClass('next')) {
					a.next().show();

					move(root, true);

					if (settings.resize) {
						resize(menu, a.next());
					}
				} else if (a.hasClass('back')) {
					move(root, false, function () {
						a.parent().hide();
					});

					if (settings.resize) {
						resize(menu, a.parent().parents('ul'));
					}
				}
			});
		});

		return this;
	};
}(jQuery));
<commit_msg>Bug fix<commit_after>/*

Slinky
A light-weight, responsive, mobile-like menu plugin for jQuery
Made by Ali Zahid
Published under the MIT license

*/

;(function ($) {
	$.fn.slinky = function (options) {
		// Setup plugin defaults

		var settings = $.extend({
			label: 'Back',
			speed: 300,
			resize: true
		}, options);

		// Convenience method for navigation animation

		var move = function (menu, next, callback) {
			var width = menu.outerWidth(),
				left = Math.round(parseInt(menu[0].style.left)) || 0;

			// Use multiples of 100% for responsive animation

			menu.stop(true, true).animate({
				left: -Math.abs(next ? left - 100 : left + 100) + '%'
			}, settings.speed, function () {
				// Callback after animation is finished

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

		// Convenience method for resizing menu

		var resize = function (menu, content) {
			menu.stop(true, true).animate({
				height: content.outerHeight()
			}, settings.speed);
		};

		return this.each(function () {
			// The root node is where animation happens

			var menu = $(this),
				root = menu.children().first();

			// Add .next class to links with sub menus

			$('a + ul', menu).prev().addClass('next');

			// Add back links with correct labels

			if (settings.label === true) {
				// Create a link with label from parent

				$('li > ul', menu).each(function () {
					var label = menu.parent().find('a').first().text(),
						backLink = $('<a>').text(label).prop('href', '#').addClass('back');

					menu.prepend(backLink);
				});
			} else {
				// Create a link with the label from settings

				var backLink = $('<a>').text(settings.label).prop('href', '#').addClass('back');

				$('li > ul', menu).prepend(backLink);
			}

			// Setup navigation

			$('a', menu).on('click', function (e) {
				var a = $(this);

				// Disable navigation if link has hash
				// else proceed to URL

				if (/#/.test(this.href)) {
					e.preventDefault();
				}

				// Animate forward or backward
				// Resize menu height to match content, if required

				if (a.hasClass('next')) {
					a.next().show();

					move(root, true);

					if (settings.resize) {
						resize(menu, a.next());
					}
				} else if (a.hasClass('back')) {
					move(root, false, function () {
						a.parent().hide();
					});

					if (settings.resize) {
						resize(menu, a.parent().parents('ul'));
					}
				}
			});
		});

		return this;
	};
}(jQuery));
<|endoftext|>


<commit_before>function change_row_state($orderid, $tr, $state, $lqty, $rqty, $tqty)
{
    if($tqty === undefined)
    {
        $lqty = -1;
        $rqty = -1;
        $tqty = -1;
    }
    var $id = $tr.attr("id"); // This will give Id of the item
    var $setstate = -1;
    switch ($state)
    {
        case "fz-success":
            $setstate = 1;
            break;
        case "edit":
            $setstate = 0;
            break;
        case "fz-danger":
            $setstate = 2;
            break;
        default:
            $setstate = -1;
    }

    $data = {};
    // If edit then also send new R,L and Total Qty
    if ($tr.attr("class")==="edit" && $state === "fz-success")
    {
        $data = {
            oiid: $id,
            oiomid: $orderid,
            oileftqty: $lqty,
            oirightqty: $rqty,
            oitotalqty: $tqty,
            status: $setstate
        };
    }
    else
    {
        $data = {
            oiid: $id,
            oiomid: $orderid,
            status: $setstate
        };
    }
    if ($tr.attr("class") != $state && $setstate != -1)
    {
        $.ajax({
                type: "POST",
                url: "../orders/order_item_state",
                dataType: 'json',
                data: $data,
                success: function(res)
                {
                    $tr.attr("class",$state);
                    console.log(res);
                }
            });
    }
}

$(document).ready(function()
{
    $('#print').click(function(event) {
        /* Act on the event */
        window.print();
    });
    // When Item is Ready.
    $('.done').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "fz-success";
        var lqty = parseInt(tr.children(".LQty").html());
        var rqty = parseInt(tr.children(".RQty").html());
        var tqty = parseInt(tr.children(".TQty").html());
        // Calling function
        change_row_state(orderid, tr, state, lqty, rqty, tqty);
        ////console.log(tqty);
    });
    // When Item is NOT Available
    $('.delete').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "fz-danger";
        // Calling function
        change_row_state(orderid, tr, state);
    });
    // When Item QTY needs to be changed.
    $('.edit').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "edit";
        // Calling function
        change_row_state(orderid, tr, state);
        // Make Qty columns editable
        $(this).nextAll('.RQty').attr("contenteditable","true");
        $(this).nextAll('.LQty').attr("contenteditable","true");
        $(this).nextAll('.TQty').attr("contenteditable",true);
    });
	// Store1 or store2 button clicked
	$("#OmStore1,#OmStore2").on('click',function(e)
	{
		var storeName = e.target.id;
		var orderId = $("#omid").attr("data-omid");
		var state = ($("#"+storeName).attr("data-state") == 0)? 1 : 0;
		var bgColor = (state == 0)? "#337ab7" : "#5cb85c";
		$.ajax({
                type: "POST",
                url: "../orders/set_store_state",
                dataType: 'json',
                data: {
					orderid: orderId,
					storename: storeName,
					status: state
				},
                success: function(res)
                {
					// primary color #337ab7 (blue color)
					//  success color #5cb85c (green color)
					$("#"+storeName).attr("data-state",state).css("background-color",bgColor); // Also need to chang class but cant figure how.
                }
            });

	});

});

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
<commit_msg>170426<commit_after>function change_row_state($orderid, $tr, $state, $lqty, $rqty, $tqty)
{
    if($tqty === undefined)
    {
        $lqty = -1;
        $rqty = -1;
        $tqty = -1;
    }
    var $id = $tr.attr("id"); // This will give Id of the item
    var $setstate = -1;
    switch ($state)
    {
        case "fz-success":
            $setstate = 1;
            break;
        case "edit":
            $setstate = 0;
            break;
        case "fz-danger":
            $setstate = 2;
            break;
        default:
            $setstate = -1;
    }

    $data = {};
    // If edit then also send new R,L and Total Qty
    if ($tr.attr("class")==="edit" && $state === "fz-success")
    {
        $data = {
            oiid: $id,
            oiomid: $orderid,
            oileftqty: $lqty,
            oirightqty: $rqty,
            oitotalqty: $tqty,
            status: $setstate
        };
    }
    else
    {
        $data = {
            oiid: $id,
            oiomid: $orderid,
            status: $setstate
        };
    }
    if ($tr.attr("class") != $state && $setstate != -1)
    {
        $.ajax({
                type: "POST",
                url: "../orders/order_item_state",
                dataType: 'json',
                data: $data,
                success: function(res)
                {
                    $tr.attr("class",$state);
                    console.log(res);
                }
            });
    }
}

$(document).ready(function()
{
    $('#print').click(function(event) {
        /* Act on the event */
        window.print();
    });
    // When Item is Ready.
    $('.done').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "fz-success";
        var lqty = parseInt(tr.children(".LQty").html());
        var rqty = parseInt(tr.children(".RQty").html());
        var tqty = parseInt(tr.children(".TQty").html());
        // Calling function
        change_row_state(orderid, tr, state, lqty, rqty, tqty);
        ////console.log(tqty);
    });
    // When Item is NOT Available
    $('.delete').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "fz-danger";
        // Calling function
        change_row_state(orderid, tr, state);
    });
    // When Item QTY needs to be changed.
    $('.edit').on('click',function()
    {
        // Setting up vars for function
		var txtedits = $('.edit-toggle');
		var bolisdisabled = $(this).attr('data-edit-state');
		txtedits.attr('disabled',!bolisdisabled);

		$(this).attr('data-edit-state','true');
		console.log(txtedits);
    });
	// Store1 or store2 button clicked
	$("#OmStore1,#OmStore2").on('click',function(e)
	{
		var storeName = e.target.id;
		var orderId = $("#omid").attr("data-omid");
		var state = ($("#"+storeName).attr("data-state") == 0)? 1 : 0;
		var bgColor = (state == 0)? "#337ab7" : "#5cb85c";
		$.ajax({
                type: "POST",
                url: "../orders/set_store_state",
                dataType: 'json',
                data: {
					orderid: orderId,
					storename: storeName,
					status: state
				},
                success: function(res)
                {
					// primary color #337ab7 (blue color)
					//  success color #5cb85c (green color)
					$("#"+storeName).attr("data-state",state).css("background-color",bgColor); // Also need to chang class but cant figure how.
                }
            });

	});

});

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
<|endoftext|>


<commit_before>$.fn.romoDropdown = function() {
  return $.map(this, function(element) {
    return new RomoDropdown(element);
  });
}

var RomoDropdown = function(element) {
  this.elem = $(element);
  this.popupElem = $('

');
  this.popupElem.appendTo('body');
  this.doSetPopupZIndex(this.elem);
  this.bodyElem = this.popupElem.find('> .romo-dropdown-body');
  this.contentElem = $();
  this.romoInvoke = this.elem.romoInvoke()[0];

  var positionData = this._parsePositionData(this.elem.data('romo-dropdown-position'));
  this.popupPosition  = positionData.position  || 'bottom';
  this.popupAlignment = positionData.alignment || 'left';
  this.popupElem.attr('data-romo-dropdown-position',  this.popupPosition);
  this.popupElem.attr('data-romo-dropdown-alignment', this.popupAlignment);
  this.popupElem.attr('data-romo-dropdown-fixed', this.elem.data('romo-dropdown-fixed'));
  // don't propagate click events on the popup elem.  this prevents the popup
  // from closing when clicked (see body click event bind on popup open)
  this.popupElem.on('click', function(e) {
    if (e !== undefined) {
      e.stopPropagation();
    }
  })

  if (this.elem.data('romo-dropdown-style-class') !== undefined) {
    this.bodyElem.addClass(this.elem.data('romo-dropdown-style-class'));
  }

  this.elem.unbind('click');
  this.elem.on('click', $.proxy(this.onToggleClick, this));
  this.elem.on('dropdown:triggerToggle', $.proxy(this.onToggleClick, this));
  this.elem.on('dropdown:triggerPopupOpen', $.proxy(this.onPopupOpen, this));
  this.elem.on('dropdown:triggerPopupClose', $.proxy(this.onPopupClose, this));
  this.elem.on('invoke:loadStart', $.proxy(function(e, invoke) {
    this.doLoadBodyStart();
  }, this));
  this.elem.on('invoke:loadSuccess', $.proxy(function(e, data, invoke) {
    this.doLoadBodySuccess(data);
  }, this));
  this.elem.on('invoke:loadError', $.proxy(function(e, xhr, invoke) {
    this.doLoadBodyError(xhr);
  }, this));
  this.elem.on('keyup', $.proxy(this.onElemKeyUp, this));
  this.popupElem.on('keyup', $.proxy(this.onElemKeyUp, this));

  this.doInit();
  this.doInitBody();

  this.elem.trigger('dropdown:ready', [this]);
}

RomoDropdown.prototype.doInit = function() {
  // override as needed
}

RomoDropdown.prototype.doInitBody = function() {
  this.doResetBody();

  this.contentElem = this.bodyElem.find('.romo-dropdown-content').last();
  if (this.contentElem.size() === 0) {
    this.contentElem = this.bodyElem;
  }
  this.closeElem = this.popupElem.find('[data-romo-dropdown-close="true"]');

  this.contentElem.css({
    'min-height': this.elem.data('romo-dropdown-min-height'),
    'height':     this.elem.data('romo-dropdown-height'),
    'overflow-x': this.elem.data('romo-dropdown-overflow-x') || 'auto',
    'overflow-y': this.elem.data('romo-dropdown-overflow-y') || 'auto'
  });

  if (this.elem.data('romo-dropdown-max-height') === undefined) {
    this.elem.attr('data-romo-dropdown-max-height', 'detect');
  }
  if (this.elem.data('romo-dropdown-max-height') !== 'detect') {
    this.contentElem.css({
      'max-height': this.elem.data('romo-dropdown-max-height')
    });
  }

  if (this.elem.data('romo-dropdown-width') === 'elem') {
    this.popupElem.css({
      'width': this.elem.css('width')
    });
  } else {
    this.contentElem.css({
      'min-width':  this.elem.data('romo-dropdown-min-width'),
      'max-width':  this.elem.data('romo-dropdown-max-width'),
      'width':      this.elem.data('romo-dropdown-width')
    });
  }

  this.closeElem.unbind('click');
  this.closeElem.on('click', $.proxy(this.onPopupClose, this));
}

RomoDropdown.prototype.doResetBody = function() {
  this.contentElem.css({
    'min-width':  '',
    'max-width':  '',
    'width':      '',
    'min-height': '',
    'max-height': '',
    'height':     '',
    'overflow-x': '',
    'overflow-y': ''
  });
}

RomoDropdown.prototype.doLoadBodyStart = function() {
  this.bodyElem.html('');
  this.doInitBody();
  this.doPlacePopupElem();
  this.elem.trigger('dropdown:loadBodyStart', [this]);
}

RomoDropdown.prototype.doLoadBodySuccess = function(data) {
  Romo.initHtml(this.bodyElem, data);
  this.doInitBody();
  this.doPlacePopupElem();
  this.elem.trigger('dropdown:loadBodySuccess', [data, this]);
}

RomoDropdown.prototype.doLoadBodyError = function(xhr) {
  this.elem.trigger('dropdown:loadBodyError', [xhr, this]);
}

RomoDropdown.prototype.onToggleClick = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  if (this.elem.hasClass('disabled') === false) {
    if (!this.popupElem.hasClass('romo-dropdown-open') ||
         this.elem.data('romo-dropdown-disable-toggle') !== true) {
      this.doToggle();
      return true;
    }
  }
  return false;
}

RomoDropdown.prototype.doToggle = function() {
  if (this.popupElem.hasClass('romo-dropdown-open')) {
    setTimeout($.proxy(function() {
      this.doPopupClose();
    }, this), 100);
  } else {
    setTimeout($.proxy(function() {
      this.doPopupOpen();
    }, this), 100);
  }
  this.elem.trigger('dropdown:toggle', [this]);
}

RomoDropdown.prototype.onPopupOpen = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  if ((this.elem.hasClass('disabled') === false) &&
      (this.popupElem.hasClass('romo-dropdown-open') === false)) {
    setTimeout($.proxy(function() {
      this.doPopupOpen();
    }, this), 100);
  }
}

RomoDropdown.prototype.doPopupOpen = function() {
  this.romoInvoke.doInvoke();
  this.popupElem.addClass('romo-dropdown-open');
  this.doPlacePopupElem();

  // bind an event to close the popup when clicking away from the
  // popup.  Bind on a timeout to allow time for any toggle
  // click event to propagate.  If no timeout, we'll bind this
  // event, then the toggle click will propagate which will call
  // this event and immediately close the popup.
  setTimeout($.proxy(function() {
    $('body').on('click', $.proxy(this.onWindowBodyClick, this));
    $('body').on('modal:mousedown', $.proxy(this.onWindowBodyClick, this));
  }, this), 100);
  $('body').on('keyup', $.proxy(this.onWindowBodyKeyUp, this));
  $(window).on('resize', $.proxy(this.onResizeWindow, this));

  this.elem.trigger('dropdown:popupOpen', [this]);
}

RomoDropdown.prototype.onPopupClose = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  if (this.elem.hasClass('disabled') === false) {
    setTimeout($.proxy(function() {
      this.doPopupClose();
    }, this), 100);
  }
}

RomoDropdown.prototype.doPopupClose = function() {
  this.popupElem.removeClass('romo-dropdown-open');

  $('body').off('click', $.proxy(this.onWindowBodyClick, this));
  $('body').off('modal:mousedown', $.proxy(this.onWindowBodyClick, this));
  $('body').off('keyup', $.proxy(this.onWindowBodyKeyUp, this));
  $(window).off('resize', $.proxy(this.onResizeWindow, this));

  this.elem.trigger('dropdown:popupClose', [this]);
}

RomoDropdown.prototype.onElemKeyUp = function(e) {
  if (this.elem.hasClass('disabled') === false) {
    if (this.popupElem.hasClass('romo-dropdown-open')) {
      if(e.keyCode === 27 /* Esc */ ) {
        this.doPopupClose();
        return false;
      } else {
        return true;
      }
    } else {
      return true;
    }
  }
  return true;
}

RomoDropdown.prototype.onWindowBodyClick = function(e) {
  // if not clicked on the popup elem
  if (e !== undefined && $(e.target).parents('.romo-dropdown-popup').size() === 0) {
    this.doPopupClose();
  }
  return true;
}

RomoDropdown.prototype.onWindowBodyKeyUp = function(e) {
  if (e.keyCode === 27 /* Esc */) {
    this.doPopupClose();
  }
  return true;
}

RomoDropdown.prototype.onResizeWindow = function(e) {
  this.doPlacePopupElem();
  return true;
}

RomoDropdown.prototype.doPlacePopupElem = function() {
  if (this.elem.parents('.romo-modal-popup').size() !== 0) {
    this.popupElem.css({'position': 'fixed'});
  }

  var pos = $.extend({}, this.elem[0].getBoundingClientRect(), this.elem.offset());
  var w = this.popupElem[0].offsetWidth;
  var h = this.popupElem[0].offsetHeight;
  var pad = 2;
  var offset = {};

  switch (this.popupPosition) {
    case 'top':
      $.extend(offset, { top: pos.top - h - pad });
      break;
    case 'bottom':
      $.extend(offset, { top: pos.top + pos.height + pad });
      break;
  }
  switch (this.popupAlignment) {
    case 'left':
      $.extend(offset, { left: pos.left });
      break;
    case 'right':
      $.extend(offset, { left: pos.right - w });
      break;
  }

  this.popupElem.offset(offset);

  if (this.elem.data('romo-dropdown-max-height') === 'detect') {
    var pad = this.elem.data('romo-dropdown-max-height-detect-pad') || 10;
    var contentTop = this.contentElem[0].getBoundingClientRect().top;
    var contentBottom = this.contentElem[0].getBoundingClientRect().bottom;
    var bodyBottom = this.bodyElem[0].getBoundingClientRect().bottom;
    var padBottom = bodyBottom - contentBottom;

    var maxHeight = $(window).height() - contentTop - padBottom - pad;
    this.contentElem.css({'max-height': maxHeight.toString() + 'px'});
  }
}

RomoDropdown.prototype.doSetPopupZIndex = function(relativeElem) {
  var relativeZIndex = Romo.parseZIndex(relativeElem);
  this.popupElem.css({'z-index': relativeZIndex + 1200}); // see z-index.css
}

RomoDropdown.prototype._parsePositionData = function(posString) {
  var posData = (posString || '').split(',');
  return { position: posData[0], alignment: posData[1] };
}

Romo.onInitUI(function(e) {
  Romo.initUIElems(e, '[data-romo-dropdown-auto="true"]').romoDropdown();
});
<commit_msg>dropdown js: popup close bug fixes<commit_after>$.fn.romoDropdown = function() {
  return $.map(this, function(element) {
    return new RomoDropdown(element);
  });
}

var RomoDropdown = function(element) {
  this.elem = $(element);
  this.popupElem = $('

');
  this.popupElem.appendTo('body');
  this.doSetPopupZIndex(this.elem);
  this.bodyElem = this.popupElem.find('> .romo-dropdown-body');
  this.contentElem = $();
  this.romoInvoke = this.elem.romoInvoke()[0];

  var positionData = this._parsePositionData(this.elem.data('romo-dropdown-position'));
  this.popupPosition  = positionData.position  || 'bottom';
  this.popupAlignment = positionData.alignment || 'left';
  this.popupElem.attr('data-romo-dropdown-position',  this.popupPosition);
  this.popupElem.attr('data-romo-dropdown-alignment', this.popupAlignment);
  this.popupElem.attr('data-romo-dropdown-fixed', this.elem.data('romo-dropdown-fixed'));
  // don't propagate click events on the popup elem.  this prevents the popup
  // from closing when clicked (see body click event bind on popup open)
  this.popupElem.on('click', function(e) {
    if (e !== undefined) {
      e.stopPropagation();
    }
  })

  if (this.elem.data('romo-dropdown-style-class') !== undefined) {
    this.bodyElem.addClass(this.elem.data('romo-dropdown-style-class'));
  }

  this.elem.unbind('click');
  this.elem.on('click', $.proxy(this.onToggleClick, this));
  this.elem.on('dropdown:triggerToggle', $.proxy(this.onToggleClick, this));
  this.elem.on('dropdown:triggerPopupOpen', $.proxy(this.onPopupOpen, this));
  this.elem.on('dropdown:triggerPopupClose', $.proxy(this.onPopupClose, this));
  this.elem.on('invoke:loadStart', $.proxy(function(e, invoke) {
    this.doLoadBodyStart();
  }, this));
  this.elem.on('invoke:loadSuccess', $.proxy(function(e, data, invoke) {
    this.doLoadBodySuccess(data);
  }, this));
  this.elem.on('invoke:loadError', $.proxy(function(e, xhr, invoke) {
    this.doLoadBodyError(xhr);
  }, this));
  this.elem.on('keyup', $.proxy(this.onElemKeyUp, this));
  this.popupElem.on('keyup', $.proxy(this.onElemKeyUp, this));

  this.doInit();
  this.doInitBody();

  this.elem.trigger('dropdown:ready', [this]);
}

RomoDropdown.prototype.doInit = function() {
  // override as needed
}

RomoDropdown.prototype.doInitBody = function() {
  this.doResetBody();

  this.contentElem = this.bodyElem.find('.romo-dropdown-content').last();
  if (this.contentElem.size() === 0) {
    this.contentElem = this.bodyElem;
  }
  this.closeElem = this.popupElem.find('[data-romo-dropdown-close="true"]');

  this.contentElem.css({
    'min-height': this.elem.data('romo-dropdown-min-height'),
    'height':     this.elem.data('romo-dropdown-height'),
    'overflow-x': this.elem.data('romo-dropdown-overflow-x') || 'auto',
    'overflow-y': this.elem.data('romo-dropdown-overflow-y') || 'auto'
  });

  if (this.elem.data('romo-dropdown-max-height') === undefined) {
    this.elem.attr('data-romo-dropdown-max-height', 'detect');
  }
  if (this.elem.data('romo-dropdown-max-height') !== 'detect') {
    this.contentElem.css({
      'max-height': this.elem.data('romo-dropdown-max-height')
    });
  }

  if (this.elem.data('romo-dropdown-width') === 'elem') {
    this.popupElem.css({
      'width': this.elem.css('width')
    });
  } else {
    this.contentElem.css({
      'min-width':  this.elem.data('romo-dropdown-min-width'),
      'max-width':  this.elem.data('romo-dropdown-max-width'),
      'width':      this.elem.data('romo-dropdown-width')
    });
  }

  this.closeElem.unbind('click');
  this.closeElem.on('click', $.proxy(this.onPopupClose, this));
}

RomoDropdown.prototype.doResetBody = function() {
  this.contentElem.css({
    'min-width':  '',
    'max-width':  '',
    'width':      '',
    'min-height': '',
    'max-height': '',
    'height':     '',
    'overflow-x': '',
    'overflow-y': ''
  });
}

RomoDropdown.prototype.doLoadBodyStart = function() {
  this.bodyElem.html('');
  this.doInitBody();
  this.doPlacePopupElem();
  this.elem.trigger('dropdown:loadBodyStart', [this]);
}

RomoDropdown.prototype.doLoadBodySuccess = function(data) {
  Romo.initHtml(this.bodyElem, data);
  this.doInitBody();
  this.doPlacePopupElem();
  this.elem.trigger('dropdown:loadBodySuccess', [data, this]);
}

RomoDropdown.prototype.doLoadBodyError = function(xhr) {
  this.elem.trigger('dropdown:loadBodyError', [xhr, this]);
}

RomoDropdown.prototype.onToggleClick = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  if (this.elem.hasClass('disabled') === false &&
      this.elem.data('romo-dropdown-disable-toggle') !== true) {
    this.doToggle();
    return true;
  }
  return false;
}

RomoDropdown.prototype.doToggle = function() {
  if (this.popupElem.hasClass('romo-dropdown-open')) {
    setTimeout($.proxy(function() {
      this.doPopupClose();
    }, this), 100);
  } else {
    setTimeout($.proxy(function() {
      this.doPopupOpen();
    }, this), 100);
  }
  this.elem.trigger('dropdown:toggle', [this]);
}

RomoDropdown.prototype.onPopupOpen = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  if (this.elem.hasClass('disabled') === false &&
      this.popupElem.hasClass('romo-dropdown-open') === false) {
    setTimeout($.proxy(function() {
      this.doPopupOpen();
    }, this), 100);
  }
}

RomoDropdown.prototype.doPopupOpen = function() {
  this.romoInvoke.doInvoke();
  this.popupElem.addClass('romo-dropdown-open');
  this.doPlacePopupElem();

  // bind an event to close the popup when clicking away from the
  // popup.  Bind on a timeout to allow time for any toggle
  // click event to propagate.  If no timeout, we'll bind this
  // event, then the toggle click will propagate which will call
  // this event and immediately close the popup.
  setTimeout($.proxy(function() {
    $('body').on('click', $.proxy(this.onWindowBodyClick, this));
    $('body').on('modal:mousedown', $.proxy(this.onWindowBodyClick, this));
  }, this), 100);
  $('body').on('keyup', $.proxy(this.onWindowBodyKeyUp, this));
  $(window).on('resize', $.proxy(this.onResizeWindow, this));

  this.elem.trigger('dropdown:popupOpen', [this]);
}

RomoDropdown.prototype.onPopupClose = function(e) {
  if (e !== undefined) {
    e.preventDefault();
  }

  if (this.elem.hasClass('disabled') === false &&
      this.popupElem.hasClass('romo-dropdown-open') === true) {
    setTimeout($.proxy(function() {
      this.doPopupClose();
    }, this), 100);
  }
}

RomoDropdown.prototype.doPopupClose = function() {
  this.popupElem.removeClass('romo-dropdown-open');

  $('body').off('click', $.proxy(this.onWindowBodyClick, this));
  $('body').off('modal:mousedown', $.proxy(this.onWindowBodyClick, this));
  $('body').off('keyup', $.proxy(this.onWindowBodyKeyUp, this));
  $(window).off('resize', $.proxy(this.onResizeWindow, this));

  this.elem.trigger('dropdown:popupClose', [this]);
}

RomoDropdown.prototype.onElemKeyUp = function(e) {
  if (this.elem.hasClass('disabled') === false) {
    if (this.popupElem.hasClass('romo-dropdown-open')) {
      if(e.keyCode === 27 /* Esc */ ) {
        this.doPopupClose();
        return false;
      } else {
        return true;
      }
    } else {
      return true;
    }
  }
  return true;
}

RomoDropdown.prototype.onWindowBodyClick = function(e) {
  // if not clicked on the popup elem or the elem
  var target = $(e.target);
  if (e !== undefined &&
      target.parents('.romo-dropdown-popup').size() === 0 &&
      target.closest(this.elem).size() === 0) {
    this.doPopupClose();
  }
  return true;
}

RomoDropdown.prototype.onWindowBodyKeyUp = function(e) {
  if (e.keyCode === 27 /* Esc */) {
    this.doPopupClose();
  }
  return true;
}

RomoDropdown.prototype.onResizeWindow = function(e) {
  this.doPlacePopupElem();
  return true;
}

RomoDropdown.prototype.doPlacePopupElem = function() {
  if (this.elem.parents('.romo-modal-popup').size() !== 0) {
    this.popupElem.css({'position': 'fixed'});
  }

  var pos = $.extend({}, this.elem[0].getBoundingClientRect(), this.elem.offset());
  var w = this.popupElem[0].offsetWidth;
  var h = this.popupElem[0].offsetHeight;
  var pad = 2;
  var offset = {};

  switch (this.popupPosition) {
    case 'top':
      $.extend(offset, { top: pos.top - h - pad });
      break;
    case 'bottom':
      $.extend(offset, { top: pos.top + pos.height + pad });
      break;
  }
  switch (this.popupAlignment) {
    case 'left':
      $.extend(offset, { left: pos.left });
      break;
    case 'right':
      $.extend(offset, { left: pos.right - w });
      break;
  }

  this.popupElem.offset(offset);

  if (this.elem.data('romo-dropdown-max-height') === 'detect') {
    var pad = this.elem.data('romo-dropdown-max-height-detect-pad') || 10;
    var contentTop = this.contentElem[0].getBoundingClientRect().top;
    var contentBottom = this.contentElem[0].getBoundingClientRect().bottom;
    var bodyBottom = this.bodyElem[0].getBoundingClientRect().bottom;
    var padBottom = bodyBottom - contentBottom;

    var maxHeight = $(window).height() - contentTop - padBottom - pad;
    this.contentElem.css({'max-height': maxHeight.toString() + 'px'});
  }
}

RomoDropdown.prototype.doSetPopupZIndex = function(relativeElem) {
  var relativeZIndex = Romo.parseZIndex(relativeElem);
  this.popupElem.css({'z-index': relativeZIndex + 1200}); // see z-index.css
}

RomoDropdown.prototype._parsePositionData = function(posString) {
  var posData = (posString || '').split(',');
  return { position: posData[0], alignment: posData[1] };
}

Romo.onInitUI(function(e) {
  Romo.initUIElems(e, '[data-romo-dropdown-auto="true"]').romoDropdown();
});
<|endoftext|>


<commit_before>function TargetingCtrl($rootScope, $scope, Translate, n2translations) {
	angular.extend(n2translations, {
		targeting: {
			menu: {
				fullsize: " Full size",
				rotate: " Switch portrait/landscape"
			},
			preview: {
				custom: "Custom",
				viewportsize: "Viewport size",
				close: "Close"
			}
		}
	});

	$rootScope.$on("contextchanged", function (scope, e) {
		if ($scope.Context.Flags.indexOf('Management') >= 0)
			delete $scope.preview;
	});

	function rotate() {
		var s = $scope.preview.size;
		var newDimensions = { Height: s.Width, Width: s.Height };
		angular.extend(s, newDimensions);
	}

	$rootScope.$on("device-preview", function (e, size) {
		if ($scope.preview && $scope.preview.size && $scope.preview.size.Height == size.Height && $scope.preview.size.Width == size.Width) {
			rotate();
			return;
		}
		$scope.preview = {
			size: size,
			url: window.frames.preview && window.frames.preview.window.location.toString()
		};
		console.log($scope.preview);
	});
	$rootScope.$on("device-close", function (e, size) {
		delete $scope.preview;
	});
	$rootScope.$on("device-rotate", function (e, size) {
		if ($scope.preview) {
			rotate();
		}
	});
	$rootScope.$on("resized", function () {
		$scope.preview.size.Title = Translate("targeting.preview.custom");// "Custom";
	});

	$scope.frameLoaded = function (e) {
		try {
			var loco = e.target.contentWindow.location;
			$scope.$emit("preiewloaded", { path: loco.pathname, query: loco.search, url: loco.toString() });
		} catch (ex) {
			$scope.$emit("preiewaccessexception", { ex: ex });
			console.log("frame access exception", ex);
		}
	};
};<commit_msg>Fixed icons in targeting localization<commit_after>function TargetingCtrl($rootScope, $scope, Translate, n2translations) {
	angular.extend(n2translations, {
		targeting: {
			menu: {
				fullsize: { text: " Full size" },
				rotate: { text: " Switch portrait/landscape" }
			},
			preview: {
				custom: "Custom",
				viewportsize: "Viewport size",
				close: "Close"
			}
		}
	});

	$rootScope.$on("contextchanged", function (scope, e) {
		if ($scope.Context.Flags.indexOf('Management') >= 0)
			delete $scope.preview;
	});

	function rotate() {
		var s = $scope.preview.size;
		var newDimensions = { Height: s.Width, Width: s.Height };
		angular.extend(s, newDimensions);
	}

	$rootScope.$on("device-preview", function (e, size) {
		if ($scope.preview && $scope.preview.size && $scope.preview.size.Height == size.Height && $scope.preview.size.Width == size.Width) {
			rotate();
			return;
		}
		$scope.preview = {
			size: size,
			url: window.frames.preview && window.frames.preview.window.location.toString()
		};
		console.log($scope.preview);
	});
	$rootScope.$on("device-close", function (e, size) {
		delete $scope.preview;
	});
	$rootScope.$on("device-rotate", function (e, size) {
		if ($scope.preview) {
			rotate();
		}
	});
	$rootScope.$on("resized", function () {
		$scope.preview.size.Title = Translate("targeting.preview.custom");// "Custom";
	});

	$scope.frameLoaded = function (e) {
		try {
			var loco = e.target.contentWindow.location;
			$scope.$emit("preiewloaded", { path: loco.pathname, query: loco.search, url: loco.toString() });
		} catch (ex) {
			$scope.$emit("preiewaccessexception", { ex: ex });
			console.log("frame access exception", ex);
		}
	};
};<|endoftext|>


<commit_before>angular.module("calendar").factory("Month", [ "$http", function($http) {
    var month = {};

    month.getDays = function(month, year) {
        return $http.get("/ajax/month-view", {
            params: {
                year: year,
                month: month
            },
            cache: true
        });
    };

    return month;
}]);
<commit_msg>don't cache month view for now<commit_after>angular.module("calendar").factory("Month", [ "$http", function($http) {
    var month = {};

    month.getDays = function(month, year) {
        return $http.get("/ajax/month-view", {
            params: {
                year: year,
                month: month
            }
        });
    };

    return month;
}]);
<|endoftext|>


<commit_before>define(function (require, exports, module) {
	'use strict';

	var LanguageManager = brackets.getModule("language/LanguageManager");
	var CodeMirror 		= brackets.getModule("thirdparty/CodeMirror2/lib/codemirror");
    var highlightClass  = "keyword";

	CodeMirror.defineMode("laravelblade", function (config, parserConfig) {

		var laravelOverlay = {
			startState: function() {
				return {
					inComment: false,
                    inEcho: false,
                    inEcho5: false,
                    inForm: false
				}
			},
			token: function(stream, state) {
				var ch;

				// Laravel Comment Syntax (Single Line and Multiline)
				if (state.inComment) {
					if (!stream.skipTo("--}}")) {
						stream.skipToEnd();
					} else {
						stream.match("--}}");
						state.inComment = false;
					}
					return "comment";
				} else {
					if (stream.match("{{--")) {
						state.inComment = true;
						if (!stream.skipTo("--}}")) {
							stream.skipToEnd();
						} else {
							stream.match("--}}");
							state.inComment = false;
						}
						return "comment";
					}
				}

				//Laravel5 Echo Syntax (Single Line and Multiline)
				if (state.inEcho5) {
					if (!stream.skipTo("%}")) {
						stream.skipToEnd();
					} else {
						stream.match("%}");
						state.inEcho5 = false;
					}
					return highlightClass;
				} else {
					if (stream.match("{%")) {
						state.inEcho5 = true;
						if (!stream.skipTo("%}")) {
							stream.skipToEnd();
						} else {
							stream.match("%}");
							state.inEcho5 = false;
						}
						return highlightClass;
					}
				}

                //Laravel Echo Syntax (Single Line and Multiline)
				if (state.inEcho) {
					if (!stream.skipTo("}}")) {
						stream.skipToEnd();
					} else {
						stream.match("}}");
						state.inEcho = false;
					}
					return highlightClass;
				} else {
					if (stream.match("{{")) {
						state.inEcho = true;
						if (!stream.skipTo("}}")) {
							stream.skipToEnd();
						} else {
							stream.match("}}");
							state.inEcho = false;
						}
						return highlightClass;
					}
				}

				//Laravel5 Form Syntax (Single Line and Multiline)
				if (state.inForm) {
					if (!stream.skipTo("!!}")) {
						stream.skipToEnd();
					} else {
						stream.match("!!}");
						state.inForm = false;
					}
					return highlightClass;
				} else {
					if (stream.match("{!!")) {
						state.inForm = true;
						if (!stream.skipTo("!!}")) {
							stream.skipToEnd();
						} else {
							stream.match("!!}");
							state.inForm = false;
						}
						return highlightClass;
					}
				}

                //listen for opening tags
				while (stream.next() != null &&
					   !stream.match("{{--", false) &&
					   !stream.match("{%", false) &&
					   !stream.match("{!!", false) &&
					   !stream.match("{{", false)
					  ) {}
				return null;

			}
		  };
		  return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "php"), laravelOverlay);
	});

	LanguageManager.defineLanguage("laravelblade", {
		"name": "Laravel Blade",
		"mode": "laravelblade",
		"fileExtensions": ["blade.php"],
		"blockComment": ["{{--", "--}}"]
	});
});
<commit_msg>Update bladesyntaxhighlight.js<commit_after>define(function (require, exports, module) {
	'use strict';

	var LanguageManager = brackets.getModule("language/LanguageManager");
	var CodeMirror 		= brackets.getModule("thirdparty/CodeMirror2/lib/codemirror");
    	var highlightClass  = "keyword";

	CodeMirror.defineMode("laravelblade", function (config, parserConfig) {

		var laravelOverlay = {
			startState: function() {
				return {
					inComment: false,
                    			inEcho: false,
                    			inEcho5: false,
                			inForm: false
				}
			},
			token: function(stream, state) {
				var ch;

				// Laravel Comment Syntax (Single Line and Multiline)
				if (state.inComment) {
					if (!stream.skipTo("--}}")) {
						stream.skipToEnd();
					} else {
						stream.match("--}}");
						state.inComment = false;
					}
					return "comment";
				} else {
					if (stream.match("{{--")) {
						state.inComment = true;
						if (!stream.skipTo("--}}")) {
							stream.skipToEnd();
						} else {
							stream.match("--}}");
							state.inComment = false;
						}
						return "comment";
					}
				}

				//Laravel5 Echo Syntax (Single Line and Multiline)
				if (state.inEcho5) {
					if (!stream.skipTo("%}")) {
						stream.skipToEnd();
					} else {
						stream.match("%}");
						state.inEcho5 = false;
					}
					return highlightClass;
				} else {
					if (stream.match("{%")) {
						state.inEcho5 = true;
						if (!stream.skipTo("%}")) {
							stream.skipToEnd();
						} else {
							stream.match("%}");
							state.inEcho5 = false;
						}
						return highlightClass;
					}
				}

                		//Laravel Echo Syntax (Single Line and Multiline)
				if (state.inEcho) {
					if (!stream.skipTo("}}")) {
						stream.skipToEnd();
					} else {
						stream.match("}}");
						state.inEcho = false;
					}
					return highlightClass;
				} else {
					if (stream.match("{{")) {
						state.inEcho = true;
						if (!stream.skipTo("}}")) {
							stream.skipToEnd();
						} else {
							stream.match("}}");
							state.inEcho = false;
						}
						return highlightClass;
					}
				}

				//Laravel5 Form Syntax (Single Line and Multiline)
				if (state.inForm) {
					if (!stream.skipTo("!!}")) {
						stream.skipToEnd();
					} else {
						stream.match("!!}");
						state.inForm = false;
					}
					return highlightClass;
				} else {
					if (stream.match("{!!")) {
						state.inForm = true;
						if (!stream.skipTo("!!}")) {
							stream.skipToEnd();
						} else {
							stream.match("!!}");
							state.inForm = false;
						}
						return highlightClass;
					}
				}

                		//listen for opening tags
				while (stream.next() != null &&
					   !stream.match("{{--", false) &&
					   !stream.match("{%", false) &&
					   !stream.match("{!!", false) &&
					   !stream.match("{{", false)
					  ) {}
				return null;

			}
		  };
		  return CodeMirror.overlayMode(CodeMirror.getMode(config, parserConfig.backdrop || "php"), laravelOverlay);
	});

	LanguageManager.defineLanguage("laravelblade", {
		"name": "Laravel Blade",
		"mode": "laravelblade",
		"fileExtensions": ["blade.php"],
		"blockComment": ["{{--", "--}}"]
	});
});
<|endoftext|>