<commit_before>/*
 *  asf -- Ada Server Faces
 *  Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2016 Stephane Carrez
 *  Written by Stephane Carrez (Stephane.Carrez@gmail.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
var ASF = {};

(function () {
    ASF.Actions = {
        update: function(id, action) {
            $(id).html(action.data);
        },
        prepend: function(id, action) {
            $(id).prepend(action.data);
        },
        append: function(id, action) {
            $(id).append(action.data);
        },
        show: function(id, action) {
            $(id).show('slow');
        },
        hide: function(id, action) {
            $(id).hide('slow');
        },
        "delete": function(id, action) {
            $(id).remove();
        },
        removeClass: function(id, action) {
            $(id).removeClass(action.data);
        },
        addClass: function(id, action) {
            $(id).addClass(action.data);
        },
        fadeIn: function(id, action) {
            $(id).fadeIn('slow');
        },
        fadeOut: function(id, action) {
            $(id).fadeOut('slow');
        },
        slideUp: function(id, action) {
            $(id).slideUp('slow');
        },
        slideDown: function(id, action) {
            $(id).slideDown('slow');
        },
        closeDialog: function(id, action) {
            $(id).dialog('close');
        },
        closePopup: function(id, action) {
            $(id).popup('close');
        },
        redirect: function(id, action) {
            document.location = action.url;
        },
        message: function(id, action) {
            ASF.Message(node, action.id, action.data);
        },
        notification: function(id, action) {
	        ASF.Message(node, action.id, action.data, 'asf-notification').message('autoClose');
        },
        get: function(id, action) {
            ASF.Update(null, action.url, id);
        },
        script: function(id, action) {
            try {
                eval(action.script);
            } catch (e) {
                alert(e);
            }
        },
        clear: function(id, action) {
	        $(id).each(function() {
                switch (this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
                    break;
                }
            });
        }
    };

    /**
     * Execute the AJAX response action represented by the JSON object action.
     *
     * @param node the current node
     * @param action the JSON action object
     */
    ASF.ExecuteOne = function(node, action) {
        var id = action.id ? action.id : node;
        if (action.child) {
            id = $(id).children(action.child);
        }
        if (ASF.Actions.hasOwnProperty(action.action)) {
            var handler = ASF.Actions[action.action];
            handler(id, action);
        }
    };

    ASF.Execute = function(node, data) {
        if (data) {
            for (var i = 0; i < data.length; i++) {
                ASF.ExecuteOne(node, data[i]);
            }
        }
    };

    /**
     * Handle an AJAX operation that failed.
     */
    ASF.AjaxError = function(jqXHDR, status, error, node) {
        var contentType = jqXHDR.getResponseHeader('Content-type');
        if (contentType && contentType.match(/^application\/json(;.*)?$/i)) {
            var data = $.parseJSON(jqXHDR.responseText);
            ASF.Execute(node, data);
        } else {
            ASF.Message(node, null, "Operation failed");
        }
    };

    /**
     * Update the target container with the content of the AJAX GET request
     * on the given URL.  The target parameter is optional.
     *
     * @param node the current element
     * @param url the URL to fetch using an HTTP GET
     * @param target the optional target element
     * @param complete an optional function called when the response is received
     */
    ASF.Update = function(node, url, target, complete) {
        /* Find the container to update */
        var d;
        if (target != null) {
            d = $(target);
        } else {
            d = $(node);
            if (!d.is('.asf-container')) {
                d = d.parent('.asf-container');
            }
        }
        if (d.length > 0) {
            /* Perform the HTTP GET */
            jQuery.ajax({
                url: url,
                context: document.body,
                success: function(data, status, jqXHDR) {
                    var contentType = jqXHDR.getResponseHeader('Content-type');
                    if (contentType == null) {
                        contentType = "text/html";
                    }
                    if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                        d.html(jqXHDR.responseText);

                    } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                        ASF.Execute(d, data);
                    }
                    if (complete != null) {
                        complete(d, jqXHDR);
                    }
               },
               error: function(jqXHDR, status, error) {
                   ASF.AjaxError(jqXHDR, status, error, d);
               }
            });
        }
    };

    /**
     * Submit the current form.  The node element refers to the element being clicked.
     * From that element, we can identify the form to submit.  The element to refresh upon
     * the form submit is an outer element that should have the asf-container class.
     * If not such element as parent node, the parent node of the form is used.
     *
     * After the form is submitted, the response is executed if it is a JSON response.
     * If the response is an HTML content, the container element is refreshed with it.
     *
     * @param node the current element
     * @param url the URL to fetch using an HTTP GET
     * @param target the optional target element
     */
    ASF.Submit = function(node) {
        /* Find the form and container to update */
        var f = $(node).closest("form");
        var d = $(f);
        if (!d.is('.asf-container,ui-dialog-content')) {
            d = d.closest('.asf-container,.ui-dialog-content');
        }
        if (d.length == 0) {
            d = $(f).parent();
        }
        if (d.length > 0) {
            var params;
            var params = $(f).serialize();
            var url = $(f).attr('action');

            if (node.tagName == 'a' || node.tagName == 'A') {
                params = node.id + "=1&" + $(f).serialize();
            } else {
                params = node.name + "=1&" + $(f).serialize();
            }
            /**
             * Send notification on form to indicate a form submit is now in progress.
             */
            $(f).triggerHandler("notifySubmit", d);

            /* Perform the HTTP POST */
            jQuery.ajax({
                type: "POST",
                url: url,
                data: params,
                context: document.body,
                success: function(data, status, jqXHDR) {
                    var contentType = jqXHDR.getResponseHeader('Content-type');
                    if (contentType == null) {
                        contentType = "text/html";
                    }
                    $(f).triggerHandler("successSubmit", d);
                    if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                        d.fadeOut("fast", function() {
                            d.html(jqXHDR.responseText);
                            d.fadeIn("fast");
                        });

                    } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                        ASF.Execute(d, data);
                    }
               },
               error: function(jqXHDR, status, error) {
                   ASF.AjaxError(jqXHDR, status, error, d);
               }
            });
        }
        return false;
    };

    /**
     * Perform an HTTP POST on the given URL.
     *
     * @param node the node element that will be updated by default on the AJAX response.
     * @param url the HTTP URL.
     * @param params the HTTP POST parameters.
     */
    ASF.Post = function(node, url, params) {
        /* Perform the HTTP POST */
        jQuery.ajax({
            type: "POST",
            url: url,
            data: params,
            context: document.body,
            success: function(data, status, jqXHDR) {
                var contentType = jqXHDR.getResponseHeader('Content-type');
                if (contentType == null) {
                    contentType = "text/html";
                }
                if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                    $(node).html(jqXHDR.responseText);

                } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                    ASF.Execute(node, data);
                }
            },
            error: function(jqXHDR, status, error) {
                ASF.AjaxError(jqXHDR, status, error, node);
            }
        });
        return false;
    };

    /**
     * Open a popup form attached to the node element and which is filled by
     * the given URL.
     *
     * The popup form is created when the page refered by <tt>url</tt> is fetched.
     * It can be referenced by the unique id given in <tt>id</tt>.
     *
     * @param node the node element where the popup is attached to.
     * @param id the popup unique id.
     * @param url the URL to fetch to fill the popup content.
     * @param params the popup creation parameters.
     */
    ASF.Popup = function(node, id, url, params) {
        jQuery.ajax({
            type: "GET",
            url: url,
            context: document.body,
            success: function(data, status, jqXHDR) {
                var contentType = jqXHDR.getResponseHeader('Content-type');
                if (contentType == null) {
                    contentType = "text/html";
                }
                var div = $('#' + id);
                if (div.length == 0) {
                    div = document.createElement("div");
                    div.id = id;
                    $(document.body).append($(div));
                }
                if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                    $(div).html(jqXHDR.responseText);

                } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                    ASF.Execute(div, data);
                }
                $(div).popup(params).popup('open');
                $(div).find('form:not(.filter) :input:visible:first').focus();
            },
            error: function(jqXHDR, status, error) {
                ASF.AjaxError(jqXHDR, status, error, node);
            }
        });
        return false;
    };

    /**
     * Open a dialog box and fetch the dialog content from the given URI.
     *
     * @param node the current element
     * @param id the dialog id
     * @param url the URL to fetch using an HTTP GET
     * @param params the optional dialog options
     */
    ASF.OpenDialog = function(node, id, url, params) {
        var div = $(id);
        if (div.length > 0) {
            return false;
        }

        div = document.createElement("div");
        div.id = id;
        div = $(div);

        var d = $(document.body);
        if (d.length == 0) {
            return false;
        }

        $(d).append($(div));

        /* Perform the HTTP GET */
        jQuery.ajax({
            url: url,
            context: document.body,
            success: function(data, status, jqXHDR) {
                var contentType = jqXHDR.getResponseHeader('Content-type');
                if (contentType == null) {
                    contentType = "text/html";
                }
                if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                    $(div).dialog({
                        autoOpen: false,
                        show: "blind",
                        hide: "explode",
                        minWidth: 600,
                        close: function() {
                            $(div).dialog('destroy');
                            $(div).remove();
                            if (params && params.close) {
                                params.close(node);
                            }
                        }
                     });

                     $(div).html(jqXHDR.responseText);

                     /**
                      * Extract a title from the inner form to setup the dialog box.
                      */
                     var dTitle, dBox = $(div).children('div');
                     if (dBox.length == 0) {
                        dTitle = $(div).children('h2');
                     } else {
                        dTitle = $(dBox).children('h2');
                     }
                     if (dTitle.length > 0) {
                        $(div).dialog("option", "title", dTitle.html());
                        dTitle.remove();
                     } else {
                        dTitle = $(div).children('div').attr('title');
                        if (dTitle != null) {
                            $(div).dialog("option", "title", dTitle );
                            /* $(div).attr('title', title); */
                        }
                     }
                     $(div).dialog('open');

                } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                    ASF.Execute(node, data);
                }
            },
            error: function(jqXHDR, status, error) {
                ASF.AjaxError(jqXHDR, status, error, d);
            }
        });
        return false;
    };

    /**
     * Close the dialog box identified by the given identifier.
     *
     * @param id the dialog box identifier
     */
    ASF.CloseDialog = function(id) {
        $('#' + id).dialog('close');
        return false;
    };

    /**
     * Create and display a popup message near the node element.
     *
     * @param node the element giving the location of the message
     * @param id the message id or null
     * @param message the HTML message content
     * @param css the optional CSS to set on the message content.
     */
    ASF.Message = function(node, id, message, css) {
        if (!id) {
            id = "#asf-message";
        }
        var div = $(id);
        if (div.length == 0) {
            div = document.createElement("div");
            div.id = id.substring(1);
            $(document.body).append($(div));
        } else {
            $(div).removeClass();
        }
        if (css) {
            $(div).addClass(css);
        }
        return $(div).html(message).message({}).message("attachment", node);
    };
})();

<commit_msg>Add some documentation<commit_after>/*
 *  asf -- Ada Server Faces
 *  Copyright (C) 2009, 2010, 2011, 2012, 2013, 2015, 2016 Stephane Carrez
 *  Written by Stephane Carrez (Stephane.Carrez@gmail.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

/**
 * @class Ada Server Faces namespace.
 */
var ASF = {};

(function () {
    ASF.Actions = {
        update: function(id, action) {
            $(id).html(action.data);
        },
        prepend: function(id, action) {
            $(id).prepend(action.data);
        },
        append: function(id, action) {
            $(id).append(action.data);
        },
        show: function(id, action) {
            $(id).show('slow');
        },
        hide: function(id, action) {
            $(id).hide('slow');
        },
        "delete": function(id, action) {
            $(id).remove();
        },
        removeClass: function(id, action) {
            $(id).removeClass(action.data);
        },
        addClass: function(id, action) {
            $(id).addClass(action.data);
        },
        fadeIn: function(id, action) {
            $(id).fadeIn('slow');
        },
        fadeOut: function(id, action) {
            $(id).fadeOut('slow');
        },
        slideUp: function(id, action) {
            $(id).slideUp('slow');
        },
        slideDown: function(id, action) {
            $(id).slideDown('slow');
        },
        closeDialog: function(id, action) {
            $(id).dialog('close');
        },
        closePopup: function(id, action) {
            $(id).popup('close');
        },
        redirect: function(id, action) {
            document.location = action.url;
        },
        message: function(id, action) {
            ASF.Message(node, action.id, action.data);
        },
        notification: function(id, action) {
	        ASF.Message(node, action.id, action.data, 'asf-notification').message('autoClose');
        },
        get: function(id, action) {
            ASF.Update(null, action.url, id);
        },
        script: function(id, action) {
            try {
                eval(action.script);
            } catch (e) {
                alert(e);
            }
        },
        clear: function(id, action) {
	        $(id).each(function() {
                switch (this.type) {
                case 'password':
                case 'select-multiple':
                case 'select-one':
                case 'text':
                case 'textarea':
                    $(this).val('');
                    break;
                case 'checkbox':
                case 'radio':
                    this.checked = false;
                    break;
                }
            });
        }
    };

    /**
     * Execute the AJAX response action represented by the JSON object action.
     *
     * @param node the current node
     * @param action the JSON action object
     */
    ASF.ExecuteOne = function(node, action) {
        var id = action.id ? action.id : node;
        if (action.child) {
            id = $(id).children(action.child);
        }
        if (ASF.Actions.hasOwnProperty(action.action)) {
            var handler = ASF.Actions[action.action];
            handler(id, action);
        }
    };

    ASF.Execute = function(node, data) {
        if (data) {
            for (var i = 0; i < data.length; i++) {
                ASF.ExecuteOne(node, data[i]);
            }
        }
    };

    /**
     * Handle an AJAX operation that failed.
     */
    ASF.AjaxError = function(jqXHDR, status, error, node) {
        var contentType = jqXHDR.getResponseHeader('Content-type');
        if (contentType && contentType.match(/^application\/json(;.*)?$/i)) {
            var data = $.parseJSON(jqXHDR.responseText);
            ASF.Execute(node, data);
        } else {
            ASF.Message(node, null, "Operation failed");
        }
    };

    /**
     * Update the target container with the content of the AJAX GET request
     * on the given URL.  The target parameter is optional.
     *
     * @param node the current element
     * @param url the URL to fetch using an HTTP GET
     * @param target the optional target element
     * @param complete an optional function called when the response is received
     */
    ASF.Update = function(node, url, target, complete) {
        /* Find the container to update */
        var d;
        if (target != null) {
            d = $(target);
        } else {
            d = $(node);
            if (!d.is('.asf-container')) {
                d = d.parent('.asf-container');
            }
        }
        if (d.length > 0) {
            /* Perform the HTTP GET */
            jQuery.ajax({
                url: url,
                context: document.body,
                success: function(data, status, jqXHDR) {
                    var contentType = jqXHDR.getResponseHeader('Content-type');
                    if (contentType == null) {
                        contentType = "text/html";
                    }
                    if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                        d.html(jqXHDR.responseText);

                    } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                        ASF.Execute(d, data);
                    }
                    if (complete != null) {
                        complete(d, jqXHDR);
                    }
               },
               error: function(jqXHDR, status, error) {
                   ASF.AjaxError(jqXHDR, status, error, d);
               }
            });
        }
    };

    /**
     * Submit the current form.  The node element refers to the element being clicked.
     * From that element, we can identify the form to submit.  The element to refresh upon
     * the form submit is an outer element that should have the asf-container class.
     * If not such element as parent node, the parent node of the form is used.
     *
     * After the form is submitted, the response is executed if it is a JSON response.
     * If the response is an HTML content, the container element is refreshed with it.
     *
     * @param node the current element
     * @param url the URL to fetch using an HTTP GET
     * @param target the optional target element
     */
    ASF.Submit = function(node) {
        /* Find the form and container to update */
        var f = $(node).closest("form");
        var d = $(f);
        if (!d.is('.asf-container,ui-dialog-content')) {
            d = d.closest('.asf-container,.ui-dialog-content');
        }
        if (d.length == 0) {
            d = $(f).parent();
        }
        if (d.length > 0) {
            var params;
            var params = $(f).serialize();
            var url = $(f).attr('action');

            if (node.tagName == 'a' || node.tagName == 'A') {
                params = node.id + "=1&" + $(f).serialize();
            } else {
                params = node.name + "=1&" + $(f).serialize();
            }
            /**
             * Send notification on form to indicate a form submit is now in progress.
             */
            $(f).triggerHandler("notifySubmit", d);

            /* Perform the HTTP POST */
            jQuery.ajax({
                type: "POST",
                url: url,
                data: params,
                context: document.body,
                success: function(data, status, jqXHDR) {
                    var contentType = jqXHDR.getResponseHeader('Content-type');
                    if (contentType == null) {
                        contentType = "text/html";
                    }
                    $(f).triggerHandler("successSubmit", d);
                    if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                        d.fadeOut("fast", function() {
                            d.html(jqXHDR.responseText);
                            d.fadeIn("fast");
                        });

                    } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                        ASF.Execute(d, data);
                    }
               },
               error: function(jqXHDR, status, error) {
                   ASF.AjaxError(jqXHDR, status, error, d);
               }
            });
        }
        return false;
    };

    /**
     * Perform an HTTP POST on the given URL.
     *
     * @param node the node element that will be updated by default on the AJAX response.
     * @param url the HTTP URL.
     * @param params the HTTP POST parameters.
     */
    ASF.Post = function(node, url, params) {
        /* Perform the HTTP POST */
        jQuery.ajax({
            type: "POST",
            url: url,
            data: params,
            context: document.body,
            success: function(data, status, jqXHDR) {
                var contentType = jqXHDR.getResponseHeader('Content-type');
                if (contentType == null) {
                    contentType = "text/html";
                }
                if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                    $(node).html(jqXHDR.responseText);

                } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                    ASF.Execute(node, data);
                }
            },
            error: function(jqXHDR, status, error) {
                ASF.AjaxError(jqXHDR, status, error, node);
            }
        });
        return false;
    };

    /**
     * Open a popup form attached to the node element and which is filled by
     * the given URL.
     *
     * The popup form is created when the page refered by <tt>url</tt> is fetched.
     * It can be referenced by the unique id given in <tt>id</tt>.
     *
     * @param node the node element where the popup is attached to.
     * @param id the popup unique id.
     * @param url the URL to fetch to fill the popup content.
     * @param params the popup creation parameters.
     */
    ASF.Popup = function(node, id, url, params) {
        jQuery.ajax({
            type: "GET",
            url: url,
            context: document.body,
            success: function(data, status, jqXHDR) {
                var contentType = jqXHDR.getResponseHeader('Content-type');
                if (contentType == null) {
                    contentType = "text/html";
                }
                var div = $('#' + id);
                if (div.length == 0) {
                    div = document.createElement("div");
                    div.id = id;
                    $(document.body).append($(div));
                }
                if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                    $(div).html(jqXHDR.responseText);

                } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                    ASF.Execute(div, data);
                }
                $(div).popup(params).popup('open');
                $(div).find('form:not(.filter) :input:visible:first').focus();
            },
            error: function(jqXHDR, status, error) {
                ASF.AjaxError(jqXHDR, status, error, node);
            }
        });
        return false;
    };

    /**
     * Open a dialog box and fetch the dialog content from the given URI.
     *
     * @param node the current element
     * @param id the dialog id
     * @param url the URL to fetch using an HTTP GET
     * @param params the optional dialog options
     */
    ASF.OpenDialog = function(node, id, url, params) {
        var div = $(id);
        if (div.length > 0) {
            return false;
        }

        div = document.createElement("div");
        div.id = id;
        div = $(div);

        var d = $(document.body);
        if (d.length == 0) {
            return false;
        }

        $(d).append($(div));

        /* Perform the HTTP GET */
        jQuery.ajax({
            url: url,
            context: document.body,
            success: function(data, status, jqXHDR) {
                var contentType = jqXHDR.getResponseHeader('Content-type');
                if (contentType == null) {
                    contentType = "text/html";
                }
                if (contentType.match(/^text\/(html|xml)(;.*)?$/i)) {
                    $(div).dialog({
                        autoOpen: false,
                        show: "blind",
                        hide: "explode",
                        minWidth: 600,
                        close: function() {
                            $(div).dialog('destroy');
                            $(div).remove();
                            if (params && params.close) {
                                params.close(node);
                            }
                        }
                     });

                     $(div).html(jqXHDR.responseText);

                     /**
                      * Extract a title from the inner form to setup the dialog box.
                      */
                     var dTitle, dBox = $(div).children('div');
                     if (dBox.length == 0) {
                        dTitle = $(div).children('h2');
                     } else {
                        dTitle = $(dBox).children('h2');
                     }
                     if (dTitle.length > 0) {
                        $(div).dialog("option", "title", dTitle.html());
                        dTitle.remove();
                     } else {
                        dTitle = $(div).children('div').attr('title');
                        if (dTitle != null) {
                            $(div).dialog("option", "title", dTitle );
                            /* $(div).attr('title', title); */
                        }
                     }
                     $(div).dialog('open');

                } else if (contentType.match(/^application\/json(;.*)?$/i)) {
                    ASF.Execute(node, data);
                }
            },
            error: function(jqXHDR, status, error) {
                ASF.AjaxError(jqXHDR, status, error, d);
            }
        });
        return false;
    };

    /**
     * Close the dialog box identified by the given identifier.
     *
     * @param id the dialog box identifier
     */
    ASF.CloseDialog = function(id) {
        $('#' + id).dialog('close');
        return false;
    };

    /**
     * Create and display a popup message near the node element.
     *
     * @param node the element giving the location of the message
     * @param id the message id or null
     * @param message the HTML message content
     * @param css the optional CSS to set on the message content.
     */
    ASF.Message = function(node, id, message, css) {
        if (!id) {
            id = "#asf-message";
        }
        var div = $(id);
        if (div.length == 0) {
            div = document.createElement("div");
            div.id = id.substring(1);
            $(document.body).append($(div));
        } else {
            $(div).removeClass();
        }
        if (css) {
            $(div).addClass(css);
        }
        return $(div).html(message).message({}).message("attachment", node);
    };
})();

<|endoftext|>


<commit_before>// from http://stackoverflow.com/a/105074/342013
function GUID () {
    var S4 = function () {
        return Math.floor(
                Math.random() * 0x10000 /* 65536 */
            ).toString(16);
    };

    return (
            S4() + S4() + "-" +
            S4() + "-" +
            S4() + "-" +
            S4() + "-" +
            S4() + S4() + S4()
        );
}

function randomQueueName() {
    return "sim.gen-" + jQuery.base64.encode(CryptoJS.MD5(GUID()).words.join()).substr(0, 12);
}

function getProcessing() {
    return Processing.getInstanceById("Simulator");
}

var bound = false;

function bindJavascript() {
    var pjs = getProcessing();
    if(pjs!=null) {
        pjs.bindJavascript(this);
        bound = true;
    }

    if(!bound) setTimeout(bindJavascript, 250);
}

bindJavascript();

var EXCHANGE = 0;
var QUEUE = 1;

function newExchange(name, type) {
    return {
        name: name,
        vhost: "/",
        type: type,
        durable: true,
        auto_delete: false,
        internal: false,
        arguments: []
    };
}

function newQueue(name) {
    return {
        name: name,
        vhost: "/",
        durable: true,
        auto_delete: false,
        arguments: []
    };
}

function newBinding(source, destination, destination_type, routing_key) {
    return {
        source: source,
        vhost: "/",
        destination: destination,
        destination_type: destination_type,
        routing_key: routing_key,
        arguments: []
    };
}

function processBindings(pjs, source, bindings) {
    var ret = [];
    var es = bindings.entrySet().iterator();
    while (es.hasNext()) {
        var me = es.next();
        var destinations = me.getValue();
        for (var i = 0; i < destinations.size(); i++) {
            var dest = destinations.get(i);
            ret.push(newBinding(
                source,
                dest.getLabel(),
                pjs.nodeTypeToString(dest.getType()),
                me.getKey()
            ));
        }
    }
    return ret;
}

function buildExport() {
    var pjs = getProcessing();
    var nodes = pjs.getNodes();
    var toExport = {
        exchanges: [],
        queues: [],
        bindings: []
    };

    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i] != null && (nodes[i].getType() == EXCHANGE || nodes[i].getType() == QUEUE)) {
            var nodeName = nodes[i].getLabel();
            var nodeType = pjs.nodeTypeToString(nodes[i].getType());
            switch(nodes[i].getType()) {
                case EXCHANGE:
                toExport["exchanges"].push(newExchange(nodeName, nodes[i].getExchangeTypeString()));
                toExport["bindings"] = processBindings(pjs, nodeName, nodes[i].getAllBindings());
                break;
                case QUEUE:
                toExport["queues"].push(newQueue(nodeName));
                break;
                default:
                console.log("ignoring: ", pjs.nodeTypeToString(nodes[i].getType()));
            }
        }
    }

    return toExport;
}

function exportNodes() {
    var toExport = buildExport();
    console.log(JSON.stringify(toExport));
}

var exchange_types = {
    direct: 0,
    fanout: 1,
    topic: 2
};

function importNodes(nodes) {
    var sections = 5;
    var pjs = getProcessing();
    var imp_exchanges = {};
    var imp_queues = {};

    jQuery.each(nodes["exchanges"], function(k, v) {
        var x = (pjs.width/sections) * 2; // 2 is the exchange section;
        var y = ((pjs.height-50)/nodes["exchanges"].length+1) * (k+1);
        imp_exchanges[v["name"]] = pjs.addNodeByType(EXCHANGE, v["name"], x, y);
        imp_exchanges[v["name"]].setExchangeType(exchange_types[v["type"]]);
    });

    jQuery.each(nodes["queues"], function(k, v) {
        var x = (pjs.width/sections) * 3; // 3 is the queue section;
        var y = ((pjs.height-50)/nodes["queues"].length+1) * (k+1);
        imp_queues[v["name"]] = pjs.addNodeByType(QUEUE, v["name"], x, y);
        pjs.bindToAnonExchange(imp_queues[v["name"]]);
    });

    jQuery.each(nodes["bindings"], function(k, v) {
        var destination = v.destination_type == "queue" ? imp_queues[v.destination] : imp_exchanges[v.destination];
        var source = imp_exchanges[v.source];
        var routing_key = v.routing_key;
        var binding = pjs.addConnection(destination, source);
        binding.updateBindingKey(routing_key);
    });
}

function getDefinitions() {
    jQuery.getJSON('/definitions', function (data) {
        importNodes(data);
    });
}

function postDefinitions() {
    var definitions = buildExport();
    console.log(definitions);
    jQuery.ajax('/definitions', {
        data: JSON.stringify(definitions),
        contentType: 'application/json',
        type: 'POST',
        success: function (data) {
            console.log(data);
        }
    });
}

jQuery(document).ready(function() {

});<commit_msg>stops rendering if windows is out of focus<commit_after>// from http://stackoverflow.com/a/105074/342013
function GUID () {
    var S4 = function () {
        return Math.floor(
                Math.random() * 0x10000 /* 65536 */
            ).toString(16);
    };

    return (
            S4() + S4() + "-" +
            S4() + "-" +
            S4() + "-" +
            S4() + "-" +
            S4() + S4() + S4()
        );
}

function randomQueueName() {
    return "sim.gen-" + jQuery.base64.encode(CryptoJS.MD5(GUID()).words.join()).substr(0, 12);
}

function getProcessing() {
    return Processing.getInstanceById("Simulator");
}

var bound = false;

function bindJavascript() {
    var pjs = getProcessing();
    if(pjs!=null) {
        pjs.bindJavascript(this);
        bound = true;
    }

    if(!bound) setTimeout(bindJavascript, 250);
}

bindJavascript();

var EXCHANGE = 0;
var QUEUE = 1;

function newExchange(name, type) {
    return {
        name: name,
        vhost: "/",
        type: type,
        durable: true,
        auto_delete: false,
        internal: false,
        arguments: []
    };
}

function newQueue(name) {
    return {
        name: name,
        vhost: "/",
        durable: true,
        auto_delete: false,
        arguments: []
    };
}

function newBinding(source, destination, destination_type, routing_key) {
    return {
        source: source,
        vhost: "/",
        destination: destination,
        destination_type: destination_type,
        routing_key: routing_key,
        arguments: []
    };
}

function processBindings(pjs, source, bindings) {
    var ret = [];
    var es = bindings.entrySet().iterator();
    while (es.hasNext()) {
        var me = es.next();
        var destinations = me.getValue();
        for (var i = 0; i < destinations.size(); i++) {
            var dest = destinations.get(i);
            ret.push(newBinding(
                source,
                dest.getLabel(),
                pjs.nodeTypeToString(dest.getType()),
                me.getKey()
            ));
        }
    }
    return ret;
}

function buildExport() {
    var pjs = getProcessing();
    var nodes = pjs.getNodes();
    var toExport = {
        exchanges: [],
        queues: [],
        bindings: []
    };

    for (var i = 0; i < nodes.length; i++) {
        if (nodes[i] != null && (nodes[i].getType() == EXCHANGE || nodes[i].getType() == QUEUE)) {
            var nodeName = nodes[i].getLabel();
            var nodeType = pjs.nodeTypeToString(nodes[i].getType());
            switch(nodes[i].getType()) {
                case EXCHANGE:
                toExport["exchanges"].push(newExchange(nodeName, nodes[i].getExchangeTypeString()));
                toExport["bindings"] = processBindings(pjs, nodeName, nodes[i].getAllBindings());
                break;
                case QUEUE:
                toExport["queues"].push(newQueue(nodeName));
                break;
                default:
                console.log("ignoring: ", pjs.nodeTypeToString(nodes[i].getType()));
            }
        }
    }

    return toExport;
}

function exportNodes() {
    var toExport = buildExport();
    console.log(JSON.stringify(toExport));
}

var exchange_types = {
    direct: 0,
    fanout: 1,
    topic: 2
};

function importNodes(nodes) {
    var sections = 5;
    var pjs = getProcessing();
    var imp_exchanges = {};
    var imp_queues = {};

    jQuery.each(nodes["exchanges"], function(k, v) {
        var x = (pjs.width/sections) * 2; // 2 is the exchange section;
        var y = ((pjs.height-50)/nodes["exchanges"].length+1) * (k+1);
        imp_exchanges[v["name"]] = pjs.addNodeByType(EXCHANGE, v["name"], x, y);
        imp_exchanges[v["name"]].setExchangeType(exchange_types[v["type"]]);
    });

    jQuery.each(nodes["queues"], function(k, v) {
        var x = (pjs.width/sections) * 3; // 3 is the queue section;
        var y = ((pjs.height-50)/nodes["queues"].length+1) * (k+1);
        imp_queues[v["name"]] = pjs.addNodeByType(QUEUE, v["name"], x, y);
        pjs.bindToAnonExchange(imp_queues[v["name"]]);
    });

    jQuery.each(nodes["bindings"], function(k, v) {
        var destination = v.destination_type == "queue" ? imp_queues[v.destination] : imp_exchanges[v.destination];
        var source = imp_exchanges[v.source];
        var routing_key = v.routing_key;
        var binding = pjs.addConnection(destination, source);
        binding.updateBindingKey(routing_key);
    });
}

function getDefinitions() {
    jQuery.getJSON('/definitions', function (data) {
        importNodes(data);
    });
}

function postDefinitions() {
    var definitions = buildExport();
    console.log(definitions);
    jQuery.ajax('/definitions', {
        data: JSON.stringify(definitions),
        contentType: 'application/json',
        type: 'POST',
        success: function (data) {
            console.log(data);
        }
    });
}

jQuery(document).ready(function() {
   $(window).focus(function() {
       var pjs = getProcessing();
       if (pjs != null) {
           pjs.loop();
       }
   });

   $(window).blur(function() {
       var pjs = getProcessing();
       if (pjs != null) {
           pjs.noLoop();
       }
   });
});<|endoftext|>


<commit_before>
XT.StartupTask.create({
  taskName: "loadSessionSettings",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XT.session.loadSessionObjects(XT.session.SETTINGS, options);
  }
});

XT.StartupTask.create({
  taskName: "loadSessionPrivileges",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XT.session.loadSessionObjects(XT.session.PRIVILEGES, options);
  }
});

XT.StartupTask.create({
  taskName: "loadSessionSchema",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XT.session.loadSessionObjects(XT.session.SCHEMA, options);
  }
});

XT.StartupTask.create({
  taskName: "loadSessionLocale",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XT.session.loadSessionObjects(XT.session.LOCALE, options);
  }
});

XT.StartupTask.create({
  taskName: "loadCurrentUser",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this),
      id: XT.session.details.username
    };
    XM.currentUser = new XM.UserAccountInfo();
    XM.currentUser.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadHonorifics",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.honorifics = new XM.HonorificCollection();
    XM.honorifics.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadCommentTypes",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.commentTypes = new XM.CommentTypeCollection();
    XM.commentTypes.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadCharacteristics",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.characteristics = new XM.CharacteristicCollection();
    XM.characteristics.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadLanguages",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.languages = new XM.LanguageCollection();
    XM.languages.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadLocales",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.locales = new XM.LocaleCollection();
    XM.locales.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadPrivileges",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.privileges = new XM.PrivilegeCollection();
    XM.privileges.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadCurrencies",
  task: function() {
    var that = this,
      options = {};
    options.success = function () {
      enyo.bind(that, "didComplete");
      XM.baseCurrency = _.find(XM.currencies.models, function (currency) {
        return currency.get('isBase');
      });
    };
    XM.currencies = new XM.CurrencyCollection();
    XM.currencies.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadCountries",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.countries = new XM.CountryCollection();
    XM.countries.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadStates",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.states = new XM.StateCollection();
    XM.states.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadUnits",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.units = new XM.UnitCollection();
    XM.units.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadClassCodes",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.classCodes = new XM.ClassCodeCollection();
    XM.classCodes.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadProductCategories",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.productCategories = new XM.ProductCategoryCollection();
    XM.productCategories.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadPriorities",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.priorities = new XM.PriorityCollection();
    XM.priorities.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadIncidentCategories",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.incidentCategories = new XM.IncidentCategoryCollection();
    XM.incidentCategories.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadIncidentResolutions",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.incidentResolutions = new XM.IncidentResolutionCollection();
    XM.incidentResolutions.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadIncidentSeverities",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.incidentSeverities = new XM.IncidentSeverityCollection();
    XM.incidentSeverities.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadOpportunityStages",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.opportunityStages = new XM.OpportunityStageCollection();
    XM.opportunityStages.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadOpportunityTypes",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.opportunityTypes = new XM.OpportunityTypeCollection();
    XM.opportunityTypes.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadOpportunitySources",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.opportunitySources = new XM.OpportunitySourceCollection();
    XM.opportunitySources.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});
<commit_msg>remove dependency on enyo.bind and fix to use consistent implementation pattern<commit_after>
XT.StartupTask.create({
  taskName: "loadSessionSettings",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XT.session.loadSessionObjects(XT.session.SETTINGS, options);
  }
});

XT.StartupTask.create({
  taskName: "loadSessionPrivileges",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XT.session.loadSessionObjects(XT.session.PRIVILEGES, options);
  }
});

XT.StartupTask.create({
  taskName: "loadSessionSchema",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XT.session.loadSessionObjects(XT.session.SCHEMA, options);
  }
});

XT.StartupTask.create({
  taskName: "loadSessionLocale",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XT.session.loadSessionObjects(XT.session.LOCALE, options);
  }
});

XT.StartupTask.create({
  taskName: "loadCurrentUser",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this),
      id: XT.session.details.username
    };
    XM.currentUser = new XM.UserAccountInfo();
    XM.currentUser.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadHonorifics",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.honorifics = new XM.HonorificCollection();
    XM.honorifics.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadCommentTypes",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.commentTypes = new XM.CommentTypeCollection();
    XM.commentTypes.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadCharacteristics",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.characteristics = new XM.CharacteristicCollection();
    XM.characteristics.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadLanguages",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.languages = new XM.LanguageCollection();
    XM.languages.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadLocales",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.locales = new XM.LocaleCollection();
    XM.locales.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadPrivileges",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.privileges = new XM.PrivilegeCollection();
    XM.privileges.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadCurrencies",
  task: function() {
    var options = {
      success: _.bind(function() {
        XM.baseCurrency = _.find(XM.currencies.models, function(currency) {
          return currency.get("isBase");
        });
        this.didComplete();
      }, this)
    };
    XM.currencies = new XM.CurrencyCollection();
    XM.currencies.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadCountries",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.countries = new XM.CountryCollection();
    XM.countries.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadStates",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.states = new XM.StateCollection();
    XM.states.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadUnits",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.units = new XM.UnitCollection();
    XM.units.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadClassCodes",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.classCodes = new XM.ClassCodeCollection();
    XM.classCodes.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadProductCategories",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.productCategories = new XM.ProductCategoryCollection();
    XM.productCategories.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadPriorities",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.priorities = new XM.PriorityCollection();
    XM.priorities.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadIncidentCategories",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.incidentCategories = new XM.IncidentCategoryCollection();
    XM.incidentCategories.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadIncidentResolutions",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.incidentResolutions = new XM.IncidentResolutionCollection();
    XM.incidentResolutions.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadIncidentSeverities",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.incidentSeverities = new XM.IncidentSeverityCollection();
    XM.incidentSeverities.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadOpportunityStages",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.opportunityStages = new XM.OpportunityStageCollection();
    XM.opportunityStages.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadOpportunityTypes",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.opportunityTypes = new XM.OpportunityTypeCollection();
    XM.opportunityTypes.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});

XT.StartupTask.create({
  taskName: "loadOpportunitySources",
  task: function() {
    var options = {
      success: _.bind(this.didComplete, this)
    };
    XM.opportunitySources = new XM.OpportunitySourceCollection();
    XM.opportunitySources.fetch(options);
  },
  waitingList: ["loadSessionSettings","loadSessionSchema","loadSessionPrivileges"]
});
<|endoftext|>


<commit_before><commit_msg>removed logs<commit_after><|endoftext|>


<commit_before>'use strict'
// lets make this into an array like object
// fix key moving! (make it special -- think about context)
var Observable = require('../../observable')
var Base = require('../../base')

var cache = new Observable({
  key: '_cache',
  define: {
    set (val, event) {
      var name = 'cache create: ' + this.path.join('.')
      console.time(name)
      let parent = this._parent
      let subscription = parent && parent._childSub

      if (val instanceof Base) {
        val.each((property, key) => {
          if (property._input !== null) {
            this.setKey(key, property, false)
            let addedProp = this[key]
            if (subscription) {
              for (let i in subscription) {
                let sub = subscription[i]
                let pattern = sub.pattern
                let map = sub.map
                findit(pattern, property, map, addedProp, event)
              }
            }
          }
        })
        val.clearContextUp()
      } else {
        for (let i in val) {
          this.setKey(i, val[i], event)
          // this.parent.clearContextUp()
        }
      }
      console.timeEnd(name)
    },
    filter (val, event) {
      var name = 'cache filter: ' + this.path.join('.')
      console.time(name)
      this.each(function remove (property, key) {
        var field = val[key]
        if (!field || field._input === null) {
          property.remove(event)
        }
      })
      console.timeEnd(name)
    }
  }
})

module.exports = cache.Constructor

function findit (pattern, obs, map, context, event) {
  if (typeof pattern === 'object') {
    for (var i in pattern) {
      let property = obs[i]
      if (property) {
        findit(i === 'val' ? pattern : pattern[i], property, map, context, event)
      }
    }
  } else {
    bindit(map, obs, context, event)
  }
}

function bindit (map, obs, context, event) {
  if (map === true && obs) {
    context.$origin.set(obs, event)
  } else {
    for (let i in map) {
      bindit(map[i], obs, i === 'val' ? context : context[i], event)
    }
  }
}
<commit_msg>removed logs<commit_after>'use strict'
// lets make this into an array like object
// fix key moving! (make it special -- think about context)
var Observable = require('../../observable')
var Base = require('../../base')

var cache = new Observable({
  key: '_cache',
  define: {
    set (val, event) {
      // var name = 'cache create: ' + this.path.join('.')
      // console.time(name)
      let parent = this._parent
      let subscription = parent && parent._childSub

      if (val instanceof Base) {
        val.each((property, key) => {
          if (property._input !== null) {
            this.setKey(key, property, false)
            let addedProp = this[key]
            if (subscription) {
              for (let i in subscription) {
                let sub = subscription[i]
                let pattern = sub.pattern
                let map = sub.map
                findit(pattern, property, map, addedProp, event)
              }
            }
          }
        })
        val.clearContextUp()
      } else {
        for (let i in val) {
          this.setKey(i, val[i], event)
          // this.parent.clearContextUp()
        }
      }
      // console.timeEnd(name)
    },
    filter (val, event) {
      // var name = 'cache filter: ' + this.path.join('.')
      // console.time(name)
      this.each(function remove (property, key) {
        var field = val[key]
        if (!field || field._input === null) {
          property.remove(event)
        }
      })
      // console.timeEnd(name)
    }
  }
})

module.exports = cache.Constructor

function findit (pattern, obs, map, context, event) {
  if (typeof pattern === 'object') {
    for (var i in pattern) {
      let property = obs[i]
      if (property) {
        findit(i === 'val' ? pattern : pattern[i], property, map, context, event)
      }
    }
  } else {
    bindit(map, obs, context, event)
  }
}

function bindit (map, obs, context, event) {
  if (map === true && obs) {
    context.$origin.set(obs, event)
  } else {
    for (let i in map) {
      bindit(map[i], obs, i === 'val' ? context : context[i], event)
    }
  }
}
<|endoftext|>


<commit_before>var overrideTemp = Number(0.0);

function getNewValues( immediate, initial ) {
  var url = "/heating/all_details";
  if( immediate ) {
    url = url + "/no_wait";
  }
  var qry = $.ajax({
    type: "GET",
    url: url,
    dataType: "json",
    cache: false
  })
    .done( function( data ) {
      processNewValues( data );
    })
    .always( function( data, textStatus, jqXHR ) {
    $( "#goneoutuntil" ).clockTimePicker({
      precision: 10,
      afternoonHoursInOuterCircle: true,
      minimum: moment().add( 1, 'hours' ).format( "HH:mm" ),
      required: true,
      onChange:( function( newValue, oldValue ) {
        var newTime = moment();
        var hours = newValue.substring( 0, 2 );
        var minutes = newValue.substring( 3, 5 );
        newTime.hour(hours);
        newTime.minute(minutes);
        newTime.second(0);
        newTime.millisecond(0);
        $.ajax({
          type: "GET",
          url: "/heating/gone_out_until/" + newTime.format()
        })
        .done( function () { getNewValues( true, false ) } )
    })
  });
      if ( initial )
        setTimeout( function() { getNewValues( false, initial )}, 55000 );
    });
}

function processNewValues( data ) {
  for ( var key in data.temps ) {
    $("#"+key+"temp").html( data.temps[key].toFixed(1) + "°" );
  }

  if ( data.heating ) {
    $( "#heatingstatus" ).removeClass( "bgwhite" ).addClass( "bgred" ).text( "Heating: On" );
  } else {
    $( "#heatingstatus" ).removeClass( "bgred" ).addClass( "bgwhite" ).text( "Heating: Off" );
  }

  if ( data.preheat ) {
    $( "#preheatstatus" ).removeClass( "bgwhite" ).addClass( "bgorange" ).text( "Preheat: On" );
  } else {
    $( "#preheatstatus" ).removeClass( "bgorange" ).addClass( "bgwhite" ).text( "Preheat: Off" );
  }

  if (!isNaN(parseFloat(data.currentsetpoint)) && !isNaN(parseFloat(data.override))) {
    var currentsetpoint = Number(data.currentsetpoint.toFixed(1));
    overrideTemp = Number(data.override.toFixed(1));

    if ( overrideTemp > 0 ) {
      currentsetpoint = currentsetpoint + "+" + overrideTemp + "°";
    } else if ( overrideTemp < 0 ) {
      currentsetpoint = currentsetpoint + overrideTemp + "°";
    } else {
      currentsetpoint = currentsetpoint + "°";
    }
    $( "#currentsetpoint" ).html( currentsetpoint );

    $( "#override" ).html( "Override by " + overrideTemp + "°" );
  }

  if ( data.nextsetpoint ) {
    $( "#nextsetpoint" ).html( data.nextsetpoint.toFixed(1) + "°" );
  } else {
    $( "#nextsetpoint" ).text( "Unknown" ) ;
  }

  if ( data.nexteventstart ) {
    var nexteventstart = new moment( data.nexteventstart );
    $( "#nexteventstart" ).text( nexteventstart.format( "DD/MM/YYYY HH:mm" ));
  } else {
    $( "#nexteventstart" ).text( "Unknown" );
  }

  var goneOutUntil = "";
  if ( data.goneoutuntil ) {
    goneOutUntil = moment( data.goneoutuntil );
    $( "#goneoutuntil" ).val( goneOutUntil.format( "HH:mm" ) );
  } else {
    $( "#goneoutuntil" ).val( "" );
  }
}

$( document ).ready( function () {
  $( "#decrease" ).click( function() {
    overrideTemp -= 0.5;
    $.ajax({
      type: "GET",
      url: "/heating/override/" + overrideTemp
    })
      .done( function () { getNewValues( true, false ) } );
  });

  $( "#increase" ).click( function() {
    overrideTemp += 0.5;
    $.ajax({
      type: "GET",
      url: "/heating/override/" + overrideTemp
    })
      .done( function () { getNewValues( true, false ) } );
  });

  $( "#clear" ).click( function() {
    $( "#goneoutuntil" ).val( "" );
    $.ajax({
      type: "GET",
      url: "/heating/gone_out_until/null"
    })
      .done( function () { getNewValues( true, false ) } )
  });

  getNewValues( true, true );
});
<commit_msg>Tidy up whitespace<commit_after>var overrideTemp = Number(0.0);

function getNewValues( immediate, initial ) {
  var url = "/heating/all_details";
  if( immediate ) {
    url = url + "/no_wait";
  }
  var qry = $.ajax({
    type: "GET",
    url: url,
    dataType: "json",
    cache: false
  })
  .done( function( data ) {
    processNewValues( data );
  })
  .always( function( data, textStatus, jqXHR ) {
    $( "#goneoutuntil" ).clockTimePicker({
      precision: 10,
      afternoonHoursInOuterCircle: true,
      minimum: moment().add( 1, 'hours' ).format( "HH:mm" ),
      required: true,
      onChange:( function( newValue, oldValue ) {
        var newTime = moment();
        var hours = newValue.substring( 0, 2 );
        var minutes = newValue.substring( 3, 5 );
        newTime.hour(hours);
        newTime.minute(minutes);
        newTime.second(0);
        newTime.millisecond(0);
        $.ajax({
          type: "GET",
          url: "/heating/gone_out_until/" + newTime.format()
        })
        .done( function () { getNewValues( true, false ) } )
      })
    });
    if ( initial )
      setTimeout( function() { getNewValues( false, initial )}, 55000 );
  });
}

function processNewValues( data ) {
  for ( var key in data.temps ) {
    $("#"+key+"temp").html( data.temps[key].toFixed(1) + "°" );
  }

  if ( data.heating ) {
    $( "#heatingstatus" ).removeClass( "bgwhite" ).addClass( "bgred" ).text( "Heating: On" );
  } else {
    $( "#heatingstatus" ).removeClass( "bgred" ).addClass( "bgwhite" ).text( "Heating: Off" );
  }

  if ( data.preheat ) {
    $( "#preheatstatus" ).removeClass( "bgwhite" ).addClass( "bgorange" ).text( "Preheat: On" );
  } else {
    $( "#preheatstatus" ).removeClass( "bgorange" ).addClass( "bgwhite" ).text( "Preheat: Off" );
  }

  if (!isNaN(parseFloat(data.currentsetpoint)) && !isNaN(parseFloat(data.override))) {
    var currentsetpoint = Number(data.currentsetpoint.toFixed(1));
    overrideTemp = Number(data.override.toFixed(1));

    if ( overrideTemp > 0 ) {
      currentsetpoint = currentsetpoint + "+" + overrideTemp + "°";
    } else if ( overrideTemp < 0 ) {
      currentsetpoint = currentsetpoint + overrideTemp + "°";
    } else {
      currentsetpoint = currentsetpoint + "°";
    }
    $( "#currentsetpoint" ).html( currentsetpoint );

    $( "#override" ).html( "Override by " + overrideTemp + "°" );
  }

  if ( data.nextsetpoint ) {
    $( "#nextsetpoint" ).html( data.nextsetpoint.toFixed(1) + "°" );
  } else {
    $( "#nextsetpoint" ).text( "Unknown" ) ;
  }

  if ( data.nexteventstart ) {
    var nexteventstart = new moment( data.nexteventstart );
    $( "#nexteventstart" ).text( nexteventstart.format( "DD/MM/YYYY HH:mm" ));
  } else {
    $( "#nexteventstart" ).text( "Unknown" );
  }

  var goneOutUntil = "";
  if ( data.goneoutuntil ) {
    goneOutUntil = moment( data.goneoutuntil );
    $( "#goneoutuntil" ).val( goneOutUntil.format( "HH:mm" ) );
  } else {
    $( "#goneoutuntil" ).val( "" );
  }
}

$( document ).ready( function () {
  $( "#decrease" ).click( function() {
    overrideTemp -= 0.5;
    $.ajax({
      type: "GET",
      url: "/heating/override/" + overrideTemp
    })
      .done( function () { getNewValues( true, false ) } );
  });

  $( "#increase" ).click( function() {
    overrideTemp += 0.5;
    $.ajax({
      type: "GET",
      url: "/heating/override/" + overrideTemp
    })
      .done( function () { getNewValues( true, false ) } );
  });

  $( "#clear" ).click( function() {
    $( "#goneoutuntil" ).val( "" );
    $.ajax({
      type: "GET",
      url: "/heating/gone_out_until/null"
    })
      .done( function () { getNewValues( true, false ) } )
  });

  getNewValues( true, true );
});
<|endoftext|>


<commit_before>var overrideTemp = Number(0.0);

function getNewValues( immediate, initial ) {
  var url = "/heating/all_details";
  if( immediate ) {
    url = url + "/no_wait";
  }
  var qry = $.ajax({
    type: "GET",
    url: url,
    dataType: "json",
    cache: false
  })
    .done( function( data ) {
      processNewValues( data );
    })
    .always( function( data, textStatus, jqXHR ) {
      if ( initial )
        setTimeout( function() { getNewValues( false, initial )}, 55000 );
    });
}

function processNewValues( data ) {
  for ( var key in data.temps ) {
    $("#"+key+"temp").html( data.temps[key].toFixed(1) + "°" );
  }

  if ( data.heating ) {
    $( "#heatingstatus" ).removeClass( "bgwhite" ).addClass( "bgred" ).text( "Heating: On" );
  } else {
    $( "#heatingstatus" ).removeClass( "bgred" ).addClass( "bgwhite" ).text( "Heating: Off" );
  }

  if ( data.preheat ) {
    $( "#preheatstatus" ).removeClass( "bgwhite" ).addClass( "bgorange" ).text( "Preheat: On" );
  } else {
    $( "#preheatstatus" ).removeClass( "bgorange" ).addClass( "bgwhite" ).text( "Preheat: Off" );
  }

  if (!isNaN(parseFloat(data.currentsetpoint)) && !isNaN(parseFloat(data.override))) {
    var currentsetpoint = Number(data.currentsetpoint.toFixed(1));
    overrideTemp = Number(data.override.toFixed(1));

    if ( overrideTemp > 0 ) {
      currentsetpoint = currentsetpoint + "+" + overrideTemp + "°";
    } else if ( overrideTemp < 0 ) {
      currentsetpoint = currentsetpoint + overrideTemp + "°";
    } else {
      currentsetpoint = currentsetpoint + "°";
    }
    $( "#currentsetpoint" ).html( currentsetpoint );

    $( "#override" ).html( "Override by " + overrideTemp + "°" );
  }

  if ( data.nextsetpoint ) {
    $( "#nextsetpoint" ).html( data.nextsetpoint.toFixed(1) + "°" );
  } else {
    $( "#nextsetpoint" ).text( "Unknown" ) ;
  }

  if ( data.nexteventstart ) {
    var nexteventstart = new moment( data.nexteventstart );
    $( "#nexteventstart" ).text( nexteventstart.format( "DD/MM/YYYY HH:mm" ));
  } else {
    $( "#nexteventstart" ).text( "Unknown" );
  }

  var goneOutUntil = "";
  if ( data.goneoutuntil ) {
    goneOutUntil = moment( data.goneoutuntil );
    $( "#goneoutuntil" ).val( goneOutUntil.format( "HH:mm" ) );
  } else {
    $( "#goneoutuntil" ).val( "" );
  }
}

$( document ).ready( function () {
  $( "#decrease" ).click( function() {
    overrideTemp -= 0.5;
    $.ajax({
      type: "GET",
      url: "/heating/override/" + overrideTemp
    })
      .done( function () { getNewValues( true, false ) } );
  });

  $( "#increase" ).click( function() {
    overrideTemp += 0.5;
    $.ajax({
      type: "GET",
      url: "/heating/override/" + overrideTemp
    })
      .done( function () { getNewValues( true, false ) } );
  });

  $( "#goneoutuntil" ).clockTimePicker({
    precision: 10,
    afternoonHoursInOuterCircle: true,
    minimum: moment().add( 1, 'hours' ).format( "HH:mm" ),
    required: true,
    onChange:( function( newValue, oldValue ) {
      var newTime = moment();
      var hours = newValue.substring( 0, 2 );
      var minutes = newValue.substring( 3, 5 );
      newTime.hour(hours);
      newTime.minute(minutes);
      newTime.second(0);
      newTime.millisecond(0);
      $.ajax({
        type: "GET",
        url: "/heating/gone_out_until/" + newTime.format()
      })
        .done( function () { getNewValues( true, false ) } )
    })
  });

  $( "#clear" ).click( function() {
    $( "#goneoutuntil" ).val( "" );
    $.ajax({
      type: "GET",
      url: "/heating/gone_out_until/null"
    })
      .done( function () { getNewValues( true, false ) } )
  });

  getNewValues( true, true );
});
<commit_msg>Update minimum gone out time every refresh<commit_after>var overrideTemp = Number(0.0);

function getNewValues( immediate, initial ) {
  var url = "/heating/all_details";
  if( immediate ) {
    url = url + "/no_wait";
  }
  var qry = $.ajax({
    type: "GET",
    url: url,
    dataType: "json",
    cache: false
  })
    .done( function( data ) {
      processNewValues( data );
    })
    .always( function( data, textStatus, jqXHR ) {
      $( "#goneoutuntil" ).clockTimePicker.minimum = moment().add( 1, 'hours' ).format( "HH:mm" );
      if ( initial )
        setTimeout( function() { getNewValues( false, initial )}, 55000 );
    });
}

function processNewValues( data ) {
  for ( var key in data.temps ) {
    $("#"+key+"temp").html( data.temps[key].toFixed(1) + "°" );
  }

  if ( data.heating ) {
    $( "#heatingstatus" ).removeClass( "bgwhite" ).addClass( "bgred" ).text( "Heating: On" );
  } else {
    $( "#heatingstatus" ).removeClass( "bgred" ).addClass( "bgwhite" ).text( "Heating: Off" );
  }

  if ( data.preheat ) {
    $( "#preheatstatus" ).removeClass( "bgwhite" ).addClass( "bgorange" ).text( "Preheat: On" );
  } else {
    $( "#preheatstatus" ).removeClass( "bgorange" ).addClass( "bgwhite" ).text( "Preheat: Off" );
  }

  if (!isNaN(parseFloat(data.currentsetpoint)) && !isNaN(parseFloat(data.override))) {
    var currentsetpoint = Number(data.currentsetpoint.toFixed(1));
    overrideTemp = Number(data.override.toFixed(1));

    if ( overrideTemp > 0 ) {
      currentsetpoint = currentsetpoint + "+" + overrideTemp + "°";
    } else if ( overrideTemp < 0 ) {
      currentsetpoint = currentsetpoint + overrideTemp + "°";
    } else {
      currentsetpoint = currentsetpoint + "°";
    }
    $( "#currentsetpoint" ).html( currentsetpoint );

    $( "#override" ).html( "Override by " + overrideTemp + "°" );
  }

  if ( data.nextsetpoint ) {
    $( "#nextsetpoint" ).html( data.nextsetpoint.toFixed(1) + "°" );
  } else {
    $( "#nextsetpoint" ).text( "Unknown" ) ;
  }

  if ( data.nexteventstart ) {
    var nexteventstart = new moment( data.nexteventstart );
    $( "#nexteventstart" ).text( nexteventstart.format( "DD/MM/YYYY HH:mm" ));
  } else {
    $( "#nexteventstart" ).text( "Unknown" );
  }

  var goneOutUntil = "";
  if ( data.goneoutuntil ) {
    goneOutUntil = moment( data.goneoutuntil );
    $( "#goneoutuntil" ).val( goneOutUntil.format( "HH:mm" ) );
  } else {
    $( "#goneoutuntil" ).val( "" );
  }
}

$( document ).ready( function () {
  $( "#decrease" ).click( function() {
    overrideTemp -= 0.5;
    $.ajax({
      type: "GET",
      url: "/heating/override/" + overrideTemp
    })
      .done( function () { getNewValues( true, false ) } );
  });

  $( "#increase" ).click( function() {
    overrideTemp += 0.5;
    $.ajax({
      type: "GET",
      url: "/heating/override/" + overrideTemp
    })
      .done( function () { getNewValues( true, false ) } );
  });

  $( "#goneoutuntil" ).clockTimePicker({
    precision: 10,
    afternoonHoursInOuterCircle: true,
    minimum: moment().add( 1, 'hours' ).format( "HH:mm" ),
    required: true,
    onChange:( function( newValue, oldValue ) {
      var newTime = moment();
      var hours = newValue.substring( 0, 2 );
      var minutes = newValue.substring( 3, 5 );
      newTime.hour(hours);
      newTime.minute(minutes);
      newTime.second(0);
      newTime.millisecond(0);
      $.ajax({
        type: "GET",
        url: "/heating/gone_out_until/" + newTime.format()
      })
        .done( function () { getNewValues( true, false ) } )
    })
  });

  $( "#clear" ).click( function() {
    $( "#goneoutuntil" ).val( "" );
    $.ajax({
      type: "GET",
      url: "/heating/gone_out_until/null"
    })
      .done( function () { getNewValues( true, false ) } )
  });

  getNewValues( true, true );
});
<|endoftext|>


<commit_before>var allTestFiles = [];
var TEST_REGEXP = /_test\.js$/i;

var pathToModule = function(path) {
  return path.replace(/^\/base\/js\//, '..\/').replace(/\.js$/, '');
};

Object.keys(window.__karma__.files).forEach(function(file) {
  if (TEST_REGEXP.test(file)) {
    // Normalize paths to RequireJS module names.
    allTestFiles.push(pathToModule(file));
  }
});

require.config({
  baseUrl: '/base/js/vendor',

  paths: {
    jquery: 'jquery/jquery-2.1.1.min',
    squire: 'squire/Squire',
    client: '../client'
  }
});

// Kick off Jasmine
// NOTE: this MUST NOT be run via deps+config, otherwise Squire will run the tests multiple times.
require( allTestFiles, window.__karma__.start );
<commit_msg>Include all client files for coverage reporting<commit_after>(function() {
	'use strict';

	var test_files, coverage_files;

	function pathToModule(path) {
		return path.replace(/^\/base\/js\//, '..\/').replace(/\.js$/, '');
	};

	// Configure require's paths
	require.config({
		baseUrl: '/base/js/vendor',

		paths: {
			jquery: 'jquery/jquery-2.1.1.min',
			squire: 'squire/Squire',
			client: '../client'
		}
	});

	// Ensure all client files are included for code coverage
	coverage_files = [];
	Object.keys(window.__karma__.files).forEach(function(file) {
		var regex;

		// Only pick up client files
		regex = /^\/base\/js\/client\//;
		if( !regex.test(file) ) {
			return;
		}

		// Don't pick up main.js - we only want the modules, not to actually start anything up.
		if( file === '/base/js/client/main.js' ) {
			return;
		}

		// Convert to a require path
		coverage_files.push(pathToModule(file));
	});

	// Actually get coverage to see the files
	require(coverage_files, function() {});

	// Find all test files to run in Jasmine
	test_files = [];

	Object.keys(window.__karma__.files).forEach(function(file) {
		var regex;

		regex = /_test\.js$/i;
		if (regex.test(file)) {
			// Normalize paths to RequireJS module names.
			test_files.push(pathToModule(file));
		}
	});

	// Kick off Jasmine
	// NOTE: this MUST NOT be run via deps+config, otherwise Squire will run the tests multiple times.
	require( test_files, window.__karma__.start );

})();
<|endoftext|>


<commit_before>'use strict';

angular.module('rippleDemonstrator')
  .controller('headerController', function ($scope, $rootScope, $state, usSpinnerService, $stateParams, UserService, AdvancedSearch) {

    $rootScope.searchExpression = '';
    $scope.searchExpression = $rootScope.searchExpression;
    $scope.reportTypes = [];

    $scope.searchFocused = false;

    // Get current user
    UserService.findCurrentUser().then( function (response) {
       redirectUrl = response.headers().location;

      if (redirectUrl) {
        $window.location = redirectUrl;
      }
      else {
        $rootScope.currentUser = response.data;

        $scope.autoAdvancedSearch = $rootScope.currentUser.feature.autoAdvancedSearch;
        $scope.searchBarEnabled = $rootScope.currentUser.feature.searchBarEnabled;
        $scope.navBar = $rootScope.currentUser.feature.navBar;

        // Direct different roles to different pages at login
        switch ($rootScope.currentUser.role) {
          case 'IDCR':
            $state.go('main-search');
            break;
          case 'PHR':
            $state.go('patients-summary', {
              patientId: $rootScope.currentUser.nhsNumber
            });
            break;
          default:
            $state.go('patients-summary', {
              patientId: $rootScope.currentUser.nhsNumber
            });
        }
      }
    });

    $scope.logout = function () {
      UserService.logout().then(function (response) {
        redirectUrl = response.headers().location;

        if (redirectUrl) {
          $window.location = redirectUrl;
        }
      });
    };

    $rootScope.$on('$stateChangeSuccess', function (event, toState) {
      var params = $stateParams;
      var previousState = '';
      var pageHeader = '';
      var previousPage = '';

      var mainWidth = 0;
      var detailWidth = 0;

      switch (toState.name) {
        case 'main-search':
          previousState = '';
          pageHeader = 'Welcome';
          previousPage = '';
          mainWidth = 12;
          detailWidth = 0;
          break;
      case 'patients-list':
        previousState = 'patients-charts';
        pageHeader = 'Patient Lists';
        previousPage = 'Patient Dashboard';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-charts':
        previousState = '';
        pageHeader = 'Patient Dashboard';
        previousPage = '';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-search':
        previousState = '';
        pageHeader = 'Patient Dashboard';
        previousPage = '';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-landing':
        previousState = 'patients-search';
        pageHeader = 'Patient Summary';
        previousPage = 'Patient Search';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-summary':
        previousState = 'patients-list';
        pageHeader = 'Patient Summary';
        previousPage = 'Patient Lists';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-lookup':
        previousState = '';
        pageHeader = 'Patients lookup';
        previousPage = '';
        mainWidth = 6;
        detailWidth = 6;
        break;
      case 'search-report':
        previousState = 'patients-charts';
        pageHeader = 'Report Search';
        previousPage = 'Patient Dashboard';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-list-full':
        previousState = 'patients-charts';
        pageHeader = 'Patients Details';
        previousPage = 'Patient Dashboard';
        mainWidth = 12;
        detailWidth = 0;
        break;
      default:
        previousState = 'patients-list';
        pageHeader = 'Patients Details';
        previousPage = 'Patient Lists';
        mainWidth = 6;
        detailWidth = 6;
        break;
      }

      if (params.queryType === 'Reports: ') {
        previousState = 'search-report';
        previousPage = 'Report Chart';
      }

      $scope.containsReportString = function () {
        return $scope.searchExpression.indexOf('rp ') === 0;
      };

      $scope.containsSettingString = function () {
        return $scope.searchExpression.lastIndexOf('st ') === 0;
      };

      $scope.containsPatientString = function () {
        return $scope.searchExpression.lastIndexOf('pt ') === 0;
      };

      $scope.containsReportTypeString = function () {
        for (var i = 0; i < $scope.reportTypes.length; i++) {
          if ($scope.searchExpression.lastIndexOf($scope.reportTypes[i]) !== -1) {
            return true;
          }
        }
        return false;
      };

      $rootScope.searchMode = false;
      $rootScope.reportMode = false;
      $rootScope.settingsMode = false;
      $rootScope.patientMode = false;
      $rootScope.reportTypeSet = false;
      $rootScope.reportTypeString = '';

      $scope.checkExpression = function () {
        if($scope.autoAdvancedSearch) {
          if($scope.searchExpression.length >= 3) {
            AdvancedSearch.openAdvancedSearch($scope.searchExpression);
          }
        }
        else if ($rootScope.searchMode) {
          if ($rootScope.reportMode && !$rootScope.reportTypeSet) {
            $scope.reportTypes = [
              'Diagnosis: ',
              'Orders: '
              ];
          }
          if ($scope.containsReportTypeString() && !$scope.patientMode) {
            $rootScope.reportTypeSet = true;
            $scope.processReportTypeMode();
          }
        } else {
          $scope.reportTypes = [];
          $rootScope.searchMode = ($scope.containsReportString() || $scope.containsSettingString() || $scope.containsPatientString());
          $rootScope.reportMode = $scope.containsReportString();
          $rootScope.settingsMode = $scope.containsSettingString();
          $rootScope.patientMode = $scope.containsPatientString();
          if ($rootScope.reportMode) {
            if ($scope.containsReportTypeString) {
              $scope.processReportTypeMode();
            }
            $scope.processReportMode();
          }
          if ($rootScope.settingsMode) {
            $scope.processSettingMode();
          }
          if ($rootScope.patientMode) {
            $scope.processPatientMode();
          }
        }
      };

      $scope.cancelSearchMode = function () {
        $rootScope.reportMode = false;
        $rootScope.searchMode = false;
        $rootScope.patientMode = false;
        $rootScope.settingsMode = false;
        $scope.searchExpression = '';
        $scope.reportTypes = '';
        $rootScope.reportTypeSet = false;
        $rootScope.reportTypeString = '';
      };

      $scope.cancelReportType = function () {
        $rootScope.reportTypeString = '';
        $rootScope.reportTypeSet = false;
      };

      $scope.searchFunction = function () {
        if($scope.autoAdvancedSearch)
        {
          AdvancedSearch.openAdvancedSearch();
        }
        if ($rootScope.reportTypeSet && $scope.searchExpression !== '') {
          var tempExpression = $rootScope.reportTypeString + ': ' + $scope.searchExpression;
          $state.go('search-report', {
            searchString: tempExpression
          });
        }
        if ($rootScope.settingsMode && $scope.searchExpression !== '') {
          $state.go('patients-list-full', {
            queryType: 'Setting: ',
            searchString: $scope.searchExpression,
            orderType: 'ASC',
            pageNumber: '1'
          });
        }
        if ($rootScope.patientMode && $scope.searchExpression !== '') {
          $state.go('patients-list-full', {
            queryType: 'Patient: ',
            searchString: $scope.searchExpression,
            orderType: 'ASC',
            pageNumber: '1'
          });
        }
      };

      $scope.processReportMode = function () {
        if ($scope.searchExpression === 'rp ') {
          $scope.searchExpression = '';
        }
      };

      $scope.processReportTypeMode = function () {
        for (var i = 0; i < $scope.reportTypes.length; i++) {
          if ($scope.searchExpression.lastIndexOf($scope.reportTypes[i]) !== -1) {
            var arr = $scope.searchExpression.split(':');
            $rootScope.reportTypeString = arr[0];
            $rootScope.reportTypeSet = true;
            $scope.searchExpression = '';
          }
        }
        $scope.reportTypes = [];
      };

      $scope.processSettingMode = function () {
        if ($scope.searchExpression === 'st ') {
          $scope.searchExpression = '';
        }
      };

      $scope.processPatientMode = function () {
        if ($scope.searchExpression === 'pt ') {
          $scope.searchExpression = '';
        }
      };

      if (typeof $stateParams.ageFrom === 'undefined') {
        previousState = 'patients-list';
        previousPage = 'Patient Lists';
      }

      $scope.pageHeader = pageHeader;
      $scope.previousState = previousState;
      $scope.previousPage = previousPage;

      $scope.backButtonEnabled = $scope.currentUser.feature.homeView !== 'main-search';

      $scope.mainWidth = mainWidth;
      $scope.detailWidth = detailWidth;

      $scope.searchBarEnabled = !$state.is('main-search');

      $scope.goBack = function () {
        history.back();
      };

      $scope.footer = 'Integrated Digital Care Record';
      $scope.userContextViewExists = ('user-context' in $state.current.views);
      $scope.actionsExists = ('actions' in $state.current.views);

      $scope.go = function (patient) {
        $state.go('patients-summary', {
          patientId: patient.id
        });
      };

      if ($scope.currentUser.role === 'IDCR') {
        $scope.title = 'IDCR POC'
      }
      if ($scope.currentUser.role === 'PHR') {
        $scope.title = 'PHR POC'
      }

      $scope.goHome = function () {
        $scope.cancelSearchMode();

        if ($scope.currentUser.role === 'IDCR') {
          $state.go('main-search');
        }
        if ($scope.currentUser.role === 'PHR') {
          $state.go('patients-summary', {
            patientId: 10
          }); // Id is hardcoded
        }
      };
    });

    $scope.openAdvancedSearch = AdvancedSearch.openAdvancedSearch;

    $scope.$on("toggleHeaderSearchEnabled", function(event, enabled) {
      $scope.searchBarEnabled = enabled;
    });

    $scope.$on("populateHeaderSearch", function(event, expression) {
      $scope.searchExpression = expression;
      $scope.searchFocused = true;
    });
  });
<commit_msg>Fixed a missing dependency on header-controller<commit_after>'use strict';

angular.module('rippleDemonstrator')
  .controller('headerController', function ($scope, $rootScope, $state, $window, usSpinnerService, $stateParams, UserService, AdvancedSearch) {

    $rootScope.searchExpression = '';
    $scope.searchExpression = $rootScope.searchExpression;
    $scope.reportTypes = [];

    $scope.searchFocused = false;

    var redirectUrl;

    // Get current user
    UserService.findCurrentUser().then( function (response) {
       redirectUrl = response.headers().location;

      if (redirectUrl) {
        $window.location = redirectUrl;
      }
      else {
        $rootScope.currentUser = response.data;

        $scope.autoAdvancedSearch = $rootScope.currentUser.feature.autoAdvancedSearch;
        $scope.searchBarEnabled = $rootScope.currentUser.feature.searchBarEnabled;
        $scope.navBar = $rootScope.currentUser.feature.navBar;

        // Direct different roles to different pages at login
        switch ($rootScope.currentUser.role) {
          case 'IDCR':
            $state.go('main-search');
            break;
          case 'PHR':
            $state.go('patients-summary', {
              patientId: $rootScope.currentUser.nhsNumber
            });
            break;
          default:
            $state.go('patients-summary', {
              patientId: $rootScope.currentUser.nhsNumber
            });
        }
      }
    });

    $scope.logout = function () {
      UserService.logout().then(function (response) {
        redirectUrl = response.headers().location;

        if (redirectUrl) {
          $window.location = redirectUrl;
        }
      });
    };

    $rootScope.$on('$stateChangeSuccess', function (event, toState) {
      var params = $stateParams;
      var previousState = '';
      var pageHeader = '';
      var previousPage = '';

      var mainWidth = 0;
      var detailWidth = 0;

      switch (toState.name) {
        case 'main-search':
          previousState = '';
          pageHeader = 'Welcome';
          previousPage = '';
          mainWidth = 12;
          detailWidth = 0;
          break;
      case 'patients-list':
        previousState = 'patients-charts';
        pageHeader = 'Patient Lists';
        previousPage = 'Patient Dashboard';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-charts':
        previousState = '';
        pageHeader = 'Patient Dashboard';
        previousPage = '';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-search':
        previousState = '';
        pageHeader = 'Patient Dashboard';
        previousPage = '';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-landing':
        previousState = 'patients-search';
        pageHeader = 'Patient Summary';
        previousPage = 'Patient Search';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-summary':
        previousState = 'patients-list';
        pageHeader = 'Patient Summary';
        previousPage = 'Patient Lists';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-lookup':
        previousState = '';
        pageHeader = 'Patients lookup';
        previousPage = '';
        mainWidth = 6;
        detailWidth = 6;
        break;
      case 'search-report':
        previousState = 'patients-charts';
        pageHeader = 'Report Search';
        previousPage = 'Patient Dashboard';
        mainWidth = 12;
        detailWidth = 0;
        break;
      case 'patients-list-full':
        previousState = 'patients-charts';
        pageHeader = 'Patients Details';
        previousPage = 'Patient Dashboard';
        mainWidth = 12;
        detailWidth = 0;
        break;
      default:
        previousState = 'patients-list';
        pageHeader = 'Patients Details';
        previousPage = 'Patient Lists';
        mainWidth = 6;
        detailWidth = 6;
        break;
      }

      if (params.queryType === 'Reports: ') {
        previousState = 'search-report';
        previousPage = 'Report Chart';
      }

      $scope.containsReportString = function () {
        return $scope.searchExpression.indexOf('rp ') === 0;
      };

      $scope.containsSettingString = function () {
        return $scope.searchExpression.lastIndexOf('st ') === 0;
      };

      $scope.containsPatientString = function () {
        return $scope.searchExpression.lastIndexOf('pt ') === 0;
      };

      $scope.containsReportTypeString = function () {
        for (var i = 0; i < $scope.reportTypes.length; i++) {
          if ($scope.searchExpression.lastIndexOf($scope.reportTypes[i]) !== -1) {
            return true;
          }
        }
        return false;
      };

      $rootScope.searchMode = false;
      $rootScope.reportMode = false;
      $rootScope.settingsMode = false;
      $rootScope.patientMode = false;
      $rootScope.reportTypeSet = false;
      $rootScope.reportTypeString = '';

      $scope.checkExpression = function () {
        if($scope.autoAdvancedSearch) {
          if($scope.searchExpression.length >= 3) {
            AdvancedSearch.openAdvancedSearch($scope.searchExpression);
          }
        }
        else if ($rootScope.searchMode) {
          if ($rootScope.reportMode && !$rootScope.reportTypeSet) {
            $scope.reportTypes = [
              'Diagnosis: ',
              'Orders: '
              ];
          }
          if ($scope.containsReportTypeString() && !$scope.patientMode) {
            $rootScope.reportTypeSet = true;
            $scope.processReportTypeMode();
          }
        } else {
          $scope.reportTypes = [];
          $rootScope.searchMode = ($scope.containsReportString() || $scope.containsSettingString() || $scope.containsPatientString());
          $rootScope.reportMode = $scope.containsReportString();
          $rootScope.settingsMode = $scope.containsSettingString();
          $rootScope.patientMode = $scope.containsPatientString();
          if ($rootScope.reportMode) {
            if ($scope.containsReportTypeString) {
              $scope.processReportTypeMode();
            }
            $scope.processReportMode();
          }
          if ($rootScope.settingsMode) {
            $scope.processSettingMode();
          }
          if ($rootScope.patientMode) {
            $scope.processPatientMode();
          }
        }
      };

      $scope.cancelSearchMode = function () {
        $rootScope.reportMode = false;
        $rootScope.searchMode = false;
        $rootScope.patientMode = false;
        $rootScope.settingsMode = false;
        $scope.searchExpression = '';
        $scope.reportTypes = '';
        $rootScope.reportTypeSet = false;
        $rootScope.reportTypeString = '';
      };

      $scope.cancelReportType = function () {
        $rootScope.reportTypeString = '';
        $rootScope.reportTypeSet = false;
      };

      $scope.searchFunction = function () {
        if($scope.autoAdvancedSearch)
        {
          AdvancedSearch.openAdvancedSearch();
        }
        if ($rootScope.reportTypeSet && $scope.searchExpression !== '') {
          var tempExpression = $rootScope.reportTypeString + ': ' + $scope.searchExpression;
          $state.go('search-report', {
            searchString: tempExpression
          });
        }
        if ($rootScope.settingsMode && $scope.searchExpression !== '') {
          $state.go('patients-list-full', {
            queryType: 'Setting: ',
            searchString: $scope.searchExpression,
            orderType: 'ASC',
            pageNumber: '1'
          });
        }
        if ($rootScope.patientMode && $scope.searchExpression !== '') {
          $state.go('patients-list-full', {
            queryType: 'Patient: ',
            searchString: $scope.searchExpression,
            orderType: 'ASC',
            pageNumber: '1'
          });
        }
      };

      $scope.processReportMode = function () {
        if ($scope.searchExpression === 'rp ') {
          $scope.searchExpression = '';
        }
      };

      $scope.processReportTypeMode = function () {
        for (var i = 0; i < $scope.reportTypes.length; i++) {
          if ($scope.searchExpression.lastIndexOf($scope.reportTypes[i]) !== -1) {
            var arr = $scope.searchExpression.split(':');
            $rootScope.reportTypeString = arr[0];
            $rootScope.reportTypeSet = true;
            $scope.searchExpression = '';
          }
        }
        $scope.reportTypes = [];
      };

      $scope.processSettingMode = function () {
        if ($scope.searchExpression === 'st ') {
          $scope.searchExpression = '';
        }
      };

      $scope.processPatientMode = function () {
        if ($scope.searchExpression === 'pt ') {
          $scope.searchExpression = '';
        }
      };

      if (typeof $stateParams.ageFrom === 'undefined') {
        previousState = 'patients-list';
        previousPage = 'Patient Lists';
      }

      $scope.pageHeader = pageHeader;
      $scope.previousState = previousState;
      $scope.previousPage = previousPage;

      $scope.backButtonEnabled = $scope.currentUser.feature.homeView !== 'main-search';

      $scope.mainWidth = mainWidth;
      $scope.detailWidth = detailWidth;

      $scope.searchBarEnabled = !$state.is('main-search');

      $scope.goBack = function () {
        history.back();
      };

      $scope.footer = 'Integrated Digital Care Record';
      $scope.userContextViewExists = ('user-context' in $state.current.views);
      $scope.actionsExists = ('actions' in $state.current.views);

      $scope.go = function (patient) {
        $state.go('patients-summary', {
          patientId: patient.id
        });
      };

      if ($scope.currentUser.role === 'IDCR') {
        $scope.title = 'IDCR POC'
      }
      if ($scope.currentUser.role === 'PHR') {
        $scope.title = 'PHR POC'
      }

      $scope.goHome = function () {
        $scope.cancelSearchMode();

        if ($scope.currentUser.role === 'IDCR') {
          $state.go('main-search');
        }
        if ($scope.currentUser.role === 'PHR') {
          $state.go('patients-summary', {
            patientId: 10
          }); // Id is hardcoded
        }
      };
    });

    $scope.openAdvancedSearch = AdvancedSearch.openAdvancedSearch;

    $scope.$on("toggleHeaderSearchEnabled", function(event, enabled) {
      $scope.searchBarEnabled = enabled;
    });

    $scope.$on("populateHeaderSearch", function(event, expression) {
      $scope.searchExpression = expression;
      $scope.searchFocused = true;
    });
  });
<|endoftext|>