<commit_before>/*
  KnockoutFire.js
  (c) Hiroshi Saito <hiroshi3110@gmail.com>
  CC BY 2.0

  Basic Usage Example:
    var firebaseRef = new Firebase("https://yourdb.firebaseio.com/items");
    var viewModel = {
      "items": ko.observableArray().extend{firebaseArray:{firebaase: firebaseRef}})
    };
    ko.applyBindings(viewModel, document.getElementById("items"));
*/
KnockoutFire = {version: "0.0.2"}
/*
*/
KnockoutFire.utils = {
    "firstMatchedProperty": function(obj, regexp) {
        for (var k in obj) {
            if (k.match(regexp)) {
                return k;
            }
        }
    }
}
/*
*/
KnockoutFire.observable = function(firebaseRefOrSnap, map) {
    var isPrimitive = true;
    var self = null;
    var ref = null;
    var snap = null;
    map = map || {}
    // primitive or object?
    if (firebaseRefOrSnap.val) {
        isPrimitive = (typeof(firebaseRefOrSnap.val()) != "object");
        ref = firebaseRefOrSnap.ref();
        snap = firebaseRefOrSnap;
    } else {
        ref = firebaseRefOrSnap;
        if (KnockoutFire.utils.firstMatchedProperty(map, /^[^\/\.]+$/)) {
            isPrimitive = false;
        }
        // for (var k in map) {
        //     if (k.match(/^[^\/\.]+$/)) {
        //         isPrimitive = false;
        //         break;
        //     }
        // }
    }
    if (isPrimitive) {
        var val = snap ? snap.val() : null;
        self = ko.observable(val);
        ref.on("value", function(valueSnap) {
            self._remoteValue = valueSnap.val();
            self(valueSnap.val());
        });
        self.subscribe(function(newValue) {
            if (self._remoteValue != newValue) {
                self._ref.set(newValue);
            }
        });
    } else {
        self = ko.observableArray([]);
        ref.on("child_added", function(childSnap) {
            var name = childSnap.name();
            // parent map has a key start with "$"
            var variableKey = KnockoutFire.utils.firstMatchedProperty(map, /^\$/);
            var childMap = (variableKey ? map[variableKey] : map[name]) || {};
            if (variableKey && childMap[".indexOf"]) {
                var childPath =  childMap[".indexOf"].replace(variableKey, name);
                ref.root().child(childPath).once("value", function(valueSnap) {
                    var child = KnockoutFire.observable(valueSnap, childMap);
                    self.push(child);
                    self()[name] = child;
                });
            } else {
                if (childMap[".indexOf"]) {
                    var childPath = childMap[".indexOf"].replace("data()", childSnap.val());
                    var child = KnockoutFire.observable(ref.root().child(childPath), childMap);
                    self.push(child);
                    self()[name] = child;
                } else {
                    var child = KnockoutFire.observable(childSnap, childMap);
                    self.push(child);
                    self()[name] = child;
                }
            }
        });
    }
    // for (var k in map) {
    //     self[k] = map[k];
    // }
    self._ref = ref;
    self()._path = ref.path.toString();
    if (ref.name) { // Query has no name()
        self()._name = ref.name();
    }
    if (snap) {
        self()._priority = snap.getPriority();
    }
    if (map[".extend"]) {
        //console.log(map[".extend"]);
        self.extend(map[".extend"]);
    }
    return self;
}

/*
  firebaseArray observable array extender

  This extender bind the target observableArray with firebase as an array.

  Options:
    firebase: [REQUIRED]
      The firebase reference or query.
    reverseOrder: (true|false)
      Order the items in reverse order of their priority.
    itemExtendFunc: function(item, itemRef)
      Can be used to declare computed observable for each item
      Example:
      ko.observableArray().extend({firebaseArray: {firebase: firebaseRef, itemExtendFunc: function(obj) {
        item.fullName = ko.computed(function() {
          return item.firstName() + " " + item.lastName();
        });
      }}});

  Tips:
    You can get the firebase reference for a knockout context with `ko.contextFor(DOM).$data._ref`.
    Example:
    $(document).on("click", "a.remove", function() {
      var firebaseRef = ko.contextFor(this).$data._ref;
      firebaseRef.remove();
    });
*/
ko.extenders.firebaseArray = function(array, options) {
    var firebaseRef = options.firebase;
    firebaseRef.on("child_added", function(addedSnap) {
        var addItem = function(snap) {
            var item = ko.observable({}).extend({firebaseObject: {snapshot: snap, excludes: options.excludes}})();
            if (options.itemExtendFunc) {
                options.itemExtendFunc(item, snap.ref());
            }
            if (options.reverseOrder) {
                array.unshift(item);
            } else {
                array.push(item);
            }
        };
        if (options.reference) {
            options.reference.child(addedSnap.name()).once("value", function(valueSnap) {
                addItem(valueSnap);
            });
        } else {
            addItem(addedSnap);
        }
    });
    firebaseRef.on("child_removed", function(removedSnap) {
        var name = removedSnap.name();
        array.remove(function(item) {
            return name == item._ref.name();
        });
    });
    firebaseRef.on("child_moved", function(movedSnap, prevChildName) {
        var i, len = array().length, item = undefined;
        for (i=0; i < len; i++) {
            if (array()[i]._ref.name() == movedSnap.name()) {
                item = array.splice(i, 1)[0];
                break;
            }
        }
        if (prevChildName) {
            for (i=0; i < len - 1; i++) {
                if (array()[i]._ref.name() == prevChildName) {
                    break;
                }
            }
            if (options.reverseOrder) {
                array.splice(i, 0, item);
            } else {
                array.splice(i + 1, 0, item);
            }
        } else {
            if (options.reverseOrder) {
                array.unshift(item);
            } else {
                array.push(item);
            }
        }
    });
    return array;
};
/*
  firebaseObject observable object extender

  This extender bind properties of the target with firebase as an object.

  Options:
    snapshot: [REQUIRED]
      The firebase snapshot
*/
ko.extenders.firebaseObject = function(target, options) {
    var snapshot = options.snapshot;
    var excludes = options.excludes || [];
    var val = target();
    val._ref = snapshot.ref();
    val._name = snapshot.name();
    val._priority = snapshot.getPriority();
    if (typeof(snapshot.val()) == "object") {
        for (var name in snapshot.val()) {
            if (excludes.indexOf(name) > -1) {
                continue;
            }
            val[name] = ko.observable(snapshot.val()[name]);
            val[name][".name"] = name;
            val._ref.child(name).on("value", function(valueSnap) {
                var prop = val[valueSnap.name()];
                prop._remoteValue = valueSnap.val();
                prop(valueSnap.val());
            });
            val[name].subscribe(function(newValue) {
                var prop = this.target;
                if (prop._remoteValue != newValue) {
                    val._ref.child(prop[".name"]).set(newValue);
                }
            });
        }
    } else {
        val.val = ko.observable(snapshot.val());
    }
    return target;
};
<commit_msg>Use ko.extenders instead of custom constructors so that created empty observable can be initilalized.<commit_after>/*
  KnockoutFire.js
  (c) Hiroshi Saito <hiroshi3110@gmail.com>
  CC BY 2.0

  Basic Usage Example:
    var firebaseRef = new Firebase("https://yourdb.firebaseio.com/items");
    var viewModel = {
      "items": ko.observableArray().extend{firebaseArray:{firebaase: firebaseRef}})
    };
    ko.applyBindings(viewModel, document.getElementById("items"));
*/
KnockoutFire = {version: "0.0.3"}
/*

*/
KnockoutFire.utils = {
    "firstMatchedProperty": function(obj, regexp) {
        for (var k in obj) {
            if (k.match(regexp)) {
                return k;
            }
        }
    },
    "matchedProperties": function(obj, regexp) {
        var props = [];
        for (var k in obj) {
            if (k.match(regexp)) {
                props.push(k);
            }
        }
        return props;
    }
}
/*

*/
// KnockoutFire.observablePrimitive = function(self, firebaseRef, map) {
//     var self = ko.observable();
//     self.extend({firebase: firebaseRef});
//     firebaseRef.on("value", function(valueSnap) {
//         self._remoteValue = valueSnap.val();
//         self(valueSnap.val());
//     });
//     self.subscribe(function(newValue) {
//         if (self._remoteValue != newValue) {
//             firebaseRef.set(newValue);
//         }
//     });
//     return self;
// };
// KnockoutFire.observableArray = function(self, firebaseRef, map) {
//     if (self) {
//         self([]);
//     } else {
//         self = ko.observableArray([]);
//     }
//     self.extend({firebase: firebaseRef});
//     var variableName = KnockoutFire.utils.firstMatchedProperty(map, /^\$/);
//     var childMap = map[variableName];
//     firebaseRef.on("child_added", function(addedSnap) {
//         if (childMap[".indexOf"]) {
//             var childPath =  childMap[".indexOf"].replace(variableName, addedSnap.name());
//             firebaseRef.root().child(childPath).once("value", function(valueSnap) {
//                 self.push(KnockoutFire._observable(null, valueSnap.ref(), childMap));
//             });
//         } else {
//             self.push(KnockoutFire._observable(null, addedSnap.ref(), childMap));
//         }
//     });
//     return self;
// };
/*
*/
// KnockoutFire._observable = function(self, firebaseRef, map) {
//     var childNames = KnockoutFire.utils.matchedProperties(map, /^[^\$\.][^\/]+$/);
//     // object (named children) or collection ($variable name) or primitive
//     if (childNames.length > 0) {
//         if (self) {
//             self({});
//         } else {
//             self = ko.observable({});
//         }
//         self.extend({firebase: firebaseRef});
//         childNames.forEach(function(name, i) {
//             self()[name] = KnockoutFire._observable(null, firebaseRef.child(name), map[name])
//         });
//     } else {
//         var variableName = KnockoutFire.utils.firstMatchedProperty(map, /^\$/);
//         if (variableName) {
//             self = KnockoutFire.observableArray(self, firebaseRef, map);
//         } else {
//             self = KnockoutFire.observablePrimitive(self, firebaseRef, map);
//         }
//     }
//     if (map[".extend"]) {
//         self.extend(map[".extend"]);
//     }
//     return self;
// };

/*
*/
ko.extenders.firebase = function(self, options) {
    var firebase = {
        ref: options.firebaseRef,
        path: options.firebaseRef.path.toString(),
        map: options.map
    };
    self._ref = options.firebaseRef;
    self._path = options.firebaseRef.path.toString();
    self._map = options.map;
    // query has no name
    if (self._ref.name) {
        self._name = self._ref.name();
        firebase.name = self._ref.name();
    }
    self().firebase = firebase;
    //console.log("knockoutFire: " + self._path);
};
/*
*/
// ko.extenders.firebasePrimitive = function(self, options) {
//     self.extend(firebase: options);
//     self._ref.on("value", function(valueSnap) {
//         self._remoteValue = valueSnap.val();
//         self(valueSnap.val());
//     });
//     self.subscribe(function(newValue) {
//         if (self._remoteValue != newValue) {
//             self._ref.set(newValue);
//         }
//     });
// };
/*
*/
ko.extenders.firebaseCollection = function(self, options) {
    self.extend({"firebase": options});
    var variableName = KnockoutFire.utils.firstMatchedProperty(self._map, /^\$/);
    var childMap = self._map[variableName];
    self._ref.on("child_added", function(addedSnap) {
        var priority = addedSnap.getPriority();
        if (childMap[".indexOf"]) {
            var childPath =  childMap[".indexOf"].replace(variableName, addedSnap.name());
            self._ref.root().child(childPath).once("value", function(valueSnap) {
                var child = KnockoutFire.observable(valueSnap.ref(), childMap);
                child._priority = priority;
                child().firebase.priority = priority;
                self.push(child);
            });
        } else {
            var child = KnockoutFire.observable(addedSnap.ref(), childMap);
            child._priority = priority;
            child().firebase.priority = priority;
            self.push(child);
        }
    });
};
/*
*/
ko.extenders.firebaseObject = function(self, options) {
    self.extend({"firebase": options});
    var childNames = KnockoutFire.utils.matchedProperties(self._map, /^[^\$\.][^\/]+$/);
    if (childNames.length > 0) {
        childNames.forEach(function(name, i) {
            self()[name] = KnockoutFire.observable(self._ref.child(name), self._map[name])
        });
    } else {
        //self(self._name);
        self._ref.on("value", function(valueSnap) {
            self._remoteValue = valueSnap.val();
            self(valueSnap.val());
        });
        self.subscribe(function(newValue) {
            if (self._remoteValue != newValue) {
                self._ref.set(newValue);
            }
        });
    }
};
/*
  In map you must specify every single child.
*/
KnockoutFire.observable = function(firebaseRef, map) {
    var self = null;
    // If map has key start with "$", it must be an array.
    var variableName = KnockoutFire.utils.firstMatchedProperty(map, /^\$/);
    if (variableName) {
        self = ko.observableArray([]);
        self.extend({"firebaseCollection": {"firebaseRef": firebaseRef, "map": map}});
        if (map[".extend"]) {
            self.extend(map[".extend"]);
        }
    } else {
        self = ko.observable({});
        if (map[".indexOf"] && map[".indexOf"].match("data()")) {
            //////
            var childNames = KnockoutFire.utils.matchedProperties(map, /^[^\$\.][^\/]+$/);
            if (childNames.length > 0) {
                childNames.forEach(function(name, i) {
                    self()[name] = ko.observable({});
                });
            }
            //////
            firebaseRef.on("value", function(valueSnap) {
                var path = map[".indexOf"].replace("data()", valueSnap.val());
                var ref = firebaseRef.root().child(path);
                self.extend({"firebase": {"firebaseRef": ref, "map": map}});
                childNames.forEach(function(name, i) {
                    self()[name].extend({"firebaseObject": {"firebaseRef": ref.child(name), "map": map[name]}});
                });
                if (map[".extend"]) {
                    self.extend(map[".extend"]);
                }
            });
        } else {
            self.extend({"firebaseObject": {"firebaseRef": firebaseRef, "map": map}});
            if (map[".extend"]) {
                self.extend(map[".extend"]);
            }
        }
    }
    return self;
}

KnockoutFire.__observable = function(firebaseRefOrSnap, map) {
    var isPrimitive = true;
    var self = null;
    var ref = null;
    var snap = null;
    map = map || {}
    // primitive or object?
    if (firebaseRefOrSnap.val) {
        isPrimitive = (typeof(firebaseRefOrSnap.val()) != "object");
        ref = firebaseRefOrSnap.ref();
        snap = firebaseRefOrSnap;
    } else {
        ref = firebaseRefOrSnap;
        if (KnockoutFire.utils.firstMatchedProperty(map, /^[^\/\.]+$/)) {
            isPrimitive = false;
        }
        // for (var k in map) {
        //     if (k.match(/^[^\/\.]+$/)) {
        //         isPrimitive = false;
        //         break;
        //     }
        // }
    }
    if (isPrimitive) {
        var val = snap ? snap.val() : null;
        self = ko.observable(val);
        ref.on("value", function(valueSnap) {
            self._remoteValue = valueSnap.val();
            self(valueSnap.val());
        });
        self.subscribe(function(newValue) {
            if (self._remoteValue != newValue) {
                self._ref.set(newValue);
            }
        });
    } else {
        self = ko.observableArray([]);
        ref.on("child_added", function(childSnap) {
            var name = childSnap.name();
            // parent map has a key start with "$"
            var variableKey = KnockoutFire.utils.firstMatchedProperty(map, /^\$/);
            var childMap = (variableKey ? map[variableKey] : map[name]) || {};
            if (variableKey && childMap[".indexOf"]) {
                var childPath =  childMap[".indexOf"].replace(variableKey, name);
                ref.root().child(childPath).once("value", function(valueSnap) {
                    var child = KnockoutFire.observable(valueSnap, childMap);
                    self.push(child);
                    self()[name] = child;
                });
            } else {
                if (childMap[".indexOf"]) {
                    var childPath = childMap[".indexOf"].replace("data()", childSnap.val());
                    var child = KnockoutFire.observable(ref.root().child(childPath), childMap);
                    self.push(child);
                    self()[name] = child;
                } else {
                    var child = KnockoutFire.observable(childSnap, childMap);
                    self.push(child);
                    self()[name] = child;
                }
            }
        });
    }
    // for (var k in map) {
    //     self[k] = map[k];
    // }
    self._ref = ref;
    self()._path = ref.path.toString();
    if (ref.name) { // Query has no name()
        self()._name = ref.name();
    }
    if (snap) {
        self()._priority = snap.getPriority();
    }
    if (map[".extend"]) {
        //console.log(map[".extend"]);
        self.extend(map[".extend"]);
    }
    return self;
}

/*
  firebaseArray observable array extender

  This extender bind the target observableArray with firebase as an array.

  Options:
    firebase: [REQUIRED]
      The firebase reference or query.
    reverseOrder: (true|false)
      Order the items in reverse order of their priority.
    itemExtendFunc: function(item, itemRef)
      Can be used to declare computed observable for each item
      Example:
      ko.observableArray().extend({firebaseArray: {firebase: firebaseRef, itemExtendFunc: function(obj) {
        item.fullName = ko.computed(function() {
          return item.firstName() + " " + item.lastName();
        });
      }}});

  Tips:
    You can get the firebase reference for a knockout context with `ko.contextFor(DOM).$data._ref`.
    Example:
    $(document).on("click", "a.remove", function() {
      var firebaseRef = ko.contextFor(this).$data._ref;
      firebaseRef.remove();
    });
*/
ko.extenders._firebaseArray = function(array, options) {
    var firebaseRef = options.firebase;
    firebaseRef.on("child_added", function(addedSnap) {
        var addItem = function(snap) {
            var item = ko.observable({}).extend({firebaseObject: {snapshot: snap, excludes: options.excludes}})();
            if (options.itemExtendFunc) {
                options.itemExtendFunc(item, snap.ref());
            }
            if (options.reverseOrder) {
                array.unshift(item);
            } else {
                array.push(item);
            }
        };
        if (options.reference) {
            options.reference.child(addedSnap.name()).once("value", function(valueSnap) {
                addItem(valueSnap);
            });
        } else {
            addItem(addedSnap);
        }
    });
    firebaseRef.on("child_removed", function(removedSnap) {
        var name = removedSnap.name();
        array.remove(function(item) {
            return name == item._ref.name();
        });
    });
    firebaseRef.on("child_moved", function(movedSnap, prevChildName) {
        var i, len = array().length, item = undefined;
        for (i=0; i < len; i++) {
            if (array()[i]._ref.name() == movedSnap.name()) {
                item = array.splice(i, 1)[0];
                break;
            }
        }
        if (prevChildName) {
            for (i=0; i < len - 1; i++) {
                if (array()[i]._ref.name() == prevChildName) {
                    break;
                }
            }
            if (options.reverseOrder) {
                array.splice(i, 0, item);
            } else {
                array.splice(i + 1, 0, item);
            }
        } else {
            if (options.reverseOrder) {
                array.unshift(item);
            } else {
                array.push(item);
            }
        }
    });
    return array;
};
/*
  firebaseObject observable object extender

  This extender bind properties of the target with firebase as an object.

  Options:
    snapshot: [REQUIRED]
      The firebase snapshot
*/
ko.extenders._firebaseObject = function(target, options) {
    var snapshot = options.snapshot;
    var excludes = options.excludes || [];
    var val = target();
    val._ref = snapshot.ref();
    val._name = snapshot.name();
    val._priority = snapshot.getPriority();
    if (typeof(snapshot.val()) == "object") {
        for (var name in snapshot.val()) {
            if (excludes.indexOf(name) > -1) {
                continue;
            }
            val[name] = ko.observable(snapshot.val()[name]);
            val[name][".name"] = name;
            val._ref.child(name).on("value", function(valueSnap) {
                var prop = val[valueSnap.name()];
                prop._remoteValue = valueSnap.val();
                prop(valueSnap.val());
            });
            val[name].subscribe(function(newValue) {
                var prop = this.target;
                if (prop._remoteValue != newValue) {
                    val._ref.child(prop[".name"]).set(newValue);
                }
            });
        }
    } else {
        val.val = ko.observable(snapshot.val());
    }
    return target;
};
<|endoftext|>


<commit_before>var array = require("../lib/abaaso.js").abaaso.array;

exports["add"] = {
	setUp: function (done) {
		this.val = [];
		done();
	},
	direct: function (test) {
		test.expect(2);
		test.equal(array.add(this.val, 1).length, 1, "Should be 1");
		test.equal(array.add(this.val, 1)[0], 1, "Should be 1");
		test.done();
	},
	sugar: function (test) {
		test.expect(2);
		test.equal(this.val.add(1).length, 1, "Should be 1");
		test.equal(this.val.add(1)[0], 1, "Should be 1");
		test.done();
	}
};

exports["cast"] = {
	setUp: function (done) {
		this.val = {abc: true, xyz: false};
		done();
	},
	indices: function (test) {
		test.expect(2);
		test.equal(array.cast(this.val)[0], true, "Should be true");
		test.equal(array.cast(this.val)[1], false, "Should be false");
		test.done();
	},
	keys: function (test) {
		test.expect(2);
		test.equal(array.cast(this.val, true)[0], "abc", "Should be 'abc'");
		test.equal(array.cast(this.val, true)[1], "xyz", "Should be 'xyz'");
		test.done();
	}
};

exports["clone"] = {
	setUp: function (done) {
		this.val = [true, false];
		done();
	},
	"clone - direct": function (test) {
		test.expect(2);
		test.equal(array.clone(this.val)[0], true, "Should be true");
		test.equal(array.clone(this.val)[1], false, "Should be false");
		test.done();
	},
	"clone - sugar": function (test) {
		test.expect(2);
		test.equal(this.val.clone()[0], true, "Should be true");
		test.equal(this.val.clone()[1], false, "Should be false");
		test.done();
	}
};

exports["diff"] = {
	setUp: function (done) {
		this.a1 = ['abc', 'def'];
		this.a2 = ['abc', 'xyz'];
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.diff(this.a1, this.a2).length, 2, "Should be 2 differences");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.a1.diff(this.a2).length, 2, "Should be 2 differences");
		test.done();
	}
};<commit_msg>Created array unit tests<commit_after>var array = require("../lib/abaaso.js").abaaso.array;

exports["add"] = {
	setUp: function (done) {
		this.val = [0];
		done();
	},
	direct: function (test) {
		test.expect(2);
		test.equal(array.add(this.val, 0).length, 1, "Should be 1");
		test.equal(array.add(this.val, 1).length, 2, "Should be 2");
		test.done();
	},
	sugar: function (test) {
		test.expect(2);
		test.equal(this.val.add(0).length, 1, "Should be 1");
		test.equal(this.val.add(1).length, 2, "Should be 2");
		test.done();
	}
};

exports["cast"] = {
	setUp: function (done) {
		this.val = {abc: true, xyz: false};
		done();
	},
	indices: function (test) {
		test.expect(2);
		test.equal(array.cast(this.val)[0], true, "Should be true");
		test.equal(array.cast(this.val)[1], false, "Should be false");
		test.done();
	},
	keys: function (test) {
		test.expect(2);
		test.equal(array.cast(this.val, true)[0], "abc", "Should be 'abc'");
		test.equal(array.cast(this.val, true)[1], "xyz", "Should be 'xyz'");
		test.done();
	}
};

exports["clone"] = {
	setUp: function (done) {
		this.val = [true, false];
		done();
	},
	"clone - direct": function (test) {
		test.expect(2);
		test.equal(array.clone(this.val)[0], true, "Should be true");
		test.equal(array.clone(this.val)[1], false, "Should be false");
		test.done();
	},
	"clone - sugar": function (test) {
		test.expect(2);
		test.equal(this.val.clone()[0], true, "Should be true");
		test.equal(this.val.clone()[1], false, "Should be false");
		test.done();
	}
};

exports["diff"] = {
	setUp: function (done) {
		this.a1 = ["abc", "def"];
		this.a2 = ["abc", "xyz"];
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.diff(this.a1, this.a2).length, 2, "Should be 2 differences");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.a1.diff(this.a2).length, 2, "Should be 2 differences");
		test.done();
	}
};

exports["each"] = {
	setUp: function (done) {
		this.val = ["abc"];
		self     = this;
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.each(this.val, function (i, idx) { self.val[idx] = "blah"; })[0], "blah", "Should be 'blah'");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.val.each(function (i, idx) { self.val[idx] = "blah"; })[0], "blah", "Should be 'blah'");
		test.done();
	}
};

exports["first"] = {
	setUp: function (done) {
		this.val = ["abc"];
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.first(this.val), "abc", "Should be 'abc'");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.val.first(), "abc", "Should be 'abc'");
		test.done();
	}
};

exports["index"] = {
	setUp: function (done) {
		this.val = ["abc", "xyz"];
		done();
	},
	direct: function (test) {
		test.expect(2);
		test.equal(array.index(this.val, "abc"), 0, "Should be 0");
		test.equal(array.index(this.val, "xyz"), 1, "Should be 1");
		test.done();
	},
	sugar: function (test) {
		test.expect(2);
		test.equal(this.val.index("abc"), 0, "Should be 0");
		test.equal(this.val.index("xyz"), 1, "Should be 1");
		test.done();
	}
};

exports["indexed"] = {
	setUp: function (done) {
		this.val = ["abc", "xyz"];
		this.val.someProperty      = true;
		this.val.someOtherProperty = true;
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.indexed(this.val).length, 4, "Should be 4");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.val.indexed().length, 4, "Should be 4");
		test.done();
	}
};

exports["intersect"] = {
	setUp: function (done) {
		this.a1 = ["abc", "def"];
		this.a2 = ["abc", "xyz"];
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.intersect(this.a1, this.a2).length, 1, "Should be 1 match");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.a1.intersect(this.a2).length, 1, "Should be 1 match");
		test.done();
	}
};

exports["keys"] = {
	setUp: function (done) {
		this.val = ["abc", "xyz"];
		this.val.someProperty      = true;
		this.val.someOtherProperty = true;
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.keys(this.val).length, 4, "Should be 4");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.val.keys().length, 4, "Should be 4");
		test.done();
	}
};

exports["last"] = {
	setUp: function (done) {
		this.val = ["abc", "xyz"];
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.last(this.val), "xyz", "Should be 'xyz'");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.val.last(), "xyz", "Should be 'xyz'");
		test.done();
	}
};

exports["range"] = {
	setUp: function (done) {
		this.val = ["a", "b", "c", "d", "e"];
		done();
	},
	direct: function (test) {
		test.expect(3);
		test.equal(array.range(this.val, 3, 4).length, 2, "Should be 2");
		test.equal(array.range(this.val, 3, 4)[0], "d", "Should be 'd'");
		test.equal(array.range(this.val, 3, 4)[1], "e", "Should be 'e'");
		test.done();
	},
	sugar: function (test) {
		test.expect(3);
		test.equal(this.val.range(3, 4).length, 2, "Should be 2");
		test.equal(this.val.range(3, 4)[0], "d", "Should be 'd'");
		test.equal(this.val.range(3, 4)[1], "e", "Should be 'e'");
		test.done();
	}
};

exports["remove"] = {
	setUp: function (done) {
		this.val = ["abc", "xyz"];
		done();
	},
	direct: function (test) {
		test.expect(4);
		test.equal(array.remove(this.val.clone(), 0).length, 1, "Should be 1");
		test.equal(array.remove(this.val.clone(), 1).length, 1, "Should be 1");
		test.equal(array.remove(this.val.clone(), "abc").length, 1, "Should be 'xyz'");
		test.equal(array.remove(this.val.clone(), "xyz").length, 1, "Should be 'abc'");
		test.done();
	},
	sugar: function (test) {
		test.expect(4);
		test.equal(this.val.clone().remove(0).length, 1, "Should be 1");
		test.equal(this.val.clone().remove(1).length, 1, "Should be 1");
		test.equal(this.val.clone().remove("abc")[0], "xyz", "Should be 'xyz'");
		test.equal(this.val.clone().remove("xyz")[0], "abc", "Should be 'abc'");
		test.done();
	}
};

exports["sort"] = {
	setUp: function (done) {
		this.val = ["abc", "xyz", "A", "d", 123];
		done();
	},
	direct: function (test) {
		test.expect(5);
		test.equal(this.val.sort(array.sort)[0], 123, "Should be 123");
		test.equal(this.val[1], "A", "Should be 'A'");
		test.equal(this.val[2], "abc", "Should be 'abc'");
		test.equal(this.val[3], "d", "Should be 'd'");
		test.equal(this.val[4], "xyz", "Should be 'xyz'");
		test.done();
	}
};

exports["total"] = {
	setUp: function (done) {
		this.val = ["abc", "xyz"];
		this.val.someProperty      = true;
		this.val.someOtherProperty = true;
		done();
	},
	direct: function (test) {
		test.expect(1);
		test.equal(array.total(this.val), 4, "Should be 4");
		test.done();
	},
	sugar: function (test) {
		test.expect(1);
		test.equal(this.val.total(), 4, "Should be 4");
		test.done();
	}
};

exports["toObject"] = {
	setUp: function (done) {
		this.val = ["abc", "xyz", "A", "d", 123];
		done();
	},
	direct: function (test) {
		test.expect(2);
		test.equal(array.toObject(this.val) instanceof Object, true, "Should be true");
		test.equal(array.toObject(this.val)["0"], "abc", "Should be 'abc'");
		test.done();
	}
};<|endoftext|>


<commit_before>//Event Listeners for Submit Button

SubmitButton.addEventListener("click", validateDonationFormName);
SubmitButton.addEventListener("click", validateDonationFormLocation);
// SubmitButton.addEventListener("submit", validateEmail);

// Function to validate the Name input in the DonationForm

function validateDonationFormName(e) {
    e.preventDefault();
    var checkIt = document.forms["DonationForm"]["fname"].value;
    if (checkIt == null || checkIt == "") {
        nameAlert.setAttribute('style', 'visibility:visible');
        return false;
    }
}

// Function to validate the Location input in the DonationForm

function validateDonationFormLocation(e) {
    e.preventDefault();
    var checkIt2 = document.forms["DonationForm"]["flocation"].value;
    if (checkIt2 == null || checkIt2 == "") {
        locationAlert.setAttribute('style', 'visibility:visible');
        return false;
    }
}

// Function to validate the E-Mail input in the DonationForm

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}
<commit_msg>Form validation is working. Message appears if no input<commit_after>var userInput = {};

//Event Listeners for Submit Button

SubmitButton.addEventListener("click", validateDonationFormName);
SubmitButton.addEventListener("click", validateDonationFormLocation);
// SubmitButton.addEventListener("submit", validateEmail);

// Function to validate the Name input in the DonationForm

function validateDonationFormName(e) {
    e.preventDefault();
    var userName = document.forms["DonationForm"]["fname"].value;
    if (userName == null || userName == "") {
        nameAlert.setAttribute('style', 'visibility:visible');
    } else {
      userInput.name = userName;
    }
    console.log(userInput);
}

// Function to validate the Location input in the DonationForm

function validateDonationFormLocation(e) {
    e.preventDefault();
    var userEmail = document.forms["DonationForm"]["flocation"].value;
    if (userEmail == null || userEmail == "") {
        locationAlert.setAttribute('style', 'visibility:visible');
    } else {
      userInput.name = userEmail;
    }
    console.log(userInput);
}

// Function to validate the E-Mail input in the DonationForm

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(email);
}

//Local Storage
<|endoftext|>


<commit_before>var margin = {top: 20, right: 80, bottom: 30, left: 50},
    width = 1140 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    heightBrush = 200 - margin.top - margin.bottom;

//var parseDate = d3.time.format("%d-%b-%y").parse;

var brush;

var x = d3.time.scale().range([0, width]),
    y = d3.scale.linear().range([height, 0]);

var x2 = d3.time.scale().range([0, width]);

var xAxis = d3.svg.axis().scale(x).orient("bottom"),
    yAxis = d3.svg.axis().scale(y).orient("left");

var color = d3.scale.category10();

var line = d3.svg.line()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); });

var svg = d3.select("#graph").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var svgBrush = d3.select("#graph").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", heightBrush + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

function showChart(data, chartInit) {
    color.domain(d3.keys(["Hamburg", "Munich"]));

    x.domain([
        d3.min(data, function(c) { return d3.min(c.data, function(v) { return v.date; }); }),
        d3.max(data, function(c) { return d3.max(c.data, function(v) { return v.date; }); })
    ]);
    y.domain([
        d3.min(data, function(c) { return d3.min(c.data, function(v) { return v.value; }); }),
        d3.max(data, function(c) { return d3.max(c.data, function(v) { return v.value; }); })
    ]);

    var node = svg.selectAll("g.city")
        .data(data, function(d) {
            return d.name;
        });

    var enter = node.enter().append("g")
        .attr("class", "city");

    enter.append("path")
        .attr("class", "line")
        .attr("d", function(d) {
            return line(d.data);
        })
        .style("stroke", function(d) {
            return color(d.name);
        });

    enter.append("text")
        .datum(function(d) { return {name: d.name, value: d.data[d.data.length - 1]}; })
        .attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.value) + ")"; })
        .attr("x", 3)
        .attr("dy", ".35em")
        .text(function(d) { return d.name; });

    var remove = node.exit().remove();

    if(chartInit) {
        draw(data);
    } else {
        update(data);
    }
}

function draw(data) {
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Temperature");
}

function update(data) {
    var chart = d3.select("#graph").transition();

    chart.select(".x.axis")
        .duration(750)
        .call(xAxis);

    chart.select(".y.axis")
        .duration(750)
        .call(yAxis);

/*    chart.selectAll(".line")
        .duration(750)
        .attr("d", function(d) {
            return line(d.data);
        })*/
}

var brushInit = false;

function showBrush(start, end, coarseTicks, fineTicks, fineTicksCount) {
    x2.domain([start, end]);

    brush =  d3.svg.brush()
        .x(x2)
        .on("brushend", brushended);

    if(!brushInit) {
        drawBrush(coarseTicks, fineTicks, fineTicksCount);
        brushInit = true;
    } else {
        updateBrush(coarseTicks, fineTicks, fineTicksCount);
    }
}

var xGrid = d3.svg.axis()
    .scale(x2)
    .orient("bottom")
    .tickSize(-heightBrush)
    .tickFormat("");

var xAxisBrush = d3.svg.axis()
    .scale(x2)
    .orient("bottom");

function drawBrush(coarseTicks, fineTicks, fineTicksCount) {
    svgBrush.append("rect")
        .attr("class", "grid-background")
        .attr("width", width)
        .attr("height", heightBrush);

    svgBrush.append("g")
        .attr("class", "x grid")
        .attr("transform", "translate(0," + heightBrush + ")")
        .call(xGrid.ticks(fineTicks, fineTicksCount))
        .selectAll(".tick")
        .classed("minor", function(d) { return d.getHours(); });

    svgBrush.append("g")
        .attr("class", "x axisBrush")
        .attr("transform", "translate(0," + heightBrush + ")")
        .call(xAxisBrush.ticks(coarseTicks))
        .selectAll("text")
        .attr("x", 6)
        .style("text-anchor", null);

    var gBrush = svgBrush.append("g")
        .attr("class", "brush")
        .call(brush)
        .call(brush.event);

    gBrush.selectAll("rect")
        .attr("height", heightBrush);
}

function updateBrush(coarseTicks, fineTicks, fineTicksCount) {
    var chart = d3.select("#graph").transition();

    chart.select(".x.grid")
        .duration(750)
        .call(xGrid.ticks(fineTicks, fineTicksCount));

    chart.select(".x.axisBrush")
        .duration(750)
        .call(xAxisBrush.ticks(coarseTicks));

    chart.select(".brush")
        .duration(750)
        .call(brush.clear());
}

function brushended() {
    if (!d3.event.sourceEvent) return; // only transition after input
    var extent0 = brush.extent(),
        extent1 = extent0.map(picker.getTimeLevel().round);

    // if empty when rounded, use floor & ceil instead
    if (extent1[0] >= extent1[1]) {
        extent1[0] = picker.getTimeLevel().floor(extent0[0]);
        extent1[1] = picker.getTimeLevel().ceil(extent0[1]);
    }

    d3.select(this).transition()
        .call(brush.extent(extent1))
        .call(brush.event);

    updateBoundaries(extent1[0], extent1[1]);
}<commit_msg>Fix update lines at climate visualization<commit_after>var margin = {top: 20, right: 80, bottom: 30, left: 50},
    width = 1140 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom,
    heightBrush = 200 - margin.top - margin.bottom;

//var parseDate = d3.time.format("%d-%b-%y").parse;

var brush;

var x = d3.time.scale().range([0, width]),
    y = d3.scale.linear().range([height, 0]);

var x2 = d3.time.scale().range([0, width]);

var xAxis = d3.svg.axis().scale(x).orient("bottom"),
    yAxis = d3.svg.axis().scale(y).orient("left");

var color = d3.scale.category10();

var line = d3.svg.line()
    .interpolate("basis")
    .x(function(d) { return x(d.date); })
    .y(function(d) { return y(d.value); });

var svg = d3.select("#graph").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var svgBrush = d3.select("#graph").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", heightBrush + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

function showChart(data, chartInit) {
    color.domain(d3.keys(["Hamburg", "Munich"]));

    x.domain([
        d3.min(data, function(c) { return d3.min(c.data, function(v) { return v.date; }); }),
        d3.max(data, function(c) { return d3.max(c.data, function(v) { return v.date; }); })
    ]);
    y.domain([
        d3.min(data, function(c) { return d3.min(c.data, function(v) { return v.value; }); }),
        d3.max(data, function(c) { return d3.max(c.data, function(v) { return v.value; }); })
    ]);

    var node = svg.selectAll("g.city")
        .data(data, function(d) {
            return d.name;
        });

    var enter = node.enter().append("g")
        .attr("class", "city");

    enter.append("path")
        .attr("class", "line")
        .style("stroke", function(d) {
            return color(d.name);
        });

    node.select("path")
        .transition()
        .duration(750)
        .attr("d", function(d) {
            return line(d.data);
        });

    enter.append("text")
        .attr("x", 3)
        .attr("dy", ".35em")
        .text(function(d) { return d.name; });

    node.select("text")
        .transition()
        .duration(750)
        .attr("transform", function(d) {
            var xy = d.data[d.data.length - 1];
            return "translate(" + x(xy.date) + "," + y(xy.value) + ")";
        });

    var remove = node.exit().remove();

    if(chartInit) {
        draw(data);
    } else {
        update(data);
    }
}

function draw(data) {
    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Temperature");
}

function update(data) {
    var chart = d3.select("#graph").transition();

    chart.select(".x.axis")
        .duration(750)
        .call(xAxis);

    chart.select(".y.axis")
        .duration(750)
        .call(yAxis);

/*    chart.selectAll(".line")
        .duration(750)
        .attr("d", function(d) {
            return line(d.data);
        })*/
}

var brushInit = false;

function showBrush(start, end, coarseTicks, fineTicks, fineTicksCount) {
    x2.domain([start, end]);

    brush =  d3.svg.brush()
        .x(x2)
        .on("brushend", brushended);

    if(!brushInit) {
        drawBrush(coarseTicks, fineTicks, fineTicksCount);
        brushInit = true;
    } else {
        updateBrush(coarseTicks, fineTicks, fineTicksCount);
    }
}

var xGrid = d3.svg.axis()
    .scale(x2)
    .orient("bottom")
    .tickSize(-heightBrush)
    .tickFormat("");

var xAxisBrush = d3.svg.axis()
    .scale(x2)
    .orient("bottom");

function drawBrush(coarseTicks, fineTicks, fineTicksCount) {
    svgBrush.append("rect")
        .attr("class", "grid-background")
        .attr("width", width)
        .attr("height", heightBrush);

    svgBrush.append("g")
        .attr("class", "x grid")
        .attr("transform", "translate(0," + heightBrush + ")")
        .call(xGrid.ticks(fineTicks, fineTicksCount))
        .selectAll(".tick")
        .classed("minor", function(d) { return d.getHours(); });

    svgBrush.append("g")
        .attr("class", "x axisBrush")
        .attr("transform", "translate(0," + heightBrush + ")")
        .call(xAxisBrush.ticks(coarseTicks))
        .selectAll("text")
        .attr("x", 6)
        .style("text-anchor", null);

    var gBrush = svgBrush.append("g")
        .attr("class", "brush")
        .call(brush)
        .call(brush.event);

    gBrush.selectAll("rect")
        .attr("height", heightBrush);
}

function updateBrush(coarseTicks, fineTicks, fineTicksCount) {
    var chart = d3.select("#graph").transition();

    chart.select(".x.grid")
        .duration(750)
        .call(xGrid.ticks(fineTicks, fineTicksCount));

    chart.select(".x.axisBrush")
        .duration(750)
        .call(xAxisBrush.ticks(coarseTicks));

    chart.select(".brush")
        .duration(750)
        .call(brush.clear());
}

function brushended() {
    if (!d3.event.sourceEvent) return; // only transition after input
    var extent0 = brush.extent(),
        extent1 = extent0.map(picker.getTimeLevel().round);

    // if empty when rounded, use floor & ceil instead
    if (extent1[0] >= extent1[1]) {
        extent1[0] = picker.getTimeLevel().floor(extent0[0]);
        extent1[1] = picker.getTimeLevel().ceil(extent0[1]);
    }

    d3.select(this).transition()
        .call(brush.extent(extent1))
        .call(brush.event);

    updateBoundaries(extent1[0], extent1[1]);
}<|endoftext|>


<commit_before>app.controller('MessageController', ['$http', 'AuthFactory', '$mdDialog', function($http, AuthFactory, $mdDialog) {
  console.log('MessageController running');
  var self = this;
  self.newMessage = [];
  var authInfo = AuthFactory.auth;
  var userStatus = AuthFactory.userStatus;
  // var messageInfo =

  // console.log(InboxController.selectedMessage);

  self.userStatus = AuthFactory.userStatus;

  self.sendMessage = function(message){
    console.log('newMessage: ', self.newMessage);
    console.log('authInfo: ', authInfo);
    console.log('userStatus: ', userStatus);
    // $http.post('/message/new-message', self.newMessage);
    //   .then(function(response) {
    //     console.log('response: ', response);
    //   });
  // };

  };

  self.cancel = function() {
    $mdDialog.cancel();
  };

}]);

// To create a new message when a student clicks "Send Message"
// 	- Send a `POST` request to `/message/new-message`
// 		- Must send token to be decoded
// 		- Must send a `message` object on data following this template:
// 			message {
// 				mentorEmail: 'mentor's email address',
// 				subject: 'subject text',
// 				body: 'body text',
// 				studentName: 'optional student name'
// 			}
<commit_msg>Connect message controller to BioFactory<commit_after>app.controller('MessageController', ['$http', 'AuthFactory', '$mdDialog', 'BioFactory', function($http, AuthFactory, $mdDialog, BioFactory) {
  console.log('MessageController running');
  var self = this;
  self.newMessage = [];
  var authInfo = AuthFactory.auth;
  var userStatus = AuthFactory.userStatus;
  // var messageInfo =

  // console.log(InboxController.selectedMessage);

  self.userStatus = AuthFactory.userStatus;

  self.mentor = BioFactory.mentorBio.info;

  self.sendMessage = function(message){
    console.log('newMessage: ', self.newMessage);
    console.log('authInfo: ', authInfo);
    console.log('userStatus: ', userStatus);
    console.log('self.mentor: ', self.mentor);
    // $http.post('/message/new-message', self.newMessage);
    //   .then(function(response) {
    //     console.log('response: ', response);
    //   });
  // };

  };

  self.cancel = function() {
    $mdDialog.cancel();
  };

}]);

// To create a new message when a student clicks "Send Message"
// 	- Send a `POST` request to `/message/new-message`
// 		- Must send token to be decoded
// 		- Must send a `message` object on data following this template:
// 			message {
// 				mentorEmail: 'mentor's email address',
// 				subject: 'subject text',
// 				body: 'body text',
// 				studentName: 'optional student name'
// 			}
<|endoftext|>


<commit_before>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

 /*  $("#buttonemail").click(function(e){

     var pdf = new jsPDF('p', 'pt', 'a4', false);

           alert("courte");
alert(duration_courte);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

*/

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

   //  pdf.output("dataurlnewwindow");

    //  });*/

  });

function demoFromHTML() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);

    var logo = new Image();

  //  alert(localStorage.duree);

          if(localStorage.duree == "longue_adult"){

    //        if(adult){
      //        alert("adulto " + localStorage.duree);
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }
            else if(localStorage.duree == 'longue_enfant'){
      //      }else{
            //     alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
        //    }

      }
      else if(localStorage.duree == 'courte_enfant'){

        //    if(enfant){

                //alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

          }
          else {
            //  alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

        //    }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

        }
<commit_msg>Update dynamic_carousel.js<commit_after>

 var duration_longue = true;
  var  duration_courte = false;
  var  enfant = false;
   var adult = true;
   var duree = "longue";

  $(document).ready(function(){
  //on initialise les variables avec les valeurs par défaut

    var pub = "adu";
    var nbDePersonnes = 16;
    var sce = 1;

  //  localStorage.duree = 'longue_adult';

  //on appuie les boutons en conséquence
    $("#dur_lon").addClass("active");
    $("#pub_adu").addClass("active");
    $("#sce_1").addClass("active");
    //$("#car").load('carousel_long.html');

    //On remplit le champ du bouton +/- avec la valeur par défaut
    $("#inputnb").val(nbDePersonnes);

   localStorage.duree = 'longue_adult';
    //var carousel_c = $.get("carousel_court.html");
    //var carousel_l = $.get("carousel_long.html");
  //On change la valeur des variables en fonction des actions utilisateurs
  //Pour la durée :
    $("#dur_cou").click(function(e){

  //    localStorage.duree = 'courte';

      duree = "courte";
      duration_courte = true;
      duration_longue = false;
      $("#dur_lon").removeClass("active");
      $("#dur_cou").addClass("active");
      //var code = load("carousel_court.html");
      //$("#myCarousel").replaceWith("
 This text is strong
  This text is italic
");
      //alert(carousel_c);
      //$("#car").empty();
      $("#car").load('carousel_court.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier court !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();});

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";

    });
    $("#dur_lon").click(function(e){

    //  localStorage.duree = 'longue';

      duree = "longue";
      duration_longue = true;
      duration_courte = false;
      $("#dur_cou").removeClass("active");
      $("#dur_lon").addClass("active");
      //$("#myCarousel").replaceWith(carousel_l);
      //$("#car").empty();
      $("#car").load('carousel_long.html');
      $("#p1").show();
      alert("Chargement terminé \n Guide pour atelier long !");
      $("#rest").hide();
      $("#plusbtn, #minubtn").click(function(){$("#rest").show();})

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le public :
    $("#pub_enf").click(function(e){

      localStorage.type = 'enfant';

      pub = "enf";
      adult = false;
      enfant = true;
      $("#pub_adu").removeClass("active");
      $("#pub_enf").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
    $("#pub_adu").click(function(e){

      localStorage.type = 'adult';

      pub = "adu";
      adult = true;
      enfant = false;
      $("#pub_enf").removeClass("active");
      $("#pub_adu").addClass("active");

      if (duree == "longue" && enfant) localStorage.duree = "longue_enfant";
      else if (duree == "courte" && adult) localStorage.duree = "courte_adult";
      else if (duree == "courte" && enfant) localStorage.duree = "courte_enfant";
      else  localStorage.duree = "longue_adult";
    });
  //Pour le scénario :
    $("#sce_2").click(function(e){
      sce = 2;
      $("#sce_1").removeClass("active");
      $("#sce_2").addClass("active");
    });
    $("#sce_1").click(function(e){
      sce = 1;
      $("#sce_2").removeClass("active");
      $("#sce_1").addClass("active");
    });

    $("#pointLien").click(function(e){
      if(pub == "enf"){
        $("#pointLien").attr('href','graphiques_enfants.html');
      }else{
        $("#pointLien").attr('href','graphiques_adultes.html');
      }
    });

 /*  $("#buttonemail").click(function(e){

     var pdf = new jsPDF('p', 'pt', 'a4', false);

           alert("courte");
alert(duration_courte);

          if(duration_longue){

            if(adult){
              alert("adult_long");
              var logo = new Image();
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }else{
                 alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }

          }else{
            if(enfant){
                 alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

            }else {
              alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

            }

           var uno= 1;
          }

*/

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

   //  pdf.output("dataurlnewwindow");

    //  });*/

  });

function demoFromHTML() {

     var pdf = new jsPDF('p', 'pt', 'a4', false);

  //   alert(localStorage.duree);

    var logo = new Image();

  //  alert(localStorage.duree);

          if(localStorage.duree == "longue_adult"){

    //        if(adult){
      //        alert("adulto " + localStorage.duree);
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_adults/long_adults_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
            }
            else if(localStorage.duree == 'longue_enfant'){
      //      }else{
            //     alert("enfant_LONGUE");
              logo.src = "https://vizkit.github.io/pdf_images/long/Long_enfants/long_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();
        //    }

      }
      else if(localStorage.duree == 'courte_enfant'){

        //    if(enfant){

                //alert("enfant_Court");
                logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
                pdf.addImage(logo, 'PNG', 2, 2, 590,850);
                pdf.addPage();

          }
          else {
            //  alert("adult_court");
              logo.src = "https://vizkit.github.io/pdf_images/court/Court_enfants/court_enfants_dataset1_1.PNG";
              pdf.addImage(logo, 'PNG', 2, 2, 590,850);
              pdf.addPage();

        //    }

           var uno= 1;
          }

       /*   var paso;
        for (paso = 4; paso < 6; paso++) {
            pdf.addPage();
            var logo = new Image();
            logo.src = paso+".png";
            pdf.addImage(logo, 'PNG', 2, 2, 590,850);
          // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.

          };*/

     pdf.output("dataurlnewwindow");

        }
<|endoftext|>


<commit_before>/**
 * Created by anauriarte on 6/23/15.
 */

//Function to validate if a field or select is null or empty
function isNull(field){
    if (field == '' || field == null) {
        return false;
    }
    else {
        return true;
    }
}

//Function to validate if a field has only number without decimals
function isNumberInteger(field){
    if(field.match(/^[1-9]\d*$/)){
        return true;
    }
    else{
        return false;
    }
}

//Function to validate if a field has only numbers with or without decimals
function isNumberDecimal(field){
    if(field.match(/^[1-9]\d*(\.\d+)?$/)){
        return true;
    }else{
        return false;
    }
}

//Function that receives a json and connects to the backend

function jsonAjax(json){
    console.log("Entra a funcion");
    console.log(json);
    console.log(JSON.stringify(json));

    $.ajax({
        url : "create_account/", // the endpoint
        type : "POST", // http method
        data : json, // data sent with the post request

        // handle a successful response
        success : function(json) {

            console.log(json); // log the returned json to the console
            console.log("success"); // another sanity check
            $('#modalAddAccount').modal('hide');
            $('#modalAddAccount').find('#inputAmount').val('');
            $('#modalAddAccount').find('#inputAccountNo').val('');
            $('#modalAddAccount').find('#inputBank').val('');
            //$('#modalAddAccount').find("input[type=radio]").prop("checked", "radioBank");
            //$('#bankTxtField').css("display", "block");
            //$('#accountNoTxtField').css("display", "block");

        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {

            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
            alert("Error saving the account, can't reach the server. Please try again or contact the system manager.");

            $('#modalAddAccount').modal('hide');
            $('#modalAddAccount').find('#inputAmount').val('');
            $('#modalAddAccount').find('#inputAccountNo').val('');
            $('#modalAddAccount').find('#inputBank').val('');
            /*$('#modalAddAccount').find("input,select").val('').end();
            $('#modalAddAccount').find("input[type=radio]").prop("checked", "radioBank");
            $('#bankTxtField').css("display", "block");
            $('#accountNoTxtField').css("display", "block");*/

        }
    });

    return true;
}

//Function to SAVE info from the New Account modal
$(document).on('click', '#modal_save' ,function (){

    //Validate account type
    var accountType = $('input[name=accountTypeRadio]:checked', '#addAccountForm').val();

    console.log("Despues accountType");
    console.log(accountType);

    //Get data
    if(accountType == "c"){

        console.log("EN SAVE CCCC");

        var currency = $('#currencySelect').val();
        var amount= $('#inputAmount').val();

        //Validations
        if(isNull(currency)==false){
            console.log("in currency");
            alert("You need to select a currency");
            return;
        }
        if(isNull(amount)==false){
            console.log("in amount");
            alert("The field Amount cannot be empty");
            return;
        }
        if(isNumberDecimal(amount)==false){
            console.log("in number");
            alert("The amount must be a number");
            return;
        }

        //Connection to backend
        var accountData = {"account_type": accountType, "balance":amount, "currency":currency};
        /*if(jsonAjax(accountData)==false){
         alert("Error saving the account, can't reach the server. Please try again or contact the system manager.");
         return false;
         }*/
        jsonAjax(accountData);
    }
    if(accountType == "b"){
        var currency = $('#currencySelect').val();
        var bank= $('#inputBank').val();
        var account= $('#inputAccountNo').val();
        var amount= $('#inputAmount').val();

        //Validations
        if(isNull(currency)==false){
            alert("You need to select a currency");

            return;
        }
        if(isNull(bank)==false){
            alert("The field Bank cannot be empty");
            return;
        }
        if(isNull(account)==false){
            alert("The field Account cannot be empty");
            return;
        }
        if(isNull(amount)==false){
            alert("The field amount cannot be empty");
            return;
        }
        if(isNumberInteger(account)==false){
            alert("The Account # must be a number without decimals");
            return;
        }
        if(isNumberDecimal(amount)==false){
            alert("The Amount must be a number");
            return;
        }

        console.log("DESPUES DE C Y B");

        //Connection to backend
        var accountData={"account_type":accountType, "bank_name":bank, "number":account, "balance":amount, "currency":currency};

        jsonAjax(accountData)

    }

    /*//Close modal and clear fields
     $('#modalAddAccount').modal('hide');
     $('#modalAddAccount').find("input,select").val('').end();
     $('#modalAddAccount').find("input[type=radio]").prop("checked", "radioBank");
     $('#bankTxtField').css("display", "block");
     $('#accountNoTxtField').css("display", "block");*/

});

function getJson(){
    //var prueba='{"account_type":"b", "bank_name":"Santander", "number":"123456", "balance":"500.00", "currency":"Pesos"}';
    var prueba='{"account_type":"c", "balance":"1000.00", "currency":"Pounds"}';
    return prueba;
    //return null;
}

//Function to EDIT account info
function editAccount(){

    //Get json from backend
    var json=getJson();

    //Validate
    if(json==null){
        alert("Error. Can't reach the server.");
        return false;
    }
    else{
        var data = JSON.parse(json);
        var accountType = data.account_type;

        // Get data
        if(accountType == "b") {

            var bank = data.bank_name;
            var accountNo = data.number;
            var amount = data.balance;
            var currency = data.currency;

            //Fill fields
            $("#radioBankEdit").prop('checked', true);
            $("#currencySelectEdit").val(currency);
            $("#inputBankEdit").val(bank);
            $("#inputAccountNoEdit").val(accountNo);
            $("#inputAmountEdit").val(amount);
            $('#bankTxtFieldEdit').css("display", "block");
            $('#accountNoTxtFieldEdit').css("display", "block");

        }
        if(accountType == "c"){
            var amount = data.balance;
            var currency = data.currency;

            //Fill fields
            $("#radioCashEdit").prop('checked', true);
            $("#currencySelectEdit").val(currency);
            $("#inputAmountEdit").val(amount);
            $('#bankTxtFieldEdit').css("display", "none");
            $('#accountNoTxtFieldEdit').css("display", "none");
        }

    }
}

//Function to hide additional fields when the account type is cash
function cashSelectAddAccount(){
    $('#bankTxtField').css("display", "none");
    $('#accountNoTxtField').css("display", "none");
}

//Function to display additional fields when the account type is bank
function bankSelectAddAccount(){
    $('#bankTxtField').css("display", "block");
    $('#accountNoTxtField').css("display", "block");
}

function cashSelectEditAccount(){
    $('#bankTxtFieldEdit').css("display", "none");
    $('#accountNoTxtFieldEdit').css("display", "none");
}

//Function to display additional fields when the account type is bank
function bankSelectEditAccount(){
    $('#bankTxtFieldEdit').css("display", "block");
    $('#accountNoTxtFieldEdit').css("display", "block");
}

function deleteBtnOver(){
    $('#deleteBtnEdit').css("background", "#C61212");
    $('#deleteBtnEdit').css("color", "#ffffff");
}

function deleteBtnOut(){
    $('#deleteBtnEdit').css("background", "#ffffff");
    $('#deleteBtnEdit').css("color", "#C61212");
}
<commit_msg>Better Handling of Json Response<commit_after>/**
 * Created by anauriarte on 6/23/15.
 */

//Function to validate if a field or select is null or empty
function isNull(field){
    if (field == '' || field == null) {
        return false;
    }
    else {
        return true;
    }
}

//Function to validate if a field has only number without decimals
function isNumberInteger(field){
    if(field.match(/^[1-9]\d*$/)){
        return true;
    }
    else{
        return false;
    }
}

//Function to validate if a field has only numbers with or without decimals
function isNumberDecimal(field){
    if(field.match(/^[1-9]\d*(\.\d+)?$/)){
        return true;
    }else{
        return false;
    }
}

//Function that receives a json and connects to the backend

function jsonAjax(lejson){
    console.log("Entra a funcion");
    console.log(lejson);
    console.log(JSON.stringify(lejson));

    $.ajax({
        url : "create_account/", // the endpoint
        type : "POST", // http method
        data : lejson, // data sent with the post request
        dataType: 'json',

        // handle a successful response
        success : function(jsonResponse) {

            console.log(jsonResponse); // log the returned json to the console
            console.log("success"); // another sanity check

            $('#modalAddAccount').modal('hide');
            $('#modalAddAccount').find('#inputAmount').val('');
            $('#modalAddAccount').find('#inputAccountNo').val('');
            $('#modalAddAccount').find('#inputBank').val('');

            if(lejson.account_type == 'c'){
                console.log('Cambiar la tabla de Cash');
            }
            else {
                console.log('Cambiar la tabla de Bank');
            }

        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {

            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
            alert("Error saving the account, can't reach the server. Please try again or contact the system manager.");

            $('#modalAddAccount').modal('hide');
            $('#modalAddAccount').find('#inputAmount').val('');
            $('#modalAddAccount').find('#inputAccountNo').val('');
            $('#modalAddAccount').find('#inputBank').val('');
            /*$('#modalAddAccount').find("input,select").val('').end();
            $('#modalAddAccount').find("input[type=radio]").prop("checked", "radioBank");
            $('#bankTxtField').css("display", "block");
            $('#accountNoTxtField').css("display", "block");*/

        }
    });

    return true;
}

//Function to SAVE info from the New Account modal
$(document).on('click', '#modal_save' ,function (){

    //Validate account type
    var accountType = $('input[name=accountTypeRadio]:checked', '#addAccountForm').val();

    console.log("Despues accountType");
    console.log(accountType);

    //Get data
    if(accountType == "c"){

        console.log("EN SAVE CCCC");

        var currency = $('#currencySelect').val();
        var amount= $('#inputAmount').val();

        //Validations
        if(isNull(currency)==false){
            console.log("in currency");
            alert("You need to select a currency");
            return;
        }
        if(isNull(amount)==false){
            console.log("in amount");
            alert("The field Amount cannot be empty");
            return;
        }
        if(isNumberDecimal(amount)==false){
            console.log("in number");
            alert("The amount must be a number");
            return;
        }

        //Connection to backend
        var accountData = {"account_type": accountType, "balance":amount, "currency":currency};
        /*if(jsonAjax(accountData)==false){
         alert("Error saving the account, can't reach the server. Please try again or contact the system manager.");
         return false;
         }*/
        jsonAjax(accountData);
    }
    if(accountType == "b"){
        var currency = $('#currencySelect').val();
        var bank= $('#inputBank').val();
        var account= $('#inputAccountNo').val();
        var amount= $('#inputAmount').val();

        //Validations
        if(isNull(currency)==false){
            alert("You need to select a currency");

            return;
        }
        if(isNull(bank)==false){
            alert("The field Bank cannot be empty");
            return;
        }
        if(isNull(account)==false){
            alert("The field Account cannot be empty");
            return;
        }
        if(isNull(amount)==false){
            alert("The field amount cannot be empty");
            return;
        }
        if(isNumberInteger(account)==false){
            alert("The Account # must be a number without decimals");
            return;
        }
        if(isNumberDecimal(amount)==false){
            alert("The Amount must be a number");
            return;
        }

        //Connection to backend
        var accountData={"account_type":accountType, "bank_name":bank, "number":account, "balance":amount, "currency":currency};

        jsonAjax(accountData)

    }

});

function getJson(){
    //var prueba='{"account_type":"b", "bank_name":"Santander", "number":"123456", "balance":"500.00", "currency":"Pesos"}';
    var prueba='{"account_type":"c", "balance":"1000.00", "currency":"Pounds"}';
    return prueba;
    //return null;
}

//Function to EDIT account info
function editAccount(){

    //Get json from backend
    var json=getJson();

    //Validate
    if(json==null){
        alert("Error. Can't reach the server.");
        return false;
    }
    else{
        var data = JSON.parse(json);
        var accountType = data.account_type;

        // Get data
        if(accountType == "b") {

            var bank = data.bank_name;
            var accountNo = data.number;
            var amount = data.balance;
            var currency = data.currency;

            //Fill fields
            $("#radioBankEdit").prop('checked', true);
            $("#currencySelectEdit").val(currency);
            $("#inputBankEdit").val(bank);
            $("#inputAccountNoEdit").val(accountNo);
            $("#inputAmountEdit").val(amount);
            $('#bankTxtFieldEdit').css("display", "block");
            $('#accountNoTxtFieldEdit').css("display", "block");

        }
        if(accountType == "c"){
            var amount = data.balance;
            var currency = data.currency;

            //Fill fields
            $("#radioCashEdit").prop('checked', true);
            $("#currencySelectEdit").val(currency);
            $("#inputAmountEdit").val(amount);
            $('#bankTxtFieldEdit').css("display", "none");
            $('#accountNoTxtFieldEdit').css("display", "none");
        }

    }
}

//Function to hide additional fields when the account type is cash
function cashSelectAddAccount(){
    $('#bankTxtField').css("display", "none");
    $('#accountNoTxtField').css("display", "none");
}

//Function to display additional fields when the account type is bank
function bankSelectAddAccount(){
    $('#bankTxtField').css("display", "block");
    $('#accountNoTxtField').css("display", "block");
}

function cashSelectEditAccount(){
    $('#bankTxtFieldEdit').css("display", "none");
    $('#accountNoTxtFieldEdit').css("display", "none");
}

//Function to display additional fields when the account type is bank
function bankSelectEditAccount(){
    $('#bankTxtFieldEdit').css("display", "block");
    $('#accountNoTxtFieldEdit').css("display", "block");
}

function deleteBtnOver(){
    $('#deleteBtnEdit').css("background", "#C61212");
    $('#deleteBtnEdit').css("color", "#ffffff");
}

function deleteBtnOut(){
    $('#deleteBtnEdit').css("background", "#ffffff");
    $('#deleteBtnEdit').css("color", "#C61212");
}
<|endoftext|>


<commit_before>/*
 *  respimg-inspector - v0.1.0
 *  A javascript plugin to check responsive images in the browser.
 *
 *
 *  Made by Florent Bourgeois
 *  Under MIT License
 */
;( function( window, document, undefined ) {

	"use strict";

	var respImgInspector = {};

	var supports = !!document.querySelector &&
		!!window.addEventListener &&
		!!window.MutationObserver;

	var settings, wrapper, items = [], images = [], overlays = [];

	var defaults = {
		selectors: null,
		classNamespace: "respimg-inspector-",
		wrapperId: "respimg-inspector-wrapper"
	};

	var elementsToExclude = [
		"span", "em", "strong", "i", "b", "big", "small", "tt", "abbr",
		"script", "br", "hr", "sub", "sup", "button", "input", "label",
		"select", "textarea", "samp", "var"
	];

	var docBody = document.body;

	var forEach = function( collection, callback, scope ) {
		if ( Object.prototype.toString.call( collection ) === "[object Object]" ) {
			for ( var prop in collection ) {
				if ( Object.prototype.hasOwnProperty.call( collection, prop ) ) {
					callback.call( scope, collection[ prop ], prop, collection );
				}
			}
		} else {
			for ( var i = 0, len = collection.length; i < len; i++ ) {
				callback.call( scope, collection[ i ], i, collection );
			}
		}
	};

	var extend = function( defaults, options ) {
		var extended = {};
		var prop;
		for ( prop in defaults ) {
			if ( Object.prototype.hasOwnProperty.call( defaults, prop ) ) {
				extended[ prop ] = defaults[ prop ];
			}
		}
		for ( prop in options ) {
			if ( Object.prototype.hasOwnProperty.call( options, prop ) ) {
				extended[ prop ] = options[ prop ];
			}
		}
		return extended;
	};

	var throttle = function( type, name, scope ) {
		var obj = scope || window;
		var running = false;
		var func = function() {
			if ( running ) { return; }
			running = true;
			observer.disconnect();
			requestAnimationFrame( function() {
				obj.dispatchEvent ( new CustomEvent( name ) );
				running = false;
			} );
		};
		obj.addEventListener( type, func );
	};

	var getCss = function( element, property ) {
		return window.getComputedStyle( element, null ).getPropertyValue( property );
	};

	var observer = new MutationObserver( function( mutations ) {
		mutations.forEach( function() {
			update();
		} );
	} );

	var update = function() {
		cleanUp();
		var selectors = getSelectors();
		var respImgElements = document.querySelectorAll( selectors );
		forEach( respImgElements, function( respImgElement ) {
			var image = getImage( respImgElement );
			var item = {
				el: respImgElement,
				img: image
			};

			// TODO: Handle more background image usages.
			// Only handle IMG tag and background "cover" for now.
			if ( item.el.nodeName === "IMG" ||
				getCss( item.el, "background-size" ) === "cover"
			) {
				items.push( item );
				images.push( image );
			}
		} );
		window.imagesLoaded( images, function() {
			forEach( items, function( item ) {
				var data = extend( getElementData( item.el ), getImageData( item.img ) );
				overlays.push( getOverlay( data ) );
				observer.observe( item.el, {
					attributes: true
				} );
			} );
			renderWrapper();
			renderOverlays();
			observer.observe( docBody, {
				childList: true
			} );
		} );
	};

	var getSelectors = function() {
		if ( settings.selectors ) {
			return settings.selectors;
		} else {
			var array = elementsToExclude.map( function( element ) {
				return "*:not(" + element + ")";
			} );
			return array.join();
		}
	};

	var getElementData = function( element ) {
		var elRect = element.getBoundingClientRect();
		return {
			elTag: element.nodeName.toLowerCase(),
			elWidth: elRect.width,
			elHeight: elRect.height,
			elTop: elRect.top,
			elBottom: elRect.bottom,
			elLeft: elRect.left,
			elRight: elRect.right
		};
	};

	var getImageData = function( img ) {
		return {
			imgWidth: img.width,
			imgHeight: img.height,
			imgNaturalWidth: img.naturalWidth,
			imgNaturalHeight: img.naturalHeight,
			imgSizes: img.sizes
		};
	};

	var getImage = function( element ) {
		var image;
		if ( element.nodeName === "IMG" ) {
			image = element;
		} else if ( getCss( element, "background-image" ) !== "none" ) {
			var bgUrl = /^url\((['"]?)(.*)\1\)$/.exec( getCss( element, "background-image" ) );
			image = new Image();
			image.src = bgUrl[ 2 ];
		}
		return image;
	};

	var getOverlayClassName = function( data ) {
		var overlayClassName;
		var pixelRatio = window.devicePixelRatio;
		if ( data.elWidth * pixelRatio < data.imgNaturalWidth ||
			data.elHeight * pixelRatio < data.imgNaturalHeight
		) {
			overlayClassName = "warning";
		} else if ( data.elWidth * pixelRatio > data.imgNaturalWidth ||
			data.elHeight * pixelRatio > data.imgNaturalHeight
		) {
			overlayClassName = "bad";
		} else {
			overlayClassName = "good";
		}
		return settings.classNamespace + overlayClassName;
	};

	var getOverlay = function( data ) {
		var marginTop = getCss( docBody, "margin-top" );
		var marginLeft = getCss( docBody, "margin-left" );
		var bodyRect = docBody.getBoundingClientRect();
		var offsetTop = data.elTop - bodyRect.top;
		var offsetLeft = data.elLeft - bodyRect.left;
		var overlay = document.createElement( "div" );
		overlay.classList.add( settings.classNamespace + "overlay" );
		overlay.style.position = "absolute";
		overlay.style.width = data.elWidth + "px";
		overlay.style.height = data.elHeight + "px";
		overlay.style.top = "calc(" + offsetTop + "px + " + marginTop + ")";
		overlay.style.left =	"calc(" + offsetLeft + "px + " + marginLeft + ")";
		overlay.classList.add( getOverlayClassName( data ) );
		forEach( data, function( dataValue, dataKey ) {
			overlay.dataset[ dataKey ] = dataValue;
		} );
		return overlay;
	};

	var renderWrapper = function() {
		wrapper = document.createElement( "div" );
		wrapper.id = settings.wrapperId;
		wrapper.style.position = "absolute";
		wrapper.style.top = 0;
		wrapper.style.bottom = 0;
		wrapper.style.left = 0;
		wrapper.style.right = 0;
		wrapper.style.zIndex = 2147483647;
		docBody.appendChild( wrapper );
	};

	var renderOverlays = function() {
		forEach( overlays, function( overlay ) {
			wrapper.appendChild( overlay );
		} );
	};

	var cleanUp = function() {
		observer.disconnect();
		if ( overlays.length ) {
			forEach( overlays, function( overlay ) {
				overlay.remove();
			} );
		}
		if ( wrapper !== undefined ) {
			wrapper.remove();
		}
		items = [];
		images = [];
		overlays = [];
	};

	respImgInspector.init = function( options ) {
		if ( !supports ) { return; }
		settings = extend( defaults, options || {} );
		throttle( "resize", "optimizedResize" );
		window.addEventListener( "optimizedResize", update );
		window.addEventListener( "load", update );
	};

	if ( typeof define === "function" && define.amd ) {
		define( [], function() {
			return respImgInspector;
		} );
	} else if ( typeof module !== "undefined" && module.exports ) {
		module.exports = respImgInspector;
	} else {
		window.respImgInspector = respImgInspector;
	}

} )( window, document );
<commit_msg>Initial build<commit_after>/*
 *  respimg-inspector - v0.1.0
 *  A javascript plugin to check responsive images in the browser.
 *
 *
 *  Made by Florent Bourgeois
 *  Under MIT License
 */
;( function( window, document, undefined ) {

	"use strict";

	var respImgInspector = {};

	var supports = !!document.querySelector &&
		!!window.addEventListener &&
		!!window.MutationObserver;

	var settings, wrapper, items = [], images = [], overlays = [];

	var defaults = {
		selectors: null,
		classNamespace: "respimg-inspector-",
		wrapperId: "respimg-inspector-wrapper"
	};

	var elementsToExclude = [
		"span", "em", "strong", "i", "b", "big", "small", "tt", "abbr",
		"script", "br", "hr", "sub", "sup", "button", "input", "label",
		"select", "textarea", "samp", "var"
	];

	var docBody = document.body;

	var forEach = function( collection, callback, scope ) {
		if ( Object.prototype.toString.call( collection ) === "[object Object]" ) {
			for ( var prop in collection ) {
				if ( Object.prototype.hasOwnProperty.call( collection, prop ) ) {
					callback.call( scope, collection[ prop ], prop, collection );
				}
			}
		} else {
			for ( var i = 0, len = collection.length; i < len; i++ ) {
				callback.call( scope, collection[ i ], i, collection );
			}
		}
	};

	var extend = function( defaults, options ) {
		var extended = {};
		var prop;
		for ( prop in defaults ) {
			if ( Object.prototype.hasOwnProperty.call( defaults, prop ) ) {
				extended[ prop ] = defaults[ prop ];
			}
		}
		for ( prop in options ) {
			if ( Object.prototype.hasOwnProperty.call( options, prop ) ) {
				extended[ prop ] = options[ prop ];
			}
		}
		return extended;
	};

	var throttle = function( type, name, scope ) {
		var obj = scope || window;
		var running = false;
		var func = function() {
			if ( running ) { return; }
			running = true;
			observer.disconnect();
			requestAnimationFrame( function() {
				obj.dispatchEvent( new CustomEvent( name ) );
				running = false;
			} );
		};
		obj.addEventListener( type, func );
	};

	var getCss = function( element, property ) {
		return window.getComputedStyle( element, null ).getPropertyValue( property );
	};

	var observer = new MutationObserver( function( mutations ) {
		mutations.forEach( function() {
			update();
		} );
	} );

	var update = function() {
		cleanUp();
		var selectors = getSelectors();
		var respImgElements = document.querySelectorAll( selectors );
		forEach( respImgElements, function( respImgElement ) {
			var image = getImage( respImgElement );
			var item = {
				el: respImgElement,
				img: image
			};

			// TODO: Handle more background image usages.
			// Only handle IMG tag and background "cover" for now.
			if ( item.el.nodeName === "IMG" ||
				getCss( item.el, "background-size" ) === "cover"
			) {
				items.push( item );
				images.push( image );
			}
		} );
		window.imagesLoaded( images, function() {
			forEach( items, function( item ) {
				var data = extend( getElementData( item.el ), getImageData( item.img ) );
				overlays.push( getOverlay( data ) );
				observer.observe( item.el, {
					attributes: true
				} );
			} );
			renderWrapper();
			renderOverlays();
			observer.observe( docBody, {
				childList: true
			} );
		} );
	};

	var getSelectors = function() {
		if ( settings.selectors ) {
			return settings.selectors;
		} else {
			var array = elementsToExclude.map( function( element ) {
				return "*:not(" + element + ")";
			} );
			return array.join();
		}
	};

	var getElementData = function( element ) {
		var elRect = element.getBoundingClientRect();
		return {
			elTag: element.nodeName.toLowerCase(),
			elWidth: elRect.width,
			elHeight: elRect.height,
			elTop: elRect.top,
			elBottom: elRect.bottom,
			elLeft: elRect.left,
			elRight: elRect.right
		};
	};

	var getImageData = function( img ) {
		return {
			imgWidth: img.width,
			imgHeight: img.height,
			imgNaturalWidth: img.naturalWidth,
			imgNaturalHeight: img.naturalHeight,
			imgSizes: img.sizes
		};
	};

	var getImage = function( element ) {
		var image;
		if ( element.nodeName === "IMG" ) {
			image = element;
		} else if ( getCss( element, "background-image" ) !== "none" ) {
			var bgUrl = /^url\((['"]?)(.*)\1\)$/.exec( getCss( element, "background-image" ) );
			image = new Image();
			image.src = bgUrl[ 2 ];
		}
		return image;
	};

	var getOverlayClassName = function( data ) {
		var overlayClassName;
		var pixelRatio = window.devicePixelRatio;
		if ( data.elWidth * pixelRatio < data.imgNaturalWidth ||
			data.elHeight * pixelRatio < data.imgNaturalHeight
		) {
			overlayClassName = "warning";
		} else if ( data.elWidth * pixelRatio > data.imgNaturalWidth ||
			data.elHeight * pixelRatio > data.imgNaturalHeight
		) {
			overlayClassName = "bad";
		} else {
			overlayClassName = "good";
		}
		return settings.classNamespace + overlayClassName;
	};

	var getOverlay = function( data ) {
		var marginTop = getCss( docBody, "margin-top" );
		var marginLeft = getCss( docBody, "margin-left" );
		var bodyRect = docBody.getBoundingClientRect();
		var offsetTop = data.elTop - bodyRect.top;
		var offsetLeft = data.elLeft - bodyRect.left;
		var overlay = document.createElement( "div" );
		overlay.classList.add( settings.classNamespace + "overlay" );
		overlay.style.position = "absolute";
		overlay.style.width = data.elWidth + "px";
		overlay.style.height = data.elHeight + "px";
		overlay.style.top = "calc(" + offsetTop + "px + " + marginTop + ")";
		overlay.style.left =	"calc(" + offsetLeft + "px + " + marginLeft + ")";
		overlay.classList.add( getOverlayClassName( data ) );
		forEach( data, function( dataValue, dataKey ) {
			overlay.dataset[ dataKey ] = dataValue;
		} );
		return overlay;
	};

	var renderWrapper = function() {
		wrapper = document.createElement( "div" );
		wrapper.id = settings.wrapperId;
		wrapper.style.position = "absolute";
		wrapper.style.top = 0;
		wrapper.style.bottom = 0;
		wrapper.style.left = 0;
		wrapper.style.right = 0;
		wrapper.style.zIndex = 2147483647;
		docBody.appendChild( wrapper );
	};

	var renderOverlays = function() {
		forEach( overlays, function( overlay ) {
			wrapper.appendChild( overlay );
		} );
	};

	var cleanUp = function() {
		observer.disconnect();
		if ( overlays.length ) {
			forEach( overlays, function( overlay ) {
				overlay.remove();
			} );
		}
		if ( wrapper !== undefined ) {
			wrapper.remove();
		}
		items = [];
		images = [];
		overlays = [];
	};

	respImgInspector.init = function( options ) {
		if ( !supports ) { return; }
		settings = extend( defaults, options || {} );
		throttle( "resize", "optimizedResize" );
		window.addEventListener( "optimizedResize", update );
		window.addEventListener( "load", update );
	};

	if ( typeof define === "function" && define.amd ) {
		define( [], function() {
			return respImgInspector;
		} );
	} else if ( typeof module !== "undefined" && module.exports ) {
		module.exports = respImgInspector;
	} else {
		window.respImgInspector = respImgInspector;
	}

} )( window, document );
<|endoftext|>