<commit_before>storeApi = {

	getFullUrl: function(company, url){
		var newUrl = "";

		switch(company.toLowerCase()){
			case "gap":
			case "old navy":
			case "banana":
			case "piperlime":
			case "athleta":
				newUrl = url;
				break;
			case "jcrew":
				newUrl = url;
				break;
			case "ann taylor":
				var catid = url.substring(url.lastIndexOf("/") + 1);
				newUrl = url.indexOf("?") > 0 ? '' : "http://www.anntaylor.com/ann/catalog/category.jsp?pageSize=1000&goToPage=1&catid=" + catid;
				break;
			case "loft":
				newUrl = url;
				break;
			case "urban outfitters":
				newUrl = url;
				break;
			case "zara":
				newUrl = url;
				break;
			case "hm":
				newUrl = url;
				break;
			case "tory burch":
				newUrl = url;
				break;
		}

		return newUrl;
	},

	getProducts: function(company, data, url){
		var home = url.substring(0,url.indexOf(".com")+4);

		var products = "";

		switch(company.toLowerCase()){
			case "gap":
			case "old navy":
			case "banana":
			case "piperlime":
			case "athleta":
				products = storeApi.getGapJson(data, home);
				break;
			case "jcrew":
				products = storeApi.getJcrew(data, home);
				break;
			case "ann taylor":
				products = storeApi.getAnnTaylor(data, home);
				break;
			case "loft":
				products = storeApi.getLoft(data, home);
				break;
			case "urban outfitters":
				products = storeApi.getUrban(data, home);
				break;
			case "zara":
				products = storeApi.getZara(data, home);
				break;
			case "hm":
				products = storeApi.getHM(data, home);
				break;
			case "tory burch":
				products = storeApi.getToryBurch(data, home);
				break;
		}

		return products;
	},

	getGapJson: function(data, siteHome){
			var json = $.parseJSON(data);
			var products = new Object();
	  		var cid = json.productCategoryFacetedSearch.productCategory.businessCatalogItemId;
			var vid = 1;

			if(json.productCategoryFacetedSearch.productCategory.childCategories != null){
				if(json.productCategoryFacetedSearch.productCategory.childCategories.length > 1){
					$.each(json.productCategoryFacetedSearch.productCategory.childCategories, function(){

						$.each(this.childProducts, function(){
							var pid = this.businessCatalogItemId;

							var item = new Object();
							item.image = this.quicklookImage.path;
							item.link = siteHome + "/browse/product.do?cid="+cid+"&vid="+vid+"&pid="+pid;
							item.name = this.name;
							item.price = this.price.currentMinPrice;
							item.sku = 'g-' + this.businessCatalogItemId;

							if(item.image != undefined){
								var itemid = item.sku.replace(/-\W/g, '');
								products[itemid] = item;
							}
						});
					});
				}else if (json.productCategoryFacetedSearch.productCategory.childCategories.childProducts != null){
					$.each(json.productCategoryFacetedSearch.productCategory.childCategories.childProducts, function(){
	                                                var pid = this.businessCatalogItemId;

	                                                var item = new Object();
	                                                item.image = this.quicklookImage.path;
	                                                item.link = siteHome + "/browse/product.do?cid="+cid+"&vid="+vid+"&pid="+pid;
	                                                item.name = this.name;
	                                                item.price = this.price.currentMinPrice;
	                                                item.sku = 'g-' + this.businessCatalogItemId;

	                                                if(item.image != undefined){
	                                                        var itemid = item.sku.replace(/-\W/g, '');
	                                                        products[itemid] = item;
	                                               }

	                                });
				}
			}else if(json.productCategoryFacetedSearch.productCategory.childProducts != null){
				$.each(json.productCategoryFacetedSearch.productCategory.childProducts, function(){
	                        	var pid = this.businessCatalogItemId;

	                                var item = new Object();
	                                item.image = this.quicklookImage.path;
	                                item.link = siteHome + "/browse/product.do?cid="+cid+"&vid="+vid+"&pid="+pid;
	                                item.name = this.name;
	                                item.price = this.price.currentMinPrice;
	                                item.sku = 'g-' + this.businessCatalogItemId;

	                                if(item.image != undefined){
	                                	var itemid = item.sku.replace(/-\W/g, '');
	                                        products[itemid] = item;
	                                }
	                        });
			}

		return JSON.stringify(products);
	},

	getJcrew: function(data, siteHome){
		siteHome += "?iNextCategory=-1";
	  	var products = new Object();

		$(data).find(".arrayProdCell").each(function(){
			var item = new Object();

			item.image = $(this).find(".arrayImg").find("img").attr("src");
			item.link = $(this).find(".arrayImg").find("a").attr("href");
			item.name = $(this).find(".arrayProdName").find("a").text().trim();
			item.price = $(this).find(".arrayProdPrice").text().trim();

			if(item.image != undefined){
			    item.sku = 'jc-' + item.link.substring(item.link.lastIndexOf("/")+1, item.link.lastIndexOf("."));

				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getAnnTaylor: function(data, siteHome){
	 	var products = new Object();

		$(data).find(".product").each(function(){
			var item = new Object();

			item.image = $(this).find(".thumb").children("img").first().attr("src");
			item.link = siteHome + $(this).find(".overlay > a.clickthrough").first().attr("href");
			item.name = $(this).find(".overlay > .fg > .description > .messaging > p").not(".POS").first().text().trim();
			item.price = $(this).find(".overlay > .fg > .description > .price > p").not(".was").first().text().trim();

			var url = item.link.substring(0, item.link.indexOf("?"));
            item.sku = 'at-' + url.substring(url.lastIndexOf("/")+1);

			if(item.image != undefined){
				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getLoft: function(data, siteHome){
		 var products = new Object();

		$(data).find(".products").find(".product").each(function(){
			var item = new Object();

			item.image = $(this).find(".thumb").children("img").first().attr("src");
			item.link = siteHome + $(this).find(".overlay > a.clickthrough").first().attr("href");
			item.name = $(this).find(".description > .messaging > p").not(".POS").first().text().trim();
			item.price = $(this).find(".description > .price > p").not(".was").first().text().trim();

			var url = item.link.substring(0, item.link.indexOf("?"));
            item.sku = 'l-' +url.substring(url.lastIndexOf("/")+1);

			if(item.image != undefined){
				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getUrban: function(data, siteHome){
	    var products = new Object();

		$(data).find("#category-products").children().each(function(){
			var item = new Object();

			item.image = $(this).find(".category-product-image > a > img").first().attr("src");
			item.link = siteHome + $(this).find(".category-product-image > a").first().attr("href");
			item.name = $(this).find(".category-product-description > h2 > a").first().text().trim();
			item.price = $(this).find(".category-product-description > .price").first().text().trim();

			if(item.image != undefined){
			    item.sku = 'uo-' + item.link.substring(item.link.indexOf("id=")+3, item.link.indexOf("&"));

				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getZara: function(data, siteHome){
		var products = new Object();
	    	$(".currency").html("");

		$(data).find("#product-list").children(".product").each(function(){
			var item = new Object();

			item.image = $(this).find("a.gaProductDetailsLink > img").first().attr("data-src");
			item.link = $(this).find("a.gaProductDetailsLink").first().attr("href");
			item.name = $(this).find(".product-info > a.name").first().text().trim();
			item.price = $(this).find(".product-info > .price").first().text().trim();
			item.sku = 'z-' + $(this).find("a.gaProductDetailsLink").first().attr("data-item");

			if(item.image != undefined){
				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getHM: function(data, siteHome){
		siteHome += "&size=1000";
		var products = new Object();

		$(data).find("#list-products").children("li").not(".getTheLook").each(function(){
			var item = new Object();

			item.image = $(this).find(".image > img:nth-child(2)").first().attr("src");
			item.link = $(this).find("a").first().attr("href");
			item.price = $(this).find("a > .details > .price").first().text().trim();
			$(this).find("a > .details > .price").first().remove();
			item.name = $(this).find("a > .details").first().text().trim();
			item.sku = 'hm-' + $(this).find("button.quicklook").first().attr("data-product");

			if(item.image != undefined){
				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getToryBurch: function(data, siteHome){
	        var products = new Object();

	        $(data).find("#search > .productresultarea > .productlisting > .product").each(function(){
	                var item = new Object();

	                item.image = $(this).children(".image").find("img:nth-child(2)").attr("src");
	                item.link = $(this).children(".image").find("a").first().attr("href");
	                item.price = $(this).find(".pricing > .price").first().text().trim();
	                item.name = $(this).children(".name").find("a").first().text().trim();

	                if(item.image != undefined){
	                   item.sku = 'tb-' + item.link.substring(item.link.lastIndexOf("/")+1,item.link.indexOf(","));

				        var itemid = item.sku.replace(/-\W/g, '');
	                    products[itemid] = item;
	                }
	        });

	        return JSON.stringify(products);
	}
}
<commit_msg>adding store name to sku<commit_after>storeApi = {

	getFullUrl: function(company, url){
		var newUrl = "";

		switch(company.toLowerCase()){
			case "gap":
			case "old navy":
			case "banana":
			case "piperlime":
			case "athleta":
				newUrl = url;
				break;
			case "jcrew":
				newUrl = url;
				break;
			case "ann taylor":
				var catid = url.substring(url.lastIndexOf("/") + 1);
				newUrl = url.indexOf("?") > 0 ? '' : "http://www.anntaylor.com/ann/catalog/category.jsp?pageSize=1000&goToPage=1&catid=" + catid;
				break;
			case "loft":
				newUrl = url;
				break;
			case "urban outfitters":
				newUrl = url;
				break;
			case "zara":
				newUrl = url;
				break;
			case "hm":
				newUrl = url;
				break;
			case "tory burch":
				newUrl = url;
				break;
		}

		return newUrl;
	},

	getProducts: function(company, data, url){
		var home = url.substring(0,url.indexOf(".com")+4);

		var products = "";

		switch(company.toLowerCase()){
			case "gap":
			case "old navy":
			case "banana":
			case "piperlime":
			case "athleta":
				products = storeApi.getGapJson(data, home);
				break;
			case "jcrew":
				products = storeApi.getJcrew(data, home);
				break;
			case "ann taylor":
				products = storeApi.getAnnTaylor(data, home);
				break;
			case "loft":
				products = storeApi.getLoft(data, home);
				break;
			case "urban outfitters":
				products = storeApi.getUrban(data, home);
				break;
			case "zara":
				products = storeApi.getZara(data, home);
				break;
			case "hm":
				products = storeApi.getHM(data, home);
				break;
			case "tory burch":
				products = storeApi.getToryBurch(data, home);
				break;
		}

		return products;
	},

	getGapJson: function(data, siteHome){
			var json = $.parseJSON(data);
			var products = new Object();
	  		var cid = json.productCategoryFacetedSearch.productCategory.businessCatalogItemId;
			var vid = 1;

			if(json.productCategoryFacetedSearch.productCategory.childCategories != null){
				if(json.productCategoryFacetedSearch.productCategory.childCategories.length > 1){
					$.each(json.productCategoryFacetedSearch.productCategory.childCategories, function(){

						$.each(this.childProducts, function(){
							var pid = this.businessCatalogItemId;

							var item = new Object();
							item.image = this.quicklookImage.path;
							item.link = siteHome + "/browse/product.do?cid="+cid+"&vid="+vid+"&pid="+pid;
							item.name = this.name;
							item.price = this.price.currentMinPrice;
							item.sku = 'g' + this.businessCatalogItemId;

							if(item.image != undefined){
								var itemid = item.sku.replace(/-\W/g, '');
								products[itemid] = item;
							}
						});
					});
				}else if (json.productCategoryFacetedSearch.productCategory.childCategories.childProducts != null){
					$.each(json.productCategoryFacetedSearch.productCategory.childCategories.childProducts, function(){
	                                                var pid = this.businessCatalogItemId;

	                                                var item = new Object();
	                                                item.image = this.quicklookImage.path;
	                                                item.link = siteHome + "/browse/product.do?cid="+cid+"&vid="+vid+"&pid="+pid;
	                                                item.name = this.name;
	                                                item.price = this.price.currentMinPrice;
	                                                item.sku = 'g' + this.businessCatalogItemId;

	                                                if(item.image != undefined){
	                                                        var itemid = item.sku.replace(/-\W/g, '');
	                                                        products[itemid] = item;
	                                               }

	                                });
				}
			}else if(json.productCategoryFacetedSearch.productCategory.childProducts != null){
				$.each(json.productCategoryFacetedSearch.productCategory.childProducts, function(){
	                        	var pid = this.businessCatalogItemId;

	                                var item = new Object();
	                                item.image = this.quicklookImage.path;
	                                item.link = siteHome + "/browse/product.do?cid="+cid+"&vid="+vid+"&pid="+pid;
	                                item.name = this.name;
	                                item.price = this.price.currentMinPrice;
	                                item.sku = 'g' + this.businessCatalogItemId;

	                                if(item.image != undefined){
	                                	var itemid = item.sku.replace(/-\W/g, '');
	                                        products[itemid] = item;
	                                }
	                        });
			}

		return JSON.stringify(products);
	},

	getJcrew: function(data, siteHome){
		siteHome += "?iNextCategory=-1";
	  	var products = new Object();

		$(data).find(".arrayProdCell").each(function(){
			var item = new Object();

			item.image = $(this).find(".arrayImg").find("img").attr("src");
			item.link = $(this).find(".arrayImg").find("a").attr("href");
			item.name = $(this).find(".arrayProdName").find("a").text().trim();
			item.price = $(this).find(".arrayProdPrice").text().trim();

			if(item.image != undefined){
			    item.sku = 'jc' + item.link.substring(item.link.lastIndexOf("/")+1, item.link.lastIndexOf("."));

				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getAnnTaylor: function(data, siteHome){
	 	var products = new Object();

		$(data).find(".product").each(function(){
			var item = new Object();

			item.image = $(this).find(".thumb").children("img").first().attr("src");
			item.link = siteHome + $(this).find(".overlay > a.clickthrough").first().attr("href");
			item.name = $(this).find(".overlay > .fg > .description > .messaging > p").not(".POS").first().text().trim();
			item.price = $(this).find(".overlay > .fg > .description > .price > p").not(".was").first().text().trim();

			var url = item.link.substring(0, item.link.indexOf("?"));
            item.sku = 'at' + url.substring(url.lastIndexOf("/")+1);

			if(item.image != undefined){
				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getLoft: function(data, siteHome){
		 var products = new Object();

		$(data).find(".products").find(".product").each(function(){
			var item = new Object();

			item.image = $(this).find(".thumb").children("img").first().attr("src");
			item.link = siteHome + $(this).find(".overlay > a.clickthrough").first().attr("href");
			item.name = $(this).find(".description > .messaging > p").not(".POS").first().text().trim();
			item.price = $(this).find(".description > .price > p").not(".was").first().text().trim();

			var url = item.link.substring(0, item.link.indexOf("?"));
            item.sku = 'l-' +url.substring(url.lastIndexOf("/")+1);

			if(item.image != undefined){
				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getUrban: function(data, siteHome){
	    var products = new Object();

		$(data).find("#category-products").children().each(function(){
			var item = new Object();

			item.image = $(this).find(".category-product-image > a > img").first().attr("src");
			item.link = siteHome + $(this).find(".category-product-image > a").first().attr("href");
			item.name = $(this).find(".category-product-description > h2 > a").first().text().trim();
			item.price = $(this).find(".category-product-description > .price").first().text().trim();

			if(item.image != undefined){
			    item.sku = 'uo' + item.link.substring(item.link.indexOf("id=")+3, item.link.indexOf("&"));

				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getZara: function(data, siteHome){
		var products = new Object();
	    	$(".currency").html("");

		$(data).find("#product-list").children(".product").each(function(){
			var item = new Object();

			item.image = $(this).find("a.gaProductDetailsLink > img").first().attr("data-src");
			item.link = $(this).find("a.gaProductDetailsLink").first().attr("href");
			item.name = $(this).find(".product-info > a.name").first().text().trim();
			item.price = $(this).find(".product-info > .price").first().text().trim();
			item.sku = 'z' + $(this).find("a.gaProductDetailsLink").first().attr("data-item");

			if(item.image != undefined){
				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getHM: function(data, siteHome){
		siteHome += "&size=1000";
		var products = new Object();

		$(data).find("#list-products").children("li").not(".getTheLook").each(function(){
			var item = new Object();

			item.image = $(this).find(".image > img:nth-child(2)").first().attr("src");
			item.link = $(this).find("a").first().attr("href");
			item.price = $(this).find("a > .details > .price").first().text().trim();
			$(this).find("a > .details > .price").first().remove();
			item.name = $(this).find("a > .details").first().text().trim();
			item.sku = 'hm' + $(this).find("button.quicklook").first().attr("data-product");

			if(item.image != undefined){
				var itemid = item.sku.replace(/-\W/g, '');
				products[itemid] = item;
			}
		});

		return JSON.stringify(products);
	},

	getToryBurch: function(data, siteHome){
	        var products = new Object();

	        $(data).find("#search > .productresultarea > .productlisting > .product").each(function(){
	                var item = new Object();

	                item.image = $(this).children(".image").find("img:nth-child(2)").attr("src");
	                item.link = $(this).children(".image").find("a").first().attr("href");
	                item.price = $(this).find(".pricing > .price").first().text().trim();
	                item.name = $(this).children(".name").find("a").first().text().trim();

	                if(item.image != undefined){
	                   item.sku = 'tb' + item.link.substring(item.link.lastIndexOf("/")+1,item.link.indexOf(","));

				        var itemid = item.sku.replace(/-\W/g, '');
	                    products[itemid] = item;
	                }
	        });

	        return JSON.stringify(products);
	}
}
<|endoftext|>


<commit_before>//jQuery.Class
// This is a modified version of John Resig's class
// It provides class level inheritence and callbacks.

steal.plugin("jquery").then(function($){

	//if we are initializing a new class
var initializing = false,

	//tests if we can get super in .toString()
	fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/,

	newInstance = function(){
		initializing = true;
		var inst = new this();
		initializing = false;
		if ( inst.setup )
			inst.setup.apply(inst, arguments);
		if ( inst.init )
			inst.init.apply(inst, arguments);
		return inst;
	},
	rawInstance = function(){
		initializing = true;
		var inst = new this();
		initializing = false;
		return inst;
	},
	/**
	 * Copy and overwrite options from old class
	 * @param {Object} oldClass
	 * @param {Object} options
	 */
	setup = function(oldClass, options){
		this.defaults = $.extend(true, {},oldClass.defaults, this.defaults);
	},
	toString = function(){
		return this.className || Object.prototype.toString.call(this)
	},
	id = 1,
	inheritProps = function(newProps, oldProps, addTo){
		addTo = addTo || newProps
		for(var name in newProps) {
		  // Check if we're overwriting an existing function
		  addTo[name] = typeof newProps[name] == "function" &&
			typeof oldProps[name] == "function" && fnTest.test(newProps[name]) ?
			(function(name, fn){
			  return function() {
				var tmp = this._super, ret;

				// Add a new ._super() method that is the same method
				// but on the super-class
				this._super = oldProps[name];

				// The method only need to be bound temporarily, so we
				// remove it when we're done executing
				ret = fn.apply(this, arguments);
				this._super = tmp;
				return ret;
			  };
			})(name, newProps[name]) :
			newProps[name];
		}
	};
// The base Class implementation (does nothing)

/**
* @constructor jQuery.Class
* @plugin jquery/class
* @tag core
* @download dist/jquery.class.js
* Class provides simulated inheritance in JavaScript.
* It is based off John Resig's [http://ejohn.org/blog/simple-javascript-inheritance/|Simple Class]
* Inheritance library.  Besides prototypal inheritance, it adds a few important features:
*

*
Static inheritance

*
Introspection

*
Ad-Hoc Polymorphism

*
Easy callback function creation

*

*
Definitions

* Classes have static and prototype properties and
* methods:
* @codestart
* //STATIC
* MyClass.staticProperty  //shared property
*
* //PROTOTYPE
* myclass = new MyClass()
* myclass.prototypeMethod() //instance method
* @codeend
*
*
Examples

*
Basic example

* Creates a class with a shortName (for introspection), static, and prototype members:
* @codestart
* jQuery.Class.extend('Monster',
* /* @static *|
* {
*   count: 0
* },
* /* @prototype *|
* {
*   init : function(name){
*     this.name = name;
*     this.Class.count++
*   }
* })
* hydra = new Monster('hydra')
* dragon = new Monster('dragon')
* hydra.name        // -> hydra
* Monster.count     // -> 2
* Monster.shortName // -> 'Monster'
* @codeend
* Notice that the prototype init function is called when a new instance of Monster is created.
*
Static property inheritance

* Demonstrates inheriting a class property.
* @codestart
* jQuery.Class.extend("First",
* {
*     staticMethod : function(){ return 1;}
* },{})
*
* First.extend("Second",{
*     staticMethod : function(){ return this._super()+1;}
* },{})
*
* Second.staticMethod() // -> 2
* @codeend
*
Introspection

* Often, it's nice to create classes whose name helps determine functionality.  Ruby on
* Rails's [http://api.rubyonrails.org/classes/ActiveRecord/Base.html|ActiveRecord] ORM class
* is a great example of this.  Unfortunately, JavaScript doesn't have a way of determining
* an object's name, so the developer must provide a name.  Class fixes this by taking a String name for the class.
* @codestart
* $.Class.extend("MyOrg.MyClass",{},{})
* MyOrg.MyClass.shortName //-> 'MyClass'
* MyOrg.MyClass.fullName //->  'MyOrg.MyClass'
* @codeend
*
Construtors

* Class uses static and class initialization constructor functions.
* @codestart
* $.Class.extend("MyClass",
* {
*   init: function(){} //static constructor
* },
* {
*   init: function(){} //prototype constructor
* })
* @codeend
*
The static constructor is called after
* a class has been created.
* This is a good place to add introspection and similar class setup code.

*
*
The prototype constructor is called whenever a new instance of the class is created.
*

*
* @init Creating a new instance of an object that has extended jQuery.Class
*     calls the init prototype function and returns a new instance of the class.
*
*/

jQuery.Class = function(){
	if(arguments.length) this.extend.apply(this, arguments)
};

/* @Static*/
$.extend($.Class,{
	/**
	* @function callback
	* Returns a callback function for a function on this Class.
	* The callback function ensures that 'this' is set appropriately.
	* @codestart
	* $.Class.extend("MyClass",{
	*     getData : function(){
	*         this.showing = null;
	*         $.get("data.json",this.callback('gotData'),'json')
	*     },
	*     gotData : function(data){
	*         this.showing = data;
	*     }
	* },{});
	* MyClass.showData();
	* @codeend
	*
Currying Arguments

	* Additional arguments to callback will fill in arguments on the returning function.
	* @codestart
	* $.Class.extend("MyClass",{
	*    getData : function(callback){
	*      $.get("data.json",this.callback('process',callback),'json');
	*    },
	*    process : function(callback, jsonData){ //callback is added as first argument
	*        jsonData.processed = true;
	*        callback(jsonData);
	*    }
	* },{});
	* MyClass.getData(showDataFunc)
	* @codeend
	*
Nesting Functions

	* Callback can take an array of functions to call as the first argument.  When the returned callback function
	* is called each function in the array is passed the return value of the prior function.  This is often used
	* to eliminate currying initial arguments.
	* @codestart
	* $.Class.extend("MyClass",{
	*    getData : function(callback){
	*      //calls process, then callback with value from process
	*      $.get("data.json",this.callback(['process2',callback]),'json')
	*    },
	*    process2 : function(type,jsonData){
	*        jsonData.processed = true;
	*        return [jsonData];
	*    }
	* },{});
	* MyClass.getData(showDataFunc);
	* @codeend
	* @param {String|Array} fname If a string, it represents the function to be called.
	* If it is an array, it will call each function in order and pass the return value of the prior function to the
	* next function.
	* @return {Function} the callback function.
	*/
	callback: function(funcs){

		//args that should be curried
		var args = jQuery.makeArray(arguments),
			self;

		funcs = args.shift();

		if( !jQuery.isArray(funcs) ) {
			funcs = [funcs];
		}

		self = this;
		return function(){
			var cur = args.concat(jQuery.makeArray(arguments)),
				isString,
				length = funcs.length,
				f =0, func;

			for(; f < length; f++ ) {
				if( !funcs[f] ) {
					continue;
				}
				func = funcs[f];
				isString = typeof func == "string";
				if( isString && self._set_called ) {
					self.called = func;
				}
				cur = ( isString ? self[func] : func ).apply(self, cur || []);
				if( f < length- 1 ){
					cur = !jQuery.isArray(cur) || cur._use_call ? [cur] : cur
				}
			}
			return cur;
		}
	},
	/**
	*   @function getObject
	*   Gets an object from a String.
	*   If the object or namespaces the string represent do not
	*   exist it will create them.
	*   @codestart
	*   Foo = {Bar: {Zar: {"Ted"}}}
	*   $.Class.getobject("Foo.Bar.Zar") //-> "Ted"
	*   @codeend
	*   @param {String} objectName the object you want to get
	*   @param {Object} [current=window] the object you want to look in.
	*   @return {Object} the object you are looking for.
	*/
	getObject: function(objectName, current){
		var current = current || window,
			parts = objectName.split(/\./)
		for(var i =0; i < parts.length; i++){
			current = current[parts[i]] || ( current[parts[i]] = {} )
		}
		return current;
	},
	/**
	 * Extends a class with new static and prototype functions.  There are a variety of ways
	 * to use extend:
	 * @codestart
	 * //with className, static and prototype functions
	 * $.Class.extend('Task',{ STATIC },{ PROTOTYPE })
	 * //with just classname and prototype functions
	 * $.Class.extend('Task',{ PROTOTYPE })
	 * //With just a className
	 * $.Class.extend('Task')
	 * @codeend
	 * @param {String} [fullName]  the classes name (used for classes w/ introspection)
	 * @param {Object} [klass]  the new classes static/class functions
	 * @param {Object} [proto]  the new classes prototype functions
	 * @return {jQuery.Class} returns the new class
	 */
	extend: function(fullName, klass, proto) {

		if(typeof fullName != 'string'){
			proto = klass;
			klass = fullName;
			fullName = null;
		}

		if(!proto){
			proto = klass;
			klass = null;
		}

		proto = proto || {};
		var _super_class = this;
		var _super = this.prototype;
		// Instantiate a base class (but only create the instance,
		// don't run the init constructor)
		initializing = true;
		var prototype = new this();
		initializing = false;
		// Copy the properties over onto the new prototype
		inheritProps(proto, _super, prototype);

		// The dummy class constructor
		function Class() {
		  // All construction is actually done in the init method
		  if(initializing) return;

		  if(this.constructor !== Class && arguments.length){  //we are being called w/o new
			  return makeClass.apply(null, arguments)
		  } else {												//we are being called w/ new
			 //this.id = (++id);
			 if(this.setup) this.setup.apply(this, arguments);
			 if(this.init)  this.init.apply(this, arguments);
		  }
		}
		for(var name in this){
			if(this.hasOwnProperty(name) &&
				name != 'prototype'&&
				name != 'defaults' &&
				name != 'getObject'){
				Class[name] = this[name];
			}
		}
		$.extend(Class,{
			/**
			 * @function newInstance
			 * Creates a new instance of the class.  This method is useful for creating new instances
			 * with arbitrary parameters.
			 *
Example

			 * @codestart
			 * $.Class.extend("MyClass",{},{})
			 * var mc = MyClass.newInstance.apply(null, new Array(parseInt(Math.random()*10,10))
			 * @codeend
			 */
			newInstance : newInstance,
			rawInstance : rawInstance,
			extend : arguments.callee,
			setup : setup
		});

		//copy properties from current class to static

		//do static inheritence
		inheritProps(klass, this, Class)

		var shortName,
			namespace;

		if (fullName) {
			var current = window
			var parts = fullName.split(/\./)
			for(var i =0; i < parts.length-1; i++){
				current = current[parts[i]] || ( current[parts[i]] = {} )
			}
			namespace = current;
			shortName = parts[parts.length - 1];

			//@steal-remove-start
			steal.dev.isHappyName(fullName)
			//@steal-remove-end
		}

		Class.prototype = prototype;
		//Provide a reference to this class
		Class.prototype.Class = Class; //only changing buff prototype
		Class.prototype.constructor = Class; //only buff prototype
		// Enforce the constructor to be what we expect
		Class.constructor = Class;

		Class.namespace = namespace;
		Class.shortName = shortName
		/**
		 * @attribute fullName
		 * The full name of the class, including namespace, provided for introspection purposes.
		 * @codestart
		 * $.Class.extend("MyOrg.MyClass",{},{})
		 * MyOrg.MyClass.shortName //-> 'MyClass'
		 * MyOrg.MyClass.fullName //->  'MyOrg.MyClass'
		 * @codeend
		 */
		Class.fullName = fullName;

		Class.setup.apply(Class, [_super_class].concat( $.makeArray(arguments) ));

		if(Class.init) Class.init(Class);

		/* @Prototype*/

		if(shortName){
			current[shortName] = Class;
		}

		return Class;
		/* @function init
		 * Called with the same arguments as new Class(arguments ...) when a new instance is created.
		 * @codestart
		 * $.Class.extend("MyClass",
		 * {
		 *    init: function(val){
		 *       this.val = val;
		 *    }
		 * })
		 * var mc = new MyClass("Check Check")
		 * mc.val //-> 'Check Check'
		 * @codeend
		 */
		//Breaks up code
		/**
		 * @attribute Class
		 * Access to the static properties of the instance's class.
		 * @codestart
		 * $.Class.extend("MyClass", {classProperty : true}, {});
		 * var mc2 = new MyClass();
		 * mc.Class.classProperty = true;
		 * var mc2 = new mc.Class(); //creates a new MyClass
		 * @codeend
		 */
	}

})

jQuery.Class.prototype = {
  /**
   * @function callback
   * Returns a callback function.  This does the same thing as and is described better in [jQuery.Class.static.callback].
   * The only difference is this callback works
   * on a instance instead of a class.
   * @param {String|Array} fname If a string, it represents the function to be called.
   * If it is an array, it will call each function in order and pass the return value of the prior function to the
   * next function.
   * @return {Function} the callback function
   */
  callback : jQuery.Class.callback
}

})();
<commit_msg>class demo<commit_after>//jQuery.Class
// This is a modified version of John Resig's class
// It provides class level inheritence and callbacks.

steal.plugin("jquery").then(function($){

	//if we are initializing a new class
var initializing = false,

	//tests if we can get super in .toString()
	fnTest = /xyz/.test(function(){xyz;}) ? /\b_super\b/ : /.*/,

	newInstance = function(){
		initializing = true;
		var inst = new this();
		initializing = false;
		if ( inst.setup )
			inst.setup.apply(inst, arguments);
		if ( inst.init )
			inst.init.apply(inst, arguments);
		return inst;
	},
	rawInstance = function(){
		initializing = true;
		var inst = new this();
		initializing = false;
		return inst;
	},
	/**
	 * Copy and overwrite options from old class
	 * @param {Object} oldClass
	 * @param {Object} options
	 */
	setup = function(oldClass, options){
		this.defaults = $.extend(true, {},oldClass.defaults, this.defaults);
	},
	toString = function(){
		return this.className || Object.prototype.toString.call(this)
	},
	id = 1,
	inheritProps = function(newProps, oldProps, addTo){
		addTo = addTo || newProps
		for(var name in newProps) {
		  // Check if we're overwriting an existing function
		  addTo[name] = typeof newProps[name] == "function" &&
			typeof oldProps[name] == "function" && fnTest.test(newProps[name]) ?
			(function(name, fn){
			  return function() {
				var tmp = this._super, ret;

				// Add a new ._super() method that is the same method
				// but on the super-class
				this._super = oldProps[name];

				// The method only need to be bound temporarily, so we
				// remove it when we're done executing
				ret = fn.apply(this, arguments);
				this._super = tmp;
				return ret;
			  };
			})(name, newProps[name]) :
			newProps[name];
		}
	};
// The base Class implementation (does nothing)

/**
* @constructor jQuery.Class
* @plugin jquery/class
* @tag core
* @download dist/jquery/jquery.class.js
* Class provides simulated inheritance in JavaScript.
* It is based off John Resig's [http://ejohn.org/blog/simple-javascript-inheritance/|Simple Class]
* Inheritance library.  Besides prototypal inheritance, it adds a few important features:
*

*
Static inheritance

*
Introspection

*
Easy callback function creation

*
Namespaces

*

*
Definitions

* Classes have static and prototype properties and
* methods:
* @codestart
* //STATIC
* MyClass.staticProperty  //shared property
*
* //PROTOTYPE
* myclass = new MyClass()
* myclass.prototypeMethod() //instance method
* @codeend
*
*
Examples

*
Basic example

* Creates a class with a shortName (for introspection), static, and prototype members:
* @codestart
* jQuery.Class.extend('Monster',
* /* @static *|
* {
*   count: 0
* },
* /* @prototype *|
* {
*   init : function(name){
*     this.name = name;
*     this.Class.count++
*   }
* })
* hydra = new Monster('hydra')
* dragon = new Monster('dragon')
* hydra.name        // -> hydra
* Monster.count     // -> 2
* Monster.shortName // -> 'Monster'
* @codeend
* Notice that the prototype init function is called when a new instance of Monster is created.
*
Static property inheritance

* Demonstrates inheriting a class property.
* @codestart
* jQuery.Class.extend("First",
* {
*     staticMethod : function(){ return 1;}
* },{})
*
* First.extend("Second",{
*     staticMethod : function(){ return this._super()+1;}
* },{})
*
* Second.staticMethod() // -> 2
* @codeend
*
Introspection

* Often, it's nice to create classes whose name helps determine functionality.  Ruby on
* Rails's [http://api.rubyonrails.org/classes/ActiveRecord/Base.html|ActiveRecord] ORM class
* is a great example of this.  Unfortunately, JavaScript doesn't have a way of determining
* an object's name, so the developer must provide a name.  Class fixes this by taking a String name for the class.
* @codestart
* $.Class.extend("MyOrg.MyClass",{},{})
* MyOrg.MyClass.shortName //-> 'MyClass'
* MyOrg.MyClass.fullName //->  'MyOrg.MyClass'
* @codeend
*
Construtors

* Class uses static and class initialization constructor functions.
* @codestart
* $.Class.extend("MyClass",
* {
*   init: function(){} //static constructor
* },
* {
*   init: function(){} //prototype constructor
* })
* @codeend
*
The static constructor is called after
* a class has been created.
* This is a good place to add introspection and similar class setup code.

*
*
The prototype constructor is called whenever a new instance of the class is created.
*

*
Use

*
[jQuery.Controller] and [jQuery.Model] use $.Class to bridge the gap between
* jQuery's functional programming style and Object Oriented Programming.

*
JavaScript's prototypal inheritence is extremely powerful, but limited
* in a few critical ways.  Class patches these problems but conforms to
* how constructor functions work in every way possible.
*

*

*
*
* @init Creating a new instance of an object that has extended jQuery.Class
*     calls the init prototype function and returns a new instance of the class.
*
*/

jQuery.Class = function(){
	if(arguments.length) this.extend.apply(this, arguments)
};

/* @Static*/
$.extend($.Class,{
	/**
	* @function callback
	* Returns a callback function for a function on this Class.
	* The callback function ensures that 'this' is set appropriately.
	* @codestart
	* $.Class.extend("MyClass",{
	*     getData : function(){
	*         this.showing = null;
	*         $.get("data.json",this.callback('gotData'),'json')
	*     },
	*     gotData : function(data){
	*         this.showing = data;
	*     }
	* },{});
	* MyClass.showData();
	* @codeend
	*
Currying Arguments

	* Additional arguments to callback will fill in arguments on the returning function.
	* @codestart
	* $.Class.extend("MyClass",{
	*    getData : function(callback){
	*      $.get("data.json",this.callback('process',callback),'json');
	*    },
	*    process : function(callback, jsonData){ //callback is added as first argument
	*        jsonData.processed = true;
	*        callback(jsonData);
	*    }
	* },{});
	* MyClass.getData(showDataFunc)
	* @codeend
	*
Nesting Functions

	* Callback can take an array of functions to call as the first argument.  When the returned callback function
	* is called each function in the array is passed the return value of the prior function.  This is often used
	* to eliminate currying initial arguments.
	* @codestart
	* $.Class.extend("MyClass",{
	*    getData : function(callback){
	*      //calls process, then callback with value from process
	*      $.get("data.json",this.callback(['process2',callback]),'json')
	*    },
	*    process2 : function(type,jsonData){
	*        jsonData.processed = true;
	*        return [jsonData];
	*    }
	* },{});
	* MyClass.getData(showDataFunc);
	* @codeend
	* @param {String|Array} fname If a string, it represents the function to be called.
	* If it is an array, it will call each function in order and pass the return value of the prior function to the
	* next function.
	* @return {Function} the callback function.
	*/
	callback: function(funcs){

		//args that should be curried
		var args = jQuery.makeArray(arguments),
			self;

		funcs = args.shift();

		if( !jQuery.isArray(funcs) ) {
			funcs = [funcs];
		}

		self = this;
		return function(){
			var cur = args.concat(jQuery.makeArray(arguments)),
				isString,
				length = funcs.length,
				f =0, func;

			for(; f < length; f++ ) {
				if( !funcs[f] ) {
					continue;
				}
				func = funcs[f];
				isString = typeof func == "string";
				if( isString && self._set_called ) {
					self.called = func;
				}
				cur = ( isString ? self[func] : func ).apply(self, cur || []);
				if( f < length- 1 ){
					cur = !jQuery.isArray(cur) || cur._use_call ? [cur] : cur
				}
			}
			return cur;
		}
	},
	/**
	*   @function getObject
	*   Gets an object from a String.
	*   If the object or namespaces the string represent do not
	*   exist it will create them.
	*   @codestart
	*   Foo = {Bar: {Zar: {"Ted"}}}
	*   $.Class.getobject("Foo.Bar.Zar") //-> "Ted"
	*   @codeend
	*   @param {String} objectName the object you want to get
	*   @param {Object} [current=window] the object you want to look in.
	*   @return {Object} the object you are looking for.
	*/
	getObject: function(objectName, current){
		var current = current || window,
			parts = objectName.split(/\./)
		for(var i =0; i < parts.length; i++){
			current = current[parts[i]] || ( current[parts[i]] = {} )
		}
		return current;
	},
	/**
	 * Extends a class with new static and prototype functions.  There are a variety of ways
	 * to use extend:
	 * @codestart
	 * //with className, static and prototype functions
	 * $.Class.extend('Task',{ STATIC },{ PROTOTYPE })
	 * //with just classname and prototype functions
	 * $.Class.extend('Task',{ PROTOTYPE })
	 * //With just a className
	 * $.Class.extend('Task')
	 * @codeend
	 * @param {String} [fullName]  the classes name (used for classes w/ introspection)
	 * @param {Object} [klass]  the new classes static/class functions
	 * @param {Object} [proto]  the new classes prototype functions
	 * @return {jQuery.Class} returns the new class
	 */
	extend: function(fullName, klass, proto) {

		if(typeof fullName != 'string'){
			proto = klass;
			klass = fullName;
			fullName = null;
		}

		if(!proto){
			proto = klass;
			klass = null;
		}

		proto = proto || {};
		var _super_class = this;
		var _super = this.prototype;
		// Instantiate a base class (but only create the instance,
		// don't run the init constructor)
		initializing = true;
		var prototype = new this();
		initializing = false;
		// Copy the properties over onto the new prototype
		inheritProps(proto, _super, prototype);

		// The dummy class constructor
		function Class() {
		  // All construction is actually done in the init method
		  if(initializing) return;

		  if(this.constructor !== Class && arguments.length){  //we are being called w/o new
			  return makeClass.apply(null, arguments)
		  } else {												//we are being called w/ new
			 //this.id = (++id);
			 if(this.setup) this.setup.apply(this, arguments);
			 if(this.init)  this.init.apply(this, arguments);
		  }
		}
		for(var name in this){
			if(this.hasOwnProperty(name) &&
				name != 'prototype'&&
				name != 'defaults' &&
				name != 'getObject'){
				Class[name] = this[name];
			}
		}
		$.extend(Class,{
			/**
			 * @function newInstance
			 * Creates a new instance of the class.  This method is useful for creating new instances
			 * with arbitrary parameters.
			 *
Example

			 * @codestart
			 * $.Class.extend("MyClass",{},{})
			 * var mc = MyClass.newInstance.apply(null, new Array(parseInt(Math.random()*10,10))
			 * @codeend
			 */
			newInstance : newInstance,
			rawInstance : rawInstance,
			extend : arguments.callee,
			setup : setup
		});

		//copy properties from current class to static

		//do static inheritence
		inheritProps(klass, this, Class)

		var shortName,
			namespace;

		if (fullName) {
			var current = window
			var parts = fullName.split(/\./)
			for(var i =0; i < parts.length-1; i++){
				current = current[parts[i]] || ( current[parts[i]] = {} )
			}
			namespace = current;
			shortName = parts[parts.length - 1];

			//@steal-remove-start
			steal.dev.isHappyName(fullName)
			//@steal-remove-end
		}

		Class.prototype = prototype;
		//Provide a reference to this class
		Class.prototype.Class = Class; //only changing buff prototype
		Class.prototype.constructor = Class; //only buff prototype
		// Enforce the constructor to be what we expect
		Class.constructor = Class;

		Class.namespace = namespace;
		Class.shortName = shortName
		/**
		 * @attribute fullName
		 * The full name of the class, including namespace, provided for introspection purposes.
		 * @codestart
		 * $.Class.extend("MyOrg.MyClass",{},{})
		 * MyOrg.MyClass.shortName //-> 'MyClass'
		 * MyOrg.MyClass.fullName //->  'MyOrg.MyClass'
		 * @codeend
		 */
		Class.fullName = fullName;

		Class.setup.apply(Class, [_super_class].concat( $.makeArray(arguments) ));

		if(Class.init) Class.init(Class);

		/* @Prototype*/

		if(shortName){
			current[shortName] = Class;
		}

		return Class;
		/* @function init
		 * Called with the same arguments as new Class(arguments ...) when a new instance is created.
		 * @codestart
		 * $.Class.extend("MyClass",
		 * {
		 *    init: function(val){
		 *       this.val = val;
		 *    }
		 * })
		 * var mc = new MyClass("Check Check")
		 * mc.val //-> 'Check Check'
		 * @codeend
		 */
		//Breaks up code
		/**
		 * @attribute Class
		 * Access to the static properties of the instance's class.
		 * @codestart
		 * $.Class.extend("MyClass", {classProperty : true}, {});
		 * var mc2 = new MyClass();
		 * mc.Class.classProperty = true;
		 * var mc2 = new mc.Class(); //creates a new MyClass
		 * @codeend
		 */
	}

})

jQuery.Class.prototype = {
  /**
   * @function callback
   * Returns a callback function.  This does the same thing as and is described better in [jQuery.Class.static.callback].
   * The only difference is this callback works
   * on a instance instead of a class.
   * @param {String|Array} fname If a string, it represents the function to be called.
   * If it is an array, it will call each function in order and pass the return value of the prior function to the
   * next function.
   * @return {Function} the callback function
   */
  callback : jQuery.Class.callback
}

})();
<|endoftext|>


<commit_before>// See the file COPYRIGHT for copyright information.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//
// Initialize UI
//

function initIncidentPage() {
    function loadedBody() {
        addLocationAddressOptions();
        disableEditing();
        loadAndDisplayIncident();
    }

    loadBody(loadedBody);
}

//
// Load incident
//

var incident = null;

function loadIncident(success) {
    function loaded(data, status, request) {
        incident = data;

        if (success != undefined) {
            success();
        }
    }

    var url = incidentsURL + "/ss" + incidentNumber;

    function ok(data, status, xhr) {
        incident = data;

        if (success != undefined) {
            success();
        }
    }

    function fail(xhr, status, error) {
        disableEditing();
        var message = "Failed to load incident:\n" + error
        console.error(message);
        window.alert(message);
    }

    $.ajax({
        "url": url,
        "method": "GET",
        "dataType": "json",
        "success": ok,
        "error": fail,
    });
}

function loadAndDisplayIncident(success) {
    function loaded() {
        drawIncidentFields();
        enableEditing();

        if (success != undefined) {
            success();
        }
    }

    loadIncident(loaded);
}

//
// Draw all fields
//

function drawIncidentFields() {
    drawNumber();
    drawState();
    drawPriority();
    drawSummary();
    drawRangers();
    drawIncidentTypes();
    drawLocationName();
    drawLocationAddressRadialHour();
    drawLocationAddressRadialMinute();
    drawLocationAddressConcentric();
    drawLocationDescription();
    drawReportEntries();
}

//
// Add option elements to location address select elements
//

function addLocationAddressOptions() {
    var hours = range(1, 13);
    for (var i in hours) {
        var hour = padTwo(hours[i]);
        $("#incident_location_address_radial_hour")
            .append($("<option />", { "value": hour, "text": hour }))
            ;
    }

    var minutes = range(0, 12, 5);
    for (var i in minutes) {
        var minute = padTwo(minutes[i]);
        $("#incident_location_address_radial_minute")
            .append($("<option />", { "value": minute, "text": minute }))
            ;
    }

    for (var id in concentricStreetNameByID) {
        var name = concentricStreetNameByID[id];
        $("#incident_location_address_concentric")
            .append($("<option />", { "value": id, "text": name }))
            ;
    }
}

//
// Populate incident number
//

function drawNumber() {
    $("#incident_number").text(incident.number);
}

//
// Populate incident state
//

function drawState() {
    selectOptionWithValue(
        $("#incident_state"), stateForIncident(incident)
    );
}

//
// Populate incident priority
//

function drawPriority() {
    selectOptionWithValue(
        $("#incident_priority"), incident.priority
    );
}

//
// Populate incident summary
//

function drawSummary() {
    $("#incident_summary").attr("value", summarizeIncident(incident));
}

//
// Populate Rangers list
//

var _rangerItem = null;

function drawRangers() {
    if (_rangerItem == null) {
        _rangerItem = $("#incident_rangers_list")
            .children(".list-group-item:first")
            ;
    }

    var items = [];

    for (var i in incident.ranger_handles) {
        var item = _rangerItem.clone();
        item.append(incident.ranger_handles[i]);
        items.push(item);
    }

    var container = $("#incident_rangers_list");
    container.empty();
    container.append(items);
}

//
// Populate incident types list
//

var _typesItem = null;

function drawIncidentTypes() {
    if (_typesItem == null) {
        _typesItem = $("#incident_types_list")
            .children(".list-group-item:first")
            ;
    }

    var items = [];

    for (var i in incident.incident_types) {
        var item = _typesItem.clone();
        item.append(incident.incident_types[i]);
        items.push(item);
    }

    var container = $("#incident_types_list");
    container.empty();
    container.append(items);
}

//
// Populate location
//

function drawLocationName() {
    if (incident.location != undefined) {
        if (incident.location.name != undefined) {
            $("#incident_location_name").attr("value", incident.location.name);
        }
    }
}

function drawLocationAddressRadialHour() {
    var hour = null;
    if (incident.location != undefined) {
        if (incident.location.radial_hour != undefined) {
            hour = padTwo(incident.location.radial_hour);
        }
    }
    selectOptionWithValue(
        $("#incident_location_address_radial_hour"), hour
    );
}

function drawLocationAddressRadialMinute() {
    var minute = null;
    if (incident.location != undefined) {
        if (incident.location.radial_minute != undefined) {
            minute = normalizeMinute(incident.location.radial_minute);
        }
    }
    selectOptionWithValue(
        $("#incident_location_address_radial_minute"), minute
    );
}

function drawLocationAddressConcentric() {
    var concentric = null;
    if (incident.location != undefined) {
        if (incident.location.concentric != undefined) {
            concentric = incident.location.concentric;
        }
    }
    selectOptionWithValue(
        $("#incident_location_address_concentric"), concentric
    );
}

function drawLocationDescription() {
    if (incident.location != undefined) {
        if (incident.location.description != undefined) {
            $("#incident_location_description")
                .attr("value", incident.location.description)
                ;
        }
    }
}

//
// Populate report entry text
//

function reportEntryElement(entry) {
    // Build a container for the entry

    var entryContainer = $("<div />", {"class": "report_entry"});

    if (entry.system_entry) {
        entryContainer.addClass("report_entry_system");
    } else {
        entryContainer.addClass("report_entry_user");
    }

    // Add the timestamp and author

    metaDataContainer = $("<p />", {"class": "report_entry_metadata"})

    var timeStampContainer = timeElement(new Date(entry.created));
    timeStampContainer.addClass("report_entry_timestamp");

    metaDataContainer.append([timeStampContainer, ", "]);

    var author = entry.author;
    if (author == undefined) {
        author = "(unknown)";
    }
    var authorContainer = $("<span />");
    authorContainer.text(entry.author);
    authorContainer.addClass("report_entry_author");

    metaDataContainer.append(author);
    metaDataContainer.append(":");

    entryContainer.append(metaDataContainer);

    // Add report text

    var lines = entry.text.split("\n");
    for (var i in lines) {
        var textContainer = $("<p />", {"class": "report_entry_text"});
        textContainer.text(lines[i]);

        entryContainer.append(textContainer);
    }

    // Return container

    return entryContainer;
}

function drawReportEntries() {
    var container = $("#incident_report");
    container.empty();

    var entries = incident.report_entries;

    if (entries != undefined) {
        for (var i in entries) {
            container.append(reportEntryElement(entries[i]));
        }
    }
}

//
// Editing
//

function sendEdits(edits, sender) {
    edits.number = incident.number;

    var jsonText = JSON.stringify(edits);

    console.log("Sending edit: " + jsonText);

    var url = incidentsURL + "/" + incident.number;

    function ok(data, status, xhr) {
        controlHasSuccess(sender);
        loadAndDisplayIncident();
        // Clear success state after a 1s delay
        sender.delay("1000").queue(function() {controlClear(sender)});
    }

    function fail(xhr, status, error) {
        var message = "Failed to apply edit:\n" + error
        console.error(message);
        controlHasError(sender);
        loadAndDisplayIncident();
        window.alert(message);
    }

    $.ajax({
        "url": url,
        "method": "POST",
        "contentType": "application/json",
        "data": jsonText,
        "success": ok,
        "error": fail,
    })
}

function editFromElement(element, jsonKey, transform) {
    var value = element.val();

    if (transform != undefined) {
        value = transform(value);
    }

    // Build a JSON object representing the requested edits

    var edits = {};

    var keyPath = jsonKey.split(".");
    var lastKey = keyPath.pop();

    var current = edits;
    for (var i in keyPath) {
        var next = {};
        current[keyPath[i]] = next;
        current = next;
    }
    current[lastKey] = value;

    // Location must include type

    if (edits.location != undefined) {
        edits.location.type = "garett";  // UI only supports one type
    }

    // Send request to server

    sendEdits(edits, element);
}

function editState() {
    editFromElement($("#incident_state"), "state");
}

function editPriority() {
    editFromElement($("#incident_priority"), "priority", Number);
}

function editSummary() {
    editFromElement($("#incident_summary"), "summary");
}

function editLocationName() {
    editFromElement($("#incident_location_name"), "location.name");
}

function editLocationAddressRadialHour() {
    editFromElement(
        $("#incident_location_address_radial_hour"),
        "location.radial_hour",
        Number
    );
}

function editLocationAddressRadialMinute() {
    editFromElement(
        $("#incident_location_address_radial_minute"),
        "location.radial_minute",
        Number
    );
}

function editLocationAddressConcentric() {
    editFromElement(
        $("#incident_location_address_concentric"),
        "location.concentric",
        Number
    );
}

function editLocationDescription() {
    editFromElement($("#incident_location_description"), "location.description");
}

function removeRanger(sender) {
    rangerHandle = $(sender).parent().text().trim();

    sendEdits(
        {
            "ranger_handles": incident.ranger_handles.filter(
                function(h) { return h != rangerHandle }
            ),
        },
        $(sender)
    );
}

function removeIncidentType(sender) {
    incidentType = $(sender).parent().text().trim();

    sendEdits(
        {
            "incident_types": incident.incident_types.filter(
                function(t) { return t != incidentType }
            ),
        },
        $(sender)
    );
}
<commit_msg>Remove junk<commit_after>// See the file COPYRIGHT for copyright information.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//
// Initialize UI
//

function initIncidentPage() {
    function loadedBody() {
        addLocationAddressOptions();
        disableEditing();
        loadAndDisplayIncident();
    }

    loadBody(loadedBody);
}

//
// Load incident
//

var incident = null;

function loadIncident(success) {
    function loaded(data, status, request) {
        incident = data;

        if (success != undefined) {
            success();
        }
    }

    var url = incidentsURL + "/" + incidentNumber;

    function ok(data, status, xhr) {
        incident = data;

        if (success != undefined) {
            success();
        }
    }

    function fail(xhr, status, error) {
        disableEditing();
        var message = "Failed to load incident:\n" + error
        console.error(message);
        window.alert(message);
    }

    $.ajax({
        "url": url,
        "method": "GET",
        "dataType": "json",
        "success": ok,
        "error": fail,
    });
}

function loadAndDisplayIncident(success) {
    function loaded() {
        drawIncidentFields();
        enableEditing();

        if (success != undefined) {
            success();
        }
    }

    loadIncident(loaded);
}

//
// Draw all fields
//

function drawIncidentFields() {
    drawNumber();
    drawState();
    drawPriority();
    drawSummary();
    drawRangers();
    drawIncidentTypes();
    drawLocationName();
    drawLocationAddressRadialHour();
    drawLocationAddressRadialMinute();
    drawLocationAddressConcentric();
    drawLocationDescription();
    drawReportEntries();
}

//
// Add option elements to location address select elements
//

function addLocationAddressOptions() {
    var hours = range(1, 13);
    for (var i in hours) {
        var hour = padTwo(hours[i]);
        $("#incident_location_address_radial_hour")
            .append($("<option />", { "value": hour, "text": hour }))
            ;
    }

    var minutes = range(0, 12, 5);
    for (var i in minutes) {
        var minute = padTwo(minutes[i]);
        $("#incident_location_address_radial_minute")
            .append($("<option />", { "value": minute, "text": minute }))
            ;
    }

    for (var id in concentricStreetNameByID) {
        var name = concentricStreetNameByID[id];
        $("#incident_location_address_concentric")
            .append($("<option />", { "value": id, "text": name }))
            ;
    }
}

//
// Populate incident number
//

function drawNumber() {
    $("#incident_number").text(incident.number);
}

//
// Populate incident state
//

function drawState() {
    selectOptionWithValue(
        $("#incident_state"), stateForIncident(incident)
    );
}

//
// Populate incident priority
//

function drawPriority() {
    selectOptionWithValue(
        $("#incident_priority"), incident.priority
    );
}

//
// Populate incident summary
//

function drawSummary() {
    $("#incident_summary").attr("value", summarizeIncident(incident));
}

//
// Populate Rangers list
//

var _rangerItem = null;

function drawRangers() {
    if (_rangerItem == null) {
        _rangerItem = $("#incident_rangers_list")
            .children(".list-group-item:first")
            ;
    }

    var items = [];

    for (var i in incident.ranger_handles) {
        var item = _rangerItem.clone();
        item.append(incident.ranger_handles[i]);
        items.push(item);
    }

    var container = $("#incident_rangers_list");
    container.empty();
    container.append(items);
}

//
// Populate incident types list
//

var _typesItem = null;

function drawIncidentTypes() {
    if (_typesItem == null) {
        _typesItem = $("#incident_types_list")
            .children(".list-group-item:first")
            ;
    }

    var items = [];

    for (var i in incident.incident_types) {
        var item = _typesItem.clone();
        item.append(incident.incident_types[i]);
        items.push(item);
    }

    var container = $("#incident_types_list");
    container.empty();
    container.append(items);
}

//
// Populate location
//

function drawLocationName() {
    if (incident.location != undefined) {
        if (incident.location.name != undefined) {
            $("#incident_location_name").attr("value", incident.location.name);
        }
    }
}

function drawLocationAddressRadialHour() {
    var hour = null;
    if (incident.location != undefined) {
        if (incident.location.radial_hour != undefined) {
            hour = padTwo(incident.location.radial_hour);
        }
    }
    selectOptionWithValue(
        $("#incident_location_address_radial_hour"), hour
    );
}

function drawLocationAddressRadialMinute() {
    var minute = null;
    if (incident.location != undefined) {
        if (incident.location.radial_minute != undefined) {
            minute = normalizeMinute(incident.location.radial_minute);
        }
    }
    selectOptionWithValue(
        $("#incident_location_address_radial_minute"), minute
    );
}

function drawLocationAddressConcentric() {
    var concentric = null;
    if (incident.location != undefined) {
        if (incident.location.concentric != undefined) {
            concentric = incident.location.concentric;
        }
    }
    selectOptionWithValue(
        $("#incident_location_address_concentric"), concentric
    );
}

function drawLocationDescription() {
    if (incident.location != undefined) {
        if (incident.location.description != undefined) {
            $("#incident_location_description")
                .attr("value", incident.location.description)
                ;
        }
    }
}

//
// Populate report entry text
//

function reportEntryElement(entry) {
    // Build a container for the entry

    var entryContainer = $("<div />", {"class": "report_entry"});

    if (entry.system_entry) {
        entryContainer.addClass("report_entry_system");
    } else {
        entryContainer.addClass("report_entry_user");
    }

    // Add the timestamp and author

    metaDataContainer = $("<p />", {"class": "report_entry_metadata"})

    var timeStampContainer = timeElement(new Date(entry.created));
    timeStampContainer.addClass("report_entry_timestamp");

    metaDataContainer.append([timeStampContainer, ", "]);

    var author = entry.author;
    if (author == undefined) {
        author = "(unknown)";
    }
    var authorContainer = $("<span />");
    authorContainer.text(entry.author);
    authorContainer.addClass("report_entry_author");

    metaDataContainer.append(author);
    metaDataContainer.append(":");

    entryContainer.append(metaDataContainer);

    // Add report text

    var lines = entry.text.split("\n");
    for (var i in lines) {
        var textContainer = $("<p />", {"class": "report_entry_text"});
        textContainer.text(lines[i]);

        entryContainer.append(textContainer);
    }

    // Return container

    return entryContainer;
}

function drawReportEntries() {
    var container = $("#incident_report");
    container.empty();

    var entries = incident.report_entries;

    if (entries != undefined) {
        for (var i in entries) {
            container.append(reportEntryElement(entries[i]));
        }
    }
}

//
// Editing
//

function sendEdits(edits, sender) {
    edits.number = incident.number;

    var jsonText = JSON.stringify(edits);

    console.log("Sending edit: " + jsonText);

    var url = incidentsURL + "/" + incident.number;

    function ok(data, status, xhr) {
        controlHasSuccess(sender);
        loadAndDisplayIncident();
        // Clear success state after a 1s delay
        sender.delay("1000").queue(function() {controlClear(sender)});
    }

    function fail(xhr, status, error) {
        var message = "Failed to apply edit:\n" + error
        console.error(message);
        controlHasError(sender);
        loadAndDisplayIncident();
        window.alert(message);
    }

    $.ajax({
        "url": url,
        "method": "POST",
        "contentType": "application/json",
        "data": jsonText,
        "success": ok,
        "error": fail,
    })
}

function editFromElement(element, jsonKey, transform) {
    var value = element.val();

    if (transform != undefined) {
        value = transform(value);
    }

    // Build a JSON object representing the requested edits

    var edits = {};

    var keyPath = jsonKey.split(".");
    var lastKey = keyPath.pop();

    var current = edits;
    for (var i in keyPath) {
        var next = {};
        current[keyPath[i]] = next;
        current = next;
    }
    current[lastKey] = value;

    // Location must include type

    if (edits.location != undefined) {
        edits.location.type = "garett";  // UI only supports one type
    }

    // Send request to server

    sendEdits(edits, element);
}

function editState() {
    editFromElement($("#incident_state"), "state");
}

function editPriority() {
    editFromElement($("#incident_priority"), "priority", Number);
}

function editSummary() {
    editFromElement($("#incident_summary"), "summary");
}

function editLocationName() {
    editFromElement($("#incident_location_name"), "location.name");
}

function editLocationAddressRadialHour() {
    editFromElement(
        $("#incident_location_address_radial_hour"),
        "location.radial_hour",
        Number
    );
}

function editLocationAddressRadialMinute() {
    editFromElement(
        $("#incident_location_address_radial_minute"),
        "location.radial_minute",
        Number
    );
}

function editLocationAddressConcentric() {
    editFromElement(
        $("#incident_location_address_concentric"),
        "location.concentric",
        Number
    );
}

function editLocationDescription() {
    editFromElement($("#incident_location_description"), "location.description");
}

function removeRanger(sender) {
    rangerHandle = $(sender).parent().text().trim();

    sendEdits(
        {
            "ranger_handles": incident.ranger_handles.filter(
                function(h) { return h != rangerHandle }
            ),
        },
        $(sender)
    );
}

function removeIncidentType(sender) {
    incidentType = $(sender).parent().text().trim();

    sendEdits(
        {
            "incident_types": incident.incident_types.filter(
                function(t) { return t != incidentType }
            ),
        },
        $(sender)
    );
}
<|endoftext|>


<commit_before>frappe.ui.form.on(cur_frm.doctype, {
	setup: function(frm) {
		frm.set_query("employee", function() {
			return {
				filters: {
					"status": "Active"
				}
			};
		});
	},
	onload: function(frm){
		if(frm.doc.__islocal){
			if(frm.doctype == "Employee Promotion"){
				frm.doc.promotion_details = [];
			}else if (frm.doctype == "Employee Transfer") {
				frm.doc.transfer_details = [];
			}
		}
	},
	employee: function(frm) {
		frm.add_fetch("employee", "company", "company");
	},
	refresh: function(frm) {
		var table;
		if(frm.doctype == "Employee Promotion"){
			table = "promotion_details";
		}else if (frm.doctype == "Employee Transfer") {
			table = "transfer_details";
		}
		if(!table){return;}
		cur_frm.fields_dict[table].grid.wrapper.find('.grid-add-row').hide();
		cur_frm.fields_dict[table].grid.add_custom_button(__('Add Row'), () => {
			if(!frm.doc.employee){
				frappe.msgprint(__("Please select Employee"));
				return;
			}
			frappe.call({
				method: 'erpnext.hr.utils.get_employee_fields_label',
				callback: function(r) {
					if(r.message){
						show_dialog(frm, table, r.message);
					}
				}
			});
		});
	}
});

var show_dialog = function(frm, table, field_labels) {
	var d = new frappe.ui.Dialog({
		title: "Update Property",
		fields: [
			{fieldname: "property", label: __('Select Property'), fieldtype:"Select", options: field_labels},
			{fieldname: "current", fieldtype: "Data", label:__('Current'), read_only: true},
			{fieldname: "field_html", fieldtype: "HTML"}
		],
		primary_action_label: __('Add to Details'),
		primary_action: () => {
			d.get_primary_btn().attr('disabled', true);
			if(d.data){
				add_to_details(frm, d, table);
			}
		}
	});
	d.fields_dict["property"].df.onchange = () => {
		let property = d.get_values().property;
		d.data.fieldname = property;
		if(!property){return;}
		frappe.call({
			method: 'erpnext.hr.utils.get_employee_field_property',
			args: {employee: frm.doc.employee, fieldname: property},
			callback: function(r) {
				if(r.message){
					d.data.current = r.message.value;
					d.data.property = r.message.label;
					d.fields_dict.field_html.$wrapper.html("");
					d.set_value('current', r.message.value);
					render_dynamic_field(d, r.message.datatype, r.message.options, property);
					d.get_primary_btn().attr('disabled', false);
				}
			}
		});
	};
	d.get_primary_btn().attr('disabled', true);
	d.data = {};
	d.show();
};

var render_dynamic_field = function(d, fieldtype, options, fieldname) {
	d.data.new = null;
	var dynamic_field = frappe.ui.form.make_control({
		df: {
			"fieldtype": fieldtype,
			"fieldname": fieldname,
			"options": options || ''
		},
		parent: d.fields_dict.field_html.wrapper,
		only_input: false
	});
	dynamic_field.make_input();
	$(dynamic_field.label_area).text(__("New"));
	dynamic_field.$input.on("change", function(e) {
		d.data.new = e.target.value;
	}).on("awesomplete-close", function(e) {
		d.data.new = e.target.value;
	});
};

var add_to_details = function(frm, d, table) {
	let data = d.data;
	if(data.fieldname){
		if(validate_duplicate(frm, table, data.fieldname)){
			frappe.show_alert({message:__("Property already added"), indicator:'orange'});
			return false;
		}
		if(data.current == data.new){
			frappe.show_alert({message:__("Nothing to change"), indicator:'orange'});
			d.get_primary_btn().attr('disabled', false);
			return false;
		}
		frm.add_child(table, {
			fieldname: data.fieldname,
			property: data.property,
			current: data.current,
			new: data.new
		});
		frm.refresh_field(table);
		d.fields_dict.field_html.$wrapper.html("");
		d.set_value("property", "");
		d.set_value('current', "");
		frappe.show_alert({message:__("Added to details"),indicator:'green'});
		d.data = {};
	}else {
		frappe.show_alert({message:__("Value missing"),indicator:'red'});
	}
};

var validate_duplicate =  function(frm, table, fieldname){
	let duplicate = false;
	$.each(frm.doc[table], function(i, detail) {
		if(detail.fieldname === fieldname){
			duplicate = true;
			return;
		}
	});
	return duplicate;
};
<commit_msg>Fix updation of new values<commit_after>frappe.ui.form.on(cur_frm.doctype, {
	setup: function(frm) {
		frm.set_query("employee", function() {
			return {
				filters: {
					"status": "Active"
				}
			};
		});
	},
	onload: function(frm){
		if(frm.doc.__islocal){
			if(frm.doctype == "Employee Promotion"){
				frm.doc.promotion_details = [];
			}else if (frm.doctype == "Employee Transfer") {
				frm.doc.transfer_details = [];
			}
		}
	},
	employee: function(frm) {
		frm.add_fetch("employee", "company", "company");
	},
	refresh: function(frm) {
		var table;
		if(frm.doctype == "Employee Promotion"){
			table = "promotion_details";
		}else if (frm.doctype == "Employee Transfer") {
			table = "transfer_details";
		}
		if(!table){return;}
		cur_frm.fields_dict[table].grid.wrapper.find('.grid-add-row').hide();
		cur_frm.fields_dict[table].grid.add_custom_button(__('Add Row'), () => {
			if(!frm.doc.employee){
				frappe.msgprint(__("Please select Employee"));
				return;
			}
			frappe.call({
				method: 'erpnext.hr.utils.get_employee_fields_label',
				callback: function(r) {
					if(r.message){
						show_dialog(frm, table, r.message);
					}
				}
			});
		});
	}
});

var show_dialog = function(frm, table, field_labels) {
	var d = new frappe.ui.Dialog({
		title: "Update Property",
		fields: [
			{fieldname: "property", label: __('Select Property'), fieldtype:"Select", options: field_labels},
			{fieldname: "current", fieldtype: "Data", label:__('Current'), read_only: true},
			{fieldname: "field_html", fieldtype: "HTML"}
		],
		primary_action_label: __('Add to Details'),
		primary_action: () => {
			d.get_primary_btn().attr('disabled', true);
			if(d.data) {
				var input = $('[data-fieldname="field_html"] input');
				d.data.new = input.val();
				$(input).remove();
				add_to_details(frm, d, table);
			}
		}
	});
	d.fields_dict["property"].df.onchange = () => {
		let property = d.get_values().property;
		d.data.fieldname = property;
		if(!property){return;}
		frappe.call({
			method: 'erpnext.hr.utils.get_employee_field_property',
			args: {employee: frm.doc.employee, fieldname: property},
			callback: function(r) {
				if(r.message){
					d.data.current = r.message.value;
					d.data.property = r.message.label;
					d.fields_dict.field_html.$wrapper.html("");
					d.set_value('current', r.message.value);
					render_dynamic_field(d, r.message.datatype, r.message.options, property);
					d.get_primary_btn().attr('disabled', false);
				}
			}
		});
	};
	d.get_primary_btn().attr('disabled', true);
	d.data = {};
	d.show();
};

var render_dynamic_field = function(d, fieldtype, options, fieldname) {
	d.data.new = null;
	var dynamic_field = frappe.ui.form.make_control({
		df: {
			"fieldtype": fieldtype,
			"fieldname": fieldname,
			"options": options || ''
		},
		parent: d.fields_dict.field_html.wrapper,
		only_input: false
	});
	dynamic_field.make_input();
	$(dynamic_field.label_area).text(__("New"));
};

var add_to_details = function(frm, d, table) {
	let data = d.data;
	if(data.fieldname){
		if(validate_duplicate(frm, table, data.fieldname)){
			frappe.show_alert({message:__("Property already added"), indicator:'orange'});
			return false;
		}
		if(data.current == data.new){
			frappe.show_alert({message:__("Nothing to change"), indicator:'orange'});
			d.get_primary_btn().attr('disabled', false);
			return false;
		}
		frm.add_child(table, {
			fieldname: data.fieldname,
			property: data.property,
			current: data.current,
			new: data.new
		});
		frm.refresh_field(table);
		d.fields_dict.field_html.$wrapper.html("");
		d.set_value("property", "");
		d.set_value('current', "");
		frappe.show_alert({message:__("Added to details"),indicator:'green'});
		d.data = {};
	}else {
		frappe.show_alert({message:__("Value missing"),indicator:'red'});
	}
};

var validate_duplicate =  function(frm, table, fieldname){
	let duplicate = false;
	$.each(frm.doc[table], function(i, detail) {
		if(detail.fieldname === fieldname){
			duplicate = true;
			return;
		}
	});
	return duplicate;
};
<|endoftext|>


<commit_before>'use strict';

var util = require('util'),
    _ = require('lodash'),
    Promise = require('bluebird'),
    workerFarm = require('worker-farm'),
    WebpackConfig = require('webpack-config'),
    GlobRunCompilerStrategy = require('./globRunCompilerStrategy');

/**
 * @private
 * @constant
 * @type {String}
 */
var WORKER_PATH = require.resolve('./workerFarmRunWorker');

/**
 * @private
 * @constant
 * @type {Object}
 */
var FARM_OPTIONS = {};

/**
 * @private
 * @constant
 * @type {String}
 */
var CALLBACK_ERROR_MESSAGE = 'You cannot pass `callback` because all configs are compiled in separate `process` and currently is no way to share `stats` between processes';

/**
 * @private
 * @class
 * @alias WorkerFarmRunCompilerStrategy
 * @extends {GlobRunCompilerStrategy}
 */
function WorkerFarmRunCompilerStrategy() {
    GlobRunCompilerStrategy.apply(this, _.toArray(arguments));

    this.environment = WebpackConfig.environment.getAll();
    this.workers = workerFarm(FARM_OPTIONS, WORKER_PATH);
    this.pipe = Promise.promisify(this.workers);

    process.on('SIGINT', _.bind(this.close, this));
}

util.inherits(WorkerFarmRunCompilerStrategy, GlobRunCompilerStrategy);

/**
 * @private
 */
WorkerFarmRunCompilerStrategy.prototype.close = function() {
    workerFarm.end(this.workers);
};

/**
 * @override
 */
WorkerFarmRunCompilerStrategy.prototype.compile = function(filename, pattern, callback) { // eslint-disable-line
    var config = this.newConfig().glob(pattern).build();

    return this.pipe(filename, {
        compilerOptions: this.compilerOptions,
        webpackOptions: config.toObject(),
        environment: this.environment
    });
};

/**
 * @override
 */
WorkerFarmRunCompilerStrategy.prototype.execute = function(pattern, callback) {
    if (_.isFunction(callback)) {
        throw Error(CALLBACK_ERROR_MESSAGE);
    }

    return this.compileAll(pattern).finally(_.bind(this.close, this));
};

/**
 * @private
 * @module webpack-glob/lib/workerFarmRunCompilerStrategy
 * @returns {WorkerFarmRunCompilerStrategy}
 */
module.exports = WorkerFarmRunCompilerStrategy;
<commit_msg>fix(workerFarmRunCompilerStrategy): throws `error` when `callback` is defined<commit_after>'use strict';

var util = require('util'),
    _ = require('lodash'),
    Promise = require('bluebird'),
    workerFarm = require('worker-farm'),
    WebpackConfig = require('webpack-config'),
    GlobRunCompilerStrategy = require('./globRunCompilerStrategy');

/**
 * @private
 * @constant
 * @type {String}
 */
var WORKER_PATH = require.resolve('./workerFarmRunWorker');

/**
 * @private
 * @constant
 * @type {Object}
 */
var FARM_OPTIONS = {};

/**
 * @private
 * @constant
 * @type {String}
 */
var CALLBACK_ERROR_MESSAGE = 'You cannot pass `callback` because all configs are compiled in separate `process` and currently is no way to share `stats` between processes';

/**
 * @private
 * @class
 * @alias WorkerFarmRunCompilerStrategy
 * @extends {GlobRunCompilerStrategy}
 */
function WorkerFarmRunCompilerStrategy() {
    GlobRunCompilerStrategy.apply(this, _.toArray(arguments));

    this.environment = WebpackConfig.environment.getAll();
    this.workers = workerFarm(FARM_OPTIONS, WORKER_PATH);
    this.pipe = Promise.promisify(this.workers);

    process.on('SIGINT', _.bind(this.close, this));
}

util.inherits(WorkerFarmRunCompilerStrategy, GlobRunCompilerStrategy);

/**
 * @private
 */
WorkerFarmRunCompilerStrategy.prototype.close = function() {
    workerFarm.end(this.workers);
};

/**
 * @override
 */
WorkerFarmRunCompilerStrategy.prototype.compile = function(filename, pattern, callback) { // eslint-disable-line
    var config = this.newConfig().glob(pattern).build();

    return this.pipe(filename, {
        compilerOptions: this.compilerOptions,
        webpackOptions: config.toObject(),
        environment: this.environment
    });
};

/**
 * @override
 */
WorkerFarmRunCompilerStrategy.prototype.execute = function(pattern, callback) {
    if (_.isFunction(callback)) {
        throw new Error(CALLBACK_ERROR_MESSAGE);
    }

    return this.compileAll(pattern).finally(_.bind(this.close, this));
};

/**
 * @private
 * @module webpack-glob/lib/workerFarmRunCompilerStrategy
 * @returns {WorkerFarmRunCompilerStrategy}
 */
module.exports = WorkerFarmRunCompilerStrategy;
module.exports.CALLBACK_ERROR_MESSAGE = CALLBACK_ERROR_MESSAGE;
<|endoftext|>


<commit_before>/**
 * @file keyframe管理
 * @author mj(zoumiaojiang@gmail.com)
 */

'use strict';

const Router = require('koa-router');
const router = new Router();
const KeyframeModel = require('../model/Keyframe.js');
const KeyframeLayerModel = require('../model/KeyframeLayer.js');

router.prefix('/keyframes');

router.post('/add', function* () {
    const dbModels = yield this.getDBModels();
    const keyframeModel = KeyframeModel.getInstance(dbModels);
    const keyframeLayerModel = KeyframeLayerModel.getInstance(dbModels);

    const params = this.request.body;
    const projectid = params.projectid;
    const index = params.index;
    const layerid = params.layerid;
    const prop = params.prop;
    const type = params.type;
    const key = params.key;
    const value = +(params.value || 0);
    const fx = 'linear';
    const keyframe = yield keyframeModel.fetchKeyframe({ index, projectid });
    const keyframes = yield keyframeModel.fetchKeyframes(projectid);

    let obj = {};
    let flag = false;

    // 找到前一帧，并复制前一帧的属性值
    for (let i = index - 1; i >= 0; i--) {
        const item = keyframes[i];
        if (item) {
            for (let layer of item.layers) {
                console.log(layer.layerid, layer[prop]);
                if (layer.layerid === layerid && layer[prop]) {
                    obj = layer[prop];
                    flag = true;
                }
            }
        }
    }

    console.log(flag);

    if (!flag) {
        if (('' + type) === 'false') {
            obj = {
                value: 100,
                fx
            }
        }
        else {
            obj = {
                x: {
                    value: 0,
                    fx
                },
                y: {
                    value: 0,
                    fx
                }
            }
        }
    }

    console.log(obj);

    if (value) {
        if (key) {
            obj[key] = {
                value,
                fx
            }
        }
        else {
            obj = {
                value,
                fx
            }
        }
    }

    // 先判断是不是在index下含有关键帧, 没有就新增一项
    if (!keyframe) {
        const newKeyframe = yield keyframeModel.add({ index, projectid });
        yield keyframeLayerModel.add({
            kfid: newKeyframe._id,
            layerid,
            [prop]: obj
        })
    }
    else {
        // 如果确定有关键帧的话，确定是不是有这个图层的关键帧
        const keyframeLayer = yield keyframeLayerModel.fetchKeyframeLayer(layerid);
        if (!keyframeLayer) {
            yield keyframeLayerModel.add({
                layerid,
                kfid: keyframe._id,
                [prop]: obj
            });
        }
        else {
            yield keyframeLayerModel.update({
                kfid: keyframe._id,
                props: {
                    [prop]: obj
                }
            });
        }
    }

    const data = yield keyframeModel.fetchKeyframes(projectid);

    this.body = {
        status: 0,
        data
    };
});

module.exports = router;
<commit_msg>fix bug: when the frameIndex equal to 0, the "keyframe/add" cannot get origin value<commit_after>/**
 * @file keyframe管理
 * @author mj(zoumiaojiang@gmail.com)
 */

'use strict';

const Router = require('koa-router');
const router = new Router();
const KeyframeModel = require('../model/Keyframe.js');
const KeyframeLayerModel = require('../model/KeyframeLayer.js');
const LayerModel = require('../model/Layer.js');

router.prefix('/keyframes');

router.post('/add', function* () {
    const dbModels = yield this.getDBModels();
    const keyframeModel = KeyframeModel.getInstance(dbModels);
    const keyframeLayerModel = KeyframeLayerModel.getInstance(dbModels);
    const layerModel = LayerModel.getInstance(dbModels);

    const params = this.request.body;
    const projectid = params.projectid;
    const index = params.index;
    const layerid = params.layerid;
    const prop = params.prop;
    const type = params.type;
    const key = params.key;
    const value = +(params.value || 0);
    const fx = 'linear';
    const keyframe = yield keyframeModel.fetchKeyframe({ index, projectid });
    const keyframes = yield keyframeModel.fetchKeyframes(projectid);
    const layers = yield layerModel.fetchLayers(projectid);

    let obj = {};
    let flag = false;

    // 如果为第一帧 应该取layer的默认属性
    if (+index === 0) {
        for (let layer of layers) {
            if (layer._id.toString() === layerid) {
                obj = layer[prop];
                flag = true;
            }
        }
    }
    else {
        // 找到前一帧，并复制前一帧的属性值
        for (let i = index - 1; i >= 0; i--) {
            const item = keyframes[i];
            if (item) {
                for (let layer of item.layers) {
                    if (layer.layerid === layerid && layer[prop]) {
                        obj = layer[prop];
                        flag = true;
                    }
                }
            }
        }
    }

    console.log(flag);

    if (!flag) {
        if (('' + type) === 'false') {
            obj = {
                value: 100,
                fx
            };
        }
        else {
            obj = {
                x: {
                    value: 0,
                    fx
                },
                y: {
                    value: 0,
                    fx
                }
            };
        }
    }

    if (value) {
        if (key) {
            obj[key] = {
                value,
                fx
            };
        }
        else {
            obj = {
                value,
                fx
            };
        }
    }

    console.log(prop, obj);
    // 先判断是不是在index下含有关键帧, 没有就新增一项
    if (!keyframe) {
        const newKeyframe = yield keyframeModel.add({ index, projectid });
        yield keyframeLayerModel.add({
            kfid: newKeyframe._id,
            layerid,
            [prop]: obj
        });
    }
    else {
        // 如果确定有关键帧的话，确定是不是有这个图层的关键帧
        const keyframeLayer = yield keyframeLayerModel.fetchKeyframeLayer(layerid);
        if (!keyframeLayer) {
            yield keyframeLayerModel.add({
                layerid,
                kfid: keyframe._id,
                [prop]: obj
            });
        }
        else {

            // FIX: 如果这个帧存在 应该和之前的属性进行合并 然后将新值赋上去
            // TODO: 这个 add 方法应该重构一下
            let tmpProp = Object.assign(obj, keyframeLayer[prop]);
            if (key) {
                tmpProp[key] = {
                    value,
                    fx
                };
            }
            else {
                tmpProp[key] = {
                    value,
                    fx
                };
            }
            yield keyframeLayerModel.update({
                kfid: keyframe._id,
                props: {
                    [prop]: tmpProp
                }
            });
        }
    }

    const data = yield keyframeModel.fetchKeyframes(projectid);

    this.body = {
        status: 0,
        data
    };
});

module.exports = router;
<|endoftext|>


<commit_before>(function(module) {

  function Route(markers, map){
    this.id = googleMap.routeList.length;
    this.markers = markers;
  };

  Route.colors = ['navy', 'gray', 'fuchsia', 'lime', 'maroon'];

  selectRouteDisplay = function() {
    googleMap.markers.forEach(function(ele){
      ele.setMap(null);
    });
    $('#route-filter').on('change', function() {
      Route.testAll();
    });
  };

  selectRouteDisplay();

  Route.renderRoutes = function(directions, map, which){
    var routes = googleMap.getRequest(which);
    routes.forEach(function(route) {
      directions.route(route.request,
      function(response, status) {
        if (status === 'OK') {
          // googleMap.rendererArray[route.id].setOptions({
          //   preserveViewport: true,
          //   suppressInfoWindows: true,
          //   polylineOptions: {
          //     strokeWeight: 4,
          //     strokeOpacity: .8,
          //     strokeColor: Route.colors[route.id]
          //   }
          // });
          console.log(googleMap.rendererArray[route.id]);
          googleMap.rendererArray[route.id].setDirections(response);
          var responseRoute = response.routes[0];
          var elevator = new google.maps.ElevationService;
          var detailedPath = responseRoute.overview_path.map(function(point) {
            return {
              lat: point.lat(),
              lng: point.lng()
            };
          });
          elevationsView.displayPathElevation(detailedPath, elevator, map);

          var summaryPanel = document.getElementById('directions-panel');
          summaryPanel.innerHTML = '';
          // For each route, display summary information.

          for (var i = 0; i < responseRoute.legs.length; i++) {
            var routeSegment = i + 1;
            summaryPanel.innerHTML += 'Route Segment: ' + routeSegment +
                '
';
            summaryPanel.innerHTML += responseRoute.legs[i].start_address + ' to ';
            summaryPanel.innerHTML += responseRoute.legs[i].end_address + '
';
            summaryPanel.innerHTML += responseRoute.legs[i].distance.text + '

';

            var totalDistance = document.getElementById('total-distance');
            totalDistance.innerHTML= '';
            // this should create a new array with the distances of the legs
            function countDistance() {
              var runDistanceArray = responseRoute.legs.map(function(curr){
                return (curr.distance.value);
              });
              // this should reduce the created array into one distance value
              var totalDistanceCount = runDistanceArray.reduce(function(prev, curr){
                return prev + curr;

              },0);
              var distanceMiles = totalDistanceCount/1609.34;
              totalDistance.innerHTML= 'Total distance ran: '+totalDistanceCount+' meters, or '+
              distanceMiles.toFixed(2) + ' miles';
            }
            countDistance();
          }
        } else {
          window.alert('Directions request failed due to ' + status);
        }
      });
    });
  };

  Route.testAll = function() {
    Route.renderRoutes(googleMap.directionsService, googleMap.map, '[' + $('#route-filter').val() + ']');
  };

  Route.calcRoute = function(route, newRoute) {

    Route.calcRoute = function(route) {

      var len = route.markers.length;
      var path = route.markers.map(function(marker){
        return {
          location: {lat: marker.position.lat(), lng: marker.position.lng()},
          stopover: true
        };
      });

      route.request = {
        origin: {lat: path[0].location.lat,
              lng: path[0].location.lng},
        destination: {lat: path[len - 1].location.lat,
                  lng: path[len - 1].location.lng},
        waypoints: path.slice(1,len-1),
        optimizeWaypoints: true,
        travelMode: 'WALKING'
      };

      route.markers = path;
      googleMap.routeList.push(route);

    };
  };
  module.Route = Route;
})(window);
<commit_msg>create show route select box, start hide route function<commit_after>(function(module) {

  function Route(markers, map){
    this.id = googleMap.routeList.length;
    this.markers = markers;
  };

  Route.colors = ['navy', 'gray', 'fuchsia', 'lime', 'maroon'];

  function grabMarkers(){
    googleMap.routeList.map(function(i){
      console.log(i.markers);
      console.log(googleMap.routeList);
      return i.markers;
    });
  };
  function selectRouteDisplay() {
    //     function setMapOnAll(map) {
    //       for (var i = 0; i < grabMarkers().length; i++) {
    //         grabMarkers()[i].setMap(map);
    //       }
    //     }
    // console.log(googleMap.routeList);
    // setMapOnAll(null);
    console.log('fin');
    $('#route-filter').on('change', function() {
      Route.testAll();
    });
  };

  selectRouteDisplay();

  Route.renderRoutes = function(directions, map, which){
    var routes = googleMap.getRequest(which);
    routes.forEach(function(route) {
      directions.route(route.request,
      function(response, status) {
        if (status === 'OK') {
          // googleMap.rendererArray[route.id].setOptions({
          //   preserveViewport: true,
          //   suppressInfoWindows: true,
          //   polylineOptions: {
          //     strokeWeight: 4,
          //     strokeOpacity: .8,
          //     strokeColor: Route.colors[route.id]
          //   }
          // });
          console.log(googleMap.rendererArray[route.id]);
          googleMap.rendererArray[route.id].setDirections(response);
          var responseRoute = response.routes[0];
          var elevator = new google.maps.ElevationService;
          var detailedPath = responseRoute.overview_path.map(function(point) {
            return {
              lat: point.lat(),
              lng: point.lng()
            };
          });
          elevationsView.displayPathElevation(detailedPath, elevator, map);

          var summaryPanel = document.getElementById('directions-panel');
          summaryPanel.innerHTML = '';
          // For each route, display summary information.

          for (var i = 0; i < responseRoute.legs.length; i++) {
            var routeSegment = i + 1;
            summaryPanel.innerHTML += 'Route Segment: ' + routeSegment +
                '
';
            summaryPanel.innerHTML += responseRoute.legs[i].start_address + ' to ';
            summaryPanel.innerHTML += responseRoute.legs[i].end_address + '
';
            summaryPanel.innerHTML += responseRoute.legs[i].distance.text + '

';

            var totalDistance = document.getElementById('total-distance');
            totalDistance.innerHTML= '';
            // this should create a new array with the distances of the legs
            function countDistance() {
              var runDistanceArray = responseRoute.legs.map(function(curr){
                return (curr.distance.value);
              });
              // this should reduce the created array into one distance value
              var totalDistanceCount = runDistanceArray.reduce(function(prev, curr){
                return prev + curr;

              },0);
              var distanceMiles = totalDistanceCount/1609.34;
              totalDistance.innerHTML= 'Total distance ran: '+totalDistanceCount+' meters, or '+
              distanceMiles.toFixed(2) + ' miles';
            }
            countDistance();
          }
        } else {
          window.alert('Directions request failed due to ' + status);
        }
      });
    });
  };

  Route.testAll = function() {
    Route.renderRoutes(googleMap.directionsService, googleMap.map, '[' + $('#route-filter').val() + ']');
  };

  Route.calcRoute = function(route, newRoute) {

    Route.calcRoute = function(route) {

      var len = route.markers.length;
      var path = route.markers.map(function(marker){
        return {
          location: {lat: marker.position.lat(), lng: marker.position.lng()},
          stopover: true
        };
      });

      route.request = {
        origin: {lat: path[0].location.lat,
              lng: path[0].location.lng},
        destination: {lat: path[len - 1].location.lat,
                  lng: path[len - 1].location.lng},
        waypoints: path.slice(1,len-1),
        optimizeWaypoints: true,
        travelMode: 'WALKING'
      };

      route.markers = path;
      googleMap.routeList.push(route);

    };
  };
  module.Route = Route;
})(window);
<|endoftext|>