<commit_before>$(function () {
  $('.orgdashboards-filters').on('change', function () {
    var url = $(this).val();
    if (url) {
      window.location = url + '#search-data';
    }
    return false;
  });

 $(document).ready(function(){

     var disclaimerText = $('.hero-info .media-body');
     var disclaimerContainer = $('.media.hero-info');

     $('#newly-released-data-btn').on('click', function () {
         console.log('detected click');
         if ($('#newly-released-data').hasClass('hidden')) {
             $('#newly-released-data-btn').html('');
             $('#newly-released-data').removeClass('hidden');
             $('#newly-released-data-btn').html('');

         }
         else {
             $('#newly-released-data-btn').html('');
             $('#newly-released-data').addClass('hidden');
             $('#newly-released-data-btn').html('');
         }
     });

     // Click handler for the disclaimer icon.
     $('.hero-info > .media-left').click(function onMapDisclaimerClick(event) {
         var bodyWidth = $('body').outerWidth();
         var topPosition;

         if (disclaimerText.hasClass('hidden')) {
             topPosition = bodyWidth <= 976 ? '790px' : '295px';

             disclaimerText.removeClass('hidden');
             disclaimerContainer.css({
                 'width': '300px',
                 'padding': '10px',
             });
         } else {
             topPosition = bodyWidth <= 976 ? '905px' : '410px';

             disclaimerText.addClass('hidden');
             disclaimerContainer.css({
                 'width': '54px',
                 'padding': '2px',
             });
         }
     });

     _setActiveLanguage();

     // Enable toggling of Extension descriptions
     $('.dashboard-description .more-link').click(function (e) {
         e.preventDefault(); // Prevents other scripts from triggering window.scroll();
         $(this).parent().parent().parent().children('.description-short').toggleClass('hidden');
         $(this).parent().parent().parent().children('.description-full').toggleClass('hidden');
     });

     if ($('#survey_popup').length) {
         var survey_popup = $('#survey_popup').popup({
             type: 'overlay',
             outline: true,
             scrolllock: true,
             transition: 'all 0.3s',
             closeelement: '#survey_popup_close',
             blur: false,
             onclose: function () {
                 Cookies.set('survey_popup_link', $('.survey_link').attr('href'), { expires: 365 });
             }
         });
         var survey_popup_link = $('.survey_link').attr('href');

         cookie = Cookies.get('survey_popup_link');

         if (undefined == cookie) {
             $('#survey_popup').removeClass('hidden');
             survey_popup.popup('show');
         } else if (cookie != survey_popup_link) {
             Cookies.set('survey_popup_link', survey_popup_link, { expires: 365 });
             $('#survey_popup').removeClass('hidden');
             survey_popup.popup('show');
         }
     }

     $('#survey_link_button').click(function() {
         Cookies.set('survey_popup_link', survey_popup_link, { expires: 365 });
         $('#survey_popup').popup('hide');
     });

    _setFocusOnSelectFilters();
  });

});

function toggleResources(resourceId) {
  $('#' + resourceId).toggleClass('hidden');
}

/*
 * Set the active language in the language picker
 * based on the active locale
 */
function _setActiveLanguage() {
  var pathname = window.location.pathname;
  var paths = pathname.split('/');
  var languageSelector = $('.language-selector');
  var currentLanguage;
  var languageElement;

  // If there is a locale then set the active one
  if (paths.length === 5) {
    currentLanguage = paths[1];

    if (currentLanguage === 'en') {
      languageElement = languageSelector.find('li')[0];
    } else {
      languageElement = languageSelector.find('li')[1];
    }
  } else {
    languageElement = languageSelector.find('li')[0];
  }

  languageElement.className = 'active';
}

function _setFocusOnSelectFilters() {
  var baseColor = $('.all-data > .data-block-header')[0].style.background;
  var rule = ['border-color: ' + baseColor + ';',
              'box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 3px ' + baseColor + ';'].join('');
  var organization = window.location.pathname.split('/').reverse()[1];

  // Check whether there is already a rule set for the current organization
  if (!_ruleExists('.' + organization + ':focus')) {
    _addCssRule('select.form-control:focus', rule);
  }
}

function _addCssRule(selector, rule) {
  if (document.styleSheets) {
    if (!document.styleSheets.length) {
      var head = document.getElementsByTagName('head')[0];
      head.appendChild(bc.createEl('style'));
    }

    var i = document.styleSheets.length-1;
    var ss = document.styleSheets[i];
    var l = 0;

    if (ss.cssRules) {
      l = ss.cssRules.length;
    } else if (ss.rules) {
      // IE
      l = ss.rules.length;
    }

    if (ss.insertRule) {
      ss.insertRule(selector + ' {' + rule + '}', l);
    } else if (ss.addRule) {
      // IE
      ss.addRule(selector, rule, l);
    }
  }
};

function _ruleExists(selector) {
  var rules = [];

  $.each(document.styleSheets, function(value, key) {
    if (key.href && key.href.indexOf('style.css') > -1) {
      rules = key.rules;
      return false;
    }
  });

  for (var i = 0; i < rules.length; i++) {
    if (rules[i].selectorText === selector) {
      return true;
    }
  }
}
<commit_msg>Add outline to form controls<commit_after>$(function () {
  $('.orgdashboards-filters').on('change', function () {
    var url = $(this).val();
    if (url) {
      window.location = url + '#search-data';
    }
    return false;
  });

 $(document).ready(function(){

     var disclaimerText = $('.hero-info .media-body');
     var disclaimerContainer = $('.media.hero-info');

     $('#newly-released-data-btn').on('click', function () {
         console.log('detected click');
         if ($('#newly-released-data').hasClass('hidden')) {
             $('#newly-released-data-btn').html('');
             $('#newly-released-data').removeClass('hidden');
             $('#newly-released-data-btn').html('');

         }
         else {
             $('#newly-released-data-btn').html('');
             $('#newly-released-data').addClass('hidden');
             $('#newly-released-data-btn').html('');
         }
     });

     // Click handler for the disclaimer icon.
     $('.hero-info > .media-left').click(function onMapDisclaimerClick(event) {
         var bodyWidth = $('body').outerWidth();
         var topPosition;

         if (disclaimerText.hasClass('hidden')) {
             topPosition = bodyWidth <= 976 ? '790px' : '295px';

             disclaimerText.removeClass('hidden');
             disclaimerContainer.css({
                 'width': '300px',
                 'padding': '10px',
             });
         } else {
             topPosition = bodyWidth <= 976 ? '905px' : '410px';

             disclaimerText.addClass('hidden');
             disclaimerContainer.css({
                 'width': '54px',
                 'padding': '2px',
             });
         }
     });

     _setActiveLanguage();

     // Enable toggling of Extension descriptions
     $('.dashboard-description .more-link').click(function (e) {
         e.preventDefault(); // Prevents other scripts from triggering window.scroll();
         $(this).parent().parent().parent().children('.description-short').toggleClass('hidden');
         $(this).parent().parent().parent().children('.description-full').toggleClass('hidden');
     });

     if ($('#survey_popup').length) {
         var survey_popup = $('#survey_popup').popup({
             type: 'overlay',
             outline: true,
             scrolllock: true,
             transition: 'all 0.3s',
             closeelement: '#survey_popup_close',
             blur: false,
             onclose: function () {
                 Cookies.set('survey_popup_link', $('.survey_link').attr('href'), { expires: 365 });
             }
         });
         var survey_popup_link = $('.survey_link').attr('href');

         cookie = Cookies.get('survey_popup_link');

         if (undefined == cookie) {
             $('#survey_popup').removeClass('hidden');
             survey_popup.popup('show');
         } else if (cookie != survey_popup_link) {
             Cookies.set('survey_popup_link', survey_popup_link, { expires: 365 });
             $('#survey_popup').removeClass('hidden');
             survey_popup.popup('show');
         }
     }

     $('#survey_link_button').click(function() {
         Cookies.set('survey_popup_link', survey_popup_link, { expires: 365 });
         $('#survey_popup').popup('hide');
     });

    _setFocusOnSelectFormControls();
  });

});

function toggleResources(resourceId) {
  $('#' + resourceId).toggleClass('hidden');
}

/*
 * Set the active language in the language picker
 * based on the active locale
 */
function _setActiveLanguage() {
  var pathname = window.location.pathname;
  var paths = pathname.split('/');
  var languageSelector = $('.language-selector');
  var currentLanguage;
  var languageElement;

  // If there is a locale then set the active one
  if (paths.length === 5) {
    currentLanguage = paths[1];

    if (currentLanguage === 'en') {
      languageElement = languageSelector.find('li')[0];
    } else {
      languageElement = languageSelector.find('li')[1];
    }
  } else {
    languageElement = languageSelector.find('li')[0];
  }

  languageElement.className = 'active';
}

function _setFocusOnSelectFormControls() {
  var baseColor = $('.all-data > .data-block-header')[0].style.background;
  var rule = ['border-color: ' + baseColor + ';',
              'outline': '0',
              'box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075), 0 0 3px ' + baseColor + ';'].join('');
  var organization = window.location.pathname.split('/').reverse()[1];

  // Check whether there is already a rule set for the current organization
  if (!_ruleExists('.' + organization + ':focus')) {
    _addCssRule('select.form-control:focus', rule);
  }
}

function _addCssRule(selector, rule) {
  if (document.styleSheets) {
    if (!document.styleSheets.length) {
      var head = document.getElementsByTagName('head')[0];
      head.appendChild(bc.createEl('style'));
    }

    var i = document.styleSheets.length-1;
    var ss = document.styleSheets[i];
    var l = 0;

    if (ss.cssRules) {
      l = ss.cssRules.length;
    } else if (ss.rules) {
      // IE
      l = ss.rules.length;
    }

    if (ss.insertRule) {
      ss.insertRule(selector + ' {' + rule + '}', l);
    } else if (ss.addRule) {
      // IE
      ss.addRule(selector, rule, l);
    }
  }
};

function _ruleExists(selector) {
  var rules = [];

  $.each(document.styleSheets, function(value, key) {
    if (key.href && key.href.indexOf('style.css') > -1) {
      rules = key.rules;
      return false;
    }
  });

  for (var i = 0; i < rules.length; i++) {
    if (rules[i].selectorText === selector) {
      return true;
    }
  }
}
<|endoftext|>


<commit_before>//
// GistbookRoute
//

import * as Radio from 'radio';
import Route from '../../vendor/routing/route';
import GistView from '../../shared/views/gist-view';
import Gist from '../../shared/entities/gist';
import ServerErrorView from '../../shared/views/server-error-view';

export default Route.extend({
  fetch: function(urlData) {
    this.gistbook = new Gist({
      id: urlData.params.gistbookId
    });
    return this.gistbook.fetch();
  },

  onFetchError: function() {
    Radio.command('rootView', 'showIn:container', new ServerErrorView());
  },

  show: function(data, urlData) {
    var gistOwner = this.gistbook.get('owner');
    var gistUser = gistOwner ? gistOwner.login : 'anonymous';
    var username = urlData.params.username;
    var View = gistUser === username ? GistView : ServerErrorView;
    var user = Radio.request('user', 'user');
    var view = new View({
      model: this.gistbook,
      ownGistbook: user.get('login') === username
    });
    Radio.command('rootView', 'showIn:container', view);
  }
});
<commit_msg>Add case-insensitive username comparison.<commit_after>//
// GistbookRoute
//

import * as Radio from 'radio';
import Route from '../../vendor/routing/route';
import GistView from '../../shared/views/gist-view';
import Gist from '../../shared/entities/gist';
import ServerErrorView from '../../shared/views/server-error-view';

export default Route.extend({
  fetch: function(urlData) {
    this.gistbook = new Gist({
      id: urlData.params.gistbookId
    });
    return this.gistbook.fetch();
  },

  onFetchError: function() {
    Radio.command('rootView', 'showIn:container', new ServerErrorView());
  },

  show: function(data, urlData) {
    var gistOwner = this.gistbook.get('owner');
    var gistUser = gistOwner ? gistOwner.login : 'anonymous';
    var username = urlData.params.username;
    var View = gistUser.toLowerCase() === username.toLowerCase() ? GistView : ServerErrorView;
    var user = Radio.request('user', 'user');
    var view = new View({
      model: this.gistbook,
      ownGistbook: user.get('login') === username
    });
    Radio.command('rootView', 'showIn:container', view);
  }
});
<|endoftext|>


<commit_before>define(['marionette',
    'collections/shipments',
    'views/table',
    'utils/table',
    'utils'],
    function(Marionette, Shipments, TableView, table, utils) {

    var ClickableRow = table.ClickableRow.extend({
        event: 'shipment:show',
        argument: 'SHIPPINGID',
        cookie: true
    })

    return Marionette.LayoutView.extend({
        className: 'content',
        template: _.template('
Shipping Manifest
<select name="month"></select> Print Shipping Manifest

'),
        regions: { rshps: '.shipments' },

        events: {
            'click a.manifest': 'loadManifest',
        },

        ui: {
            month: 'select[name=month]',
        },

        loadManifest: function(e) {
            e.preventDefault()

            var month = '?month='+this.ui.month.val()
            var url = app.apiurl+'/pdf/manifest'+month

            utils.sign({
                url: url,
                callback: function(resp) {
                    window.location = url+'&token='+resp.token
                }
            })
        },

        initialize: function() {
            this.shipments = new Shipments()
            this.shipments.queryParams.manifest = 1
            this.shipments.queryParams.all = 1
            this.shipments.fetch()
        },

        onRender: function() {
            this.ui.month.empty()
            var d = new Date()
            _.each([d.getFullYear(), d.getFullYear()-1], function(y) {
                _.each(_.range(1,13), function(m) {
                    var m = (m < 10 ? ('0'+m) : m)+'-'+y
                    this.ui.month.append('<option value="'+m+'">'+m+'</option>')
                }, this)
            }, this)

            var m = d.getMonth() +1
            var cur = (m < 10 ? ('0'+m) : m)+'-'+d.getFullYear()
            this.ui.month.val(cur)

            var columns = [
                { name: 'PROP', label: 'Proposal', cell: 'string', editable: false },
                { name: 'SHIPPINGNAME', label: 'Shipment', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_FLIGHTCODETIMESTAMP', label: 'Created', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_SHIPPINGDATE', label: 'Shipped', cell: 'string', editable: false },
                { label: 'Account', cell: table.TemplateCell, editable: false, template: '<% if (TERMSACCEPTED == "1") { %>Facility<% } else { %><%=DELIVERYAGENT_AGENTCODE%><% } %>' },
                { name: 'DELIVERYAGENT_FLIGHTCODE', label: 'Flightcode', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_PRODUCTCODE', label: 'Product', cell: 'string', editable: false },
                { name: 'DCOUNT', label: 'Pieces', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_BARCODE', label: 'Piece Barcodes', cell: 'string', editable: false },
                { name: 'WEIGHT', label: 'Weight', cell: 'string', editable: false },
                { label: 'Sender', cell: table.TemplateCell, editable: false, template: '<%=GIVENNAME%> <%=FAMILYNAME%> <%=LABNAME%>' },
                { label: 'Origin', cell: table.TemplateCell, editable: false, template: '<%=CITY%> <%=POSTCODE%> <%=COUNTRY%>' },
            ]

            if (app.mobile()) {
                _.each([2,3,5,6], function(v) {
                    columns[v].renderable = false
                })
            }

            this.rshps.show(new TableView({ collection: this.shipments, columns: columns, filter: 's', tableClass: 'shipments', backgrid: { row: ClickableRow, emptyText: 'No shipments found' } }))

        }

    })

})<commit_msg>add awb creator to manifest<commit_after>define(['marionette',
    'collections/shipments',
    'views/table',
    'utils/table',
    'utils'],
    function(Marionette, Shipments, TableView, table, utils) {

    var ClickableRow = table.ClickableRow.extend({
        event: 'shipment:show',
        argument: 'SHIPPINGID',
        cookie: true
    })

    return Marionette.LayoutView.extend({
        className: 'content',
        template: _.template('
Shipping Manifest
<select name="month"></select> Print Shipping Manifest

'),
        regions: { rshps: '.shipments' },

        events: {
            'click a.manifest': 'loadManifest',
        },

        ui: {
            month: 'select[name=month]',
        },

        loadManifest: function(e) {
            e.preventDefault()

            var month = '?month='+this.ui.month.val()
            var url = app.apiurl+'/pdf/manifest'+month

            utils.sign({
                url: url,
                callback: function(resp) {
                    window.location = url+'&token='+resp.token
                }
            })
        },

        initialize: function() {
            this.shipments = new Shipments()
            this.shipments.queryParams.manifest = 1
            this.shipments.queryParams.all = 1
            this.shipments.fetch()
        },

        onRender: function() {
            this.ui.month.empty()
            var d = new Date()
            _.each([d.getFullYear(), d.getFullYear()-1], function(y) {
                _.each(_.range(1,13), function(m) {
                    var m = (m < 10 ? ('0'+m) : m)+'-'+y
                    this.ui.month.append('<option value="'+m+'">'+m+'</option>')
                }, this)
            }, this)

            var m = d.getMonth() +1
            var cur = (m < 10 ? ('0'+m) : m)+'-'+d.getFullYear()
            this.ui.month.val(cur)

            var columns = [
                { name: 'PROP', label: 'Proposal', cell: 'string', editable: false },
                { name: 'SHIPPINGNAME', label: 'Shipment', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_FLIGHTCODETIMESTAMP', label: 'Created', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_SHIPPINGDATE', label: 'Shipped', cell: 'string', editable: false },
                { label: 'Account', cell: table.TemplateCell, editable: false, template: '<% if (TERMSACCEPTED == "1") { %>Facility<% } else { %><%=DELIVERYAGENT_AGENTCODE%><% } %>' },
                { name: 'DELIVERYAGENT_FLIGHTCODE', label: 'Flightcode', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_PRODUCTCODE', label: 'Product', cell: 'string', editable: false },
                { name: 'DCOUNT', label: 'Pieces', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_BARCODE', label: 'Piece Barcodes', cell: 'string', editable: false },
                { name: 'WEIGHT', label: 'Weight', cell: 'string', editable: false },
                { name: 'DELIVERYAGENT_FLIGHTCODEPERSON', label: 'Creator', cell: 'string', editable: false },
                { label: 'Sender', cell: table.TemplateCell, editable: false, template: '<%=GIVENNAME%> <%=FAMILYNAME%> <%=LABNAME%>' },
                { label: 'Origin', cell: table.TemplateCell, editable: false, template: '<%=CITY%> <%=POSTCODE%> <%=COUNTRY%>' },
            ]

            if (app.mobile()) {
                _.each([2,3,5,6], function(v) {
                    columns[v].renderable = false
                })
            }

            this.rshps.show(new TableView({ collection: this.shipments, columns: columns, filter: 's', tableClass: 'shipments', backgrid: { row: ClickableRow, emptyText: 'No shipments found' } }))

        }

    })

})<|endoftext|>


<commit_before>define(['marionette', 'backbone', 'views/pages',
    'collections/shipments',
    'collections/containers',
    'collections/dewars',
    'models/shipment',
    'models/dewar',
    'modules/assign/collections/pucknames',

    'utils',
    'templates/assign/assign.html',
    'jquery-ui/ui/widgets/droppable'
    ], function(Marionette,
        Backbone,
        Pages,
        Shipments,
        Containers,
        Dewars,
        Shipment,
        Dewar,
        PuckNames,

        utils,
        template) {

    var ContainerView = Marionette.CompositeView.extend({
        template: _.template('<a class="button button-notext" title="Click to view container contents" href="/containers/cid/<%-CONTAINERID%>"> View Container
<%-NAME%>
'),
        className: function() { return  'container' + (this.getOption('assigned') ? ' assigned' : '') },

        initialize: function(options) {
            this.getOption('model').view = this
        },

        onRender: function() {
            this.$el.draggable({
                containment: '#drag_container',
                stack: '#unassigned div',
                revert: true
            })
        },

        events: {
            'drop:assign': 'assignContainer',
            'drop:unassign': 'unassignContainer',
        },

        // possible circular reference
        onDestroy: function() {
            this.model.view = null
        },

        // Assign Containers
        assignContainer: function(e, options) {
            console.log('confirm container on to', options.id, this.model)
            utils.confirm({
                title: 'Confirm Container Assignment',
                content: 'Are you sure you want to assign "'+this.model.get('NAME')+'" to sample changer position "'+options.id+'"?',
                callback: this.doAssign.bind(this, options)
            })
        },

        doAssign: function(options) {
            console.log('dropped container on to', options.id, this.model, options.assigned)

            var assigned = options.assigned.where({ SAMPLECHANGERLOCATION: options.id.toString() })
            console.log(assigned)
            _.each(assigned, function(c) {
                c.view.doUnAssign.call(c.view,options)
            })

            Backbone.ajax({
                url: app.apiurl+'/assign/assign',
                data: { visit: options.visit, cid: this.model.get('CONTAINERID'), pos: options.id },
                success: this.assignUpdateGUI.bind(this, options),
                error: function(xhr, message, options) {
                    app.alert({ message: 'Something went wrong assigning this container:' })
                },
            })
        },

        assignUpdateGUI: function(options) {
            this.trigger('remove:container', this.model)
            this.model.set({ SAMPLECHANGERLOCATION: options.id.toString() })
            options.assigned.add(this.model)
        },

        // Unassign Containers
        unassignContainer: function(e, options) {
            console.log('unassign container', this.model)
            utils.confirm({
                title: 'Confirm Container Unassignment',
                content: 'Are you sure you want to unassign "'+this.model.get('NAME')+'" from sample changer position "'+this.model.get('SAMPLECHANGERLOCATION')+'"?',
                callback: this.doUnAssign.bind(this, options)
            })
        },

        doUnAssign: function(options) {
            console.log('unassigning', this.model)
            Backbone.ajax({
                url: app.apiurl+'/assign/unassign',
                data: { visit: options.visit, cid: this.model.get('CONTAINERID') },
                success: this.unassignUpdateGUI.bind(this, options),
                error: function(xhr, message, options) {
                    app.alert({ message: 'Something went wrong unassigning this container:' })

                },
            })
        },

        unassignUpdateGUI: function(options) {
            this.model.set({ SAMPLECHANGERLOCATION: null })
            this.trigger('remove:container', this.model)

            var shipments = _.uniq(options.shipments.pluck('SHIPPINGID'))
            if (shipments.indexOf(this.model.get('SHIPPINGID')) > -1) {
                var s = options.shipments.findWhere({ SHIPPINGID: this.model.get('SHIPPINGID') })
                var d = s.get('DEWARS').findWhere({ DEWARID: this.model.get('DEWARID') })
                d.get('CONTAINERS').add(this.model)

                console.log('add container to dewar')
            }
        },

    })

    // List of Dewars in Shipment
    var DewarView = Marionette.CompositeView.extend({
        template: _.template('
<%-CODE%> Deactivate Dewar

'),
        className: function() {
            var classes = 'dewar clearfix'
            if (this.model.get('DEWARSTATUS') == 'processing') classes += ' active'

            return classes
        },

        childView: ContainerView,
        childEvents: {
            'remove:container': 'removeContainer',
        },

        events: {
            'click a.deact': 'deactivateDewar',
        },

        deactivateDewar: function(e) {
            e.preventDefault()
            var self = this
            Backbone.ajax({
                url: app.apiurl+'/assign/deact',
                data: { did: this.model.get('DEWARID') },
                success: function() {
                    self.$el.removeClass('active')
                    self.trigger('refresh')
                },

                error: function() {
                    app.alert({ message: 'Something went wrong deactivating this dewar' })
                }

            })
        },

        removeContainer: function(child, model) {
            console.log('remove container dewar', model)
            this.collection.remove(model)
            this.render()
        },

        initialize: function(options) {
            this.collection = this.model.get('CONTAINERS')
        },

        onRender: function() {
            this.$el.show()
        }
    })

    // List of Shipments
    var ShipmentView = Marionette.CompositeView.extend({
        template: _.template('
<%-SHIPPINGNAME%>
'),
        childView: DewarView,
        className: 'shipment',

        initialize: function(options) {
            this.collection = this.model.get('DEWARS')
        }
    })

    // Sample Changer Positions
    var PositionView = Marionette.CompositeView.extend({
        className:'bl_puck',
        template: _.template('<%-id%>

'),

        childView: ContainerView,
        childViewOptions: {
            assigned: true,
        },
        childViewContainer: '.ac',

        childEvents: {
            'remove:container': 'removeContainer',
        },

        ui: {
            name: '.name',
        },

        removeContainer: function(child, model) {
            console.log('remove container position', model)
            this.collection.remove(model)
            this.render()
        },

        collectionEvents: {
            'change reset': 'render',
        },

        events: {
            'drop': 'handleDrop',
        },

        initialize: function(options) {
            this.collection = new Containers()
            this.assigned = options.assigned
            this.listenTo(this.assigned, 'change sync reset add remove', this.updateCollection, this)
            this.updateCollection()

            this.listenTo(this.getOption('pucknames'), 'sync', this.getNameModel)
        },

        getNameModel: function() {
            this.name = this.getOption('pucknames').findWhere({ id: this.model.get('id') })
            if (this.name) {
                this.listenTo(this.name, 'change update', this.updateName)
                this.updateName()
            }
        },

        updateName: function() {
            if (this.name && this.name.get('name')) this.ui.name.text(' - '+this.name.get('name'))
        },

        updateCollection: function() {
            //console.log('update assigned', this.assigned)
            this.collection.reset(this.assigned.findWhere({ SAMPLECHANGERLOCATION: this.model.get('id').toString() }))
        },

        onRender: function() {
            this.$el.attr('id', 'blpos'+this.model.get('id'))
            this.$el.droppable({
                accept: '.container',
                hoverClass: 'bl_puck_drag',
            })
            this.updateName()
        },

        handleDrop: function(e, ui) {
            ui.draggable.trigger('drop:assign', { id: this.model.get('id'), assigned: this.assigned, visit: this.getOption('visit') })
        }

    })

    var SampleChangerView = Marionette.CollectionView.extend({
        className: 'clearfix',
        childView: PositionView,
        childViewOptions: function() {
            return {
                assigned: this.getOption('assigned'),
                visit: this.getOption('visit'),
                pucknames: this.getOption('pucknames')
            }
        }
    })

    return Marionette.CompositeView.extend({
        template: template,
        className: 'content',
        childView: ShipmentView,
        childViewContainer: '#unassigned',

        events: {
            'drop #unassigned': 'handleDrop',
        },

        handleDrop: function(e, ui) {
            ui.draggable.trigger('drop:unassign', { shipments: this.collection, visit: this.getOption('visit').get('VISIT') })
        },

        templateHelpers: function() {
            return {
                VISIT: this.getOption('visit').toJSON(),
            }
        },

        refresh: function() {
            this.assigned.fetch()
            this.containers.fetch()
        },

        initialize: function(options) {
            this.collection = new Shipments()

            this.assigned = new Containers(null, { queryParams: { assigned: 1, bl: this.getOption('visit').get('BL') }, state: { pageSize: 9999 } })
            this.assigned.fetch()

            this.containers = new Containers(null, { queryParams: { unassigned: this.getOption('visit').get('BL') }, state: { pageSize: 30, currentPage: options.page } })
            var self = this
            this.containers.fetch().done(function() {
                console.log(self.containers)
            })
            this.listenTo(this.containers, 'sync', this.generateShipments, this)
            this.paginator = new Pages({ collection: this.containers })

            this.pucknames = new PuckNames()
            this.pucknames.state.pageSize = 100
            this.pucknames.queryParams.bl = this.getOption('visit').get('BL')
            this.pucknames.fetch()
        },

        generateShipments: function() {
            console.log('generate shipments')
            var sids = _.uniq(this.containers.pluck('SHIPPINGID'))
            var shipments = []
            _.each(sids, function(sid) {
                var conts = new Containers(this.containers.where({ SHIPPINGID: sid }))

                var dids = _.uniq(conts.pluck('DEWARID'))
                var dewars = new Dewars()
                _.each(dids, function(did) {
                    var d = conts.findWhere({ DEWARID: did })
                    var dewar = new Dewar({
                        DEWARID: did,
                        CODE: d.get('DEWAR'),
                        DEWARSTATUS: d.get('DEWARSTATUS'),
                        CONTAINERS: new Containers(conts.where({ DEWARID: did }))
                    })
                    dewars.add(dewar)
                }, this)

                var shipment = new Shipment({
                    SHIPPINGID: sid,
                    SHIPPINGNAME: conts.at(0).get('SHIPMENT'),
                    DEWARS: dewars,
                })
                shipments.push(shipment)
            }, this)

            this.collection.reset(shipments)
        },

        onShow: function() {
            if (this.getOption('visit').get('BL') in app.config.pucks) {
                var pucks = app.config.pucks[this.getOption('visit').get('BL')]
            } else var pucks = 10

            var positions = new Backbone.Collection(_.map(_.range(1,pucks+1), function(i) { return { id: i } }))
            this.scview = new SampleChangerView({
                collection: positions,
                assigned: this.assigned,
                visit: this.getOption('visit').get('VISIT'),
                shipments: this.collection,
                pucknames: this.pucknames,
            })
            this.$el.find('#assigned').append(this.scview.render().$el)
            this.$el.find('.page_wrap').append(this.paginator.render().$el)

            this.$el.find('#unassigned').droppable({
                accept: '.bl_puck .ac div',
                hoverClass: 'unassigned_drag',
            })
        },

        onDestroy: function() {
            if (this.scview) this.scview.destroy()
            this.pucknames.stop()
            // hmm no destroy?
            //if (this.paginator) this.paginator.destroy()
        },
    })

})<commit_msg>Fix the condition where all containers are assigned<commit_after>define(['marionette', 'backbone', 'views/pages',
    'collections/shipments',
    'collections/containers',
    'collections/dewars',
    'models/shipment',
    'models/dewar',
    'modules/assign/collections/pucknames',

    'utils',
    'templates/assign/assign.html',
    'jquery-ui/ui/widgets/droppable'
    ], function(Marionette,
        Backbone,
        Pages,
        Shipments,
        Containers,
        Dewars,
        Shipment,
        Dewar,
        PuckNames,

        utils,
        template) {

    var ContainerView = Marionette.CompositeView.extend({
        template: _.template('<a class="button button-notext" title="Click to view container contents" href="/containers/cid/<%-CONTAINERID%>"> View Container
<%-NAME%>
'),
        className: function() { return  'container' + (this.getOption('assigned') ? ' assigned' : '') },

        initialize: function(options) {
            this.getOption('model').view = this
        },

        onRender: function() {
            this.$el.draggable({
                containment: '#drag_container',
                stack: '#unassigned div',
                revert: true
            })
        },

        events: {
            'drop:assign': 'assignContainer',
            'drop:unassign': 'unassignContainer',
        },

        // possible circular reference
        onDestroy: function() {
            this.model.view = null
        },

        // Assign Containers
        assignContainer: function(e, options) {
            console.log('confirm container on to', options.id, this.model)
            utils.confirm({
                title: 'Confirm Container Assignment',
                content: 'Are you sure you want to assign "'+this.model.get('NAME')+'" to sample changer position "'+options.id+'"?',
                callback: this.doAssign.bind(this, options)
            })
        },

        doAssign: function(options) {
            console.log('dropped container on to', options.id, this.model, options.assigned)

            var assigned = options.assigned.where({ SAMPLECHANGERLOCATION: options.id.toString() })
            console.log(assigned)
            _.each(assigned, function(c) {
                c.view.doUnAssign.call(c.view,options)
            })

            Backbone.ajax({
                url: app.apiurl+'/assign/assign',
                data: { visit: options.visit, cid: this.model.get('CONTAINERID'), pos: options.id },
                success: this.assignUpdateGUI.bind(this, options),
                error: function(xhr, message, options) {
                    app.alert({ message: 'Something went wrong assigning this container:' })
                },
            })
        },

        assignUpdateGUI: function(options) {
            this.trigger('remove:container', this.model)
            this.model.set({ SAMPLECHANGERLOCATION: options.id.toString() })
            options.assigned.add(this.model)
        },

        // Unassign Containers
        unassignContainer: function(e, options) {
            console.log('unassign container', this.model)
            utils.confirm({
                title: 'Confirm Container Unassignment',
                content: 'Are you sure you want to unassign "'+this.model.get('NAME')+'" from sample changer position "'+this.model.get('SAMPLECHANGERLOCATION')+'"?',
                callback: this.doUnAssign.bind(this, options)
            })
        },

        doUnAssign: function(options) {
            console.log('unassigning', this.model)
            Backbone.ajax({
                url: app.apiurl+'/assign/unassign',
                data: { visit: options.visit, cid: this.model.get('CONTAINERID') },
                success: this.unassignUpdateGUI.bind(this, options),
                error: function(xhr, message, options) {
                    app.alert({ message: 'Something went wrong unassigning this container:' })

                },
            })
        },

        unassignUpdateGUI: function(options) {
            this.model.set({ SAMPLECHANGERLOCATION: null })
            this.trigger('remove:container', this.model)

            var shipments = _.uniq(options.shipments.pluck('SHIPPINGID'))
            if (shipments.indexOf(this.model.get('SHIPPINGID')) > -1) {
                var s = options.shipments.findWhere({ SHIPPINGID: this.model.get('SHIPPINGID') })
                var d = s.get('DEWARS').findWhere({ DEWARID: this.model.get('DEWARID') })
                d.get('CONTAINERS').add(this.model)

                console.log('add container to dewar')
            }
        },

    })

    // List of Dewars in Shipment
    var DewarView = Marionette.CompositeView.extend({
        template: _.template('
<%-CODE%> Deactivate Dewar

'),
        className: function() {
            var classes = 'dewar clearfix'
            if (this.model.get('DEWARSTATUS') == 'processing') classes += ' active'

            return classes
        },

        childView: ContainerView,
        childEvents: {
            'remove:container': 'removeContainer',
        },

        events: {
            'click a.deact': 'deactivateDewar',
        },

        deactivateDewar: function(e) {
            e.preventDefault()
            var self = this
            Backbone.ajax({
                url: app.apiurl+'/assign/deact',
                data: { did: this.model.get('DEWARID') },
                success: function() {
                    self.$el.removeClass('active')
                    self.trigger('refresh')
                },

                error: function() {
                    app.alert({ message: 'Something went wrong deactivating this dewar' })
                }

            })
        },

        removeContainer: function(child, model) {
            console.log('remove container dewar', model)
            this.collection.remove(model)
            this.render()
        },

        initialize: function(options) {
            this.collection = this.model.get('CONTAINERS')
        },

        onRender: function() {
            this.$el.show()
        }
    })

    // List of Shipments
    var ShipmentView = Marionette.CompositeView.extend({
        template: _.template('
<%-SHIPPINGNAME%>
'),
        childView: DewarView,
        className: 'shipment',

        initialize: function(options) {
            this.collection = this.model.get('DEWARS')
        }
    })

    // Sample Changer Positions
    var PositionView = Marionette.CompositeView.extend({
        className:'bl_puck',
        template: _.template('<%-id%>

'),

        childView: ContainerView,
        childViewOptions: {
            assigned: true,
        },
        childViewContainer: '.ac',

        childEvents: {
            'remove:container': 'removeContainer',
        },

        ui: {
            name: '.name',
        },

        removeContainer: function(child, model) {
            console.log('remove container position', model)
            this.collection.remove(model)
            this.render()
        },

        collectionEvents: {
            'change reset': 'render',
        },

        events: {
            'drop': 'handleDrop',
        },

        initialize: function(options) {
            this.collection = new Containers()
            this.assigned = options.assigned
            this.listenTo(this.assigned, 'change sync reset add remove', this.updateCollection, this)
            this.updateCollection()

            this.listenTo(this.getOption('pucknames'), 'sync', this.getNameModel)
        },

        getNameModel: function() {
            this.name = this.getOption('pucknames').findWhere({ id: this.model.get('id') })
            if (this.name) {
                this.listenTo(this.name, 'change update', this.updateName)
                this.updateName()
            }
        },

        updateName: function() {
            if (this.name && this.name.get('name')) this.ui.name.text(' - '+this.name.get('name'))
        },

        updateCollection: function() {
            //console.log('update assigned', this.assigned)
            this.collection.reset(this.assigned.findWhere({ SAMPLECHANGERLOCATION: this.model.get('id').toString() }))
        },

        onRender: function() {
            this.$el.attr('id', 'blpos'+this.model.get('id'))
            this.$el.droppable({
                accept: '.container',
                hoverClass: 'bl_puck_drag',
            })
            this.updateName()
        },

        handleDrop: function(e, ui) {
            ui.draggable.trigger('drop:assign', { id: this.model.get('id'), assigned: this.assigned, visit: this.getOption('visit') })
        }

    })

    var SampleChangerView = Marionette.CollectionView.extend({
        className: 'clearfix',
        childView: PositionView,
        childViewOptions: function() {
            return {
                assigned: this.getOption('assigned'),
                visit: this.getOption('visit'),
                pucknames: this.getOption('pucknames')
            }
        }
    })

    return Marionette.CompositeView.extend({
        template: template,
        className: 'content',
        childView: ShipmentView,
        childViewContainer: '#unassigned',

        events: {
            'drop #unassigned': 'handleDrop',
        },

        handleDrop: function(e, ui) {
            ui.draggable.trigger('drop:unassign', { shipments: this.collection, visit: this.getOption('visit').get('VISIT') })
        },

        templateHelpers: function() {
            return {
                VISIT: this.getOption('visit').toJSON(),
            }
        },

        refresh: function() {
            this.assigned.fetch()
            this.containers.fetch()
        },

        initialize: function(options) {
            this.collection = new Shipments()

            this.assigned = new Containers(null, { queryParams: { assigned: 1, bl: this.getOption('visit').get('BL') }, state: { pageSize: 9999 } })
            this.assigned.fetch()

            this.containers = new Containers(null, { queryParams: { unassigned: this.getOption('visit').get('BL') }, state: { pageSize: 30, currentPage: options.page } })
            var self = this
            this.containers.fetch().done(function() {
                console.log(self.containers)
            })
            this.listenTo(this.containers, 'sync', this.generateShipments, this)
            this.paginator = new Pages({ collection: this.containers })

            this.pucknames = new PuckNames()
            this.pucknames.state.pageSize = 100
            this.pucknames.queryParams.bl = this.getOption('visit').get('BL')
            this.pucknames.fetch()
        },

        generateShipments: function() {
            console.log('generate shipments')
            var sids = _.uniq(this.containers.pluck('SHIPPINGID'))
            var shipments = []
            _.each(sids, function(sid) {
                var conts = new Containers(this.containers.where({ SHIPPINGID: sid }))

                var dids = _.uniq(conts.pluck('DEWARID'))
                var dewars = new Dewars()
                _.each(dids, function(did) {
                    var d = conts.findWhere({ DEWARID: did })
                    var dewar = new Dewar({
                        DEWARID: did,
                        CODE: d.get('DEWAR'),
                        DEWARSTATUS: d.get('DEWARSTATUS'),
                        CONTAINERS: new Containers(conts.where({ DEWARID: did }))
                    })
                    dewars.add(dewar)
                }, this)

                var shipment = new Shipment({
                    SHIPPINGID: sid,
                    SHIPPINGNAME: conts.at(0).get('SHIPMENT'),
                    DEWARS: dewars,
                })
                shipments.push(shipment)
            }, this)

            // If all containers from shipments are assigned, then no shipments are available as drop targets.
            // This means that there is no ability to unassign containers. Fix: add a dummy shipment here.
            // Dragging a container to a shipment does not associate the container with that shipment - it will still be in the original shipment.
            if (shipments.length == 0) {
                var unassignShipment = new Shipment({
                    SHIPPINGID: 0,
                    SHIPPINGNAME: 'Drag Container here to unassign',
                })
                shipments.push(unassignShipment)
            }
            this.collection.reset(shipments)
        },

        onShow: function() {
            if (this.getOption('visit').get('BL') in app.config.pucks) {
                var pucks = app.config.pucks[this.getOption('visit').get('BL')]
            } else var pucks = 10

            var positions = new Backbone.Collection(_.map(_.range(1,pucks+1), function(i) { return { id: i } }))
            this.scview = new SampleChangerView({
                collection: positions,
                assigned: this.assigned,
                visit: this.getOption('visit').get('VISIT'),
                shipments: this.collection,
                pucknames: this.pucknames,
            })
            this.$el.find('#assigned').append(this.scview.render().$el)
            this.$el.find('.page_wrap').append(this.paginator.render().$el)

            this.$el.find('#unassigned').droppable({
                accept: '.bl_puck .ac div',
                hoverClass: 'unassigned_drag',
            })
        },

        onDestroy: function() {
            if (this.scview) this.scview.destroy()
            this.pucknames.stop()
            // hmm no destroy?
            //if (this.paginator) this.paginator.destroy()
        },
    })

})<|endoftext|>


<commit_before>
var as_selection_cnt = 0;
jQuery(document).ready(function(){
  var text_filter = jQuery('#as_awesome_selector_list_filter');
  var list_wrapper = jQuery('ul#as_selection_list_wrapper');

  /*js for text_box clear btn*/
  jQuery("#as_filter_clear_btn").click(function(){
    as_reset_list_filter();
  });

  /*js for autocomplete*/
  var ac = text_filter.autocomplete({
    minChars:1,
    maxHeight:200,
    //width:179,
    zIndex: 9999,
    deferRequestBy: 5, //miliseconds
    lookup: eval(text_filter.attr('autocomplete_array'))//local lookup values
  });
  //ac.disable();
  //ac.enable();

  /*js for word filter*/
  text_filter.jfilter({
    list: '#as_selection_list_wrapper',
    clear_btn: '#as_filter_clear_btn',
    speed: 100,
    highlight: 'highlight' // Class name with no "."
  });

  /*js for selecting item*/
  jQuery("ul#as_selection_list_wrapper li.as_selectable_element_details").each(function(){
    jQuery(this).click(function(){
      obj = jQuery(this);
      selection_limit = jQuery(this).attr('selection_limit');
      as_highlight_selected_div(obj, selection_limit);
    });
  });

  /*js display list of all the items*/
  jQuery("#as_show_all").click(function(){
    jQuery(this).addClass('as_bold');
    jQuery('#as_show_selection').removeClass('as_bold');
    jQuery('#as_selection_cnt').removeClass('as_bold');
    list_wrapper.removeClass('as_selected_elements_list');
    as_reset_list_filter();
  });

  /*js display selected item list*/
  jQuery("#as_show_selection").click(function(){
    jQuery('#as_show_all').removeClass('as_bold');
    jQuery('#as_selection_cnt').addClass('as_bold');
    jQuery(this).addClass('as_bold');
    list_wrapper.children("li:not('.as_selected')").hide();
    list_wrapper.children("li.as_selected").show();
    list_wrapper.addClass('as_selected_elements_list');
    as_reset_list_filter();
  });

  /*js to collect selected ids*/
  jQuery("#as_awesome_selector_form").submit(function(){
    var ids = new Array;
    var selection_limit;
    jQuery("ul#as_selection_list_wrapper li.as_selected").each(function(){
      ids.push(jQuery(this).attr('record_id'));
      selection_limit = jQuery(this).attr('selection_limit');
    });
    if(ids.length > 0)
    {
      var limit = eval(selection_limit);
      if ((limit != "unlimited") && (ids.length > limit[0]))
        {
         alert(limit[1]);
         return false;
        }
      jQuery('#as_selected_element_ids').val(ids.join());
      return true;
    }
    else
    {
      alert("Please select an item!");
      return false;
    }
  });
});

/*method to reset filter textbox and filter result*/
function as_reset_list_filter()
{
  jQuery("#as_awesome_selector_list_filter").val('');
  jQuery("#as_awesome_selector_list_filter").keyup();
}

/*method to display error message*/
function as_display_error(obj, msg)
{
  if(jQuery('#as_err_'+ obj).length == 0)
    jQuery('
'+ msg +'
').appendTo(jQuery('#as_selectable_error_msg'));
}

/*method to selected or deselect list item*/
function as_highlight_selected_div(element, max_selection_limit)
{
  if(!(element.hasClass('as_selected')))
  {
    var selection_limit = eval(max_selection_limit);
    if ((selection_limit == "unlimited") || (parseInt(as_selection_cnt) < selection_limit[0]))
    {
      element.addClass('as_selected');
      as_selection_cnt += 1;
      jQuery('#as_selection_cnt').html("(" + as_selection_cnt + ")");
    }
    else
      alert(selection_limit[1] ? selection_limit[1] : "You can not select more");
  }
  else
  {
    as_selection_cnt -= 1;
    jQuery('#as_selection_cnt').html("(" + as_selection_cnt + ")");
    element.removeClass('as_selected');
    if(jQuery('ul#as_selection_list_wrapper').hasClass('as_selected_elements_list'))
    {
      element.hide();
    }
  }
}
<commit_msg>resolved conflict<commit_after>
var as_selection_cnt = 0;
jQuery(document).ready(function(){
  var text_filter = jQuery('#as_awesome_selector_list_filter');
  var list_wrapper = jQuery('ul#as_selection_list_wrapper');

  /*js for text_box clear btn*/
  jQuery("#as_filter_clear_btn").click(function(){
    as_reset_list_filter();
  });

  /*js for autocomplete*/
  var ac = text_filter.autocomplete({
    minChars:1,
    maxHeight:200,
    //width:179,
    zIndex: 9999,
    deferRequestBy: 5, //miliseconds
    lookup: eval(text_filter.attr('autocomplete_array'))//local lookup values
  });
  //ac.disable();
  //ac.enable();

  /*js for word filter*/
  text_filter.jfilter({
    list: '#as_selection_list_wrapper',
    clear_btn: '#as_filter_clear_btn',
    speed: 100,
    highlight: 'highlight' // Class name with no "."
  });

  /*js for selecting item*/
  jQuery("ul#as_selection_list_wrapper li.as_selectable_element_details").each(function(){
    jQuery(this).click(function(){
      obj = jQuery(this);
      selection_limit = jQuery(this).attr('selection_limit');
      as_highlight_selected_div(obj, selection_limit);
    });
  });

  /*js display list of all the items*/
  jQuery("#as_show_all").click(function(){
    jQuery(this).addClass('as_bold');
    jQuery('#as_show_selection').removeClass('as_bold');
    jQuery('#as_selection_cnt').removeClass('as_bold');
    list_wrapper.removeClass('as_selected_elements_list');
    as_reset_list_filter();
  });

  /*js display selected item list*/
  jQuery("#as_show_selection").click(function(){
    jQuery('#as_show_all').removeClass('as_bold');
    jQuery('#as_selection_cnt').addClass('as_bold');
    jQuery(this).addClass('as_bold');
    list_wrapper.children("li:not('.as_selected')").hide();
    list_wrapper.children("li.as_selected").show();
    list_wrapper.addClass('as_selected_elements_list');
    as_reset_list_filter();
  });

  /*js to collect selected ids*/
  jQuery("#as_awesome_selector_form").submit(function(){
    var ids = new Array;
    var selection_limit;
    jQuery("ul#as_selection_list_wrapper li.as_selected").each(function(){
      ids.push(jQuery(this).attr('record_id'));
      selection_limit = jQuery(this).attr('selection_limit');
    });
    if(ids.length > 0)
    {
      var limit = eval(selection_limit);
      if ((limit != "unlimited") && (ids.length > limit[0]))
        {
         alert(limit[1]);
         return false;
        }
      jQuery('#as_selected_element_ids').val(ids.join());
      return true;
    }
    else
    {
      alert("Please select an item!");
      return false;
    }
  });
});

/*method to reset filter textbox and filter result*/
function as_reset_list_filter()
{
  jQuery("#as_awesome_selector_list_filter").val('');
  jQuery("#as_awesome_selector_list_filter").keyup();
}

/*method to display error message*/
function as_display_error(obj, msg)
{
  if(jQuery('#as_err_'+ obj).length == 0)
    jQuery('
'+ msg +'
').appendTo(jQuery('#as_selectable_error_msg'));
}

/*method to selected or deselect list item*/
function as_highlight_selected_div(element, max_selection_limit)
{
  if(!(element.hasClass('as_selected')))
  {
    var selection_limit = eval(max_selection_limit);
    if ((selection_limit == "unlimited") || (parseInt(as_selection_cnt) < selection_limit[0]))
    {
      element.addClass('selected');
      as_selection_cnt = parseInt(as_selection_cnt) + 1;
      jQuery('#selection_cnt').html("(" + selection_cnt + ")");
    }
    else
      alert(selection_limit[1] ? selection_limit[1] : "You can not select more");
  }
  else
  {
    as_selection_cnt = parseInt(as_selection_cnt) - 1;
    jQuery('#selection_cnt').html("(" + selection_cnt + ")");
    element.removeClass('selected');
    if(jQuery('ul#selection_list_wrapper').hasClass('selected_elements_list'))
    {
      element.hide();
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*jslint sub: true */
/**
 * @namespace The Aura History Service, accessible using $A.historyService. Manages Browser History.
 * Internet Explorer 7 and 8 are not supported for this service.
 * @constructor
 */
$A.ns.AuraHistoryService = function() {
    this.history = [];       // tracks url hashes
    this.currentIndex = -1;  // pointer to current hash within history
    this.evt = null;
};

/**
 * Sets the new location. For example, $A.services.history.set("search") sets the location to #search.
 * Otherwise, use $A.services.layout.changeLocation() to override existing URL parameters.
 *
 * Native Android browser doesn't completely support pushState so we force hash method for it
 * IOS7 UIWebView also has weirdness when using appcache and history so force onhashchange as well
 *
 * @param {Object} token The provided token set to the current location hash
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.set = function(token) {
    if (token) {
        // Check for HTML5 window.history.pushState support
        if (this.usePushState()) {
            //
            // Need to pass in the token to the state as
            // windows phone doesn't persist the hash
            // after using the back button.
            //
            window.history.pushState({"hash":token}, null, '#' + token);
            this.changeHandler();
        } else {
            if ($A.util.isIOSWebView()) {
                // roll our own history for IOS UIWebView
                var historyLength = this.history.length;
                if (this.currentIndex < (historyLength - 1)) {
                    // remove forward entries if we moved back and new location is set
                    this.history.splice(this.currentIndex + 1, historyLength - this.currentIndex);
                }
                this.currentIndex++;
                this.history.push(token);
            }
            window.location.hash = "#" + token;
        }
    }
};

/**
 * Parses the location. A token can be used here.
 *
Example:

 * token == "newLayout";
 $A.historyService.get().token;
 *
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.get = function() {
    //
    // Windows phone doesn't save the hash after navigating backwards.
    // So get it from the history state.
    //
    var token = location["hash"] || (window.history["state"] && window.history["state"]["hash"]) || "";
    return this.parseLocation(token);
};

/**
 * Loads the previous URL in the history list. Standard JavaScript history.go() method.
 *
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.back = function() {
    if (!$A.util.isIOSWebView()) {
        //history -> Standard javascript object
        window.history.go(-1);
    } else {
        // IOS7 UIWebView has issues with appcache and history so
        // keep track of history ourselves and change hash instead
        if (this.currentIndex > 0) {
            // move pointer and get previous hash location
            var hash = this.history[--this.currentIndex];
            window.location.hash = "#" + hash;
        } else {
            // in case pointer has moved passed all history then reset to push new history
            this.reset();
            window.location.hash = "";
        }
    }
};

/**
 * Sets the title of the document.
 *
 * @param {String} title The new title
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.setTitle = function(title) {
    document.title = title;
};

/**
 * Loads the next URL in the history list. Standard JavaScript history.go() method.
 *
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.forward = function() {
    if (!$A.util.isIOSWebView()) {
        //history -> Standard javascript object
        window.history.go(1);
    } else {
        // IOS7 UIWebView has issues with appcache and history so
        // keep track of history ourselves and change hash instead
        var historyLength = this.history.length;
        if (this.currentIndex < (historyLength - 1)) {
            // if there's forward history, go forward one
            window.location.hash = "#" + this.history[++this.currentIndex];
        }
    }
};

/**
 * Resets history
 *
 * @public
 */
$A.ns.AuraHistoryService.prototype.reset = function () {
    this.history = [];
    this.currentIndex = -1;
};

/**
 * Whether to use pushState.
 * Native Android browser has issues with pushState
 * IOS7 UIWebView has issues with pushState and history
 * @returns {boolean} true if pushState should be used
 * @private
 */
$A.ns.AuraHistoryService.prototype.usePushState = function() {
    if (this._usePushState === undefined) {
        var ua = window.navigator.userAgent;
        this._usePushState =
            // browser has pushState
            !!window.history.pushState &&
            // NOT native Android browser
            !(ua.indexOf("Android ") > -1 && ua.indexOf("Mozilla/5.0") > -1 && ua.indexOf("AppleWebKit") > -1 && ua.indexOf("Chrome") == -1) &&
            // NOT IOS7 UIWebView (native app webview)
            !$A.util.isIOSWebView();
    }
    return this._usePushState;
};

/**
 * @private
 */
$A.ns.AuraHistoryService.prototype.init = function() {
    // Check for HTML5 window.history.pushState support
    var that = this;
    if (this.usePushState()) {
        window.addEventListener("popstate", function(e) {
            that.changeHandler();
        });
    } else {
        var hash = location["hash"];

        this.history.push(hash);
        this.currentIndex++;

        // Checks for existence of event, and also ie8 in ie7 mode (misreports existence)
        var docMode = document["documentMode"];
        var hasOnHashChangeEvent = 'onhashchange' in window && (docMode === undefined || docMode > 7);

        if (hasOnHashChangeEvent) {
            window["onhashchange"] = function(){
                that.changeHandler();
            };
        } else {
            var watch = function(){
                setTimeout(function(){
                    var newHash = location["hash"];
                    if (newHash !== hash) {
                        hash = newHash;
                        that.changeHandler();
                    }
                    watch();
                }, 300);
            };
            watch();
        }
    }
    this.changeHandler();
    delete this.init;
};

/**
 * @private
 */
$A.ns.AuraHistoryService.prototype.getEvent = function(){
    if (!this.evt){
        this.evt = $A.getRoot().getDef().getLocationChangeEvent();
    }
    return this.evt;
};

/**
 * @private
 */
$A.ns.AuraHistoryService.prototype.changeHandler = function(){
    var loc = location["hash"] || (history["state"] && history["state"]["hash"]);
    var event = eventService.newEvent(this.getEvent());

    if(!event) {
        throw new Error("The event specified on the app for the locationChange (" + this.getEvent() + ") was not found.");
    }

    if (loc) {
        //
        // Its possible that more querystring parameters where specified in the hash
        // then are defined on the event. In this case do specify them as parameters
        // of the event.
        //
        var parsedHash = this.parseLocation(loc);
        var parameters = {};
        var attributes = event.getDef().getAttributeDefs();
        for(var attribute in attributes) {
            if(attributes["hasOwnProperty"](attribute) && parsedHash["hasOwnProperty"](attribute)) {
                parameters[attribute] = parsedHash[attribute];
            }
        }
        event.setParams(parameters);
    }

    event.fire();
};

/**
 * @private
 */
$A.ns.AuraHistoryService.prototype.parseLocation = function(location){
    if (location["indexOf"]("#") === 0){
        location = location["substring"](1);
    }

    if (location["indexOf"]('=') > -1){
        var split = location["split"]('?');
        if(split.length == 1){
            return decodeURIComponent(split[0]);
        }

        if(split.length == 2){
            var ret = $A.util.urlDecode(split[1]);
            ret["token"] = split[0];
            return ret;
        }

        throw new Error("Invalid location");
    } else{
        return {"token" : location};
    }
};

//#include aura.AuraHistoryService_export
<commit_msg>Re-add missing AuraHistoryService code from bad merge<commit_after>/*
 * Copyright (C) 2013 salesforce.com, inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*jslint sub: true */
/**
 * @namespace The Aura History Service, accessible using $A.historyService. Manages Browser History.
 * Internet Explorer 7 and 8 are not supported for this service.
 * @constructor
 */
$A.ns.AuraHistoryService = function() {
    this.history = [];       // tracks url hashes
    this.currentIndex = -1;  // pointer to current hash within history
    this.evt = null;
};

/**
 * Sets the new location. For example, $A.services.history.set("search") sets the location to #search.
 * Otherwise, use $A.services.layout.changeLocation() to override existing URL parameters.
 *
 * Native Android browser doesn't completely support pushState so we force hash method for it
 * IOS7 UIWebView also has weirdness when using appcache and history so force onhashchange as well
 *
 * @param {Object} token The provided token set to the current location hash
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.set = function(token) {
    if (token) {
        // Check for HTML5 window.history.pushState support
        if (this.usePushState()) {
            //
            // Need to pass in the token to the state as
            // windows phone doesn't persist the hash
            // after using the back button.
            //
            window.history.pushState({"hash":token}, null, '#' + token);
            this.changeHandler();
        } else {
            if ($A.util.isIOSWebView()) {
                // roll our own history for IOS UIWebView
                var historyLength = this.history.length;
                if (this.currentIndex < (historyLength - 1)) {
                    // remove forward entries if we moved back and new location is set
                    this.history.splice(this.currentIndex + 1, historyLength - this.currentIndex);
                }
                this.currentIndex++;
                this.history.push(token);
            }
            window.location.hash = "#" + token;
        }
    }
};

/**
 * Parses the location. A token can be used here.
 *
Example:

 * token == "newLayout";
 $A.historyService.get().token;
 *
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.get = function() {
    //
    // Windows phone doesn't save the hash after navigating backwards.
    // So get it from the history state.
    //
    var token = location["hash"] || (window.history["state"] && window.history["state"]["hash"]) || "";
    return this.parseLocation(token);
};

/**
 * Loads the previous URL in the history list. Standard JavaScript history.go() method.
 *
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.back = function() {
    if (!$A.util.isIOSWebView()) {
        //history -> Standard javascript object
        window.history.go(-1);
    } else {
        // IOS7 UIWebView has issues with appcache and history so
        // keep track of history ourselves and change hash instead
        if (this.currentIndex > 0) {
            // move pointer and get previous hash location
            var hash = this.history[--this.currentIndex];
            window.location.hash = "#" + hash;
        } else {
            // in case pointer has moved passed all history then reset to push new history
            this.reset();
            window.location.hash = "";
        }
    }
};

/**
 * Sets the title of the document.
 *
 * @param {String} title The new title
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.setTitle = function(title) {
    document.title = title;
};

/**
 * Loads the next URL in the history list. Standard JavaScript history.go() method.
 *
 * @memberOf AuraHistoryService
 * @public
 */
$A.ns.AuraHistoryService.prototype.forward = function() {
    if (!$A.util.isIOSWebView()) {
        //history -> Standard javascript object
        window.history.go(1);
    } else {
        // IOS7 UIWebView has issues with appcache and history so
        // keep track of history ourselves and change hash instead
        var historyLength = this.history.length;
        if (this.currentIndex < (historyLength - 1)) {
            // if there's forward history, go forward one
            window.location.hash = "#" + this.history[++this.currentIndex];
        }
    }
};

/**
 * Resets history
 *
 * @public
 */
$A.ns.AuraHistoryService.prototype.reset = function () {
    this.history = [];
    this.currentIndex = -1;
};

/**
 * Whether to use pushState.
 * Native Android browser has issues with pushState
 * IOS7 UIWebView has issues with pushState and history
 * @returns {boolean} true if pushState should be used
 * @private
 */
$A.ns.AuraHistoryService.prototype.usePushState = function() {
    if (this._usePushState === undefined) {
        var ua = window.navigator.userAgent;
        this._usePushState =
            // browser has pushState
            !!window.history.pushState &&
            // NOT native Android browser
            !(ua.indexOf("Android ") > -1 && ua.indexOf("Mozilla/5.0") > -1 && ua.indexOf("AppleWebKit") > -1 && ua.indexOf("Chrome") == -1) &&
            // NOT IOS7 UIWebView (native app webview)
            !$A.util.isIOSWebView();
    }
    return this._usePushState;
};

/**
 * @private
 */
$A.ns.AuraHistoryService.prototype.init = function() {
    // Check for HTML5 window.history.pushState support
    var that = this;
    if (this.usePushState()) {
        window.addEventListener("popstate", function(e) {
            that.changeHandler();
        });
    } else {
        var hash = location["hash"];

        this.history.push(hash);
        this.currentIndex++;

        // Checks for existence of event, and also ie8 in ie7 mode (misreports existence)
        var docMode = document["documentMode"];
        var hasOnHashChangeEvent = 'onhashchange' in window && (docMode === undefined || docMode > 7);

        if (hasOnHashChangeEvent) {
            window["onhashchange"] = function(){
                that.changeHandler();
            };
        } else {
            var watch = function(){
                setTimeout(function(){
                    var newHash = location["hash"];
                    if (newHash !== hash) {
                        hash = newHash;
                        that.changeHandler();
                    }
                    watch();
                }, 300);
            };
            watch();
        }
    }
    this.changeHandler();
    delete this.init;
};

/**
 * @private
 */
$A.ns.AuraHistoryService.prototype.getEvent = function(){
    if (!this.evt){
        this.evt = $A.getRoot().getDef().getLocationChangeEvent();
    }
    return this.evt;
};

/**
 * @private
 */
$A.ns.AuraHistoryService.prototype.changeHandler = function(){
    var loc = location["hash"] || (history["state"] && history["state"]["hash"]);
    var event = eventService.newEvent(this.getEvent());

    if(!event) {
        throw new Error("The event specified on the app for the locationChange (" + this.getEvent() + ") was not found.");
    }

    if (loc) {
        //
        // Its possible that more querystring parameters where specified in the hash
        // then are defined on the event. In this case do specify them as parameters
        // of the event.
        //
        var parsedHash = this.parseLocation(loc);
        var parameters = {};
        var attributes = event.getDef().getAttributeDefs();
        for(var attribute in attributes) {
            if(attributes["hasOwnProperty"](attribute) && parsedHash["hasOwnProperty"](attribute)) {
                parameters[attribute] = parsedHash[attribute];
            }
        }
        event.setParams(parameters);
    }

    event.fire();
};

/**
 * @private
 */
$A.ns.AuraHistoryService.prototype.parseLocation = function(location) {
    if (location["indexOf"]("#") === 0) {
        location = location["substring"](1);
    }

    if (location["indexOf"]('=') > -1) {
        var split = location["split"]('?');
        if(split.length == 1){
            return { "token": split[0], "querystring": "" };
        }

        if (split.length == 2) {
            var ret = $A.util.urlDecode(split[1]);
            ret["token"] = split[0];
            ret["querystring"] = split[1];
            return ret;
        }

        throw new Error("Invalid location");
    } else {
        return {"token" : location, "querystring": "" };
    }
};

//#include aura.AuraHistoryService_export
<|endoftext|>


<commit_before>import { createStore } from 'redux';
import rootReducer from './reducers/root';

const defaultState = {
  user: {
    loggedIn: localStorage.get(loggedIn) || false,
  },
  polls: [],
};

const store = createStore(
  rootReducer,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

export default store;
<commit_msg>Add default state to store<commit_after>import { createStore } from 'redux';
import rootReducer from './reducers/root';

const defaultState = {
  user: {
    loggedIn: localStorage.getItem('loggedIn') || false,
  },
  polls: [],
};

const store = createStore(
  rootReducer,
  defaultState,
  window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

export default store;
<|endoftext|>


<commit_before>var gameBoard = [];
var rawWordList = ['apple', 'banana', 'pineapple', 'mango', 'blueberry', 'guava', 'cherry', 'grape'];
var width = "";
var height = "";
var wordMap2D = [[]];

$(document).ready(function () {
    $('#game_board').html("
Change
");

    $('#board_create_btn').click(function () {
        createGameBoard();
    });
});

function clearGameBoard()
{
    $('#game_board').clear();
}

function createGameBoard()
{
    width = $('input[name=board_width_len]').val();
    if (width === "") width = 5;
    else width = parseInt(width);

    height = $('input[name=board_height_len]').val();
    if (height === "") height = 5;
    else height = parseInt(height);

    var blankTileHtml = "";

    // create blank board
    for (var row = 0; row < height; ++row)
    {
        blankTileHtml += "
";
        for (var col = 0; col < width; ++col)
        {
            blankTileHtml += "

";
        }
        blankTileHtml += "
";
    }

    $('#game_board').append(blankTileHtml);
}

function getTileObj(x, y)
{
    console.debug($('.gameTile[data-x=' + x + '][data-y=' + y + ']'));
    return $('.gameTile[data-x=' + x + '][data-y=' + y + ']');
}

function setPuzzleWord(wordList, maxWord)
{
    for (var i = 0; i < maxWord; ++i)
    {
        // randomly select word idx
        var selectedIdx = Math.floor(Math.random() * wordList.length);

        // extract word by idx
        var selectedWord = wordList[selectedIdx].substr(0);

        // remove word from row array
        wordList.splice(selectedIdx, 1);

        console.debug(selectedWord);

        // if words run out, escape loop
        if (wordList.length === 0) break;
    }
}

function addWordToWordManager(word)
{
    if (typeof width === "number" && typeof height === "number")
    {
        var isHorizon = false;
        if (word.length >= width) isHorizon = true;

        var isVertical = false;
        if (word.length >= height) isVertical = true;

        if (isHorizon === false && isVertical === false) return; // puzzle map is too small

    }
    else
    {
        console.debug("Map Size Error");
        return;
    }
}<commit_msg>brute force로 문자열 비교<commit_after>var gameBoard = [];
var rawWordList = ['apple', 'banana', 'pineapple', 'mango', 'blueberry', 'guava', 'cherry', 'grape'];
var width = "";
var height = "";
var wordMap2D = [[]];

$(document).ready(function () {
    $('#game_board').html("
Change
");

    $('#board_create_btn').click(function () {
        createGameBoard();
    });
});

function clearGameBoard()
{
    $('#game_board').clear();
}

function createGameBoard()
{
    width = $('input[name=board_width_len]').val();
    if (width === "") width = 5;
    else width = parseInt(width);

    height = $('input[name=board_height_len]').val();
    if (height === "") height = 5;
    else height = parseInt(height);

    var blankTileHtml = "";

    // create blank board
    for (var row = 0; row < height; ++row)
    {
        blankTileHtml += "
";
        for (var col = 0; col < width; ++col)
        {
            blankTileHtml += "

";
        }
        blankTileHtml += "
";
    }

    $('#game_board').append(blankTileHtml);
}

function getTileObj(x, y)
{
    console.debug($('.gameTile[data-x=' + x + '][data-y=' + y + ']'));
    return $('.gameTile[data-x=' + x + '][data-y=' + y + ']');
}

function setPuzzleWord(wordList, maxWord)
{
    for (var i = 0; i < maxWord; ++i)
    {
        // randomly select word idx
        var selectedIdx = Math.floor(Math.random() * wordList.length);

        // extract word by idx
        var selectedWord = wordList[selectedIdx].substr(0);

        // remove word from row array
        wordList.splice(selectedIdx, 1);

        console.debug(selectedWord);

        // if words run out, escape loop
        if (wordList.length === 0) break;
    }
}

function addWordToWordManager(word)
{
    if (typeof width === "number" && typeof height === "number")
    {
        // if word length is longer than puzzle board width
        var isHorizon = false;
        if (word.length >= width) isHorizon = true;

        // if word length is longer than puzzle board height
        var isVertical = false;
        if (word.length >= height) isVertical = true;

        // if puzzle map is too small, escape loop
        if (isHorizon === false && isVertical === false) return;

    }
    else
    {
        console.debug("Map Size Error");
        return;
    }
}

function findCrossIdxBetweenWords(firstWord, secondWord)
{
    var result = {};

    for(var i = 0; i < firstWord.length; ++i)
    {
        var indexOfSecond = secondWord.indexOf(firstWord[i]);

        if(indexOfSecond !== -1)
        {
            if (result[i] === undefined) result[i] = [];

            result[i].push(indexOfSecond);
        }
    }

    return result;
}<|endoftext|>


<commit_before><commit_msg>extract function for handling example placements<commit_after><|endoftext|>