<commit_before>define(function (require) {

    var React = require('react'),
        Backbone = require('backbone'),
        stores = require('stores'),
        MachineSelect = require('components/modals/instance_launch/MachineSelect.react'),
        IdentitySelect = require('components/modals/instance_launch/IdentitySelect.react');

    return React.createClass({

        propTypes: {
            application: React.PropTypes.instanceOf(Backbone.Model),
            version: React.PropTypes.instanceOf(Backbone.Model),
            identity: React.PropTypes.instanceOf(Backbone.Model),
            name: React.PropTypes.string,
            onPrevious: React.PropTypes.func.isRequired,
            onNext: React.PropTypes.func.isRequired
        },

        getInitialState: function () {
            return {
                name: this.props.name,
                version: this.props.version,
                identity: this.props.identity
            };
        },
        isSubmittable: function () {
            var allocation = this.state.identity.get('allocation'),
            // Allocation Usage cannot exceed 100%
                allocationUsageStats = this.calculateAllocationUsage(allocation);
            //TODO: Short-circuit on isStaff

            return (this.state.name && this.state.version && this.state.identity && allocationUsageStats.percentUsed < 1);
        },
        confirm: function () {
            //Test if information is valid before continuing
            this.props.onNext(this.state);
        },
        onBack: function () {
            this.props.onPrevious(this.state);
        },
        componentDidMount: function () {
            stores.IdentityStore.addChangeListener(this.updateState);
            stores.ProviderMachineStore.addChangeListener(this.updateState);
        },

        componentWillUnmount: function () {
            stores.IdentityStore.removeChangeListener(this.updateState);
            stores.ProviderMachineStore.removeChangeListener(this.updateState);
        },

        onNameChange: function (e) {
            var newName = e.target.value;
            this.setState({name: newName});
        },

        onVersionChange: function (e) {
            var newVersionId = e.target.value;
            var versions = this.props.application.get('provider_images');
            var selectedVersion = versions.get(newVersionId);
            this.setState({version: selectedVersion});
        },

        onIdentityChange: function (e) {
            var newIdentityId = e.target.value;
            var selectedIdentity = stores.IdentityStore.get(newIdentityId);
            this.setState({identity: selectedIdentity});
        },
        cleanVersions: function (versions) {
            // don't show duplicate images
            versions = new versions.constructor(_.uniq(versions.models, function (m) {
                return m.get('uuid');
            }));
            //TODO: Sort Me!
            return versions;
        },
        calculateAllocationUsage: function (allocation) {
            var maxAllocation = allocation.threshold;
            var currentAllocation = allocation.current;

            return {
                currentUsage: currentAllocation,
                maxAllocation: maxAllocation,
                percentUsed: currentAllocation / maxAllocation
            };
        },
        renderAllocationConsumption: function (identity) {
            var allocation = identity.get('allocation'),
            // Allocation Usage
                allocationUsageStats = this.calculateAllocationUsage(allocation),

            // convert to percentages
                currentlyUsed = allocationUsageStats.currentUsage,
                maximumAllowed = allocationUsageStats.maxAllocation,
                currentlyUsedPercent = allocationUsageStats.percentUsed * 100,
                message = (
                "You have currently used " + (Math.round(currentlyUsed)) + " of " + maximumAllowed + " AUs on this Provider."
                ),
                overQuotaMessage = (

                        CPU quota exceeded.
                        {" Choose another provider or request more resources to launch a new instance."}

                );

            return this.renderProgressBar(message, currentlyUsedPercent, 0, overQuotaMessage);
        },

        renderProgressBar: function (message, currentlyUsedPercent, projectedPercent, overQuotaMessage) {
            var currentlyUsedStyle = {width: currentlyUsedPercent + "%"},
                projectedUsedStyle = {width: projectedPercent + "%", opacity: "0.6"},
                totalPercent = currentlyUsedPercent + projectedPercent,
                barTypeClass;

            if (totalPercent <= 50) {
                barTypeClass = "progress-bar-success";
            } else if (totalPercent <= 100) {
                barTypeClass = "progress-bar-warning";
            } else {
                barTypeClass = "progress-bar-danger";
                projectedUsedStyle.width = (100 - currentlyUsedPercent) + "%";
                message = overQuotaMessage;
            }

            return (

{Math.round(currentlyUsedPercent + projectedPercent) + "%"}

{message}

            );
        },

        renderBody: function () {
            var image = this.props.application,
                identities = stores.IdentityStore.getAll(),
                providers = stores.ProviderStore.getAll(),
                versions = image.get('provider_images');

            if (!providers || !identities) return

;

            // don't show duplicate images
            versions = this.cleanVersions(versions);

            // remove identities whose provider has no versions
            identities = new identities.constructor(identities.filter(function (i) {
                return versions.find(function (m) {
                    return m.get('provider').id === i.get('provider').id;
                });
            }));
            if (!this.state.identity) {
                this.state.identity = identities.first();
            }
            if (!this.state.version) {
                this.state.version = versions.first();
            }

            return (

Basic Information

                            Instance Name

                                <input
                                    type='text'
                                    className='form-control'
                                    id='instance-launch-name'
                                    value={this.state.name}
                                    onChange={this.onNameChange}
                                />

                            Version

                                <MachineSelect
                                    machine={this.state.version}
                                    machines={versions}
                                    onChange={this.onVersionChange}
                                />

                        {
                        //TODO: Include some interesting information about Selected version here?
                        //IDEAS: Description
                        //TODO: Include some interesting information about Selected Identity here?
                        // IDEAS: Current Allocation Usage?
                        }

                            Provider

                                <IdentitySelect
                                    identityId={this.state.identityId}
                                    identities={identities}
                                    providers={providers}
                                    onChange={this.onIdentityChange}
                                />

Project Allocation Usage

                            {this.renderAllocationConsumption(this.state.identity)}

            );
        },
        render: function () {

            return (

                {this.renderBody()}

                        <button type="button" className="btn btn-default pull-left" onClick={this.onBack}>

                            Back
                        </button>
                        <button type="button" className="btn btn-primary" onClick={this.confirm} disabled={!this.isSubmittable()}>
                            Continue
                        </button>

            );
        }

    });

});
<commit_msg>Changed method for retrieving 'provider_images/versions'<commit_after>define(function (require) {

    var React = require('react'),
        Backbone = require('backbone'),
        stores = require('stores'),
        MachineSelect = require('components/modals/instance_launch/MachineSelect.react'),
        IdentitySelect = require('components/modals/instance_launch/IdentitySelect.react');

    return React.createClass({

        propTypes: {
            application: React.PropTypes.instanceOf(Backbone.Model),
            version: React.PropTypes.instanceOf(Backbone.Model),
            identity: React.PropTypes.instanceOf(Backbone.Model),
            name: React.PropTypes.string,
            onPrevious: React.PropTypes.func.isRequired,
            onNext: React.PropTypes.func.isRequired
        },

        getInitialState: function () {
            return {
                name: this.props.name,
                version: this.props.version,
                identity: this.props.identity
            };
        },
        isSubmittable: function () {
            var allocation = this.state.identity.get('allocation'),
            // Allocation Usage cannot exceed 100%
                allocationUsageStats = this.calculateAllocationUsage(allocation);
            //TODO: Short-circuit on isStaff

            return (this.state.name && this.state.version && this.state.identity && allocationUsageStats.percentUsed < 1);
        },
        confirm: function () {
            //Test if information is valid before continuing
            this.props.onNext(this.state);
        },
        onBack: function () {
            this.props.onPrevious(this.state);
        },
        componentDidMount: function () {
            stores.IdentityStore.addChangeListener(this.updateState);
            stores.ProviderMachineStore.addChangeListener(this.updateState);
        },

        componentWillUnmount: function () {
            stores.IdentityStore.removeChangeListener(this.updateState);
            stores.ProviderMachineStore.removeChangeListener(this.updateState);
        },

        onNameChange: function (e) {
            var newName = e.target.value;
            this.setState({name: newName});
        },

        onVersionChange: function (e) {
            var newVersionId = e.target.value;
            var versions = this.props.application.get('provider_images');
            var selectedVersion = versions.get(newVersionId);
            this.setState({version: selectedVersion});
        },

        onIdentityChange: function (e) {
            var newIdentityId = e.target.value;
            var selectedIdentity = stores.IdentityStore.get(newIdentityId);
            this.setState({identity: selectedIdentity});
        },
        cleanVersions: function (versions) {
            // don't show duplicate images
            versions = new versions.constructor(_.uniq(versions.models, function (m) {
                return m.get('uuid');
            }));
            //TODO: Sort Me!
            return versions;
        },
        calculateAllocationUsage: function (allocation) {
            var maxAllocation = allocation.threshold;
            var currentAllocation = allocation.current;

            return {
                currentUsage: currentAllocation,
                maxAllocation: maxAllocation,
                percentUsed: currentAllocation / maxAllocation
            };
        },
        renderAllocationConsumption: function (identity) {
            var allocation = identity.get('allocation'),
            // Allocation Usage
                allocationUsageStats = this.calculateAllocationUsage(allocation),

            // convert to percentages
                currentlyUsed = allocationUsageStats.currentUsage,
                maximumAllowed = allocationUsageStats.maxAllocation,
                currentlyUsedPercent = allocationUsageStats.percentUsed * 100,
                message = (
                "You have currently used " + (Math.round(currentlyUsed)) + " of " + maximumAllowed + " AUs on this Provider."
                ),
                overQuotaMessage = (

                        CPU quota exceeded.
                        {" Choose another provider or request more resources to launch a new instance."}

                );

            return this.renderProgressBar(message, currentlyUsedPercent, 0, overQuotaMessage);
        },

        renderProgressBar: function (message, currentlyUsedPercent, projectedPercent, overQuotaMessage) {
            var currentlyUsedStyle = {width: currentlyUsedPercent + "%"},
                projectedUsedStyle = {width: projectedPercent + "%", opacity: "0.6"},
                totalPercent = currentlyUsedPercent + projectedPercent,
                barTypeClass;

            if (totalPercent <= 50) {
                barTypeClass = "progress-bar-success";
            } else if (totalPercent <= 100) {
                barTypeClass = "progress-bar-warning";
            } else {
                barTypeClass = "progress-bar-danger";
                projectedUsedStyle.width = (100 - currentlyUsedPercent) + "%";
                message = overQuotaMessage;
            }

            return (

{Math.round(currentlyUsedPercent + projectedPercent) + "%"}

{message}

            );
        },

        renderBody: function () {
            var image = this.props.application,
                identities = stores.IdentityStore.getAll(),
                providers = stores.ProviderStore.getAll(),
                versions = image.getVersions();
                // versions = image.get('provider_images');

            if (!providers || !identities || !versions) return

;

            // don't show duplicate images
            versions = this.cleanVersions(versions);

            // remove identities whose provider has no versions
            identities = new identities.constructor(identities.filter(function (i) {
                return versions.find(function (m) {
                    return m.get('provider').id === i.get('provider').id;
                });
            }));
            if (!this.state.identity) {
                this.state.identity = identities.first();
            }
            if (!this.state.version) {
                this.state.version = versions.first();
            }

            return (

Basic Information

                            Instance Name

                                <input
                                    type='text'
                                    className='form-control'
                                    id='instance-launch-name'
                                    value={this.state.name}
                                    onChange={this.onNameChange}
                                />

                            Version

                                <MachineSelect
                                    machine={this.state.version}
                                    machines={versions}
                                    onChange={this.onVersionChange}
                                />

                        {
                        //TODO: Include some interesting information about Selected version here?
                        //IDEAS: Description
                        //TODO: Include some interesting information about Selected Identity here?
                        // IDEAS: Current Allocation Usage?
                        }

                            Provider

                                <IdentitySelect
                                    identityId={this.state.identityId}
                                    identities={identities}
                                    providers={providers}
                                    onChange={this.onIdentityChange}
                                />

Project Allocation Usage

                            {this.renderAllocationConsumption(this.state.identity)}

            );
        },
        render: function () {

            return (

                {this.renderBody()}

                        <button type="button" className="btn btn-default pull-left" onClick={this.onBack}>

                            Back
                        </button>
                        <button type="button" className="btn btn-primary" onClick={this.confirm} disabled={!this.isSubmittable()}>
                            Continue
                        </button>

            );
        }

    });

});
<|endoftext|>


<commit_before>var async = require('async');
var utils = require('prana').utils;

var rest = module.exports;

/**
 * The route() hook.
 */
rest.route = function(routes, callback) {
  var application = this.application;
  var newRoutes = {};

  var validationResponseCallback = function(callback) {
    return function(error, item, errors) {
      if (error) {
        // Application error.
        return callback(error);
      }
      if (errors && errors.length > 0) {
        // Validation errors.
        return callback(null, errors, 400);
      }
      // Validation passed.
      callback(null, item);
    };
  };

  var self = this;
  async.each(Object.keys(this.application.types), function(typeName, next) {
    var typeModel = self.application.types[typeName];
    var type = typeModel.type;

    // Default path to type name.
    if (!type.path) {
      type.path = '/' + type.name;
    }

    // Initialize access rules.
    type.settings.access = type.settings.access || {};

    // Add default access rules.
    var access = {
      'list': false,
      'load': false,
      'add': false,
      'edit': false,
      'delete': false
    };
    utils.extend(access, type.settings.access);

    // List or add items.
    newRoutes['/rest' + type.path] = {
      access: true,
      callback: function(request, response, callback) {
        if (request.method == 'GET') {
          // @todo: filter out dangerous stuff from query before passing it to
          // list() method?
          var query = request.query;
          return application.invoke('query', type, query, request, function() {
            typeModel.list(query, callback);
          });
        }
        if (request.method == 'POST') {
          return typeModel.validateAndSave(request.body, validationResponseCallback(callback));
        }
        callback();
      },
      access: function(request, response, callback) {
        if (request.method == 'GET') {
          return application.access(request, access.list, callback);
        }
        if (request.method == 'POST') {
          return application.access(request, access.add, callback);
        }
        callback();
      }
    };

    // Get, update or delete an item.
    newRoutes['/rest' + type.path + '/:' + type.name] = {
      access: true,
      callback: function(request, response, callback) {
        if (request.method == 'GET') {
          return typeModel.load(request.params[type.name], callback);
        }
        if (request.method == 'PUT') {
          return typeModel.validateAndSave(request.body, validationResponseCallback(callback));
        }
        if (request.method == 'POST' || request.method == 'PATCH') {
          return typeModel.load(request.params[type.name], function(err, item) {
            if (item) {
              // Delete MongoDB ID if any.
              delete item._id;
              utils.extend(item, request.body);
              request.body = item;
            }
            typeModel.validateAndSave(request.body, validationResponseCallback(callback));
          });
        }
        if (request.method == 'DELETE') {
          return typeModel.delete(request.params[type.name], callback);
        }
        callback();
      },
      access: function(request, response, callback) {
        if (request.method == 'GET') {
          return application.access(request, access.load, callback);
        }
        if (request.method == 'PUT' || request.method == 'POST' || request.method == 'PATCH') {
          return application.access(request, access.edit, callback);
        }
        if (request.method == 'DELETE') {
          return application.access(request, access.delete, callback);
        }
        callback();
      }
    };
    next();
  }, function(err) {
    callback(null, newRoutes);
  });
};
<commit_msg>Removed obsolete access property from rest routes.<commit_after>var async = require('async');
var utils = require('prana').utils;

var rest = module.exports;

/**
 * The route() hook.
 */
rest.route = function(routes, callback) {
  var application = this.application;
  var newRoutes = {};

  var validationResponseCallback = function(callback) {
    return function(error, item, errors) {
      if (error) {
        // Application error.
        return callback(error);
      }
      if (errors && errors.length > 0) {
        // Validation errors.
        return callback(null, errors, 400);
      }
      // Validation passed.
      callback(null, item);
    };
  };

  var self = this;
  async.each(Object.keys(this.application.types), function(typeName, next) {
    var typeModel = self.application.types[typeName];
    var type = typeModel.type;

    // Default path to type name.
    if (!type.path) {
      type.path = '/' + type.name;
    }

    // Initialize access rules.
    type.settings.access = type.settings.access || {};

    // Add default access rules.
    var access = {
      'list': false,
      'load': false,
      'add': false,
      'edit': false,
      'delete': false
    };
    utils.extend(access, type.settings.access);

    // List or add items.
    newRoutes['/rest' + type.path] = {
      callback: function(request, response, callback) {
        if (request.method == 'GET') {
          // @todo: filter out dangerous stuff from query before passing it to
          // list() method?
          var query = request.query;
          return application.invoke('query', type, query, request, function() {
            typeModel.list(query, callback);
          });
        }
        if (request.method == 'POST') {
          return typeModel.validateAndSave(request.body, validationResponseCallback(callback));
        }
        callback();
      },
      access: function(request, response, callback) {
        if (request.method == 'GET') {
          return application.access(request, access.list, callback);
        }
        if (request.method == 'POST') {
          return application.access(request, access.add, callback);
        }
        callback();
      }
    };

    // Get, update or delete an item.
    newRoutes['/rest' + type.path + '/:' + type.name] = {
      callback: function(request, response, callback) {
        if (request.method == 'GET') {
          return typeModel.load(request.params[type.name], callback);
        }
        if (request.method == 'PUT') {
          return typeModel.validateAndSave(request.body, validationResponseCallback(callback));
        }
        if (request.method == 'POST' || request.method == 'PATCH') {
          return typeModel.load(request.params[type.name], function(err, item) {
            if (item) {
              // Delete MongoDB ID if any.
              delete item._id;
              utils.extend(item, request.body);
              request.body = item;
            }
            typeModel.validateAndSave(request.body, validationResponseCallback(callback));
          });
        }
        if (request.method == 'DELETE') {
          return typeModel.delete(request.params[type.name], callback);
        }
        callback();
      },
      access: function(request, response, callback) {
        if (request.method == 'GET') {
          return application.access(request, access.load, callback);
        }
        if (request.method == 'PUT' || request.method == 'POST' || request.method == 'PATCH') {
          return application.access(request, access.edit, callback);
        }
        if (request.method == 'DELETE') {
          return application.access(request, access.delete, callback);
        }
        callback();
      }
    };
    next();
  }, function(err) {
    callback(null, newRoutes);
  });
};
<|endoftext|>


<commit_before>/**
 * Period overview (overview of an period).
 */
Ext.define('devilry_subjectadmin.view.period.PeriodOverview' ,{
    extend: 'Ext.container.Container',
    alias: 'widget.periodoverview',
    cls: 'devilry_subjectadmin_periodoverview',
    requires: [
        'Ext.layout.container.Column',
        'devilry_extjsextras.AlertMessage',
        'devilry_extjsextras.AlertMessageList',
        'devilry_subjectadmin.view.AdminsBox',
        'devilry_subjectadmin.utils.UrlLookup',
        'devilry_subjectadmin.view.DangerousActions',
        'devilry_subjectadmin.view.period.EditDurationWidget',
        'devilry_extjsextras.SingleActionBox',
        'devilry_subjectadmin.view.EditSidebarContainer'
    ],

    /**
     * @cfg {String} period_id (required)
     */

    initComponent: function() {
        Ext.apply(this, {
            padding: '20 20 20 20',
            autoScroll: true,
            layout: 'column',

            items: [{
                xtype: 'editsidebarcontainer',
                layout: 'anchor',
                width: 250,
                margin: '6 0 0 0',
                padding: '0 10 0 10',
                defaults: {
                    margin: '10 0 0 0',
                    anchor: '100%'
                },
                items: [{
                    //margin: '0 0 0 0',
                    xtype: 'editperiod_duration-widget'
                }, {
                    xtype: 'adminsbox'
                }]
            }, {
                xtype: 'container',
                columnWidth: 1.0,
                cls: 'devilry_focuscontainer',
                padding: '20',
                items: [{
                    xtype: 'box',
                    cls: 'bootstrap',
                    margin: '0 0 20 0',
                    itemId: 'header',
                    tpl: [
                        '<tpl if="loading">',
                            gettext('Loading'), ' ...',
                        '<tpl else>',
                            '
',
                                '{period}',
                                '  — {subject}',
                            '
',
                        '</tpl>'
                    ],
                    data: {
                        loading: true
                    }
                }, {
                    xtype: 'box',
                    cls: 'bootstrap devilry_subjectadmin_navigation',
                    itemId: 'createNewAssignmentBox',
                    tpl: [
                        '
{text}
'
                    ],
                    data: {
                        url: devilry_subjectadmin.utils.UrlLookup.createNewAssignment(this.period_id),
                        text: gettext('Create new assignment')
                    }
                }, {
                    xtype: 'alertmessage',
                    itemId: 'noRelatedStudentsMessage',
                    hidden: true,
                    type: 'error',
                    title: gettext('No students'),
                    message: interpolate(gettext('This %(period_term)s has no students. Go to the students page and add some students. You will not be able to add any assignments until you have at least one student.'), {
                        period_term: gettext('period'),
                        relatedstudents_url: devilry_subjectadmin.utils.UrlLookup.manageRelatedStudents(this.period_id)
                    }, true)
                }, {
                    xtype: 'alertmessage',
                    itemId: 'noRelatedExaminersMessage',
                    hidden: true,
                    type: 'warning',
                    title: gettext('No examiners'),
                    message: interpolate(gettext('This %(period_term)s has no examiners. Go to the examiners page and add some examiners.'), {
                        period_term: gettext('period'),
                        relatedexaminers_url: devilry_subjectadmin.utils.UrlLookup.manageRelatedExaminers(this.period_id)
                    }, true)
                }, {
                    xtype: 'listofassignments'
                }, {
                    xtype: 'box',
                    cls: 'bootstrap',
                    margin: '30 0 0 0',
                    html: [
                        '
', gettext('Students and examiners'), '
',
                        '
',
                            '

',
                                '',
                                    gettext('Students'),
                                '',
                            '

',
                            '

',
                                '',
                                    gettext('Examiners'),
                                '',
                            '

',
                        '
'
                    ].join('')
                }, {
                    xtype: 'dangerousactions',
                    margin: '45 0 0 0',
                    items: [{
                        xtype: 'singleactionbox',
                        margin: '0 0 0 0',
                        itemId: 'renameButton',
                        id: 'periodRenameButton',
                        titleText: gettext('Loading') + ' ...',
                        bodyTpl: [
                            '
',
                                gettext('Renaming a {period_term} should not be done without a certain amount of consideration. The name of a {period_term}, especially the short name, is often used as an identifier when integrating other systems with Devilry.'),
                            '
'
                        ],
                        bodyData: {
                            period_term: gettext('period')
                        },
                        buttonText: gettext('Rename') + ' ...'
                    }, {
                        xtype: 'singleactionbox',
                        itemId: 'deleteButton',
                        id: 'periodDeleteButton',
                        titleText: gettext('Loading') + ' ...',
                        buttonUi: 'danger',
                        bodyTpl: [
                            '
',
                                gettext('Once you delete a {period_term}, there is no going back. Only superusers can delete a non-empty {period_term}.'),
                            '
'
                        ],
                        bodyData: {
                            period_term: gettext('period')
                        },
                        buttonText: gettext('Delete') + ' ...'
                    }]
                }]
            }]
        });
        this.callParent(arguments);
    }
});
<commit_msg>devilry_subjectadmin...PeriodOverview: Qualifies for final exam link.<commit_after>/**
 * Period overview (overview of an period).
 */
Ext.define('devilry_subjectadmin.view.period.PeriodOverview' ,{
    extend: 'Ext.container.Container',
    alias: 'widget.periodoverview',
    cls: 'devilry_subjectadmin_periodoverview',
    requires: [
        'Ext.layout.container.Column',
        'devilry_extjsextras.AlertMessage',
        'devilry_extjsextras.AlertMessageList',
        'devilry_subjectadmin.view.AdminsBox',
        'devilry_subjectadmin.utils.UrlLookup',
        'devilry_subjectadmin.view.DangerousActions',
        'devilry_subjectadmin.view.period.EditDurationWidget',
        'devilry_extjsextras.SingleActionBox',
        'devilry_subjectadmin.view.EditSidebarContainer'
    ],

    /**
     * @cfg {String} period_id (required)
     */

    initComponent: function() {
        Ext.apply(this, {
            padding: '20 20 20 20',
            autoScroll: true,
            layout: 'column',

            items: [{
                xtype: 'editsidebarcontainer',
                layout: 'anchor',
                width: 250,
                margin: '6 0 0 0',
                padding: '0 10 0 10',
                defaults: {
                    margin: '10 0 0 0',
                    anchor: '100%'
                },
                items: [{
                    //margin: '0 0 0 0',
                    xtype: 'editperiod_duration-widget'
                }, {
                    xtype: 'adminsbox'
                }]
            }, {
                xtype: 'container',
                columnWidth: 1.0,
                cls: 'devilry_focuscontainer',
                padding: '20',
                items: [{
                    xtype: 'box',
                    cls: 'bootstrap',
                    margin: '0 0 20 0',
                    itemId: 'header',
                    tpl: [
                        '<tpl if="loading">',
                            gettext('Loading'), ' ...',
                        '<tpl else>',
                            '
',
                                '{period}',
                                '  — {subject}',
                            '
',
                        '</tpl>'
                    ],
                    data: {
                        loading: true
                    }
                }, {
                    xtype: 'box',
                    cls: 'bootstrap devilry_subjectadmin_navigation',
                    itemId: 'createNewAssignmentBox',
                    tpl: [
                        '
{text}
'
                    ],
                    data: {
                        url: devilry_subjectadmin.utils.UrlLookup.createNewAssignment(this.period_id),
                        text: gettext('Create new assignment')
                    }
                }, {
                    xtype: 'alertmessage',
                    itemId: 'noRelatedStudentsMessage',
                    hidden: true,
                    type: 'error',
                    title: gettext('No students'),
                    message: interpolate(gettext('This %(period_term)s has no students. Go to the students page and add some students. You will not be able to add any assignments until you have at least one student.'), {
                        period_term: gettext('period'),
                        relatedstudents_url: devilry_subjectadmin.utils.UrlLookup.manageRelatedStudents(this.period_id)
                    }, true)
                }, {
                    xtype: 'alertmessage',
                    itemId: 'noRelatedExaminersMessage',
                    hidden: true,
                    type: 'warning',
                    title: gettext('No examiners'),
                    message: interpolate(gettext('This %(period_term)s has no examiners. Go to the examiners page and add some examiners.'), {
                        period_term: gettext('period'),
                        relatedexaminers_url: devilry_subjectadmin.utils.UrlLookup.manageRelatedExaminers(this.period_id)
                    }, true)
                }, {
                    xtype: 'listofassignments'
                }, {
                    xtype: 'box',
                    cls: 'bootstrap',
                    margin: '30 0 0 0',
                    tpl: [
                        '
',
                            gettext('Edit and view information related to the {period_term}'),
                        '
',
                        '
',
                            '

',
                                '',
                                    gettext('Students'),
                                '',
                            '

',
                            '

',
                                '',
                                    gettext('Examiners'),
                                '',
                            '

',
                            '

',
                                '',
                                    gettext('Qualified for final exams'),
                                '',
                            '

',
                        '
'
                    ],
                    data: {
                        period_term: gettext('period'),
                        manageRelatedExaminersUrl: devilry_subjectadmin.utils.UrlLookup.manageRelatedExaminers(this.period_id),
                        manageRelatedStudentsUrl: devilry_subjectadmin.utils.UrlLookup.manageRelatedStudents(this.period_id),
                        qualifiedForFinalExamsUrl: Ext.String.format(
                            '{0}/devilry_qualifiesforexam/#/{1}/showstatus',
                            window.DevilrySettings.DEVILRY_URLPATH_PREFIX,
                            this.period_id)
                    }
                }, {
                    xtype: 'dangerousactions',
                    margin: '45 0 0 0',
                    items: [{
                        xtype: 'singleactionbox',
                        margin: '0 0 0 0',
                        itemId: 'renameButton',
                        id: 'periodRenameButton',
                        titleText: gettext('Loading') + ' ...',
                        bodyTpl: [
                            '
',
                                gettext('Renaming a {period_term} should not be done without a certain amount of consideration. The name of a {period_term}, especially the short name, is often used as an identifier when integrating other systems with Devilry.'),
                            '
'
                        ],
                        bodyData: {
                            period_term: gettext('period')
                        },
                        buttonText: gettext('Rename') + ' ...'
                    }, {
                        xtype: 'singleactionbox',
                        itemId: 'deleteButton',
                        id: 'periodDeleteButton',
                        titleText: gettext('Loading') + ' ...',
                        buttonUi: 'danger',
                        bodyTpl: [
                            '
',
                                gettext('Once you delete a {period_term}, there is no going back. Only superusers can delete a non-empty {period_term}.'),
                            '
'
                        ],
                        bodyData: {
                            period_term: gettext('period')
                        },
                        buttonText: gettext('Delete') + ' ...'
                    }]
                }]
            }]
        });
        this.callParent(arguments);
    }
});
<|endoftext|>


<commit_before>'use strict';

/**
 * @file Choko core directives.
 */

// Append directives to main choko module.
angular.module('choko')

  // Directive to return the application's version.
  .directive('appVersion', ['version', function(version) {
    return function(scope, elm, attrs) {
      elm.text(version);
    };
  }])

  .directive('ckReplace', ['$http', '$compile', function($http, $compile) {
    return {
      restrict: 'EA',

      // As this directive will replace the existing markup, it's better that
      // we run it previously to most other directives, to avoid dumb processing.
      priority: 100,
      compile: function(element, attrs) {
         return function(scope, element, attrs) {

          // Request the template content.
          var loadTemplate = $http({
            method: 'GET',
            // If the directive is an element, "src" should be available.
            url: attrs.ckReplace || attrs.src,
            cache: true
          });

          // When ready, compile the retrieved template.
          loadTemplate.then(function(result) {

            // Compile the returned template.
            var compiled = $compile(result.data)(scope);

            // Replace old element with compiled one.
            element.replaceWith(angular.element(compiled));

          });
        };
      }
    };
  }])

  // @todo: Verify if the directives ckReplaceAndRecompile, ckReplaceElement
  // and ckButtonOld are using.

  // A helper service to handle re-compiling of directives.
  .factory('ckReplaceAndRecompile', ['$compile', function ($compile) {
    /**
     * Creates a new element from the given, copying attributes but removing
     * the old directive to avoid running it again. Recompiles the new
     * element and replaces the old with it.
     */
    return function (element, directiveToRemove, scope, newTag) {

      // Handle multiple removals using a array of removing directives.
      var directives  = directiveToRemove.length ? directiveToRemove : [];
      var tagName     = element.prop('localName');
      var replacement;

      // Replace the directive, be it a tag name or attribute.
      directives.forEach(function (directive) {
        if (tagName == directive) {
          replacement = angular.element(document.createElement(newTag || 'div'));
          angular.element.each(element[0].attributes, function (i, attr) {
            replacement.attr(attr.name, attr.value);
          });
          element.replaceWith(replacement);
          element = replacement;
        } else {
          element.removeAttr(directive);
        }
      });

      // Recompile the element.
      $compile(element)(scope || {});
    }
  }])

  // Directive to replace form elements with overridable templates from
  // the server.
  .directive('ckReplaceElement', ['ckReplaceAndRecompile', function(ckReplaceAndRecompile) {
    return {
      restrict: 'EA',
      // This directive will insert other directives dynamically. We set
      // priority=999 (high number) to make it run first, but nor before core
      // Angular directives, as we need their data. (ng-repeat runs at 1000
      // priority).
      priority: 999,
      terminal: true,
      compile: function (tElement, attrs) {
        return function(scope, element, attrs) {

          // Allow for custom templates but fallback to default one based
          // on element type.
          scope.element.template = scope.element.template || '/templates/' + scope.element.type + '.html';
          scope.element.isSubform = attrs.subForm ? true : false;

          // Append the ck-replace directive.
          element.attr('ck-replace', scope.element.template);

          ckReplaceAndRecompile(element, ['ck-replace-element', 'ng-repeat'], scope);
        }
      }
    };
  }])

  // Handles button or button groups for navigation bars.
  // @todo This directive is specifically used by the navigation extension.
  //       Therefore it should be moved to this extension's directory.
  .directive('ckButton', ['ckReplaceAndRecompile', function(ckReplaceAndRecompile) {
    return {
      restrict: 'EA',
      scope: true,
      // This directive will insert other directives dynamically. We set
      // priority=999 (high number) to make it run first, but nor before core
      // Angular directives, as we need their data. (ng-repeat runs at 1000
      // priority).
      priority: 999,
      terminal: true,
      compile: function(element, attrs) {
        return function(scope, element, attrs) {

          // Add bootstrap button class.
          scope.item.classes = scope.item.classes || ['btn-default'];

          // Allow for custom templates but fallback to default
          if (!scope.item.template) {
            scope.item.template = scope.item.items ? '/templates/btn-group-dropdown.html' : '/templates/btn-group-button.html';
          }

          // Append the replacement directive.
          element.attr('ck-replace', scope.item.template);

          ckReplaceAndRecompile(element, ['ck-button', 'ng-repeat'], scope);
        };
      }
    };
  }]);
<commit_msg>Changing the ckButton directive so it don't include de btn-default class to all buttons.<commit_after>'use strict';

/**
 * @file Choko core directives.
 */

// Append directives to main choko module.
angular.module('choko')

  // Directive to return the application's version.
  .directive('appVersion', ['version', function(version) {
    return function(scope, elm, attrs) {
      elm.text(version);
    };
  }])

  .directive('ckReplace', ['$http', '$compile', function($http, $compile) {
    return {
      restrict: 'EA',

      // As this directive will replace the existing markup, it's better that
      // we run it previously to most other directives, to avoid dumb processing.
      priority: 100,
      compile: function(element, attrs) {
         return function(scope, element, attrs) {

          // Request the template content.
          var loadTemplate = $http({
            method: 'GET',
            // If the directive is an element, "src" should be available.
            url: attrs.ckReplace || attrs.src,
            cache: true
          });

          // When ready, compile the retrieved template.
          loadTemplate.then(function(result) {

            // Compile the returned template.
            var compiled = $compile(result.data)(scope);

            // Replace old element with compiled one.
            element.replaceWith(angular.element(compiled));

          });
        };
      }
    };
  }])

  // @todo: Verify if the directives ckReplaceAndRecompile, ckReplaceElement
  // and ckButtonOld are using.

  // A helper service to handle re-compiling of directives.
  .factory('ckReplaceAndRecompile', ['$compile', function ($compile) {
    /**
     * Creates a new element from the given, copying attributes but removing
     * the old directive to avoid running it again. Recompiles the new
     * element and replaces the old with it.
     */
    return function (element, directiveToRemove, scope, newTag) {

      // Handle multiple removals using a array of removing directives.
      var directives  = directiveToRemove.length ? directiveToRemove : [];
      var tagName     = element.prop('localName');
      var replacement;

      // Replace the directive, be it a tag name or attribute.
      directives.forEach(function (directive) {
        if (tagName == directive) {
          replacement = angular.element(document.createElement(newTag || 'div'));
          angular.element.each(element[0].attributes, function (i, attr) {
            replacement.attr(attr.name, attr.value);
          });
          element.replaceWith(replacement);
          element = replacement;
        } else {
          element.removeAttr(directive);
        }
      });

      // Recompile the element.
      $compile(element)(scope || {});
    }
  }])

  // Directive to replace form elements with overridable templates from
  // the server.
  .directive('ckReplaceElement', ['ckReplaceAndRecompile', function(ckReplaceAndRecompile) {
    return {
      restrict: 'EA',
      // This directive will insert other directives dynamically. We set
      // priority=999 (high number) to make it run first, but nor before core
      // Angular directives, as we need their data. (ng-repeat runs at 1000
      // priority).
      priority: 999,
      terminal: true,
      compile: function (tElement, attrs) {
        return function(scope, element, attrs) {

          // Allow for custom templates but fallback to default one based
          // on element type.
          scope.element.template = scope.element.template || '/templates/' + scope.element.type + '.html';
          scope.element.isSubform = attrs.subForm ? true : false;

          // Append the ck-replace directive.
          element.attr('ck-replace', scope.element.template);

          ckReplaceAndRecompile(element, ['ck-replace-element', 'ng-repeat'], scope);
        }
      }
    };
  }])

  // Handles button or button groups for navigation bars.
  // @todo This directive is specifically used by the navigation extension.
  //       Therefore it should be moved to this extension's directory.
  .directive('ckButton', ['ckReplaceAndRecompile', function(ckReplaceAndRecompile) {
    return {
      restrict: 'EA',
      scope: true,
      // This directive will insert other directives dynamically. We set
      // priority=999 (high number) to make it run first, but nor before core
      // Angular directives, as we need their data. (ng-repeat runs at 1000
      // priority).
      priority: 999,
      terminal: true,
      compile: function(element, attrs) {
        return function(scope, element, attrs) {
          // Add bootstrap button class.
          scope.item.classes = scope.item.classes || ['btn-default'];

          // Allow for custom templates but fallback to default
          if (!scope.item.template) {
            scope.item.template = scope.item.items ? '/templates/btn-group-dropdown.html' : '/templates/btn-group-button.html';
          }

          // Append the replacement directive.
          element.attr('ck-replace', scope.item.template);

          ckReplaceAndRecompile(element, ['ck-button', 'ng-repeat'], scope);
        };
      }
    };
  }]);
<|endoftext|>


<commit_before>"use strict";

define(['js/Constants',
    'js/NodePropertyNames',
    'js/Widgets/DiagramDesigner/DiagramDesignerWidget.DecoratorBase',
    'js/Widgets/DiagramDesigner/DiagramDesignerWidget.Constants',
    'text!../Core/ModelDecorator.html',
    '../Core/ModelDecorator.Core',
    '../Core/ModelDecorator.Constants',
    'js/DragDrop/DragConstants',
    'js/DragDrop/DragHelper',
    'css!./ModelDecorator.DiagramDesignerWidget'], function (CONSTANTS,
                                                          nodePropertyNames,
                                                          DiagramDesignerWidgetDecoratorBase,
                                                          DiagramDesignerWidgetConstants,
                                                          modelDecoratorTemplate,
                                                          ModelDecoratorCore,
                                                          ModelDecoratorConstants,
                                                          DragConstants,
                                                          DragHelper) {

    var ModelDecoratorDiagramDesignerWidget,
        DECORATOR_ID = "ModelDecoratorDiagramDesignerWidget",
        PORT_CONTAINER_OFFSET_Y = 21,
        ACCEPT_DROPPABLE_CLASS = 'accept-droppable',
        DRAGGABLE_MOUSE = 'DRAGGABLE';

    ModelDecoratorDiagramDesignerWidget = function (options) {
        var opts = _.extend( {}, options);

        DiagramDesignerWidgetDecoratorBase.apply(this, [opts]);

        this._initializeVariables({"connectors": true});

        this._selfPatterns = {};

        this.logger.debug("ModelDecoratorDiagramDesignerWidget ctor");
    };

    /************************ INHERITANCE *********************/
    _.extend(ModelDecoratorDiagramDesignerWidget.prototype, DiagramDesignerWidgetDecoratorBase.prototype);
    _.extend(ModelDecoratorDiagramDesignerWidget.prototype, ModelDecoratorCore.prototype);

    /**************** OVERRIDE INHERITED / EXTEND ****************/

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.DECORATORID = DECORATOR_ID;

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.$DOMBase = $(modelDecoratorTemplate);

    //callback method for territory update
    ModelDecoratorDiagramDesignerWidget.prototype.onOneEvent = function (events) {
        //don't really care here, just want to make sure that the reference object is loaded in the client
        this.logger.debug('onOneEvent: ' + JSON.stringify(events));
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.on_addTo = function () {
        var self = this;

        this._renderContent();

        // set title editable on double-click
        this.skinParts.$name.on("dblclick.editOnDblClick", null, function (event) {
            if (self.hostDesignerItem.canvas.getIsReadOnlyMode() !== true) {
                $(this).editInPlace({"class": "",
                    "onChange": function (oldValue, newValue) {
                        self.__onNodeTitleChanged(oldValue, newValue);
                    }});
            }
            event.stopPropagation();
            event.preventDefault();
        });

        // reference icon on double-click
        this.$el.on("dblclick.refDblClick", '.' + ModelDecoratorConstants.REFERENCE_POINTER_CLASS, function (event) {
            if (!($(this).hasClass(ModelDecoratorConstants.REFERENCE_POINTER_CLASS_NONSET))) {
                self.__navigateToReference();
            }
            event.stopPropagation();
            event.preventDefault();
        });
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.update = function () {
        this._update();
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.calculateDimension = function () {
        if (this.hostDesignerItem) {
            this.hostDesignerItem.setSize(this.$el.outerWidth(true), this.$el.outerHeight(true));

            this._paddingTop = parseInt(this.$el.css('padding-top'), 10);
            this._borderTop = parseInt(this.$el.css('border-top-width'), 10);
        }
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.destroy = function () {
        //drop territory
        if (this._territoryId) {
            this._control._client.removeUI(this._territoryId);
        }

        //call base destroy
        ModelDecoratorCore.prototype.destroy.call(this);
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.getConnectionAreas = function (id/*, isEnd, connectionMetaInfo*/) {
        var result = [],
            edge = 10,
            LEN = 20;

        //by default return the bounding box edges midpoints

        if (id === undefined || id === this.hostDesignerItem.id) {
            //top left
            result.push( {"id": "0",
                "x1": edge,
                "y1": 0,
                "x2": this.hostDesignerItem.getWidth() - edge,
                "y2": 0,
                "angle1": 270,
                "angle2": 270,
                "len": LEN} );

            result.push( {"id": "1",
                "x1": edge,
                "y1": this.hostDesignerItem.getHeight(),
                "x2": this.hostDesignerItem.getWidth() - edge,
                "y2": this.hostDesignerItem.getHeight(),
                "angle1": 90,
                "angle2": 90,
                "len": LEN} );
        } else {
            //subcomponent
            var portConnArea = this._ports[id].getConnectorArea(),
                idx = this._portIDs.indexOf(id);

            result.push( {"id": idx,
                "x1": portConnArea.x1,
                "y1": portConnArea.y1 + PORT_CONTAINER_OFFSET_Y + this._paddingTop + this._borderTop,
                "x2": portConnArea.x2,
                "y2": portConnArea.y2 + PORT_CONTAINER_OFFSET_Y + this._paddingTop + this._borderTop,
                "angle1": portConnArea.angle1,
                "angle2": portConnArea.angle2,
                "len": portConnArea.len} );
        }

        return result;
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //called when the designer item's subcomponent should be updated
    ModelDecoratorDiagramDesignerWidget.prototype.updateSubcomponent = function (portId) {
        this._updatePort(portId);
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //Shows the 'connectors' - appends them to the DOM
    ModelDecoratorDiagramDesignerWidget.prototype.showSourceConnectors = function (params) {
        var connectors,
            i;

        if (!params) {
            this.$sourceConnectors.show();
            if (this._portIDs) {
                i = this._portIDs.length;
                while (i--) {
                    this._ports[this._portIDs[i]].showConnectors();
                }
            }
        } else {
            connectors = params.connectors;
            i = connectors.length;
            while (i--) {
                if (connectors[i] === undefined) {
                    //show connector for the represented item itself
                    this.$sourceConnectors.show();
                } else {
                    //one of the ports' connector should be displayed
                    if (this._ports[connectors[i]]) {
                        this._ports[connectors[i]].showConnectors();
                    }
                }
            }
        }
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //Hides the 'connectors' - detaches them from the DOM
    ModelDecoratorDiagramDesignerWidget.prototype.hideSourceConnectors = function () {
        var i;

        this.$sourceConnectors.hide();

        if (this._portIDs) {
            i = this._portIDs.length;
            while (i--) {
                this._ports[this._portIDs[i]].hideConnectors();
            }
        }
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //should highlight the connectors for the given elements
    ModelDecoratorDiagramDesignerWidget.prototype.showEndConnectors = function (params) {
       this.showSourceConnectors(params);
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //Hides the 'connectors' - detaches them from the DOM
    ModelDecoratorDiagramDesignerWidget.prototype.hideEndConnectors = function () {
        this.hideSourceConnectors();
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.notifyComponentEvent = function (componentList) {
        var len = componentList.length;
        while (len--) {
            this._updatePort(componentList[len].id);
        }
        this._checkTerritoryReady();
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._portPositionChanged = function (portId) {
        this.calculateDimension();
        this.hostDesignerItem.canvas.dispatchEvent(this.hostDesignerItem.canvas.events.ITEM_SUBCOMPONENT_POSITION_CHANGED, {"ItemID": this.hostDesignerItem.id,
            "SubComponentID": portId});
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._registerForNotification = function(portId) {
        var partId = this._metaInfo[CONSTANTS.GME_ID];

        this._control.registerComponentIDForPartID(portId, partId);
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._unregisterForNotification = function(portId) {
        var partId = this._metaInfo[CONSTANTS.GME_ID];

        this._control.unregisterComponentIDFromPartID(portId, partId);
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._renderPort = function (portId) {
        var isPort;

        isPort = ModelDecoratorCore.prototype._renderPort.call(this, portId);

        if (isPort) {
            this.__registerAsSubcomponent(portId);
        }
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._removePort = function (portId) {
        var idx = this._portIDs.indexOf(portId);

        if (idx !== -1) {
            this.__unregisterAsSubcomponent(portId);
        }

        ModelDecoratorCore.prototype._removePort.call(this, portId);
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._updateReference = function () {
        var inverseClass = 'inverse-on-hover',
            icon,
            self = this;

        ModelDecoratorCore.prototype._updateReference.call(this);

        if (this.skinParts.$ref) {
            icon = this.skinParts.$ref.find('i').first();
            if (this.skinParts.$ref.hasClass(ModelDecoratorConstants.REFERENCE_POINTER_CLASS_NONSET)) {
                this.skinParts.$ref.removeClass(inverseClass);
            } else {
                this.skinParts.$ref.addClass(inverseClass);
            }

            //edit droppable mode
            this.$el.on('mouseenter.' + DRAGGABLE_MOUSE, null, function (event) {
                self.__onMouseEnter(event);
            })
            .on('mouseleave.' + DRAGGABLE_MOUSE, null, function (event) {
                self.__onMouseLeave(event);
            })
            .on('mouseup.' + DRAGGABLE_MOUSE, null, function (event) {
                self.__onMouseUp(event);
            });
        } else {
            this.$el.off('mouseenter.' + DRAGGABLE_MOUSE)
                .off('mouseleave.' + DRAGGABLE_MOUSE)
                .off('mouseup.' + DRAGGABLE_MOUSE);
        }
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._refToChanged = function (oldValue, newValue) {
        this.logger.debug('refToChanged from ' + oldValue + ' to ' + newValue);

        if (oldValue) {
            delete this._selfPatterns[oldValue];
        }

        if (newValue) {
            this._territoryId = this._territoryId || this._control._client.addUI(this, true);
            this._selfPatterns[newValue] = { "children": 0 };
        }

        if (this._selfPatterns && !_.isEmpty(this._selfPatterns)) {
            this._control._client.updateTerritory(this._territoryId, this._selfPatterns);
        } else {
            if (this._territoryId) {
                this._control._client.removeUI(this._territoryId);
            }
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onBackgroundDroppableOver = function (helper) {
        if (this.__onBackgroundDroppableAccept(helper) === true) {
            this.__doAcceptDroppable(true);
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onBackgroundDroppableOut = function () {
        this.__doAcceptDroppable(false);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onBackgroundDrop = function (helper) {
        var dragInfo = helper.data(DragConstants.DRAG_INFO),
            dragItems = DragHelper.getDragItems(dragInfo),
            dragEffects = DragHelper.getDragEffects(dragInfo);

        if (this.__acceptDroppable === true) {
            if (dragItems.length === 1 && dragEffects.indexOf(DragHelper.DRAG_EFFECTS.DRAG_CREATE_REFERENCE) !== -1) {
                this._setReferenceValue(dragItems[0]);
            }
        }

        this.__doAcceptDroppable(false);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onBackgroundDroppableAccept = function (helper) {
        var dragInfo = helper.data(DragConstants.DRAG_INFO),
            dragItems = DragHelper.getDragItems(dragInfo),
            dragEffects = DragHelper.getDragEffects(dragInfo);

        return (dragItems.length === 1 && dragEffects.indexOf(DragHelper.DRAG_EFFECTS.DRAG_CREATE_REFERENCE) !== -1);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__doAcceptDroppable = function (accept) {
        if (accept === true) {
            this.__acceptDroppable = true;
            this.$el.addClass(ACCEPT_DROPPABLE_CLASS);
        } else {
            this.__acceptDroppable = false;
            this.$el.removeClass(ACCEPT_DROPPABLE_CLASS);
        }

        this.hostDesignerItem.canvas._enableDroppable(!accept);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onMouseEnter = function (event) {
        if (this.hostDesignerItem.canvas.getIsReadOnlyMode() !== true) {
            //check if it's dragging anything with jQueryUI
            if ($.ui.ddmanager.current && $.ui.ddmanager.current.helper) {
                this.__onDragOver = true;
                this.__onBackgroundDroppableOver($.ui.ddmanager.current.helper);
                event.stopPropagation();
                event.preventDefault();
            }
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onMouseLeave = function (event) {
        if (this.__onDragOver) {
            this.__onBackgroundDroppableOut();
            this.__onDragOver = false;
            event.stopPropagation();
            event.preventDefault();
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onMouseUp = function (/*event*/) {
        if (this.__onDragOver) {
            //TODO: this is still questionable if we should hack the jQeuryUI 's draggable&droppable and use half of it only
            this.__onBackgroundDrop($.ui.ddmanager.current.helper);
            this.__onDragOver = false;
            this.hostDesignerItem.canvas._enableDroppable(false);
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__registerAsSubcomponent = function(portId) {
        if (this.hostDesignerItem) {
            this.hostDesignerItem.registerSubcomponent(portId, {"GME_ID": portId});
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__unregisterAsSubcomponent = function(portId) {
        if (this.hostDesignerItem) {
            this.hostDesignerItem.unregisterSubcomponent(portId);
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onNodeTitleChanged = function (oldValue, newValue) {
        var client = this._control._client;

        client.setAttributes(this._metaInfo[CONSTANTS.GME_ID], nodePropertyNames.Attributes.name, newValue);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__navigateToReference = function () {
        var client = this._control._client,
            nodeObj;

        if (this._refTo) {
            nodeObj = client.getNode(this._refTo);
            if (nodeObj) {
                if (nodeObj.getParentId()) {
                    this._control._client.setSelectedObjectId(nodeObj.getParentId(), this._refTo);
                } else {
                    this._control._client.setSelectedObjectId('root', this._refTo);
                }
            } else {
                this.logger.warning('_navigateToReference client.getNode(' + this._refTo + ') returned null... :(');
            }
        }
    };

    return ModelDecoratorDiagramDesignerWidget;
});<commit_msg>don't enable create reference to itself while drag&drop<commit_after>"use strict";

define(['js/Constants',
    'js/NodePropertyNames',
    'js/Widgets/DiagramDesigner/DiagramDesignerWidget.DecoratorBase',
    'js/Widgets/DiagramDesigner/DiagramDesignerWidget.Constants',
    'text!../Core/ModelDecorator.html',
    '../Core/ModelDecorator.Core',
    '../Core/ModelDecorator.Constants',
    'js/DragDrop/DragConstants',
    'js/DragDrop/DragHelper',
    'css!./ModelDecorator.DiagramDesignerWidget'], function (CONSTANTS,
                                                          nodePropertyNames,
                                                          DiagramDesignerWidgetDecoratorBase,
                                                          DiagramDesignerWidgetConstants,
                                                          modelDecoratorTemplate,
                                                          ModelDecoratorCore,
                                                          ModelDecoratorConstants,
                                                          DragConstants,
                                                          DragHelper) {

    var ModelDecoratorDiagramDesignerWidget,
        DECORATOR_ID = "ModelDecoratorDiagramDesignerWidget",
        PORT_CONTAINER_OFFSET_Y = 21,
        ACCEPT_DROPPABLE_CLASS = 'accept-droppable',
        DRAGGABLE_MOUSE = 'DRAGGABLE';

    ModelDecoratorDiagramDesignerWidget = function (options) {
        var opts = _.extend( {}, options);

        DiagramDesignerWidgetDecoratorBase.apply(this, [opts]);

        this._initializeVariables({"connectors": true});

        this._selfPatterns = {};

        this.logger.debug("ModelDecoratorDiagramDesignerWidget ctor");
    };

    /************************ INHERITANCE *********************/
    _.extend(ModelDecoratorDiagramDesignerWidget.prototype, DiagramDesignerWidgetDecoratorBase.prototype);
    _.extend(ModelDecoratorDiagramDesignerWidget.prototype, ModelDecoratorCore.prototype);

    /**************** OVERRIDE INHERITED / EXTEND ****************/

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.DECORATORID = DECORATOR_ID;

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.$DOMBase = $(modelDecoratorTemplate);

    //callback method for territory update
    ModelDecoratorDiagramDesignerWidget.prototype.onOneEvent = function (events) {
        //don't really care here, just want to make sure that the reference object is loaded in the client
        this.logger.debug('onOneEvent: ' + JSON.stringify(events));
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.on_addTo = function () {
        var self = this;

        this._renderContent();

        // set title editable on double-click
        this.skinParts.$name.on("dblclick.editOnDblClick", null, function (event) {
            if (self.hostDesignerItem.canvas.getIsReadOnlyMode() !== true) {
                $(this).editInPlace({"class": "",
                    "onChange": function (oldValue, newValue) {
                        self.__onNodeTitleChanged(oldValue, newValue);
                    }});
            }
            event.stopPropagation();
            event.preventDefault();
        });

        // reference icon on double-click
        this.$el.on("dblclick.refDblClick", '.' + ModelDecoratorConstants.REFERENCE_POINTER_CLASS, function (event) {
            if (!($(this).hasClass(ModelDecoratorConstants.REFERENCE_POINTER_CLASS_NONSET))) {
                self.__navigateToReference();
            }
            event.stopPropagation();
            event.preventDefault();
        });
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.update = function () {
        this._update();
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.calculateDimension = function () {
        if (this.hostDesignerItem) {
            this.hostDesignerItem.setSize(this.$el.outerWidth(true), this.$el.outerHeight(true));

            this._paddingTop = parseInt(this.$el.css('padding-top'), 10);
            this._borderTop = parseInt(this.$el.css('border-top-width'), 10);
        }
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.destroy = function () {
        //drop territory
        if (this._territoryId) {
            this._control._client.removeUI(this._territoryId);
        }

        //call base destroy
        ModelDecoratorCore.prototype.destroy.call(this);
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.getConnectionAreas = function (id/*, isEnd, connectionMetaInfo*/) {
        var result = [],
            edge = 10,
            LEN = 20;

        //by default return the bounding box edges midpoints

        if (id === undefined || id === this.hostDesignerItem.id) {
            //top left
            result.push( {"id": "0",
                "x1": edge,
                "y1": 0,
                "x2": this.hostDesignerItem.getWidth() - edge,
                "y2": 0,
                "angle1": 270,
                "angle2": 270,
                "len": LEN} );

            result.push( {"id": "1",
                "x1": edge,
                "y1": this.hostDesignerItem.getHeight(),
                "x2": this.hostDesignerItem.getWidth() - edge,
                "y2": this.hostDesignerItem.getHeight(),
                "angle1": 90,
                "angle2": 90,
                "len": LEN} );
        } else {
            //subcomponent
            var portConnArea = this._ports[id].getConnectorArea(),
                idx = this._portIDs.indexOf(id);

            result.push( {"id": idx,
                "x1": portConnArea.x1,
                "y1": portConnArea.y1 + PORT_CONTAINER_OFFSET_Y + this._paddingTop + this._borderTop,
                "x2": portConnArea.x2,
                "y2": portConnArea.y2 + PORT_CONTAINER_OFFSET_Y + this._paddingTop + this._borderTop,
                "angle1": portConnArea.angle1,
                "angle2": portConnArea.angle2,
                "len": portConnArea.len} );
        }

        return result;
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //called when the designer item's subcomponent should be updated
    ModelDecoratorDiagramDesignerWidget.prototype.updateSubcomponent = function (portId) {
        this._updatePort(portId);
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //Shows the 'connectors' - appends them to the DOM
    ModelDecoratorDiagramDesignerWidget.prototype.showSourceConnectors = function (params) {
        var connectors,
            i;

        if (!params) {
            this.$sourceConnectors.show();
            if (this._portIDs) {
                i = this._portIDs.length;
                while (i--) {
                    this._ports[this._portIDs[i]].showConnectors();
                }
            }
        } else {
            connectors = params.connectors;
            i = connectors.length;
            while (i--) {
                if (connectors[i] === undefined) {
                    //show connector for the represented item itself
                    this.$sourceConnectors.show();
                } else {
                    //one of the ports' connector should be displayed
                    if (this._ports[connectors[i]]) {
                        this._ports[connectors[i]].showConnectors();
                    }
                }
            }
        }
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //Hides the 'connectors' - detaches them from the DOM
    ModelDecoratorDiagramDesignerWidget.prototype.hideSourceConnectors = function () {
        var i;

        this.$sourceConnectors.hide();

        if (this._portIDs) {
            i = this._portIDs.length;
            while (i--) {
                this._ports[this._portIDs[i]].hideConnectors();
            }
        }
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //should highlight the connectors for the given elements
    ModelDecoratorDiagramDesignerWidget.prototype.showEndConnectors = function (params) {
       this.showSourceConnectors(params);
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    //Hides the 'connectors' - detaches them from the DOM
    ModelDecoratorDiagramDesignerWidget.prototype.hideEndConnectors = function () {
        this.hideSourceConnectors();
    };

    /**** Override from DiagramDesignerWidgetDecoratorBase ****/
    ModelDecoratorDiagramDesignerWidget.prototype.notifyComponentEvent = function (componentList) {
        var len = componentList.length;
        while (len--) {
            this._updatePort(componentList[len].id);
        }
        this._checkTerritoryReady();
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._portPositionChanged = function (portId) {
        this.calculateDimension();
        this.hostDesignerItem.canvas.dispatchEvent(this.hostDesignerItem.canvas.events.ITEM_SUBCOMPONENT_POSITION_CHANGED, {"ItemID": this.hostDesignerItem.id,
            "SubComponentID": portId});
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._registerForNotification = function(portId) {
        var partId = this._metaInfo[CONSTANTS.GME_ID];

        this._control.registerComponentIDForPartID(portId, partId);
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._unregisterForNotification = function(portId) {
        var partId = this._metaInfo[CONSTANTS.GME_ID];

        this._control.unregisterComponentIDFromPartID(portId, partId);
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._renderPort = function (portId) {
        var isPort;

        isPort = ModelDecoratorCore.prototype._renderPort.call(this, portId);

        if (isPort) {
            this.__registerAsSubcomponent(portId);
        }
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._removePort = function (portId) {
        var idx = this._portIDs.indexOf(portId);

        if (idx !== -1) {
            this.__unregisterAsSubcomponent(portId);
        }

        ModelDecoratorCore.prototype._removePort.call(this, portId);
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._updateReference = function () {
        var inverseClass = 'inverse-on-hover',
            icon,
            self = this;

        ModelDecoratorCore.prototype._updateReference.call(this);

        if (this.skinParts.$ref) {
            icon = this.skinParts.$ref.find('i').first();
            if (this.skinParts.$ref.hasClass(ModelDecoratorConstants.REFERENCE_POINTER_CLASS_NONSET)) {
                this.skinParts.$ref.removeClass(inverseClass);
            } else {
                this.skinParts.$ref.addClass(inverseClass);
            }

            //edit droppable mode
            this.$el.on('mouseenter.' + DRAGGABLE_MOUSE, null, function (event) {
                self.__onMouseEnter(event);
            })
            .on('mouseleave.' + DRAGGABLE_MOUSE, null, function (event) {
                self.__onMouseLeave(event);
            })
            .on('mouseup.' + DRAGGABLE_MOUSE, null, function (event) {
                self.__onMouseUp(event);
            });
        } else {
            this.$el.off('mouseenter.' + DRAGGABLE_MOUSE)
                .off('mouseleave.' + DRAGGABLE_MOUSE)
                .off('mouseup.' + DRAGGABLE_MOUSE);
        }
    };

    /**** Override from ModelDecoratorCore ****/
    ModelDecoratorDiagramDesignerWidget.prototype._refToChanged = function (oldValue, newValue) {
        this.logger.debug('refToChanged from ' + oldValue + ' to ' + newValue);

        if (oldValue) {
            delete this._selfPatterns[oldValue];
        }

        if (newValue) {
            this._territoryId = this._territoryId || this._control._client.addUI(this, true);
            this._selfPatterns[newValue] = { "children": 0 };
        }

        if (this._selfPatterns && !_.isEmpty(this._selfPatterns)) {
            this._control._client.updateTerritory(this._territoryId, this._selfPatterns);
        } else {
            if (this._territoryId) {
                this._control._client.removeUI(this._territoryId);
            }
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onBackgroundDroppableOver = function (helper) {
        if (this.__onBackgroundDroppableAccept(helper) === true) {
            this.__doAcceptDroppable(true);
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onBackgroundDroppableOut = function () {
        this.__doAcceptDroppable(false);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onBackgroundDrop = function (helper) {
        var dragInfo = helper.data(DragConstants.DRAG_INFO),
            dragItems = DragHelper.getDragItems(dragInfo),
            dragEffects = DragHelper.getDragEffects(dragInfo);

        if (this.__acceptDroppable === true) {
            if (dragItems.length === 1 && dragEffects.indexOf(DragHelper.DRAG_EFFECTS.DRAG_CREATE_REFERENCE) !== -1) {
                this._setReferenceValue(dragItems[0]);
            }
        }

        this.__doAcceptDroppable(false);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onBackgroundDroppableAccept = function (helper) {
        var dragInfo = helper.data(DragConstants.DRAG_INFO),
            dragItems = DragHelper.getDragItems(dragInfo),
            dragEffects = DragHelper.getDragEffects(dragInfo);

        return (dragItems.length === 1 &&
                dragItems[0] !== this._metaInfo[CONSTANTS.GME_ID] &&
                dragEffects.indexOf(DragHelper.DRAG_EFFECTS.DRAG_CREATE_REFERENCE) !== -1);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__doAcceptDroppable = function (accept) {
        if (accept === true) {
            this.__acceptDroppable = true;
            this.$el.addClass(ACCEPT_DROPPABLE_CLASS);
        } else {
            this.__acceptDroppable = false;
            this.$el.removeClass(ACCEPT_DROPPABLE_CLASS);
        }

        this.hostDesignerItem.canvas._enableDroppable(!accept);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onMouseEnter = function (event) {
        if (this.hostDesignerItem.canvas.getIsReadOnlyMode() !== true) {
            //check if it's dragging anything with jQueryUI
            if ($.ui.ddmanager.current && $.ui.ddmanager.current.helper) {
                this.__onDragOver = true;
                this.__onBackgroundDroppableOver($.ui.ddmanager.current.helper);
                event.stopPropagation();
                event.preventDefault();
            }
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onMouseLeave = function (event) {
        if (this.__onDragOver) {
            this.__onBackgroundDroppableOut();
            this.__onDragOver = false;
            event.stopPropagation();
            event.preventDefault();
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onMouseUp = function (/*event*/) {
        if (this.__onDragOver) {
            //TODO: this is still questionable if we should hack the jQeuryUI 's draggable&droppable and use half of it only
            this.__onBackgroundDrop($.ui.ddmanager.current.helper);
            this.__onDragOver = false;
            this.hostDesignerItem.canvas._enableDroppable(false);
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__registerAsSubcomponent = function(portId) {
        if (this.hostDesignerItem) {
            this.hostDesignerItem.registerSubcomponent(portId, {"GME_ID": portId});
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__unregisterAsSubcomponent = function(portId) {
        if (this.hostDesignerItem) {
            this.hostDesignerItem.unregisterSubcomponent(portId);
        }
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__onNodeTitleChanged = function (oldValue, newValue) {
        var client = this._control._client;

        client.setAttributes(this._metaInfo[CONSTANTS.GME_ID], nodePropertyNames.Attributes.name, newValue);
    };

    ModelDecoratorDiagramDesignerWidget.prototype.__navigateToReference = function () {
        var client = this._control._client,
            nodeObj;

        if (this._refTo) {
            nodeObj = client.getNode(this._refTo);
            if (nodeObj) {
                if (nodeObj.getParentId()) {
                    this._control._client.setSelectedObjectId(nodeObj.getParentId(), this._refTo);
                } else {
                    this._control._client.setSelectedObjectId('root', this._refTo);
                }
            } else {
                this.logger.warning('_navigateToReference client.getNode(' + this._refTo + ') returned null... :(');
            }
        }
    };

    return ModelDecoratorDiagramDesignerWidget;
});<|endoftext|>


<commit_before>/**
 * Created by IntelliJ IDEA.
 * User: sbortman
 * Date: 1/30/12
 * Time: 4:57 PM
 * To change this template use File | Settings | File Templates.
 */

(function ()
{
    var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event;

    Event.addListener(window, 'resize', bodyOnResize);

    Event.onDOMReady( function ()
    {
        var outerLayout = new YAHOO.widget.Layout( {
            minWidth:1000,
            minHeight:500,
            units:[
                { position:'top', height:50, body:'top1', scroll: null, zIndex: 2 },
                /*{ position:'right', header:'', width:200, resize:true, gutter:'0px', collapse:true, scroll:true, body:'right1', animate:false },*/
                { position:'bottom', height:25, body:'bottom1' },
                { position:'left', header:'', width:200, resize:true, body:'left1', gutter:'0px', collapse:true, scroll:true, animate:false },
                { position:'center', minWidth:400, minHeight:200 }
            ]
        } );
        outerLayout.on('resize', function(evt) {
            if(OMAR.imageManipulator)
            {
                OMAR.imageManipulator.checkResize();
            }
        //bodyOnResize();
        });
        outerLayout.on( 'render', function ()
        {
            var el = outerLayout.getUnitByPosition( 'center' ).get( 'wrap' );
            var innerLayout = new YAHOO.widget.Layout( el, {
                parent:outerLayout,
                minWidth:400,
                minHeight:200,
                units:[
                    { position:'top',  height:35, proxy:false, body:'top2' },
                    { position:'bottom',  height:30, proxy:false, body:'bottom2' },
                    { position:'center', body:'center2', gutter:'0px' }
                ]
            } );
            innerLayout.render();
            bodyOnResize();
            Dom.setStyle( document.body, 'visibility', 'visible' );
        } );
        outerLayout.render();
        outerLayout.getUnitByPosition( "left" ).on( "collapse", function ()
        {
            bodyOnResize();
        } );

        outerLayout.getUnitByPosition( "left" ).on( "expand", function ()
        {
            bodyOnResize();
        } );

        outerLayout.getUnitByPosition( "right" ).on( "collapse", function ()
        {
            bodyOnResize();
        } );

        outerLayout.getUnitByPosition( "right" ).on( "expand", function ()
        {
            bodyOnResize();
        } );
       init();

    } );
})();

var bodyOnResize = function ()
{
   if(OMAR.imageManipulator)
    {
        OMAR.imageManipulator.checkResize();
    }
   // map.updateSize();
};
<commit_msg>Added check to see if we need to call init<commit_after>/**
 * Created by IntelliJ IDEA.
 * User: sbortman
 * Date: 1/30/12
 * Time: 4:57 PM
 * To change this template use File | Settings | File Templates.
 */

(function ()
{
    var Dom = YAHOO.util.Dom,
            Event = YAHOO.util.Event;

    Event.addListener(window, 'resize', bodyOnResize);

    Event.onDOMReady( function ()
    {
        var outerLayout = new YAHOO.widget.Layout( {
            minWidth:1000,
            minHeight:500,
            units:[
                { position:'top', height:50, body:'top1', scroll: null, zIndex: 2 },
                /*{ position:'right', header:'', width:200, resize:true, gutter:'0px', collapse:true, scroll:true, body:'right1', animate:false },*/
                { position:'bottom', height:25, body:'bottom1' },
                { position:'left', header:'', width:200, resize:true, body:'left1', gutter:'0px', collapse:true, scroll:true, animate:false },
                { position:'center', minWidth:400, minHeight:200 }
            ]
        } );
        outerLayout.on('resize', function(evt) {
            if(OMAR.imageManipulator)
            {
                OMAR.imageManipulator.checkResize();
            }
        //bodyOnResize();
        });
        outerLayout.on( 'render', function ()
        {
            var el = outerLayout.getUnitByPosition( 'center' ).get( 'wrap' );
            var innerLayout = new YAHOO.widget.Layout( el, {
                parent:outerLayout,
                minWidth:400,
                minHeight:200,
                units:[
                    { position:'top',  height:35, proxy:false, body:'top2' },
                    { position:'bottom',  height:30, proxy:false, body:'bottom2' },
                    { position:'center', body:'center2', gutter:'0px' }
                ]
            } );
            innerLayout.render();
            bodyOnResize();
            Dom.setStyle( document.body, 'visibility', 'visible' );
        } );
        outerLayout.render();
        outerLayout.getUnitByPosition( "left" ).on( "collapse", function ()
        {
            bodyOnResize();
        } );

        outerLayout.getUnitByPosition( "left" ).on( "expand", function ()
        {
            bodyOnResize();
        } );

        outerLayout.getUnitByPosition( "right" ).on( "collapse", function ()
        {
            bodyOnResize();
        } );

        outerLayout.getUnitByPosition( "right" ).on( "expand", function ()
        {
            bodyOnResize();
        } );
       init();

    } );
})();

var bodyOnResize = function ()
{
   if(OMAR.imageManipulator)
    {
        OMAR.imageManipulator.checkResize();
    }
    else
    {
        init();
    }
   // map.updateSize();
};
<|endoftext|>


<commit_before>module.exports = function(el) {
  //Had to grab the width & vertical position off the original
  //to stop it popping to the windows width when position was changed to fixed
  var orgElementPos = $('.attorneyBanner').offset(),
  orgElementTop = orgElementPos.top,
  widthOrgElement = $('.attorneyBanner').width();

  //Banner pops out the DOM so this makes sure the content below doesn't shift up
  $('#heightHolder').css('height', $('#heightHolder').height());

  //Run the function to reposition the banner
  setInterval(stickIt, 100);

  function stickIt() {
    if ($(window).scrollTop() >= (orgElementTop)) {
      // scrolled past the original position; change the position to fixed.
      $('.attorneyBanner').css('position', 'fixed').css('width', widthOrgElement).css('top', '0px');
    } else {
      //Returns the banner to the DOM once we scroll up
      $('.attorneyBanner').css('position', 'relative');
    }
  }
}
<commit_msg>DDCNFF-813 Generalized the JS<commit_after>module.exports = function(el) {
  //Had to grab the width & vertical position off the original
  //to stop it popping to the windows width when position was changed to fixed
  //ADD THE DATA-FOCUSES TAG TO YOUR ELEMENT WITH ITS OWN ID IN IT
  var bannerId = $('[data-focuses]').attr('data-focuses'),
  idOfBanner = $('#' + bannerId),
  orgElementPos = idOfBanner.offset(),
  orgElementTop = orgElementPos.top,
  widthOrgElement = idOfBanner.width();

  //Banner pops out the DOM so this makes sure the content below doesn't shift up
  //You need a containing element around the floating element!
  idOfBanner.parent().css('height', idOfBanner.parent().height());

  //Run the function to reposition the banner
  setInterval(stickIt, 100);

  function stickIt() {
    if ($(window).scrollTop() >= (orgElementTop)) {
      // scrolled past the original position; change the position to fixed.
      idOfBanner.css('position', 'fixed').css('width', widthOrgElement).css('top', '0px');
    } else {
      //Returns the banner to the DOM once we scroll up
      idOfBanner.css('position', 'relative');
    }
  }
}
<|endoftext|>