<commit_before>(function (context) {

    var Oxy = {};
    (function () {
        var AUTO_ID = 1000,
            objectPrototype = Object.prototype,
            toString = objectPrototype.toString,
            CLASS_RESERVED_KEYS = {$classname:1, mixinId:1, $mixinId:1, $super:1, $superclass:1},
            CONFIG_RESERVED_KEYS = {extend:1, constructor:1, singleton:1, statics:1, mixins:1, inherits:1},
            TemplateClass = function(){};

        function getAutoId(prefiex) {
            return (prefiex ? prefiex.toString() : '') + (++AUTO_ID);
        }

        Oxy.apply = function (object, config, filter) {
            if (object && config && typeof config === 'object') {
                var key;

                for (key in config) {
                    if (!filter || !filter[key]) {
                        object[key] = config[key];
                    }
                }
            }
            return object;
        };

        Oxy.apply(Oxy, {

            isEmpty:function (value, allowEmptyString) {
                return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Oxy.isArray(value) && value.length === 0);
            },

            isArray:('isArray' in Array) ? Array.isArray : function (value) {
                return toString.call(value) === '[object Array]';
            },

            isFunction:function (value) {
                return value && typeof value === 'function';
            },

            isObject:function (value) {
                return value && typeof value === 'object';
            },

            isSimpleObject:function (value) {
                return value instanceof Object && value.constructor === Object;
            },

            isPrimitive:function (value) {
                var type = typeof value;

                return type === 'string' || type === 'number' || type === 'boolean';
            },

            isNumber:function (value) {
                return typeof value === 'number' && isFinite(value);
            },

            isNumeric:function (value) {
                return !isNaN(parseFloat(value)) && isFinite(value);
            },

            isString:function (value) {
                return typeof value === 'string';
            },

            isBoolean:function (value) {
                return typeof value === 'boolean';
            },

            isDefined:function (value) {
                return typeof value !== 'undefined';
            }
        });

        Oxy.apply(Oxy, {

            applyIf:function (object, config, filter) {
                var property;

                if (object) {
                    for (property in config) {
                        if (!filter || !filter.hasOwnProperty(property)) {
                            if (object[property] === undefined) {
                                object[property] = config[property];
                            }
                        }
                    }
                }

                return object;
            },

            merge:function (destination) {
                var i = 1,
                    ln = arguments.length,
                    mergeFn = Oxy.merge,
                    cloneFn = Oxy.clone,
                    object, key, value, sourceKey;

                for (; i < ln; i++) {
                    object = arguments[i];

                    for (key in object) {
                        value = object[key];
                        if (value && value.constructor === Object) {
                            sourceKey = destination[key];
                            if (sourceKey && sourceKey.constructor === Object) {
                                mergeFn(sourceKey, value);
                            }
                            else {
                                destination[key] = cloneFn(value);
                            }
                        }
                        else {
                            destination[key] = value;
                        }
                    }
                }

                return destination;
            },

            clone:function (item) {
                var type,
                    i,
                    clone,
                    key;

                if (item === null || item === undefined) {
                    return item;
                }

                type = toString.call(item);

                // Date
                if (type === '[object Date]') {
                    return new Date(item.getTime());
                }

                // Array
                if (type === '[object Array]') {
                    i = item.length;

                    clone = [];

                    while (i--) {
                        clone[i] = Oxy.clone(item[i]);
                    }
                }
                // Object
                else if (type === '[object Object]' && item.constructor === Object) {
                    clone = {};

                    for (key in item) {
                        clone[key] = Oxy.clone(item[key]);
                    }
                }

                return clone || item;
            },

            chain: function (object) {
                TemplateClass.prototype = object;
                var result = new TemplateClass();
                TemplateClass.prototype = null;
                return result;
            }
        });

//        var ALL_RESERVED_KEYS = Oxy.merge({}, CLASS_RESERVED_KEYS, CONFIG_RESERVED_KEYS);

        function Base() {
        }

        function define(className, data) {
            var hasClassName = Oxy.isString(className);
            if (!data) data = (hasClassName ? {} : className) || {};

            if (className) {
                data.$classname = className;
            } else {
                data.$classname = null;
            }

            var _extend = data.extend,
                Parent;
            if (_extend && !Oxy.isObject(_extend)) {
                Parent = _extend;
            } else {
                Parent = Base;
            }
            return extend(Parent, data);
        }

        function makeCtor(parent) {
            if (parent.constructor === Object) {
                return function(){};
            } else {
                return function() {
                    parent.constructor.apply(this, arguments);
                }
            }
        }

        function extend(parentClass, data) {
            var parent = parentClass.prototype,
                prototype = Oxy.chain(parent),
                body = (Oxy.isFunction(data) ? data(parentClass, parent) : data) || {},
                cls;

            if (Oxy.isFunction(body)) {
                cls = body;
            } else if (body.constructor !== Object) {
                cls = body.constructor;
            } else {
                cls = makeCtor(parent);
            }

            prototype.constructor = cls;
            cls.prototype = prototype;

            // the '$super' property of class refers to its super prototype
            cls.$super = parent;
            // the '$superclass' property of class refers to its super class
            cls.$superclass = parentClass;

            if (typeof body === 'object') {
                process(cls, body, prototype);
                if (body.singleton) {
                    cls = new cls();
                }
            }

            return cls;
        }

        function process(targetClass, data, targetPrototype) {
            var prototype = targetPrototype || targetClass.prototype,
                statics = data.statics,
                mixins = data.mixins,
                inherits = data.inherits,
                key;

            if (statics) {
                // copy static properties from statics to class
                Oxy.apply(targetClass, statics);
            }
            if (mixins) {
                processMixins(targetClass, mixins, targetPrototype)
            }
            if (inherits) {
                processInherits(targetClass, inherits, targetPrototype);
            }

            Oxy.apply(prototype, data, CONFIG_RESERVED_KEYS);

            if (data.toString !== Object.prototype.toString) {
                prototype.toString = data.toString;
            }
        }

        function processInherits(targetClass, inherits, targetPrototype) {
            var i, ln;

            if (!targetPrototype) {
                targetPrototype = targetClass.prototype;
            }

            if (inherits instanceof Array) {
                for (i = 0, ln = inherits.length; i < ln; i++) {
                    mixin(targetClass, null, inherits[i], targetPrototype);
                }
            }
            else {
                for (var mixinName in inherits) {
                    if (inherits.hasOwnProperty(mixinName)) {
                        mixin(targetClass, null, inherits[mixinName], targetPrototype);
                    }
                }
            }
        }

        function processMixins(targetClass, mixins, targetPrototype) {
            var name, item, i, ln;

            if (!targetPrototype) {
                targetPrototype = targetClass.prototype;
            }

            if (mixins instanceof Array) {
                for (i = 0, ln = mixins.length; i < ln; i++) {
                    item = mixins[i];
                    name = item.prototype.mixinId || item.$mixinId;
                    if (!name) {
                        name = item.$mixinId = getAutoId('mixin_');
                    }

                    mixin(targetClass, name, mixin, targetPrototype);
                }
            }
            else {
                for (var mixinName in mixins) {
                    if (mixins.hasOwnProperty(mixinName)) {
                        mixin(targetClass, mixinName, mixins[mixinName], targetPrototype);
                    }
                }
            }
        }

        function mixin(target, name, mixinClass, targetPrototype) {
            var mixin = mixinClass.prototype,
                prototype = targetPrototype || target.prototype,
                key;

            if (name) {
                if (!prototype.hasOwnProperty('mixins')) {
                    if ('mixins' in prototype) {
                        prototype.mixins = Oxy.chain(prototype.mixins);
                    }
                    else {
                        prototype.mixins = {};
                    }
                }
            }

            for (key in mixin) {
                if (name && (key === 'mixins')) {
                    Oxy.merge(prototype.mixins, mixin[key]);
                }
                else if (typeof prototype[key] == 'undefined' && key != 'mixinId') {
                    prototype[key] = mixin[key];
                }
            }
            if (name) {
                prototype.mixins[name] = mixin;
            }
        }

        // expose oop functions
        Oxy.apply(Oxy, {
            define:define,
            extend:extend,
            mixins:function(targetClass, mixins) {
                return processMixins(targetClass, mixins);
            },
            inherits:function(targetClass, inherits) {
                return processInherits(targetClass, inherits);
            }
        })

    }());

    if (typeof module !== "undefined" && module.exports) {              // NodeJS/CommonJS
        module.exports = Oxy;
    } else {
        var _Oxy = context.Oxy;                                         // save current Class namespace
        context.Oxy = Oxy;                                              // bind Class and Oxygen to global scope
        Oxy.noConflict = function () {
            if (context.Oxy === Oxy) {
                context.Oxy = _Oxy;
            }
            return Oxy;
        }
    }

})(this);<commit_msg>Fix incorrect function call for define(function(){…})<commit_after>(function (context) {

    var Oxy = {};
    (function () {
        var AUTO_ID = 1000,
            objectPrototype = Object.prototype,
            toString = objectPrototype.toString,
            CLASS_RESERVED_KEYS = {$classname:1, mixinId:1, $mixinId:1, $super:1, $superclass:1},
            CONFIG_RESERVED_KEYS = {extend:1, constructor:1, singleton:1, statics:1, mixins:1, inherits:1},
            TemplateClass = function(){};

        function getAutoId(prefiex) {
            return (prefiex ? prefiex.toString() : '') + (++AUTO_ID);
        }

        Oxy.apply = function (object, config, filter) {
            if (object && config && typeof config === 'object') {
                var key;

                for (key in config) {
                    if (!filter || !filter[key]) {
                        object[key] = config[key];
                    }
                }
            }
            return object;
        };

        Oxy.apply(Oxy, {

            isEmpty:function (value, allowEmptyString) {
                return (value === null) || (value === undefined) || (!allowEmptyString ? value === '' : false) || (Oxy.isArray(value) && value.length === 0);
            },

            isArray:('isArray' in Array) ? Array.isArray : function (value) {
                return toString.call(value) === '[object Array]';
            },

            isFunction:function (value) {
                return value && typeof value === 'function';
            },

            isObject:function (value) {
                return value && typeof value === 'object';
            },

            isSimpleObject:function (value) {
                return value instanceof Object && value.constructor === Object;
            },

            isPrimitive:function (value) {
                var type = typeof value;

                return type === 'string' || type === 'number' || type === 'boolean';
            },

            isNumber:function (value) {
                return typeof value === 'number' && isFinite(value);
            },

            isNumeric:function (value) {
                return !isNaN(parseFloat(value)) && isFinite(value);
            },

            isString:function (value) {
                return typeof value === 'string';
            },

            isBoolean:function (value) {
                return typeof value === 'boolean';
            },

            isDefined:function (value) {
                return typeof value !== 'undefined';
            }
        });

        Oxy.apply(Oxy, {

            applyIf:function (object, config, filter) {
                var property;

                if (object) {
                    for (property in config) {
                        if (!filter || !filter.hasOwnProperty(property)) {
                            if (object[property] === undefined) {
                                object[property] = config[property];
                            }
                        }
                    }
                }

                return object;
            },

            merge:function (destination) {
                var i = 1,
                    ln = arguments.length,
                    mergeFn = Oxy.merge,
                    cloneFn = Oxy.clone,
                    object, key, value, sourceKey;

                for (; i < ln; i++) {
                    object = arguments[i];

                    for (key in object) {
                        value = object[key];
                        if (value && value.constructor === Object) {
                            sourceKey = destination[key];
                            if (sourceKey && sourceKey.constructor === Object) {
                                mergeFn(sourceKey, value);
                            }
                            else {
                                destination[key] = cloneFn(value);
                            }
                        }
                        else {
                            destination[key] = value;
                        }
                    }
                }

                return destination;
            },

            clone:function (item) {
                var type,
                    i,
                    clone,
                    key;

                if (item === null || item === undefined) {
                    return item;
                }

                type = toString.call(item);

                // Date
                if (type === '[object Date]') {
                    return new Date(item.getTime());
                }

                // Array
                if (type === '[object Array]') {
                    i = item.length;

                    clone = [];

                    while (i--) {
                        clone[i] = Oxy.clone(item[i]);
                    }
                }
                // Object
                else if (type === '[object Object]' && item.constructor === Object) {
                    clone = {};

                    for (key in item) {
                        clone[key] = Oxy.clone(item[key]);
                    }
                }

                return clone || item;
            },

            chain: function (object) {
                TemplateClass.prototype = object;
                var result = new TemplateClass();
                TemplateClass.prototype = null;
                return result;
            }
        });

//        var ALL_RESERVED_KEYS = Oxy.merge({}, CLASS_RESERVED_KEYS, CONFIG_RESERVED_KEYS);

        function Base() {
        }

        function define(className, data) {
            var hasClassName = Oxy.isString(className);
            if (!data) data = (hasClassName ? {} : className) || {};

            if (className) {
                data.$classname = className;
            } else {
                data.$classname = null;
            }

            var _extend = data.extend,
                Parent;
            if (_extend && !Oxy.isObject(_extend)) {
                Parent = _extend;
            } else {
                Parent = Base;
            }
            return extend(Parent, data);
        }

        function makeCtor(parent) {
            if (parent.constructor === Object) {
                return function(){};
            } else {
                return function() {
                    parent.constructor.apply(this, arguments);
                }
            }
        }

        function extend(parentClass, data) {
            var parent = parentClass.prototype,
                prototype = Oxy.chain(parent),
                body = (Oxy.isFunction(data) ? data.call(prototype, parentClass, parent) : data) || {},
                cls;

            if (Oxy.isFunction(body)) {
                cls = body;
            } else if (body.constructor !== Object) {
                cls = body.constructor;
            } else {
                cls = makeCtor(parent);
            }

            prototype.constructor = cls;
            cls.prototype = prototype;

            // the '$super' property of class refers to its super prototype
            cls.$super = parent;
            // the '$superclass' property of class refers to its super class
            cls.$superclass = parentClass;

            if (typeof body === 'object') {
                process(cls, body, prototype);
                if (body.singleton) {
                    cls = new cls();
                }
            }

            return cls;
        }

        function process(targetClass, data, targetPrototype) {
            var prototype = targetPrototype || targetClass.prototype,
                statics = data.statics,
                mixins = data.mixins,
                inherits = data.inherits,
                key;

            if (statics) {
                // copy static properties from statics to class
                Oxy.apply(targetClass, statics);
            }
            if (mixins) {
                processMixins(targetClass, mixins, targetPrototype)
            }
            if (inherits) {
                processInherits(targetClass, inherits, targetPrototype);
            }

            Oxy.apply(prototype, data, CONFIG_RESERVED_KEYS);

            if (data.toString !== Object.prototype.toString) {
                prototype.toString = data.toString;
            }
        }

        function processInherits(targetClass, inherits, targetPrototype) {
            var i, ln;

            if (!targetPrototype) {
                targetPrototype = targetClass.prototype;
            }

            if (inherits instanceof Array) {
                for (i = 0, ln = inherits.length; i < ln; i++) {
                    mixin(targetClass, null, inherits[i], targetPrototype);
                }
            }
            else {
                for (var mixinName in inherits) {
                    if (inherits.hasOwnProperty(mixinName)) {
                        mixin(targetClass, null, inherits[mixinName], targetPrototype);
                    }
                }
            }
        }

        function processMixins(targetClass, mixins, targetPrototype) {
            var name, item, i, ln;

            if (!targetPrototype) {
                targetPrototype = targetClass.prototype;
            }

            if (mixins instanceof Array) {
                for (i = 0, ln = mixins.length; i < ln; i++) {
                    item = mixins[i];
                    name = item.prototype.mixinId || item.$mixinId;
                    if (!name) {
                        name = item.$mixinId = getAutoId('mixin_');
                    }

                    mixin(targetClass, name, mixin, targetPrototype);
                }
            }
            else {
                for (var mixinName in mixins) {
                    if (mixins.hasOwnProperty(mixinName)) {
                        mixin(targetClass, mixinName, mixins[mixinName], targetPrototype);
                    }
                }
            }
        }

        function mixin(target, name, mixinClass, targetPrototype) {
            var mixin = mixinClass.prototype,
                prototype = targetPrototype || target.prototype,
                key;

            if (name) {
                if (!prototype.hasOwnProperty('mixins')) {
                    if ('mixins' in prototype) {
                        prototype.mixins = Oxy.chain(prototype.mixins);
                    }
                    else {
                        prototype.mixins = {};
                    }
                }
            }

            for (key in mixin) {
                if (name && (key === 'mixins')) {
                    Oxy.merge(prototype.mixins, mixin[key]);
                }
                else if (typeof prototype[key] == 'undefined' && key != 'mixinId') {
                    prototype[key] = mixin[key];
                }
            }
            if (name) {
                prototype.mixins[name] = mixin;
            }
        }

        // expose oop functions
        Oxy.apply(Oxy, {
            define:define,
            extend:extend,
            mixins:function(targetClass, mixins) {
                return processMixins(targetClass, mixins);
            },
            inherits:function(targetClass, inherits) {
                return processInherits(targetClass, inherits);
            }
        })

    }());

    if (typeof module !== "undefined" && module.exports) {              // NodeJS/CommonJS
        module.exports = Oxy;
    } else {
        var _Oxy = context.Oxy;                                         // save current Class namespace
        context.Oxy = Oxy;                                              // bind Class and Oxygen to global scope
        Oxy.noConflict = function () {
            if (context.Oxy === Oxy) {
                context.Oxy = _Oxy;
            }
            return Oxy;
        }
    }

})(this);<|endoftext|>


<commit_before>// Reorganizes the category links
function reorganizeLinks(){

//	firebase.$.child("spider").once('value', function(spider){
//	   spider.forEach(function(company){
//	       company.forEach(function(customer){
//	           customer.forEach(function(category){
//	               var catObj = {url: category.val(), status: "works"};
//
//	               firebase.$.child("spider")
//	                         .child(company.name())
//	                         .child(customer.name())
//	                         .child(category.name()).remove();
//
//	               firebase.$.child("spider")
//	                         .child(company.name())
//	                         .child(customer.name())
//	                         .child(category.name()).set(catObj);
//
//	               console.log(company.name() + " -> " + customer.name() + " -> " + category.name());
//	           });
//	       });
//	   });
//	});
}

// Gets the category links
function getLinks(){
	$("#links").html("");

	firebase.$.child("spider").once('value', function(spider){
	   spider.forEach(function(company){
	       $("#links").append(
	           $("
").addClass("company").append(
	               $("
").addClass("companyName").html("• " + company.name())
	            )
	        );

	       company.forEach(function(customer){
	           $("#links > .company").last().append($("
").addClass("customer").append($("
").addClass("customerName").html("» " + customer.name())));

	           customer.forEach(function(category){
	               var statusText = " - " + category.child("status").val();

	               if (category.hasChild("count")){
	                   statusText += ' (' + category.child("count").val() + ' products)';
	               }

	               var statusColor = "red";

	               if (category.child("status").val() == "Works!" || category.child("status").val() == "works"){
	                   statusColor = "green";
	               }

	               $("#links > .company > .customer").last().append(
    					$("
").addClass("category").append(
    						$("<input>")
    							.attr("type","checkbox")
    							.attr("company",company.name())
    							.attr("customer",customer.name())
    							.attr("category",category.name())
    							.attr("url",category.child("url").val())
    						).append(
    						      $("").attr("href",category.child("url").val()).html(category.name())
    						).append(
    						      $("").addClass("isvalid").css("color",statusColor).html(statusText)
    						).append(
    						      $("").addClass("removeCategory").html("x")
    						)
    				);
	           });
	       });
	   });
	});
}

// Gets the products from the selected links and optionally saves them
function getProductsFromLinks(save){
	$("#json-output").html("");

	var total = $("#links > .company > .customer > .category > input:checked").size();
	var count = 0;

	if (total <= 0){
		alert("Please select a product store > category");
	}else{

		$("#links > .company > .customer > .category > input:checked").each(function(){
			var company = $(this).attr("company");
			var customer = $(this).attr("customer");
			var category = $(this).attr("category");
			var url = $(this).attr("url");
			url = storeApi.getFullUrl(company, url);

			$.post("webProxy.php", {u:url}, function(data){
			    if (data == null || data.trim() == ""){
			         console.log("webProxy returned nothing. Make sure the URL is correct and does not redirect.");
			     }

			    var jsonProducts = storeApi.getProducts(company, data, url);
			    var storeProducts = $.parseJSON(jsonProducts);

			    for (var i=0; i < Object.keys(storeProducts).length; i++){
			         var sku = Object.keys(storeProducts)[i];
			         storeProducts[sku]['company'] = company;
			         storeProducts[sku]['customer'] = customer;
			         storeProducts[sku]['category'] = category;
			    }

			    if (save){
			        // Used for firebase
    				$("#json-output").append(
    					$("
")
    						.attr("company", company)
    						.attr("customer", customer)
    						.attr("category", category)
    						.html( storeProducts )
    				);

    				// Used for database
    				if ($("#json-products").text() != ""){
        				var jsonProducts = $.parseJSON($("#json-products").text());
        				$.extend(storeProducts, jsonProducts);
    				}
    				$("#json-products").text(JSON.stringify(storeProducts));

    				count++;
    				if(count == total){
    				    saveAllProducts();
    				}
			    }else{
			         alert(company + " > " + customer + " > " + category + ": " + storeProducts);
			    }
			});
		});
	}
}

// Gets the checked prdocuts frm the link, validates them, and shows a sampling of them
function testProductsFromLinks(showSample){

	var total = $("#links > .company > .customer > .category > input:checked").size();
	var count = 0;
	var validCount = 0;

	if (total <= 0){
		alert("Please select a product store > category");
	}else{

		$("#links > .company > .customer > .category > input:checked").each(function(){
		    $(this).siblings(".isvalid").remove();

		    var link = $(this);
			var company = link.attr("company");
			var customer = link.attr("customer");
			var category = link.attr("category");
			var url = link.attr("url");
			url = storeApi.getFullUrl(company, url);

			$.post("webProxy.php", {u:url}, function(data){																		    if (data == null || data.trim() == ""){
			         console.log("webProxy returned nothing. Make sure the URL is correct and does not redirect.");
			     }

				var isValid = false;
				var itemCount = 0;

				try{
				    var dataString = storeApi.getProducts(company, data, url);
				    var data = $.parseJSON(dataString);

				    if (data != null && data.constructor === {}.constructor){
				        var testProduct = data[Object.keys(data)[0]];

				        if (testProduct != null &&
				            testProduct.price != null &&
				            testProduct.image != null &&
				            testProduct.link != null &&
				            testProduct.name != null &&
				            testProduct.sku != null){

				                var price = testProduct.price + "";
				                price = parseFloat(price.replace("$",""));
        				        price = parseFloat(price);

        				        if(!isNaN(price)){
            				        isValid = true;
            				        itemCount = Object.keys(data).length;
            				        validCount++;

            				        if (showSample && validCount == 1){
            				            showSampleProducts(data, company, customer, category);
            				        }
        				        }
				            }else{
				                console.log("one or more of the fields in the product entity are null");
				            }
				    }
				}catch(err){
				    // do nothing
				    console.log("Whoops ran into a problem: " + err);
				}

				if (isValid){
				    link.siblings("a").after(' - Works! ('+itemCount+' products)');

				    var statusObj = {status: "Works!", count: itemCount};

				    firebase.$.child("spider")
	                         .child(company)
	                         .child(customer)
	                         .child(category).update(statusObj);

				}else{
				    link.siblings("a").after(' - BROKEN :(');

				    var statusObj = {status: "BROKEN :(", count: itemCount};

				    firebase.$.child("spider")
	                         .child(company)
	                         .child(customer)
	                         .child(category).update(statusObj);
				}

				count++;
				if(count == total){
					alert(validCount + "/" + total + " catgeories were valid");
				}
			});
		});
	}
}

function showSampleProducts(data, company, audience, category){
    if (data != null && Object.keys(data).length > 0){
        gridPresenter.beginTask();
        var grid = $("#sample-grid");
        grid.html("");

    	for(var i=0; i< 28 ;i++){
    		var outfit = getProductTemplate(data[Object.keys(data)[i]], company, audience, category);
    		grid.append(outfit);
    	}

     	gridPresenter.endTask();
     	gridPresenter.alignGrid("sample-grid", 4, 200, 270, 25);
     	$(document).on("mouseenter",".outfit", gridEvents.showOverlay);
    }
}

// Saves the products
function saveAllProducts(){
	var total = $("#links > .company > .customer > .category > input:checked").size();
	var fireBaseStore = new Firebase('https://clothies.firebaseio.com/store/products');
 	var success = 0;

 	if (total <= 0){
		alert("There is nothing to save! Please add product data.");
	}else{
	    $.post( window.HOME_ROOT + "spider/update", $.parseJSON($("#json-products").text()), function( result ) {
            console.log(result);

            var output = "";

            if (result == null){
                output += "Data was NOT saved successfully! ";
            }else{
                if (result['clearProducts'] != null && result['clearProducts']){

                    if (result['new'] != null && !isNaN(result['new']) &&
                        result['updated'] != null && !isNaN(result['updated']) &&
                        result['historicalPrices'] != null && !isNaN(result['historicalPrices'])){

                            output += " Success! ";
                            output += " Processed " + result['numProducts'] + " products! ";
                    }

                    if (result['new'] == null || isNaN(result['new'])){
                        output += "Error adding new products! ";
                    }else{
                        output += "Added " + result['new'] + " new products. ";
                    }

                    if (result['updated'] == null || isNaN(result['updated'])){
                        output += "Error updating existing products! ";
                    }else{
                        output += "Updated " + result['updated'] + " products! ";
                    }

                    if (result['historicalPrices'] == null || isNaN(result['historicalPrices'])){
                        output += "Error getting historical prices! ";
                    }else{
                        output += "Added " + result['historicalPrices'] + " historical prices! ";
                    }
                }else{
                    output += "There was an issue saving the products. Data was NOT saved successfully! ";
                }
            }

            alert(output);
        }
        , "json"
        );
	}
}

$('form').submit(function(e) {
	e.preventDefault();

	var company = $("#inputCompany").val().toLowerCase().trim();
	var customer = $("#inputAudience").val().toLowerCase().trim();
	var category = $("#inputCategory").val().toLowerCase().trim();
	var catObj = {url: $("#inputLink").val(), status: "works"};

	firebase.$.child("spider").child(company).child(customer).child(category).set(catObj, function(error){
	  if (!error){
	      getLinks();
	      alert("Added!");
			  $("#inputLink").val("");
			  $("#inputCategory").val("");
	  }
	});

	return false;
});

function getProductTemplate(product, company, audience, category){
    if (product == null){
        return $("");
    }

	var link = product.link;
	var image = product.image;
	var name = product.name;
	var id = product.sku;
	var price = product.price + "";
	price = "$" + Math.round(parseInt(price.replace("$","").trim()));

	var rand = Math.floor(Math.random() * 3) + 1;
	var shadow = "";
	if(rand == 1){
		shadow = 'shadow';
	}

		//var attr = 	'company="'+company+'" customer="'+audience+'" category="'+category+'" price="'+filterPrice+'"';
		var attr = 	''; //'company="'+company+'" customer="'+audience+'" category="'+category+'"';
	var html ='
';
			html +='

';
			html +='
';
				html +='
';
					html +='

';
				html += '
';
				html +='
';
					html +='

';
				html += '
';
				html +='
';
				    html += '
';
				       html += '
0
';
				    html += '
';
					html +='
' + company + '
';
					html +='
' +  price + '
';
					html +='
' + name + '
';
				html += '
';
				html += '

';
			html += '
';
			html += '

';
		html +='
';

	return $(html);
}

function getTotalProductCount(){
    $.post( window.HOME_ROOT + "spider/count", function( result ) {
            console.log(result);

            if (isNaN(result)){
                alert("There was an error getting the total product count!");
            }else{
                alert("There are currently " + result + " products in the database");
            }
    });
}

$('#selectall').click(function () {
    $("#links").find(':checkbox').prop('checked', true);
});

$('#deselectall').click(function () {
    $("#links").find(':checkbox').prop('checked', false);
});

$(document).on("click",".companyName", function(el){
    if ($(el.currentTarget).parent(".company").find(':checkbox').first().prop('checked')){
        $(el.currentTarget).parent(".company").find(':checkbox').prop('checked', false);
    }else{
        $(el.currentTarget).parent(".company").find(':checkbox').prop('checked', true);
    }
});

$(document).on("click",".customerName", function(el){
    if ($(el.currentTarget).parent(".customer").find(':checkbox').first().prop('checked')){
        $(el.currentTarget).parent(".customer").find(':checkbox').prop('checked', false);
    }else{
        $(el.currentTarget).parent(".customer").find(':checkbox').prop('checked', true);
    }
});

$(document).on("click",".removeCategory", function(el){
    var category = $(el.currentTarget).siblings(':checkbox');

    var dialog = confirm("Are you sure you want to remove " + category.attr("company") + " -> " + category.attr("customer") + " -> " + category.attr("category") + "? ");

    if (dialog==true){
        firebase.$.child("spider")
                  .child(category.attr("company"))
                  .child(category.attr("customer"))
                  .child(category.attr("category"))
                  .remove(function(error) {
                      if (error){
                        alert("There was a problem removing this category")
                      }else{
                        $(el.currentTarget).parents(".category").remove();
                        alert("Category was removed! (This only deletes the category. It does not delete products that were already added to this category)")
                      }
                   });
    }

});

$(document).find(".feedback-maximize").hide('fade');
$(document).find(".feedback-minimized").show('fade');<commit_msg>changing initial status<commit_after>// Reorganizes the category links
function reorganizeLinks(){

//	firebase.$.child("spider").once('value', function(spider){
//	   spider.forEach(function(company){
//	       company.forEach(function(customer){
//	           customer.forEach(function(category){
//	               var catObj = {url: category.val(), status: "works"};
//
//	               firebase.$.child("spider")
//	                         .child(company.name())
//	                         .child(customer.name())
//	                         .child(category.name()).remove();
//
//	               firebase.$.child("spider")
//	                         .child(company.name())
//	                         .child(customer.name())
//	                         .child(category.name()).set(catObj);
//
//	               console.log(company.name() + " -> " + customer.name() + " -> " + category.name());
//	           });
//	       });
//	   });
//	});
}

// Gets the category links
function getLinks(){
	$("#links").html("");

	firebase.$.child("spider").once('value', function(spider){
	   spider.forEach(function(company){
	       $("#links").append(
	           $("
").addClass("company").append(
	               $("
").addClass("companyName").html("• " + company.name())
	            )
	        );

	       company.forEach(function(customer){
	           $("#links > .company").last().append($("
").addClass("customer").append($("
").addClass("customerName").html("» " + customer.name())));

	           customer.forEach(function(category){
	               var statusText = " - " + category.child("status").val();

	               if (category.hasChild("count")){
	                   statusText += ' (' + category.child("count").val() + ' products)';
	               }

	               var statusColor = "red";

	               if (category.child("status").val() == "Works!" || category.child("status").val() == "works"){
	                   statusColor = "green";
	               }

	               $("#links > .company > .customer").last().append(
    					$("
").addClass("category").append(
    						$("<input>")
    							.attr("type","checkbox")
    							.attr("company",company.name())
    							.attr("customer",customer.name())
    							.attr("category",category.name())
    							.attr("url",category.child("url").val())
    						).append(
    						      $("").attr("href",category.child("url").val()).html(category.name())
    						).append(
    						      $("").addClass("isvalid").css("color",statusColor).html(statusText)
    						).append(
    						      $("").addClass("removeCategory").html("x")
    						)
    				);
	           });
	       });
	   });
	});
}

// Gets the products from the selected links and optionally saves them
function getProductsFromLinks(save){
	$("#json-output").html("");

	var total = $("#links > .company > .customer > .category > input:checked").size();
	var count = 0;

	if (total <= 0){
		alert("Please select a product store > category");
	}else{

		$("#links > .company > .customer > .category > input:checked").each(function(){
			var company = $(this).attr("company");
			var customer = $(this).attr("customer");
			var category = $(this).attr("category");
			var url = $(this).attr("url");
			url = storeApi.getFullUrl(company, url);

			$.post("webProxy.php", {u:url}, function(data){
			    if (data == null || data.trim() == ""){
			         console.log("webProxy returned nothing. Make sure the URL is correct and does not redirect.");
			     }

			    var jsonProducts = storeApi.getProducts(company, data, url);
			    var storeProducts = $.parseJSON(jsonProducts);

			    for (var i=0; i < Object.keys(storeProducts).length; i++){
			         var sku = Object.keys(storeProducts)[i];
			         storeProducts[sku]['company'] = company;
			         storeProducts[sku]['customer'] = customer;
			         storeProducts[sku]['category'] = category;
			    }

			    if (save){
			        // Used for firebase
    				$("#json-output").append(
    					$("
")
    						.attr("company", company)
    						.attr("customer", customer)
    						.attr("category", category)
    						.html( storeProducts )
    				);

    				// Used for database
    				if ($("#json-products").text() != ""){
        				var jsonProducts = $.parseJSON($("#json-products").text());
        				$.extend(storeProducts, jsonProducts);
    				}
    				$("#json-products").text(JSON.stringify(storeProducts));

    				count++;
    				if(count == total){
    				    saveAllProducts();
    				}
			    }else{
			         alert(company + " > " + customer + " > " + category + ": " + storeProducts);
			    }
			});
		});
	}
}

// Gets the checked prdocuts frm the link, validates them, and shows a sampling of them
function testProductsFromLinks(showSample){

	var total = $("#links > .company > .customer > .category > input:checked").size();
	var count = 0;
	var validCount = 0;

	if (total <= 0){
		alert("Please select a product store > category");
	}else{

		$("#links > .company > .customer > .category > input:checked").each(function(){
		    $(this).siblings(".isvalid").remove();

		    var link = $(this);
			var company = link.attr("company");
			var customer = link.attr("customer");
			var category = link.attr("category");
			var url = link.attr("url");
			url = storeApi.getFullUrl(company, url);

			$.post("webProxy.php", {u:url}, function(data){																		    if (data == null || data.trim() == ""){
			         console.log("webProxy returned nothing. Make sure the URL is correct and does not redirect.");
			     }

				var isValid = false;
				var itemCount = 0;

				try{
				    var dataString = storeApi.getProducts(company, data, url);
				    var data = $.parseJSON(dataString);

				    if (data != null && data.constructor === {}.constructor){
				        var testProduct = data[Object.keys(data)[0]];

				        if (testProduct != null &&
				            testProduct.price != null &&
				            testProduct.image != null &&
				            testProduct.link != null &&
				            testProduct.name != null &&
				            testProduct.sku != null){

				                var price = testProduct.price + "";
				                price = parseFloat(price.replace("$",""));
        				        price = parseFloat(price);

        				        if(!isNaN(price)){
            				        isValid = true;
            				        itemCount = Object.keys(data).length;
            				        validCount++;

            				        if (showSample && validCount == 1){
            				            showSampleProducts(data, company, customer, category);
            				        }
        				        }
				            }else{
				                console.log("one or more of the fields in the product entity are null");
				            }
				    }
				}catch(err){
				    // do nothing
				    console.log("Whoops ran into a problem: " + err);
				}

				if (isValid){
				    link.siblings("a").after(' - Works! ('+itemCount+' products)');

				    var statusObj = {status: "Works!", count: itemCount};

				    firebase.$.child("spider")
	                         .child(company)
	                         .child(customer)
	                         .child(category).update(statusObj);

				}else{
				    link.siblings("a").after(' - BROKEN :(');

				    var statusObj = {status: "BROKEN :(", count: itemCount};

				    firebase.$.child("spider")
	                         .child(company)
	                         .child(customer)
	                         .child(category).update(statusObj);
				}

				count++;
				if(count == total){
					alert(validCount + "/" + total + " catgeories were valid");
				}
			});
		});
	}
}

function showSampleProducts(data, company, audience, category){
    if (data != null && Object.keys(data).length > 0){
        gridPresenter.beginTask();
        var grid = $("#sample-grid");
        grid.html("");

    	for(var i=0; i< 28 ;i++){
    		var outfit = getProductTemplate(data[Object.keys(data)[i]], company, audience, category);
    		grid.append(outfit);
    	}

     	gridPresenter.endTask();
     	gridPresenter.alignGrid("sample-grid", 4, 200, 270, 25);
     	$(document).on("mouseenter",".outfit", gridEvents.showOverlay);
    }
}

// Saves the products
function saveAllProducts(){
	var total = $("#links > .company > .customer > .category > input:checked").size();
	var fireBaseStore = new Firebase('https://clothies.firebaseio.com/store/products');
 	var success = 0;

 	if (total <= 0){
		alert("There is nothing to save! Please add product data.");
	}else{
	    $.post( window.HOME_ROOT + "spider/update", $.parseJSON($("#json-products").text()), function( result ) {
            console.log(result);

            var output = "";

            if (result == null){
                output += "Data was NOT saved successfully! ";
            }else{
                if (result['clearProducts'] != null && result['clearProducts']){

                    if (result['new'] != null && !isNaN(result['new']) &&
                        result['updated'] != null && !isNaN(result['updated']) &&
                        result['historicalPrices'] != null && !isNaN(result['historicalPrices'])){

                            output += " Success! ";
                            output += " Processed " + result['numProducts'] + " products! ";
                    }

                    if (result['new'] == null || isNaN(result['new'])){
                        output += "Error adding new products! ";
                    }else{
                        output += "Added " + result['new'] + " new products. ";
                    }

                    if (result['updated'] == null || isNaN(result['updated'])){
                        output += "Error updating existing products! ";
                    }else{
                        output += "Updated " + result['updated'] + " products! ";
                    }

                    if (result['historicalPrices'] == null || isNaN(result['historicalPrices'])){
                        output += "Error getting historical prices! ";
                    }else{
                        output += "Added " + result['historicalPrices'] + " historical prices! ";
                    }
                }else{
                    output += "There was an issue saving the products. Data was NOT saved successfully! ";
                }
            }

            alert(output);
        }
        , "json"
        );
	}
}

$('form').submit(function(e) {
	e.preventDefault();

	var company = $("#inputCompany").val().toLowerCase().trim();
	var customer = $("#inputAudience").val().toLowerCase().trim();
	var category = $("#inputCategory").val().toLowerCase().trim();
	var catObj = {url: $("#inputLink").val(), status: "not tested"};

	firebase.$.child("spider").child(company).child(customer).child(category).set(catObj, function(error){
	  if (!error){
	      getLinks();
	      alert("Added!");
			  $("#inputLink").val("");
			  $("#inputCategory").val("");
	  }
	});

	return false;
});

function getProductTemplate(product, company, audience, category){
    if (product == null){
        return $("");
    }

	var link = product.link;
	var image = product.image;
	var name = product.name;
	var id = product.sku;
	var price = product.price + "";
	price = "$" + Math.round(parseInt(price.replace("$","").trim()));

	var rand = Math.floor(Math.random() * 3) + 1;
	var shadow = "";
	if(rand == 1){
		shadow = 'shadow';
	}

		//var attr = 	'company="'+company+'" customer="'+audience+'" category="'+category+'" price="'+filterPrice+'"';
		var attr = 	''; //'company="'+company+'" customer="'+audience+'" category="'+category+'"';
	var html ='
';
			html +='

';
			html +='
';
				html +='
';
					html +='

';
				html += '
';
				html +='
';
					html +='

';
				html += '
';
				html +='
';
				    html += '
';
				       html += '
0
';
				    html += '
';
					html +='
' + company + '
';
					html +='
' +  price + '
';
					html +='
' + name + '
';
				html += '
';
				html += '

';
			html += '
';
			html += '

';
		html +='
';

	return $(html);
}

function getTotalProductCount(){
    $.post( window.HOME_ROOT + "spider/count", function( result ) {
            console.log(result);

            if (isNaN(result)){
                alert("There was an error getting the total product count!");
            }else{
                alert("There are currently " + result + " products in the database");
            }
    });
}

$('#selectall').click(function () {
    $("#links").find(':checkbox').prop('checked', true);
});

$('#deselectall').click(function () {
    $("#links").find(':checkbox').prop('checked', false);
});

$(document).on("click",".companyName", function(el){
    if ($(el.currentTarget).parent(".company").find(':checkbox').first().prop('checked')){
        $(el.currentTarget).parent(".company").find(':checkbox').prop('checked', false);
    }else{
        $(el.currentTarget).parent(".company").find(':checkbox').prop('checked', true);
    }
});

$(document).on("click",".customerName", function(el){
    if ($(el.currentTarget).parent(".customer").find(':checkbox').first().prop('checked')){
        $(el.currentTarget).parent(".customer").find(':checkbox').prop('checked', false);
    }else{
        $(el.currentTarget).parent(".customer").find(':checkbox').prop('checked', true);
    }
});

$(document).on("click",".removeCategory", function(el){
    var category = $(el.currentTarget).siblings(':checkbox');

    var dialog = confirm("Are you sure you want to remove " + category.attr("company") + " -> " + category.attr("customer") + " -> " + category.attr("category") + "? ");

    if (dialog==true){
        firebase.$.child("spider")
                  .child(category.attr("company"))
                  .child(category.attr("customer"))
                  .child(category.attr("category"))
                  .remove(function(error) {
                      if (error){
                        alert("There was a problem removing this category")
                      }else{
                        $(el.currentTarget).parents(".category").remove();
                        alert("Category was removed! (This only deletes the category. It does not delete products that were already added to this category)")
                      }
                   });
    }

});

$(document).find(".feedback-maximize").hide('fade');
$(document).find(".feedback-minimized").show('fade');<|endoftext|>


<commit_before>
var gBossFightTriggers = [
  {
    id: 'test',
    zoneRegex: /^Middle La Noscea$/,
    startRegex: /:You bow courteously to the striking dummy/,
    endRegex: /:You bid farewell to the striking dummy/,
    countdownStarts: true,
  },
  {
    id: 'o1s',
    zoneRegex: /^Deltascape V1.0 \(Savage\)$/,
    startRegex: /:Alte Roite uses Wyrm Tail/,
    endRegex: /:Alte Roite was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o2s',
    zoneRegex: /^Deltascape V2.0 \(Savage\)$/,
    startRegex: /:Catastrophe uses Earthquake/,
    endRegex: /:Catastrophe was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o3s',
    zoneRegex: /^Deltascape V3.0 \(Savage\)$/,
    startRegex: /:Halicarnassus uses Critical Hit/,
    endRegex: /:Halicarnassus was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o4s-exdeath',
    zoneRegex: /^Deltascape V4.0 \(Savage\)$/,
    startRegex: /:Exdeath uses Dualcast/,
    endRegex: /:The limit gauge resets!/,
    countdownStarts: false,
  },
  {
    id: 'o4s-neo',
    zoneRegex: /^Deltascape V4.0 \(Savage\)$/,
    startRegex: /:Neo Exdeath uses Almagest/,
    endRegex: /:Neo Exdeath is defeated/,
    countdownStarts: false,
  },
  {
    id: 'Unending Coil',
    zoneRegex: /^The Unending Coil Of Bahamut \(Ultimate\)$/,
    startRegex: /:Twintania:26A7:/,
    endRegex: /Removing combatant Bahamut Prime\.  Max HP: 13751450\./,
    countdownStarts: true,
  },
  {
    id: 'Shinryu Ex',
    zoneRegex: /^The Minstrel's Ballad: Shinryu's Domain$/,
    startRegex: /:Shinryu starts using Earthen Fury/,
    endRegex: /Removing combatant Shinryu\.  Max HP: 17167557\./,
    countdownStarts: true,
  },
  {
    id: 'o5s',
    zoneRegex: /Sigmascape V1\.0 \(Savage\)/,
    startRegex: /:Wroth Ghost:28B6:/,
    endRegex: /:Phantom Train was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o6s',
    zoneRegex: /Sigmascape V2\.0 \(Savage\)/,
    startRegex: /14:2829:Demon Chadarnook starts using Demonic Shear/,
    endRegex: /:Demon Chadarnook was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o7s',
    zoneRegex: /Sigmascape V3\.0 \(Savage\)/,
    startRegex: /00:0044:WEAPON SYSTEMS ONLINE/,
    endRegex: /:Guardian was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o8s-kefka',
    zoneRegex: /Sigmascape V4\.0 \(Savage\)/,
    startRegex: / 15:........:Kefka:28C2:/,
    endRegex: /:Kekfa was defeated by/,
    countdownStarts: false,
  },
  {
    id: 'Byakko Ex',
    zoneRegex: /^The Jade Stoa \(Extreme\)$/,
    startRegex: /:Byakko starts using Storm Pulse/,
    endRegex: /:Byakko was defeated by/,
    countdownStarts: true,
  },
];
<commit_msg>Update fights.js for o8s god kefka<commit_after>
var gBossFightTriggers = [
  {
    id: 'test',
    zoneRegex: /^Middle La Noscea$/,
    startRegex: /:You bow courteously to the striking dummy/,
    endRegex: /:You bid farewell to the striking dummy/,
    countdownStarts: true,
  },
  {
    id: 'o1s',
    zoneRegex: /^Deltascape V1.0 \(Savage\)$/,
    startRegex: /:Alte Roite uses Wyrm Tail/,
    endRegex: /:Alte Roite was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o2s',
    zoneRegex: /^Deltascape V2.0 \(Savage\)$/,
    startRegex: /:Catastrophe uses Earthquake/,
    endRegex: /:Catastrophe was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o3s',
    zoneRegex: /^Deltascape V3.0 \(Savage\)$/,
    startRegex: /:Halicarnassus uses Critical Hit/,
    endRegex: /:Halicarnassus was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o4s-exdeath',
    zoneRegex: /^Deltascape V4.0 \(Savage\)$/,
    startRegex: /:Exdeath uses Dualcast/,
    endRegex: /:The limit gauge resets!/,
    countdownStarts: false,
  },
  {
    id: 'o4s-neo',
    zoneRegex: /^Deltascape V4.0 \(Savage\)$/,
    startRegex: /:Neo Exdeath uses Almagest/,
    endRegex: /:Neo Exdeath is defeated/,
    countdownStarts: false,
  },
  {
    id: 'Unending Coil',
    zoneRegex: /^The Unending Coil Of Bahamut \(Ultimate\)$/,
    startRegex: /:Twintania:26A7:/,
    endRegex: /Removing combatant Bahamut Prime\.  Max HP: 13751450\./,
    countdownStarts: true,
  },
  {
    id: 'Shinryu Ex',
    zoneRegex: /^The Minstrel's Ballad: Shinryu's Domain$/,
    startRegex: /:Shinryu starts using Earthen Fury/,
    endRegex: /Removing combatant Shinryu\.  Max HP: 17167557\./,
    countdownStarts: true,
  },
  {
    id: 'o5s',
    zoneRegex: /Sigmascape V1\.0 \(Savage\)/,
    startRegex: /:Wroth Ghost:28B6:/,
    endRegex: /:Phantom Train was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o6s',
    zoneRegex: /Sigmascape V2\.0 \(Savage\)/,
    startRegex: /14:2829:Demon Chadarnook starts using Demonic Shear/,
    endRegex: /:Demon Chadarnook was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o7s',
    zoneRegex: /Sigmascape V3\.0 \(Savage\)/,
    startRegex: /00:0044:WEAPON SYSTEMS ONLINE/,
    endRegex: /:Guardian was defeated by/,
    countdownStarts: true,
  },
  {
    id: 'o8s-kefka',
    zoneRegex: /Sigmascape V4\.0 \(Savage\)/,
    startRegex: / 15:........:Kefka:28C2:/,
    endRegex: /:Kekfa was defeated by/,
    countdownStarts: false,
  },
  {
    id: 'o8s-god kefka',
    zoneRegex: /Sigmascape V4\.0 \(Savage\)/,
    startRegex: / 15:........:Kefka:28EC:/,
    endRegex: /:Kekfa was defeated by/,
    countdownStarts: false,
  },
  {
    id: 'Byakko Ex',
    zoneRegex: /^The Jade Stoa \(Extreme\)$/,
    startRegex: /:Byakko starts using Storm Pulse/,
    endRegex: /:Byakko was defeated by/,
    countdownStarts: true,
  },
];
<|endoftext|>


<commit_before>/*
locale('name', 'Fred'); // saves the value
locale('name'); // returns "Fred"
locale('countries.USA', "United States of America"); // saves the value
locale('countries.USA'); // returns "United States of America"
locale({countries:{USA:"United States of America"}}); // saves the value. It also returns is and can be chained if passing objects.
*/
define('locale', ['resolve', 'date.format', 'supplant', 'extend'], function (resolve, format, supplant, extend) {
    // format is required to localize the dates.
    //TODO: this needs to be updated to support date patterns like European date formats.
    var r;
    var config = {
        localStorageKey: 'language',
        basePath: 'languages',
        defaultLocale: 'en-US',
        fileExtension: '.lang.json',
        persistLanguage: true,
        supported: ['en-US'],
        fallbacks: {'en':'en-US'}
    };
    var language = getLang();
    var defaults = {
        monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
        dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
    };
    var locale = function (key, supplantValues) {
        if (typeof key === 'object') {
            return locale.$set(key);
        }
        return supplant(r.get(key), supplantValues);
    };

    locale.$set = function(key, value) {
        if (key) {
            if (typeof key === 'string') {
                r.set(key, value);
            } else if (typeof key === 'object') {
                extend(locale, key);
                Date.setLocalization(locale.monthNames, locale.dayNames);
                return locale;
            }
        }
        return r.get(key);
    };

    function getLang() {
        var lang = language || window.localStorage.getItem(config.localStorageKey) || window.navigator.language || window.navigator.userLanguage;
        if (config.supported.indexOf(lang) === -1) {
            lang = config.fallbacks[lang] || config.defaultLocale;
        }
        return lang;
    }

    Object.defineProperties(locale, {
        $config: {
            enumerable: true,
            get: function() { return config; },
            set: function(value) {
                extend(config, value);
                return config;
            }
        },
        $lang: {
            enumerable: true,
            get: function () {
                return language;
            },
            set: function (lang) {
                if (lang || !language) {
                    lang = lang || window.localStorage.getItem(config.localStorageKey) || window.navigator.language || window.navigator.userLanguage;
                    if (config.supported.indexOf(lang) === -1) {
                        lang = config.fallbacks[lang] || config.defaultLocale;
                    }
                    if (language !== lang) {
                        language = lang;
                        window.localStorage.setItem(config.localStorageKey, language);
                    }
                }
                return language;
            }
        },
        $url: {
            enumerable: true,
            get: function() {
                return config.basePath + '/' + language + config.fileExtension;
            }
        }
    });
    r = resolve(locale);
    extend(locale, defaults);
    Date.setLocalization(locale.monthNames, locale.dayNames);

    return locale;
});<commit_msg>locale.$get creates a new Locale<commit_after>/*
locale('name', 'Fred'); // saves the value
locale('name'); // returns "Fred"
locale('countries.USA', "United States of America"); // saves the value
locale('countries.USA'); // returns "United States of America"
locale({countries:{USA:"United States of America"}}); // saves the value. It also returns is and can be chained if passing objects.
*/
define('locale', ['resolve', 'date.format', 'supplant', 'extend'], function (resolve, format, supplant, extend) {
    // format is required to localize the dates.
    //TODO: this needs to be updated to support date patterns like European date formats.
    function Locale() {
        var r;
        var config = {
            localStorageKey: 'language',
            basePath: 'languages',
            defaultLocale: 'en-US',
            fileExtension: '.lang.json',
            persistLanguage: true,
            supported: ['en-US'],
            fallbacks: {'en':'en-US'}
        };
        var language = getLang();
        var defaults = {
            monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
            dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
        };
        var locale = function (key, supplantValues) {
            if (typeof key === 'object') {
                return locale.$set(key);
            }
            return supplant(r.get(key), supplantValues);
        };
        locale.$get = function(path) {
            return new Locale()(r.get(path));
        };
        locale.$set = function(key, value) {
            if (key) {
                if (typeof key === 'string') {
                    r.set(key, value);
                } else if (typeof key === 'object') {
                    extend(locale, key);
                    Date.setLocalization(locale.monthNames, locale.dayNames);
                    return locale;
                }
            }
            return r.get(key);
        };

        function getLang() {
            var lang = language || window.localStorage.getItem(config.localStorageKey) || window.navigator.language || window.navigator.userLanguage;
            if (config.supported.indexOf(lang) === -1) {
                lang = config.fallbacks[lang] || config.defaultLocale;
            }
            return lang;
        }

        Object.defineProperties(locale, {
            $config: {
                enumerable: true,
                get: function() { return config; },
                set: function(value) {
                    extend(config, value);
                    return config;
                }
            },
            $lang: {
                enumerable: true,
                get: function () {
                    return language;
                },
                set: function (lang) {
                    if (lang || !language) {
                        lang = lang || window.localStorage.getItem(config.localStorageKey) || window.navigator.language || window.navigator.userLanguage;
                        if (config.supported.indexOf(lang) === -1) {
                            lang = config.fallbacks[lang] || config.defaultLocale;
                        }
                        if (language !== lang) {
                            language = lang;
                            window.localStorage.setItem(config.localStorageKey, language);
                        }
                    }
                    return language;
                }
            },
            $url: {
                enumerable: true,
                get: function() {
                    return config.basePath + '/' + language + config.fileExtension;
                }
            }
        });

        r = resolve(locale);
        extend(locale, defaults);
        Date.setLocalization(locale.monthNames, locale.dayNames);

        return locale;
    }

    return new Locale();
});<|endoftext|>


<commit_before>/*
Copyright 2018 New Vector Ltd

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.
*/

/*
 * Separate file that sets up rageshake logging when imported.
 * This is necessary so that rageshake logging is set up before
 * anything else. Webpack puts all import statements at the top
 * of the file before any code, so imports will always be
 * evaluated first. Other imports can cause other code to be
 * evaluated (eg. the loglevel library in js-sdk, which if set
 * up before rageshake causes some js-sdk logging to be missing
 * from the rageshake.)
 */

import rageshake from "matrix-react-sdk/lib/rageshake/rageshake";
import SdkConfig from "matrix-react-sdk/src/SdkConfig";

function initRageshake() {
    rageshake.init().then(() => {
        console.log("Initialised rageshake: See https://bugs.chromium.org/p/chromium/issues/detail?id=583193 to fix line numbers on Chrome.");

        window.addEventListener('beforeunload', (e) => {
            console.log('riot-web closing');
            // try to flush the logs to indexeddb
            rageshake.flush();
        });

        rageshake.cleanup();
    }, (err) => {
        console.error("Failed to initialise rageshake: " + err);
    });
}

initRageshake();

global.mxSendRageshake = function(text, withLogs) {
    if (withLogs === undefined) withLogs = true;
    require(['matrix-react-sdk/lib/rageshake/submit-rageshake'], (s) => {
        s(SdkConfig.get().bug_report_endpoint_url, {
            userText: text,
            sendLogs: withLogs,
            progressCallback: console.log.bind(console),
        }).then(() => {
            console.log("Bug report sent!");
        }, (err) => {
            console.error(err);
        });
    });
};
<commit_msg>Clarify line number instructions<commit_after>/*
Copyright 2018 New Vector Ltd

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.
*/

/*
 * Separate file that sets up rageshake logging when imported.
 * This is necessary so that rageshake logging is set up before
 * anything else. Webpack puts all import statements at the top
 * of the file before any code, so imports will always be
 * evaluated first. Other imports can cause other code to be
 * evaluated (eg. the loglevel library in js-sdk, which if set
 * up before rageshake causes some js-sdk logging to be missing
 * from the rageshake.)
 */

import rageshake from "matrix-react-sdk/lib/rageshake/rageshake";
import SdkConfig from "matrix-react-sdk/src/SdkConfig";

function initRageshake() {
    rageshake.init().then(() => {
        console.log("Initialised rageshake.");
        console.log("To fix line numbers in Chrome: " +
            "Meatball menu → Settings → Blackboxing → Add /rageshake\\.js$");

        window.addEventListener('beforeunload', (e) => {
            console.log('riot-web closing');
            // try to flush the logs to indexeddb
            rageshake.flush();
        });

        rageshake.cleanup();
    }, (err) => {
        console.error("Failed to initialise rageshake: " + err);
    });
}

initRageshake();

global.mxSendRageshake = function(text, withLogs) {
    if (withLogs === undefined) withLogs = true;
    require(['matrix-react-sdk/lib/rageshake/submit-rageshake'], (s) => {
        s(SdkConfig.get().bug_report_endpoint_url, {
            userText: text,
            sendLogs: withLogs,
            progressCallback: console.log.bind(console),
        }).then(() => {
            console.log("Bug report sent!");
        }, (err) => {
            console.error(err);
        });
    });
};
<|endoftext|>


<commit_before>function getNav() {
  var mainNav = $('ul.main-navigation, ul[role=main-navigation]').before('<fieldset class="mobile-nav">')
  var mobileNav = $('fieldset.mobile-nav').append('<select>');
  mobileNav.find('select').append('<option value="">Navigate…</option>');
  var addOption = function(i, option) {
    mobileNav.find('select').append('<option value="' + this.href + '">» ' + $(this).text() + '</option>');
  }
  mainNav.find('a').each(addOption);
  $('ul.subscription a').each(addOption);
  mobileNav.find('select').bind('change', function(event) {
    if (event.target.value) { window.location.href = event.target.value; }
  });
}

function addSidebarToggler() {
  if(!$('body').hasClass('sidebar-footer')) {
    $('#content').append('');
    $('.toggle-sidebar').bind('click', function(e) {
      e.preventDefault();
      if ($('body').hasClass('collapse-sidebar')) {
        $('body').removeClass('collapse-sidebar');
      } else {
        $('body').addClass('collapse-sidebar');
      }
    });
  }
  var sections = $('aside.sidebar > section');
  if (sections.length > 1) {
    sections.each(function(index, section){
      if ((sections.length >= 3) && index % 3 === 0) {
        $(section).addClass("first");
      }
      var count = ((index +1) % 2) ? "odd" : "even";
      $(section).addClass(count);
    });
  }
  if (sections.length >= 3){ $('aside.sidebar').addClass('thirds'); }
}

function testFeatures() {
  var features = ['maskImage'];
  $(features).map(function(i, feature) {
    if (Modernizr.testAllProps(feature)) {
      $('html').addClass(feature);
    } else {
      $('html').addClass('no-'+feature);
    }
  });
  if ("placeholder" in document.createElement("input")) {
    $('html').addClass('placeholder');
  } else {
    $('html').addClass('no-placeholder');
  }
}

function addCodeLineNumbers() {
  if (navigator.appName === 'Microsoft Internet Explorer') { return; }
  $('div.gist-highlight').each(function(code) {
    var tableStart = '

',
        lineNumbers = '
',
        tableMiddle = '
	',
        tableEnd = '

',
        count = $('.line', code).length;
    for (var i=1;i<=count; i++) {
      lineNumbers += ''+i+'\n';
    }
    var table = tableStart + lineNumbers + tableMiddle + '
'+$('pre', code).html()+'
' + tableEnd;
    $(code).html(table);
  });
}

function flashVideoFallback(){
  var flashplayerlocation = "/assets/jwplayer/player.swf",
      flashplayerskin = "/assets/jwplayer/glow/glow.xml";
  $('video').each(function(video){
    video = $(video);
    if (!Modernizr.video.h264 && swfobject.getFlashPlayerVersion() || window.location.hash.indexOf("flash-test") !== -1){
      video.children('source[src$=mp4]').first().map(function(i, source){
        var src = $(source).attr('src'),
            id = 'video_'+Math.round(1 + Math.random()*(100000)),
            width = video.attr('width'),
            height = parseInt(video.attr('height'), 10) + 30;
            video.after('

');
        swfobject.embedSWF(flashplayerlocation, id, width, height + 30, "9.0.0",
          { file : src, image : video.attr('poster'), skin : flashplayerskin } ,
          { movie : src, wmode : "opaque", allowfullscreen : "true" }
        );
      });
      video.remove();
    }
  });
}

function wrapFlashVideos() {
  $('object').each(function(object) {
    object = $(object);
    if ( $('param[name=movie]', object).length ) {
      var wrapper = object.before('

').previous();
      $(wrapper).children().append(object);
    }
  });
  $('iframe[src*=vimeo],iframe[src*=youtube]').each(function(iframe) {
    iframe = $(iframe);
    var wrapper = iframe.before('

').previous();
    $(wrapper).children().append(iframe);
  });
}

function renderDeliciousLinks(items) {
  var output = "
";
  for (var i=0,l=items.length; i<l; i++) {
    output += '
' + items[i].d + '
';
  }
  output += "
";
  $('#delicious').html(output);
}

$('document').ready(function() {
  testFeatures();
  wrapFlashVideos();
  flashVideoFallback();
  addCodeLineNumbers();
  getNav();
  addSidebarToggler();
});

// iOS scaling bug fix
// Rewritten version
// By @mathias, @cheeaun and @jdalton
// Source url: https://gist.github.com/901295
(function(doc) {
  var addEvent = 'addEventListener',
      type = 'gesturestart',
      qsa = 'querySelectorAll',
      scales = [1, 1],
      meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];
  function fix() {
    meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
    doc.removeEventListener(type, fix, true);
  }
  if ((meta = meta[meta.length - 1]) && addEvent in doc) {
    fix();
    scales = [0.25, 1.6];
    doc[addEvent](type, fix, true);
  }
}(document));

/*!	SWFObject v2.2 modified by Brandon Mathis to contain only what is necessary to dynamically embed flash objects
  * Uncompressed source in javascripts/libs/swfobject-dynamic.js
  * <http://code.google.com/p/swfobject/>
	released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){function s(a,b,d){var q,k=n(d);if(g.wk&&g.wk<312)return q;if(k){if(typeof a.id==l)a.id=d;if(g.ie&&g.win){var e="",c;for(c in a)if(a[c]!=Object.prototype[c])c.toLowerCase()=="data"?b.movie=a[c]:c.toLowerCase()=="styleclass"?e+=' class="'+a[c]+'"':c.toLowerCase()!="classid"&&(e+=" "+c+'="'+a[c]+'"');c="";for(var f in b)b[f]!=Object.prototype[f]&&(c+='<param name="'+f+'" value="'+b[f]+'" />');k.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+e+">"+c+
"</object>";q=n(a.id)}else{f=i.createElement(o);f.setAttribute("type",m);for(var h in a)a[h]!=Object.prototype[h]&&(h.toLowerCase()=="styleclass"?f.setAttribute("class",a[h]):h.toLowerCase()!="classid"&&f.setAttribute(h,a[h]));for(e in b)b[e]!=Object.prototype[e]&&e.toLowerCase()!="movie"&&(a=f,c=e,h=b[e],d=i.createElement("param"),d.setAttribute("name",c),d.setAttribute("value",h),a.appendChild(d));k.parentNode.replaceChild(f,k);q=f}}return q}function n(a){var b=null;try{b=i.getElementById(a)}catch(d){}return b}
function t(a){var b=g.pv,a=a.split(".");a[0]=parseInt(a[0],10);a[1]=parseInt(a[1],10)||0;a[2]=parseInt(a[2],10)||0;return b[0]>a[0]||b[0]==a[0]&&b[1]>a[1]||b[0]==a[0]&&b[1]==a[1]&&b[2]>=a[2]?!0:!1}function u(a){return/[\\\"<>\.;]/.exec(a)!=null&&typeof encodeURIComponent!=l?encodeURIComponent(a):a}var l="undefined",o="object",m="application/x-shockwave-flash",v=window,i=document,j=navigator,g=function(){var a=typeof i.getElementById!=l&&typeof i.getElementsByTagName!=l&&typeof i.createElement!=l,
b=j.userAgent.toLowerCase(),d=j.platform.toLowerCase(),g=d?/win/.test(d):/win/.test(b),d=d?/mac/.test(d):/mac/.test(b),b=/webkit/.test(b)?parseFloat(b.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):!1,k=!+"\u000b1",e=[0,0,0],c=null;if(typeof j.plugins!=l&&typeof j.plugins["Shockwave Flash"]==o){if((c=j.plugins["Shockwave Flash"].description)&&!(typeof j.mimeTypes!=l&&j.mimeTypes[m]&&!j.mimeTypes[m].enabledPlugin))k=!1,c=c.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),e[0]=parseInt(c.replace(/^(.*)\..*$/,"$1"),
10),e[1]=parseInt(c.replace(/^.*\.(.*)\s.*$/,"$1"),10),e[2]=/[a-zA-Z]/.test(c)?parseInt(c.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}else if(typeof v.ActiveXObject!=l)try{var f=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");if(f&&(c=f.GetVariable("$version")))k=!0,c=c.split(" ")[1].split(","),e=[parseInt(c[0],10),parseInt(c[1],10),parseInt(c[2],10)]}catch(h){}return{w3:a,pv:e,wk:b,ie:k,win:g,mac:d}}();return{embedSWF:function(a,b,d,i,k,e,c,f,h){var j={success:!1,id:b};if(g.w3&&!(g.wk&&g.wk<312)&&
a&&b&&d&&i&&k){d+="";i+="";var p={};if(f&&typeof f===o)for(var m in f)p[m]=f[m];p.data=a;p.width=d;p.height=i;a={};if(c&&typeof c===o)for(var n in c)a[n]=c[n];if(e&&typeof e===o)for(var r in e)typeof a.flashvars!=l?a.flashvars+="&"+r+"="+e[r]:a.flashvars=r+"="+e[r];if(t(k))b=s(p,a,b),j.success=!0,j.ref=b}h&&h(j)},ua:g,getFlashPlayerVersion:function(){return{major:g.pv[0],minor:g.pv[1],release:g.pv[2]}},hasFlashPlayerVersion:t,createSWF:function(a,b,d){if(g.w3)return s(a,b,d)},getQueryParamValue:function(a){var b=
i.location.search||i.location.hash;if(b){/\?/.test(b)&&(b=b.split("?")[1]);if(a==null)return u(b);for(var b=b.split("&"),d=0;d<b.length;d++)if(b[d].substring(0,b[d].indexOf("="))==a)return u(b[d].substring(b[d].indexOf("=")+1))}return""}}}();

<commit_msg>fixed video wrapping js<commit_after>function getNav() {
  var mainNav = $('ul.main-navigation, ul[role=main-navigation]').before('<fieldset class="mobile-nav">')
  var mobileNav = $('fieldset.mobile-nav').append('<select>');
  mobileNav.find('select').append('<option value="">Navigate…</option>');
  var addOption = function(i, option) {
    mobileNav.find('select').append('<option value="' + this.href + '">» ' + $(this).text() + '</option>');
  }
  mainNav.find('a').each(addOption);
  $('ul.subscription a').each(addOption);
  mobileNav.find('select').bind('change', function(event) {
    if (event.target.value) { window.location.href = event.target.value; }
  });
}

function addSidebarToggler() {
  if(!$('body').hasClass('sidebar-footer')) {
    $('#content').append('');
    $('.toggle-sidebar').bind('click', function(e) {
      e.preventDefault();
      if ($('body').hasClass('collapse-sidebar')) {
        $('body').removeClass('collapse-sidebar');
      } else {
        $('body').addClass('collapse-sidebar');
      }
    });
  }
  var sections = $('aside.sidebar > section');
  if (sections.length > 1) {
    sections.each(function(index, section){
      if ((sections.length >= 3) && index % 3 === 0) {
        $(section).addClass("first");
      }
      var count = ((index +1) % 2) ? "odd" : "even";
      $(section).addClass(count);
    });
  }
  if (sections.length >= 3){ $('aside.sidebar').addClass('thirds'); }
}

function testFeatures() {
  var features = ['maskImage'];
  $(features).map(function(i, feature) {
    if (Modernizr.testAllProps(feature)) {
      $('html').addClass(feature);
    } else {
      $('html').addClass('no-'+feature);
    }
  });
  if ("placeholder" in document.createElement("input")) {
    $('html').addClass('placeholder');
  } else {
    $('html').addClass('no-placeholder');
  }
}

function addCodeLineNumbers() {
  if (navigator.appName === 'Microsoft Internet Explorer') { return; }
  $('div.gist-highlight').each(function(code) {
    var tableStart = '

',
        lineNumbers = '
',
        tableMiddle = '
	',
        tableEnd = '

',
        count = $('.line', code).length;
    for (var i=1;i<=count; i++) {
      lineNumbers += ''+i+'\n';
    }
    var table = tableStart + lineNumbers + tableMiddle + '
'+$('pre', code).html()+'
' + tableEnd;
    $(code).html(table);
  });
}

function flashVideoFallback(){
  var flashplayerlocation = "/assets/jwplayer/player.swf",
      flashplayerskin = "/assets/jwplayer/glow/glow.xml";
  $('video').each(function(i, video){
    video = $(video);
    if (!Modernizr.video.h264 && swfobject.getFlashPlayerVersion() || window.location.hash.indexOf("flash-test") !== -1){
      video.children('source[src$=mp4]').first().map(i, function(source){
        var src = $(source).attr('src'),
            id = 'video_'+Math.round(1 + Math.random()*(100000)),
            width = video.attr('width'),
            height = parseInt(video.attr('height'), 10) + 30;
            video.after('

');
        swfobject.embedSWF(flashplayerlocation, id, width, height + 30, "9.0.0",
          { file : src, image : video.attr('poster'), skin : flashplayerskin } ,
          { movie : src, wmode : "opaque", allowfullscreen : "true" }
        );
      });
      video.remove();
    }
  });
}

function wrapFlashVideos() {
  $('object').each(function(i, object) {
    if( $(object).find('param[name=movie]').length ){
      $(object).wrap('
')
    }
  });
  $('iframe[src*=vimeo],iframe[src*=youtube]').wrap('
')
}

function renderDeliciousLinks(items) {
  var output = "
";
  for (var i=0,l=items.length; i<l; i++) {
    output += '
' + items[i].d + '
';
  }
  output += "
";
  $('#delicious').html(output);
}

$('document').ready(function() {
  testFeatures();
  wrapFlashVideos();
  flashVideoFallback();
  addCodeLineNumbers();
  getNav();
  addSidebarToggler();
});

// iOS scaling bug fix
// Rewritten version
// By @mathias, @cheeaun and @jdalton
// Source url: https://gist.github.com/901295
(function(doc) {
  var addEvent = 'addEventListener',
      type = 'gesturestart',
      qsa = 'querySelectorAll',
      scales = [1, 1],
      meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : [];
  function fix() {
    meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1];
    doc.removeEventListener(type, fix, true);
  }
  if ((meta = meta[meta.length - 1]) && addEvent in doc) {
    fix();
    scales = [0.25, 1.6];
    doc[addEvent](type, fix, true);
  }
}(document));

/*!	SWFObject v2.2 modified by Brandon Mathis to contain only what is necessary to dynamically embed flash objects
  * Uncompressed source in javascripts/libs/swfobject-dynamic.js
  * <http://code.google.com/p/swfobject/>
	released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
var swfobject=function(){function s(a,b,d){var q,k=n(d);if(g.wk&&g.wk<312)return q;if(k){if(typeof a.id==l)a.id=d;if(g.ie&&g.win){var e="",c;for(c in a)if(a[c]!=Object.prototype[c])c.toLowerCase()=="data"?b.movie=a[c]:c.toLowerCase()=="styleclass"?e+=' class="'+a[c]+'"':c.toLowerCase()!="classid"&&(e+=" "+c+'="'+a[c]+'"');c="";for(var f in b)b[f]!=Object.prototype[f]&&(c+='<param name="'+f+'" value="'+b[f]+'" />');k.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+e+">"+c+
"</object>";q=n(a.id)}else{f=i.createElement(o);f.setAttribute("type",m);for(var h in a)a[h]!=Object.prototype[h]&&(h.toLowerCase()=="styleclass"?f.setAttribute("class",a[h]):h.toLowerCase()!="classid"&&f.setAttribute(h,a[h]));for(e in b)b[e]!=Object.prototype[e]&&e.toLowerCase()!="movie"&&(a=f,c=e,h=b[e],d=i.createElement("param"),d.setAttribute("name",c),d.setAttribute("value",h),a.appendChild(d));k.parentNode.replaceChild(f,k);q=f}}return q}function n(a){var b=null;try{b=i.getElementById(a)}catch(d){}return b}
function t(a){var b=g.pv,a=a.split(".");a[0]=parseInt(a[0],10);a[1]=parseInt(a[1],10)||0;a[2]=parseInt(a[2],10)||0;return b[0]>a[0]||b[0]==a[0]&&b[1]>a[1]||b[0]==a[0]&&b[1]==a[1]&&b[2]>=a[2]?!0:!1}function u(a){return/[\\\"<>\.;]/.exec(a)!=null&&typeof encodeURIComponent!=l?encodeURIComponent(a):a}var l="undefined",o="object",m="application/x-shockwave-flash",v=window,i=document,j=navigator,g=function(){var a=typeof i.getElementById!=l&&typeof i.getElementsByTagName!=l&&typeof i.createElement!=l,
b=j.userAgent.toLowerCase(),d=j.platform.toLowerCase(),g=d?/win/.test(d):/win/.test(b),d=d?/mac/.test(d):/mac/.test(b),b=/webkit/.test(b)?parseFloat(b.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):!1,k=!+"\u000b1",e=[0,0,0],c=null;if(typeof j.plugins!=l&&typeof j.plugins["Shockwave Flash"]==o){if((c=j.plugins["Shockwave Flash"].description)&&!(typeof j.mimeTypes!=l&&j.mimeTypes[m]&&!j.mimeTypes[m].enabledPlugin))k=!1,c=c.replace(/^.*\s+(\S+\s+\S+$)/,"$1"),e[0]=parseInt(c.replace(/^(.*)\..*$/,"$1"),
10),e[1]=parseInt(c.replace(/^.*\.(.*)\s.*$/,"$1"),10),e[2]=/[a-zA-Z]/.test(c)?parseInt(c.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}else if(typeof v.ActiveXObject!=l)try{var f=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");if(f&&(c=f.GetVariable("$version")))k=!0,c=c.split(" ")[1].split(","),e=[parseInt(c[0],10),parseInt(c[1],10),parseInt(c[2],10)]}catch(h){}return{w3:a,pv:e,wk:b,ie:k,win:g,mac:d}}();return{embedSWF:function(a,b,d,i,k,e,c,f,h){var j={success:!1,id:b};if(g.w3&&!(g.wk&&g.wk<312)&&
a&&b&&d&&i&&k){d+="";i+="";var p={};if(f&&typeof f===o)for(var m in f)p[m]=f[m];p.data=a;p.width=d;p.height=i;a={};if(c&&typeof c===o)for(var n in c)a[n]=c[n];if(e&&typeof e===o)for(var r in e)typeof a.flashvars!=l?a.flashvars+="&"+r+"="+e[r]:a.flashvars=r+"="+e[r];if(t(k))b=s(p,a,b),j.success=!0,j.ref=b}h&&h(j)},ua:g,getFlashPlayerVersion:function(){return{major:g.pv[0],minor:g.pv[1],release:g.pv[2]}},hasFlashPlayerVersion:t,createSWF:function(a,b,d){if(g.w3)return s(a,b,d)},getQueryParamValue:function(a){var b=
i.location.search||i.location.hash;if(b){/\?/.test(b)&&(b=b.split("?")[1]);if(a==null)return u(b);for(var b=b.split("&"),d=0;d<b.length;d++)if(b[d].substring(0,b[d].indexOf("="))==a)return u(b[d].substring(b[d].indexOf("=")+1))}return""}}}();

<|endoftext|>


<commit_before>
// Service to extract META TAG
var request = require("request");
var htmlparser = require("htmlparser");
var soupselect = require("soupselect");

module.exports = {
	process: function(twist, callback) {
		request({url: twist.url}, function(error, response, body) {
			// Invalid url
			if (error) {
				callback({
					provider: 'metaparser',
					error: 'invalid url'
				});
				return;
			}

			// Register handler
			response.setEncoding('utf8');
			var handler = new htmlparser.DefaultHandler(function (error, dom) {
				// Unable to handle parser
				if (error) {
					callback({
						provider: 'metaparser',
						error: 'unable to instanciate handler'
					});
					return;
				}

				// Extract title and descriptin
				var metadata = {};
				var metas = soupselect.select(dom, "meta");
				metas.forEach(function(meta) {
					if (meta.attribs.name == 'dc.title' || meta.attribs.property == 'og:title') {
						metadata.title = meta.attribs.content;
					} else if (meta.attribs.name == 'dc.description' || meta.attribs.property == 'og:description') {
						metadata.description = meta.attribs.content;
					} else if (meta.attribs.property == 'og:image') {
						metadata.image = meta.attribs.content;
					}
				});

				// Extract image if not in metadata
				if (!metadata.image) {
					var links = soupselect.select(dom, "link");
					links.forEach(function(link) {
						if (link.attribs.rel == 'image_src')
							metadata.image = link.attribs.href;
					});
				}

				// HACK: Some images could start by / or // instead of protocol
				if (metadata.image.indexOf('//')==0) {
					var i = 0;
					for(; i < metadata.image.length && metadata.image[i] == '/' ; i++);
					var dotdotslashslash = twist.url.indexOf('://');
					var scheme = twist.url.substr(0, dotdotslashslash);
					metadata.image = scheme + "://" + metadata.image.substr(i);
				}

				// Return metadata
				twist.metadata = metadata;
				callback({
					provider: 'metaparser',
					metadata: metadata
				});
			});

			// Launch parsing
			var parser = new htmlparser.Parser(handler);
			parser.parseComplete(body);
		});
	}
}
<commit_msg>Fix issue on previous fix<commit_after>
// Service to extract META TAG
var request = require("request");
var htmlparser = require("htmlparser");
var soupselect = require("soupselect");

module.exports = {
	process: function(twist, callback) {
		request({url: twist.url}, function(error, response, body) {
			// Invalid url
			if (error) {
				callback({
					provider: 'metaparser',
					error: 'invalid url'
				});
				return;
			}

			// Register handler
			response.setEncoding('utf8');
			var handler = new htmlparser.DefaultHandler(function (error, dom) {
				// Unable to handle parser
				if (error) {
					callback({
						provider: 'metaparser',
						error: 'unable to instanciate handler'
					});
					return;
				}

				// Extract title and descriptin
				var metadata = {};
				var metas = soupselect.select(dom, "meta");
				metas.forEach(function(meta) {
					if (meta.attribs.name == 'dc.title' || meta.attribs.property == 'og:title') {
						metadata.title = meta.attribs.content;
					} else if (meta.attribs.name == 'dc.description' || meta.attribs.property == 'og:description') {
						metadata.description = meta.attribs.content;
					} else if (meta.attribs.property == 'og:image') {
						metadata.image = meta.attribs.content;
					}
				});

				// Extract image if not in metadata
				if (!metadata.image) {
					var links = soupselect.select(dom, "link");
					links.forEach(function(link) {
						if (link.attribs.rel == 'image_src')
							metadata.image = link.attribs.href;
					});
				}

				// HACK: Some images could start by / or // instead of protocol
				else if (metadata.image.indexOf('//')==0) {
					var i = 0;
					for(; i < metadata.image.length && metadata.image[i] == '/' ; i++);
					var dotdotslashslash = twist.url.indexOf('://');
					var scheme = twist.url.substr(0, dotdotslashslash);
					metadata.image = scheme + "://" + metadata.image.substr(i);
				}

				// Return metadata
				twist.metadata = metadata;
				callback({
					provider: 'metaparser',
					metadata: metadata
				});
			});

			// Launch parsing
			var parser = new htmlparser.Parser(handler);
			parser.parseComplete(body);
		});
	}
}
<|endoftext|>


<commit_before>'use strict';

var bower = require('../bower');
var rivets = module.exports = Object.create(null);

rivets.version = '~0.5.13'

rivets.add = function() {
  var self = this;

  bower.edit(function(json) {
    json.dependencies.rivets = self.version;
    json.overrides.rivets = {
      main: 'dist/rivets.js'
    };
  });
};

rivets.remove = function() {
  bower.edit(function(json) {
    delete json.dependencies.rivets;
    delete json.overrides.rivets;
  });
};<commit_msg>Add missing semicolon<commit_after>'use strict';

var bower = require('../bower');
var rivets = module.exports = Object.create(null);

rivets.version = '~0.5.13';

rivets.add = function() {
  var self = this;

  bower.edit(function(json) {
    json.dependencies.rivets = self.version;
    json.overrides.rivets = {
      main: 'dist/rivets.js'
    };
  });
};

rivets.remove = function() {
  bower.edit(function(json) {
    delete json.dependencies.rivets;
    delete json.overrides.rivets;
  });
};<|endoftext|>


<commit_before>/**
 * Created by mobilitymacbook on 5/12/16.
 */
<commit_msg>add comment<commit_after>/**
 * Created by mobilitymacbook on 5/12/16.
 */
//外观模式(门面模式)，是一种相对简单而又无处不在的模式。外观模式提供一个高层接口，这个接口使得客户端或子系统更加方便调用<|endoftext|>


<commit_before>'use strict';

const filecount = require('./filecount');
const gulp = require('gulp');
const modernizr = require('gulp-modernizr');
const rename = require('gulp-rename');

const dest_js = 'scripts/lib/';
const dest_css = 'lib/';

module.exports = function () {
  gulp.task('lib-scripts', function () {
    return gulp.src([
      'node_modules/file-saver/FileSaver.js',
      'node_modules/diff/dist/diff.js',
      'node_modules/jquery/dist/jquery.js'
    ])
      .pipe(filecount())
      .pipe(gulp.dest(dest_js));
  });

  gulp.task('lib-styles', function () {
    return gulp.src('node_modules/normalize.css/normalize.css')
      .pipe(filecount())
      .pipe(gulp.dest(dest_css));
  });

  gulp.task('lib-modernizr', function () {
    return gulp.src(['scripts/background/featuredetect.js'])
      .pipe(filecount())
      .pipe(modernizr())
      .pipe(gulp.dest(dest_js));
  });

  gulp.task('lib-requirejs', function () {
    return gulp.src('node_modules/requirejs/require.js')
      .pipe(filecount())
      .pipe(gulp.dest('basic/scripts/'))
      .pipe(gulp.dest('boule/scripts/'))
      .pipe(gulp.dest('tac/scripts/'))
      .pipe(gulp.dest('test/scripts/'));
  });

  gulp.task('lib-test-scripts', function () {
    return gulp.src('node_modules/qunit/qunit/qunit.js')
      .pipe(filecount())
      .pipe(gulp.dest('test/scripts/'));
  });

  gulp.task('lib-test-styles', function () {
    return gulp.src('node_modules/qunit/qunit/qunit.css')
      .pipe(filecount())
      .pipe(gulp.dest('test/style/'));
  });

  return Object.keys(gulp.tasks).filter(task => /^lib-.*$/.test(task));
};
<commit_msg>Remove rename dependency from libs.js<commit_after>'use strict';

const filecount = require('./filecount');
const gulp = require('gulp');
const modernizr = require('gulp-modernizr');

const dest_js = 'scripts/lib/';
const dest_css = 'lib/';

module.exports = function () {
  gulp.task('lib-scripts', function () {
    return gulp.src([
      'node_modules/file-saver/FileSaver.js',
      'node_modules/diff/dist/diff.js',
      'node_modules/jquery/dist/jquery.js'
    ])
      .pipe(filecount())
      .pipe(gulp.dest(dest_js));
  });

  gulp.task('lib-styles', function () {
    return gulp.src('node_modules/normalize.css/normalize.css')
      .pipe(filecount())
      .pipe(gulp.dest(dest_css));
  });

  gulp.task('lib-modernizr', function () {
    return gulp.src(['scripts/background/featuredetect.js'])
      .pipe(filecount())
      .pipe(modernizr())
      .pipe(gulp.dest(dest_js));
  });

  gulp.task('lib-requirejs', function () {
    return gulp.src('node_modules/requirejs/require.js')
      .pipe(filecount())
      .pipe(gulp.dest('basic/scripts/'))
      .pipe(gulp.dest('boule/scripts/'))
      .pipe(gulp.dest('tac/scripts/'))
      .pipe(gulp.dest('test/scripts/'));
  });

  gulp.task('lib-test-scripts', function () {
    return gulp.src('node_modules/qunit/qunit/qunit.js')
      .pipe(filecount())
      .pipe(gulp.dest('test/scripts/'));
  });

  gulp.task('lib-test-styles', function () {
    return gulp.src('node_modules/qunit/qunit/qunit.css')
      .pipe(filecount())
      .pipe(gulp.dest('test/style/'));
  });

  return Object.keys(gulp.tasks).filter(task => /^lib-.*$/.test(task));
};
<|endoftext|>