<commit_before>CloudPebble.Settings = (function() {
    var settings_template = null;
    var shared_pane = null;

    var show_settings_pane = function() {
        CloudPebble.Sidebar.SuspendActive();
        if(CloudPebble.Sidebar.Restore("settings")) {
            return;
        }
        ga('send', 'event', 'project', 'load settings');
        var pane = settings_template;
        shared_pane = pane;

        if(CloudPebble.ProjectInfo.type != 'native') {
            pane.find('.native-only').hide();
        }

        var display_error = function(message) {
            $('#main-pane')[0].scrollTop = 0;
            pane.find('.alert').addClass('alert-error').removeClass('hide').text(message);
            pane.find('input, button, select').removeAttr('disabled');
        };

        var display_success = function(message) {
            $('#main-pane')[0].scrollTop = 0;
            pane.find('.alert').addClass('alert-success').removeClass('hide').text(message);
            pane.find('input, button, select').removeAttr('disabled');
        };

        pane.find('#settings-name').val(CloudPebble.ProjectInfo.name);
        pane.find('form').submit(function(e) {e.preventDefault();});
        pane.find('#project-save').click(function() {
            var name = pane.find('#settings-name').val();
            var sdk_version = pane.find('#settings-sdk-version').val();
            var short_name = pane.find('#settings-short-name').val();
            var long_name = pane.find('#settings-long-name').val();
            var company_name = pane.find('#settings-company-name').val();
            var version_label = pane.find('#settings-version-label').val();
            var app_uuid = pane.find('#settings-uuid').val();
            var app_is_watchface = pane.find('#settings-app-is-watchface').val();
            var app_keys = {};
            var app_jshint = pane.find('#settings-app-jshint').prop("checked") ? 1 : 0;
            var menu_icon = pane.find('#settings-menu-image').val();
            var build_aplite = pane.find('#settings-build-aplite').prop('checked');
            var build_basalt = pane.find('#settings-build-basalt').prop('checked');

            var app_capabilities = [];
            if(pane.find('#settings-capabilities-location').is(':checked')) {
                app_capabilities.push('location');
            }
            if(pane.find('#settings-capabilities-configuration').is(':checked')) {
                app_capabilities.push('configurable');
            }
            app_capabilities = app_capabilities.join(',');

            if(name.replace(/\s/g, '') === '') {
                display_error(gettext("You must specify a project name"));
                return;
            }

            pane.find('input, button, select').attr('disabled', 'disabled');

            var saved_settings = {
                'name': name
            };

            if(short_name.replace(/\s/g, '') == '') {
                display_error(gettext("You must specify a short name."));
                return;
            }
            if(long_name.replace(/\s/g, '') == '') {
                display_error(gettext("You must specify a long name."));
                return;
            }
            if(company_name.replace(/\s/g, '') == '') {
                display_error(gettext("You must specify a company name."));
                return;
            }
            // This is not an appropriate use of a regex, but we have to have it for the HTML5 pattern attribute anyway,
            // so we may as well reuse the effort here.
            // It validates that the format matches x[.y] with x, y in [0, 255].
            if(!version_label.match(/^(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5]))?$/)) {
                display_error(gettext("You must specify a valid version number."));
                return;
            }
            if(!app_uuid.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}/)) {
                display_error(gettext("You must specify a valid UUID (of the form 00000000-0000-0000-0000-000000000000)"));
                return;
            }

            if(sdk_version == '3') {
                if (!build_aplite && !build_basalt) {
                    display_error(gettext("You must build your app for at least one platform."));
                    return;
                }
            }

            var target_platforms = [];
            if(build_aplite) {
                target_platforms.push('aplite');
            }
            if(build_basalt) {
                target_platforms.push('basalt');
            }
            var app_platforms = target_platforms.join(',');

            pane.find(".appkey").each(function() {
                var name = $(this).find('.appkey-name').val();
                var id = $(this).find('.appkey-id').val();

                if(name.replace(/\s/g, '') == '') {
                    // Skip blank keys.
                    return;
                }

                app_keys[name] = parseInt(id);
            });

            saved_settings['sdk_version'] = sdk_version;
            saved_settings['app_short_name'] = short_name;
            saved_settings['app_long_name'] = long_name;
            saved_settings['app_company_name'] = company_name;
            saved_settings['app_version_label'] = version_label;
            saved_settings['app_uuid'] = app_uuid;
            saved_settings['app_capabilities'] = app_capabilities;
            saved_settings['app_is_watchface'] = app_is_watchface;
            saved_settings['app_keys'] = JSON.stringify(app_keys);
            saved_settings['app_jshint'] = app_jshint;
            saved_settings['menu_icon'] = menu_icon;
            saved_settings['app_platforms'] = app_platforms;

            $.post('/ide/project/' + PROJECT_ID + '/save_settings', saved_settings, function(data) {
                pane.find('input, button, select').removeAttr('disabled');
                pane.find('.alert').removeClass("alert-success alert-error").addClass("hide");
                if(data.success) {
                    CloudPebble.ProjectInfo.name = name;
                    CloudPebble.ProjectInfo.app_uuid = app_uuid;
                    CloudPebble.ProjectInfo.app_company_name = company_name;
                    CloudPebble.ProjectInfo.app_short_name = short_name;
                    CloudPebble.ProjectInfo.app_long_name = long_name;
                    CloudPebble.ProjectInfo.app_version_label = version_label;
                    CloudPebble.ProjectInfo.app_is_watchface = app_is_watchface;
                    CloudPebble.ProjectInfo.app_capabilities = app_capabilities;
                    CloudPebble.ProjectInfo.app_jshint = app_jshint;
                    CloudPebble.ProjectInfo.app_platforms = app_platforms;
                    CloudPebble.ProjectInfo.sdk_version = sdk_version;
                    $('.project-name').text(name);
                    window.document.title = "CloudPebble – " + name;
                    display_success(gettext("Settings saved."));
                } else {
                    display_error(interpolate(gettext("Error: %s"), [data.error]));
                }
            });

            ga('send', 'event', 'project', 'save settings');
        });

        pane.find('#project-delete').click(function() {
            CloudPebble.Prompts.Confirm(gettext("Delete Project"), gettext("Are you sure you want to delete this project? THIS CANNOT BE UNDONE."), function() {
                $.post('/ide/project/' + PROJECT_ID + '/delete', {confirm: true}, function(data) {
                    if(data.success) {
                        window.location.href = "/ide/";
                    } else {
                        display_error(interpolate(gettext("Error: %s"), [data.error]));
                    }
                });
                ga('send', 'event', 'project', 'delete');
            });
        });

        pane.find('#project-export-zip').click(function() {
            var dialog = $('#export-progress');
            dialog
                .modal('show')
                .find('.progress')
                .addClass('progress-striped')
                .removeClass('progress-success progress-danger progress-warning');
            $.post('/ide/project/' + PROJECT_ID + '/export', {}, function(data) {
                if(!data.success) {
                    dialog.find('.progress').removeClass('progress-striped').addClass('progress-danger');
                    return;
                }
                var task_id = data.task_id;
                var check_update = function() {
                    $.getJSON('/ide/task/' + task_id, function(data) {
                        if(!data.success) {
                            dialog.find('.progress').addClass('progress-warning');
                            setTimeout(check_update, 1000);
                        } else {
                            if(data.state.status == 'SUCCESS') {
                                dialog.find('.progress').removeClass('progress-striped').addClass('progress-success');
                                dialog.find('.download-btn').attr('href', data.state.result).show();
                            } else if(data.state.status == 'FAILURE') {
                                dialog.find('.progress').removeClass('progress-striped').addClass('progress-danger');
                            } else {
                                setTimeout(check_update, 1000);
                            }
                        }
                    });
                };
                setTimeout(check_update, 1000);
            });

            ga('send', 'event', 'project', 'export', 'zip');
        });

        var add_appkey_field = function() {
            $(this).off('change', add_appkey_field);

            var entry = $(this).closest('.appkey');
            entry.find('.remove-appkey').removeClass('disabled').click(function() {
                entry.remove();
            });

            var new_appkey = $('
' +
                '<input class="appkey-name" type="text" placeholder="' + gettext("New Entry") + '" />	' +
                '<input class="appkey-id" type="number" value="0" />	' +
                '<button class="btn remove-appkey disabled">–</button>	' +
                '
');

            new_appkey.find('.appkey-name').on('change', add_appkey_field);

            pane.find('#appkeys').append(new_appkey);
        };

        pane.find('.appkey:last').on('change', add_appkey_field);

        pane.find('.remove-appkey').not('.disabled').click(function() {
            $(this).closest('.appkey').remove();
        });

        pane.find('#settings-sdk-version').change(function() {
            var sdk = $(this).val();
            if(sdk == '3') {
                pane.find('.sdk3-only').show();
            } else {
                pane.find('.sdk3-only').hide();
            }
        });

        pane.find('#uuid-generate').click(function() {
            var uuid_field = settings_template.find('#settings-uuid');
            new_uuid = _.UUID.v4();
            uuid_field.val(new_uuid);
        });

        CloudPebble.Sidebar.SetActivePane(pane, 'settings');
    };

    var add_resource = function(resource) {
        var thing = settings_template.find('#settings-menu-image');
        var option = $('<option>').attr('value', resource.id).text(resource.file_name);
        thing.append(option);
        if(resource.id == CloudPebble.ProjectInfo.menu_icon) {
            thing.val(resource.id);
        }
    };

    var remove_resource = function(resource) {
        var thing = settings_template.find('#settings-menu-image');
        thing.find('[value=' + resource.id + ']').remove();
        if(resource.id == CloudPebble.ProjectInfo.menu_icon) {
            thing.val('');
            CloudPebble.ProjectInfo.menu_icon = null;
        }
    };

    return {
        Show: function() {
            show_settings_pane();
        },
        Init: function() {
            settings_template = $('#settings-pane-template').remove().removeClass('hide');
        },
        AddResource: function(resource) {
            add_resource(resource);
        },
        RemoveResource: function(resource) {
            remove_resource(resource);
        }
    };
})();
<commit_msg>Improve syntax for UUID generation<commit_after>CloudPebble.Settings = (function() {
    var settings_template = null;
    var shared_pane = null;

    var show_settings_pane = function() {
        CloudPebble.Sidebar.SuspendActive();
        if(CloudPebble.Sidebar.Restore("settings")) {
            return;
        }
        ga('send', 'event', 'project', 'load settings');
        var pane = settings_template;
        shared_pane = pane;

        if(CloudPebble.ProjectInfo.type != 'native') {
            pane.find('.native-only').hide();
        }

        var display_error = function(message) {
            $('#main-pane')[0].scrollTop = 0;
            pane.find('.alert').addClass('alert-error').removeClass('hide').text(message);
            pane.find('input, button, select').removeAttr('disabled');
        };

        var display_success = function(message) {
            $('#main-pane')[0].scrollTop = 0;
            pane.find('.alert').addClass('alert-success').removeClass('hide').text(message);
            pane.find('input, button, select').removeAttr('disabled');
        };

        pane.find('#settings-name').val(CloudPebble.ProjectInfo.name);
        pane.find('form').submit(function(e) {e.preventDefault();});
        pane.find('#project-save').click(function() {
            var name = pane.find('#settings-name').val();
            var sdk_version = pane.find('#settings-sdk-version').val();
            var short_name = pane.find('#settings-short-name').val();
            var long_name = pane.find('#settings-long-name').val();
            var company_name = pane.find('#settings-company-name').val();
            var version_label = pane.find('#settings-version-label').val();
            var app_uuid = pane.find('#settings-uuid').val();
            var app_is_watchface = pane.find('#settings-app-is-watchface').val();
            var app_keys = {};
            var app_jshint = pane.find('#settings-app-jshint').prop("checked") ? 1 : 0;
            var menu_icon = pane.find('#settings-menu-image').val();
            var build_aplite = pane.find('#settings-build-aplite').prop('checked');
            var build_basalt = pane.find('#settings-build-basalt').prop('checked');

            var app_capabilities = [];
            if(pane.find('#settings-capabilities-location').is(':checked')) {
                app_capabilities.push('location');
            }
            if(pane.find('#settings-capabilities-configuration').is(':checked')) {
                app_capabilities.push('configurable');
            }
            app_capabilities = app_capabilities.join(',');

            if(name.replace(/\s/g, '') === '') {
                display_error(gettext("You must specify a project name"));
                return;
            }

            pane.find('input, button, select').attr('disabled', 'disabled');

            var saved_settings = {
                'name': name
            };

            if(short_name.replace(/\s/g, '') == '') {
                display_error(gettext("You must specify a short name."));
                return;
            }
            if(long_name.replace(/\s/g, '') == '') {
                display_error(gettext("You must specify a long name."));
                return;
            }
            if(company_name.replace(/\s/g, '') == '') {
                display_error(gettext("You must specify a company name."));
                return;
            }
            // This is not an appropriate use of a regex, but we have to have it for the HTML5 pattern attribute anyway,
            // so we may as well reuse the effort here.
            // It validates that the format matches x[.y] with x, y in [0, 255].
            if(!version_label.match(/^(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])(\.(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5]))?$/)) {
                display_error(gettext("You must specify a valid version number."));
                return;
            }
            if(!app_uuid.match(/[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}/)) {
                display_error(gettext("You must specify a valid UUID (of the form 00000000-0000-0000-0000-000000000000)"));
                return;
            }

            if(sdk_version == '3') {
                if (!build_aplite && !build_basalt) {
                    display_error(gettext("You must build your app for at least one platform."));
                    return;
                }
            }

            var target_platforms = [];
            if(build_aplite) {
                target_platforms.push('aplite');
            }
            if(build_basalt) {
                target_platforms.push('basalt');
            }
            var app_platforms = target_platforms.join(',');

            pane.find(".appkey").each(function() {
                var name = $(this).find('.appkey-name').val();
                var id = $(this).find('.appkey-id').val();

                if(name.replace(/\s/g, '') == '') {
                    // Skip blank keys.
                    return;
                }

                app_keys[name] = parseInt(id);
            });

            saved_settings['sdk_version'] = sdk_version;
            saved_settings['app_short_name'] = short_name;
            saved_settings['app_long_name'] = long_name;
            saved_settings['app_company_name'] = company_name;
            saved_settings['app_version_label'] = version_label;
            saved_settings['app_uuid'] = app_uuid;
            saved_settings['app_capabilities'] = app_capabilities;
            saved_settings['app_is_watchface'] = app_is_watchface;
            saved_settings['app_keys'] = JSON.stringify(app_keys);
            saved_settings['app_jshint'] = app_jshint;
            saved_settings['menu_icon'] = menu_icon;
            saved_settings['app_platforms'] = app_platforms;

            $.post('/ide/project/' + PROJECT_ID + '/save_settings', saved_settings, function(data) {
                pane.find('input, button, select').removeAttr('disabled');
                pane.find('.alert').removeClass("alert-success alert-error").addClass("hide");
                if(data.success) {
                    CloudPebble.ProjectInfo.name = name;
                    CloudPebble.ProjectInfo.app_uuid = app_uuid;
                    CloudPebble.ProjectInfo.app_company_name = company_name;
                    CloudPebble.ProjectInfo.app_short_name = short_name;
                    CloudPebble.ProjectInfo.app_long_name = long_name;
                    CloudPebble.ProjectInfo.app_version_label = version_label;
                    CloudPebble.ProjectInfo.app_is_watchface = app_is_watchface;
                    CloudPebble.ProjectInfo.app_capabilities = app_capabilities;
                    CloudPebble.ProjectInfo.app_jshint = app_jshint;
                    CloudPebble.ProjectInfo.app_platforms = app_platforms;
                    CloudPebble.ProjectInfo.sdk_version = sdk_version;
                    $('.project-name').text(name);
                    window.document.title = "CloudPebble – " + name;
                    display_success(gettext("Settings saved."));
                } else {
                    display_error(interpolate(gettext("Error: %s"), [data.error]));
                }
            });

            ga('send', 'event', 'project', 'save settings');
        });

        pane.find('#project-delete').click(function() {
            CloudPebble.Prompts.Confirm(gettext("Delete Project"), gettext("Are you sure you want to delete this project? THIS CANNOT BE UNDONE."), function() {
                $.post('/ide/project/' + PROJECT_ID + '/delete', {confirm: true}, function(data) {
                    if(data.success) {
                        window.location.href = "/ide/";
                    } else {
                        display_error(interpolate(gettext("Error: %s"), [data.error]));
                    }
                });
                ga('send', 'event', 'project', 'delete');
            });
        });

        pane.find('#project-export-zip').click(function() {
            var dialog = $('#export-progress');
            dialog
                .modal('show')
                .find('.progress')
                .addClass('progress-striped')
                .removeClass('progress-success progress-danger progress-warning');
            $.post('/ide/project/' + PROJECT_ID + '/export', {}, function(data) {
                if(!data.success) {
                    dialog.find('.progress').removeClass('progress-striped').addClass('progress-danger');
                    return;
                }
                var task_id = data.task_id;
                var check_update = function() {
                    $.getJSON('/ide/task/' + task_id, function(data) {
                        if(!data.success) {
                            dialog.find('.progress').addClass('progress-warning');
                            setTimeout(check_update, 1000);
                        } else {
                            if(data.state.status == 'SUCCESS') {
                                dialog.find('.progress').removeClass('progress-striped').addClass('progress-success');
                                dialog.find('.download-btn').attr('href', data.state.result).show();
                            } else if(data.state.status == 'FAILURE') {
                                dialog.find('.progress').removeClass('progress-striped').addClass('progress-danger');
                            } else {
                                setTimeout(check_update, 1000);
                            }
                        }
                    });
                };
                setTimeout(check_update, 1000);
            });

            ga('send', 'event', 'project', 'export', 'zip');
        });

        var add_appkey_field = function() {
            $(this).off('change', add_appkey_field);

            var entry = $(this).closest('.appkey');
            entry.find('.remove-appkey').removeClass('disabled').click(function() {
                entry.remove();
            });

            var new_appkey = $('
' +
                '<input class="appkey-name" type="text" placeholder="' + gettext("New Entry") + '" />	' +
                '<input class="appkey-id" type="number" value="0" />	' +
                '<button class="btn remove-appkey disabled">–</button>	' +
                '
');

            new_appkey.find('.appkey-name').on('change', add_appkey_field);

            pane.find('#appkeys').append(new_appkey);
        };

        pane.find('.appkey:last').on('change', add_appkey_field);

        pane.find('.remove-appkey').not('.disabled').click(function() {
            $(this).closest('.appkey').remove();
        });

        pane.find('#settings-sdk-version').change(function() {
            var sdk = $(this).val();
            if(sdk == '3') {
                pane.find('.sdk3-only').show();
            } else {
                pane.find('.sdk3-only').hide();
            }
        });

        pane.find('#uuid-generate').click(function() {
            var uuid_field = settings_template.find('#settings-uuid');
            uuid_field.val(_.UUID.v4());
        });

        CloudPebble.Sidebar.SetActivePane(pane, 'settings');
    };

    var add_resource = function(resource) {
        var thing = settings_template.find('#settings-menu-image');
        var option = $('<option>').attr('value', resource.id).text(resource.file_name);
        thing.append(option);
        if(resource.id == CloudPebble.ProjectInfo.menu_icon) {
            thing.val(resource.id);
        }
    };

    var remove_resource = function(resource) {
        var thing = settings_template.find('#settings-menu-image');
        thing.find('[value=' + resource.id + ']').remove();
        if(resource.id == CloudPebble.ProjectInfo.menu_icon) {
            thing.val('');
            CloudPebble.ProjectInfo.menu_icon = null;
        }
    };

    return {
        Show: function() {
            show_settings_pane();
        },
        Init: function() {
            settings_template = $('#settings-pane-template').remove().removeClass('hide');
        },
        AddResource: function(resource) {
            add_resource(resource);
        },
        RemoveResource: function(resource) {
            remove_resource(resource);
        }
    };
})();
<|endoftext|>


<commit_before>/*
 * Namespace: lb.ui.Module
 * User Interface Modules of Legal Box Web Application
 *
 * Each User Interface Module corresponds to an independent unit of
 * functionality, which may be started and stopped.
 *
 * For the purpose of this life cycle management, a new Module instance is
 * created for each User Interface Module creator registered on the application
 * core Facade.
 *
 * Author:
 * Eric Bréchemier <legalbox@eric.brechemier.name>
 *
 * Copyright:
 * Legal Box (c) 2010, All Rights Reserved
 *
 * Version:
 * 2010-04-20
 */
/*requires lb.ui.js */
/*jslint nomen:false, white:false, onevar:false, plusplus:false */
/*global window, lb */
// preserve the module, if already loaded
lb.ui.Module = lb.ui.Module || function (name, creator){
  // Function: new Module(name,creator): Module
  // Constructor of a new User Interface Module.
  //
  // Parameters:
  //   name - string, the qualified module name, e.g. 'lb.ui.myModule'
  //   creator - function, a creator function returning a UI module.
  //             A new Sandbox instance will be provided as parameter.
  //
  // Returns:
  //   object, the new instance of lb.ui.Module

  // string, the status of underlying module
  var status = 'idle';

  // object, the underlying module instance
  var module;

  // object, the sandbox instance for the underlying module
  var sb;

  function getStatus(){
    // Function: getStatus(): string
    // Get the status of the underlying module
    //
    // Returns:
    // - 'idle' initially
    // - 'created' after a new instance gets created with provided creator
    // - 'started' after the module gets started
    // - 'stopped' after the module gets stopped
    // - 'failed' after a failure in creator(), start(), stop() or notify()

    return status;
  }

  function start(sandbox){
    // Function: start(sandbox)
    // Create and start the underlying module
    //
    // Parameters:
    //   sandbox - object, the sandbox instance for this UI module.
    //
    // Note:
    // Nothing happens in case no sandbox is provided.
    if (!sandbox){
      return;
    }

    try {
      sb = sandbox;
      module = creator(sandbox);
      status = 'created';
    } catch(e) {
      sb.log('ERROR: Failed to create module "'+name+
             '" using creator "'+creator+
             '" with sandbox "'+sandbox+
             '"; '+e+'.');
      status = 'failed';
      return;
    }

    try {
      module.start();
      status = 'started';
    } catch(e){
      sb.log('ERROR: Failed to start module "'+name+'"; '+e+'.');
      status = 'failed';
    }
  }

  function stop(){
    // Function: stop()
    // Stop the underlying module
    //
    // Note:
    // Nothing happens in case no sandbox has been provided in a start() call.
    if (!sb){
      return;
    }

    try {
      module.stop();
      status = 'stopped';
    } catch(e){
      sb.log('ERROR: Failed to stop module "'+name+'": '+e+'.');
      status = 'failed';
    }
  }

  function notify(event){
    // Function: notify(event)
    // Notify an event to the underlying module
    //
    // Parameter:
    //   event - object, the event subject of the notification
    //
    // Note:
    // Nothing happens in case no sandbox has been provided in a start() call.
    if (!sb){
      return;
    }

    try {
      module.notify(event);
    } catch(e){
      sb.log('ERROR: Failed to notify module "'+name+
                  '" of event "'+event+
                  '": '+e+'.');
      status = 'failed';
    }
  }

  // Public methods
  this.getStatus = getStatus;
  this.start = start;
  this.stop = stop;
  this.notify = notify;
  return this;
};
<commit_msg>renamed exceptions in try/catch based on JSLint error<commit_after>/*
 * Namespace: lb.ui.Module
 * User Interface Modules of Legal Box Web Application
 *
 * Each User Interface Module corresponds to an independent unit of
 * functionality, which may be started and stopped.
 *
 * For the purpose of this life cycle management, a new Module instance is
 * created for each User Interface Module creator registered on the application
 * core Facade.
 *
 * Author:
 * Eric Bréchemier <legalbox@eric.brechemier.name>
 *
 * Copyright:
 * Legal Box (c) 2010, All Rights Reserved
 *
 * Version:
 * 2010-04-20
 */
/*requires lb.ui.js */
/*jslint nomen:false, white:false, onevar:false, plusplus:false */
/*global window, lb */
// preserve the module, if already loaded
lb.ui.Module = lb.ui.Module || function (name, creator){
  // Function: new Module(name,creator): Module
  // Constructor of a new User Interface Module.
  //
  // Parameters:
  //   name - string, the qualified module name, e.g. 'lb.ui.myModule'
  //   creator - function, a creator function returning a UI module.
  //             A new Sandbox instance will be provided as parameter.
  //
  // Returns:
  //   object, the new instance of lb.ui.Module

  // string, the status of underlying module
  var status = 'idle';

  // object, the underlying module instance
  var module;

  // object, the sandbox instance for the underlying module
  var sb;

  function getStatus(){
    // Function: getStatus(): string
    // Get the status of the underlying module
    //
    // Returns:
    // - 'idle' initially
    // - 'created' after a new instance gets created with provided creator
    // - 'started' after the module gets started
    // - 'stopped' after the module gets stopped
    // - 'failed' after a failure in creator(), start(), stop() or notify()

    return status;
  }

  function start(sandbox){
    // Function: start(sandbox)
    // Create and start the underlying module
    //
    // Parameters:
    //   sandbox - object, the sandbox instance for this UI module.
    //
    // Note:
    // Nothing happens in case no sandbox is provided.
    if (!sandbox){
      return;
    }

    try {
      sb = sandbox;
      module = creator(sandbox);
      status = 'created';
    } catch(e1) {
      sb.log('ERROR: Failed to create module "'+name+
             '" using creator "'+creator+
             '" with sandbox "'+sandbox+
             '"; '+e1+'.');
      status = 'failed';
      return;
    }

    try {
      module.start();
      status = 'started';
    } catch(e2){
      sb.log('ERROR: Failed to start module "'+name+'"; '+e2+'.');
      status = 'failed';
    }
  }

  function stop(){
    // Function: stop()
    // Stop the underlying module
    //
    // Note:
    // Nothing happens in case no sandbox has been provided in a start() call.
    if (!sb){
      return;
    }

    try {
      module.stop();
      status = 'stopped';
    } catch(e){
      sb.log('ERROR: Failed to stop module "'+name+'": '+e+'.');
      status = 'failed';
    }
  }

  function notify(event){
    // Function: notify(event)
    // Notify an event to the underlying module
    //
    // Parameter:
    //   event - object, the event subject of the notification
    //
    // Note:
    // Nothing happens in case no sandbox has been provided in a start() call.
    if (!sb){
      return;
    }

    try {
      module.notify(event);
    } catch(e){
      sb.log('ERROR: Failed to notify module "'+name+
                  '" of event "'+event+
                  '": '+e+'.');
      status = 'failed';
    }
  }

  // Public methods
  this.getStatus = getStatus;
  this.start = start;
  this.stop = stop;
  this.notify = notify;
  return this;
};
<|endoftext|>


<commit_before>var LeaveEditorController = Ember.Controller.extend({
    args: Ember.computed.alias('model'),

    actions: {
        confirmAccept: function () {
            var args = this.get('args'),
                editorController,
                model,
                transition;

            if (Ember.isArray(args)) {
                editorController = args[0];
                transition = args[1];
                model = editorController.get('model');
            }

            if (!transition || !editorController) {
                this.notifications.showError('Sorry, there was an error in the application. Please let the Ghost team know what happened.');
                return true;
            }

            // definitely want to clear the data store and post of any unsaved, client-generated tags
            model.updateTags();

            if (model.get('isNew')) {
                // the user doesn't want to save the new, unsaved post, so delete it.
                model.deleteRecord();
            } else {
                // roll back changes on model props
                model.rollback();
            }

            // setting isDirty to false here allows willTransition on the editor route to succeed
            editorController.set('isDirty', false);

            // since the transition is now certain to complete, we can unset window.onbeforeunload here
            window.onbeforeunload = null;

            transition.retry();
        },

        confirmReject: function () {

        }
    },

    confirm: {
        accept: {
            text: 'Leave',
            buttonClass: 'button-delete'
        },
        reject: {
            text: 'Cancel',
            buttonClass: 'button'
        }
    }
});

export default LeaveEditorController;
<commit_msg>Change text on leave modal cancel button<commit_after>var LeaveEditorController = Ember.Controller.extend({
    args: Ember.computed.alias('model'),

    actions: {
        confirmAccept: function () {
            var args = this.get('args'),
                editorController,
                model,
                transition;

            if (Ember.isArray(args)) {
                editorController = args[0];
                transition = args[1];
                model = editorController.get('model');
            }

            if (!transition || !editorController) {
                this.notifications.showError('Sorry, there was an error in the application. Please let the Ghost team know what happened.');
                return true;
            }

            // definitely want to clear the data store and post of any unsaved, client-generated tags
            model.updateTags();

            if (model.get('isNew')) {
                // the user doesn't want to save the new, unsaved post, so delete it.
                model.deleteRecord();
            } else {
                // roll back changes on model props
                model.rollback();
            }

            // setting isDirty to false here allows willTransition on the editor route to succeed
            editorController.set('isDirty', false);

            // since the transition is now certain to complete, we can unset window.onbeforeunload here
            window.onbeforeunload = null;

            transition.retry();
        },

        confirmReject: function () {

        }
    },

    confirm: {
        accept: {
            text: 'Leave',
            buttonClass: 'button-delete'
        },
        reject: {
            text: 'Stay',
            buttonClass: 'button'
        }
    }
});

export default LeaveEditorController;
<|endoftext|>


<commit_before>var Lang = A.Lang,
	isString = Lang.isString,

	RESIZE_IFRAME = 'resizeiframe',

	getClassName = A.getClassName,

	HEIGHT = 'height',
	HIDDEN = 'hidden',
	NO = 'no',
	SCROLLING = 'scrolling',
	WIDTH = 'width',

	CSS_RESIZE_IFRAME_MONITORED_HEIGHT = getClassName(RESIZE_IFRAME, 'monitored', HEIGHT);

ResizeIframe = A.Component.create(
	{
		NAME: RESIZE_IFRAME,
		NS: RESIZE_IFRAME,

		EXTENDS: A.Plugin.Base,

		ATTRS: {
			height: {
				value: 0
			},
			monitorHeight: {
				value: true
			},
			width: {
				value: null
			}
		},

		prototype: {
			initializer: function(config) {
				var instance = this;

				var frame = instance.get('host');

				instance.node = frame;
				instance._iframeEl = frame.getDOM();

				instance._defaultHeight = config.height;

				instance.bindUI();
				instance.syncUI();
			},

			bindUI: function() {
				var instance = this;

				instance.after('heightChange', instance._afterHeightChange);
				instance.after('monitorHeightChange', instance._afterMonitorHeightChange);
				instance.after('widthChange', instance._afterWidthChange);
			},

			syncUI: function() {
				var instance = this;

				instance._uiSetMonitorHeight(instance.get('monitorHeight'));
			},

			destructor: function() {
				var instance = this;

				instance._uiSetMonitorHeight(false);
			},

			pauseMonitor: function() {
				var instance = this;

				instance._clearInterval();
			},

			restartMonitor: function() {
				var instance = this;

				if (instance.get('monitorHeight')) {
					instance._setInterval();
				}
			},

			_afterHeightChange: function(event) {
				var instance = this;

				instance.set('monitorHeight', false);

				instance._uiSetHeight(event.newVal);
			},

			_afterMonitorHeightChange: function(event) {
				var instance = this;

				instance._uiSetMonitorHeight(event.newVal);
			},

			_afterWidthChange: function(event) {
				var instance = this;

				instance._uiSetWidth(event.newVal);
			},

			_clearInterval: function() {
				var instance = this;

				var iframeDoc = instance._iframeDoc;

				if (iframeDoc) {
					var docEl = iframeDoc.documentElement;

					if (docEl) {
						docEl.style.overflowY = '';
					}
				}

				if (instance._intervalId) {
					A.clearInterval(instance._intervalId);

					instance._intervalId = null;
				}
			},

			_onResize: function() {
				var instance = this;

				instance._iframeDoc = null;

				var newHeight = instance._iframeHeight;
				var iframeWin = instance._iframeEl.contentWindow;

				var iframeDoc;

				try {
					iframeDoc = iframeWin.document;

					instance._iframeDoc = iframeDoc;
				}
				catch (e) {
				}

				if (iframeDoc) {
					newHeight = ResizeIframe._getContentHeight(iframeWin, iframeDoc, instance._iframeHeight);

					instance._uiSetHeight(newHeight);
				}
				else {
					instance._clearInterval();

					instance._uiSetHeight(instance._defaultHeight);
				}
			},

			_setInterval: function(event) {
				var instance = this;

				if (!instance._intervalId) {
					instance._onResize();

					instance._intervalId = A.setInterval(instance._onResize, 100, instance);
				}
			},

			_uiSetHeight: function(value) {
				var instance = this;

				if (instance._iframeHeight != value) {
					instance._iframeHeight = value;

					instance.node.setStyle(HEIGHT, value);
				}
			},

			_uiSetMonitorHeight: function(monitorHeight) {
				var instance = this;

				var iframe = instance.node;

				if (monitorHeight) {
					instance._setInterval();

					instance._loadHandle = iframe.on('load', instance._setInterval, instance);

					iframe.addClass(CSS_RESIZE_IFRAME_MONITORED_HEIGHT);
				}
				else {
					instance._clearInterval();

					if (instance._loadHandle) {
						instance._loadHandle.detach();
					}

					iframe.removeClass(CSS_RESIZE_IFRAME_MONITORED_HEIGHT);
				}
			},

			_uiSetWidth: function(value) {
				var instance = this;

				instance.node.setStyle(WIDTH, value);
			},

			_iframeHeight: 0
		}
	}
);

A.mix(
	ResizeIframe,
	{
		getContentHeight: function(iframeWin) {
			var contentHeight = null;

			try {
				var iframeDoc;

				if (iframeWin.nodeName && iframeWin.nodeName.toLowerCase() == 'iframe') {
					iframeWin = iframeWin.contentWindow;
				}
				else if (A.instanceOf(iframeWin, A.Node)) {
					iframeWin = iframeWin.getDOM().contentWindow;
				}

				iframeDoc = iframeWin.document;

				contentHeight = ResizeIframe._getContentHeight(iframeWin, iframeDoc);
			}
			catch (e) {
			}

			return contentHeight;
		},

		_getContentHeight: function(iframeWin, iframeDoc, fallbackHeight) {
			var contentHeight = null;

			if (iframeDoc && iframeWin.location.href != 'about:blank') {
				var docEl = iframeDoc.documentElement;
				var iframeBody = iframeDoc.body;

				if (docEl) {
					docEl.style.overflowY = HIDDEN;
				}

				var docOffsetHeight = (iframeBody && iframeBody.offsetHeight) || 0;

				var standardsMode = (iframeDoc.compatMode == 'CSS1Compat');

				if (standardsMode && docOffsetHeight) {
					contentHeight = docOffsetHeight;
				}
				else {
					contentHeight = ResizeIframe._getQuirksHeight(iframeWin) || fallbackHeight;
				}
			}

			return contentHeight;
		},

		_getQuirksHeight: function(iframeWin) {
			var contentHeight = 0;

			var iframeDoc = iframeWin.document;
			var docEl = iframeDoc && iframeDoc.documentElement;
			var iframeBody = iframeDoc && iframeDoc.body;

			var viewPortHeight = 0;

			if (iframeWin.innerHeight) {
				viewPortHeight = iframeWin.innerHeight;
			}
			else if (docEl && docEl.clientHeight) {
				viewPortHeight = docEl.clientHeight;
			}
			else if (iframeBody) {
				viewPortHeight = iframeBody.clientHeight;
			}

			if (iframeDoc) {
				var docClientHeight;
				var docScrollHeight;
				var docOffsetHeight = (iframeBody && iframeBody.offsetHeight);

				if (docEl) {
					docClientHeight = docEl.clientHeight;
					docScrollHeight = docEl.scrollHeight;
					docOffsetHeight = docEl.offsetHeight;
				}

				if (docClientHeight != docOffsetHeight && iframeBody) {
					docOffsetHeight = iframeBody.offsetHeight;
					docScrollHeight = iframeBody.scrollHeight;
				}

				var compareNum;

				if (docScrollHeight > viewPortHeight) {
					compareNum = Math.max;
				}
				else {
					compareNum = Math.min;
				}

				contentHeight = compareNum(docScrollHeight, docOffsetHeight);
			}

			return contentHeight;
		}
	}
);

A.Plugin.ResizeIframe = ResizeIframe;<commit_msg>AUI-632 - Source Formatting<commit_after>var Lang = A.Lang,
	isString = Lang.isString,

	RESIZE_IFRAME = 'resizeiframe',

	getClassName = A.getClassName,

	HEIGHT = 'height',
	HIDDEN = 'hidden',
	NO = 'no',
	SCROLLING = 'scrolling',
	WIDTH = 'width',

	CSS_RESIZE_IFRAME_MONITORED_HEIGHT = getClassName(RESIZE_IFRAME, 'monitored', HEIGHT);

ResizeIframe = A.Component.create(
	{
		NAME: RESIZE_IFRAME,
		NS: RESIZE_IFRAME,

		EXTENDS: A.Plugin.Base,

		ATTRS: {
			height: {
				value: 0
			},
			monitorHeight: {
				value: true
			},
			width: {
				value: null
			}
		},

		prototype: {
			initializer: function(config) {
				var instance = this;

				var frame = instance.get('host');

				instance.node = frame;
				instance._iframeEl = frame.getDOM();

				instance._defaultHeight = config.height;

				instance.bindUI();
				instance.syncUI();
			},

			bindUI: function() {
				var instance = this;

				instance.after('heightChange', instance._afterHeightChange);
				instance.after('monitorHeightChange', instance._afterMonitorHeightChange);
				instance.after('widthChange', instance._afterWidthChange);
			},

			syncUI: function() {
				var instance = this;

				instance._uiSetMonitorHeight(instance.get('monitorHeight'));
			},

			destructor: function() {
				var instance = this;

				instance._uiSetMonitorHeight(false);
			},

			pauseMonitor: function() {
				var instance = this;

				instance._clearInterval();
			},

			restartMonitor: function() {
				var instance = this;

				if (instance.get('monitorHeight')) {
					instance._setInterval();
				}
			},

			_afterHeightChange: function(event) {
				var instance = this;

				instance.set('monitorHeight', false);

				instance._uiSetHeight(event.newVal);
			},

			_afterMonitorHeightChange: function(event) {
				var instance = this;

				instance._uiSetMonitorHeight(event.newVal);
			},

			_afterWidthChange: function(event) {
				var instance = this;

				instance._uiSetWidth(event.newVal);
			},

			_clearInterval: function() {
				var instance = this;

				var iframeDoc = instance._iframeDoc;

				if (iframeDoc) {
					var docEl = iframeDoc.documentElement;

					if (docEl) {
						docEl.style.overflowY = '';
					}
				}

				if (instance._intervalId) {
					A.clearInterval(instance._intervalId);

					instance._intervalId = null;
				}
			},

			_onResize: function() {
				var instance = this;

				instance._iframeDoc = null;

				var newHeight = instance._iframeHeight;

				var iframeDoc;
				var iframeWin;

				try {
					iframeWin = instance._iframeEl.contentWindow;

					iframeDoc = iframeWin.document;

					instance._iframeDoc = iframeDoc;
				}
				catch (e) {
				}

				if (iframeDoc && iframeWin) {
					newHeight = ResizeIframe._getContentHeight(iframeWin, iframeDoc, instance._iframeHeight);

					instance._uiSetHeight(newHeight);
				}
				else if (!iframeDoc) {
					instance._clearInterval();

					instance._uiSetHeight(instance._defaultHeight);
				}
			},

			_setInterval: function(event) {
				var instance = this;

				if (!instance._intervalId) {
					instance._onResize();

					instance._intervalId = A.setInterval(instance._onResize, 100, instance);
				}
			},

			_uiSetHeight: function(value) {
				var instance = this;

				if (instance._iframeHeight != value) {
					instance._iframeHeight = value;

					instance.node.setStyle(HEIGHT, value);
				}
			},

			_uiSetMonitorHeight: function(monitorHeight) {
				var instance = this;

				var iframe = instance.node;

				if (monitorHeight) {
					instance._setInterval();

					instance._loadHandle = iframe.on('load', instance._setInterval, instance);

					iframe.addClass(CSS_RESIZE_IFRAME_MONITORED_HEIGHT);
				}
				else {
					instance._clearInterval();

					if (instance._loadHandle) {
						instance._loadHandle.detach();
					}

					iframe.removeClass(CSS_RESIZE_IFRAME_MONITORED_HEIGHT);
				}
			},

			_uiSetWidth: function(value) {
				var instance = this;

				instance.node.setStyle(WIDTH, value);
			},

			_iframeHeight: 0
		}
	}
);

A.mix(
	ResizeIframe,
	{
		getContentHeight: function(iframeWin) {
			var contentHeight = null;

			try {
				var iframeDoc;

				if (iframeWin.nodeName && iframeWin.nodeName.toLowerCase() == 'iframe') {
					iframeWin = iframeWin.contentWindow;
				}
				else if (A.instanceOf(iframeWin, A.Node)) {
					iframeWin = iframeWin.getDOM().contentWindow;
				}

				iframeDoc = iframeWin.document;

				contentHeight = ResizeIframe._getContentHeight(iframeWin, iframeDoc);
			}
			catch (e) {
			}

			return contentHeight;
		},

		_getContentHeight: function(iframeWin, iframeDoc, fallbackHeight) {
			var contentHeight = null;

			if (iframeDoc && iframeWin.location.href != 'about:blank') {
				var docEl = iframeDoc.documentElement;
				var iframeBody = iframeDoc.body;

				if (docEl) {
					docEl.style.overflowY = HIDDEN;
				}

				var docOffsetHeight = (iframeBody && iframeBody.offsetHeight) || 0;

				var standardsMode = (iframeDoc.compatMode == 'CSS1Compat');

				if (standardsMode && docOffsetHeight) {
					contentHeight = docOffsetHeight;
				}
				else {
					contentHeight = ResizeIframe._getQuirksHeight(iframeWin) || fallbackHeight;
				}
			}

			return contentHeight;
		},

		_getQuirksHeight: function(iframeWin) {
			var contentHeight = 0;

			var iframeDoc = iframeWin.document;
			var docEl = iframeDoc && iframeDoc.documentElement;
			var iframeBody = iframeDoc && iframeDoc.body;

			var viewPortHeight = 0;

			if (iframeWin.innerHeight) {
				viewPortHeight = iframeWin.innerHeight;
			}
			else if (docEl && docEl.clientHeight) {
				viewPortHeight = docEl.clientHeight;
			}
			else if (iframeBody) {
				viewPortHeight = iframeBody.clientHeight;
			}

			if (iframeDoc) {
				var docClientHeight;
				var docScrollHeight;
				var docOffsetHeight = (iframeBody && iframeBody.offsetHeight);

				if (docEl) {
					docClientHeight = docEl.clientHeight;
					docScrollHeight = docEl.scrollHeight;
					docOffsetHeight = docEl.offsetHeight;
				}

				if (docClientHeight != docOffsetHeight && iframeBody) {
					docOffsetHeight = iframeBody.offsetHeight;
					docScrollHeight = iframeBody.scrollHeight;
				}

				var compareNum;

				if (docScrollHeight > viewPortHeight) {
					compareNum = Math.max;
				}
				else {
					compareNum = Math.min;
				}

				contentHeight = compareNum(docScrollHeight, docOffsetHeight);
			}

			return contentHeight;
		}
	}
);

A.Plugin.ResizeIframe = ResizeIframe;<|endoftext|>


<commit_before>$(document).ready(function(){

	var customer_id; // must set to zero if customer is deleted
	var counter=0;
	var mode;
	var customer_dup;
	var url_action;
	var customers = [];

	$.post($('#base_url').attr('base-url')+'customers/get_customer', function(response){
		$.each(JSON.parse(response), function(index, value){
			if(customers.indexOf(value.complete_name) == -1 && value.complete_name != null){
				customers.push(value.complete_name);
			}
		});
		$('#search_customer').autocomplete({
			lookup: customers,
			width: 280
		});
	});

	var source = $('#display_picture').attr('source');
	$('#display_picture').attr('src', source+'/user.png');
	$('[name=mobilenumber]').inputmask('9999 999 9999');

	$('.list-group').on('click', '.customers', function(e){
		e.preventDefault();
		if(customer_id != $(this).attr('customer_id')){
			$('#customer_id').text('Loading...');
			customer_id = $(this).attr('customer_id');
			$('.customers').removeClass('active');
			$('[customer_id='+customer_id+']').addClass('active');

			$.post($('.list-group').attr('get-url'), {id:customer_id}, function(response){
				var customer = JSON.parse(response);
				customer_dup = customer[0];
				$.each(customer[0], function(index, value){
					var new_value = (value) ? value : '';
					if(index=='display_picture'){
						var source = $('#'+index).attr('source');
						if(!new_value){
							$('#'+index).attr('src', source+'/user.png');
						}else{
							$('#'+index).attr('src', source+'/'+value);
						}
					}else if(index=='deleted_at'){
						var text = (new_value.length==0) ? 'Active' : 'Inactive';
						$('#'+index).text(text);
					}else{
						$('#'+index).text(new_value);
					}
				});
				var del_url = $('#btn-delete').attr('base-url');
				$('#btn-delete').attr('href', del_url+'/'+customer_id);
				$('#btn-update, #btn-delete').removeClass('disabled');
			});
		}
	});

	$('.add-btn').click(function(e){
		e.preventDefault();
		mode = 1;
		url_action = $('#form_customer').attr('add-url');
		$('.modal-body').find('form')[0].reset();
		$('#myModal').modal('show');
	});

	$('#btn-update').click(function(e){
		e.preventDefault();
		url_action = $('#form_customer').attr('update-url');
		mode = 0;
	});

	$('#myModal').on('show.bs.modal', function(e){
		if(mode==1){
			$('.modal-title').html('Add Customer');
		}else{
			$('.modal-title').html('Update Customer - '+$('#firstname').text()+' '+$('#lastname').text());
			$.each(customer_dup, function(index, value){
				var new_value = (value) ? value : '';
				if(index==='guarantor_id'){
					$('[name=guarantor_customers_id]').val(new_value);
				}else{
					$('[name='+index+']').val(new_value);
				}
			});
			$('option[value='+customer_dup.id+']').wrap('<span/>');
		}
	});

	$('#myModal').on('hidden.bs.modal', function(e){
		$('.form-group').removeClass('has-error');
		$('.errhandler').html('');
		if(mode!=1) $('option[value='+customer_dup.id+']').unwrap();
	});

	$('#form_customer').submit(function(e){
		e.preventDefault();
		$(this).ajaxSubmit({url:url_action, success:function(responseText){
			var response = JSON.parse(responseText);
			if(mode==1){	// add
				if(response.status){	// add success
					location.reload();
				}else{						// add fail
					$.each(response.data, function(index, value){
						$('[errhandler='+index+']').html(value);
						$('[name='+index+']').parent().addClass('has-error');
					})
				}
			}else{			// update
				if(response.status){	// update success
					location.reload();
				}else{						// update fail
					$.each(response.data, function(index, value){
						$('[errhandler='+index+']').html(value);
						$('[name='+index+']').parent().addClass('has-error');
					})
				}
			}
		}});
	});

	$('#forCustomerSettings').click(function(e){
		e.preventDefault();
		$('#customerSettings').modal('show');
	});

	$('#btn-setting').click(function(e){
		var set_page = $('[name=set_page]').val();
		var set_sortby = $('[name=set_sortby]').val();
		var set_orderby = $('[name=set_orderby]:checked').val();
		var set_display = ($('[name=set_display]').is(':checked')) ? 1 : 0;

		var setting_url = $('#form_setting').attr('action');
		setting_url = setting_url+"/"+set_page+"/"+set_sortby+"/"+set_orderby+"/"+set_display;
	});

});<commit_msg>nabilin. hahahaha<commit_after>$(document).ready(function(){

	var customer_id; // must set to zero if customer is deleted
	var counter=0;
	var mode;
	var customer_dup;
	var url_action;
	var customers = [];

	$.post($('#base_url').attr('base-url')+'customers/get_customer', function(response){
		$.each(JSON.parse(response), function(index, value){
			if(customers.indexOf(value.complete_name) == -1 && value.complete_name != null){
				customers.push(value.complete_name);
			}
		});
		$('#search_customer').autocomplete({
			lookup: customers,
			width: 280
		});
	});

	var source = $('#display_picture').attr('source');
	$('#display_picture').attr('src', source+'/user.png');
	$('[name=mobilenumber]').inputmask('9999 999 9999');

	$('.list-group').on('click', '.customers', function(e){
		e.preventDefault();
		if(customer_id != $(this).attr('customer_id')){
			$('#customer_id').text('Loading...');
			customer_id = $(this).attr('customer_id');
			$('.customers').removeClass('active');
			$('[customer_id='+customer_id+']').addClass('active');

			$.post($('.list-group').attr('get-url'), {id:customer_id}, function(response){
				var customer = JSON.parse(response);
				customer_dup = customer[0];
				$.each(customer[0], function(index, value){
					var new_value = (value) ? value : '';
					if(index=='display_picture'){
						var source = $('#'+index).attr('source');
						if(!new_value){
							$('#'+index).attr('src', source+'/user.png');
						}else{
							$('#'+index).attr('src', source+'/'+value);
						}
					}else if(index=='deleted_at'){
						var text = (new_value.length==0) ? 'Active' : 'Inactive';
						$('#'+index).text(text);
					}else{
						$('#'+index).text(new_value);
					}
				});
				var del_url = $('#btn-delete').attr('base-url');
				$('#btn-delete').attr('href', del_url+'/'+customer_id);
				$('#btn-update, #btn-delete').removeClass('disabled');
			});
		}
	});

	$('.add-btn').click(function(e){
		e.preventDefault();
		mode = 1;
		url_action = $('#form_customer').attr('add-url');
		$('.modal-body').find('form')[0].reset();
		$('#myModal').modal('show');
	});

	$('#btn-update').click(function(e){
		e.preventDefault();
		url_action = $('#form_customer').attr('update-url');
		mode = 0;
	});

	$('#myModal').on('show.bs.modal', function(e){
		if(mode==1){
			$('.modal-title').html('Add Customer');
		}else{
			$('.modal-title').html('Update Customer - '+$('#firstname').text()+' '+$('#lastname').text());
			$.each(customer_dup, function(index, value){
				var new_value = (value) ? value : '';
				if(index==='guarantor_id'){
					$('[name=guarantor_customers_id]').val(new_value);
				}else{
					$('[name='+index+']').val(new_value);
				}
			});
			$('option[value='+customer_dup.id+']').wrap('<span/>');
		}
	});

	$('#myModal').on('hidden.bs.modal', function(e){
		$('.form-group').removeClass('has-error');
		$('.errhandler').html('');
		if(mode!=1) $('option[value='+customer_dup.id+']').unwrap();
	});

	$('#form_customer').submit(function(e){
		e.preventDefault();
		$(this).ajaxSubmit({url:url_action, success:function(responseText){
			var response = JSON.parse(responseText);
			if(mode==1){	// add
				if(response.status){	// add success
					location.reload();
				}else{						// add fail
					$.each(response.data, function(index, value){
						$('[errhandler='+index+']').html(value);
						$('[name='+index+']').parent().addClass('has-error');
					})
				}
			}else{			// update
				if(response.status){	// update success
					location.reload();
				}else{						// update fail
					$.each(response.data, function(index, value){
						$('[errhandler='+index+']').html(value);
						$('[name='+index+']').parent().addClass('has-error');
					})
				}
			}
		}});
	});

	$('#forCustomerSettings').click(function(e){
		e.preventDefault();
		$('#customerSettings').modal('show');
	});

	$('#btn-setting').click(function(e){
		var set_page = $('[name=set_page]').val();
		var set_sortby = $('[name=set_sortby]').val();
		var set_orderby = $('[name=set_orderby]:checked').val();
		var set_display = ($('[name=set_display]').is(':checked')) ? 1 : 0;

		var setting_url = $('#form_setting').attr('action');
		setting_url = setting_url+"/"+set_page+"/"+set_sortby+"/"+set_orderby+"/"+set_display;
		window.location.href = setting_url;
	});

});<|endoftext|>


<commit_before>var pom = {
	repos : {
		'google' : '//ajax.googleapis.com/ajax/libs',
		'bootstrapcdn' : '//netdna.bootstrapcdn.com',
		'cloudfare' : '//cdnjs.cloudflare.com/ajax/libs',
		'jsdelivr' : '//cdn.jsdelivr.net'
	},
	versions : {
		'jquery' : '1.7.2',
		'jqueryui' : '1.10.2',
		'jquerycolor' : '2.1.2',
		'bootstrap' : '2.3.1',
		'datetimepicker' : '0.0.11',
		'flot' : '0.8',
		'sparkline' : '2.1',
		'fullcalendar' : '1.6.0',
		'sizzle' : '1.9.1',
		'prettyphoto' : '3.1.4'
	},
	cssDependencies :  {

		//css delivered via cdn
		'bootstrap' : '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css',
		'bootstrap-datetimepicker' : '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/0.0.11/css/bootstrap-datetimepicker.min.css',
		'bootstrap-responsive' : '//cdn.jsdelivr.net/bootstrap/2.3.2/css/bootstrap-responsive.css',
		'fontawesome' : '//cdnjs.cloudflare.com/ajax/libs/font-awesome/3.1.0/css/font-awesome.min.css',
		'jqueryui' : '//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.2/css/smoothness/jquery-ui-1.10.2.custom.css',
		'fullcalendar' : '//cdnjs.cloudflare.com/ajax/libs/fullcalendar/1.6.1/fullcalendar.css',
		'prettyphoto' : '//cdn.jsdelivr.net/prettyphoto/3.1.5/css/prettyPhoto.css',

		//stored css
		'rateit' : 'css/rateit.css',
		'gritter' : 'css/jquery.gritter.css',
		'cleditor' : 'css/jquery.cleditor.css',
		'style' : 'css/style.css',
		'widgets' : 'css/widgets.css',
		'bootstrap-switch' : 'css/bootstrap-switch.css',
		'kendo-common' : 'css/kendo.common.min.css',
		'kendo-metro' : 'css/kendo.metro.min.css'
	}
}

requirejs.config({
	//transitive dependencies
	shim: {
		'sparkline' : ['jquery'],
		'sizzle' : ['jquery'],
		'color' : ['jquery'],
		'prettyPhoto' : ['jquery'],
		'jquery.cleditor.min' : ['jquery'],
		'jquery.gritter.min' : ['jquery'],
		'jquery.rateit.min' : ['jquery'],
		'jquery.toggle.buttons' : ['jquery'],
		'fullcalendar' : ['jquery'],
		'flot': ['jquery'],
        'flot.pie': ['flot', 'jquery'],
        'flot.resize': ['flot', 'jquery'],
        'flot.stack': ['flot', 'jquery'],
        'flot.time': ['flot', 'jquery'],
        'excanvas': ['flot', 'jquery'],
        'bootstrap' : ['jquery'],
        'jquery-ui' :['jquery'],
        'bootstrap-datetimepicker' :['bootstrap'],
        'kendo.web' : ['jquery'],
        'mustache' : [],

    },
	"baseUrl" : "js",
	"paths" : {
		"lib" : "lib",
		"app" : "app",
		"core" : "core",
		"gadget" : "gadget",
		"jquery" : pom.repos.google + "/jquery/" + pom.versions.jquery + "/jquery.min",
		"jquery-ui" : pom.repos.google + "/jqueryui/" + pom.versions.jqueryui + "/jquery-ui.min",
		"bootstrap" : pom.repos.cloudfare + "/twitter-bootstrap/" + pom.versions.bootstrap + "/js/bootstrap.min",
		"bootstrap-datetimepicker" : pom.repos.cloudfare + "/bootstrap-datetimepicker/" + pom.versions.datetimepicker + "/js/bootstrap-datetimepicker.min",
		"bootstrap-switch" : pom.repos.cloudfare + "/bootstrap-switch/1.3/bootstrapSwitch.min",
		"flot" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.min",
		"flot.pie" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.pie.min",
		"flot.resize" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.resize.min",
		"flot.stack" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.stack.min",
		"flot.time" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.time.min",
		"excanvas" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/excanvas.min",
		"sparkline" : pom.repos.jsdelivr + "/jquery.sparkline/" + pom.versions.sparkline + "/jquery.sparkline.min",
		"fullcalendar" : pom.repos.cloudfare + "/fullcalendar/" + pom.versions.fullcalendar + "/fullcalendar.min",
		"sizzle" : pom.repos.cloudfare + "/sizzle/" + pom.versions.sizzle + "/sizzle.min",
		"color" : pom.repos.cloudfare + "/jquery-color/" + pom.versions.jquerycolor + "/jquery.color.min",
		"prettyPhoto" : pom.repos.jsdelivr + "/prettyphoto/" + pom.versions.prettyphoto + "/jquery.prettyPhoto",
		"kendo-web" : "lib/kendo.web",
		//"jquery" : "lib/offline/jquery.min",
		"mustache" : "lib/offline/mustache"
	}
});

// Load the main app module to start the app
require(["core/sandbox"], function(Sandbox) {
	Sandbox.Core.Loader.loadCSS();
})

<commit_msg>pom.js annotated<commit_after>/**
 * Project Object Model (POM) object defines Content Delivery Networks (CDN's)
 * and local paths of required JavaScipt (JS) libraries and Cascading Style
 * Sheet (CSS) documents. It also manages versions of required JS libraries and
 * CSS files.
 *
 * @see {@link http://requirejs.org/docs/api.html#config} for further
 *      information
 */
var pom = {

	repos : {
		'google' : '//ajax.googleapis.com/ajax/libs',
		'bootstrapcdn' : '//netdna.bootstrapcdn.com',
		'cloudfare' : '//cdnjs.cloudflare.com/ajax/libs',
		'jsdelivr' : '//cdn.jsdelivr.net'
	},
	versions : {
		'jquery' : '1.7.2',
		'jqueryui' : '1.10.2',
		'jquerycolor' : '2.1.2',
		'bootstrap' : '2.3.1',
		'datetimepicker' : '0.0.11',
		'flot' : '0.8',
		'sparkline' : '2.1',
		'fullcalendar' : '1.6.0',
		'sizzle' : '1.9.1',
		'prettyphoto' : '3.1.4'
	},
	cssDependencies :  {

		// css delivered via cdn
		'bootstrap' : '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.1/css/bootstrap.min.css',
		'bootstrap-datetimepicker' : '//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/0.0.11/css/bootstrap-datetimepicker.min.css',
		'bootstrap-responsive' : '//cdn.jsdelivr.net/bootstrap/2.3.2/css/bootstrap-responsive.css',
		'fontawesome' : '//cdnjs.cloudflare.com/ajax/libs/font-awesome/3.1.0/css/font-awesome.min.css',
		'jqueryui' : '//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.10.2/css/smoothness/jquery-ui-1.10.2.custom.css',
		'fullcalendar' : '//cdnjs.cloudflare.com/ajax/libs/fullcalendar/1.6.1/fullcalendar.css',
		'prettyphoto' : '//cdn.jsdelivr.net/prettyphoto/3.1.5/css/prettyPhoto.css',

		// stored css
		'rateit' : 'css/rateit.css',
		'gritter' : 'css/jquery.gritter.css',
		'cleditor' : 'css/jquery.cleditor.css',
		'style' : 'css/style.css',
		'widgets' : 'css/widgets.css',
		'bootstrap-switch' : 'css/bootstrap-switch.css',
		'kendo-common' : 'css/kendo.common.min.css',
		'kendo-metro' : 'css/kendo.metro.min.css'
	}
}

/**
 * Project Object Model (POM) object defines Content Delivery Networks (CDN's)
 * and local paths of required JavaScrpt (JS) libraries and Cascading Style
 * Sheet (CSS) documents. It also manages versions of required JS libraries and
 * CSS files.
 */
requirejs.config({

    /**
	 * @cfg {String} shim (optional) Configure the dependencies, exports, and
	 *      custom initialization for older, traditional "browser globals"
	 *      scripts that do not use define() to declare the dependencies and set
	 *      a module value.
	 */
	shim: {
		'sparkline' : ['jquery'],
		'sizzle' : ['jquery'],
		'color' : ['jquery'],
		'prettyPhoto' : ['jquery'],
		'jquery.cleditor.min' : ['jquery'],
		'jquery.gritter.min' : ['jquery'],
		'jquery.rateit.min' : ['jquery'],
		'jquery.toggle.buttons' : ['jquery'],
		'fullcalendar' : ['jquery'],
		'flot': ['jquery'],
        'flot.pie': ['flot', 'jquery'],
        'flot.resize': ['flot', 'jquery'],
        'flot.stack': ['flot', 'jquery'],
        'flot.time': ['flot', 'jquery'],
        'excanvas': ['flot', 'jquery'],
        'bootstrap' : ['jquery'],
        'jquery-ui' :['jquery'],
        'bootstrap-datetimepicker' :['bootstrap'],
        'kendo.web' : ['jquery'],
        'mustache' : [],

    },

    /**
	 * @cfg {String} baseUrl (required) The root path to use for all module
	 *      lookups.
	 */
	"baseUrl" : "js",

    /**
	 * @cfg {String} paths (required) Path mappings for module names not found
	 *      directly under baseUrl. The path settings are assumed to be relative
	 *      to baseUrl, unless the paths setting starts with a "/" or has a URL
	 *      protocol in it ("like http:").
	 */
	"paths" : {
		"lib" : "lib",
		"app" : "app",
		"core" : "core",
		"gadget" : "gadget",
		"jquery" : pom.repos.google + "/jquery/" + pom.versions.jquery + "/jquery.min",
		"jquery-ui" : pom.repos.google + "/jqueryui/" + pom.versions.jqueryui + "/jquery-ui.min",
		"bootstrap" : pom.repos.cloudfare + "/twitter-bootstrap/" + pom.versions.bootstrap + "/js/bootstrap.min",
		"bootstrap-datetimepicker" : pom.repos.cloudfare + "/bootstrap-datetimepicker/" + pom.versions.datetimepicker + "/js/bootstrap-datetimepicker.min",
		"bootstrap-switch" : pom.repos.cloudfare + "/bootstrap-switch/1.3/bootstrapSwitch.min",
		"flot" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.min",
		"flot.pie" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.pie.min",
		"flot.resize" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.resize.min",
		"flot.stack" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.stack.min",
		"flot.time" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/jquery.flot.time.min",
		"excanvas" : pom.repos.cloudfare + "/flot/" + pom.versions.flot + "/excanvas.min",
		"sparkline" : pom.repos.jsdelivr + "/jquery.sparkline/" + pom.versions.sparkline + "/jquery.sparkline.min",
		"fullcalendar" : pom.repos.cloudfare + "/fullcalendar/" + pom.versions.fullcalendar + "/fullcalendar.min",
		"sizzle" : pom.repos.cloudfare + "/sizzle/" + pom.versions.sizzle + "/sizzle.min",
		"color" : pom.repos.cloudfare + "/jquery-color/" + pom.versions.jquerycolor + "/jquery.color.min",
		"prettyPhoto" : pom.repos.jsdelivr + "/prettyphoto/" + pom.versions.prettyphoto + "/jquery.prettyPhoto",
		"kendo-web" : "lib/kendo.web",
		// "jquery" : "lib/offline/jquery.min",
		"mustache" : "lib/offline/mustache"
	}
});

// Load the main app module to start the app
require(["core/sandbox"],
		// This function will be called when all the dependencies
        // listed above in deps are loaded. Note that this
        // function could be called before the page is loaded.
        // This callback is optional.
		function(Sandbox) {
	Sandbox.Core.Loader.loadCSS();
})

<|endoftext|>


<commit_before>import {Readable} from "stream"
import {basename} from "path"

import invariant from "@octetstream/invariant"
import mimes from "mime-types"

import bind from "./util/bind"
import concat from "./util/concat"
import nextTick from "./util/nextTick"
import boundary from "./util/boundary"

import isString from "./util/isString"

import isBuffer from "./util/isBuffer"
import isReadable from "./util/isReadable"

import StreamIterator from "./util/StreamIterator"

class FormData {
  constructor() {
    bind([
      Symbol.iterator, Symbol.asyncIterator,
      "toString", "toJSON", "inspect",
      "keys", "values", "entries"
    ], this)

    this.__carriage = "\r\n"
    this.__defaultContentType = "application/octet-steam"

    this.__dashes = "--"
    this.__boundary = concat("NodeJSFormDataStream", boundary())

    this.__contents = new Map()
    this.__entries = this.__contents.entries()

    this.__curr = this.__getField()

    const read = this.__read

    this.__stream = new Readable({read})
  }

  /**
   * Check if given value is instance of FormData
   * Note: This method is not a part of client-side FormData interface.
   *
   * @param {any} value
   *
   * @return {boolean}
   */
  static isFormData(value) {
    return value instanceof FormData
  }

  __getMime = filename => mimes.lookup(filename) || this.__defaultContentType

  __getHeader(name, filename) {
    const head = [
      this.__dashes, this.__boundary, this.__carriage,
      "Content-Disposition: form-data; ", `name="${name}"`,
    ]

    if (filename) {
      head.push(`; filename="${filename}"${this.__carriage}`)
      head.push(`Content-Type: "${this.__getMime(filename)}"`)
    }

    head.push(this.__carriage.repeat(2))

    return Buffer.from(concat(head))
  }

  __getFooter = () => (
    Buffer.from(
      concat(
        this.__dashes, this.__boundary,
        this.__dashes, this.__carriage.repeat(2)
      )
    )
  )

  /**
   * @private
   */
  async* __getField() {
    while (true) {
      await nextTick()

      const curr = this.__entries.next()

      if (curr.done === true) {
        yield this.__getFooter()

        return
      }

      const [name, {values, filename}] = curr.value

      yield this.__getHeader(name, filename)

      for (const value of values) {
        if (isReadable(value)) {
          yield* new StreamIterator(value) // Read the stream contents
        } else {
          yield value
        }
      }

      yield this.__carriage
    }
  }

  /**
   * Read values from internal storage and push it to the internal stream
   *
   * @private
   */
  __read = () => {
    const onFulfilled = curr => {
      if (curr.done) {
        return this.__stream.push(null)
      }

      const chunk = curr.value

      this.__stream.push(isBuffer(chunk) ? chunk : Buffer.from(chunk))
    }

    const onRejected = err => this.__stream.emit("error", err)

    this.__curr.next().then(onFulfilled, onRejected)
  }

  /**
   * Set a new filed to internal FormData Map object
   *
   * @param {string} name
   * @param {any} value
   * @param {string} filename
   * @param {number} mode – a value setting mode. Can be:
   *   * 0 – disallow appending or replacing existing field
   *   * 1 – replace existing field value
   *   * 2 – append a new value for existing field
   *
   * @return {void}
   */
  __setField(name, value, filename, mode = 0) {
    invariant(
      !isString(name), TypeError,
      "Field name should be a string. Received %s", typeof name
    )

    invariant(
      filename && !isString(filename), TypeError,
      "Filename should be a string (if passed). Received %s", typeof filename
    )

    // Try to get a filename for buffer and stream values
    if (isBuffer(value) && filename) {
      filename = basename(filename)
    } else if (isReadable(value) && (value.path || filename)) {
      filename = basename(value.path || filename)
    }

    const field = this.__contents.get(name)

    if (!field) {
      return void this.__contents.set(name, {filename, values: [value]})
    }

    if (!mode || mode > 2) {
      return
    }

    if (mode === 1) {
      return void this.__contents.set(name, {filename, values: [value]})
    }

    field.values.push(value)

    this.__contents.set(name, field)
  }

  /**
   * Returns boundary string
   */
  get boundary() {
    return this.__boundary
  }

  /**
   * Returns the internal stream
   *
   * @return {stream.Readable}
   */
  get stream() {
    return this.__stream
  }

  append = (name, value, filename) => this.__setField(name, value, filename, 2)

  /**
   * Set new field on FormData
   *
   * @param {string} name – field name
   * @param {any} value – field value
   * @param {string} filename
   *
   * @return {void}
   */
  set = (name, value, filename) => this.__setField(name, value, filename, 1)

  /**
   * Check if the value with given key exists
   *
   * @param {string} name – name of a value you are looking for
   *
   * @return {boolean}
   */
  has = name => this.__contents.has(name)

  get = name => {
    const field = this.__contents.get(name)

    // NOTE: This method should return only the first field value.
    // I should add this behaviour somehow
    if (!field) {
      return void 0
    }

    const [value] = field.values

    return isBuffer(value) || isReadable(value) ? value : String(value)
  }

  getAll = name => {
    const res = []

    const field = this.__contents.get(name)

    if (field) {
      for (const value of field.values) {
        res.push(isBuffer(value) || isReadable(value) ? value : String(value))
      }
    }

    return res
  }

  delete = name => void this.__contents.delete(name)

  pipe = (dest, options) => this.__stream.pipe(dest, options)

  on = (name, fn) => {
    this.__stream.on(name, fn)

    return this
  }

  forEach = (fn, ctx = null) => {
    for (const [name, value] of this.entries()) {
      fn.call(ctx, value, name, this)
    }
  }

  toString() {
    return `[object ${this.constructor.name}]`
  }

  toJSON() {
    return this.constructor.name
  }

  inspect() {
    return this.constructor.name
  }

  * keys() {
    for (const key of this.__contents.keys()) {
      yield key
    }
  }

  * values() {
    for (const name of this.keys()) {
      const value = this.getAll(name)

      yield value.length === 1 ? value[0] : value
    }
  }

  * entries() {
    for (const name of this.keys()) {
      const value = this.getAll(name)

      yield [name, value.length === 1 ? value[0] : value]
    }
  }

  [Symbol.iterator]() {
    return this.entries()
  }

  /**
   * This method allows to read a content from internal stream
   * using async generators and for-await..of APIs
   *
   * @return {StreamIterator}
   */
  [Symbol.asyncIterator]() {
    return new StreamIterator(this.__stream)
  }
}

export default FormData
<commit_msg>Tiny fix<commit_after>import {Readable} from "stream"
import {basename} from "path"

import invariant from "@octetstream/invariant"
import mimes from "mime-types"

import bind from "./util/bind"
import concat from "./util/concat"
import nextTick from "./util/nextTick"
import boundary from "./util/boundary"

import isString from "./util/isString"

import isBuffer from "./util/isBuffer"
import isReadable from "./util/isReadable"

import StreamIterator from "./util/StreamIterator"

class FormData {
  constructor() {
    bind([
      Symbol.iterator, Symbol.asyncIterator,
      "toString", "toJSON", "inspect",
      "keys", "values", "entries"
    ], this)

    this.__carriage = "\r\n"
    this.__defaultContentType = "application/octet-steam"

    this.__dashes = "--"
    this.__boundary = concat("NodeJSFormDataStream", boundary())

    this.__contents = new Map()
    this.__entries = this.__contents.entries()

    this.__curr = this.__getField()

    const read = this.__read

    this.__stream = new Readable({read})
  }

  /**
   * Check if given value is instance of FormData
   * Note: This method is not a part of client-side FormData interface.
   *
   * @param {any} value
   *
   * @return {boolean}
   */
  static isFormData(value) {
    return value instanceof FormData
  }

  __getMime = filename => mimes.lookup(filename) || this.__defaultContentType

  __getHeader(name, filename) {
    const head = [
      this.__dashes, this.__boundary, this.__carriage,
      "Content-Disposition: form-data; ", `name="${name}"`,
    ]

    if (filename) {
      head.push(`; filename="${filename}"${this.__carriage}`)
      head.push(`Content-Type: "${this.__getMime(filename)}"`)
    }

    head.push(this.__carriage.repeat(2))

    return Buffer.from(concat(head))
  }

  __getFooter = () => (
    Buffer.from(
      concat(
        this.__dashes, this.__boundary,
        this.__dashes, this.__carriage.repeat(2)
      )
    )
  )

  /**
   * @private
   */
  async* __getField() {
    while (true) {
      await nextTick()

      const curr = this.__entries.next()

      if (curr.done === true) {
        yield this.__getFooter()

        return
      }

      const [name, {values, filename}] = curr.value

      yield this.__getHeader(name, filename)

      for (const value of values) {
        if (isReadable(value)) {
          yield* new StreamIterator(value) // Read the stream contents
        } else {
          yield value
        }
      }

      yield this.__carriage
    }
  }

  /**
   * Read values from internal storage and push it to the internal stream
   *
   * @private
   */
  __read = () => {
    const onFulfilled = curr => {
      if (curr.done) {
        return this.__stream.push(null)
      }

      const chunk = curr.value

      this.__stream.push(isBuffer(chunk) ? chunk : Buffer.from(String(chunk)))
    }

    const onRejected = err => this.__stream.emit("error", err)

    this.__curr.next().then(onFulfilled, onRejected)
  }

  /**
   * Set a new filed to internal FormData Map object
   *
   * @param {string} name
   * @param {any} value
   * @param {string} filename
   * @param {number} mode – a value setting mode. Can be:
   *   * 0 – disallow appending or replacing existing field
   *   * 1 – replace existing field value
   *   * 2 – append a new value for existing field
   *
   * @return {void}
   */
  __setField(name, value, filename, mode = 0) {
    invariant(
      !isString(name), TypeError,
      "Field name should be a string. Received %s", typeof name
    )

    invariant(
      filename && !isString(filename), TypeError,
      "Filename should be a string (if passed). Received %s", typeof filename
    )

    // Try to get a filename for buffer and stream values
    if (isBuffer(value) && filename) {
      filename = basename(filename)
    } else if (isReadable(value) && (value.path || filename)) {
      filename = basename(value.path || filename)
    }

    const field = this.__contents.get(name)

    if (!field) {
      return void this.__contents.set(name, {filename, values: [value]})
    }

    if (!mode || mode > 2) {
      return
    }

    if (mode === 1) {
      return void this.__contents.set(name, {filename, values: [value]})
    }

    field.values.push(value)

    this.__contents.set(name, field)
  }

  /**
   * Returns boundary string
   */
  get boundary() {
    return this.__boundary
  }

  /**
   * Returns the internal stream
   *
   * @return {stream.Readable}
   */
  get stream() {
    return this.__stream
  }

  append = (name, value, filename) => this.__setField(name, value, filename, 2)

  /**
   * Set new field on FormData
   *
   * @param {string} name – field name
   * @param {any} value – field value
   * @param {string} filename
   *
   * @return {void}
   */
  set = (name, value, filename) => this.__setField(name, value, filename, 1)

  /**
   * Check if the value with given key exists
   *
   * @param {string} name – name of a value you are looking for
   *
   * @return {boolean}
   */
  has = name => this.__contents.has(name)

  get = name => {
    const field = this.__contents.get(name)

    // NOTE: This method should return only the first field value.
    // I should add this behaviour somehow
    if (!field) {
      return void 0
    }

    const [value] = field.values

    return isBuffer(value) || isReadable(value) ? value : String(value)
  }

  getAll = name => {
    const res = []

    const field = this.__contents.get(name)

    if (field) {
      for (const value of field.values) {
        res.push(isBuffer(value) || isReadable(value) ? value : String(value))
      }
    }

    return res
  }

  delete = name => void this.__contents.delete(name)

  pipe = (dest, options) => this.__stream.pipe(dest, options)

  on = (name, fn) => {
    this.__stream.on(name, fn)

    return this
  }

  forEach = (fn, ctx = null) => {
    for (const [name, value] of this.entries()) {
      fn.call(ctx, value, name, this)
    }
  }

  toString() {
    return `[object ${this.constructor.name}]`
  }

  toJSON() {
    return this.constructor.name
  }

  inspect() {
    return this.constructor.name
  }

  * keys() {
    for (const key of this.__contents.keys()) {
      yield key
    }
  }

  * values() {
    for (const name of this.keys()) {
      const value = this.getAll(name)

      yield value.length === 1 ? value[0] : value
    }
  }

  * entries() {
    for (const name of this.keys()) {
      const value = this.getAll(name)

      yield [name, value.length === 1 ? value[0] : value]
    }
  }

  [Symbol.iterator]() {
    return this.entries()
  }

  /**
   * This method allows to read a content from internal stream
   * using async generators and for-await..of APIs
   *
   * @return {StreamIterator}
   */
  [Symbol.asyncIterator]() {
    return new StreamIterator(this.__stream)
  }
}

export default FormData
<|endoftext|>


<commit_before>// Include our config file
Ti.include('../config.js');

// Define the variable win to contain the current window
var win = Ti.UI.currentWindow;

var registerView = Titanium.UI.createScrollView({
  contentWidth:'auto',
  contentHeight:'auto',
  showVerticalScrollIndicator:true,
  showHorizontalScrollIndicator:true,
});

win.add(registerView);

var registerText = Titanium.UI.createTextArea({
  editable: '0',
  text:'Welcome message',
  value: 'Please provide your data.',
  font:{fontSize:16, fontWeight: "light"},
  color: 'white',
  left:10,
  top:30,
  width:300,
  height:'auto',
  backgroundColor: 'transparent',
});

registerView.add(registerText);

// Create the username textfield
var usernameTextfield = Titanium.UI.createTextField({
  hintText:'Username',
  height:35,
  top:100,
  left:10,
  width:300,
  font:{fontSize:16},
  borderWidth:1,
  borderColor:'#bbb',
  borderRadius:3,
  autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
  paddingLeft: 5,
  paddingRight: 5,
  color: 'black',
  backgroundColor: 'white',
});

registerView.add(usernameTextfield);

// Create the textfield for the email
var emailTextfield = Titanium.UI.createTextField({
  hintText:'E-Mail',
  height:35,
  top:150,
  left:10,
  width:300,
  font:{fontSize:16},
  borderWidth:1,
  borderColor:'#bbb',
  borderRadius:3,
  autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
  paddingLeft: 5,
  paddingRight: 5,
  color: 'black',
  backgroundColor: 'white',
});

registerView.add(emailTextfield);

// Create the password textfield
var passwordTextfield = Titanium.UI.createTextField({
  hintText:'Password',
  height:35,
  top:200,
  left:10,
  width:300,
  font:{fontSize:16},
  borderWidth:1,
  borderColor:'#bbb',
  borderRadius:3,
  autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
  passwordMask:true,
  paddingLeft: 5,
  paddingRight: 5,
  color: 'black',
  backgroundColor: 'white',
});

registerView.add(passwordTextfield);

// Create the password textfield
var repeatPasswordTextfield = Titanium.UI.createTextField({
  hintText:'Repeat password',
  height:35,
  top:250,
  left:10,
  width:300,
  font:{fontSize:16},
  borderWidth:1,
  borderColor:'#bbb',
  borderRadius:3,
  autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
  passwordMask:true,
  paddingLeft: 5,
  paddingRight: 5,
  color: 'black',
  backgroundColor: 'white',
});

registerView.add(repeatPasswordTextfield);

// Create the login button
var cancelButton = Titanium.UI.createButton({
  title:'Cancel',
  height:40,
  width:140,
  top:300,
  left:10
});

registerView.add(cancelButton);

cancelButton.addEventListener('click', function() {
  win.close();
  Ti.App.homeWin.show();
})

// Create the login button
var registerButton = Titanium.UI.createButton({
  title:'Register',
  height:40,
  width:140,
  top:300,
  left:160
});

registerView.add(registerButton);

// Add the event listener for when the button is created
registerButton.addEventListener('click', function() {

  if (usernameTextfield.value == '' || emailTextfield.value == '' || passwordTextfield.value == '') {
    alert('Please fill out all fields.')
  }
  else {

    if (passwordTextfield.value == repeatPasswordTextfield.value) {

      var newUser = {
        name: usernameTextfield.value,
        pass: passwordTextfield.value,
        mail: emailTextfield.value,
      };

      var userString = JSON.stringify(newUser);

      var url = REST_PATH + 'user/register.json';
      var xhr = Titanium.Network.createHTTPClient();
      xhr.open("POST", url);
      xhr.setRequestHeader('Content-Type','application/json; charset=utf-8');
      xhr.send(userString);

      // When the connection loads we do:
      xhr.onload = function() {
        // Save the status of the connection in a variable
        // this will be used to see if we have a connection (200) or not
        var statusCode = xhr.status;
        Ti.API.info('onload');
        Ti.API.info(statusCode);
        Ti.API.info(xhr.responseText);
        // Check if we have a valid status
        if(statusCode == 200) {

          // Create a variable response to hold the response
          var response = xhr.responseText;

          // Ti.API.info(response);
          var logoutUrl = REST_PATH + 'user/logout.json';
          var xhr2 = Titanium.Network.createHTTPClient();
          xhr2.open("POST", logoutUrl);
          xhr2.setRequestHeader('Content-Type','application/json; charset=utf-8');
          xhr2.send();

          xhr2.onload = function() {
            var logoutStatusCode = xhr2.status;
            alert('User successfully created. You can now log in.')
            win.close();
          }
        }
        else {
          alert("There was an error");
        }
      }

      xhr.onerror = function() {
        Ti.API.info('onerror');
        var statusCode = xhr.status;
        Ti.API.info(statusCode);
        var response = JSON.parse(xhr.responseText);
        Ti.API.info(response);
        if (statusCode == 401) {
          var error = response[0];
          alert(error);
        }
        else if (statusCode == 406) {
          var error = response[0];
          // If username is invalid
          var userInvalid = error.search(/The username contains an illegal character.+/);
          // If username is taken
          var userTaken = error.search(/The name .*<\/em> is already taken.+/);
          // If E-Mail is invalid
          var mailInvalid = error.search(/The e-mail address .*<\/em> is not valid.+/);
          // If E-Mail is taken
          var mailTaken = error.search(/The e-mail address .*<\/em> is already registered.+/);
          if (userInvalid != -1) {
            alert('The username contains an illegal character.');
          }
          else if (userTaken != -1) {
            alert('The username is already taken.');
          }
          else if (mailInvalid != -1) {
            alert('Invalid e-mail address.');
          }
          else if (mailTaken != -1) {
            alert('The e-mail address is already registered.');
          }
        }
      }

    }
    else {
      alert('The passwords do not match.')
    }
  }
});
<commit_msg>bugfix: show home window after registration<commit_after>// Include our config file
Ti.include('../config.js');

// Define the variable win to contain the current window
var win = Ti.UI.currentWindow;

var registerView = Titanium.UI.createScrollView({
  contentWidth:'auto',
  contentHeight:'auto',
  showVerticalScrollIndicator:true,
  showHorizontalScrollIndicator:true,
});

win.add(registerView);

var registerText = Titanium.UI.createTextArea({
  editable: '0',
  text:'Welcome message',
  value: 'Please provide your data.',
  font:{fontSize:16, fontWeight: "light"},
  color: 'white',
  left:10,
  top:30,
  width:300,
  height:'auto',
  backgroundColor: 'transparent',
});

registerView.add(registerText);

// Create the username textfield
var usernameTextfield = Titanium.UI.createTextField({
  hintText:'Username',
  height:35,
  top:100,
  left:10,
  width:300,
  font:{fontSize:16},
  borderWidth:1,
  borderColor:'#bbb',
  borderRadius:3,
  autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
  paddingLeft: 5,
  paddingRight: 5,
  color: 'black',
  backgroundColor: 'white',
});

registerView.add(usernameTextfield);

// Create the textfield for the email
var emailTextfield = Titanium.UI.createTextField({
  hintText:'E-Mail',
  height:35,
  top:150,
  left:10,
  width:300,
  font:{fontSize:16},
  borderWidth:1,
  borderColor:'#bbb',
  borderRadius:3,
  autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
  paddingLeft: 5,
  paddingRight: 5,
  color: 'black',
  backgroundColor: 'white',
});

registerView.add(emailTextfield);

// Create the password textfield
var passwordTextfield = Titanium.UI.createTextField({
  hintText:'Password',
  height:35,
  top:200,
  left:10,
  width:300,
  font:{fontSize:16},
  borderWidth:1,
  borderColor:'#bbb',
  borderRadius:3,
  autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
  passwordMask:true,
  paddingLeft: 5,
  paddingRight: 5,
  color: 'black',
  backgroundColor: 'white',
});

registerView.add(passwordTextfield);

// Create the password textfield
var repeatPasswordTextfield = Titanium.UI.createTextField({
  hintText:'Repeat password',
  height:35,
  top:250,
  left:10,
  width:300,
  font:{fontSize:16},
  borderWidth:1,
  borderColor:'#bbb',
  borderRadius:3,
  autocapitalization:Titanium.UI.TEXT_AUTOCAPITALIZATION_NONE,
  passwordMask:true,
  paddingLeft: 5,
  paddingRight: 5,
  color: 'black',
  backgroundColor: 'white',
});

registerView.add(repeatPasswordTextfield);

// Create the login button
var cancelButton = Titanium.UI.createButton({
  title:'Cancel',
  height:40,
  width:140,
  top:300,
  left:10
});

registerView.add(cancelButton);

cancelButton.addEventListener('click', function() {
  win.close();
  Ti.App.homeWin.show();
})

// Create the login button
var registerButton = Titanium.UI.createButton({
  title:'Register',
  height:40,
  width:140,
  top:300,
  left:160
});

registerView.add(registerButton);

// Add the event listener for when the button is created
registerButton.addEventListener('click', function() {

  if (usernameTextfield.value == '' || emailTextfield.value == '' || passwordTextfield.value == '') {
    alert('Please fill out all fields.')
  }
  else {

    if (passwordTextfield.value == repeatPasswordTextfield.value) {

      var newUser = {
        name: usernameTextfield.value,
        pass: passwordTextfield.value,
        mail: emailTextfield.value,
      };

      var userString = JSON.stringify(newUser);

      var url = REST_PATH + 'user/register.json';
      var xhr = Titanium.Network.createHTTPClient();
      xhr.open("POST", url);
      xhr.setRequestHeader('Content-Type','application/json; charset=utf-8');
      xhr.send(userString);

      // When the connection loads we do:
      xhr.onload = function() {
        // Save the status of the connection in a variable
        // this will be used to see if we have a connection (200) or not
        var statusCode = xhr.status;
        Ti.API.info('onload');
        Ti.API.info(statusCode);
        Ti.API.info(xhr.responseText);
        // Check if we have a valid status
        if(statusCode == 200) {

          // Create a variable response to hold the response
          var response = xhr.responseText;

          // Ti.API.info(response);
          var logoutUrl = REST_PATH + 'user/logout.json';
          var xhr2 = Titanium.Network.createHTTPClient();
          xhr2.open("POST", logoutUrl);
          xhr2.setRequestHeader('Content-Type','application/json; charset=utf-8');
          xhr2.send();

          xhr2.onload = function() {
            var logoutStatusCode = xhr2.status;
            alert('User successfully created. You can now log in.')
            win.close();
            Ti.App.homeWin.show();
          }
        }
        else {
          alert("There was an error");
        }
      }

      xhr.onerror = function() {
        Ti.API.info('onerror');
        var statusCode = xhr.status;
        Ti.API.info(statusCode);
        var response = JSON.parse(xhr.responseText);
        Ti.API.info(response);
        if (statusCode == 401) {
          var error = response[0];
          alert(error);
        }
        else if (statusCode == 406) {
          var error = response[0];
          // If username is invalid
          var userInvalid = error.search(/The username contains an illegal character.+/);
          // If username is taken
          var userTaken = error.search(/The name .*<\/em> is already taken.+/);
          // If E-Mail is invalid
          var mailInvalid = error.search(/The e-mail address .*<\/em> is not valid.+/);
          // If E-Mail is taken
          var mailTaken = error.search(/The e-mail address .*<\/em> is already registered.+/);
          if (userInvalid != -1) {
            alert('The username contains an illegal character.');
          }
          else if (userTaken != -1) {
            alert('The username is already taken.');
          }
          else if (mailInvalid != -1) {
            alert('Invalid e-mail address.');
          }
          else if (mailTaken != -1) {
            alert('The e-mail address is already registered.');
          }
        }
      }

    }
    else {
      alert('The passwords do not match.')
    }
  }
});
<|endoftext|>


<commit_before>// https://github.com/yannickcr/eslint-plugin-react#jsx-specific-rules
module.exports = {
  rules: {

    // Enforce boolean attributes notation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
    // 'react/jsx-boolean-value': 'error'
  }
}
<commit_msg>Added jsx rules<commit_after>module.exports = {

  // https://github.com/yannickcr/eslint-plugin-react#jsx-specific-rules
  rules: {

    // Enforce boolean attributes notation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-boolean-value.md
    'react/jsx-boolean-value': 'off',

    // Validate closing bracket location in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-closing-bracket-location.md
    'react/jsx-closing-bracket-location': 'off',

    // Enforce or disallow spaces inside of curly braces in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-curly-spacing.md
    'react/jsx-curly-spacing': 'off',

    // Enforce or disallow spaces around equal signs in JSX attributes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-equals-spacing.md
    'react/jsx-equals-spacing': 'off',

    // Restrict file extensions that may contain JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-filename-extension.md
    'react/jsx-filename-extension': 'off',

    // Enforce position of the first prop in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-first-prop-new-line.md
    'react/jsx-first-prop-new-line': 'off',

    // Enforce event handler naming conventions in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-handler-names.md
    'react/jsx-handler-names': 'off',

    // Validate JSX indentation
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent.md
    'react/jsx-indent': 'off',

    // Validate props indentation in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-indent-props.md
    'react/jsx-indent-props': 'off',

    // Validate JSX has key prop when in array or iterator
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-key.md
    'react/jsx-key': 'off',

    // Limit maximum of props on a single line in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-max-props-per-line.md
    'react/jsx-max-props-per-line': 'off',

    // Prevent usage of .bind() and arrow functions in JSX props
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
    'react/jsx-no-bind': 'off',

    // Prevent comments from being inserted as text nodes
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-comment-textnodes.md
    'react/jsx-no-comment-textnodes': 'off',

    // Prevent duplicate props in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-duplicate-props.md
    'react/jsx-no-duplicate-props': 'off',

    // Prevent usage of unwrapped JSX strings
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-literals.md
    'react/jsx-no-literals': 'off',

    // Prevent usage of unsafe target='_blank'
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-target-blank.md
    'react/jsx-no-target-blank': 'off',

    // Disallow undeclared variables in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-undef.md
    'react/jsx-no-undef': 'off',

    // Enforce PascalCase for user-defined JSX components
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-pascal-case.md
    'react/jsx-pascal-case': 'off',

    // Enforce props alphabetical sorting
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-sort-props.md
    'react/jsx-sort-props': 'off',

    // Validate spacing before closing bracket in JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-space-before-closing.md
    'react/jsx-space-before-closing': 'off',

    // Prevent React to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-react.md
    'react/jsx-uses-react': 'off',

    // Prevent variables used in JSX to be incorrectly marked as unused
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-uses-vars.md
    'react/jsx-uses-vars': 'off',

    // Prevent missing parentheses around multilines JSX
    // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-wrap-multilines.md
    'react/jsx-wrap-multilines': 'off'
  }
}
<|endoftext|>


<commit_before>var express = require('express'),
    app = express();

app.get('/summary', function(request, response) {
  response.render('./app/blocks/eventsummarypersonal');
});

module.exports = app;
<commit_msg>edit redirect for eventpersonal view when submitting form<commit_after>var express = require('express'),
    app = express();

app.get('/summaryp', function(request, response) {
  response.render('./app/blocks/eventsummarypersonal');
});

module.exports = app;
<|endoftext|>