rename blackcherry -> tweetbook; package demos as zips; rename intro -> adm101
diff --git a/asterix-examples/src/main/resources/tweetbook-demo/static/js/asterix-sdk-stable.js b/asterix-examples/src/main/resources/tweetbook-demo/static/js/asterix-sdk-stable.js
new file mode 100755
index 0000000..3e5aa8d
--- /dev/null
+++ b/asterix-examples/src/main/resources/tweetbook-demo/static/js/asterix-sdk-stable.js
@@ -0,0 +1,1045 @@
+/**
+* Asterix SDK - Beta Version
+* @author Eugenia Gabrielov <genia.likes.science@gmail.com>
+* 
+* This is a Javascript helper file for generating AQL queries for AsterixDB (https://code.google.com/p/asterixdb/) 
+*/
+
+/**
+* AsterixDBConnection
+* 
+* This is a handler for connections to a local AsterixDB REST API Endpoint. 
+* This initialization takes as input a configuraiton object, and initializes
+* same basic functionality. 
+*/
+function AsterixDBConnection(configuration) {
+    // Initialize AsterixDBConnection properties
+    this._properties = {};
+    
+    // Set dataverse as null for now, this needs to be set by the user.
+    this._properties["dataverse"] = "";
+    
+    // By default, we will wait for calls to the REST API to complete. The query method
+    // sends a different setting when executed asynchronously. Calls that do not specify a mode
+    // will be executed synchronously.
+    this._properties["mode"] = "synchronous";
+    
+    // These are the default error behaviors for Asterix and ajax errors, respectively. 
+    // They can be overridden by calling initializing your AsterixDBConnection like so:
+    // adb = new AsterixDBConnection({
+    //                                  "error" : function(data) {
+    //                                              // override here...
+    //                                  });
+    // and similarly for ajax_error, just pass in the configuration as a json object.
+    this._properties["error"] = function(data) {
+        alert("Asterix REST API Error:\n" + data["error-code"][0] + "\n" + data["error-code"][1]);
+    };
+    
+    this._properties["ajax_error"] = function(message) {
+        alert("[Ajax Error]\n" + message);
+    };
+
+    // This is the default path to the local Asterix REST API. Can be overwritten for remote configurations
+    // or for demo setup purposes (such as with a proxy handler with Python or PHP.
+    this._properties["endpoint_root"] = "http://localhost:19002/";
+    
+    // If we have passed in a configuration, we will update the internal properties
+    // using that configuration. You can do things such as include a new endpoint_root,
+    // a new error function, a new dataverse, etc. You can even store extra info.
+    //
+    // NOTE Long-term, this should have more strict limits.
+    var configuration = configuration || {};
+
+    for (var key in configuration) {
+        this._properties[key] = configuration[key];
+    }
+    
+    return this;
+}
+
+
+/**
+* dataverse
+*
+* Sets dataverse for execution for the AsterixDBConnection.
+*/
+AsterixDBConnection.prototype.dataverse = function(dataverseName) {
+    this._properties["dataverse"] = dataverseName;
+    
+    return this;
+};
+
+
+/**
+* query (http://asterix.ics.uci.edu/documentation/api.html#QueryApi)
+* 
+* @param statements, statements of an AQL query
+* @param successFn, a function to execute if this query is run successfully
+* @param mode, a string either "synchronous" or "asynchronous", depending on preferred
+*               execution mode. 
+*/
+AsterixDBConnection.prototype.query = function(statements, successFn, mode) {
+ 
+    if ( typeof statements === 'string') {
+        statements = [ statements ];
+    }
+    
+    var m = typeof mode ? mode : "synchronous";
+    
+    // DEBUG
+    //alert(statements.join("\n"));
+     
+    var query = "use dataverse " + this._properties["dataverse"] + ";\n" + statements.join("\n");
+    
+    this._api(
+        {
+            "query" : query,
+            "mode"  : m
+        },
+        successFn, 
+        "query"
+    );
+
+    return this;
+};
+
+/**
+* query_status (http://asterix.ics.uci.edu/documentation/api.html#QueryStatusApi)
+* 
+* @param handle, a json object of the form {"handle" : handleObject}, where
+*                   the handle object is an opaque handle previously returned
+*                   from an asynchronous call.
+* @param successFn, a function to call on successful execution of this API call.
+*/
+AsterixDBConnection.prototype.query_status = function(handle, successFn) {
+    this._api(
+        handle,
+        successFn,
+        "query/status"
+    );
+
+    return this;
+};
+
+
+/**
+* query_result (http://asterix.ics.uci.edu/documentation/api.html#AsynchronousResultApi)
+* 
+* handle, a json object of the form {"handle" : handleObject}, where
+*           the handle object is an opaque handle previously returned
+*           from an asynchronous call.
+* successFn, a function to call on successful execution of this API call.
+*/
+AsterixDBConnection.prototype.query_result = function(handle, successFn) {
+    this._api(
+        handle,
+        successFn,
+        "query/result"
+    ); 
+
+    return this;
+};
+
+
+/**
+* ddl (http://asterix.ics.uci.edu/documentation/api.html#DdlApi)
+* 
+* @param statements, statements to run through ddl api
+* @param successFn, a function to execute if they are successful
+*/
+AsterixDBConnection.prototype.ddl = function(statements, successFn) {
+    if ( typeof statements === 'string') {
+        statements = [ statements ];
+    }
+    
+    this._api(
+        {
+            "ddl" :  "use dataverse " + this._properties["dataverse"] + ";\n" + statements.join("\n")
+        },
+        successFn,
+        "ddl"
+    );
+}
+
+
+/**
+* update (http://asterix.ics.uci.edu/documentation/api.html#UpdateApi)
+*
+* @param statements, statement(s) for an update API call
+* @param successFn, a function to run if this is executed successfully.
+* 
+* This is an AsterixDBConnection handler for the update API. It passes statements provided
+* to the internal API endpoint handler.
+*/
+AsterixDBConnection.prototype.update = function(statements, successFn) {
+    if ( typeof statements === 'string') {
+        statements = [ statements ];
+    }
+    
+    // DEBUG
+    // alert(statements.join("\n"));
+    
+    this._api(
+        {
+            "statements" : "use dataverse " + this._properties["dataverse"] + ";\n" + statements.join("\n")
+        },
+        successFn,
+        "update"
+    );
+}
+
+
+/**
+* meta
+* @param statements, a string or a list of strings representing an Asterix query object
+* @param successFn, a function to execute if call succeeds
+*
+* Queries without a dataverse. This is a work-around for an Asterix REST API behavior
+* that sometiems throws an error. This is handy for Asterix Metadata queries.
+*/
+AsterixDBConnection.prototype.meta = function(statements, successFn) {
+
+    if ( typeof statements === 'string') {
+        statements = [ statements ];
+    }
+    
+    var query = statements.join("\n");
+    
+    this._api(
+        {
+            "query" : query,
+            "mode"  : "synchronous"
+        },
+        successFn, 
+        "query"
+    );
+
+    return this;
+}
+
+
+/**
+* _api
+*
+* @param json, the data to be passed with the request
+* @param onSuccess, the success function to be run if this succeeds
+* @param endpoint, a string representing one of the Asterix API endpoints 
+* 
+* Documentation of endpoints is here:
+* http://asterix.ics.uci.edu/documentation/api.html
+*
+* This is treated as an internal method for making the actual call to the API.
+*/
+AsterixDBConnection.prototype._api = function(json, onSuccess, endpoint) {
+
+    // The success function is called if the response is successful and returns data,
+    // or is just OK.
+    var success_fn = onSuccess;
+    
+    // This is the error function. Called if something breaks either on the Asterix side
+    // or in the Ajax call.
+    var error_fn = this._properties["error"];
+    var ajax_error_fn = this._properties["ajax_error"];
+    
+    // This is the target endpoint from the REST api, called as a string.
+    var endpoint_url = this._properties["endpoint_root"] + endpoint;    
+
+    // This SDK does not rely on jQuery, but utilizes its Ajax capabilities when present.
+    if (window.jQuery) {
+        $.ajax({
+        
+            // The Asterix API does not accept post requests.
+            type        : 'GET',
+            
+            // This is the endpoint url provided by combining the default
+            // or reconfigured endpoint root along with the appropriate api endpoint
+            // such as "query" or "update".
+            url         : endpoint_url,
+            
+            // This is the data in the format specified on the API documentation.
+            data        : json,
+            
+            // We send out the json datatype to make sure our data is parsed correctly. 
+            dataType    : "json",
+            
+            // The success option calls a function on success, which in this case means
+            // something was returned from the API. However, this does not mean the call succeeded
+            // on the REST API side, it just means we got something back. This also contains the
+            // error return codes, which need to be handled before we call th success function.
+            success     : function(data) {
+
+                // Check Asterix Response for errors
+                // See http://asterix.ics.uci.edu/documentation/api.html#ErrorCodes
+                if (data["error-code"]) { 
+                    error_fn(data);
+                    
+                // Otherwise, run our provided success function
+                } else {
+                    success_fn(data);
+                }
+            },
+            
+            // This is the function that gets called if there is an ajax-related (non-Asterix)
+            // error. Network errors, empty response bodies, syntax errors, and a number of others
+            // can pop up. 
+            error       : function(data) {
+
+                // Some of the Asterix API endpoints return empty responses on success.
+                // However, the ajax function treats these as errors while reporting a
+                // 200 OK code with no payload. So we will check for that, otherwise 
+                // alert of an error. An example response is as follows:
+                // {"readyState":4,"responseText":"","status":200,"statusText":"OK"}
+                if (data["status"] == 200 && data["responseText"] == "") {
+                    success_fn(data);
+                } else {
+                    alert("[Ajax Error]\n" + JSON.stringify(data));
+                }
+            }
+        });
+        
+    } else {
+    
+        // NOTE: This section is in progress; currently API requires jQuery.
+    
+        // First, we encode the parameters of the query to create a new url.
+        api_endpoint = endpoint_url + "?" + Object.keys(json).map(function(k) {
+            return encodeURIComponent(k) + '=' + encodeURIComponent(json[k])
+        }).join('&');
+       
+        // Now, create an XMLHttp object to carry our request. We will call the
+        // UI callback function on ready.
+        var xmlhttp;
+        xmlhttp = new XMLHttpRequest();
+        xmlhttp.open("GET", endpoint_url, true);
+        xmlhttp.send(null);
+        
+        xmlhttp.onreadystatechange = function(){
+            if (xmlhttp.readyState == 4) {
+                if (xmlhttp.status === 200) {
+                    alert(xmlhttp.responseText);
+                    //success.call(null, xmlHttp.responseText);
+                } else {
+                    //error.call(null, xmlHttp.responseText);
+                }
+            } else {
+                // Still processing
+            }
+        };
+    }
+    return this;
+};
+
+// Asterix Expressions - Base
+function AExpression () {
+
+    this._properties = {};
+    this._success = function() {};
+
+    if (arguments.length == 1) {
+        this._properties["value"] = arguments[0];    
+    }
+
+    return this;
+}
+
+
+AExpression.prototype.bind = function(options) {
+    var options = options || {};
+
+    if (options.hasOwnProperty("success")) {
+        this._success = options["success"];
+    }
+
+    if (options.hasOwnProperty("return")) {
+        this._properties["return"] = " return " + options["return"].val();
+    }
+};
+
+
+AExpression.prototype.run = function(successFn) {
+    return this;
+};
+
+
+AExpression.prototype.val = function() { 
+
+    var value = "";
+
+    // If there is a dataverse defined, provide it.
+    if (this._properties.hasOwnProperty("dataverse")) {
+        value += "use dataverse " + this._properties["dataverse"] + ";\n";
+    };
+
+    if (this._properties.hasOwnProperty("value")) {
+        value += this._properties["value"].toString();
+    }
+
+    return value;
+};
+
+
+// @param expressionValue [String]
+AExpression.prototype.set = function(expressionValue) {
+    this._properties["value"] = expressionValue; 
+    return this;
+};
+
+
+// AQL Statements
+// SingleStatement ::= DataverseDeclaration
+//                  | FunctionDeclaration
+//                  | CreateStatement
+//                  | DropStatement
+//                  | LoadStatement
+//                  | SetStatement
+//                  | InsertStatement
+//                  | DeleteStatement
+//                  | Query
+function InsertStatement(quantifiedName, query) {
+    AExpression.call(this);
+    
+    var innerQuery = "";
+    if (query instanceof AExpression) {
+        innerQuery = query.val();
+    } else if (typeof query == "object" && Object.getPrototypeOf( query ) === Object.prototype ) {
+        
+        var insertStatements = [];
+        for (querykey in query) {
+            if (query[querykey] instanceof AExpression) {
+                insertStatements.push('"' + querykey + '" : ' + query[querykey].val());
+            } else if (typeof query[querykey] == "string") {
+                insertStatements.push('"' + querykey + '" : ' + query[querykey]);
+            } else {
+                insertStatements.push('"' + querykey + '" : ' + query[querykey].toString());
+            }
+        }
+        
+        innerQuery = "{" + insertStatements.join(', ') + "}";
+    }
+    
+    var statement = "insert into dataset " + quantifiedName + "(" + innerQuery + ");";
+    
+    AExpression.prototype.set.call(this, statement);
+
+    return this;
+}
+
+InsertStatement.prototype = Object.create(AExpression.prototype);
+InsertStatement.prototype.constructor = InsertStatement;
+
+
+// Delete Statement
+// DeleteStatement ::= "delete" Variable "from" "dataset" QualifiedName ( "where" Expression )?
+function DeleteStatement (variable, quantifiedName, whereExpression) {
+    AExpression.call(this);
+    
+    var statement = "delete " + variable + " from dataset " + quantifiedName;
+    
+    if (whereExpression instanceof AExpression) {
+        statement += " where " + whereExpression.val();
+    }
+    
+    AExpression.prototype.set.call(this, statement);
+    
+    return this;
+}
+
+DeleteStatement.prototype = Object.create(AExpression.prototype);
+DeleteStatement.prototype.constructor = DeleteStatement;
+
+// SetStatement
+//
+// Grammar
+// "set" Identifier StringLiteral
+function SetStatement (identifier, stringLiteral) {
+    AExpression.call(this);
+
+    var statement = "set " + identifier + ' "' + stringLiteral + '";';
+
+    AExpression.prototype.set.call(this, statement);
+
+    return this;
+}
+
+SetStatement.prototype = Object.create(AExpression.prototype);
+SetStatement.prototype.constructor = SetStatement;
+
+
+// Other Expressions
+
+// FunctionExpression
+// Parent: AsterixExpression
+// 
+// @param   options [Various], 
+// @key     function [String], a function to be applid to the expression
+// @key     expression [AsterixExpression or AQLClause] an AsterixExpression/Clause to which the fn will be applied
+function FunctionExpression() {
+    
+    // Initialize superclass
+    AExpression.call(this);
+    
+    this._properties["function"] = "";
+    this._properties["expressions"] = [];
+
+    // Check for fn/expression input
+    if (arguments.length >= 2 && typeof arguments[0] == "string") {
+        
+        this._properties["function"] = arguments[0];
+
+        for (i = 1; i < arguments.length; i++) {
+            if (arguments[i] instanceof AExpression || arguments[i] instanceof AQLClause) {
+                this._properties["expressions"].push(arguments[i]);
+            } else {
+                this._properties["expressions"].push(new AExpression(arguments[i]));
+            }
+        }
+    } 
+
+    // Return FunctionCallExpression object
+    return this;
+}
+
+
+FunctionExpression.prototype = Object.create(AExpression.prototype);
+FunctionExpression.prototype.constructor = FunctionExpression;
+   
+
+FunctionExpression.prototype.val = function () {
+    var fn_args = [];
+    for (var i = 0; i < this._properties["expressions"].length; i++) {
+        fn_args.push(this._properties["expressions"][i].val());
+    }
+
+    return this._properties["function"] + "(" + fn_args.join(", ") + ")";
+};
+
+
+// FLWOGRExpression
+//
+// FLWOGRExpression ::= ( ForClause | LetClause ) ( Clause )* "return" Expression
+function FLWOGRExpression (options) {
+    // Initialize superclass
+    AExpression.call(this);
+
+    this._properties["clauses"] = [];
+    this._properties["minSize"] = 0;
+
+    // Bind options and return
+    this.bind(options);
+    return this;
+}
+
+
+FLWOGRExpression.prototype = Object.create(AExpression.prototype);
+FLWOGRExpression.prototype.constructor = FLWOGRExpression;
+
+
+FLWOGRExpression.prototype.bind = function(options) {
+    AExpression.prototype.bind.call(this, options);
+
+    var options = options || {};
+
+    if (options instanceof SetStatement) {
+         this._properties["clauses"].push(options);
+         this._properties["minSize"] += 1;
+    }
+
+    if (this._properties["clauses"].length <= this._properties["minSize"]) {
+        // Needs to start with for or let clause
+        if (options instanceof ForClause || options instanceof LetClause) {
+            this._properties["clauses"].push(options);
+        }
+    } else {
+        if (options instanceof AQLClause) {
+            this._properties["clauses"].push(options);
+        }
+    }
+
+    return this;
+};
+
+
+FLWOGRExpression.prototype.val = function() {
+    var value = AExpression.prototype.val.call(this);
+
+    var clauseValues = [];
+    for (var c in this._properties["clauses"]) {
+        clauseValues.push(this._properties["clauses"][c].val());
+    }
+
+    return value + clauseValues.join("\n");// + ";";
+};
+
+// Pretty Expression Shorthand
+
+FLWOGRExpression.prototype.ReturnClause = function(expression) {
+    return this.bind(new ReturnClause(expression));
+};
+
+FLWOGRExpression.prototype.ForClause = function() {
+    return this.bind(new ForClause(Array.prototype.slice.call(arguments)));
+};
+
+FLWOGRExpression.prototype.LetClause = function() {
+    return this.bind(new LetClause(Array.prototype.slice.call(arguments)));
+};
+
+FLWOGRExpression.prototype.WhereClause = function() {
+    return this.bind(new WhereClause(Array.prototype.slice.call(arguments)));
+};
+
+FLWOGRExpression.prototype.and = function() {
+    var args = Array.prototype.slice.call(arguments);
+    args.push(true);
+    return this.bind(new WhereClause().and(args));
+};
+
+FLWOGRExpression.prototype.or = function() {
+    var args = Array.prototype.slice.call(arguments);
+    args.push(true);
+    return this.bind(new WhereClause().or(args));
+};
+
+FLWOGRExpression.prototype.OrderbyClause = function() {
+    return this.bind(new OrderbyClause(Array.prototype.slice.call(arguments)));
+};
+
+
+FLWOGRExpression.prototype.GroupClause = function() {
+    return this.bind(new GroupClause(Array.prototype.slice.call(arguments)));
+};
+
+FLWOGRExpression.prototype.LimitClause = function() {
+    return this.bind(new LimitClause(Array.prototype.slice.call(arguments)));
+};
+
+FLWOGRExpression.prototype.DistinctClause = function() {
+    return this.bind(new DistinctClause(Array.prototype.slice.call(arguments)));
+};
+
+FLWOGRExpression.prototype.AQLClause = function() {
+    return this.bind(new AQLClause(Array.prototype.slice.call(arguments)));
+};
+
+
+// AQLClause
+//
+// Base Clause  ::= ForClause | LetClause | WhereClause | OrderbyClause | GroupClause | LimitClause | DistinctClause
+function AQLClause() {
+    this._properties = {};
+    this._properties["clause"] = "";
+    this._properties["stack"] = [];
+    if (typeof arguments[0] == 'string') {
+        this._properties["clause"] = arguments[0];
+    }
+    return this;
+}
+
+AQLClause.prototype.val = function() {
+    var value = this._properties["clause"];
+ 
+    return value;
+};
+
+AQLClause.prototype.bind = function(options) {
+
+    if (options instanceof AQLClause) {
+        this._properties["clause"] += " " + options.val();
+    }
+
+    return this;
+};
+
+AQLClause.prototype.set = function(value) {
+    this._properties["clause"] = value;
+    return this;
+};
+
+
+// ForClause
+//
+// Grammar:
+// "for" Variable ( "at" Variable )? "in" ( Expression )
+//
+// @param for_variable [String], REQUIRED, first variable in clause 
+// @param at_variable [String], NOT REQUIRED, first variable in clause
+// @param expression [AsterixExpression], REQUIRED, expression to evaluate
+function ForClause(for_variable, at_variable, expression) {
+    AQLClause.call(this);
+  
+    var parameters = [];
+    if (arguments[0] instanceof Array) {
+        parameters = arguments[0];
+    } else {
+        parameters = arguments;
+    }
+  
+    this._properties["clause"] = "for " + parameters[0];
+    
+    if (parameters.length == 3) {
+        this._properties["clause"] += " at " + parameters[1];
+        this._properties["clause"] += " in " + parameters[2].val();
+    } else if (parameters.length == 2) {
+        this._properties["clause"] += " in " + parameters[1].val();
+    }
+    
+    return this;
+}
+
+ForClause.prototype = Object.create(AQLClause.prototype);
+ForClause.prototype.constructor = ForClause;
+
+
+// LetClause
+//
+// Grammar:
+// LetClause      ::= "let" Variable ":=" Expression
+//
+// @param let_variable [String]
+// @param expression [AExpression]
+function LetClause(let_variable, expression) {
+    AQLClause.call(this);
+    
+    var parameters = [];
+    if (arguments[0] instanceof Array) {
+        parameters = arguments[0];
+    } else {
+        parameters = arguments;
+    }
+    
+    this._properties["clause"] = "let " + parameters[0] + " := ";
+    this._properties["clause"] += parameters[1].val();
+    
+    return this; 
+}
+
+LetClause.prototype = Object.create(AQLClause.prototype);
+LetClause.prototype.constructor = LetClause;
+
+
+// ReturnClause
+//
+// Grammar:
+// return [AQLExpression]
+function ReturnClause(expression) {
+    AQLClause.call(this);
+
+    this._properties["clause"] = "return ";
+    
+    if (expression instanceof AExpression || expression instanceof AQLClause) {
+        this._properties["clause"] += expression.val();
+    
+    } else if ( typeof expression == "object" && Object.getPrototypeOf( expression ) === Object.prototype ) {
+        
+        this._properties["clause"] += "\n{\n";
+        var returnStatements = [];
+        for (returnValue in expression) {
+           
+            if (expression[returnValue] instanceof AExpression) { 
+                returnStatements.push('"' + returnValue + '" ' + " : " + expression[returnValue].val());            
+            } else if (typeof expression[returnValue] == "string") {          
+                returnStatements.push('"' + returnValue + '" ' + " : " + expression[returnValue]);   
+            }
+        }
+        this._properties["clause"] += returnStatements.join(",\n");
+        this._properties["clause"] += "\n}";  
+    
+    } else {
+        this._properties["clause"] += new AQLClause().set(expression).val();
+    }
+
+    return this;
+}
+
+
+ReturnClause.prototype = Object.create(AQLClause.prototype);
+ReturnClause.prototype.constructor = ReturnClause;
+
+
+// WhereClause
+//
+// Grammar: 
+// ::= "where" Expression
+// 
+// @param expression [BooleanExpression], pushes this expression onto the stack
+function WhereClause(expression) {
+    AQLClause.call(this);
+    
+    this._properties["stack"] = [];
+
+    if (expression instanceof Array) {
+        this.bind(expression[0]);
+    } else {
+        this.bind(expression);
+    }
+    
+    return this;
+}
+
+
+WhereClause.prototype = Object.create(AQLClause.prototype);
+WhereClause.prototype.constructor = WhereClause;
+
+
+WhereClause.prototype.bind = function(expression) {
+    if (expression instanceof AExpression) {
+        this._properties["stack"].push(expression);
+    }
+    return this;
+};
+
+
+WhereClause.prototype.val = function() {
+    var value = "";  
+    
+    if (this._properties["stack"].length == 0) {
+        return value;
+    }
+
+    var count = this._properties["stack"].length - 1;
+    while (count >= 0) {
+        value += this._properties["stack"][count].val() + " ";
+        count -= 1;
+    }
+    
+    return "where " + value;
+};
+
+
+WhereClause.prototype.and = function() {
+    
+    var parameters = [];
+    if (arguments[0] instanceof Array) {
+        parameters = arguments[0];
+    } else {
+        parameters = arguments;
+    }
+    
+    var andClauses = [];  
+    for (var expression in parameters) {
+        
+        if (parameters[expression] instanceof AExpression) {
+            andClauses.push(parameters[expression].val());
+        }
+    }
+    
+    if (andClauses.length > 0) {
+        this._properties["stack"].push(new AExpression().set(andClauses.join(" and ")));
+    }
+    
+    return this;
+};
+
+
+WhereClause.prototype.or = function() {
+
+    var parameters = [];
+    if (arguments[0] instanceof Array) {
+        parameters = arguments[0];
+    } else {
+        parameters = arguments;
+    }
+
+    var orClauses = [];  
+    for (var expression in parameters) {
+        
+        if (parameters[expression] instanceof AExpression) {
+            orClauses.push(parameters[expression].val());
+        }
+    }
+    
+    if (andClauses.length > 0) {
+        this._properties["stack"].push(new AExpression().set(orClauses.join(" and ")));
+    }
+    
+    return this;
+};
+
+// LimitClause
+// Grammar:
+// LimitClause    ::= "limit" Expression ( "offset" Expression )?
+// 
+// @param   limitExpression [REQUIRED, AQLExpression]
+// @param   offsetExpression [OPTIONAL, AQLExpression]
+function LimitClause(limitExpression, offsetExpression) {
+
+    AQLClause.call(this);
+    
+    var parameters = [];
+    if (arguments[0] instanceof Array) {
+        parameters = arguments[0];
+    } else {
+        parameters = arguments;
+    }
+  
+    // limitExpression required
+    this._properties["clause"] = "limit " + parameters[0].val();
+
+    // Optional: Offset
+    if (parameters.length == 2) {
+        this._properties["clause"] += " offset " + parameters[1].val();
+    }
+
+    return this;
+}
+
+LimitClause.prototype = Object.create(AQLClause.prototype);
+LimitClause.prototype.constructor = LimitClause;
+
+
+// OrderbyClause
+//
+// Grammar:
+// OrderbyClause  ::= "order" "by" Expression ( ( "asc" ) | ( "desc" ) )? ( "," Expression ( ( "asc" ) | ( "desc" ) )? )*
+//
+// @params AQLExpressions and asc/desc strings, in any quantity. At least one required. 
+function OrderbyClause() {
+    
+    AQLClause.call(this);
+
+    // At least one argument expression is required, and first should be expression
+    if (arguments.length == 0) {
+        this._properties["clause"] = null;
+        return this;    
+    }
+    
+    var parameters = [];
+    if (arguments[0] instanceof Array) {
+        parameters = arguments[0];
+    } else {
+        parameters = arguments;
+    }
+
+    var expc = 0;
+    var expressions = [];    
+
+    while (expc < parameters.length) {
+      
+        var expression = "";
+
+        if (parameters[expc] instanceof AExpression) {
+            expression += parameters[expc].val();
+        }
+
+        var next = expc + 1;
+        if (next < parameters.length && (parameters[next] == "asc" || parameters[next] == "desc")) {
+            expc++;
+            expression += " " + parameters[expc];
+        }
+        
+        expressions.push(expression);
+      
+        expc++;
+    }
+
+    this._properties["clause"] = "order by " + expressions.join(", ");
+    return this;
+}
+
+OrderbyClause.prototype = Object.create(AQLClause.prototype);
+OrderbyClause.prototype.constructor = OrderbyClause;
+
+
+// GroupClause
+//
+// Grammar:
+// GroupClause    ::= "group" "by" ( Variable ":=" )? Expression ( "," ( Variable ":=" )? Expression )* ( "decor" Variable ":=" Expression ( "," "decor" Variable ":=" Expression )* )? "with" VariableRef ( "," VariableRef )*
+function GroupClause() {
+    AQLClause.call(this);
+
+    if (arguments.length == 0) {
+        this._properties["clause"] = null;
+        return this;    
+    } 
+    
+    var parameters = [];
+    if (arguments[0] instanceof Array) {
+        parameters = arguments[0];
+    } else {
+        parameters = arguments;
+    }
+
+    var expc = 0;
+    var expressions = [];
+    var variableRefs = [];
+    var isDecor = false;
+    
+    while (expc < parameters.length) {
+
+        if (parameters[expc] instanceof AExpression) {
+
+            isDecor = false;
+            expressions.push(parameters[expc].val());
+
+        } else if (typeof parameters[expc] == "string") {       
+            
+            // Special keywords, decor & with
+            if (parameters[expc] == "decor") {
+                isDecor = true;
+            } else if (parameters[expc] == "with") {
+                isDecor = false;
+                expc++;
+                while (expc < parameters.length) {
+                    variableRefs.push(parameters[expc]);
+                    expc++;
+                }
+            
+            // Variables and variable refs
+            } else {
+                
+                var nextc = expc + 1;
+                var expression = "";
+            
+                if (isDecor) {
+                    expression += "decor "; 
+                    isDecor = false;
+                }
+
+                expression += parameters[expc] + " := " + parameters[nextc].val();
+                expressions.push(expression);
+                expc++;
+            }
+        }
+
+        expc++;
+    }
+
+    this._properties["clause"] = "group by " + expressions.join(", ") + " with " + variableRefs.join(", ");
+    return this;
+}
+
+GroupClause.prototype = Object.create(AQLClause.prototype);
+GroupClause.prototype.constructor = GroupClause;
+
+
+// Quantified Expression
+// 
+// Grammar
+// QuantifiedExpression ::= ( ( "some" ) | ( "every" ) ) Variable "in" Expression ( "," Variable "in" Expression )* "satisfies" Expression
+// 
+// @param String some/every
+// @param [AExpression]
+// @param [Aexpression] satisfiesExpression
+function QuantifiedExpression (keyword, expressions, satisfiesExpression) {
+    AExpression.call(this);
+
+    var expression = keyword + " ";
+    var varsInExpressions = [];
+
+    for (var varInExpression in expressions) {
+        varsInExpressions.push(varInExpression + " in " + expressions[varInExpression].val()); 
+    } 
+    expression += varsInExpressions.join(", ") + " satisfies " + satisfiesExpression.val();
+    
+    AExpression.prototype.set.call(this, expression);
+
+    return this;
+}
+
+QuantifiedExpression.prototype = Object.create(AExpression.prototype);
+QuantifiedExpression.prototype.constructor = QuantifiedExpression;
+
+QuantifiedExpression.prototype.val = function() {
+    var value = AExpression.prototype.val.call(this);
+    return "(" + value + ")";    
+};
diff --git a/asterix-examples/src/main/resources/tweetbook-demo/static/js/bootstrap.min.js b/asterix-examples/src/main/resources/tweetbook-demo/static/js/bootstrap.min.js
new file mode 100644
index 0000000..f0b7d68
--- /dev/null
+++ b/asterix-examples/src/main/resources/tweetbook-demo/static/js/bootstrap.min.js
@@ -0,0 +1,11 @@
+/*!
+ * Bootstrap v3.0.0
+ *
+ * Copyright 2013 Twitter, Inc
+ * Licensed under the Apache License v2.0
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Designed and built with all the love in the world @twitter by @mdo and @fat.
+ */
+
++function(a){"use strict";var b='[data-dismiss="alert"]',c=function(c){a(c).on("click",b,this.close)};c.prototype.close=function(b){function f(){e.trigger("closed.bs.alert").remove()}var c=a(this),d=c.attr("data-target");d||(d=c.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,""));var e=a(d);b&&b.preventDefault(),e.length||(e=c.hasClass("alert")?c:c.parent()),e.trigger(b=a.Event("close.bs.alert"));if(b.isDefaultPrevented())return;e.removeClass("in"),a.support.transition&&e.hasClass("fade")?e.one(a.support.transition.end,f).emulateTransitionEnd(150):f()};var d=a.fn.alert;a.fn.alert=function(b){return this.each(function(){var d=a(this),e=d.data("bs.alert");e||d.data("bs.alert",e=new c(this)),typeof b=="string"&&e[b].call(d)})},a.fn.alert.Constructor=c,a.fn.alert.noConflict=function(){return a.fn.alert=d,this},a(document).on("click.bs.alert.data-api",b,c.prototype.close)}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d)};b.DEFAULTS={loadingText:"loading..."},b.prototype.setState=function(a){var b="disabled",c=this.$element,d=c.is("input")?"val":"html",e=c.data();a+="Text",e.resetText||c.data("resetText",c[d]()),c[d](e[a]||this.options[a]),setTimeout(function(){a=="loadingText"?c.addClass(b).attr(b,b):c.removeClass(b).removeAttr(b)},0)},b.prototype.toggle=function(){var a=this.$element.closest('[data-toggle="buttons"]');if(a.length){var b=this.$element.find("input").prop("checked",!this.$element.hasClass("active")).trigger("change");b.prop("type")==="radio"&&a.find(".active").removeClass("active")}this.$element.toggleClass("active")};var c=a.fn.button;a.fn.button=function(c){return this.each(function(){var d=a(this),e=d.data("bs.button"),f=typeof c=="object"&&c;e||d.data("bs.button",e=new b(this,f)),c=="toggle"?e.toggle():c&&e.setState(c)})},a.fn.button.Constructor=b,a.fn.button.noConflict=function(){return a.fn.button=c,this},a(document).on("click.bs.button.data-api","[data-toggle^=button]",function(b){var c=a(b.target);c.hasClass("btn")||(c=c.closest(".btn")),c.button("toggle"),b.preventDefault()})}(window.jQuery),+function(a){"use strict";var b=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=this.sliding=this.interval=this.$active=this.$items=null,this.options.pause=="hover"&&this.$element.on("mouseenter",a.proxy(this.pause,this)).on("mouseleave",a.proxy(this.cycle,this))};b.DEFAULTS={interval:5e3,pause:"hover",wrap:!0},b.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},b.prototype.getActiveIndex=function(){return this.$active=this.$element.find(".item.active"),this.$items=this.$active.parent().children(),this.$items.index(this.$active)},b.prototype.to=function(b){var c=this,d=this.getActiveIndex();if(b>this.$items.length-1||b<0)return;return this.sliding?this.$element.one("slid",function(){c.to(b)}):d==b?this.pause().cycle():this.slide(b>d?"next":"prev",a(this.$items[b]))},b.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition.end&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},b.prototype.next=function(){if(this.sliding)return;return this.slide("next")},b.prototype.prev=function(){if(this.sliding)return;return this.slide("prev")},b.prototype.slide=function(b,c){var d=this.$element.find(".item.active"),e=c||d[b](),f=this.interval,g=b=="next"?"left":"right",h=b=="next"?"first":"last",i=this;if(!e.length){if(!this.options.wrap)return;e=this.$element.find(".item")[h]()}this.sliding=!0,f&&this.pause();var j=a.Event("slide.bs.carousel",{relatedTarget:e[0],direction:g});if(e.hasClass("active"))return;this.$indicators.length&&(this.$indicators.find(".active").removeClass("active"),this.$element.one("slid",function(){var b=a(i.$indicators.children()[i.getActiveIndex()]);b&&b.addClass("active")}));if(a.support.transition&&this.$element.hasClass("slide")){this.$element.trigger(j);if(j.isDefaultPrevented())return;e.addClass(b),e[0].offsetWidth,d.addClass(g),e.addClass(g),d.one(a.support.transition.end,function(){e.removeClass([b,g].join(" ")).addClass("active"),d.removeClass(["active",g].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger("slid")},0)}).emulateTransitionEnd(600)}else{this.$element.trigger(j);if(j.isDefaultPrevented())return;d.removeClass("active"),e.addClass("active"),this.sliding=!1,this.$element.trigger("slid")}return f&&this.cycle(),this};var c=a.fn.carousel;a.fn.carousel=function(c){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},b.DEFAULTS,d.data(),typeof c=="object"&&c),g=typeof c=="string"?c:f.slide;e||d.data("bs.carousel",e=new b(this,f)),typeof c=="number"?e.to(c):g?e[g]():f.interval&&e.pause().cycle()})},a.fn.carousel.Constructor=b,a.fn.carousel.noConflict=function(){return a.fn.carousel=c,this},a(document).on("click.bs.carousel.data-api","[data-slide], [data-slide-to]",function(b){var c=a(this),d,e=a(c.attr("data-target")||(d=c.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,"")),f=a.extend({},e.data(),c.data()),g=c.attr("data-slide-to");g&&(f.interval=!1),e.carousel(f),(g=c.attr("data-slide-to"))&&e.data("bs.carousel").to(g),b.preventDefault()}),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var b=a(this);b.carousel(b.data())})})}(window.jQuery),+function(a){function e(){a(b).remove(),a(c).each(function(b){var c=f(a(this));if(!c.hasClass("open"))return;c.trigger(b=a.Event("hide.bs.dropdown"));if(b.isDefaultPrevented())return;c.removeClass("open").trigger("hidden.bs.dropdown")})}function f(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}"use strict";var b=".dropdown-backdrop",c="[data-toggle=dropdown]",d=function(b){var c=a(b).on("click.bs.dropdown",this.toggle)};d.prototype.toggle=function(b){var c=a(this);if(c.is(".disabled, :disabled"))return;var d=f(c),g=d.hasClass("open");e();if(!g){"ontouchstart"in document.documentElement&&!d.closest(".navbar-nav").length&&a('<div class="dropdown-backdrop"/>').insertAfter(a(this)).on("click",e),d.trigger(b=a.Event("show.bs.dropdown"));if(b.isDefaultPrevented())return;d.toggleClass("open").trigger("shown.bs.dropdown"),c.focus()}return!1},d.prototype.keydown=function(b){if(!/(38|40|27)/.test(b.keyCode))return;var d=a(this);b.preventDefault(),b.stopPropagation();if(d.is(".disabled, :disabled"))return;var e=f(d),g=e.hasClass("open");if(!g||g&&b.keyCode==27)return b.which==27&&e.find(c).focus(),d.click();var h=a("[role=menu] li:not(.divider):visible a",e);if(!h.length)return;var i=h.index(h.filter(":focus"));b.keyCode==38&&i>0&&i--,b.keyCode==40&&i<h.length-1&&i++,~i||(i=0),h.eq(i).focus()};var g=a.fn.dropdown;a.fn.dropdown=function(b){return this.each(function(){var c=a(this),e=c.data("dropdown");e||c.data("dropdown",e=new d(this)),typeof b=="string"&&e[b].call(c)})},a.fn.dropdown.Constructor=d,a.fn.dropdown.noConflict=function(){return a.fn.dropdown=g,this},a(document).on("click.bs.dropdown.data-api",e).on("click.bs.dropdown.data-api",".dropdown form",function(a){a.stopPropagation()}).on("click.bs.dropdown.data-api",c,d.prototype.toggle).on("keydown.bs.dropdown.data-api",c+", [role=menu]",d.prototype.keydown)}(window.jQuery),+function(a){"use strict";var b=function(b,c){this.options=c,this.$element=a(b),this.$backdrop=this.isShown=null,this.options.remote&&this.$element.load(this.options.remote)};b.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},b.prototype.toggle=function(a){return this[this.isShown?"hide":"show"](a)},b.prototype.show=function(b){var c=this,d=a.Event("show.bs.modal",{relatedTarget:b});this.$element.trigger(d);if(this.isShown||d.isDefaultPrevented())return;this.isShown=!0,this.escape(),this.$element.on("click.dismiss.modal",'[data-dismiss="modal"]',a.proxy(this.hide,this)),this.backdrop(function(){var d=a.support.transition&&c.$element.hasClass("fade");c.$element.parent().length||c.$element.appendTo(document.body),c.$element.show(),d&&c.$element[0].offsetWidth,c.$element.addClass("in").attr("aria-hidden",!1),c.enforceFocus();var e=a.Event("shown.bs.modal",{relatedTarget:b});d?c.$element.find(".modal-dialog").one(a.support.transition.end,function(){c.$element.focus().trigger(e)}).emulateTransitionEnd(300):c.$element.focus().trigger(e)})},b.prototype.hide=function(b){b&&b.preventDefault(),b=a.Event("hide.bs.modal"),this.$element.trigger(b);if(!this.isShown||b.isDefaultPrevented())return;this.isShown=!1,this.escape(),a(document).off("focusin.bs.modal"),this.$element.removeClass("in").attr("aria-hidden",!0).off("click.dismiss.modal"),a.support.transition&&this.$element.hasClass("fade")?this.$element.one(a.support.transition.end,a.proxy(this.hideModal,this)).emulateTransitionEnd(300):this.hideModal()},b.prototype.enforceFocus=function(){a(document).off("focusin.bs.modal").on("focusin.bs.modal",a.proxy(function(a){this.$element[0]!==a.target&&!this.$element.has(a.target).length&&this.$element.focus()},this))},b.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keyup.dismiss.bs.modal",a.proxy(function(a){a.which==27&&this.hide()},this)):this.isShown||this.$element.off("keyup.dismiss.bs.modal")},b.prototype.hideModal=function(){var a=this;this.$element.hide(),this.backdrop(function(){a.removeBackdrop(),a.$element.trigger("hidden.bs.modal")})},b.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},b.prototype.backdrop=function(b){var c=this,d=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var e=a.support.transition&&d;this.$backdrop=a('<div class="modal-backdrop '+d+'" />').appendTo(document.body),this.$element.on("click.dismiss.modal",a.proxy(function(a){if(a.target!==a.currentTarget)return;this.options.backdrop=="static"?this.$element[0].focus.call(this.$element[0]):this.hide.call(this)},this)),e&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in");if(!b)return;e?this.$backdrop.one(a.support.transition.end,b).emulateTransitionEnd(150):b()}else!this.isShown&&this.$backdrop?(this.$backdrop.removeClass("in"),a.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one(a.support.transition.end,b).emulateTransitionEnd(150):b()):b&&b()};var c=a.fn.modal;a.fn.modal=function(c,d){return this.each(function(){var e=a(this),f=e.data("bs.modal"),g=a.extend({},b.DEFAULTS,e.data(),typeof c=="object"&&c);f||e.data("bs.modal",f=new b(this,g)),typeof c=="string"?f[c](d):g.show&&f.show(d)})},a.fn.modal.Constructor=b,a.fn.modal.noConflict=function(){return a.fn.modal=c,this},a(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(b){var c=a(this),d=c.attr("href"),e=a(c.attr("data-target")||d&&d.replace(/.*(?=#[^\s]+$)/,"")),f=e.data("modal")?"toggle":a.extend({remote:!/#/.test(d)&&d},e.data(),c.data());b.preventDefault(),e.modal(f,this).one("hide",function(){c.is(":visible")&&c.focus()})}),a(document).on("show.bs.modal",".modal",function(){a(document.body).addClass("modal-open")}).on("hidden.bs.modal",".modal",function(){a(document.body).removeClass("modal-open")})}(window.jQuery),+function(a){"use strict";var b=function(a,b){this.type=this.options=this.enabled=this.timeout=this.hoverState=this.$element=null,this.init("tooltip",a,b)};b.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1},b.prototype.init=function(b,c,d){this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d);var e=this.options.trigger.split(" ");for(var f=e.length;f--;){var g=e[f];if(g=="click")this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if(g!="manual"){var h=g=="hover"?"mouseenter":"focus",i=g=="hover"?"mouseleave":"blur";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&typeof b.delay=="number"&&(b.delay={show:b.delay,hide:b.delay}),b},b.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},b.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type);clearTimeout(c.timeout),c.hoverState="in";if(!c.options.delay||!c.options.delay.show)return c.show();c.timeout=setTimeout(function(){c.hoverState=="in"&&c.show()},c.options.delay.show)},b.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type);clearTimeout(c.timeout),c.hoverState="out";if(!c.options.delay||!c.options.delay.hide)return c.hide();c.timeout=setTimeout(function(){c.hoverState=="out"&&c.hide()},c.options.delay.hide)},b.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);if(b.isDefaultPrevented())return;var c=this.tip();this.setContent(),this.options.animation&&c.addClass("fade");var d=typeof this.options.placement=="function"?this.options.placement.call(this,c[0],this.$element[0]):this.options.placement,e=/\s?auto?\s?/i,f=e.test(d);f&&(d=d.replace(e,"")||"top"),c.detach().css({top:0,left:0,display:"block"}).addClass(d),this.options.container?c.appendTo(this.options.container):c.insertAfter(this.$element);var g=this.getPosition(),h=c[0].offsetWidth,i=c[0].offsetHeight;if(f){var j=this.$element.parent(),k=d,l=document.documentElement.scrollTop||document.body.scrollTop,m=this.options.container=="body"?window.innerWidth:j.outerWidth(),n=this.options.container=="body"?window.innerHeight:j.outerHeight(),o=this.options.container=="body"?0:j.offset().left;d=d=="bottom"&&g.top+g.height+i-l>n?"top":d=="top"&&g.top-l-i<0?"bottom":d=="right"&&g.right+h>m?"left":d=="left"&&g.left-h<o?"right":d,c.removeClass(k).addClass(d)}var p=this.getCalculatedOffset(d,g,h,i);this.applyPlacement(p,d),this.$element.trigger("shown.bs."+this.type)}},b.prototype.applyPlacement=function(a,b){var c,d=this.tip(),e=d[0].offsetWidth,f=d[0].offsetHeight,g=parseInt(d.css("margin-top"),10),h=parseInt(d.css("margin-left"),10);isNaN(g)&&(g=0),isNaN(h)&&(h=0),a.top=a.top+g,a.left=a.left+h,d.offset(a).addClass("in");var i=d[0].offsetWidth,j=d[0].offsetHeight;b=="top"&&j!=f&&(c=!0,a.top=a.top+f-j);if(/bottom|top/.test(b)){var k=0;a.left<0&&(k=a.left*-2,a.left=0,d.offset(a),i=d[0].offsetWidth,j=d[0].offsetHeight),this.replaceArrow(k-e+i,i,"left")}else this.replaceArrow(j-f,j,"top");c&&d.offset(a)},b.prototype.replaceArrow=function(a,b,c){this.arrow().css(c,a?50*(1-a/b)+"%":"")},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle();a.find(".tooltip-inner")[this.options.html?"html":"text"](b),a.removeClass("fade in top bottom left right")},b.prototype.hide=function(){function e(){b.hoverState!="in"&&c.detach()}var b=this,c=this.tip(),d=a.Event("hide.bs."+this.type);this.$element.trigger(d);if(d.isDefaultPrevented())return;return c.removeClass("in"),a.support.transition&&this.$tip.hasClass("fade")?c.one(a.support.transition.end,e).emulateTransitionEnd(150):e(),this.$element.trigger("hidden.bs."+this.type),this},b.prototype.fixTitle=function(){var a=this.$element;(a.attr("title")||typeof a.attr("data-original-title")!="string")&&a.attr("data-original-title",a.attr("title")||"").attr("title","")},b.prototype.hasContent=function(){return this.getTitle()},b.prototype.getPosition=function(){var b=this.$element[0];return a.extend({},typeof b.getBoundingClientRect=="function"?b.getBoundingClientRect():{width:b.offsetWidth,height:b.offsetHeight},this.$element.offset())},b.prototype.getCalculatedOffset=function(a,b,c,d){return a=="bottom"?{top:b.top+b.height,left:b.left+b.width/2-c/2}:a=="top"?{top:b.top-d,left:b.left+b.width/2-c/2}:a=="left"?{top:b.top+b.height/2-d/2,left:b.left-c}:{top:b.top+b.height/2-d/2,left:b.left+b.width}},b.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||(typeof c.title=="function"?c.title.call(b[0]):c.title),a},b.prototype.tip=function(){return this.$tip=this.$tip||a(this.options.template)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},b.prototype.validate=function(){this.$element[0].parentNode||(this.hide(),this.$element=null,this.options=null)},b.prototype.enable=function(){this.enabled=!0},b.prototype.disable=function(){this.enabled=!1},b.prototype.toggleEnabled=function(){this.enabled=!this.enabled},b.prototype.toggle=function(b){var c=b?a(b.currentTarget)[this.type](this.getDelegateOptions()).data("bs."+this.type):this;c.tip().hasClass("in")?c.leave(c):c.enter(c)},b.prototype.destroy=function(){this.hide().$element.off("."+this.type).removeData("bs."+this.type)};var c=a.fn.tooltip;a.fn.tooltip=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tooltip"),f=typeof c=="object"&&c;e||d.data("bs.tooltip",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.tooltip.Constructor=b,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=c,this}}(window.jQuery),+function(a){"use strict";var b=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");b.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),b.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),b.prototype.constructor=b,b.prototype.getDefaults=function(){return b.DEFAULTS},b.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content")[this.options.html?"html":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},b.prototype.hasContent=function(){return this.getTitle()||this.getContent()},b.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||(typeof b.content=="function"?b.content.call(a[0]):b.content)},b.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")},b.prototype.tip=function(){return this.$tip||(this.$tip=a(this.options.template)),this.$tip};var c=a.fn.popover;a.fn.popover=function(c){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f=typeof c=="object"&&c;e||d.data("bs.popover",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.popover.Constructor=b,a.fn.popover.noConflict=function(){return a.fn.popover=c,this}}(window.jQuery),+function(a){"use strict";var b=function(b){this.element=a(b)};b.prototype.show=function(){var b=this.element,c=b.closest("ul:not(.dropdown-menu)"),d=b.attr("data-target");d||(d=b.attr("href"),d=d&&d.replace(/.*(?=#[^\s]*$)/,""));if(b.parent("li").hasClass("active"))return;var e=c.find(".active:last a")[0],f=a.Event("show.bs.tab",{relatedTarget:e});b.trigger(f);if(f.isDefaultPrevented())return;var g=a(d);this.activate(b.parent("li"),c),this.activate(g,g.parent(),function(){b.trigger({type:"shown.bs.tab",relatedTarget:e})})},b.prototype.activate=function(b,c,d){function g(){e.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"),b.addClass("active"),f?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu")&&b.closest("li.dropdown").addClass("active"),d&&d()}var e=c.find("> .active"),f=d&&a.support.transition&&e.hasClass("fade");f?e.one(a.support.transition.end,g).emulateTransitionEnd(150):g(),e.removeClass("in")};var c=a.fn.tab;a.fn.tab=function(c){return this.each(function(){var d=a(this),e=d.data("bs.tab");e||d.data("bs.tab",e=new b(this)),typeof c=="string"&&e[c]()})},a.fn.tab.Constructor=b,a.fn.tab.noConflict=function(){return a.fn.tab=c,this},a(document).on("click.bs.tab.data-api",'[data-toggle="tab"], [data-toggle="pill"]',function(b){b.preventDefault(),a(this).tab("show")})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.options=a.extend({},b.DEFAULTS,d),this.$window=a(window).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(c),this.affixed=this.unpin=null,this.checkPosition()};b.RESET="affix affix-top affix-bottom",b.DEFAULTS={offset:0},b.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},b.prototype.checkPosition=function(){if(!this.$element.is(":visible"))return;var c=a(document).height(),d=this.$window.scrollTop(),e=this.$element.offset(),f=this.options.offset,g=f.top,h=f.bottom;typeof f!="object"&&(h=g=f),typeof g=="function"&&(g=f.top()),typeof h=="function"&&(h=f.bottom());var i=this.unpin!=null&&d+this.unpin<=e.top?!1:h!=null&&e.top+this.$element.height()>=c-h?"bottom":g!=null&&d<=g?"top":!1;if(this.affixed===i)return;this.unpin&&this.$element.css("top",""),this.affixed=i,this.unpin=i=="bottom"?e.top-d:null,this.$element.removeClass(b.RESET).addClass("affix"+(i?"-"+i:"")),i=="bottom"&&this.$element.offset({top:document.body.offsetHeight-h-this.$element.height()})};var c=a.fn.affix;a.fn.affix=function(c){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f=typeof c=="object"&&c;e||d.data("bs.affix",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.affix.Constructor=b,a.fn.affix.noConflict=function(){return a.fn.affix=c,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var b=a(this),c=b.data();c.offset=c.offset||{},c.offsetBottom&&(c.offset.bottom=c.offsetBottom),c.offsetTop&&(c.offset.top=c.offsetTop),b.affix(c)})})}(window.jQuery),+function(a){"use strict";var b=function(c,d){this.$element=a(c),this.options=a.extend({},b.DEFAULTS,d),this.transitioning=null,this.options.parent&&(this.$parent=a(this.options.parent)),this.options.toggle&&this.toggle()};b.DEFAULTS={toggle:!0},b.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},b.prototype.show=function(){if(this.transitioning||this.$element.hasClass("in"))return;var b=a.Event("show.bs.collapse");this.$element.trigger(b);if(b.isDefaultPrevented())return;var c=this.$parent&&this.$parent.find("> .panel > .in");if(c&&c.length){var d=c.data("bs.collapse");if(d&&d.transitioning)return;c.collapse("hide"),d||c.data("bs.collapse",null)}var e=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[e](0),this.transitioning=1;var f=function(){this.$element.removeClass("collapsing").addClass("in")[e]("auto"),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return f.call(this);var g=a.camelCase(["scroll",e].join("-"));this.$element.one(a.support.transition.end,a.proxy(f,this)).emulateTransitionEnd(350)[e](this.$element[0][g])},b.prototype.hide=function(){if(this.transitioning||!this.$element.hasClass("in"))return;var b=a.Event("hide.bs.collapse");this.$element.trigger(b);if(b.isDefaultPrevented())return;var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse").removeClass("in"),this.transitioning=1;var d=function(){this.transitioning=0,this.$element.trigger("hidden.bs.collapse").removeClass("collapsing").addClass("collapse")};if(!a.support.transition)return d.call(this);this.$element[c](0).one(a.support.transition.end,a.proxy(d,this)).emulateTransitionEnd(350)},b.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()};var c=a.fn.collapse;a.fn.collapse=function(c){return this.each(function(){var d=a(this),e=d.data("bs.collapse"),f=a.extend({},b.DEFAULTS,d.data(),typeof c=="object"&&c);e||d.data("bs.collapse",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.collapse.Constructor=b,a.fn.collapse.noConflict=function(){return a.fn.collapse=c,this},a(document).on("click.bs.collapse.data-api","[data-toggle=collapse]",function(b){var c=a(this),d,e=c.attr("data-target")||b.preventDefault()||(d=c.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""),f=a(e),g=f.data("bs.collapse"),h=g?"toggle":c.data(),i=c.attr("data-parent"),j=i&&a(i);if(!g||!g.transitioning)j&&j.find('[data-toggle=collapse][data-parent="'+i+'"]').not(c).addClass("collapsed"),c[f.hasClass("in")?"addClass":"removeClass"]("collapsed");f.collapse(h)})}(window.jQuery),+function(a){function b(c,d){var e,f=a.proxy(this.process,this);this.$element=a(c).is("body")?a(window):a(c),this.$body=a("body"),this.$scrollElement=this.$element.on("scroll.bs.scroll-spy.data-api",f),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||(e=a(c).attr("href"))&&e.replace(/.*(?=#[^\s]+$)/,"")||"")+" .nav li > a",this.offsets=a([]),this.targets=a([]),this.activeTarget=null,this.refresh(),this.process()}"use strict",b.DEFAULTS={offset:10},b.prototype.refresh=function(){var b=this.$element[0]==window?"offset":"position";this.offsets=a([]),this.targets=a([]);var c=this,d=this.$body.find(this.selector).map(function(){var d=a(this),e=d.data("target")||d.attr("href"),f=/^#\w/.test(e)&&a(e);return f&&f.length&&[[f[b]().top+(!a.isWindow(c.$scrollElement.get(0))&&c.$scrollElement.scrollTop()),e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){c.offsets.push(this[0]),c.targets.push(this[1])})},b.prototype.process=function(){var a=this.$scrollElement.scrollTop()+this.options.offset,b=this.$scrollElement[0].scrollHeight||this.$body[0].scrollHeight,c=b-this.$scrollElement.height(),d=this.offsets,e=this.targets,f=this.activeTarget,g;if(a>=c)return f!=(g=e.last()[0])&&this.activate(g);for(g=d.length;g--;)f!=e[g]&&a>=d[g]&&(!d[g+1]||a<=d[g+1])&&this.activate(e[g])},b.prototype.activate=function(b){this.activeTarget=b,a(this.selector).parents(".active").removeClass("active");var c=this.selector+'[data-target="'+b+'"],'+this.selector+'[href="'+b+'"]',d=a(c).parents("li").addClass("active");d.parent(".dropdown-menu").length&&(d=d.closest("li.dropdown").addClass("active")),d.trigger("activate")};var c=a.fn.scrollspy;a.fn.scrollspy=function(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f=typeof c=="object"&&c;e||d.data("bs.scrollspy",e=new b(this,f)),typeof c=="string"&&e[c]()})},a.fn.scrollspy.Constructor=b,a.fn.scrollspy.noConflict=function(){return a.fn.scrollspy=c,this},a(window).on("load",function(){a('[data-spy="scroll"]').each(function(){var b=a(this);b.scrollspy(b.data())})})}(window.jQuery),+function(a){function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(a.style[c]!==undefined)return{end:b[c]}}"use strict",a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one(a.support.transition.end,function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b()})}(window.jQuery)
\ No newline at end of file
diff --git a/asterix-examples/src/main/resources/tweetbook-demo/static/js/geostats.js b/asterix-examples/src/main/resources/tweetbook-demo/static/js/geostats.js
new file mode 100755
index 0000000..adc8e1d
--- /dev/null
+++ b/asterix-examples/src/main/resources/tweetbook-demo/static/js/geostats.js
@@ -0,0 +1,679 @@
+/**
+* geostats() is a tiny and standalone javascript library for classification 
+* Project page - https://github.com/simogeo/geostats
+* Copyright (c) 2011 Simon Georget, http://valums.com
+* Licensed under the MIT license
+*/
+
+var _t = function(str) {
+	return str;
+};
+
+var inArray = function(needle, haystack) {
+    for(var i = 0; i < haystack.length; i++) {
+        if(haystack[i] == needle) return true;
+    }
+    return false;
+};
+
+var geostats = function(a) {
+
+	this.separator = ' - ';
+	this.legendSeparator = this.separator;
+	this.method  = '';
+	this.roundlength 	= 2; // Number of decimals, round values
+	this.is_uniqueValues = false;
+	
+	this.bounds  = Array();
+	this.ranges  = Array();
+	this.colors  = Array();
+	this.counter = Array();
+	
+	// statistics information
+	this.stat_sorted	= null;
+	this.stat_mean 		= null;
+	this.stat_median 	= null;
+	this.stat_sum 		= null;
+	this.stat_max 		= null;
+	this.stat_min 		= null;
+	this.stat_pop 		= null;
+	this.stat_variance	= null;
+	this.stat_stddev	= null;
+	this.stat_cov		= null;
+
+	
+	if(typeof a !== 'undefined' && a.length > 0) {
+		this.serie = a;
+	} else {
+		this.serie = Array();
+	};
+	
+	/**
+	 * Set a new serie
+	 */
+	this.setSerie = function(a) {
+	
+		this.serie = Array() // init empty array to prevent bug when calling classification after another with less items (sample getQuantile(6) and getQuantile(4))
+		this.serie = a;
+		
+	};
+	
+	/**
+	 * Set colors
+	 */
+	this.setColors = function(colors) {
+		
+		this.colors = colors;
+		
+	};
+	
+	/**
+	 * Get feature count
+	 * With bounds array(0, 0.75, 1.5, 2.25, 3); 
+	 * should populate this.counter with 5 keys
+	 * and increment counters for each key
+	 */
+	this.doCount = function() {
+		
+		if (this._nodata())
+			return;
+		
+
+		var tmp = this.sorted();
+		// console.log(tmp.join(', '));
+
+		
+		// we init counter with 0 value
+		for(i = 0; i < this.bounds.length; i++) {
+			this.counter[i]= 0;
+		}
+		
+		for(j=0; j < tmp.length; j++) {
+			
+			// get current class for value to increment the counter
+			var cclass = this.getClass(tmp[j]);
+			this.counter[cclass]++;
+
+		}
+
+	};
+	
+	/**
+	 * Transform a bounds array to a range array the following array : array(0,
+	 * 0.75, 1.5, 2.25, 3); becomes : array('0-0.75', '0.75-1.5', '1.5-2.25',
+	 * '2.25-3');
+	 */
+	this.setRanges = function() {
+	
+		this.ranges = Array(); // init empty array to prevent bug when calling classification after another with less items (sample getQuantile(6) and getQuantile(4))
+		
+		for (i = 0; i < (this.bounds.length - 1); i++) {
+			this.ranges[i] = this.bounds[i] + this.separator + this.bounds[i + 1];
+		}
+	};
+
+	/** return min value */
+	this.min = function() {
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_min  == null) {
+			
+			this.stat_min = this.serie[0];
+			for (i = 0; i < this.pop(); i++) {
+				if (this.serie[i] < this.stat_min) {
+					this.stat_min = this.serie[i];
+				}
+			}
+			
+		}
+		
+		return this.stat_min;
+	};
+
+	/** return max value */
+	this.max = function() {
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_max  == null) {
+			
+			this.stat_max = this.serie[0];
+			for (i = 0; i < this.pop(); i++) {
+				if (this.serie[i] > this.stat_max) {
+					this.stat_max = this.serie[i];
+				}
+			}
+			
+		}
+		
+		return this.stat_max;
+	};
+
+	/** return sum value */
+	this.sum = function() {
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_sum  == null) {
+			
+			this.stat_sum = 0;
+			for (i = 0; i < this.pop(); i++) {
+				this.stat_sum += this.serie[i];
+			}
+			
+		}
+		
+		return this.stat_sum;
+	};
+
+	/** return population number */
+	this.pop = function() {
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_pop  == null) {
+			
+			this.stat_pop = this.serie.length;
+			
+		}
+		
+		return this.stat_pop;
+	};
+
+	/** return mean value */
+	this.mean = function() {
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_mean  == null) {
+			
+			this.stat_mean = this.sum() / this.pop();
+			
+		}
+		
+		return this.stat_mean;
+	};
+
+	/** return median value */
+	this.median = function() {
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_median  == null) {
+			
+			this.stat_median = 0;
+			var tmp = this.sorted();
+	
+			if (tmp.length % 2) {
+				this.stat_median = tmp[(Math.ceil(tmp.length / 2) - 1)];
+			} else {
+				this.stat_median = (tmp[(tmp.length / 2) - 1] + tmp[(tmp.length / 2)]) / 2;
+			}
+			
+		}
+		
+		return this.stat_median;
+	};
+
+	/** return variance value */
+	this.variance = function() {
+		
+		round = (typeof round === "undefined") ? true : false;
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_variance  == null) {
+
+			var tmp = 0;
+			for (var i = 0; i < this.pop(); i++) {
+				tmp += Math.pow( (this.serie[i] - this.mean()), 2 );
+			}
+
+			this.stat_variance =  tmp /	this.pop();
+			
+			if(round == true) {
+				this.stat_variance = Math.round(this.stat_variance * Math.pow(10,this.roundlength) )/ Math.pow(10,this.roundlength);
+			}
+			
+		}
+		
+		return this.stat_variance;
+	};
+	
+	/** return standard deviation value */
+	this.stddev = function(round) {
+		
+		round = (typeof round === "undefined") ? true : false;
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_stddev  == null) {
+			
+			this.stat_stddev = Math.sqrt(this.variance());
+			
+			if(round == true) {
+				this.stat_stddev = Math.round(this.stat_stddev * Math.pow(10,this.roundlength) )/ Math.pow(10,this.roundlength);
+			}
+			
+		}
+		
+		return this.stat_stddev;
+	};
+	
+	/** coefficient of variation - measure of dispersion */
+	this.cov = function(round) {
+		
+		round = (typeof round === "undefined") ? true : false;
+		
+		if (this._nodata())
+			return;
+		
+		if (this.stat_cov  == null) {
+			
+			this.stat_cov = this.stddev() / this.mean();
+			
+			if(round == true) {
+				this.stat_cov = Math.round(this.stat_cov * Math.pow(10,this.roundlength) )/ Math.pow(10,this.roundlength);
+			}
+			
+		}
+		
+		return this.stat_cov;
+	};
+	
+	/** data test */
+	this._nodata = function() {
+		if (this.serie.length == 0) {
+			
+			alert("Error. You should first enter a serie!");
+			return 1;
+		} else
+			return 0;
+		
+	};
+
+	/** return sorted values (as array) */
+	this.sorted = function() {
+		
+		if (this.stat_sorted  == null) {
+			
+			if(this.is_uniqueValues == false) {
+				this.stat_sorted = this.serie.sort(function(a, b) {
+					return a - b;
+				});
+			} else {
+				this.stat_sorted = this.serie.sort(function(a,b){
+					var nameA=a.toLowerCase(), nameB=b.toLowerCase()
+				    if(nameA < nameB) return -1;
+				    if(nameA > nameB) return 1;
+				    return 0;
+				})
+			}
+		}
+		
+		return this.stat_sorted;
+		
+	};
+
+	/** return all info */
+	this.info = function() {
+		
+		if (this._nodata())
+			return;
+		
+		var content = '';
+		content += _t('Population') + ' : ' + this.pop() + ' - [' + _t('Min')
+				+ ' : ' + this.min() + ' | ' + _t('Max') + ' : ' + this.max()
+				+ ']' + "\n";
+		content += _t('Mean') + ' : ' + this.mean() + ' - ' + _t('Median')	+ ' : ' + this.median() + "\n";
+		content += _t('Variance') + ' : ' + this.variance() + ' - ' + _t('Standard deviation')	+ ' : ' + this.stddev()  
+				+ ' - ' + _t('Coefficient of variation')	+ ' : ' + this.cov() + "\n";
+
+		return content;
+	};
+
+	/**
+	 * Equal intervals discretization Return an array with bounds : ie array(0,
+	 * 0.75, 1.5, 2.25, 3);
+	 */
+	this.getEqInterval = function(nbClass) {
+
+		if (this._nodata())
+			return;
+
+		this.method = _t('eq. intervals') + ' (' + nbClass + ' ' + _t('classes')
+				+ ')';
+
+		var a = Array();
+		var val = this.min();
+		var interval = (this.max() - this.min()) / nbClass;
+
+		for (i = 0; i <= nbClass; i++) {
+			a[i] = val;
+			val += interval;
+		}
+
+		this.bounds = a;
+		this.setRanges();
+		
+		return a;
+	};
+	
+
+	/**
+	 * Quantile discretization Return an array with bounds : ie array(0, 0.75,
+	 * 1.5, 2.25, 3);
+	 */
+	this.getQuantile = function(nbClass) {
+
+		if (this._nodata())
+			return;
+
+		this.method = _t('quantile') + ' (' + nbClass + ' ' + _t('classes') + ')';
+
+		var a = Array();
+		var tmp = this.sorted();
+
+		var classSize = Math.round(this.pop() / nbClass);
+		var step = classSize;
+		var i = 0;
+
+		// we set first value
+		a[0] = tmp[0];
+
+		for (i = 1; i < nbClass; i++) {
+			a[i] = tmp[step];
+			step += classSize;
+		}
+		// we set last value
+		a.push(tmp[tmp.length - 1]);
+		
+		this.bounds = a;
+		this.setRanges();
+		
+		return a;
+
+	};
+	
+	/**
+	 * Credits : Doug Curl (javascript) and Daniel J Lewis (python implementation)
+	 * http://www.arcgis.com/home/item.html?id=0b633ff2f40d412995b8be377211c47b
+	 * http://danieljlewis.org/2010/06/07/jenks-natural-breaks-algorithm-in-python/
+	 */
+	this.getJenks = function(nbClass) {
+	
+		if (this._nodata())
+			return;
+		
+		this.method = _t('Jenks') + ' (' + nbClass + ' ' + _t('classes') + ')';
+		
+		dataList = this.sorted();
+
+		// now iterate through the datalist:
+		// determine mat1 and mat2
+		// really not sure how these 2 different arrays are set - the code for
+		// each seems the same!
+		// but the effect are 2 different arrays: mat1 and mat2
+		var mat1 = []
+		for ( var x = 0, xl = dataList.length + 1; x < xl; x++) {
+			var temp = []
+			for ( var j = 0, jl = nbClass + 1; j < jl; j++) {
+				temp.push(0)
+			}
+			mat1.push(temp)
+		}
+
+		var mat2 = []
+		for ( var i = 0, il = dataList.length + 1; i < il; i++) {
+			var temp2 = []
+			for ( var c = 0, cl = nbClass + 1; c < cl; c++) {
+				temp2.push(0)
+			}
+			mat2.push(temp2)
+		}
+
+		// absolutely no idea what this does - best I can tell, it sets the 1st
+		// group in the
+		// mat1 and mat2 arrays to 1 and 0 respectively
+		for ( var y = 1, yl = nbClass + 1; y < yl; y++) {
+			mat1[0][y] = 1
+			mat2[0][y] = 0
+			for ( var t = 1, tl = dataList.length + 1; t < tl; t++) {
+				mat2[t][y] = Infinity
+			}
+			var v = 0.0
+		}
+
+		// and this part - I'm a little clueless on - but it works
+		// pretty sure it iterates across the entire dataset and compares each
+		// value to
+		// one another to and adjust the indices until you meet the rules:
+		// minimum deviation
+		// within a class and maximum separation between classes
+		for ( var l = 2, ll = dataList.length + 1; l < ll; l++) {
+			var s1 = 0.0
+			var s2 = 0.0
+			var w = 0.0
+			for ( var m = 1, ml = l + 1; m < ml; m++) {
+				var i3 = l - m + 1
+				var val = parseFloat(dataList[i3 - 1])
+				s2 += val * val
+				s1 += val
+				w += 1
+				v = s2 - (s1 * s1) / w
+				var i4 = i3 - 1
+				if (i4 != 0) {
+					for ( var p = 2, pl = nbClass + 1; p < pl; p++) {
+						if (mat2[l][p] >= (v + mat2[i4][p - 1])) {
+							mat1[l][p] = i3
+							mat2[l][p] = v + mat2[i4][p - 1]
+						}
+					}
+				}
+			}
+			mat1[l][1] = 1
+			mat2[l][1] = v
+		}
+
+		var k = dataList.length
+		var kclass = []
+
+		// fill the kclass (classification) array with zeros:
+		for (i = 0, il = nbClass + 1; i < il; i++) {
+			kclass.push(0)
+		}
+
+		// this is the last number in the array:
+		kclass[nbClass] = parseFloat(dataList[dataList.length - 1])
+		// this is the first number - can set to zero, but want to set to lowest
+		// to use for legend:
+		kclass[0] = parseFloat(dataList[0])
+		var countNum = nbClass
+		while (countNum >= 2) {
+			var id = parseInt((mat1[k][countNum]) - 2)
+			kclass[countNum - 1] = dataList[id]
+			k = parseInt((mat1[k][countNum] - 1))
+			// spits out the rank and value of the break values:
+			// console.log("id="+id,"rank = " + String(mat1[k][countNum]),"val =
+			// " + String(dataList[id]))
+			// count down:
+			countNum -= 1
+		}
+		// check to see if the 0 and 1 in the array are the same - if so, set 0
+		// to 0:
+		if (kclass[0] == kclass[1]) {
+			kclass[0] = 0
+		}
+		
+		this.bounds = kclass;
+		this.setRanges();
+
+		return kclass; //array of breaks
+	}
+	
+	
+	/**
+	 * Quantile discretization Return an array with bounds : ie array(0, 0.75,
+	 * 1.5, 2.25, 3);
+	 */
+	this.getUniqueValues = function() {
+
+		if (this._nodata())
+			return;
+
+		this.method = _t('unique values');
+		this.is_uniqueValues = true;
+		
+		var tmp = this.sorted(); // display in alphabetical order
+
+		var a = Array();
+
+		for (i = 0; i < this.pop(); i++) {
+			if(!inArray (tmp[i], a))
+				a.push(tmp[i]);
+		}
+		
+		this.bounds = a;
+		
+		return a;
+
+	};
+	
+	
+	/**
+	 * Return the class of a given value.
+	 * For example value : 6
+	 * and bounds array = (0, 4, 8, 12);
+	 * Return 2
+	 */
+	this.getClass = function(value) {
+
+		for(i = 0; i < this.bounds.length; i++) {
+			
+			
+			if(this.is_uniqueValues == true) {
+				if(value == this.bounds[i])
+					return i;
+			} else {
+				if(value <= this.bounds[i + 1]) {
+					return i;
+				}
+			}
+		}
+		
+		return _t("Unable to get value's class.");
+		
+	};
+
+	/**
+	 * Return the ranges array : array('0-0.75', '0.75-1.5', '1.5-2.25',
+	 * '2.25-3');
+	 */
+	this.getRanges = function() {
+		
+		return this.ranges;
+		
+	};
+
+	/**
+	 * Returns the number/index of this.ranges that value falls into
+	 */
+	this.getRangeNum = function(value) {
+		var bounds, i;
+
+		for (i = 0; i < this.ranges.length; i++) {
+			bounds = this.ranges[i].split(/ - /);
+			if (value <= parseFloat(bounds[1])) {
+				return i;
+			}
+		}
+	}
+	
+	/**
+	 * Return an html legend
+	 * 
+	 */
+	this.getHtmlLegend = function(colors, legend, counter, callback) {
+		
+		var cnt= '';
+		
+		if(colors != null) {
+			ccolors = colors;
+		}
+		else {
+			ccolors = this.colors;
+		}
+		
+		if(legend != null) {
+			lg = legend;
+		}
+		else {
+			lg =  'Legend';
+		}
+		
+		if(counter != null) {
+			this.doCount();
+			getcounter = true;
+		}
+		else {
+			getcounter = false;
+		}
+		
+		if(callback != null) {
+			fn = callback;
+		}
+		else {
+			fn = function(o) {return o;};
+		}
+		
+		
+		if(ccolors.length < this.ranges.length) {
+			alert(_t('The number of colors should fit the number of ranges. Exit!'));
+			return;
+		}
+		
+		var content  = '<div class="geostats-legend"><div class="geostats-legend-title">' + _t(lg) + '</div>';
+		
+		if(this.is_uniqueValues == false) {
+			for (i = 0; i < (this.ranges.length); i++) {
+				if(getcounter===true) {
+					cnt = ' <span class="geostats-legend-counter">(' + this.counter[i] + ')</span>';
+				}
+	
+				// check if it has separator or not
+				if(this.ranges[i].indexOf(this.separator) != -1) {
+					var tmp = this.ranges[i].split(this.separator);
+					var el = fn(tmp[0]) + this.legendSeparator + fn(tmp[1]);
+				} else {
+					var el = fn(this.ranges[i]);
+				}
+				content += '<div><div class="geostats-legend-block" style="background-color:' + ccolors[i] + '"></div> ' + el + cnt + '</div>';
+			}
+		} else {
+			// only if classification is done on unique values
+			for (i = 0; i < (this.bounds.length); i++) {
+				if(getcounter===true) {
+					cnt = ' <span class="geostats-legend-counter">(' + this.counter[i] + ')</span>';
+				}
+				var el = fn(this.bounds[i]);
+				content += '<div><div class="geostats-legend-block" style="background-color:' + ccolors[i] + '"></div> ' + el + cnt + '</div>';
+			}
+		}
+    content += '</div>';
+		return content;
+	};
+
+	this.getSortedlist = function() {
+		return this.sorted().join(', ');
+	};
+
+};
\ No newline at end of file
diff --git a/asterix-examples/src/main/resources/tweetbook-demo/static/js/rainbowvis.js b/asterix-examples/src/main/resources/tweetbook-demo/static/js/rainbowvis.js
new file mode 100644
index 0000000..1f444dc
--- /dev/null
+++ b/asterix-examples/src/main/resources/tweetbook-demo/static/js/rainbowvis.js
@@ -0,0 +1,178 @@
+/*
+RainbowVis-JS 
+Released under MIT License
+
+Source: https://github.com/anomal/RainbowVis-JS
+*/
+
+function Rainbow()
+{
+	var gradients = null;
+	var minNum = 0;
+	var maxNum = 100;
+	var colours = ['ff0000', 'ffff00', '00ff00', '0000ff']; 
+	setColours(colours);
+	
+	function setColours (spectrum) 
+	{
+		if (spectrum.length < 2) {
+			throw new Error('Rainbow must have two or more colours.');
+		} else {
+			var increment = (maxNum - minNum)/(spectrum.length - 1);
+			var firstGradient = new ColourGradient();
+			firstGradient.setGradient(spectrum[0], spectrum[1]);
+			firstGradient.setNumberRange(minNum, minNum + increment);
+			gradients = [ firstGradient ];
+			
+			for (var i = 1; i < spectrum.length - 1; i++) {
+				var colourGradient = new ColourGradient();
+				colourGradient.setGradient(spectrum[i], spectrum[i + 1]);
+				colourGradient.setNumberRange(minNum + increment * i, minNum + increment * (i + 1)); 
+				gradients[i] = colourGradient; 
+			}
+
+			colours = spectrum;
+			return this;
+		}
+	}
+
+	this.setColors = this.setColours;
+
+	this.setSpectrum = function () 
+	{
+		setColours(arguments);
+		return this;
+	}
+
+	this.setSpectrumByArray = function (array)
+	{
+		setColours(array);
+        return this;
+	}
+
+	this.colourAt = function (number)
+	{
+		if (isNaN(number)) {
+			throw new TypeError(number + ' is not a number');
+		} else if (gradients.length === 1) {
+			return gradients[0].colourAt(number);
+		} else {
+			var segment = (maxNum - minNum)/(gradients.length);
+			var index = Math.min(Math.floor((Math.max(number, minNum) - minNum)/segment), gradients.length - 1);
+			return gradients[index].colourAt(number);
+		}
+	}
+
+	this.colorAt = this.colourAt;
+
+	this.setNumberRange = function (minNumber, maxNumber)
+	{
+		if (maxNumber > minNumber) {
+			minNum = minNumber;
+			maxNum = maxNumber;
+			setColours(colours);
+		} else {
+			throw new RangeError('maxNumber (' + maxNumber + ') is not greater than minNumber (' + minNumber + ')');
+		}
+		return this;
+	}
+}
+
+function ColourGradient() 
+{
+	var startColour = 'ff0000';
+	var endColour = '0000ff';
+	var minNum = 0;
+	var maxNum = 100;
+
+	this.setGradient = function (colourStart, colourEnd)
+	{
+		startColour = getHexColour(colourStart);
+		endColour = getHexColour(colourEnd);
+	}
+
+	this.setNumberRange = function (minNumber, maxNumber)
+	{
+		if (maxNumber > minNumber) {
+			minNum = minNumber;
+			maxNum = maxNumber;
+		} else {
+			throw new RangeError('maxNumber (' + maxNumber + ') is not greater than minNumber (' + minNumber + ')');
+		}
+	}
+
+	this.colourAt = function (number)
+	{
+		return calcHex(number, startColour.substring(0,2), endColour.substring(0,2)) 
+			+ calcHex(number, startColour.substring(2,4), endColour.substring(2,4)) 
+			+ calcHex(number, startColour.substring(4,6), endColour.substring(4,6));
+	}
+	
+	function calcHex(number, channelStart_Base16, channelEnd_Base16)
+	{
+		var num = number;
+		if (num < minNum) {
+			num = minNum;
+		}
+		if (num > maxNum) {
+			num = maxNum;
+		} 
+		var numRange = maxNum - minNum;
+		var cStart_Base10 = parseInt(channelStart_Base16, 16);
+		var cEnd_Base10 = parseInt(channelEnd_Base16, 16); 
+		var cPerUnit = (cEnd_Base10 - cStart_Base10)/numRange;
+		var c_Base10 = Math.round(cPerUnit * (num - minNum) + cStart_Base10);
+		return formatHex(c_Base10.toString(16));
+	}
+
+	formatHex = function (hex) 
+	{
+		if (hex.length === 1) {
+			return '0' + hex;
+		} else {
+			return hex;
+		}
+	} 
+	
+	function isHexColour(string)
+	{
+		var regex = /^#?[0-9a-fA-F]{6}$/i;
+		return regex.test(string);
+	}
+
+	function getHexColour(string)
+	{
+		if (isHexColour(string)) {
+			return string.substring(string.length - 6, string.length);
+		} else {
+			var colourNames =
+			[
+				['red', 'ff0000'],
+				['lime', '00ff00'],
+				['blue', '0000ff'],
+				['yellow', 'ffff00'],
+				['orange', 'ff8000'],
+				['aqua', '00ffff'],
+				['fuchsia', 'ff00ff'],
+				['white', 'ffffff'],
+				['black', '000000'],
+				['gray', '808080'],
+				['grey', '808080'],
+				['silver', 'c0c0c0'],
+				['maroon', '800000'],
+				['olive', '808000'],
+				['green', '008000'],
+				['teal', '008080'],
+				['navy', '000080'],
+				['purple', '800080']
+			];
+			for (var i = 0; i < colourNames.length; i++) {
+				if (string.toLowerCase() === colourNames[i][0]) {
+					return colourNames[i][1];
+				}
+			}
+			throw new Error(string + ' is not a valid colour.');
+		}
+	}
+}
+
diff --git a/asterix-examples/src/main/resources/tweetbook-demo/static/js/tweetbook.js b/asterix-examples/src/main/resources/tweetbook-demo/static/js/tweetbook.js
new file mode 100755
index 0000000..61ecedb
--- /dev/null
+++ b/asterix-examples/src/main/resources/tweetbook-demo/static/js/tweetbook.js
@@ -0,0 +1,1176 @@
+$(function() {
+
+	// Initialize connection to AsterixDB. Just one connection is needed and contains
+	// logic for connecting to each API endpoint. This object A is reused throughout the
+	// code but does not store information about any individual API call.
+	A = new AsterixDBConnection({
+
+	    // We will be using the twitter dataverse, which we can configure either like this
+	    // or by following our AsterixDBConnection with a dataverse call, like so:
+	    // A = new AsterixDBConnection().dataverse("twitter");
+	    "dataverse" : "twitter",
+
+	    // Due to the setup of this demo using the Bottle server, it is necessary to change the
+	    // default endpoint of API calls. The proxy server handles the call to http://localhost:19002
+	    // for us, and we reconfigure this connection to connect to the proxy server.
+	    "endpoint_root" : "/",
+
+	    // Finally, we want to make our error function nicer so that we show errors with a call to the
+	    // reportUserMessage function. Update the "error" property to do that.
+	    "error" : function(data) {
+	                // For an error, data will look like this:
+	                // {
+	                //     "error-code" : [error-number, error-text]
+	                //     "stacktrace" : ...stack trace...
+	                //     "summary"    : ...summary of error...
+	                // }
+	                // We will report this as an Asterix REST API Error, an error code, and a reason message.
+	                // Note the method signature: reportUserMessage(message, isPositiveMessage, target). We will provide
+	                // an error message to display, a positivity value (false in this case, errors are bad), and a
+	                // target html element in which to report the message.
+	                var showErrorMessage = "Asterix Error #" + data["error-code"][0] + ": " + data["error-code"][1];
+	                var isPositive = false;
+	                var showReportAt = "report-message";
+
+	                reportUserMessage(showErrorMessage, isPositive, showReportAt);
+	              }
+	});
+
+    // This little bit of code manages period checks of the asynchronous query manager,
+    // which holds onto handles asynchornously received. We can set the handle update
+    // frequency using seconds, and it will let us know when it is ready.
+    var intervalID = setInterval(
+        function() {
+            asynchronousQueryIntervalUpdate();
+        },
+        asynchronousQueryGetInterval()
+    );
+
+    // Legend Container
+    // Create a rainbow from a pretty color scheme.
+    // http://www.colourlovers.com/palette/292482/Terra
+    rainbow = new Rainbow();
+    rainbow.setSpectrum("#E8DDCB", "#CDB380", "#036564", "#033649", "#031634");
+    buildLegend();
+
+    // Initialization of UI Tabas
+    initDemoPrepareTabs();
+
+    // UI Elements - Creates Map, Location Auto-Complete, Selection Rectangle
+    var mapOptions = {
+        center: new google.maps.LatLng(38.89, -77.03),
+        zoom: 4,
+        mapTypeId: google.maps.MapTypeId.ROADMAP,
+        streetViewControl: false,
+        draggable : false,
+        mapTypeControl: false
+    };
+    map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
+
+    var input = document.getElementById('location-text-box');
+    var autocomplete = new google.maps.places.Autocomplete(input);
+    autocomplete.bindTo('bounds', map);
+
+    google.maps.event.addListener(autocomplete, 'place_changed', function() {
+        var place = autocomplete.getPlace();
+        if (place.geometry.viewport) {
+            map.fitBounds(place.geometry.viewport);
+        } else {
+            map.setCenter(place.geometry.location);
+            map.setZoom(17);  // Why 17? Because it looks good.
+        }
+        var address = '';
+        if (place.address_components) {
+            address = [(place.address_components[0] && place.address_components[0].short_name || ''),
+              (place.address_components[1] && place.address_components[1].short_name || ''),
+              (place.address_components[2] && place.address_components[2].short_name || '') ].join(' ');
+        }
+    });
+
+    // Drawing Manager for selecting map regions. See documentation here:
+    // https://developers.google.com/maps/documentation/javascript/reference#DrawingManager
+    rectangleManager = new google.maps.drawing.DrawingManager({
+        drawingMode : google.maps.drawing.OverlayType.RECTANGLE,
+        drawingControl : false,
+        rectangleOptions : {
+            strokeWeight: 1,
+            clickable: false,
+            editable: true,
+            strokeColor: "#2b3f8c",
+            fillColor: "#2b3f8c",
+            zIndex: 1
+        }
+    });
+    rectangleManager.setMap(map);
+    selectionRectangle = null;
+
+    // Drawing Manager: Just one editable rectangle!
+    google.maps.event.addListener(rectangleManager, 'rectanglecomplete', function(rectangle) {
+        selectionRectangle = rectangle;
+        rectangleManager.setDrawingMode(null);
+    });
+
+    // Initialize data structures
+    APIqueryTracker = {};
+    asyncQueryManager = {};
+    map_cells = [];
+    map_tweet_markers = [];
+    map_info_windows = {};
+    review_mode_tweetbooks = [];
+
+    getAllDataverseTweetbooks();
+    initDemoUIButtonControls();
+
+    google.maps.event.addListenerOnce(map, 'idle', function(){
+        // Show tutorial tab only the first time the map is loaded
+        $('#mode-tabs a:first').tab('show');
+    });
+
+});
+
+function initDemoUIButtonControls() {
+
+    // Explore Mode - Update Sliders
+    var updateSliderDisplay = function(event, ui) {
+        if (event.target.id == "grid-lat-slider") {
+            $("#gridlat").text(""+ui.value);
+        } else {
+          $("#gridlng").text(""+ui.value);
+        }
+    };
+    sliderOptions = {
+        max: 10,
+        min: 2.0,
+        step: .1,
+        value: 3.0,
+        slidechange: updateSliderDisplay,
+        slide: updateSliderDisplay,
+        start: updateSliderDisplay,
+        stop: updateSliderDisplay
+    };
+    $("#gridlat").text(""+sliderOptions.value);
+    $("#gridlng").text(""+sliderOptions.value);
+    $(".grid-slider").slider(sliderOptions);
+
+    // Explore Mode - Query Builder Date Pickers
+    var dateOptions = {
+        dateFormat: "yy-mm-dd",
+        defaultDate: "2012-01-02",
+        navigationAsDateFormat: true,
+        constrainInput: true
+    };
+    var start_dp = $("#start-date").datepicker(dateOptions);
+    start_dp.val(dateOptions.defaultDate);
+    dateOptions['defaultDate'] = "2012-12-31";
+    var end_dp= $("#end-date").datepicker(dateOptions);
+    end_dp.val(dateOptions.defaultDate);
+
+    // Explore Mode: Toggle Selection/Location Search
+    $('#selection-button').on('change', function (e) {
+        $("#location-text-box").attr("disabled", "disabled");
+        rectangleManager.setMap(map);
+        if (selectionRectangle) {
+            selectionRectangle.setMap(null);
+            selectionRectangle = null;
+        } else {
+            rectangleManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
+        }
+    });
+    $('#location-button').on('change', function (e) {
+        $("#location-text-box").removeAttr("disabled");
+        selectionRectangle.setMap(null);
+        rectangleManager.setMap(null);
+        rectangleManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
+    });
+    $("#selection-button").trigger("click");
+
+    // Review Mode: New Tweetbook
+    $('#new-tweetbook-button').on('click', function (e) {
+        onCreateNewTweetBook($('#new-tweetbook-entry').val());
+
+        $('#new-tweetbook-entry').val("");
+        $('#new-tweetbook-entry').attr("placeholder", "Name a new tweetbook");
+    });
+
+    // Explore Mode - Clear Button
+    $("#clear-button").click(mapWidgetResetMap);
+
+    // Explore Mode: Query Submission
+    $("#submit-button").on("click", function () {
+
+        $("#report-message").html('');
+        $("#submit-button").attr("disabled", true);
+        rectangleManager.setDrawingMode(null);
+
+        var kwterm = $("#keyword-textbox").val();
+        var startdp = $("#start-date").datepicker("getDate");
+        var enddp = $("#end-date").datepicker("getDate");
+        var startdt = $.datepicker.formatDate("yy-mm-dd", startdp)+"T00:00:00Z";
+        var enddt = $.datepicker.formatDate("yy-mm-dd", enddp)+"T23:59:59Z";
+
+        var formData = {
+            "keyword": kwterm,
+            "startdt": startdt,
+            "enddt": enddt,
+            "gridlat": $("#grid-lat-slider").slider("value"),
+            "gridlng": $("#grid-lng-slider").slider("value")
+        };
+
+        // Get Map Bounds
+        var bounds;
+        if ($('#selection-label').hasClass("active") && selectionRectangle) {
+            bounds = selectionRectangle.getBounds();
+        } else {
+            bounds = map.getBounds();
+        }
+
+        var swLat = Math.abs(bounds.getSouthWest().lat());
+        var swLng = Math.abs(bounds.getSouthWest().lng());
+        var neLat = Math.abs(bounds.getNorthEast().lat());
+        var neLng = Math.abs(bounds.getNorthEast().lng());
+
+        formData["swLat"] = Math.min(swLat, neLat);
+        formData["swLng"] = Math.max(swLng, neLng);
+        formData["neLat"] = Math.max(swLat, neLat);
+        formData["neLng"] = Math.min(swLng, neLng);
+
+        var build_tweetbook_mode = "synchronous";
+        if ($('#asbox').is(":checked")) {
+            build_tweetbook_mode = "asynchronous";
+        }
+
+        var f = buildAQLQueryFromForm(formData);
+
+        APIqueryTracker = {
+            "query" : "use dataverse twitter;\n" + f.val(),
+            "data" : formData
+        };
+
+        if (build_tweetbook_mode == "synchronous") {
+            A.query(f.val(), tweetbookQuerySyncCallback, build_tweetbook_mode);
+        } else {
+            A.query(f.val(), tweetbookQueryAsyncCallback, build_tweetbook_mode);
+        }
+
+        // Clears selection rectangle on query execution, rather than waiting for another clear call.
+        if (selectionRectangle) {
+            selectionRectangle.setMap(null);
+            selectionRectangle = null;
+        }
+    });
+}
+
+/**
+* Builds AsterixDB REST Query from explore mode form.
+*/
+function buildAQLQueryFromForm(parameters) {
+
+    var bounds = {
+        "ne" : { "lat" : parameters["neLat"], "lng" : -1*parameters["neLng"]},
+		"sw" : { "lat" : parameters["swLat"], "lng" : -1*parameters["swLng"]}
+    };
+
+    var rectangle =
+        new FunctionExpression("create-rectangle",
+            new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
+            new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
+
+    // You can chain these all together, but let's take them one at a time.
+    // Let's start with a ForClause. Here we go through each tweet $t in the
+    // dataset TweetMessageShifted.
+    var aql = new FLWOGRExpression()
+        .ForClause("$t", new AExpression("dataset TweetMessagesShifted"));
+
+    // We know we have bounds for our region, so we can add that LetClause next.
+    aql = aql.LetClause("$region", rectangle);
+
+    // Now, let's change it up. The keyword term doesn't always show up, so it might be blank.
+    // We'll attach a new let clause for it, and then a WhereClause.
+    if (parameters["keyword"].length > 0) {
+        aql = aql
+                .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
+                .WhereClause().and(
+                    new FunctionExpression("spatial-intersect", "$t.sender-location", "$region"),
+                    new AExpression('$t.send-time > datetime("' + parameters["startdt"] + '")'),
+                    new AExpression('$t.send-time < datetime("' + parameters["enddt"] + '")'),
+                    new FunctionExpression("contains", "$t.message-text", "$keyword")
+                );
+    } else {
+        aql = aql
+                .WhereClause().and(
+                    new FunctionExpression("spatial-intersect", "$t.sender-location", "$region"),
+                    new AExpression('$t.send-time > datetime("' + parameters["startdt"] + '")'),
+                    new AExpression('$t.send-time < datetime("' + parameters["enddt"] + '")')
+                );
+    }
+
+    // Finally, we'll group our results into spatial cells.
+    aql = aql.GroupClause(
+                "$c",
+                new FunctionExpression("spatial-cell", "$t.sender-location",
+                new FunctionExpression("create-point", "24.5", "-125.5"),
+                parameters["gridlat"].toFixed(1), parameters["gridlng"].toFixed(1)),
+                "with",
+                "$t"
+            );
+
+    // ...and return a resulting cell and a count of results in that cell.
+    aql = aql.ReturnClause({ "cell" : "$c", "count" : "count($t)" });
+
+    return aql;
+}
+
+/**
+* getAllDataverseTweetbooks
+*
+* Returns all datasets of type TweetbookEntry, populates review_mode_tweetbooks
+*/
+function getAllDataverseTweetbooks(fn_tweetbooks) {
+
+    // This creates a query to the Metadata for datasets of type
+    // TweetBookEntry. Note that if we throw in a WhereClause (commented out below)
+    // there is an odd error. This is being fixed and will be removed from this demo.
+    var getTweetbooksQuery = new FLWOGRExpression()
+        .ForClause("$ds", new AExpression("dataset Metadata.Dataset"))
+        //.WhereClause(new AExpression('$ds.DataTypeName = "TweetbookEntry"'))
+        .ReturnClause({
+            "DataTypeName" : "$ds.DataTypeName",
+            "DatasetName" : "$ds.DatasetName"
+        });
+
+    // Now create a function that will be called when tweetbooks succeed.
+    // In this case, we want to parse out the results object from the Asterix
+    // REST API response.
+    var tweetbooksSuccess = function(r) {
+        // Parse tweetbook metadata results
+        $.each(r.results, function(i, data) {
+            if ($.parseJSON(data)["DataTypeName"] == "TweetbookEntry") {
+                review_mode_tweetbooks.push($.parseJSON(data)["DatasetName"]);
+            }
+        });
+
+        // Now, if any tweetbooks already exist, opulate review screen.
+        $('#review-tweetbook-titles').html('');
+        $.each(review_mode_tweetbooks, function(i, tweetbook) {
+            addTweetBookDropdownItem(tweetbook);
+        });
+    };
+
+    // Now, we are ready to run a query.
+    A.meta(getTweetbooksQuery.val(), tweetbooksSuccess);
+}
+
+/**
+* Checks through each asynchronous query to see if they are ready yet
+*/
+function asynchronousQueryIntervalUpdate() {
+    for (var handle_key in asyncQueryManager) {
+        if (!asyncQueryManager[handle_key].hasOwnProperty("ready")) {
+            asynchronousQueryGetAPIQueryStatus( asyncQueryManager[handle_key]["handle"], handle_key );
+        }
+    }
+}
+
+/**
+* Returns current time interval to check for asynchronous query readiness
+* @returns  {number}    milliseconds between asychronous query checks
+*/
+function asynchronousQueryGetInterval() {
+    var seconds = 10;
+    return seconds * 1000;
+}
+
+/**
+* Retrieves status of an asynchronous query, using an opaque result handle from API
+* @param    {Object}    handle, an object previously returned from an async call
+* @param    {number}    handle_id, the integer ID parsed from the handle object
+*/
+function asynchronousQueryGetAPIQueryStatus (handle, handle_id) {
+
+    A.query_status(
+        {
+            "handle" : JSON.stringify(handle)
+        },
+        function (res) {
+            if (res["status"] == "SUCCESS") {
+                // We don't need to check if this one is ready again, it's not going anywhere...
+                // Unless the life cycle of handles has changed drastically
+                asyncQueryManager[handle_id]["ready"] = true;
+
+                // Indicate success.
+                $('#handle_' + handle_id).removeClass("btn-disabled").prop('disabled', false).addClass("btn-success");
+            }
+        }
+     );
+}
+
+/**
+* On-success callback after async API query
+* @param    {object}    res, a result object containing an opaque result handle to Asterix
+*/
+function tweetbookQueryAsyncCallback(res) {
+
+    // Parse handle, handle id and query from async call result
+    var handle_query = APIqueryTracker["query"];
+    var handle = res;
+    var handle_id = res["handle"].toString().split(',')[0];
+
+    // Add to stored map of existing handles
+    asyncQueryManager[handle_id] = {
+        "handle" : handle,
+        "query" : handle_query, // This will show up when query control button is clicked.
+        "data" : APIqueryTracker["data"]
+    };
+
+    // Create a container for this async query handle
+    $('<div/>')
+        .css("margin-left", "1em")
+        .css("margin-bottom", "1em")
+        .css("display", "block")
+        .attr({
+            "class" : "btn-group",
+            "id" : "async_container_" + handle_id
+        })
+        .appendTo("#async-handle-controls");
+
+    // Adds the main button for this async handle
+    var handle_action_button = '<button class="btn btn-disabled" id="handle_' + handle_id + '">Handle ' + handle_id + '</button>';
+    $('#async_container_' + handle_id).append(handle_action_button);
+    $('#handle_' + handle_id).prop('disabled', true);
+    $('#handle_' + handle_id).on('click', function (e) {
+
+        // make sure query is ready to be run
+        if (asyncQueryManager[handle_id]["ready"]) {
+
+            APIqueryTracker = {
+                "query" : asyncQueryManager[handle_id]["query"],
+                "data"  : asyncQueryManager[handle_id]["data"]
+            };
+
+            if (!asyncQueryManager[handle_id].hasOwnProperty("result")) {
+                // Generate new Asterix Core API Query
+                A.query_result(
+                    { "handle" : JSON.stringify(asyncQueryManager[handle_id]["handle"]) },
+                    function(res) {
+                        asyncQueryManager[handle_id]["result"] = res;
+
+                        var resultTransform = {
+                            "results" : res.results
+                        };
+
+                        tweetbookQuerySyncCallback(resultTransform);
+                    }
+                );
+            } else {
+
+                var resultTransform = {
+                    "results" : asyncQueryManager[handle_id]["result"].results
+                };
+
+                tweetbookQuerySyncCallback(resultTransform);
+            }
+        }
+    });
+
+    // Adds a removal button for this async handle
+    var asyncDeleteButton = addDeleteButton(
+        "trashhandle_" + handle_id,
+        "async_container_" + handle_id,
+        function (e) {
+            $('#async_container_' + handle_id).remove();
+            delete asyncQueryManager[handle_id];
+        }
+    );
+
+    $('#async_container_' + handle_id).append('<br/>');
+
+    $("#submit-button").attr("disabled", false);
+}
+
+/**
+* A spatial data cleaning and mapping call
+* @param    {Object}    res, a result object from a tweetbook geospatial query
+*/
+function tweetbookQuerySyncCallback(res) {
+    // First, we check if any results came back in.
+    // If they didn't, return.
+    if (!res.hasOwnProperty("results")) {
+        reportUserMessage("Oops, no results found for those parameters.", false, "report-message");
+        return;
+    }
+
+    // Initialize coordinates and weights, to store
+    // coordinates of map cells and their weights
+    var coordinates = [];
+    var maxWeight = 0;
+    var minWeight = Number.MAX_VALUE;
+
+    // Parse resulting JSON objects. Here is an example record:
+    // { "cell": rectangle("21.5,-98.5 24.5,-95.5"), "count": 78i64 }
+    $.each(res.results, function(i, data) {
+
+        // We need to clean the JSON a bit to parse it properly in javascript
+        var cleanRecord = $.parseJSON(data
+                            .replace('rectangle(', '')
+                            .replace(')', '')
+                            .replace('i64', ''));
+
+        var recordCount = cleanRecord["count"];
+        var rectangle = cleanRecord["cell"]
+                            .replace(' ', ',')
+                            .split(',')
+                            .map( parseFloat );
+
+        // Now, using the record count and coordinates, we can create a
+        // coordinate system for this spatial cell.
+        var coordinate = {
+            "latSW"     : rectangle[0],
+            "lngSW"     : rectangle[1],
+            "latNE"     : rectangle[2],
+            "lngNE"     : rectangle[3],
+            "weight"    : recordCount
+        };
+
+        // We track the minimum and maximum weight to support our legend.
+        maxWeight = Math.max(coordinate["weight"], maxWeight);
+        minWeight = Math.min(coordinate["weight"], minWeight);
+
+        // Save completed coordinate and move to next one.
+        coordinates.push(coordinate);
+    });
+
+    triggerUIUpdate(coordinates, maxWeight, minWeight);
+}
+
+/**
+* Triggers a map update based on a set of spatial query result cells
+* @param    [Array]     mapPlotData, an array of coordinate and weight objects
+* @param    [Array]     plotWeights, a list of weights of the spatial cells - e.g., number of tweets
+*/
+function triggerUIUpdate(mapPlotData, maxWeight, minWeight) {
+    /** Clear anything currently on the map **/
+    mapWidgetClearMap();
+
+    // Initialize info windows.
+    map_info_windows = {};
+
+    $.each(mapPlotData, function (m) {
+
+        var point_center = new google.maps.LatLng(
+            (mapPlotData[m].latSW + mapPlotData[m].latNE)/2.0,
+            (mapPlotData[m].lngSW + mapPlotData[m].lngNE)/2.0);
+
+        var map_circle_options = {
+            center: point_center,
+            anchorPoint: point_center,
+            radius: mapWidgetComputeCircleRadius(mapPlotData[m], maxWeight),
+            map: map,
+            fillOpacity: 0.85,
+            fillColor: "#" + rainbow.colourAt(Math.ceil(100 * (mapPlotData[m].weight / maxWeight))),
+            clickable: true
+        };
+        var map_circle = new google.maps.Circle(map_circle_options);
+        map_circle.val = mapPlotData[m];
+
+        map_info_windows[m] = new google.maps.InfoWindow({
+            content: mapPlotData[m].weight + " tweets",
+            position: point_center
+        });
+
+        // Clicking on a circle drills down map to that value, hovering over it displays a count
+        // of tweets at that location.
+        google.maps.event.addListener(map_circle, 'click', function (event) {
+            $.each(map_info_windows, function(i) {
+                map_info_windows[i].close();
+            });
+            onMapPointDrillDown(map_circle.val);
+        });
+
+        google.maps.event.addListener(map_circle, 'mouseover', function(event) {
+            if (!map_info_windows[m].getMap()) {
+                map_info_windows[m].setPosition(map_circle.center);
+                map_info_windows[m].open(map);
+            }
+        });
+        google.maps.event.addListener(map, 'mousemove', function(event) {
+            map_info_windows[m].close();
+
+        });
+
+        // Add this marker to global marker cells
+        map_cells.push(map_circle);
+
+        // Show legend
+        $("#legend-min").html(minWeight);
+        $("#legend-max").html(maxWeight);
+        $("#rainbow-legend-container").show();
+    });
+}
+
+/**
+* prepares an Asterix API query to drill down in a rectangular spatial zone
+*
+* @params {object} marker_borders a set of bounds for a region from a previous api result
+*/
+function onMapPointDrillDown(marker_borders) {
+
+    var zoneData = APIqueryTracker["data"];
+
+    var zswBounds = new google.maps.LatLng(marker_borders.latSW, marker_borders.lngSW);
+    var zneBounds = new google.maps.LatLng(marker_borders.latNE, marker_borders.lngNE);
+
+    var zoneBounds = new google.maps.LatLngBounds(zswBounds, zneBounds);
+    zoneData["swLat"] = zoneBounds.getSouthWest().lat();
+    zoneData["swLng"] = zoneBounds.getSouthWest().lng();
+    zoneData["neLat"] = zoneBounds.getNorthEast().lat();
+    zoneData["neLng"] = zoneBounds.getNorthEast().lng();
+    var zB = {
+        "sw" : {
+            "lat" : zoneBounds.getSouthWest().lat(),
+            "lng" : zoneBounds.getSouthWest().lng()
+        },
+        "ne" : {
+            "lat" : zoneBounds.getNorthEast().lat(),
+            "lng" : zoneBounds.getNorthEast().lng()
+        }
+    };
+
+    mapWidgetClearMap();
+
+    var customBounds = new google.maps.LatLngBounds();
+    var zoomSWBounds = new google.maps.LatLng(zoneData["swLat"], zoneData["swLng"]);
+    var zoomNEBounds = new google.maps.LatLng(zoneData["neLat"], zoneData["neLng"]);
+    customBounds.extend(zoomSWBounds);
+    customBounds.extend(zoomNEBounds);
+    map.fitBounds(customBounds);
+
+    var df = getDrillDownQuery(zoneData, zB);
+
+    APIqueryTracker = {
+        "query_string" : "use dataverse twitter;\n" + df.val(),
+        "marker_path" : "static/img/mobile2.png"
+    };
+
+    A.query(df.val(), onTweetbookQuerySuccessPlot);
+}
+
+/**
+* Generates an aql query for zooming on a spatial cell and obtaining tweets contained therein.
+* @param parameters, the original query parameters
+* @param bounds, the bounds of the zone to zoom in on.
+*/
+function getDrillDownQuery(parameters, bounds) {
+
+    var zoomRectangle = new FunctionExpression("create-rectangle",
+        new FunctionExpression("create-point", bounds["sw"]["lat"], bounds["sw"]["lng"]),
+        new FunctionExpression("create-point", bounds["ne"]["lat"], bounds["ne"]["lng"]));
+
+    var drillDown = new FLWOGRExpression()
+        .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
+        .LetClause("$region", zoomRectangle);
+
+    if (parameters["keyword"].length == 0) {
+        drillDown = drillDown
+                        .WhereClause().and(
+                            new FunctionExpression('spatial-intersect', '$t.sender-location', '$region'),
+                            new AExpression().set('$t.send-time > datetime("' + parameters["startdt"] + '")'),
+                            new AExpression().set('$t.send-time < datetime("' + parameters["enddt"] + '")')
+                        );
+    } else {
+        drillDown = drillDown
+                        .LetClause("$keyword", new AExpression('"' + parameters["keyword"] + '"'))
+                        .WhereClause().and(
+                            new FunctionExpression('spatial-intersect', '$t.sender-location', '$region'),
+                            new AExpression().set('$t.send-time > datetime("' + parameters["startdt"] + '")'),
+                            new AExpression().set('$t.send-time < datetime("' + parameters["enddt"] + '")'),
+                            new FunctionExpression('contains', '$t.message-text', '$keyword')
+                        );
+    }
+
+    drillDown = drillDown
+                    .ReturnClause({
+                        "tweetId" : "$t.tweetid",
+                        "tweetText" : "$t.message-text",
+                        "tweetLoc" : "$t.sender-location"
+                    });
+
+    return drillDown;
+}
+
+/**
+* Given a location where a tweet exists, opens a modal to examine or update a tweet's content.
+* @param t0, a tweetobject that has a location, text, id, and optionally a comment.
+*/
+function onDrillDownAtLocation(tO) {
+
+    var tweetId = tO["tweetEntryId"];
+    var tweetText = tO["tweetText"];
+
+    // First, set tweet in drilldown modal to be this tweet's text
+    $('#modal-body-tweet').html('Tweet #' + tweetId + ": " + tweetText);
+
+    // Next, empty any leftover tweetbook comments or error/success messages
+    $("#modal-body-add-to").val('');
+    $("#modal-body-add-note").val('');
+    $("#modal-body-message-holder").html("");
+
+    // Next, if there is an existing tweetcomment reported, show it.
+    if (tO.hasOwnProperty("tweetComment")) {
+
+        // Show correct panel
+        $("#modal-existing-note").show();
+        $("#modal-save-tweet-panel").hide();
+
+        // Fill in existing tweet comment
+        $("#modal-body-tweet-note").val(tO["tweetComment"]);
+
+        // Change Tweetbook Badge
+        $("#modal-current-tweetbook").val(APIqueryTracker["active_tweetbook"]);
+
+        // Add deletion functionality
+        $("#modal-body-trash-icon").on('click', function () {
+            // Send comment deletion to asterix
+            var deleteTweetCommentOnId = '"' + tweetId + '"';
+            var toDelete = new DeleteStatement(
+                "$mt",
+                APIqueryTracker["active_tweetbook"],
+                new AExpression("$mt.tweetid = " + deleteTweetCommentOnId.toString())
+            );
+            A.update(
+                toDelete.val()
+            );
+
+            // Hide comment from map
+            $('#drilldown_modal').modal('hide');
+
+            // Replot tweetbook
+            onPlotTweetbook(APIqueryTracker["active_tweetbook"]);
+        });
+
+    } else {
+        // Show correct panel
+        $("#modal-existing-note").hide();
+        $("#modal-save-tweet-panel").show();
+
+        // Now, when adding a comment on an available tweet to a tweetbook
+        $('#save-comment-tweetbook-modal').unbind('click');
+        $("#save-comment-tweetbook-modal").on('click', function(e) {
+
+            // Stuff to save about new comment
+            var save_metacomment_target_tweetbook = $("#modal-body-add-to").val();
+            var save_metacomment_target_comment = '"' + $("#modal-body-add-note").val() + '"';
+            var save_metacomment_target_tweet = '"' + tweetId + '"';
+
+            // Make sure content is entered, and then save this comment.
+            if ($("#modal-body-add-note").val() == "") {
+
+                reportUserMessage("Please enter a comment about the tweet", false, "report-message");
+
+            } else if ($("#modal-body-add-to").val() == "") {
+
+                reportUserMessage("Please enter a tweetbook.", false, "report-message");
+
+            } else {
+
+                // Check if tweetbook exists. If not, create it.
+                if (!(existsTweetbook(save_metacomment_target_tweetbook))) {
+                    onCreateNewTweetBook(save_metacomment_target_tweetbook);
+                }
+
+                var toInsert = new InsertStatement(
+                    save_metacomment_target_tweetbook,
+                    {
+                        "tweetid" : save_metacomment_target_tweet.toString(),
+                        "comment-text" : save_metacomment_target_comment
+                    }
+                );
+
+                A.update(toInsert.val(), function () {
+                    var successMessage = "Saved comment on <b>Tweet #" + tweetId +
+                        "</b> in dataset <b>" + save_metacomment_target_tweetbook + "</b>.";
+                    reportUserMessage(successMessage, true, "report-message");
+
+                    $("#modal-body-add-to").val('');
+                    $("#modal-body-add-note").val('');
+                    $('#save-comment-tweetbook-modal').unbind('click');
+
+                    // Close modal
+                    $('#drilldown_modal').modal('hide');
+                });
+            }
+        });
+    }
+}
+
+/**
+* Adds a new tweetbook entry to the menu and creates a dataset of type TweetbookEntry.
+*/
+function onCreateNewTweetBook(tweetbook_title) {
+
+    var tweetbook_title = tweetbook_title.split(' ').join('_');
+
+    A.ddl(
+        "create dataset " + tweetbook_title + "(TweetbookEntry) primary key tweetid;",
+        function () {}
+    );
+
+    if (!(existsTweetbook(tweetbook_title))) {
+        review_mode_tweetbooks.push(tweetbook_title);
+        addTweetBookDropdownItem(tweetbook_title);
+    }
+}
+
+/**
+* Removes a tweetbook from both demo and from
+* dataverse metadata.
+*/
+function onDropTweetBook(tweetbook_title) {
+
+    // AQL Call
+    A.ddl(
+        "drop dataset " + tweetbook_title + " if exists;",
+        function () {}
+    );
+
+    // Removes tweetbook from review_mode_tweetbooks
+    var remove_position = $.inArray(tweetbook_title, review_mode_tweetbooks);
+    if (remove_position >= 0) review_mode_tweetbooks.splice(remove_position, 1);
+
+    // Clear UI with review tweetbook titles
+    $('#review-tweetbook-titles').html('');
+    for (r in review_mode_tweetbooks) {
+        addTweetBookDropdownItem(review_mode_tweetbooks[r]);
+    }
+}
+
+/**
+* Adds a tweetbook action button to the dropdown box in review mode.
+* @param tweetbook, a string representing a tweetbook
+*/
+function addTweetBookDropdownItem(tweetbook) {
+    // Add placeholder for this tweetbook
+    $('<div/>')
+        .attr({
+            "class" : "btn-group",
+            "id" : "rm_holder_" + tweetbook
+        }).appendTo("#review-tweetbook-titles");
+
+    // Add plotting button for this tweetbook
+    var plot_button = '<button class="btn btn-default" id="rm_plotbook_' + tweetbook + '">' + tweetbook + '</button>';
+    $("#rm_holder_" + tweetbook).append(plot_button);
+    $("#rm_plotbook_" + tweetbook).width("200px");
+    $("#rm_plotbook_" + tweetbook).on('click', function(e) {
+        onPlotTweetbook(tweetbook);
+    });
+
+    // Add trash button for this tweetbook
+    var onTrashTweetbookButton = addDeleteButton(
+        "rm_trashbook_" + tweetbook,
+        "rm_holder_" + tweetbook,
+        function(e) {
+            onDropTweetBook(tweetbook);
+        }
+    );
+}
+
+/**
+* Generates AsterixDB query to plot existing tweetbook commnets
+* @param tweetbook, a string representing a tweetbook
+*/
+function onPlotTweetbook(tweetbook) {
+
+    // Clear map for this one
+    mapWidgetClearMap();
+
+    var plotTweetQuery = new FLWOGRExpression()
+        .ForClause("$t", new AExpression("dataset TweetMessagesShifted"))
+        .ForClause("$m", new AExpression("dataset " + tweetbook))
+        .WhereClause(new AExpression("$m.tweetid = $t.tweetid"))
+        .ReturnClause({
+            "tweetId" : "$m.tweetid",
+            "tweetText" : "$t.message-text",
+            "tweetCom" : "$m.comment-text",
+            "tweetLoc" : "$t.sender-location"
+        });
+
+    APIqueryTracker = {
+        "query_string" : "use dataverse twitter;\n" + plotTweetQuery.val(),
+        "marker_path" : "static/img/mobile_green2.png",
+        "active_tweetbook" : tweetbook
+    };
+
+    A.query(plotTweetQuery.val(), onTweetbookQuerySuccessPlot);
+}
+
+/**
+* Given an output response set of tweet data,
+* prepares markers on map to represent individual tweets.
+* @param res, a JSON Object
+*/
+function onTweetbookQuerySuccessPlot (res) {
+
+    // First, we check if any results came back in.
+    // If they didn't, return.
+    if (!res.hasOwnProperty("results")) {
+        reportUserMessage("Oops, no data matches this query.", false, "report-message");
+        return;
+    }
+
+    // Parse out tweet Ids, texts, and locations
+    var tweets = [];
+    var al = 1;
+
+    $.each(res.results, function(i, data) {
+
+        // First, clean up the data
+        //{ "tweetId": "100293", "tweetText": " like at&t the touch-screen is amazing", "tweetLoc": point("31.59,-84.23") }
+        // We need to turn the point object at the end into a string
+        var json = $.parseJSON(data
+                                .replace(': point(',': ')
+                                .replace(') }', ' }'));
+
+        // Now, we construct a tweet object
+        var tweetData = {
+            "tweetEntryId" : parseInt(json.tweetId),
+            "tweetText" : json.tweetText,
+            "tweetLat" : json.tweetLoc.split(",")[0],
+            "tweetLng" : json.tweetLoc.split(",")[1]
+        };
+
+        // If we are parsing out tweetbook data with comments, we need to check
+        // for those here as well.
+        if (json.hasOwnProperty("tweetCom")) {
+            tweetData["tweetComment"] = json.tweetCom;
+        }
+
+        tweets.push(tweetData)
+    });
+
+    // Create a marker for each tweet
+    $.each(tweets, function(i, t) {
+        // Create a phone marker at tweet's position
+        var map_tweet_m = new google.maps.Marker({
+            position: new google.maps.LatLng(tweets[i]["tweetLat"], tweets[i]["tweetLng"]),
+            map: map,
+            icon: APIqueryTracker["marker_path"],
+            clickable: true,
+        });
+        map_tweet_m["test"] = t;
+
+        // Open Tweet exploration window on click
+        google.maps.event.addListener(map_tweet_m, 'click', function (event) {
+            onClickTweetbookMapMarker(map_tweet_markers[i]["test"]);
+        });
+
+        // Add marker to index of tweets
+        map_tweet_markers.push(map_tweet_m);
+    });
+}
+
+/**
+* Checks if a tweetbook exists
+* @param tweetbook, a String
+*/
+function existsTweetbook(tweetbook) {
+    if (parseInt($.inArray(tweetbook, review_mode_tweetbooks)) == -1) {
+        return false;
+    } else {
+        return true;
+    }
+}
+
+/**
+* When a marker is clicked on in the tweetbook, it will launch a modal
+* view to examine or edit the appropriate tweet
+*/
+function onClickTweetbookMapMarker(t) {
+    onDrillDownAtLocation(t)
+    $('#drilldown_modal').modal();
+}
+
+/**
+* Explore mode: Initial map creation and screen alignment
+*/
+function onOpenExploreMap () {
+    var explore_column_height = $('#explore-well').height();
+    var right_column_width = $('#right-col').width();
+    $('#map_canvas').height(explore_column_height + "px");
+    $('#map_canvas').width(right_column_width + "px");
+
+    $('#review-well').height(explore_column_height + "px");
+    $('#review-well').css('max-height', explore_column_height + "px");
+    $('#right-col').height(explore_column_height + "px");
+}
+
+/**
+* initializes demo - adds some extra events when review/explore
+* mode are clicked, initializes tabs, aligns map box, moves
+* active tab to about tab
+*/
+function initDemoPrepareTabs() {
+
+    // Tab behavior for About, Explore, and Demo
+    $('#mode-tabs a').click(function (e) {
+        e.preventDefault()
+        $(this).tab('show')
+    })
+
+    // Explore mode should show explore-mode query-builder UI
+    $('#explore-mode').click(function(e) {
+        $('#review-well').hide();
+        $('#explore-well').show();
+        rectangleManager.setMap(map);
+        rectangleManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
+        mapWidgetResetMap();
+    });
+
+    // Review mode should show review well and hide explore well
+    $('#review-mode').click(function(e) {
+        $('#explore-well').hide();
+        $('#review-well').show();
+        mapWidgetResetMap();
+        rectangleManager.setMap(null);
+        rectangleManager.setDrawingMode(null);
+    });
+
+    // Does some alignment necessary for the map canvas
+    onOpenExploreMap();
+}
+
+/**
+* Creates a delete icon button using default trash icon
+* @param    {String}    id, id for this element
+* @param    {String}    attachTo, id string of an element to which I can attach this button.
+* @param    {Function}  onClick, a function to fire when this icon is clicked
+*/
+function addDeleteButton(iconId, attachTo, onClick) {
+
+    var trashIcon = '<button class="btn btn-default" id="' + iconId + '"><span class="glyphicon glyphicon-trash"></span></button>';
+    $('#' + attachTo).append(trashIcon);
+
+    // When this trash button is clicked, the function is called.
+    $('#' + iconId).on('click', onClick);
+}
+
+/**
+* Creates a message and attaches it to data management area.
+* @param    {String}    message, a message to post
+* @param    {Boolean}   isPositiveMessage, whether or not this is a positive message.
+* @param    {String}    target, the target div to attach this message.
+*/
+function reportUserMessage(message, isPositiveMessage, target) {
+    // Clear out any existing messages
+    $('#' + target).html('');
+
+    // Select appropriate alert-type
+    var alertType = "alert-success";
+    if (!isPositiveMessage) {
+        alertType = "alert-danger";
+    }
+
+    // Append the appropriate message
+    $('<div/>')
+        .attr("class", "alert " + alertType)
+        .html('<button type="button" class="close" data-dismiss="alert">&times;</button>' + message)
+        .appendTo('#' + target);
+}
+
+/**
+* mapWidgetResetMap
+*
+* [No Parameters]
+*
+* Clears ALL map elements - plotted items, overlays, then resets position
+*/
+function mapWidgetResetMap() {
+
+    mapWidgetClearMap();
+
+    // Reset map center and zoom
+    map.setCenter(new google.maps.LatLng(38.89, -77.03));
+    map.setZoom(4);
+
+    // Selection button
+    $("#selection-button").trigger("click");
+    rectangleManager.setMap(map);
+    rectangleManager.setDrawingMode(google.maps.drawing.OverlayType.RECTANGLE);
+}
+
+/**
+* mapWidgetClearMap
+* Removes data/markers
+*/
+function mapWidgetClearMap() {
+
+    // Remove previously plotted data/markers
+    for (c in map_cells) {
+        map_cells[c].setMap(null);
+    }
+    map_cells = [];
+
+    $.each(map_info_windows, function(i) {
+        map_info_windows[i].close();
+    });
+    map_info_windows = {};
+
+    for (m in map_tweet_markers) {
+        map_tweet_markers[m].setMap(null);
+    }
+    map_tweet_markers = [];
+
+    // Hide legend
+    $("#rainbow-legend-container").hide();
+
+    // Reenable submit button
+    $("#submit-button").attr("disabled", false);
+
+    // Hide selection rectangle
+    if (selectionRectangle) {
+        selectionRectangle.setMap(null);
+        selectionRectangle = null;
+    }
+}
+
+/**
+* buildLegend
+*
+* Generates gradient, button action for legend bar
+*/
+function buildLegend() {
+
+    // Fill in legend area with colors
+    var gradientColor;
+
+    for (i = 0; i<100; i++) {
+        //$("#rainbow-legend-container").append("" + rainbow.colourAt(i));
+        $("#legend-gradient").append('<div style="display:inline-block; max-width:2px; background-color:#' + rainbow.colourAt(i) +';">&nbsp;</div>');
+    }
+}
+
+/**
+* Computes radius for a given data point from a spatial cell
+* @param    {Object}    keys => ["latSW" "lngSW" "latNE" "lngNE" "weight"]
+* @returns  {number}    radius between 2 points in metres
+*/
+function mapWidgetComputeCircleRadius(spatialCell, wLimit) {
+
+    // Define Boundary Points
+    var point_center = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
+    var point_left = new google.maps.LatLng((spatialCell.latSW + spatialCell.latNE)/2.0, spatialCell.lngSW);
+    var point_top = new google.maps.LatLng(spatialCell.latNE, (spatialCell.lngSW + spatialCell.lngNE)/2.0);
+
+    // Circle scale modifier =
+    var scale = 425 + 425*(spatialCell.weight / wLimit);
+
+    // Return proportionate value so that circles mostly line up.
+    return scale * Math.min(distanceBetweenPoints(point_center, point_left), distanceBetweenPoints(point_center, point_top));
+}
+
+/**
+* Calculates the distance between two latlng locations in km, using Google Geometry API.
+* @param p1, a LatLng
+* @param p2, a LatLng
+*/
+function distanceBetweenPoints (p1, p2) {
+  return 0.001 * google.maps.geometry.spherical.computeDistanceBetween(p1, p2);
+};