<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function() {

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var MimeHeaderParser = Cc['@mozilla.org/messenger/headerparser;1']
                         .getService(Ci.nsIMsgHeaderParser);

var { Services } = Cu.import('resource://gre/modules/Services.jsm');

var BASE = 'extensions.send-to-internals@clear-code.com.';

var SendToInternalsHelper = {
  get bundle() {
    return document.getElementById('sendToInternalsBundle');
  },

  get internalDomains() {
    var internalDomains = Services.prefs.getComplexValue(BASE + 'domains', Ci.nsISupportsString).data;
    return internalDomains
             .split(/[,\|\s]+/)
             .map(function(aDomain) {
               return aDomain.trim();
             })
             .filter(function(aDomain) {
               return aDomain;
             });
  },

  get internalMatcher() {
    var expression = this.internalDomains.map(function(aAddress) {
          return aAddress.address.replace(/\./g, '\\.').replace(/\+/g, '\\+');
        }).join('|')
    return new RegExp(expression);
  },

  checkInternals : function()
  {
    var internalDomains = this.internalDomains;
    var externals = this.getAllRecipients().filter(function(aAddress) {
      var domain = aAddress.address.split('@')[1];
      return internalDomains.indexOf(domain) < 0;
    }, this);

    if (externals.length !== 0) {
      this.highlightExternals(externals);
      Services.prompt.alert(
        window,
        this.bundle.getString('alert.haveExternals.title'),
        this.bundle.getFormattedString('alert.haveExternals.text', externals.map(function(aAddress) {
          return aAddress.address;
        }))
      );
      return false;
    }

    return true;
  },

  highlightExternals : function(aExternalAddresses)
  {
    var addressFields = document.querySelectorAll('.textbox-addressingWidget');
    Array.forEach(addressFields, this.updateExternalHighlight, this);
  },

  HIGHLIGHT : 'data-send-to-internals-external-address',

  updateExternalHighlight : function(aField)
  {
    var matcher = this.internalMatcher;
    if (!matcher || !matcher.test(aField.value))
      aField.setAttribute(this.HIGHLIGHT, true);
    else
      aField.removeAttribute(this.HIGHLIGHT);
  },

  getAllRecipients : function()
  {
    var msgCompFields = gMsgCompose.compFields;
    Recipients2CompFields(msgCompFields);
    gMsgCompose.expandMailingLists();
    return this.splitRecipients(msgCompFields.to, 'To')
    		.concat(this.splitRecipients(msgCompFields.cc, 'Cc'))
            .concat(this.splitRecipients(msgCompFields.bcc, 'Bcc'));
  },

  splitRecipients : function(aAddressesSource, aType)
  {
    var addresses = {};
    var names = {};
    var fullNames = {};
    var numAddresses = MimeHeaderParser.parseHeadersWithArray(
                         aAddressesSource, addresses, names, fullNames);
    var recipients = [];
    for (let i = 0; i < numAddresses; i++) {
      let address = addresses.value[i];
      let domain = address.split('@')[1];
      recipients.push({
        address:  address,
        name:     names.value[i],
        fullName: fullNames.value[i],
        type:     aType
      });
    }
    return recipients;
  },

  // command controller
  supportsCommand : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
      case 'cmd_sendToInternalsNow':
      case 'cmd_sendToInternalsLater':
        return true;

      default:
        return false;
    }
  },
  isCommandEnabled : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
        return defaultController.commands.cmd_sendButton.isEnabled();

      case 'cmd_sendToInternalsNow':
        return defaultController.commands.cmd_sendNow.isEnabled();

      case 'cmd_sendToInternalsLater':
        return defaultController.commands.cmd_sendLater.isEnabled();

      default:
        return false;
    }
  },
  doCommand : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
        if (this.checkInternals())
          goDoCommand('cmd_sendButton');
        return;

      case 'cmd_sendToInternalsNow':
        if (this.checkInternals())
          goDoCommand('cmd_sendNow');
        return;

      case 'cmd_sendToInternalsLater':
        if (this.checkInternals())
          goDoCommand('cmd_sendLater');
        return;

      default:
        return false;
    }
  },
  onEvent : function(aEvent)
  {
  }
};
window.SendToInternalsHelper = SendToInternalsHelper;

window.addEventListener('DOMContentLoaded', function SendToInternalsOnLoad(aEvent) {
  window.removeEventListener(aEvent.type, SendToInternalsOnLoad, false);

  top.controllers.appendController(SendToInternalsHelper);

  var toolbar = document.getElementById('composeToolbar2');
  var defaultSet = toolbar.getAttribute('defaultset');
  var currentSet = toolbar.getAttribute('currentset');

  defaultSet = (defaultSet ? (defaultSet + ',') : '' ) + 'spring,button-sendToInternals';
  toolbar.setAttribute('defaultset', defaultSet);
  if (!Services.prefs.getBoolPref(BASE + 'initialized')) {
    Services.prefs.setBoolPref(BASE + 'initialized', true);
    if (currentSet) {
      currentSet = currentSet + ',spring,button-sendToInternals';
      toolbar.setAttribute('currentset', currentSet);
    }
  }

  window.addEventListener('input', function SendToInternalsOnInput(aEvent) {
    var field = aEvent.target;
    if (field.__sendToInternals__highlightTimeout)
      clearTimeout(field.__sendToInternals__highlightTimeout);
    field.__sendToInternals__highlightTimeout = setTimeout(function() {
      SendToInternalsHelper.updateExternalHighlight(field);
    }, 250);
  }, false);
}, false);

window.__sendToInternals__updateSendCommands = window.updateSendCommands;
window.updateSendCommands = function(aHaveController, ...aArgs) {
  this.__sendToInternals__updateSendCommands(aHaveController, ...aArgs);
  if (aHaveController)
    goUpdateCommand('cmd_sendToInternals');
  else
    goUpdateCommand('cmd_sendToInternals', SendToInternalsHelper.isCommandEnabled('cmd_sendToInternals'));
};

window.__sendToInternals__MessageComposeOfflineStateChanged = window.MessageComposeOfflineStateChanged;
window.MessageComposeOfflineStateChanged = function(aGoingOffline, ...aArgs) {
  this.__sendToInternals__MessageComposeOfflineStateChanged(aGoingOffline, ...aArgs);

  var button = document.getElementById('button-sendToInternals');
  if (aGoingOffline) {
    if (button) {
      button.label = button.getAttribute('later_label');
      button.setAttribute('tooltiptext', button.getAttribute('later_tooltiptext'))
    }
  }
  else {
    if (button) {
      button.label = button.getAttribute('now_label');
      button.setAttribute('tooltiptext', button.getAttribute('now_tooltiptext'))
    }
  }
};

})();
<commit_msg>Highlight fields for external address immediately<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
(function() {

var Cc = Components.classes;
var Ci = Components.interfaces;
var Cu = Components.utils;

var MimeHeaderParser = Cc['@mozilla.org/messenger/headerparser;1']
                         .getService(Ci.nsIMsgHeaderParser);

var { Services } = Cu.import('resource://gre/modules/Services.jsm');

var BASE = 'extensions.send-to-internals@clear-code.com.';

var SendToInternalsHelper = {
  get bundle() {
    return document.getElementById('sendToInternalsBundle');
  },

  get internalDomains() {
    var internalDomains = Services.prefs.getComplexValue(BASE + 'domains', Ci.nsISupportsString).data;
    return internalDomains
             .split(/[,\|\s]+/)
             .map(function(aDomain) {
               return aDomain.trim();
             })
             .filter(function(aDomain) {
               return aDomain;
             });
  },

  get internalMatcher() {
    var expression = this.internalDomains.map(function(aDomain) {
          return '@' + aDomain.replace(/^@^/, '').replace(/\./g, '\\.').replace(/\+/g, '\\+');
        }).join('|')
    return new RegExp(expression);
  },

  checkInternals : function()
  {
    var internalDomains = this.internalDomains;
    var externals = this.getAllRecipients().filter(function(aAddress) {
      var domain = aAddress.address.split('@')[1];
      return internalDomains.indexOf(domain) < 0;
    }, this);

    if (externals.length !== 0) {
      this.highlightExternals(externals);
      Services.prompt.alert(
        window,
        this.bundle.getString('alert.haveExternals.title'),
        this.bundle.getFormattedString('alert.haveExternals.text', externals.map(function(aAddress) {
          return aAddress.address;
        }))
      );
      return false;
    }

    return true;
  },

  highlightExternals : function(aExternalAddresses)
  {
    var addressFields = document.querySelectorAll('.textbox-addressingWidget');
    Array.forEach(addressFields, this.updateExternalHighlight, this);
  },

  HIGHLIGHT : 'data-send-to-internals-external-address',

  updateExternalHighlight : function(aField)
  {
    var matcher = this.internalMatcher;
    if (aField.value.trim() && (!matcher || !matcher.test(aField.value)))
      aField.setAttribute(this.HIGHLIGHT, true);
    else
      aField.removeAttribute(this.HIGHLIGHT);
  },

  getAllRecipients : function()
  {
    var msgCompFields = gMsgCompose.compFields;
    Recipients2CompFields(msgCompFields);
    gMsgCompose.expandMailingLists();
    return this.splitRecipients(msgCompFields.to, 'To')
    		.concat(this.splitRecipients(msgCompFields.cc, 'Cc'))
            .concat(this.splitRecipients(msgCompFields.bcc, 'Bcc'));
  },

  splitRecipients : function(aAddressesSource, aType)
  {
    var addresses = {};
    var names = {};
    var fullNames = {};
    var numAddresses = MimeHeaderParser.parseHeadersWithArray(
                         aAddressesSource, addresses, names, fullNames);
    var recipients = [];
    for (let i = 0; i < numAddresses; i++) {
      let address = addresses.value[i];
      let domain = address.split('@')[1];
      recipients.push({
        address:  address,
        name:     names.value[i],
        fullName: fullNames.value[i],
        type:     aType
      });
    }
    return recipients;
  },

  // command controller
  supportsCommand : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
      case 'cmd_sendToInternalsNow':
      case 'cmd_sendToInternalsLater':
        return true;

      default:
        return false;
    }
  },
  isCommandEnabled : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
        return defaultController.commands.cmd_sendButton.isEnabled();

      case 'cmd_sendToInternalsNow':
        return defaultController.commands.cmd_sendNow.isEnabled();

      case 'cmd_sendToInternalsLater':
        return defaultController.commands.cmd_sendLater.isEnabled();

      default:
        return false;
    }
  },
  doCommand : function(aCommand)
  {
    switch (aCommand)
    {
      case 'cmd_sendToInternals':
        if (this.checkInternals())
          goDoCommand('cmd_sendButton');
        return;

      case 'cmd_sendToInternalsNow':
        if (this.checkInternals())
          goDoCommand('cmd_sendNow');
        return;

      case 'cmd_sendToInternalsLater':
        if (this.checkInternals())
          goDoCommand('cmd_sendLater');
        return;

      default:
        return false;
    }
  },
  onEvent : function(aEvent)
  {
  }
};
window.SendToInternalsHelper = SendToInternalsHelper;

window.addEventListener('DOMContentLoaded', function SendToInternalsOnLoad(aEvent) {
  window.removeEventListener(aEvent.type, SendToInternalsOnLoad, false);

  top.controllers.appendController(SendToInternalsHelper);

  var toolbar = document.getElementById('composeToolbar2');
  var defaultSet = toolbar.getAttribute('defaultset');
  var currentSet = toolbar.getAttribute('currentset');

  defaultSet = (defaultSet ? (defaultSet + ',') : '' ) + 'spring,button-sendToInternals';
  toolbar.setAttribute('defaultset', defaultSet);
  if (!Services.prefs.getBoolPref(BASE + 'initialized')) {
    Services.prefs.setBoolPref(BASE + 'initialized', true);
    if (currentSet) {
      currentSet = currentSet + ',spring,button-sendToInternals';
      toolbar.setAttribute('currentset', currentSet);
    }
  }

  window.addEventListener('input', function SendToInternalsOnInput(aEvent) {
    var field = aEvent.target;
    if (field.__sendToInternals__highlightTimeout)
      clearTimeout(field.__sendToInternals__highlightTimeout);
    field.__sendToInternals__highlightTimeout = setTimeout(function() {
      SendToInternalsHelper.updateExternalHighlight(field);
    }, 250);
  }, false);
}, false);

window.__sendToInternals__updateSendCommands = window.updateSendCommands;
window.updateSendCommands = function(aHaveController, ...aArgs) {
  this.__sendToInternals__updateSendCommands(aHaveController, ...aArgs);
  if (aHaveController)
    goUpdateCommand('cmd_sendToInternals');
  else
    goUpdateCommand('cmd_sendToInternals', SendToInternalsHelper.isCommandEnabled('cmd_sendToInternals'));
};

window.__sendToInternals__MessageComposeOfflineStateChanged = window.MessageComposeOfflineStateChanged;
window.MessageComposeOfflineStateChanged = function(aGoingOffline, ...aArgs) {
  this.__sendToInternals__MessageComposeOfflineStateChanged(aGoingOffline, ...aArgs);

  var button = document.getElementById('button-sendToInternals');
  if (aGoingOffline) {
    if (button) {
      button.label = button.getAttribute('later_label');
      button.setAttribute('tooltiptext', button.getAttribute('later_tooltiptext'))
    }
  }
  else {
    if (button) {
      button.label = button.getAttribute('now_label');
      button.setAttribute('tooltiptext', button.getAttribute('now_tooltiptext'))
    }
  }
};

})();
<|endoftext|>


<commit_before>apos.define('apostrophe-rich-text-widgets-editor', {

  afterConstruct: function(self) {
    return self.start();
  },

  construct: function(self, options) {
    self.options = options;
    self.$widget = options.$widget;

    self.start = function() {

      // Areas are interested because they want to stop
      // other editors in the same area first

      if (self.started) {
        return;
      }

      self.$widget.trigger('aposRichTextStarting');

      self.$richText = self.$widget.find('[data-rich-text]:first');
      self.id = self.$richText.attr('id');
      if (!self.id) {
        // Must have one for ckeditor
        self.id = apos.utils.generateId();
        self.$richText.attr('id', self.id);
      }
      self.$richText.attr('contenteditable', 'true');

      // Support for ckeditor4 styles
      self.styles = self.options.styles || [];

      // Allow both universal A2 and ckeditor-specific controls in the toolbar.
      // Don't worry about widgets, those are presented separately.

      self.toolbar = self.options.toolbar || [];

      if (self.options.defaultElement) {
        self.defaultElement = self.options.defaultElement;
      } else if (self.styles.length) {
        self.defaultElement = self.styles[0].element;
      }

      // This will allow loading of extra plugins for each editor
      var extraPlugins = [ 'split' ];
      // Additional standard plugins can be configured
      // simply by name, third-party plugins need an
      // object with name and path properties
      _.each(options.plugins, function(plugin) {
        if (plugin.path) {
          // Make sure we don't have it already due to
          // another instance
          var plugin = CKEDITOR.plugins.get(plugin.name) || plugin;
          if (plugin !== null) {
            CKEDITOR.plugins.addExternal(plugin.name, plugin.path);
          }
        }
        extraPlugins.push(plugin.name || plugin);
      });
      extraPlugins = extraPlugins.join(',');

      self.config = {
        extraPlugins: extraPlugins,
        toolbar: [ self.toolbar ],
        stylesSet: self.styles,
        on: {
          // TODO these event handlers should check whether the ckeditor ckeditorInstance
          // really belongs to apostrophe and play nice if not
          pluginsLoaded: function(evt) {
            var cmd = evt.editor.getCommand('table');
            // Don't allow table elements, properties and styles that
            // complicate responsive design
            cmd.allowedContent = 'table tr th td';
          },
          ckeditorInstanceReady: function(ck) {
            ck.editor.a2Area = self;
            ck.editor.$a2Item = self.$richText.closest('[data-apos-widget]');
            ck.editor.removeMenuItem('tablecellproperties');
          }
        }
      };

      if (!self.toolbar.length) {
        self.config.removePlugins = 'toolbar';
      }

      self.beforeCkeditorInline();

      self.ckeditorInstance = CKEDITOR.inline(self.id, self.config);

      self.focus = false;

      self.ckeditorInstance.on('focus', function() {
        self.focus = true;
        self.setActive(true);
      });

      self.ckeditorInstance.on('blur', function() {
        self.focus = false;
        self.setActive(false);
      });

      // Why is this necessary? Without it we don't get focus. If we don't use a timeout
      // focus is stolen back. As it is we still lose our place in the text. ):
      setTimeout(function() {
        // This should not be necessary, but without the   we are unable to
        // focus on an "empty" rich text after first clicking away an then clicking back.
        // And without the call to focus() people have to double click for no
        // apparent reason
        if (self.$richText.html() === "" || self.$richText.html() === ' ') {
          var emptyState = '<' + (self.defaultElement || 'div') + '> </' + (self.defaultElement || 'div') + '>';
          self.$richText.html(emptyState);
        }
        self.ckeditorInstance.focus();
        self.$richText.data('aposRichTextState', 'started');
        self.$widget.trigger('aposRichTextStarted');
      }, 250);

      self.setActive(true);
      self.started = true;

    };

    self.stop = function() {

      // make sure there is a blur event before
      // the destruction takes place
      var data = self.ckeditorInstance.getData();
      self.ckeditorInstance.destroy();
      self.$richText.removeAttr('contenteditable');
      self.$richText.html(data);
      self.$richText.data('aposRichTextState', undefined);
      self.$widget.trigger('aposRichTextStopped');
      self.started = false;
      self.setActive(false);
    };

    self.setActive = function(state) {
      self.$widget.trigger(state ? 'aposRichTextActive' : 'aposRichTextInactive');
      return self.$widget.toggleClass('apos-active', state);
    };

    self.beforeCkeditorInline = function() {
    };

  }
});
<commit_msg>In apostrophe-rich-text-widgets, initialize CKEditor on instanceReady<commit_after>apos.define('apostrophe-rich-text-widgets-editor', {

  afterConstruct: function(self) {
    return self.start();
  },

  construct: function(self, options) {
    self.options = options;
    self.$widget = options.$widget;

    self.start = function() {

      // Areas are interested because they want to stop
      // other editors in the same area first

      if (self.started) {
        return;
      }

      self.$widget.trigger('aposRichTextStarting');

      self.$richText = self.$widget.find('[data-rich-text]:first');
      self.id = self.$richText.attr('id');
      if (!self.id) {
        // Must have one for ckeditor
        self.id = apos.utils.generateId();
        self.$richText.attr('id', self.id);
      }
      self.$richText.attr('contenteditable', 'true');

      // Support for ckeditor4 styles
      self.styles = self.options.styles || [];

      // Allow both universal A2 and ckeditor-specific controls in the toolbar.
      // Don't worry about widgets, those are presented separately.

      self.toolbar = self.options.toolbar || [];

      if (self.options.defaultElement) {
        self.defaultElement = self.options.defaultElement;
      } else if (self.styles.length) {
        self.defaultElement = self.styles[0].element;
      }

      // This will allow loading of extra plugins for each editor
      var extraPlugins = [ 'split' ];
      // Additional standard plugins can be configured
      // simply by name, third-party plugins need an
      // object with name and path properties
      _.each(options.plugins, function(plugin) {
        if (plugin.path) {
          // Make sure we don't have it already due to
          // another instance
          var plugin = CKEDITOR.plugins.get(plugin.name) || plugin;
          if (plugin !== null) {
            CKEDITOR.plugins.addExternal(plugin.name, plugin.path);
          }
        }
        extraPlugins.push(plugin.name || plugin);
      });
      extraPlugins = extraPlugins.join(',');

      self.config = {
        extraPlugins: extraPlugins,
        toolbar: [ self.toolbar ],
        stylesSet: self.styles,
        on: {
          // TODO these event handlers should check whether the ckeditor ckeditorInstance
          // really belongs to apostrophe and play nice if not
          pluginsLoaded: function(evt) {
            var cmd = evt.editor.getCommand('table');
            // Don't allow table elements, properties and styles that
            // complicate responsive design
            cmd.allowedContent = 'table tr th td';
          },
          ckeditorInstanceReady: function(ck) {
            ck.editor.a2Area = self;
            ck.editor.$a2Item = self.$richText.closest('[data-apos-widget]');
            ck.editor.removeMenuItem('tablecellproperties');
          }
        }
      };

      if (!self.toolbar.length) {
        self.config.removePlugins = 'toolbar';
      }

      self.beforeCkeditorInline();

      self.ckeditorInstance = CKEDITOR.inline(self.id, self.config);

      self.focus = false;

      self.ckeditorInstance.on('focus', function() {
        self.focus = true;
        self.setActive(true);
      });

      self.ckeditorInstance.on('blur', function() {
        self.focus = false;
        self.setActive(false);
      });

      self.ckeditorInstance.on('instanceReady', function(event) {
        // This should not be necessary, but without the   we are unable to
        // focus on an "empty" rich text after first clicking away an then clicking back.
        // And without the call to focus() people have to double click for no
        // apparent reason
        if (self.$richText.html() === "" || self.$richText.html() === ' ') {
          var emptyState = '<' + (self.defaultElement || 'div') + '> </' + (self.defaultElement || 'div') + '>';
          self.$richText.html(emptyState);
        }
        self.ckeditorInstance.focus();
        self.$richText.data('aposRichTextState', 'started');
        self.$widget.trigger('aposRichTextStarted');
      });

      self.setActive(true);
      self.started = true;

    };

    self.stop = function() {

      // make sure there is a blur event before
      // the destruction takes place
      var data = self.ckeditorInstance.getData();
      self.ckeditorInstance.destroy();
      self.$richText.removeAttr('contenteditable');
      self.$richText.html(data);
      self.$richText.data('aposRichTextState', undefined);
      self.$widget.trigger('aposRichTextStopped');
      self.started = false;
      self.setActive(false);
    };

    self.setActive = function(state) {
      self.$widget.trigger(state ? 'aposRichTextActive' : 'aposRichTextInactive');
      return self.$widget.toggleClass('apos-active', state);
    };

    self.beforeCkeditorInline = function() {
    };

  }
});
<|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function () {
  var location = document.getElementById("location");
  function showPosition(position) {
      location.innerHTML = "Latitude: " + position.coords.latitude +
      "
Longitude: " + position.coords.longitude;
    initialize(position.coords.latitude, position.coords.longitude);
  };
  function getLocation() {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition);
      } else {
          location.innerHTML = "Geolocation is not supported by this browser.";
      }
  };

  var map;
  function initialize(lat, lng) {
      var mapOptions = {
      zoom: 12,
      center:{lat: lat, lng: lng}
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var marker = new google.maps.Marker({
        position: map.getCenter(),
        draggable: false,
        map: map,
        icon: "http://www.4smileys.com/smileys/food-smileys/hungry_boy.gif",
        animation: google.maps.Animation.DROP
      });
    var geocoder = new google.maps.Geocoder();
    var showTrucks = document.getElementById("showTrucks");
    showTrucks.addEventListener('click', function(e){
      e.preventDefault();
      geocodeAddress(geocoder, map);
    });
  }
  function geocodeAddress(geocoder, resultsMap) {
          for (i = 0; i < objArr.length; i++) {
            var address = JSON.stringify(objArr[i].address)
            geocoder.geocode({'address': address}, function(results, status) {
              if (status === google.maps.GeocoderStatus.OK) {
                console.log(results[0].formatted_address);
                resultsMap.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                  map: resultsMap,
                  position: results[0].geometry.location,
                  icon: "http://howtostartafoodtruckbusinessinindia.com/wp-content/uploads/foodtruck-icon-web.png",
                  draggable: false,
                  map: map,
                });
              };
            });
          }; // for
        }; // geocode

  getLocation();
});

<commit_msg>change food truck icon<commit_after>document.addEventListener('DOMContentLoaded', function () {
  var location = document.getElementById("location");
  function showPosition(position) {
      location.innerHTML = "Latitude: " + position.coords.latitude +
      "
Longitude: " + position.coords.longitude;
    initialize(position.coords.latitude, position.coords.longitude);
  };
  function getLocation() {
      if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(showPosition);
      } else {
          location.innerHTML = "Geolocation is not supported by this browser.";
      }
  };

  var map;
  function initialize(lat, lng) {
      var mapOptions = {
      zoom: 12,
      center:{lat: lat, lng: lng}
    };
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    var marker = new google.maps.Marker({
        position: map.getCenter(),
        draggable: false,
        map: map,
        icon: "http://www.4smileys.com/smileys/food-smileys/hungry_boy.gif",
        animation: google.maps.Animation.DROP
      });
    var geocoder = new google.maps.Geocoder();
    var showTrucks = document.getElementById("showTrucks");
    showTrucks.addEventListener('click', function(e){
      e.preventDefault();
      geocodeAddress(geocoder, map);
    });
  }
  function geocodeAddress(geocoder, resultsMap) {
          for (i = 0; i < objArr.length; i++) {
            var address = JSON.stringify(objArr[i].address)
            geocoder.geocode({'address': address}, function(results, status) {
              if (status === google.maps.GeocoderStatus.OK) {
                console.log(results[0].formatted_address);
                resultsMap.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                  map: resultsMap,
                  position: results[0].geometry.location,
                  icon: "http://www.localsconnected.com/wp-content/uploads/2014/11/Food-Truck-Icon.png",
                  draggable: false,
                  map: map,
                });
              };
            });
          }; // for
        }; // geocode

  getLocation();
});

<|endoftext|>


<commit_before>const { spawn } = require('child_process');
const path = require('path');

module.exports = function TCC(m)
{
    const ngenPath = path.join(__dirname, 'ngen.exe');
    const tccPath = path.join(__dirname, 'TCC.exe');
    const modsPath = path.join(__dirname, 'TCC.Modules.dll');

    if(!m.manager.isLoaded("tcc-chat-link"))
    {
        m.log("TCC chat link is not installed. Advanced functionality won't be available.");
    }

    m.log('Starting ngen...');

    // Cringe.
    ngen(modsPath).on('exit', () => {
        ngen(tccPath).on('exit', () => {
            run();
        });
    });

    function run(){
        m.log('Starting TCC...');
        const tcc = spawn(tccPath, ['--toolbox'], { stdio: 'ignore' });
        tcc.on('exit', () => m.log('TCC exited.'));
    }

    function ngen(assembly)
    {
        return spawn(ngenPath, ['install', assembly], {stdio : 'ignore'});
    }
}<commit_msg>TCC module isLoaded -> isInstalled<commit_after>const { spawn } = require('child_process');
const path = require('path');

module.exports = function TCC(m)
{
    const ngenPath = path.join(__dirname, 'ngen.exe');
    const tccPath = path.join(__dirname, 'TCC.exe');
    const modsPath = path.join(__dirname, 'TCC.Modules.dll');

    if(!m.manager.isInstalled("tcc-chat-link"))
    {
        m.log("TCC chat link is not installed. Advanced functionality won't be available.");
    }

    m.log('Starting ngen...');

    // Cringe.
    ngen(modsPath).on('exit', () => {
        ngen(tccPath).on('exit', () => {
            run();
        });
    });

    function run(){
        m.log('Starting TCC...');
        const tcc = spawn(tccPath, ['--toolbox'], { stdio: 'ignore' });
        tcc.on('exit', () => m.log('TCC exited.'));
    }

    function ngen(assembly)
    {
        return spawn(ngenPath, ['install', assembly], {stdio : 'ignore'});
    }
}<|endoftext|>


<commit_before>/** The minplayer namespace. */
var minplayer = minplayer || {};

/**
 * @constructor
 * @extends minplayer.display
 * @class The play loader base class, which is used to control the busy
 * cursor, big play button, and the opaque background which shows when the
 * player is paused.
 *
 * @param {object} context The jQuery context.
 * @param {object} options This components options.
 */
minplayer.playLoader = function(context, options) {

  // Define the flags that control the busy cursor.
  this.busy = new minplayer.flags();

  // Define the flags that control the big play button.
  this.bigPlay = new minplayer.flags();

  // Define the flags the control the preview.
  this.previewFlag = new minplayer.flags();

  /** The preview image. */
  this.preview = null;

  /** If the playLoader is enabled. */
  this.enabled = true;

  // Derive from display
  minplayer.display.call(this, 'playLoader', context, options);
};

/** Derive from minplayer.display. */
minplayer.playLoader.prototype = new minplayer.display();

/** Reset the constructor. */
minplayer.playLoader.prototype.constructor = minplayer.playLoader;

/**
 * The constructor.
 */
minplayer.playLoader.prototype.construct = function() {

  // Call the media display constructor.
  minplayer.display.prototype.construct.call(this);

  // Set the plugin name within the options.
  this.options.pluginName = 'playLoader';

  // Get the media plugin.
  this.initialize();

  // We are now ready.
  this.ready();
};

/**
 * Initialize the playLoader.
 */
minplayer.playLoader.prototype.initialize = function() {

  // Get the media plugin.
  this.get('media', function(media) {

    // Only bind if this player does not have its own play loader.
    if (!media.hasPlayLoader(this.options.preview)) {

      // Enable the playLoader.
      this.enabled = true;

      // Get the poster image.
      if (!this.options.preview) {
        this.options.preview = media.elements.media.attr('poster');
      }

      // Reset the media's poster image.
      media.elements.media.attr('poster', '');

      // Load the preview image.
      this.loadPreview();

      // Trigger a play event when someone clicks on the controller.
      if (this.elements.bigPlay) {
        minplayer.click(this.elements.bigPlay.unbind(), function(event) {
          event.preventDefault();
          jQuery(this).hide();
          media.play();
        });
      }

      // Bind to the player events to control the play loader.
      media.ubind(this.uuid + ':loadstart', (function(playLoader) {
        return function(event) {
          playLoader.busy.setFlag('media', true);
          playLoader.bigPlay.setFlag('media', true);
          playLoader.previewFlag.setFlag('media', true);
          playLoader.checkVisibility();
        };
      })(this));
      media.ubind(this.uuid + ':waiting', (function(playLoader) {
        return function(event) {
          playLoader.busy.setFlag('media', true);
          playLoader.checkVisibility();
        };
      })(this));
      media.ubind(this.uuid + ':loadeddata', (function(playLoader) {
        return function(event) {
          playLoader.busy.setFlag('media', false);
          playLoader.checkVisibility();
        };
      })(this));
      media.ubind(this.uuid + ':playing', (function(playLoader) {
        return function(event) {
          playLoader.busy.setFlag('media', false);
          playLoader.bigPlay.setFlag('media', false);
          if (media.mediaFile.type !== 'audio') {
            playLoader.previewFlag.setFlag('media', false);
          }
          playLoader.checkVisibility();
        };
      })(this));
      media.ubind(this.uuid + ':pause', (function(playLoader) {
        return function(event) {
          playLoader.bigPlay.setFlag('media', true);
          playLoader.checkVisibility();
        };
      })(this));
    }
    else {

      // Hide the display.
      this.enabled = false;
      this.hide(this.elements.busy);
      this.hide(this.elements.bigPlay);
      this.hide(this.elements.preview);
      this.hide();
    }
  });
};

/**
 * Loads the preview image.
 *
 * @return {boolean} Returns true if an image was loaded, false otherwise.
 */
minplayer.playLoader.prototype.loadPreview = function() {

  // Ignore if disabled.
  if (!this.enabled) {
    return;
  }

  // If the preview element exists.
  if (this.elements.preview) {

    // If there is a preview to show...
    if (this.options.preview) {

      // Say that this has a preview.
      this.elements.preview.addClass('has-preview').show();

      // Create a new preview image.
      this.preview = new minplayer.image(this.elements.preview, this.options);

      // Create the image.
      this.preview.load(this.options.preview);
      return true;
    }
    else {

      // Hide the preview.
      this.elements.preview.hide();
    }
  }

  return false;
};

/**
 * Hide or show certain elements based on the state of the busy and big play
 * button.
 */
minplayer.playLoader.prototype.checkVisibility = function() {

  // Ignore if disabled.
  if (!this.enabled) {
    return;
  }

  // Hide or show the busy cursor based on the flags.
  if (this.busy.flag) {
    this.elements.busy.show();
  }
  else {
    this.elements.busy.hide();
  }

  // Hide or show the big play button based on the flags.
  if (this.bigPlay.flag) {
    this.elements.bigPlay.show();
  }
  else {
    this.elements.bigPlay.hide();
  }

  if (this.previewFlag.flag) {
    this.elements.preview.show();
  }
  else {
    this.elements.preview.hide();
  }

  // Show the control either flag is set.
  if (this.bigPlay.flag || this.busy.flag || this.previewFlag.flag) {
    this.display.show();
  }

  // Hide the whole control if both flags are 0.
  if (!this.bigPlay.flag && !this.busy.flag && !this.previewFlag.flag) {
    this.display.hide();
  }
};
<commit_msg>Fixing the playloader to not load a preview that is already loaded.<commit_after>/** The minplayer namespace. */
var minplayer = minplayer || {};

/**
 * @constructor
 * @extends minplayer.display
 * @class The play loader base class, which is used to control the busy
 * cursor, big play button, and the opaque background which shows when the
 * player is paused.
 *
 * @param {object} context The jQuery context.
 * @param {object} options This components options.
 */
minplayer.playLoader = function(context, options) {

  // Define the flags that control the busy cursor.
  this.busy = new minplayer.flags();

  // Define the flags that control the big play button.
  this.bigPlay = new minplayer.flags();

  // Define the flags the control the preview.
  this.previewFlag = new minplayer.flags();

  /** The preview image. */
  this.preview = null;

  /** If the playLoader is enabled. */
  this.enabled = true;

  // Derive from display
  minplayer.display.call(this, 'playLoader', context, options);
};

/** Derive from minplayer.display. */
minplayer.playLoader.prototype = new minplayer.display();

/** Reset the constructor. */
minplayer.playLoader.prototype.constructor = minplayer.playLoader;

/**
 * The constructor.
 */
minplayer.playLoader.prototype.construct = function() {

  // Call the media display constructor.
  minplayer.display.prototype.construct.call(this);

  // Set the plugin name within the options.
  this.options.pluginName = 'playLoader';

  // Get the media plugin.
  this.initialize();

  // We are now ready.
  this.ready();
};

/**
 * Initialize the playLoader.
 */
minplayer.playLoader.prototype.initialize = function() {

  // Get the media plugin.
  this.get('media', function(media) {

    // Only bind if this player does not have its own play loader.
    if (!media.hasPlayLoader(this.options.preview)) {

      // Enable the playLoader.
      this.enabled = true;

      // Get the poster image.
      if (!this.options.preview) {
        this.options.preview = media.elements.media.attr('poster');
      }

      // Determine if we should load the image.
      var shouldLoad = true;
      if (this.preview && this.preview.loader) {
        shouldLoad = (this.preview.loader.src !== this.options.preview);
      }

      // Only load the image if it is different.
      if (shouldLoad) {
        // Reset the media's poster image.
        media.elements.media.attr('poster', '');

        // Load the preview image.
        this.loadPreview();
      }

      // Trigger a play event when someone clicks on the controller.
      if (this.elements.bigPlay) {
        minplayer.click(this.elements.bigPlay.unbind(), function(event) {
          event.preventDefault();
          jQuery(this).hide();
          media.play();
        });
      }

      // Bind to the player events to control the play loader.
      media.ubind(this.uuid + ':loadstart', (function(playLoader) {
        return function(event) {
          playLoader.busy.setFlag('media', true);
          playLoader.bigPlay.setFlag('media', true);
          playLoader.previewFlag.setFlag('media', true);
          playLoader.checkVisibility();
        };
      })(this));
      media.ubind(this.uuid + ':waiting', (function(playLoader) {
        return function(event) {
          playLoader.busy.setFlag('media', true);
          playLoader.checkVisibility();
        };
      })(this));
      media.ubind(this.uuid + ':loadeddata', (function(playLoader) {
        return function(event) {
          playLoader.busy.setFlag('media', false);
          playLoader.checkVisibility();
        };
      })(this));
      media.ubind(this.uuid + ':playing', (function(playLoader) {
        return function(event) {
          playLoader.busy.setFlag('media', false);
          playLoader.bigPlay.setFlag('media', false);
          if (media.mediaFile.type !== 'audio') {
            playLoader.previewFlag.setFlag('media', false);
          }
          playLoader.checkVisibility();
        };
      })(this));
      media.ubind(this.uuid + ':pause', (function(playLoader) {
        return function(event) {
          playLoader.bigPlay.setFlag('media', true);
          playLoader.checkVisibility();
        };
      })(this));
    }
    else {

      // Hide the display.
      this.enabled = false;
      this.hide(this.elements.busy);
      this.hide(this.elements.bigPlay);
      this.hide(this.elements.preview);
      this.hide();
    }
  });
};

/**
 * Loads the preview image.
 *
 * @return {boolean} Returns true if an image was loaded, false otherwise.
 */
minplayer.playLoader.prototype.loadPreview = function() {

  // Ignore if disabled.
  if (!this.enabled) {
    return;
  }

  // If the preview element exists.
  if (this.elements.preview) {

    // If there is a preview to show...
    if (this.options.preview) {

      // Say that this has a preview.
      this.elements.preview.addClass('has-preview').show();

      // Create a new preview image.
      this.preview = new minplayer.image(this.elements.preview, this.options);

      // Create the image.
      this.preview.load(this.options.preview);
      return true;
    }
    else {

      // Hide the preview.
      this.elements.preview.hide();
    }
  }

  return false;
};

/**
 * Hide or show certain elements based on the state of the busy and big play
 * button.
 */
minplayer.playLoader.prototype.checkVisibility = function() {

  // Ignore if disabled.
  if (!this.enabled) {
    return;
  }

  // Hide or show the busy cursor based on the flags.
  if (this.busy.flag) {
    this.elements.busy.show();
  }
  else {
    this.elements.busy.hide();
  }

  // Hide or show the big play button based on the flags.
  if (this.bigPlay.flag) {
    this.elements.bigPlay.show();
  }
  else {
    this.elements.bigPlay.hide();
  }

  if (this.previewFlag.flag) {
    this.elements.preview.show();
  }
  else {
    this.elements.preview.hide();
  }

  // Show the control either flag is set.
  if (this.bigPlay.flag || this.busy.flag || this.previewFlag.flag) {
    this.display.show();
  }

  // Hide the whole control if both flags are 0.
  if (!this.bigPlay.flag && !this.busy.flag && !this.previewFlag.flag) {
    this.display.hide();
  }
};
<|endoftext|>


<commit_before>const { div, h1, ul, li, a, hr } = require('../../modules/tags')
const icon = require('../components/icon.tmpl')
const spinner = require('../components/spinner.tmpl')
const previewSubjectHead = require('../components/preview_subject_head.tmpl')

const subjectResult = subject =>
    [
        a(  // TODO-2 if already in subjects, don't show this button
            {
                id: subject.entity_id,
                href: '#',
                className: 'add-to-my-subjects',
            },
            icon('create'),
            ' Add to My Subjects'
        ),
        div(
            { className: 'recommended-subjects__right' },
            previewSubjectHead({ name: subject.name, body: subject.body }),
            a(
                {
                    href: `/subjects/${subject.entity_id}/tree`,
                    className: 'recommended-subjects__view-units',
                },
                icon('unit'),
                ' View Units'
            )
        ),
    ]

module.exports = (data) => {
    if (!data.recommendedSubjects.length) { return spinner() }
    return div(
        { id: 'recommended-subjects', className: 'page' },
        h1('Recommended Subjects'),
        ul(
            data.recommendedSubjects.map(subject => li(subjectResult(subject)))
        ),
        hr(),
        a({ href: '/search?mode=as_learner' }, icon('search'), ' Search Subjects')
    )
}
<commit_msg>How to add recommended subject (again... for now...)<commit_after>const { div, h1, p, ul, li, a, hr } = require('../../modules/tags')
const icon = require('../components/icon.tmpl')
const spinner = require('../components/spinner.tmpl')
const previewSubjectHead = require('../components/preview_subject_head.tmpl')

const subjectResult = subject =>
    [
        a(  // TODO-2 if already in subjects, don't show this button
            {
                id: subject.entity_id,
                href: '#',
                className: 'add-to-my-subjects',
            },
            icon('create'),
            ' Add to My Subjects'
        ),
        div(
            { className: 'recommended-subjects__right' },
            previewSubjectHead({ name: subject.name, body: subject.body }),
            a(
                {
                    href: `/subjects/${subject.entity_id}/tree`,
                    className: 'recommended-subjects__view-units',
                },
                icon('unit'),
                ' View Units'
            )
        ),
    ]

module.exports = (data) => {
    if (!data.recommendedSubjects.length) { return spinner() }
    return div(
        { id: 'recommended-subjects', className: 'page' },
        h1('Recommended Subjects'),
        p('Want to add a subject here? Email <support@sagefy.org> and let us know!'),
        ul(
            data.recommendedSubjects.map(subject => li(subjectResult(subject)))
        ),
        hr(),
        a({ href: '/search?mode=as_learner' }, icon('search'), ' Search Subjects')
    )
}
<|endoftext|>


<commit_before>
function initThemeChooser(settings) {
	var isInitialized = false;
	var $currentStylesheet = $();
	var $loading = $('#loading');
	var $systemSelect = $('#theme-system-selector select')
		.on('change', function() {
			setThemeSystem(this.value);
		});

	setThemeSystem($systemSelect.val());

	function setThemeSystem(themeSystem) {
		var $allSelectWraps = $('.selector[data-theme-system]').hide();
		var $selectWrap = $allSelectWraps.filter('[data-theme-system="' + themeSystem +'"]').show();
		var $select = $selectWrap.find('select')
			.off('change') // avoid duplicate handlers :(
			.on('change', function() {
				setTheme(themeSystem, this.value);
			});

		setTheme(themeSystem, $select.val());
	}

	function setTheme(themeSystem, themeName) {
		var stylesheetUrl = generateStylesheetUrl(themeSystem, themeName);
		var $stylesheet;

		function done() {
			if (!isInitialized) {
				isInitialized = true;
				settings.init(themeSystem);
			}
			else {
				settings.change(themeSystem);
			}

			showCredits(themeSystem, themeName);
		}

		if (stylesheetUrl) {
			$stylesheet = $('<link rel="stylesheet" type="text/css" href="' + stylesheetUrl + '"/>').appendTo('head');
			$loading.show();

			whenStylesheetLoaded($stylesheet[0], function() {
				$currentStylesheet.remove();
				$currentStylesheet = $stylesheet;
				$loading.hide();
				done();
			});
		} else {
			$currentStylesheet.remove();
			$currentStylesheet = $();
			done();
		}
	}

	function generateStylesheetUrl(themeSystem, themeName) {
		if (themeSystem === 'jquery-ui') {
			return 'https://code.jquery.com/ui/1.12.1/themes/' + themeName + '/jquery-ui.css';
		}
		else if (themeSystem === 'bootstrap3') {
			if (themeName) {
				return 'https://bootswatch.com/' + themeName + '/bootstrap.min.css';
			}
			else { // the default bootstrap theme
				return 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css';
			}
		}
	}

	function showCredits(themeSystem, themeName) {
		var creditId;

		if (themeSystem === 'jquery-ui') {
			creditId = 'jquery-ui';
		}
		else if (themeSystem === 'bootstrap3') {
			if (themeName) {
				creditId = 'bootstrap-custom';
			}
			else {
				creditId = 'bootstrap-standard';
			}
		}

		$('.credits').hide()
			.filter('[data-credit-id="' + creditId + '"]').show();
	}

	function whenStylesheetLoaded(linkNode, callback) {
		var isReady = false;

		function ready() {
			if (!isReady) { // avoid double-call
				isReady = true;
				callback();
			}
		}

		linkNode.onload = ready; // does not work cross-browser
		setTimeout(ready, 2000); // max wait. also handles browsers that don't support onload
	}
}
<commit_msg>fix bootswatch stylesheet urls for theme chooser. fixes #3916<commit_after>
function initThemeChooser(settings) {
	var isInitialized = false;
	var $currentStylesheet = $();
	var $loading = $('#loading');
	var $systemSelect = $('#theme-system-selector select')
		.on('change', function() {
			setThemeSystem(this.value);
		});

	setThemeSystem($systemSelect.val());

	function setThemeSystem(themeSystem) {
		var $allSelectWraps = $('.selector[data-theme-system]').hide();
		var $selectWrap = $allSelectWraps.filter('[data-theme-system="' + themeSystem +'"]').show();
		var $select = $selectWrap.find('select')
			.off('change') // avoid duplicate handlers :(
			.on('change', function() {
				setTheme(themeSystem, this.value);
			});

		setTheme(themeSystem, $select.val());
	}

	function setTheme(themeSystem, themeName) {
		var stylesheetUrl = generateStylesheetUrl(themeSystem, themeName);
		var $stylesheet;

		function done() {
			if (!isInitialized) {
				isInitialized = true;
				settings.init(themeSystem);
			}
			else {
				settings.change(themeSystem);
			}

			showCredits(themeSystem, themeName);
		}

		if (stylesheetUrl) {
			$stylesheet = $('<link rel="stylesheet" type="text/css" href="' + stylesheetUrl + '"/>').appendTo('head');
			$loading.show();

			whenStylesheetLoaded($stylesheet[0], function() {
				$currentStylesheet.remove();
				$currentStylesheet = $stylesheet;
				$loading.hide();
				done();
			});
		} else {
			$currentStylesheet.remove();
			$currentStylesheet = $();
			done();
		}
	}

	function generateStylesheetUrl(themeSystem, themeName) {
		if (themeSystem === 'jquery-ui') {
			return 'https://code.jquery.com/ui/1.12.1/themes/' + themeName + '/jquery-ui.css';
		}
		else if (themeSystem === 'bootstrap3') {
			if (themeName) {
				return 'https://bootswatch.com/3/' + themeName + '/bootstrap.min.css';
			}
			else { // the default bootstrap theme
				return 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css';
			}
		}
	}

	function showCredits(themeSystem, themeName) {
		var creditId;

		if (themeSystem === 'jquery-ui') {
			creditId = 'jquery-ui';
		}
		else if (themeSystem === 'bootstrap3') {
			if (themeName) {
				creditId = 'bootstrap-custom';
			}
			else {
				creditId = 'bootstrap-standard';
			}
		}

		$('.credits').hide()
			.filter('[data-credit-id="' + creditId + '"]').show();
	}

	function whenStylesheetLoaded(linkNode, callback) {
		var isReady = false;

		function ready() {
			if (!isReady) { // avoid double-call
				isReady = true;
				callback();
			}
		}

		linkNode.onload = ready; // does not work cross-browser
		setTimeout(ready, 2000); // max wait. also handles browsers that don't support onload
	}
}
<|endoftext|>


<commit_before>var hostname = window.location.hostname;
var wsaddr = "wss://".concat(hostname, "/map/wss");
var ws;

var config;
var width = $(window).width();
var height = $(window).height();

var svg;
var zoom;
var g;

// Alert functions
function banner(type, message, delay) {
    $('body').prepend('

<button type="button" class="close" data-dismiss="alert" aria-label="Close"> ×</button>' + message + '

');
    if (delay >= 0) {
        $(".alert").delay(delay).fadeOut("slow", function () { $(this).parent('div').remove(); $(this).remove(); });
    }
}

function error(message) {
    banner("alert-danger", "An error occurred. Please contact Polaris Laboratories. Error: " + message, -1);
}

function warning(message) {
    banner("alert-warning", "Something unexpected occurred. Please contact Polaris Laboratories. Event: " + message, 5000);
}

// Register all onload stuff here
$(document).ready(function() {
    // Add handlers for the buttons
    $('#zoom-reset').click(zoom_reset);
    $('#zoom-in').click(zoom_in);
    $('#zoom-out').click(zoom_out);

    // Initialize all tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Initialize page properties
    zoom = d3.zoom()
        .scaleExtent([1, 8])
        .on("zoom", zoomed);

    svg = d3.select("svg")
        .attr("width", width)
        .attr("height", height)

    g = svg.append("g");

    svg.call(zoom);

    connect();
});

// WebSocket low level stuff. See below these for the message handlers
var functions = {
    'config': setup,
    'raw': raw,
    'rooms': rooms,
};

function connect() {
    try {
        ws = new WebSocket(wsaddr);
    } catch (err) {
        banner("alert-danger", error(err), -1);
    }
    ws.onmessage = ws_handler;
    ws.onerror = ws_error;

    banner("alert-info", "Connected to " + wsaddr, 3000);
}

function ws_error(message) {
    return error(message);
}

function ws_handler(event) {
    var response = JSON.parse(event.data);
    try {
        functions[response.type](response);
    } catch (err) {
        warning("Server sent unknown WebSocket data.");
    }
}

// WebSocket message handlers
function raw(response) {
    console.log(response.data);
    banner("alert-info", response.data, 2000);
}

function drawCircle(x, y, size) {
    console.log('Drawing circle at', x, y, size);
    g.append("circle")
        .attr('class', 'circle')
        .attr("cx", x)
        .attr("cy", y)
        .attr("r", size);
}

function setup(response) {
    config = response;

    // Grab the dimensions from the imsage
    var image = new Image();
    image.src = config.map;

    // Wait for the image to load, or else we get garbage metadata
    image.onload = function() {
        g.append("svg:image")
            .attr("xlink:href", config.map)
            .attr("x", "50%")
            .attr("y", "50%")
            .attr("width", image.width + "px")
            .attr("height", image.height + "px")
            // Disgusting string concatenation
            .attr("transform", "translate(-" + image.width / 2 + ", -" + image.height / 2 + ")")
        // Remove the CSS loading element since the map is technically loaded
        $("link[href='stylesheets/loading.css']").remove();
        $("div.loading").remove();
    }

    g.on('click', function() {
        var coords = d3.mouse(this);
        var point = {
            'type': 'point',
            'data': {
                'name': 'DSA',
                'x': coords[0],
                'y': coords[1]
            }
        };
        ws.send(JSON.stringify(point));
        drawCircle(coords[0], coords[1], 5);
    });
}

function rooms(response) {
    $(".circle").remove();
    for (var room of response.data) {
        drawCircle(room.x, room.y, 5);
    }
}

// User interface stuff
function zoomed () {
    g.attr("transform", d3.event.transform);
}

function zoom_reset() {
    svg.transition()
       .duration(750)
       .call(zoom.transform, d3.zoomIdentity);
}

function zoom_in() {
    svg.transition()
       .duration(750)
       .call(zoom.scaleBy, 2);
}

function zoom_out() {
    svg.transition()
       .duration(750)
       .call(zoom.scaleBy, 0.5);
}
<commit_msg>Fix circle placement on different screen sizes<commit_after>var hostname = window.location.hostname;
var wsaddr = "wss://".concat(hostname, "/map/wss");
var ws;

var config;
var width = $(window).width();
var height = $(window).height();

var svg;
var zoom;
var g;

// Alert functions
function banner(type, message, delay) {
    $('body').prepend('

<button type="button" class="close" data-dismiss="alert" aria-label="Close"> ×</button>' + message + '

');
    if (delay >= 0) {
        $(".alert").delay(delay).fadeOut("slow", function () { $(this).parent('div').remove(); $(this).remove(); });
    }
}

function error(message) {
    banner("alert-danger", "An error occurred. Please contact Polaris Laboratories. Error: " + message, -1);
}

function warning(message) {
    banner("alert-warning", "Something unexpected occurred. Please contact Polaris Laboratories. Event: " + message, 5000);
}

// Register all onload stuff here
$(document).ready(function() {
    // Add handlers for the buttons
    $('#zoom-reset').click(zoom_reset);
    $('#zoom-in').click(zoom_in);
    $('#zoom-out').click(zoom_out);

    // Initialize all tooltips
    $('[data-toggle="tooltip"]').tooltip();

    // Initialize page properties
    zoom = d3.zoom()
        .scaleExtent([1, 8])
        .on("zoom", zoomed);

    svg = d3.select("svg")
        .attr("width", width)
        .attr("height", height)

    g = svg.append("g");

    svg.call(zoom);

    connect();
});

// WebSocket low level stuff. See below these for the message handlers
var functions = {
    'config': setup,
    'raw': raw,
    'rooms': rooms,
};

function connect() {
    try {
        ws = new WebSocket(wsaddr);
    } catch (err) {
        banner("alert-danger", error(err), -1);
    }
    ws.onmessage = ws_handler;
    ws.onerror = ws_error;

    banner("alert-info", "Connected to " + wsaddr, 3000);
}

function ws_error(message) {
    return error(message);
}

function ws_handler(event) {
    var response = JSON.parse(event.data);
    try {
        functions[response.type](response);
    } catch (err) {
        warning("Server sent unknown WebSocket data.");
    }
}

// WebSocket message handlers
function raw(response) {
    console.log(response.data);
    banner("alert-info", response.data, 2000);
}

function drawCircle(x, y, size) {
    console.log('Drawing circle at', x, y, size);
    g.append("circle")
        .attr('class', 'circle')
        .attr("cx", x)
        .attr("cy", y)
        .attr("r", size);
}

function setup(response) {
    config = response;

    // Grab the dimensions from the imsage
    var image = new Image();
    image.src = config.map;

    // Wait for the image to load, or else we get garbage metadata
    image.onload = function() {
        g.append("svg:image")
            .attr("xlink:href", config.map)
            .attr("x", "50%")
            .attr("y", "50%")
            .attr("width", image.width + "px")
            .attr("height", image.height + "px")
            // Disgusting string concatenation
            .attr("transform", "translate(-" + image.width / 2 + ", -" + image.height / 2 + ")")
        // Remove the CSS loading element since the map is technically loaded
        $("link[href='stylesheets/loading.css']").remove();
        $("div.loading").remove();

        g.on('click', function() {
            var coords = d3.mouse(this);
            /*
             * Why do we subtract 0.5 * width and 0.5 * height? Note that the
             * image above has 50% for the x and y attributes, which is
             * necessary to ensure that the image is properly centered in
             * the g element. Thus, the value we get as the mouse click location
             * is off by 0.5 * the dimensions of the screen size. The value
             * we send to the server is this "compensated" value, but when
             * we render the dots, we add the offset for the screen size.
             */
            var x = coords[0] - (0.5 * width);
            var y = coords[1] - (0.5 * height);
            var point = {
                'type': 'point',
                'data': {
                    'name': 'DSA',
                    'x': x,
                    'y': y
                }
            };
            ws.send(JSON.stringify(point));
            drawCircle(x + (0.5 * width), y + (0.5 * height), 5);
        });
    }
}

function rooms(response) {
    $(".circle").remove();
    for (var room of response.data) {
        drawCircle(room.x + (0.5 * width), room.y + (0.5 * height), 5);
    }
}

// User interface stuff
function zoomed () {
    g.attr("transform", d3.event.transform);
}

function zoom_reset() {
    svg.transition()
       .duration(750)
       .call(zoom.transform, d3.zoomIdentity);
}

function zoom_in() {
    svg.transition()
       .duration(750)
       .call(zoom.scaleBy, 2);
}

function zoom_out() {
    svg.transition()
       .duration(750)
       .call(zoom.scaleBy, 0.5);
}
<|endoftext|>


<commit_before><commit_msg>Simplified code to show/save tiles<commit_after><|endoftext|>


<commit_before>// Tools
var urls = require('georap-urls-client');
var ui = require('georap-ui');
var emitter = require('component-emitter');
// Templates
var template = require('./template.ejs');
var statusListTemplate = require('./statusList.ejs');
var typeListTemplate = require('./typeList.ejs');
// Config
var locationStatuses = georap.config.locationStatuses;
var locationTypes = georap.config.locationTypes;
var __ = georap.i18n.__;

module.exports = function (location) {

  // Setup
  var $mount = null;
  var $elems = {};
  var self = this;
  emitter(self);

  this.bind = function ($mountEl) {
    $mount = $mountEl;

    $mount.html(template({
      // List of available statuses
      statusListHtml: statusListTemplate({
        locationStatuses: locationStatuses,
        currentStatus: location.getStatus(),
        __: __,
      }),
      // List of available types
      typeListHtml: typeListTemplate({
        locationTypes: locationTypes,
        currentType: location.getType(),
        toSymbolUrl: urls.locationTypeToSymbolUrl,
      }),
      __: __,
    }));

    $elems.show = $mount.find('.location-statustype-form-show');
    $elems.form = $mount.find('.location-statustype-form');
    $elems.cancel = $mount.find('.location-statustype-form-cancel');
    $elems.progress = $mount.find('.location-statustype-progress');
    $elems.error = $mount.find('.location-statustype-error');
    $elems.statusList = $mount.find('.location-status-list');
    $elems.typeList = $mount.find('.location-type-list');

    // Form cancel
    $elems.cancel.click(function (ev) {
      ev.preventDefault();
      self.emit('cancel');
    });

    var submitStatus = function (newStatus) {
      ui.show($elems.progress);
      ui.hide($elems.form);

      location.setStatus(newStatus, function (err) {
        if ($mount) {
          ui.hide($elems.progress);

          if (err) {
            console.error(err);
            ui.show($elems.error);
            return;
          }
          // Everything ok
        }
      });
    };

    var submitType = function (newType) {
      ui.show($elems.progress);
      ui.hide($elems.form);

      location.setType(newType, function (err) {
        if ($mount) {
          ui.hide($elems.progress);

          if (err) {
            console.error(err);
            ui.show($elems.error);
            return;
          }
          // Everything ok
        }
      });
    };

    // Click on a status button
    $elems.statusList.click(function (ev) {
      ev.preventDefault(); // Avoid page reload.
      var btnValue = ev.target.dataset.status;
      if (typeof btnValue === 'string' && btnValue.length > 0) {
        submitStatus(btnValue);
      }
    });

    // Click on a type button
    $elems.typeList.click(function (ev) {
      ev.preventDefault(); // Avoid page reload.
      var btnValue = ev.target.dataset.type;
      if (typeof btnValue === 'string' && btnValue.length > 0) {
        submitType(btnValue);
      }
    });
  };

  this.unbind = function () {
    if ($mount) {
      $mount = null;
      ui.offAll($elems);
      $elems = {};
    }
  };
};
<commit_msg>remove unused var<commit_after>// Tools
var urls = require('georap-urls-client');
var ui = require('georap-ui');
var emitter = require('component-emitter');
// Templates
var template = require('./template.ejs');
var statusListTemplate = require('./statusList.ejs');
var typeListTemplate = require('./typeList.ejs');
// Config
var locationStatuses = georap.config.locationStatuses;
var locationTypes = georap.config.locationTypes;
var __ = georap.i18n.__;

module.exports = function (location) {

  // Setup
  var $mount = null;
  var $elems = {};
  var self = this;
  emitter(self);

  this.bind = function ($mountEl) {
    $mount = $mountEl;

    $mount.html(template({
      // List of available statuses
      statusListHtml: statusListTemplate({
        locationStatuses: locationStatuses,
        currentStatus: location.getStatus(),
        __: __,
      }),
      // List of available types
      typeListHtml: typeListTemplate({
        locationTypes: locationTypes,
        currentType: location.getType(),
        toSymbolUrl: urls.locationTypeToSymbolUrl,
      }),
      __: __,
    }));

    $elems.form = $mount.find('.location-statustype-form');
    $elems.cancel = $mount.find('.location-statustype-form-cancel');
    $elems.progress = $mount.find('.location-statustype-progress');
    $elems.error = $mount.find('.location-statustype-error');
    $elems.statusList = $mount.find('.location-status-list');
    $elems.typeList = $mount.find('.location-type-list');

    // Form cancel
    $elems.cancel.click(function (ev) {
      ev.preventDefault();
      self.emit('cancel');
    });

    var submitStatus = function (newStatus) {
      ui.show($elems.progress);
      ui.hide($elems.form);

      location.setStatus(newStatus, function (err) {
        if ($mount) {
          ui.hide($elems.progress);

          if (err) {
            console.error(err);
            ui.show($elems.error);
            return;
          }
          // Everything ok
        }
      });
    };

    var submitType = function (newType) {
      ui.show($elems.progress);
      ui.hide($elems.form);

      location.setType(newType, function (err) {
        if ($mount) {
          ui.hide($elems.progress);

          if (err) {
            console.error(err);
            ui.show($elems.error);
            return;
          }
          // Everything ok
        }
      });
    };

    // Click on a status button
    $elems.statusList.click(function (ev) {
      ev.preventDefault(); // Avoid page reload.
      var btnValue = ev.target.dataset.status;
      if (typeof btnValue === 'string' && btnValue.length > 0) {
        submitStatus(btnValue);
      }
    });

    // Click on a type button
    $elems.typeList.click(function (ev) {
      ev.preventDefault(); // Avoid page reload.
      var btnValue = ev.target.dataset.type;
      if (typeof btnValue === 'string' && btnValue.length > 0) {
        submitType(btnValue);
      }
    });
  };

  this.unbind = function () {
    if ($mount) {
      $mount = null;
      ui.offAll($elems);
      $elems = {};
    }
  };
};
<|endoftext|>


<commit_before>var pxMember;

$(function() {
  $('.main.menu .item').tab('change tab', 'second'); // FIXME to select second menu
  $('.ui.accordion').accordion();
  $('#dashboardLink').click(function() { $('.details.sidebar').sidebar('toggle'); return false;});
  $('.details.sidebar').sidebar('hide', { overlay: true});
  $('.facets.sidebar').sidebar('hide');
  $('.ui.facets.button').click(function() { $('.facets.sidebar').sidebar('toggle'); });
  $('.ui.scrape.button').click(function() { $('.scrape.content').toggle('hidden'); });
  $('.sortable.table').tablesort();
  $('.ui.checkbox').checkbox({onChange : updateOptions});

  function updateOptions() {
    console.log($(this).attr('id'), $(this).is(':checked'));
    if($(this).is(':checked')) {
      $('#'+$(this).attr('id') + 'Options').show();
    } else {
      $('#'+$(this).attr('id') + 'Options').hide();
    }
  }

  pxMember = window.pxMember || $.cookie('pxMember');
  $('#searchMember').val(pxMember);
  window.pxContent.style.width = window.parent.innerWidth - 340;
  fayeClient = new Faye.Client('FAYEHOST');
  fayeClient.publish('/search', { member: pxMember });

  include "results.js"
  include "users.js"
  include "scrape.js"

  $('#searching').show();
  resetUploadForm();
  $('.processContent').click(function() {
    processContent();
    return false;
  });

  include "upload.js"

});

/* speech demo */

function onChange(inp) {
console.log(inp.value);
  $('#input').val($('#input').val() + inp.value);
  inp.value = '';
}
/* end speech demo */

<commit_msg>input upload remnants<commit_after>var pxMember;

$(function() {
  $('.main.menu .item').tab('change tab', 'second'); // FIXME to select second menu
  $('.ui.accordion').accordion();
  $('#dashboardLink').click(function() { $('.details.sidebar').sidebar('toggle'); return false;});
  $('.details.sidebar').sidebar('hide', { overlay: true});
  $('.facets.sidebar').sidebar('hide');
  $('.ui.facets.button').click(function() { $('.facets.sidebar').sidebar('toggle'); });
  $('.ui.scrape.button').click(function() { $('.scrape.content').toggle('hidden'); });
  $('.sortable.table').tablesort();
  $('.ui.checkbox').checkbox({onChange : updateOptions});

  function updateOptions() {
    console.log($(this).attr('id'), $(this).is(':checked'));
    if($(this).is(':checked')) {
      $('#'+$(this).attr('id') + 'Options').show();
    } else {
      $('#'+$(this).attr('id') + 'Options').hide();
    }
  }

  pxMember = window.pxMember || $.cookie('pxMember');
  $('#searchMember').val(pxMember);
  window.pxContent.style.width = window.parent.innerWidth - 340;
  fayeClient = new Faye.Client('FAYEHOST');
  fayeClient.publish('/search', { member: pxMember });

  include "results.js"
  include "users.js"
  include "scrape.js"

  $('#searching').show();
  resetUploadForm();
  $('.processContent').click(function() {
    processContent();
    return false;
  });

});

<|endoftext|>


<commit_before>/**
 * controller
 * @return
 */
module.exports = Controller("Home/BaseController", function(){
  "use strict";
  var Service = require("../../Service/Service");
  return {
    indexAction: function(){
      var self = this;
      if(!self.userInfo || !self.userInfo.id){
        return self.redirect("/");
      }
      var course_id = self.get('id');
      if(!course_id){
        return self.error("请选择要购买的课程！")
      }
      Service.getCourseById({id : course_id}).then(function(data){
        var course = data[0];
        var mydate = new Date();
        mydate.setFullYear(mydate.getFullYear() + 1);
        self.assign({
          section : 'pay',
          title : "购买产品",
          userInfo:self.userInfo,
          navLinks : navLinks,
          valid_date : getDate(mydate),
          course : course
        })
        self.display();
      })
    },

    errAction: function(){
      var self = this;
      if(!self.userInfo || !self.userInfo.id){
        return self.redirect("/");
      }
      this.assign({
        section : 'pay',
        title : "支付出错",
        userInfo:self.userInfo,
        navLinks : navLinks
      })
      this.display();
    },

    successAction : function(){
      var self = this;
      if(!self.userInfo || !self.userInfo.id){
        return self.redirect("/");
      }
      this.assign({
        section : 'pay',
        title : "支付成功",
        userInfo:self.userInfo,
        navLinks : navLinks
      })
      this.display();
    },

    infoAction : function(){
      var self = this;
      if(self.isPost()){
        if(!self.userInfo){
          return self.error("请登录后进行购买！")
        }else{
          var data = self.post();
          console.log('paying')
          Service.createOrder({
            user_id : self.userInfo.id,
            name : data.name,
            desc : '购买课程：' + data.name,
            detail :JSON.stringify([{
              'course_id' : data.courseid,
              'num' : 1
            }])
          }).then(function(content){
            if(content && content.errno === 0){
              Service.payOrder({
                order_unique_id : content.data,
                comment : data.comment,
                showurl : data.showurl,
                isalipay : data.isalipay,
                bankname : data.bankname
              }).then(function(ocontent){
                self.assign(extend({
                  section : 'pay',
                  title : "购买课程",
                  aliform : ocontent.request
                },ocontent))
                return self.display();
              })
            }else{
              throw new Error('抛出错误')
            }
          }).catch(function(err){
            return self.error(err);
          })
        }
      }
    },

    notifyAction : function(){
      var self = this;
      var data = self.post();
      console.log('notify');
      Service.cbOrder(data).then(function(content){
        if(content && content.errno === 0){
          self.end("success")
        }else{
          self.end('fail')
        }
      }).catch(function(err){
        return self.end('fail')
      })
    },

    returnAction : function(){
      var self = this;
      var data = self.get();
      console.log(JSON.stringify(data));
      console.log('return');
      if(data['trade_status'] == 'TRADE_FINISHED' || data['trade_status'] == 'TRADE_SUCCESS'){
        return self.redirect('/pay/success');
      }else{
        return self.redirect('/pay/err');
      }
    }
  };
})<commit_msg>add files by wangpengfei<commit_after>/**
 * controller
 * @return
 */
module.exports = Controller("Home/BaseController", function(){
  "use strict";
  var Service = require("../../Service/Service");
  return {
    indexAction: function(){
      var self = this;
      if(!self.userInfo || !self.userInfo.id){
        return self.redirect("/");
      }
      var course_id = self.get('id');
      if(!course_id){
        return self.error("请选择要购买的课程！")
      }
      Service.getCourseById({id : course_id}).then(function(data){
        var course = data[0];
        var mydate = new Date();
        mydate.setFullYear(mydate.getFullYear() + 1);
        self.assign({
          section : 'pay',
          title : "购买产品",
          userInfo:self.userInfo,
          navLinks : navLinks,
          valid_date : getDate(mydate),
          course : course
        })
        self.display();
      })
    },

    errAction: function(){
      var self = this;
      if(!self.userInfo || !self.userInfo.id){
        return self.redirect("/");
      }
      this.assign({
        section : 'pay',
        title : "支付出错",
        userInfo:self.userInfo,
        navLinks : navLinks
      })
      this.display();
    },

    successAction : function(){
      var self = this;
      if(!self.userInfo || !self.userInfo.id){
        return self.redirect("/");
      }
      this.assign({
        section : 'pay',
        title : "支付成功",
        userInfo:self.userInfo,
        navLinks : navLinks
      })
      this.display();
    },

    infoAction : function(){
      var self = this;
      if(self.isPost()){
        if(!self.userInfo){
          return self.error("请登录后进行购买！")
        }else{
          var data = self.post();
          console.log('paying')
          Service.createOrder({
            user_id : self.userInfo.id,
            name : data.name,
            desc : '购买课程：' + data.name,
            detail :JSON.stringify([{
              'course_id' : data.courseid,
              'num' : 1
            }])
          }).then(function(content){
            if(content && content.errno === 0){
              Service.payOrder({
                order_unique_id : content.data,
                comment : data.comment,
                showurl : data.showurl,
                isalipay : data.isalipay,
                bankname : data.bankname
              }).then(function(ocontent){
                self.assign(extend({
                  section : 'pay',
                  title : "购买课程",
                  aliform : ocontent.request
                },ocontent))
                return self.display();
              })
            }else{
              throw new Error('抛出错误')
            }
          }).catch(function(err){
            return self.error(err);
          })
        }
      }
    },

    notifyAction : function(){
      var self = this;
      var data = self.post();
      console.log('notify');
      Service.cbOrder(data).then(function(content){
        if(content && content.errno === 0){
          console.log('notify_success');
          self.end("success")
        }else{
          console.log('notify_fail');
          self.end('fail')
        }
      }).catch(function(err){
        console.log('notify_fail');
        return self.end('fail')
      })
    },

    returnAction : function(){
      var self = this;
      var data = self.get();
      console.log(JSON.stringify(data));
      console.log('return');
      if(data['trade_status'] == 'TRADE_FINISHED' || data['trade_status'] == 'TRADE_SUCCESS'){
        return self.redirect('/pay/success');
      }else{
        return self.redirect('/pay/err');
      }
    }
  };
})<|endoftext|>


<commit_before>define('carousel', ['jquery'], function($){

   var application = {

        'start' : function(){

            this.slideIndex = 1;

            // init-event listener
            this.initEventListener();

            // init initial size
            this.resizeElementsOnCarousel();

            this.showSlides("left");
        },

        /**
        * Function to initialize all the event listeners
        */
        'initEventListener': function() {

            // alias
            var self = this;

            // previous button
            $(".slideshow-container a.prev").on('click', function(){
                self.moveSlides(-1);
            });

            // next button
            $(".slideshow-container a.next").on('click', function(){
                self.moveSlides(1);
            });

            // buttons at the bottom
            $('.slideshow-container span.dot').on('click', function(){
                var index = $(this).index() + 1;
                self.currentSlide(index);
            });

            // on resize of window update carousel appropriately
            $(window).on('resize', function(){
                self.resizeElementsOnCarousel();
            });
        },

        /**
        Resize elements such as the caption and buttons that are on the carousel
        */
        'resizeElementsOnCarousel' : function(){

            // alias
            var self = this;

            // get the window height
            var wWidth = $(window).width();
            var sHeight = 450; // slideshow height default
            var cTop = "20%";

            // handle based on view-port
            if (wWidth > 1350) {
                sHeight = 500;
                cTop = "40%";
            } else if (wWidth > 800) {
                sHeight = 450;
                cTop = "40%";
            } else if (wWidth > 700)
                sHeight = 400;
            else if (wWidth > 600)
                sHeight = 300;
            else if (wWidth > 500)
                sHeight = 250;
            else if (wWidth > 400)
                sHeight = 200;
            else if (wWidth > 350)
                sHeight = 180;
            else
                sHeight = 160;

            // set the new height for the sliding container
            $('.slideshow-container').height(sHeight);
            $('.slideshow-caption').css('top', cTop);
        },

        /**
        * Move slides forward and backwards
        * @param n : Integer indicating how many slides to move
        * negative backwards and positive for forwards
        */
        'moveSlides' : function(n){
            this.slideIndex += n

            // indicate direction of showing slides
            if (n < 0)
                var direction = "left";
            else
                var direction = "right";

            this.showSlides(direction);
        },

        /**
        * Get to the current slide indicated by the number n
        * @param n - integer indicating the slide we want to go to
        * note the slides start from 1
        */
        'currentSlide': function(n) {
            this.slideIndex = n
            this.showSlides("left");
        },

        /**
        * Function used to show the slides
        */
        'showSlides': function(direction) {

            // alias
            var self = this;

            var i;
            var slides = $(".mySlides");
            var dots = $(".dot");
                if (self.slideIndex > slides.length) {
              self.slideIndex = 1
            }
            if (self.slideIndex < 1) {
              self.slideIndex = slides.length
            }

            // loop through all display and hide
            $(slides).each(function(index, element){
              $(element).css('display', 'none');
            });

            for (i = 0; i < dots.length; i++) {
                dots[i].className = dots[i].className.replace(" active", "");
            }

            // change direction
            if(direction == "left") {
                $(slides).addClass('fade-carousel-left');
                $(slides).removeClass('fade-carousel-right');
            } else {
                $(slides).removeClass('fade-carousel-left');
                $(slides).addClass('fade-carousel-right');
            }

            // display the slides
            slides.get(self.slideIndex-1).style.display = "block";
            dots.get(self.slideIndex-1).className += " active";

        }
   }

    return application;

})

// call on loading of page
require(['carousel'], function(app){
    app.start();
});
<commit_msg>Carousel now auto changes after 5 seconds<commit_after>define('carousel', ['jquery'], function($){

   var application = {

        'start' : function(){

            this.slideIndex = 1;

            // init-event listener
            this.initEventListener();

            // init initial size
            this.resizeElementsOnCarousel();

            this.showSlides("left");
        },

        /**
        * Function to initialize all the event listeners
        */
        'initEventListener': function() {

            // alias
            var self = this;

            // previous button
            $(".slideshow-container a.prev").on('click', function(){
                self.moveSlides(-1);
            });

            // next button
            $(".slideshow-container a.next").on('click', function(){
                self.moveSlides(1);
            });

            // buttons at the bottom
            $('.slideshow-container span.dot').on('click', function(){
                var index = $(this).index() + 1;
                self.currentSlide(index);
            });

            // on resize of window update carousel appropriately
            $(window).on('resize', function(){
                self.resizeElementsOnCarousel();
            });

            // set interval four how long we toggle the auto change
            setInterval(self.moveSlides.bind(self), 5000, 1);
        },

        /**
        Resize elements such as the caption and buttons that are on the carousel
        */
        'resizeElementsOnCarousel' : function(){

            // alias
            var self = this;

            // get the window height
            var wWidth = $(window).width();
            var sHeight = 450; // slideshow height default
            var cTop = "20%";

            // handle based on view-port
            if (wWidth > 1350) {
                sHeight = 500;
                cTop = "40%";
            } else if (wWidth > 800) {
                sHeight = 450;
                cTop = "40%";
            } else if (wWidth > 700)
                sHeight = 400;
            else if (wWidth > 600)
                sHeight = 300;
            else if (wWidth > 500)
                sHeight = 250;
            else if (wWidth > 400)
                sHeight = 200;
            else if (wWidth > 350)
                sHeight = 180;
            else
                sHeight = 160;

            // set the new height for the sliding container
            $('.slideshow-container').height(sHeight);
            $('.slideshow-caption').css('top', cTop);
        },

        /**
        * Move slides forward and backwards
        * @param n : Integer indicating how many slides to move
        * negative backwards and positive for forwards
        */
        'moveSlides' : function(n){

            // alias
            var self = this;

            this.slideIndex += n

            // indicate direction of showing slides
            if (n < 0)
                var direction = "left";
            else
                var direction = "right";

            this.showSlides(direction);
        },

        /**
        * Get to the current slide indicated by the number n
        * @param n - integer indicating the slide we want to go to
        * note the slides start from 1
        */
        'currentSlide': function(n) {
            this.slideIndex = n
            this.showSlides("left");
        },

        /**
        * Function used to show the slides
        */
        'showSlides': function(direction) {

            // alias
            var self = this;

            var i;
            var slides = $(".mySlides");
            var dots = $(".dot");
                if (self.slideIndex > slides.length) {
              self.slideIndex = 1
            }
            if (self.slideIndex < 1) {
              self.slideIndex = slides.length
            }

            // loop through all display and hide
            $(slides).each(function(index, element){
              $(element).css('display', 'none');
            });

            for (i = 0; i < dots.length; i++) {
                dots[i].className = dots[i].className.replace(" active", "");
            }

            // change direction
            if(direction == "left") {
                $(slides).addClass('fade-carousel-left');
                $(slides).removeClass('fade-carousel-right');
            } else {
                $(slides).removeClass('fade-carousel-left');
                $(slides).addClass('fade-carousel-right');
            }

            // display the slides
            slides.get(self.slideIndex-1).style.display = "block";
            dots.get(self.slideIndex-1).className += " active";

        }
   }

    return application;

})

// call on loading of page
require(['carousel'], function(app){
    app.start();
});
<|endoftext|>


<commit_before>angular.module('main')
.controller('porjectCtrl', ['$scope', '$http', '$routeParams',
	function($scope, $http, $routeParams) {
	var project = {'heading': $routeParams.id};
	$http({method:'POST', url:'/project', data: project}).success(function(data) {
		$scope.project = data[0];
		// Adding chlider to the project
		$scope.project.children = [];
		var child = {name:'Child',description:'Child Description'};
		$scope.project.children.push(child);
		//debugger;
	});
}]);
<commit_msg>Simple interface changes<commit_after>angular.module('main')
.controller('porjectCtrl', ['$scope', '$http', '$routeParams',
	function($scope, $http, $routeParams) {
	var project = {'heading': $routeParams.id};
	$http({method:'POST', url:'/project', data: project}).success(function(data) {
		$scope.project = data[0];
		// Adding chlider to the project
		$scope.project.children = [];
		var childA = {name:'ChildA',description:'Child Description'};
		var childB = {name:'ChildB',description:'Child Description'};
		var childC = {name:'ChildC',description:'Child Description'};
		$scope.project.children.push(childA);
		$scope.project.children.push(childB);
		$scope.project.children.push(childC);
		//debugger;
	});
}]);
<|endoftext|>