<commit_before>'use strict';

angular
  .module('ta-maxlength', [])
  .directive('taMaxlength', function ($timeout, textAngularManager, $translate) {
    return {
      restrict: 'A',
      link: function ($scope, element, attrs) {
        var editor, editorID, editorContainer, maxLength = parseInt(attrs.taMaxlength);
        var initDone = false;

        if(isNaN(maxLength)) {
          console.warn('Invalid number for ta-maxlength, automatically set to POSITIVE_INFINITY');
          maxLength = Number.POSITIVE_INFINITY;
        }

        var parseContent = function(content, returnValue) {
          //remove zero-width no break spaces
          content = content.replace(new RegExp('', 'g'), '');

          //build dom stack
          var domStack = [];

          //parse html text
          var strippedText = '';
          var printedChars = 0;
          var parseMode = 'text';
          var tagName = '';

          for(var i=0; i<content.length; i++) {
            var currentChar = content[i];
            var nextChar = (i<content.length-1) ? content.length[i+1] : '';
            strippedText += currentChar;

            if(currentChar == '<') {
              if(nextChar == '/') {
                domStack.pop();
                parseMode = 'ignoreHTML';
              } else {
                parseMode = 'findTagName';
              }
            } else {
              if(parseMode == 'text') {
                if(currentChar == '&') {
                  parseMode = 'htmlSpecialChar';
                } else {
                  printedChars++;

                  if(printedChars == maxLength) {
                    //close remaining tags and stop
                    domStack = domStack.reverse();
                    domStack.forEach(function (tag) {
                      strippedText += '</' + tag + '>';
                    });
                    domStack = [];

                    switch(returnValue) {
                      case 'strippedText':
                        console.log('right place. stripped content has now '+printedChars+' chars.');
                        return strippedText;
                      case 'charCount':
                        return printedChars;
                    }
                  }
                }
              } else if(parseMode == 'htmlSpecialChar') {
                if(currentChar == ';') {
                  printedChars++;
                  parseMode = 'text';
                }
                //if no semicolon, HTML special char is still parsed; do nothing
              } else if(parseMode == 'findTagName') {
                if(currentChar == '>') {
                  //tag closes
                  domStack.push(tagName);
                  tagName = '';
                  parseMode = 'text';
                } else if(currentChar == ' ') {
                  //attributes after tag name
                  domStack.push(tagName);
                  tagName = '';
                  parseMode = 'ignoreHTML';
                } else if(currentChar == '/') {
                  //self closing tags
                  tagName = '';
                  parseMode = 'ignoreHTML';
                } else {
                  //letters of tag name
                  tagName += currentChar;
                }
              } else if(parseMode == 'ignoreHTML') {
                if(currentChar == '>') {
                  parseMode = 'text';
                }
              }
            }
          }

          switch(returnValue) {
            case 'strippedText':
              //console.log('stripped text:', strippedText, strippedText.length);
              return strippedText;
            case 'charCount':
              return printedChars;
          }
        };

        var stripContent = function(content) {
          return parseContent(content, 'strippedText');
        };

        var updateRemainingChars = function() {
          var charCountDiv = angular.element(document.querySelector('#taInnerCharCount'+editorID));
          var remainingChars = maxLength - getContentLength(editor.scope.html);

          //possible if some text was copied and pasted
          if(remainingChars < 0) {
            editor.scope.html = stripContent(editor.scope.html);
            remainingChars = 0;
          }

          if(remainingChars == 0) {
            charCountDiv.html('' + remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT') + '');
          } else {
            charCountDiv.html(remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT'));
          }
        };

        var getEditor = function() {
          return editor.scope.displayElements.text[0];
        };

        var getContentLength = function(content) {
          return parseContent(content, 'charCount');
        };

        var isNavigationKey = function(keyCode) {
          return ((keyCode >= 33) && (keyCode <= 40)) || ([8, 46].indexOf(keyCode) !== -1);
        };

        var isCopying = function(event) {
          return event.ctrlKey && ([65, 67, 88].indexOf(event.keyCode) !== -1);
        };

        $scope.$watch(function() {
          var editorInstance = textAngularManager.retrieveEditor(attrs.name);

          if((editorInstance !== undefined) && (editor === undefined)) {
            editor = editorInstance;

            if(!initDone) {
              //create DIV
              editorID = editor.scope.displayElements.text[0].id.substr(13);
              editorContainer = angular.element(document.querySelector('#taTextElement'+editorID));
              editorContainer.parent().append('

');
              initDone = true;
              updateRemainingChars();
            }

            getEditor().addEventListener('keydown', function(e) {
              if(!isNavigationKey(e.keyCode) && !isCopying(e) && (getContentLength(editor.scope.html) >= maxLength)) {
                e.preventDefault();
                return false;
              }
            });

            getEditor().addEventListener('click', function() {
              updateRemainingChars();
            });
          }

          return editorInstance === undefined ? '' : editor.scope.html;
        }, function() {
          if(getContentLength(editor.scope.html) > maxLength) {
            editor.scope.html = stripContent(editor.scope.html);
          }
          updateRemainingChars();
        });
      }
    };
  });<commit_msg>tried to fix broken function<commit_after>'use strict';

angular
  .module('ta-maxlength', [])
  .directive('taMaxlength', function ($timeout, textAngularManager, $translate) {
    return {
      restrict: 'A',
      link: function ($scope, element, attrs) {
        var editor, editorID, editorContainer, maxLength = parseInt(attrs.taMaxlength);
        var initDone = false;

        if(isNaN(maxLength)) {
          console.warn('Invalid number for ta-maxlength, automatically set to POSITIVE_INFINITY');
          maxLength = Number.POSITIVE_INFINITY;
        }

        var parseContent = function(content, returnValue) {
          //remove zero-width no break spaces
          content = content.replace(new RegExp('', 'g'), '');

          //build dom stack
          var domStack = [];

          //parse html text
          var strippedText = '';
          var printedChars = 0;
          var parseMode = 'text';
          var tagName = '';

          for(var i=0; i<content.length; i++) {
            var currentChar = content[i];
            var nextChar = (i<content.length-1) ? content.length[i+1] : '';
            strippedText += currentChar;

            if(currentChar == '<') {
              if(nextChar == '/') {
                domStack.pop();
                parseMode = 'ignoreHTML';
              } else {
                parseMode = 'findTagName';
              }
            } else {
              if(parseMode == 'text') {
                if(currentChar == '&') {
                  parseMode = 'htmlSpecialChar';
                } else {
                  printedChars++;
                  console.log('current number of chars:', printedChars);

                  if(printedChars == maxLength) {
                    //close remaining tags and stop
                    domStack = domStack.reverse();
                    domStack.forEach(function (tag) {
                      strippedText += '</' + tag + '>';
                    });
                    domStack = [];

                    switch(returnValue) {
                      case 'strippedText':
                        console.log('right place. stripped content has now '+printedChars+' chars.');
                        return strippedText;
                      case 'charCount':
                        return printedChars;
                    }
                  }
                }
              } else if(parseMode == 'htmlSpecialChar') {
                if(currentChar == ';') {
                  printedChars++;
                  parseMode = 'text';
                }
                //if no semicolon, HTML special char is still parsed; do nothing
              } else if(parseMode == 'findTagName') {
                if(currentChar == '>') {
                  //tag closes
                  domStack.push(tagName);
                  tagName = '';
                  parseMode = 'text';
                } else if(currentChar == ' ') {
                  //attributes after tag name
                  domStack.push(tagName);
                  tagName = '';
                  parseMode = 'ignoreHTML';
                } else if(currentChar == '/') {
                  //self closing tags
                  tagName = '';
                  parseMode = 'ignoreHTML';
                } else {
                  //letters of tag name
                  tagName += currentChar;
                }
              } else if(parseMode == 'ignoreHTML') {
                if(currentChar == '>') {
                  parseMode = 'text';
                }
              }
            }
          }

          switch(returnValue) {
            case 'strippedText':
              //console.log('stripped text:', strippedText, strippedText.length);
              return strippedText;
            case 'charCount':
              return printedChars;
          }
        };

        var stripContent = function(content) {
          return parseContent(content, 'strippedText');
        };

        var updateRemainingChars = function() {
          var charCountDiv = angular.element(document.querySelector('#taInnerCharCount'+editorID));
          var remainingChars = maxLength - getContentLength(editor.scope.html);

          //possible if some text was copied and pasted
          if(remainingChars < 0) {
            editor.scope.html = stripContent(editor.scope.html);
            remainingChars = 0;
          }

          if(remainingChars == 0) {
            charCountDiv.html('' + remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT') + '');
          } else {
            charCountDiv.html(remainingChars + ' ' + $translate.instant('CHARACTERS_LEFT'));
          }
        };

        var getEditor = function() {
          return editor.scope.displayElements.text[0];
        };

        var getContentLength = function(content) {
          return parseContent(content, 'charCount');
        };

        var isNavigationKey = function(keyCode) {
          return ((keyCode >= 33) && (keyCode <= 40)) || ([8, 46].indexOf(keyCode) !== -1);
        };

        var isCopying = function(event) {
          return event.ctrlKey && ([65, 67, 88].indexOf(event.keyCode) !== -1);
        };

        $scope.$watch(function() {
          var editorInstance = textAngularManager.retrieveEditor(attrs.name);

          if((editorInstance !== undefined) && (editor === undefined)) {
            editor = editorInstance;

            if(!initDone) {
              //create DIV
              editorID = editor.scope.displayElements.text[0].id.substr(13);
              editorContainer = angular.element(document.querySelector('#taTextElement'+editorID));
              editorContainer.parent().append('

');
              initDone = true;
              updateRemainingChars();
            }

            getEditor().addEventListener('keydown', function(e) {
              if(!isNavigationKey(e.keyCode) && !isCopying(e) && (getContentLength(editor.scope.html) >= maxLength)) {
                e.preventDefault();
                return false;
              }
            });

            getEditor().addEventListener('click', function() {
              updateRemainingChars();
            });
          }

          return editorInstance === undefined ? '' : editor.scope.html;
        }, function() {
          if(getContentLength(editor.scope.html) > maxLength) {
            editor.scope.html = stripContent(editor.scope.html);
          }
          updateRemainingChars();
        });
      }
    };
  });<|endoftext|>


<commit_before>/*
 * BSD 3-Clause License
 *
 * Copyright (c) 2017, MapCreator
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 *  Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import {AbstractClassError} from '../../errors/AbstractError';
import ResourceBase from './ResourceBase';
import {isParentOf} from '../../utils/reflection';

/**
 * Base of all resource items that support Crud operations
 * @abstract
 */
export default class CrudBase extends ResourceBase {
  /**
   * @param {Maps4News} api - Api instance
   * @param {Object<String, *>} data - Item data
   */
  constructor(api, data = {}) {
    super(api, data);

    if (this.constructor === CrudBase) {
      throw new AbstractClassError();
    }
  }

  /**
   * Build data for create operation
   * @returns {Object<String, *>} - Create data
   * @protected
   */
  _buildCreateData() {
    this._updateProperties();

    const out = {};
    const keys = [].concat(
      Object.keys(this._properties),
      Object.keys(this._baseProperties),
    ).filter((item, pos, self) => self.indexOf(item) === pos);

    for (const key of keys) {
      out[key] = this._properties[key] || this._baseProperties[key];
    }

    delete out.id;
    return out;
  }

  /**
   * Save item. This will create a new item if `id` is unset
   * @returns {Promise} - Resolves with {@link CrudBase} instance and rejects with {@link ApiError}
   */
  save() {
    return !this.id ? this._create() : this._update();
  }

  /**
   * Store new item
   * @returns {Promise} - Resolves with {@link CrudBase} instance and rejects with {@link ApiError}
   * @private
   */
  _create() {
    return new Promise((resolve, reject) => {
      this.api
        .request(this.baseUrl, 'POST', this._buildCreateData())
        .catch(reject)
        .then(data => {
          this._properties = {};
          this._baseProperties = data;

          this._updateProperties();
          resolve(this);
        });
    });
  }

  /**
   * Update existing item
   * @returns {Promise} - Resolves with {@link CrudBase} instance and rejects with {@link ApiError}
   * @private
   */
  _update() {
    this._updateProperties();

    return new Promise((resolve, reject) => {
      this.api
        .request(this.url, 'PATCH', this._properties)
        .catch(reject)
        .then(() => {
          if (this.api.defaults.autoUpdateSharedCache) {
            this.api.cache.update(this);
          }

          resolve(this);
        });
    });
  }

  /**
   * Delete item
   * @returns {Promise} - Resolves with an empty {@link Object} and rejects with {@link ApiError}
   */
  delete() {
    return this.api.request(this.url, 'DELETE');
  }

  /**
   * Restore item
   * @returns {Promise} - Resolves with {@link CrudBase} instance and rejects with {@link ApiError}
   */
  restore() {
    return new Promise((resolve, reject) => {
      this.api.request(this.url, 'PUT')
        .catch(reject)
        .then(data => resolve(new this.constructor(this.api, data)));
    });
  }

  /**
   * Sync, attach or unlink resources
   * @param {Array<Organisation>|Array<Number>} items - List of items to sync or attach
   * @param {String} method - Http method to use
   * @param {ResourceBase} Type - Resource type
   * @param {?String} path - Optional appended resource path, will guess if null
   * @returns {Promise} - Promise will resolve with no value and reject with an {@link ApiError} instance.
   * @todo refactor to CrudBase and remove organisation specific method from trait
   * @protected
   */
  _modifyLink(items, method, Type, path) {
    if (!path) {
      const resource = (new Type(this.api)).resourceName.replace(/s+$/, '');

      path = `${resource}s`;
    }

    const filter = x => !isParentOf(Type, x) && !isParentOf(Number, x);
    const isValid = items.filter(filter).length === 0;

    if (!isValid) {
      throw new TypeError(`Array must contain either Numbers (resource id) or "${Type.name}".`);
    }

    const keys = items.map(x => typeof x === 'number' ? x : x.id).map(Number);

    return this.api.request(`${this.url}/${path}`, method, {keys});
  }
}
<commit_msg>updateSelf for delete/restore CRUD <commit_after>/*
 * BSD 3-Clause License
 *
 * Copyright (c) 2017, MapCreator
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 *  Redistributions in binary form must reproduce the above copyright notice,
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 *
 *  Neither the name of the copyright holder nor the names of its
 *   contributors may be used to endorse or promote products derived from
 *   this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

import {AbstractClassError} from '../../errors/AbstractError';
import {isParentOf} from '../../utils/reflection';
import ResourceBase from './ResourceBase';

/**
 * Base of all resource items that support Crud operations
 * @abstract
 */
export default class CrudBase extends ResourceBase {
  /**
   * @param {Maps4News} api - Api instance
   * @param {Object<String, *>} data - Item data
   */
  constructor(api, data = {}) {
    super(api, data);

    if (this.constructor === CrudBase) {
      throw new AbstractClassError();
    }
  }

  /**
   * Build data for create operation
   * @returns {Object<String, *>} - Create data
   * @protected
   */
  _buildCreateData() {
    this._updateProperties();

    const out = {};
    const keys = [].concat(
      Object.keys(this._properties),
      Object.keys(this._baseProperties),
    ).filter((item, pos, self) => self.indexOf(item) === pos);

    for (const key of keys) {
      out[key] = this._properties[key] || this._baseProperties[key];
    }

    delete out.id;
    return out;
  }

  /**
   * Save item. This will create a new item if `id` is unset
   * @returns {Promise} - Resolves with {@link CrudBase} instance and rejects with {@link ApiError}
   */
  save() {
    return !this.id ? this._create() : this._update();
  }

  /**
   * Store new item
   * @param {Boolean} updateSelf - Update the current instance
   * @returns {Promise} - Resolves with {@link CrudBase} instance and rejects with {@link ApiError}
   * @private
   */
  _create() {
    return new Promise((resolve, reject) => {
      this.api
        .request(this.baseUrl, 'POST', this._buildCreateData())
        .catch(reject)
        .then(data => {
          this._properties = {};
          this._baseProperties = data;

          this._updateProperties();
          resolve(this);
        });
    });
  }

  /**
   * Update existing item
   * @param {Boolean} updateSelf - Update the current instance
   * @returns {Promise} - Resolves with {@link CrudBase} instance and rejects with {@link ApiError}
   * @private
   */
  _update() {
    this._updateProperties();

    return new Promise((resolve, reject) => {
      this.api
        .request(this.url, 'PATCH', this._properties)
        .catch(reject)
        .then(() => {
          if (this.api.defaults.autoUpdateSharedCache) {
            this.api.cache.update(this);
          }

          resolve(this);
        });
    });
  }

  /**
   * Delete item
   * @returns {Promise} - Resolves with an empty {@link Object} and rejects with {@link ApiError}
   */
  delete(updateSelf = true) {
    return this.api
      .request(this.url, 'DELETE')
      .then(data => {
        if (updateSelf) {
          this._baseProperties['deleted_at'] = new Date();
        }

        return data;
      });
  }

  /**
   * Restore item
   * @returns {Promise} - Resolves with {@link CrudBase} instance and rejects with {@link ApiError}
   */
  restore(updateSelf = true) {
    return this.api
      .request(this.url, 'PUT')
      .then(data => {
        const instance = new this.constructor(this.api, data);

        if (updateSelf) {
          this._properties = {};
          this._baseProperties = data;

          this._updateProperties();
        }

        return instance;
      });

  }

  /**
   * Sync, attach or unlink resources
   * @param {Array<Organisation>|Array<Number>} items - List of items to sync or attach
   * @param {String} method - Http method to use
   * @param {ResourceBase} Type - Resource type
   * @param {?String} path - Optional appended resource path, will guess if null
   * @returns {Promise} - Promise will resolve with no value and reject with an {@link ApiError} instance.
   * @todo refactor to CrudBase and remove organisation specific method from trait
   * @protected
   */
  _modifyLink(items, method, Type, path) {
    if (!path) {
      const resource = (new Type(this.api)).resourceName.replace(/s+$/, '');

      path = `${resource}s`;
    }

    const filter = x => !isParentOf(Type, x) && !isParentOf(Number, x);
    const isValid = items.filter(filter).length === 0;

    if (!isValid) {
      throw new TypeError(`Array must contain either Numbers (resource id) or "${Type.name}".`);
    }

    const keys = items.map(x => typeof x === 'number' ? x : x.id).map(Number);

    return this.api.request(`${this.url}/${path}`, method, {keys});
  }
}
<|endoftext|>


<commit_before>
(function ($) {
    'use strict';
    /* jshint laxbreak: true */

    $.fn.wrap = function (value) {
        return this.wrapWith(value);
    };

    $.fn.css = function (key, value) {
        if (value === undefined) {
            return this.get(':' + key);
        }

        return this.set(':' + key, value);
    };

    $.fn.attr = function (key, value) {
        if (value === undefined) {
            return $(this).get('@' + key);
        }

        return $(this).set('@' + key, value);
    };

    $.fn.removeAttr = function (key, value) {
        return $(this).set('@' + key);
    };

    $.fn.addClass = function (key)  {
        return $(this).set('.' + key);
    };

    $.fn.removeClass = function (key)  {
        return $(this).set('.' + key, 'remove');
    };

    $.fn.toggleClass = function (key)  {
        return $(this).set('.' + key, 'toggle');
    };

    $.fn.hasClass = function (key)  {
        return $(this).get('.' + key);
    };

    $.fn.first = function (key)  {
        return $(this).eq(0);
    };

    $.fn.last = function (key)  {
        return $(this).eq(this.length - 1);
    };

    $.fn.size = function () {
        return this.length;
    };

    $.fn.toArray = function () {
        return [].slice.call(this);
    };

    $.fn.html = function (value) {
        if (value === undefined) {
            return this[0].innerHTML;
        }

        return this.each(function (i) {
            this.innerHTML = functionOrValue(value, this, i);
        });
    };

    $.fn.text = function (value) {
        if (value === undefined) {
            return this[0].innerHTML || this[0].textContent;
        }

        return this.each(function (i) {
            this.textContent = functionOrValue(value, this, i);
        });
    };

    $.fn.data = function (key, value) {
        key = camelize(key);

        if (value === undefined) {
            return this[0].dataset[key];
        }

        return this.each(function (i) {
            this.dataset[key] = value;
        });
    };

    function functionOrValue (value, elmt, i) {
        if (typeof value === 'function') {
            return value.call(elmt, i);
        }

        return value;
    }

    function camelize (string) {
        return string.replace(/-+(.)?/g, function (match, chr) {
            return chr ? chr.toUpperCase() : '';
        });
    }

    // $.fn.get = function (idx)  {
    //     if (idx === undefined) {
    //         return this.toArray();
    //     }

    //     if (idx < 0) {
    //         return this[idx + this.length];
    //     }

    //     return this[idx];
    // };
}(Pin));
<commit_msg>Add bunch of draft methods: show, hide, toggle, fadeIn, fadeOut, fadeToggle, slideUp, slideDown, slideToggle, prependTo, appendTo, insertAfter, insertBefore, contents, empty...<commit_after>
(function ($) {
    'use strict';
    /* jshint laxbreak: true */

    $.fn.wrap = function (value) {
        return this.wrapWith(value);
    };

    $.fn.css = function (key, value) {
        if (value === undefined) {
            return this.get(':' + key);
        }

        return this.set(':' + key, value);
    };

    $.fn.attr = function (key, value) {
        if (value === undefined) {
            return $(this).get('@' + key);
        }

        return $(this).set('@' + key, value);
    };

    $.fn.removeAttr = function (key, value) {
        return $(this).set('@' + key);
    };

    $.fn.addClass = function (key)  {
        return $(this).set('.' + key);
    };

    $.fn.removeClass = function (key)  {
        return $(this).set('.' + key, 'remove');
    };

    $.fn.toggleClass = function (key)  {
        return $(this).set('.' + key, 'toggle');
    };

    $.fn.hasClass = function (key)  {
        return $(this).get('.' + key);
    };

    $.fn.first = function (key)  {
        return $(this).eq(0);
    };

    $.fn.last = function (key)  {
        return $(this).eq(this.length - 1);
    };

    $.fn.size = function () {
        return this.length;
    };

    $.fn.toArray = function () {
        return [].slice.call(this);
    };

    $.fn.html = function (value) {
        if (value === undefined) {
            return this[0].innerHTML;
        }

        return this.each(function (i) {
            this.innerHTML = functionOrValue(value, this, i);
        });
    };

    $.fn.text = function (value) {
        if (value === undefined) {
            return this[0].innerHTML || this[0].textContent;
        }

        return this.each(function (i) {
            this.textContent = functionOrValue(value, this, i);
        });
    };

    $.fn.empty = function () {
        return this.each(function () {
            this.innerHTML = '';
        });
    };

    $.fn.contents = function () {
        var elmts = [];

        this.each(function () {
            elmts = elmts.concat([].slice.apply(this.childNodes));
        });

        return $($.uniq(elmts));
    };

    $.fn.data = function (key, value) {
        key = camelize(key);

        if (value === undefined) {
            return this[0].dataset[key];
        }

        return this.each(function (i) {
            this.dataset[key] = value;
        });
    };

    $.fn.show = function () {
        var args = arguments;

        return this.each(function () {
            var $elmt = $(this);

            if ($elmt.get(':display') === 'none') {
                $elmt.set(':display', $elmt.data('_display') || '');
            }

            findCallbackInArgs(args).apply(this);
        });
    };

    $.fn.hide = function () {
        var args = arguments;

        return this.each(function () {
            var $elmt = $(this);

            $elmt.data('_display', $elmt.get(':display'));
            $elmt.set(':display', 'none');

            findCallbackInArgs(args).apply(this);
        });
    };

    $.fn.toggle = function () {
        var args = arguments;

        return this.each(function () {
            var $elmt = $(this);

            if ($elmt.get(':display') === 'none') {
                $elmt.show();
            } else {
                $elmt.hide();
            }

            findCallbackInArgs(args).apply(this);
        });
    };

    [ 'fadeIn', 'slideDown', 'fadeOut', 'slideUp', 'fadeToggle', 'slideToggle', 'fadeTo' ].forEach(function (name, i) {
        if (i === 0 || i === 1) {
            $.fn[name] = function () {
                return this.show.apply(this, arguments);
            };
        }

        if (i === 2 || i === 3) {
            $.fn[name] = function () {
                return this.hide.apply(this, arguments);
            };
        }

        if (i === 4 || i === 5) {
            $.fn[name] = function () {
                return this.toggle.apply(this, arguments);
            };
        }

        $.fn[name] = function (duration, opacity) {
            if (opacity > 0.5) {
                return this.show.apply(this, arguments);
            }
            return this.hide.apply(this, arguments);
        };
    });

    [ 'prependTo', 'appendTo', 'insertBefore', 'insertAfter' ].forEach(function (name, i) {
        $.fn[name] = function (html) {
            var method = name.toLowerCase().replace(/to|insert/, '');

            $(html)[method](this);
        };
    });

    function findCallbackInArgs (args) {
        for (var i = 0; i < args.length; i++) {
            if (typeof args[i] === 'function') {
                return args[i];
            }
        }

        return function () {};
    }

    function functionOrValue (value, elmt, i) {
        if (typeof value === 'function') {
            return value.call(elmt, i);
        }

        return value;
    }

    function camelize (string) {
        return string.replace(/-+(.)?/g, function (match, chr) {
            return chr ? chr.toUpperCase() : '';
        });
    }

    // $.fn.get = function (idx)  {
    //     if (idx === undefined) {
    //         return this.toArray();
    //     }

    //     if (idx < 0) {
    //         return this[idx + this.length];
    //     }

    //     return this[idx];
    // };
}(Pin));
<|endoftext|>


<commit_before>var d3ma = {version: '0.2.0'}; // semver;

// useful to figure out how many svg elements on the current page
// track individual .canvas element
// then retrieve cancas object, could call *draw* method to update its visualization
d3ma.canvas = [];

// getter & setter function
// set the canvas object into the d3ma.canvas array, used to redraw the chart
// optional param, if omit, it will simply retrieve the current d3ma.canvas status
d3ma.setCanvas = function(canvas) {
	if(!canvas && typeof canvas !== 'object') {
		return d3ma.canvas;
	}
	d3ma.canvas.push(canvas);
};<commit_msg>manually update the d3.ma.js version to 0.2.1<commit_after>var d3ma = {version: '0.2.1'}; // semver;

// useful to figure out how many svg elements on the current page
// track individual .canvas element
// then retrieve cancas object, could call *draw* method to update its visualization
d3ma.canvas = [];

// getter & setter function
// set the canvas object into the d3ma.canvas array, used to redraw the chart
// optional param, if omit, it will simply retrieve the current d3ma.canvas status
d3ma.setCanvas = function(canvas) {
	if(!canvas && typeof canvas !== 'object') {
		return d3ma.canvas;
	}
	d3ma.canvas.push(canvas);
};
<|endoftext|>


<commit_before>;(function($){
	window.totalE = window.totalE || {};
    var $cache = {};
    $cache.window = $(window);
	$(document).ready(function (){
        $(document.images).on('dragstart', function(){
            return false;
        });
        $cache.main = $('#main');
        $cache.carbox = $('#main .carbox');
        $cache.carImg = $('.carImg', $cache.carbox);
        $cache.carbox.on('mouseover', function(e){
            var $self = $(this);
            $cache.carbox.removeClass('active');
            $self.addClass('active');
        });
        resize();
	});

    $(window).load(function(){
        $('#loading').remove();
    });

	$(window).resize(function() {
        resize();
	});

    function resize(){
        var nwindow = 1920 / 1080;
        var swindow = $cache.window.width() / $cache.window.height();
        if(nwindow > swindow){
            $cache.main.width($cache.window.height() * nwindow);
        }else{
            $cache.main.removeAttr('style');
        }
        var nimg = 640 / 1080;
        $cache.carImg.each(function(i){
            var $self = $(this);
            var $thisBox = $cache.carbox.eq(i);
            var boxW = $thisBox.width();
            var boxH = $thisBox.height();
            var thisH = boxW / nimg;
            var cssH = (boxH - thisH) / 2;
            $self.css({
                marginTop: cssH
            });
        });
    }

})(window.jQuery);<commit_msg>loadend<commit_after>;(function($){
	window.totalE = window.totalE || {};
    var $cache = {};
    $cache.window = $(window);
	$(document).ready(function (){
        $(document.images).on('dragstart', function(){
            return false;
        });
        $cache.main = $('#main');
        $cache.carbox = $('#main .carbox');
        $cache.carImg = $('.carImg', $cache.carbox);
        $cache.carbox.on('mouseover', function(e){
            var $self = $(this);
            $cache.carbox.removeClass('active');
            $self.addClass('active');
        });
        resize();
	});

    $(window).load(function(){
        $('#loading').hide(300);
    });

	$(window).resize(function() {
        resize();
	});

    function resize(){
        var nwindow = 1920 / 1080;
        var swindow = $cache.window.width() / $cache.window.height();
        if(nwindow > swindow){
            $cache.main.width($cache.window.height() * nwindow);
        }else{
            $cache.main.removeAttr('style');
        }
        var nimg = 640 / 1080;
        $cache.carImg.each(function(i){
            var $self = $(this);
            var $thisBox = $cache.carbox.eq(i);
            var boxW = $thisBox.width();
            var boxH = $thisBox.height();
            var thisH = boxW / nimg;
            var cssH = (boxH - thisH) / 2;
            $self.css({
                marginTop: cssH
            });
        });
    }

})(window.jQuery);<|endoftext|>


<commit_before>var gitallery = angular.module('gitallery',
  [ 'ngRoute', 'angularFileUpload' ]).

config(['$routeProvider', '$locationProvider',
  function($routeProvider, $locationProvider) {
  $routeProvider.
  when('/', {
    templateUrl: 'main',
    controller: 'MainController'
  }).
  when('/accounts', {
    templateUrl: 'accounts',
    controller: 'AccountsController'
  }).
  otherwise({
    title: '404 Page Not Found',
    templateUrl: '_404'
  });
  $locationProvider.html5Mode(false);
}]).

filter('filesize', function() {
  return function(size) {
    return filesize(size, { base: 2 });
  };
}).

directive('body', [function() {
  return {
    restrict: 'E',
    templateUrl: 'index'
  };
}]).

directive('navbarLink', ['$location', function($location) {
  return function(scope, element, attrs) {
    scope.$on('$routeChangeSuccess', function(event, current, previous) {
      var links = element.find('a');
      if (links.length === 0) return;
      var href = links.attr('href').replace(/^\/#!?/, '');
      var url = $location.url();
      if ((href === '/' && url === href) ||
        (href !== '/' && url.substr(0, href.length) === href)) {
        element.addClass('active');
      } else {
        element.removeClass('active');
      }
    });
  };
}]).

directive('uploader', ['$parse', function($parse) {
  return {
    restrict: 'E',
    template: '<input type="file">',
    replace: true,
    link: function($scope, elem, attrs, controller) {
      if (!attrs.model) return;
      $scope.$watchCollection(attrs.model, function(newModel) {
        if (newModel === undefined) return;
        if (!newModel || newModel.length === 0) elem.val('');
      });
      elem.bind('change', function() {
        $scope.$apply(function() {
          var files = [];
          for (var i = 0; i < elem[0].files.length; i++) {
            var file = elem[0].files[i];
            files.push({
              name: file.name,
              file: file,
              content: null,
              message: null,
              progress: 0
            });
          }
          $parse(attrs.model).assign($scope, files);
        });
      });
    }
  };
}]).

directive('fileObject', ['$parse', function($parse) {
  return {
    link: function($scope, elem, attrs, controller) {
      var reader = new FileReader();
      var file = $parse(attrs.fileObject)($scope);
      var content = $parse(attrs.fileObject + '.content');
      reader.onload = function() {
        var datauri = reader.result;
        var base64str = datauri.match(/^data:(.*?);base64,(.*)$/)[2];
        elem.attr('src', datauri);
        content.assign($scope, base64str);
      };
      reader.readAsDataURL(file.file);
    }
  };
}]).

service('GitHubAPI', ['$http', '$q', '$upload', 'Accounts',
  function($http, $q, $upload, Accounts) {
  var lS = window.localStorage;

  this.API = 'https://api.github.com';
  this.UserName = lS['username'];
  this.UserRepo = lS['userrepo'];
  this.headers = function() {
    return {
      "Authorization": "token " + Accounts.getCurrentAccount()
    };
  };

  this.GetRepositories = function() {
    var uri = [ this.API, 'user', 'repos' ];
    return $http.get(uri.join('/'), { headers: this.headers() });
  };
  this.GetContents = function(fileName) {
    var uri = [ this.API, 'repos', this.UserName, this.UserRepo, 'contents',
      fileName ];
    return $http.get(uri.join('/'), { headers: this.headers() });
  };
  this.UpdateFile = function(fileName, fileContent, message, fileSha) {
    var uri = [ this.API, 'repos', this.UserName, this.UserRepo, 'contents',
      fileName ];
    var data = {
      message: message,
      content: fileContent
    };
    if (fileSha) data['sha'] = fileSha;
    return $upload.http({
      url: uri.join('/'),
      method: 'PUT',
      headers: this.headers(),
      data: JSON.stringify(data)
    });
  };
  this.UploadFile = function(fileName, fileContent, message) {
    var self = this;
    return this.GetContents(fileName).then(function(response) {
      var fileSha = response.data.sha;
      return self.UpdateFile(fileName, fileContent, message, fileSha);
    }, function(response) {
      if (response.status === 404) {
        return self.UpdateFile(fileName, fileContent, message, null);
      }
      return $q.reject(response);
    });
  };
}]).

service('LocalStorage', ['$window', function($window) {
  return function(category, setValue) {
    try {
      var name = 'gitallery.' + category;
      if (setValue !== undefined) {
        if (setValue === null) {
          delete $window.localStorage[name];
        } else {
          $window.localStorage[name] = angular.toJson(setValue);
        }
      }
      return angular.fromJson($window.localStorage[name]);
    } catch(e) {}
    return null;
  };
}]).

service('Accounts', ['LocalStorage', function(LocalStorage) {
  this.getCurrentAccount = function() {
    return LocalStorage('accounts.active');
  };
}]).

controller('MainController', ['$scope', '$q', 'GitHubAPI',
  function($scope, $q, GitHubAPI) {
  $scope.defaultMessageForFileName = function(filename) {
    return 'Upload ' + filename + '.';
  };
  $scope.upload = function() {
    var files = $scope.files;
    if (!files || files.length === 0) {
      return alert('No files to upload!');
    }
    var deferred = $q.defer();
    var promise = deferred.promise;
    deferred.resolve();
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      var message = (file.message ||
        $scope.defaultMessageForFileName(file.name));
      var then = (function(file, message) {
        return function() {
          var deferred = $q.defer();
          GitHubAPI.UploadFile(file.name, file.content, message)
            .then(function(response) {
              deferred.resolve(response);
            }, function(response) {
              deferred.reject(response);
            }, function(event) {
              var progress = parseInt(100.0 * event.loaded / event.total);
              file.progress = Math.min(100, progress);
            });
          return deferred.promise;
        };
      })(file, message);
      promise = promise.then(then);
    }
    promise = promise.then(function() {
      console.log('come to an end', arguments);
    }, function() {
      console.log('come to an error', arguments);
    });
    promise['finally'](function() {
      $scope.files = null;
    });
  };
}]).

controller('AccountsController', ['$scope', '$window', 'LocalStorage',
  'GitHubAPI',
  function($scope, $window, LocalStorage, GitHubAPI) {

  var update = function() {
    $scope.accounts = LocalStorage('accounts');
    $scope.active = LocalStorage('accounts.active');
    GitHubAPI.GetRepositories().then(function(response) {
      $scope.repositories = response.data;
    }, function(){
      $scope.repositories = null;
    });
  };
  update();

  $scope.add = function() {
    var accounts = LocalStorage('accounts') || [];
    accounts.push({
      name: $scope.name,
      token: $scope.token
    });
    LocalStorage('accounts', accounts);
    update();
  };
  $scope.setActive = function(index) {
    var accounts = LocalStorage('accounts') || [];
    if (index > -1 && index < accounts.length) {
      LocalStorage('accounts.active', accounts[index].token);
      update();
    }
  };
}]).

run([function() {
  // end
}]);
<commit_msg>get all repos including repos from orgs;<commit_after>var gitallery = angular.module('gitallery',
  [ 'ngRoute', 'angularFileUpload' ]).

config(['$routeProvider', '$locationProvider',
  function($routeProvider, $locationProvider) {
  $routeProvider.
  when('/', {
    templateUrl: 'main',
    controller: 'MainController'
  }).
  when('/accounts', {
    templateUrl: 'accounts',
    controller: 'AccountsController'
  }).
  otherwise({
    title: '404 Page Not Found',
    templateUrl: '_404'
  });
  $locationProvider.html5Mode(false);
}]).

filter('filesize', function() {
  return function(size) {
    return filesize(size, { base: 2 });
  };
}).

directive('body', [function() {
  return {
    restrict: 'E',
    templateUrl: 'index'
  };
}]).

directive('navbarLink', ['$location', function($location) {
  return function(scope, element, attrs) {
    scope.$on('$routeChangeSuccess', function(event, current, previous) {
      var links = element.find('a');
      if (links.length === 0) return;
      var href = links.attr('href').replace(/^\/#!?/, '');
      var url = $location.url();
      if ((href === '/' && url === href) ||
        (href !== '/' && url.substr(0, href.length) === href)) {
        element.addClass('active');
      } else {
        element.removeClass('active');
      }
    });
  };
}]).

directive('uploader', ['$parse', function($parse) {
  return {
    restrict: 'E',
    template: '<input type="file">',
    replace: true,
    link: function($scope, elem, attrs, controller) {
      if (!attrs.model) return;
      $scope.$watchCollection(attrs.model, function(newModel) {
        if (newModel === undefined) return;
        if (!newModel || newModel.length === 0) elem.val('');
      });
      elem.bind('change', function() {
        $scope.$apply(function() {
          var files = [];
          for (var i = 0; i < elem[0].files.length; i++) {
            var file = elem[0].files[i];
            files.push({
              name: file.name,
              file: file,
              content: null,
              message: null,
              progress: 0
            });
          }
          $parse(attrs.model).assign($scope, files);
        });
      });
    }
  };
}]).

directive('fileObject', ['$parse', function($parse) {
  return {
    link: function($scope, elem, attrs, controller) {
      var reader = new FileReader();
      var file = $parse(attrs.fileObject)($scope);
      var content = $parse(attrs.fileObject + '.content');
      reader.onload = function() {
        var datauri = reader.result;
        var base64str = datauri.match(/^data:(.*?);base64,(.*)$/)[2];
        elem.attr('src', datauri);
        content.assign($scope, base64str);
      };
      reader.readAsDataURL(file.file);
    }
  };
}]).

service('GitHubAPI', ['$http', '$q', '$upload', 'Accounts',
  function($http, $q, $upload, Accounts) {
  var lS = window.localStorage;

  this.API = 'https://api.github.com';
  this.UserName = lS['username'];
  this.UserRepo = lS['userrepo'];
  this.headers = function() {
    return {
      "Authorization": "token " + Accounts.getCurrentAccount()
    };
  };

  this.GetRepositories = function() {
    var uri = [ this.API, 'user', 'repos' ];
    return $http.get(uri.join('/'), { headers: this.headers() });
  };
  this.GetAllRepositories = function() {
    var self = this;
    var deferred = $q.defer();
    var promises = [];
    promises.push(this.GetRepositories());
    this.GetOrganizations().then(function(response) {
      var orgs = response.data;
      for (var i = 0; i < orgs.length; i++) {
        promises.push(self.GetOrganizationRepositories(orgs[i].login));
      }
      deferred.resolve($q.all(promises));
    });
    return deferred.promise;
  };
  this.GetOrganizations = function() {
    var uri = [ this.API, 'user', 'orgs' ];
    return $http.get(uri.join('/'), { headers: this.headers() });
  };
  this.GetOrganizationRepositories = function(orgname) {
    var uri = [ this.API, 'orgs', orgname, 'repos' ];
    return $http.get(uri.join('/'), { headers: this.headers() });
  };
  this.GetContents = function(fileName) {
    var uri = [ this.API, 'repos', this.UserName, this.UserRepo, 'contents',
      fileName ];
    return $http.get(uri.join('/'), { headers: this.headers() });
  };
  this.UpdateFile = function(fileName, fileContent, message, fileSha) {
    var uri = [ this.API, 'repos', this.UserName, this.UserRepo, 'contents',
      fileName ];
    var data = {
      message: message,
      content: fileContent
    };
    if (fileSha) data['sha'] = fileSha;
    return $upload.http({
      url: uri.join('/'),
      method: 'PUT',
      headers: this.headers(),
      data: JSON.stringify(data)
    });
  };
  this.UploadFile = function(fileName, fileContent, message) {
    var self = this;
    return this.GetContents(fileName).then(function(response) {
      var fileSha = response.data.sha;
      return self.UpdateFile(fileName, fileContent, message, fileSha);
    }, function(response) {
      if (response.status === 404) {
        return self.UpdateFile(fileName, fileContent, message, null);
      }
      return $q.reject(response);
    });
  };
}]).

service('LocalStorage', ['$window', function($window) {
  return function(category, setValue) {
    try {
      var name = 'gitallery.' + category;
      if (setValue !== undefined) {
        if (setValue === null) {
          delete $window.localStorage[name];
        } else {
          $window.localStorage[name] = angular.toJson(setValue);
        }
      }
      return angular.fromJson($window.localStorage[name]);
    } catch(e) {}
    return null;
  };
}]).

service('Accounts', ['LocalStorage', function(LocalStorage) {
  this.getCurrentAccount = function() {
    return LocalStorage('accounts.active');
  };
}]).

controller('MainController', ['$scope', '$q', 'GitHubAPI',
  function($scope, $q, GitHubAPI) {
  $scope.defaultMessageForFileName = function(filename) {
    return 'Upload ' + filename + '.';
  };
  $scope.upload = function() {
    var files = $scope.files;
    if (!files || files.length === 0) {
      return alert('No files to upload!');
    }
    var deferred = $q.defer();
    var promise = deferred.promise;
    deferred.resolve();
    for (var i = 0; i < files.length; i++) {
      var file = files[i];
      var message = (file.message ||
        $scope.defaultMessageForFileName(file.name));
      var then = (function(file, message) {
        return function() {
          var deferred = $q.defer();
          GitHubAPI.UploadFile(file.name, file.content, message)
            .then(function(response) {
              deferred.resolve(response);
            }, function(response) {
              deferred.reject(response);
            }, function(event) {
              var progress = parseInt(100.0 * event.loaded / event.total);
              file.progress = Math.min(100, progress);
            });
          return deferred.promise;
        };
      })(file, message);
      promise = promise.then(then);
    }
    promise = promise.then(function() {
      console.log('come to an end', arguments);
    }, function() {
      console.log('come to an error', arguments);
    });
    promise['finally'](function() {
      $scope.files = null;
    });
  };
}]).

controller('AccountsController', ['$scope', '$window', 'LocalStorage',
  'GitHubAPI',
  function($scope, $window, LocalStorage, GitHubAPI) {

  var update = function() {
    $scope.accounts = LocalStorage('accounts');
    $scope.active = LocalStorage('accounts.active');
    GitHubAPI.GetAllRepositories().then(function(response) {
      var repositories = [];
      for (var i = 0; i < response.length; i++) {
        repositories = repositories.concat(response[i].data);
      }
      $scope.repositories = repositories;
    }, function(){
      $scope.repositories = null;
    });
  };
  update();

  $scope.add = function() {
    var accounts = LocalStorage('accounts') || [];
    accounts.push({
      name: $scope.name,
      token: $scope.token
    });
    LocalStorage('accounts', accounts);
    update();
  };
  $scope.setActive = function(index) {
    var accounts = LocalStorage('accounts') || [];
    if (index > -1 && index < accounts.length) {
      LocalStorage('accounts.active', accounts[index].token);
      update();
    }
  };
}]).

run([function() {
  // end
}]);
<|endoftext|>


<commit_before>/**
 * Created by JM Organization on 10.08.2017.
 */

function search_news(news, filter) {
    $('#article').each(function () {
        $('#article[data-article="'+news+'"]').show();
    });
}
<commit_msg>fixes<commit_after>/**
 * Created by JM Organization on 10.08.2017.
 */

function search_news(news, filter) {
    $('#article').each(function () {
        if ($(this).data('article').search(news) > 0) {
            $(this).show();
        } else {
            $(this).hide();
        }
    });
}
<|endoftext|>


<commit_before>$.fn.romoForm = function(givenSubmitElement) {
  return $.map(this, function(element) {
    return new RomoForm(element, givenSubmitElement)
  })
}

var RomoForm = function(element, givenSubmitElement) {
  this.elem = $(element)
  this.defaultSubmitElem = this.elem.find('button[type="submit"], input[type="submit"], [data-romo-form-submit="true"]')
  this.submitElem = $(givenSubmitElement || this.defaultSubmitElem)

  this.elem.on('keypress', $.proxy(this.onFormKeyPress, this))
  this.defaultSubmitElem.unbind('click')
  this.submitElem.unbind('click')
  this.submitElem.on('click', $.proxy(this.onSubmitClick, this))

  if (this.elem.data('romo-form-reload-page') === true) {
    this.elem.on('form:submitSuccess', function(e, data, form) {
      Romo.reloadPage()
    })
  }

  this.defaultListValuesDelim = ','

  this.removeEmptyGetParams = this.elem.data('romo-form-remove-empty-get-params')
  if (this.removeEmptyGetParams === undefined) {
    this.removeEmptyGetParams = true
  }

  this.decodeParams = this.elem.data('romo-form-decode-params')
  if (this.decodeParams === undefined) {
    this.decodeParams = true
  }

  this.doInit()
  this.elem.trigger('form:clearMsgs', [this])
  this.elem.trigger('form:ready', [this])
}

RomoForm.prototype.doInit = function() {
  // override as needed
}

RomoForm.prototype.onFormKeyPress = function(e) {
  var target = $(e.target)

  if(target.is(':not(TEXTAREA)') && e.which === 13 /* Enter */) {
    e.preventDefault()
    this.onSubmitClick()
  }
}

RomoForm.prototype.onSubmitClick = function(e) {
  if (e !== undefined) {
    e.preventDefault()
  }

  if (this.elem.hasClass('disabled') === false) {
    this.doSubmit()
  }
}

RomoForm.prototype.doSubmit = function() {
  this.elem.trigger('form:beforeSubmit', [this])

  if (this.elem.attr('method').toUpperCase() === 'GET') {
    this._doGetSubmit()
  } else {
    this._doNonGetSubmit()
  }
}

RomoForm.prototype.onSubmitSuccess = function(data, status, xhr) {
  this.elem.trigger('form:clearMsgs')
  this.elem.trigger('form:submitSuccess', [data, this])
}

RomoForm.prototype.onSubmitError = function(xhr, errorType, error) {
  this.elem.trigger('form:clearMsgs')

  if(xhr.status === 422) {
    this.elem.trigger('form:submitInvalidMsgs', [$.parseJSON(xhr.responseText), xhr, this])
  } else {
    this.elem.trigger('form:submitXhrError', [xhr, this])
  }
  this.elem.trigger('form:submitError', [xhr, this])
}

RomoForm.prototype._doGetSubmit = function() {
  var data = this._getSerializeObj()

  if (this.elem.data('romo-form-redirect-page') === true) {
    Romo.redirectPage(this.elem.attr('action') + '?' + Romo.param(data, {
      removeEmpty:  this.removeEmptyGetParams,
      decodeValues: this.decodeParams
    }))
  } else {
    this._doAjaxSubmit(data)
  }
}

RomoForm.prototype._doNonGetSubmit = function() {
  this._doAjaxSubmit(this._getFormData())
}

RomoForm.prototype._doAjaxSubmit = function(data) {
  $.ajax({
    url:         this.elem.attr('action'),
    type:        this.elem.attr('method'),
    dataType:    this._getXhrDataType(),
    data:        data,
    processData: false,
    contentType: false,
    success:     $.proxy(this.onSubmitSuccess, this),
    error:       $.proxy(this.onSubmitError, this)
  })
}

RomoForm.prototype._getFormData = function() {
  var formData = new FormData()

  $.each(this._getSerializeObj(), function(k, v){ formData.append(k, v) })
  $.each(this.elem.find('INPUT[type="file"]'), function(i, fileInput) {
    formData.append($(fileInput).attr('name'), fileInput.files)
  })

  return formData
}

RomoForm.prototype._getSerializeObj = function() {
  var listNamesDelims = this._getListValueInputNamesDelims()

  return this.elem.serializeArray().reduce(function(prev, curr) {
    if (listNamesDelims[curr.name] !== undefined) {
      prev[curr.name] = $.map([prev[curr.name], curr.value], function(v) {
        return v // $.map removes null/undefined vals, this acts like a compact function
      }).join(listNamesDelims[curr.name])
    } else if ($.isArray(prev[curr.name]) === true) {
      prev[curr.name].push(curr.value)
    } else if (prev[curr.name] !== undefined) {
      prev[curr.name] = [ prev[curr.name], curr.value ]
    } else {
      prev[curr.name] = curr.value
    }

    return prev
  }, {})
}

RomoForm.prototype._getListValueInputNamesDelims = function() {
  return $.map(this.elem.find('[data-romo-form-list-values="true"]'), function(item){
    return item // onverts the collection to an array
  }).reduce($.proxy(function(prev, curr) {
    prev[$(curr).attr('name')] = $(curr).data('romo-form-list-values-delim') || this.defaultListValuesDelim
    return prev
  }, this), {})
}

RomoForm.prototype._getXhrDataType = function() {
  if(this.elem.data('romo-form-xhr-data-type') !== undefined) {
    return this.elem.data('romo-form-xhr-data-type')
  } else {
    return 'json'
  }
}

Romo.onInitUI(function(e) {
  $(e.target).find('[data-romo-form-auto="true"]').romoForm()
})

<commit_msg>form: properly iterate and process file uploads<commit_after>$.fn.romoForm = function(givenSubmitElement) {
  return $.map(this, function(element) {
    return new RomoForm(element, givenSubmitElement)
  })
}

var RomoForm = function(element, givenSubmitElement) {
  this.elem = $(element)
  this.defaultSubmitElem = this.elem.find('button[type="submit"], input[type="submit"], [data-romo-form-submit="true"]')
  this.submitElem = $(givenSubmitElement || this.defaultSubmitElem)

  this.elem.on('keypress', $.proxy(this.onFormKeyPress, this))
  this.defaultSubmitElem.unbind('click')
  this.submitElem.unbind('click')
  this.submitElem.on('click', $.proxy(this.onSubmitClick, this))

  if (this.elem.data('romo-form-reload-page') === true) {
    this.elem.on('form:submitSuccess', function(e, data, form) {
      Romo.reloadPage()
    })
  }

  this.defaultListValuesDelim = ','

  this.removeEmptyGetParams = this.elem.data('romo-form-remove-empty-get-params')
  if (this.removeEmptyGetParams === undefined) {
    this.removeEmptyGetParams = true
  }

  this.decodeParams = this.elem.data('romo-form-decode-params')
  if (this.decodeParams === undefined) {
    this.decodeParams = true
  }

  this.doInit()
  this.elem.trigger('form:clearMsgs', [this])
  this.elem.trigger('form:ready', [this])
}

RomoForm.prototype.doInit = function() {
  // override as needed
}

RomoForm.prototype.onFormKeyPress = function(e) {
  var target = $(e.target)

  if(target.is(':not(TEXTAREA)') && e.which === 13 /* Enter */) {
    e.preventDefault()
    this.onSubmitClick()
  }
}

RomoForm.prototype.onSubmitClick = function(e) {
  if (e !== undefined) {
    e.preventDefault()
  }

  if (this.elem.hasClass('disabled') === false) {
    this.doSubmit()
  }
}

RomoForm.prototype.doSubmit = function() {
  this.elem.trigger('form:beforeSubmit', [this])

  if (this.elem.attr('method').toUpperCase() === 'GET') {
    this._doGetSubmit()
  } else {
    this._doNonGetSubmit()
  }
}

RomoForm.prototype.onSubmitSuccess = function(data, status, xhr) {
  this.elem.trigger('form:clearMsgs')
  this.elem.trigger('form:submitSuccess', [data, this])
}

RomoForm.prototype.onSubmitError = function(xhr, errorType, error) {
  this.elem.trigger('form:clearMsgs')

  if(xhr.status === 422) {
    this.elem.trigger('form:submitInvalidMsgs', [$.parseJSON(xhr.responseText), xhr, this])
  } else {
    this.elem.trigger('form:submitXhrError', [xhr, this])
  }
  this.elem.trigger('form:submitError', [xhr, this])
}

RomoForm.prototype._doGetSubmit = function() {
  var data = this._getSerializeObj()

  if (this.elem.data('romo-form-redirect-page') === true) {
    Romo.redirectPage(this.elem.attr('action') + '?' + Romo.param(data, {
      removeEmpty:  this.removeEmptyGetParams,
      decodeValues: this.decodeParams
    }))
  } else {
    this._doAjaxSubmit(data)
  }
}

RomoForm.prototype._doNonGetSubmit = function() {
  this._doAjaxSubmit(this._getFormData())
}

RomoForm.prototype._doAjaxSubmit = function(data) {
  $.ajax({
    url:         this.elem.attr('action'),
    type:        this.elem.attr('method'),
    dataType:    this._getXhrDataType(),
    data:        data,
    processData: false,
    contentType: false,
    success:     $.proxy(this.onSubmitSuccess, this),
    error:       $.proxy(this.onSubmitError, this)
  })
}

RomoForm.prototype._getFormData = function() {
  var formData = new FormData()

  $.each(this._getSerializeObj(), function(k, v){ formData.append(k, v) })
  $.each(this.elem.find('INPUT[type="file"]'), function(i, fileInput) {
    var attrName = $(fileInput).attr('name')
    $.each(fileInput.files, function(i, file) { formData.append(attrName, file) })
  })

  return formData
}

RomoForm.prototype._getSerializeObj = function() {
  var listNamesDelims = this._getListValueInputNamesDelims()

  return this.elem.serializeArray().reduce(function(prev, curr) {
    if (listNamesDelims[curr.name] !== undefined) {
      prev[curr.name] = $.map([prev[curr.name], curr.value], function(v) {
        return v // $.map removes null/undefined vals, this acts like a compact function
      }).join(listNamesDelims[curr.name])
    } else if ($.isArray(prev[curr.name]) === true) {
      prev[curr.name].push(curr.value)
    } else if (prev[curr.name] !== undefined) {
      prev[curr.name] = [ prev[curr.name], curr.value ]
    } else {
      prev[curr.name] = curr.value
    }

    return prev
  }, {})
}

RomoForm.prototype._getListValueInputNamesDelims = function() {
  return $.map(this.elem.find('[data-romo-form-list-values="true"]'), function(item){
    return item // onverts the collection to an array
  }).reduce($.proxy(function(prev, curr) {
    prev[$(curr).attr('name')] = $(curr).data('romo-form-list-values-delim') || this.defaultListValuesDelim
    return prev
  }, this), {})
}

RomoForm.prototype._getXhrDataType = function() {
  if(this.elem.data('romo-form-xhr-data-type') !== undefined) {
    return this.elem.data('romo-form-xhr-data-type')
  } else {
    return 'json'
  }
}

Romo.onInitUI(function(e) {
  $(e.target).find('[data-romo-form-auto="true"]').romoForm()
})

<|endoftext|>


<commit_before>var teammoldeApp = angular.module(
	"teammoldeApp",
	[
		'ngAnimate', 'ui.router'
	]
);
mangroveServerApp
.config(
[
'$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider)
{
	$urlRouterProvider
		.otherwise('/');

	$stateProvider
		.state('home', {
			url: '/',
			views: {
				"main": {
					templateUrl: '/partials/home.html'
				}
			}
		})

		.state('priser', {
			abstract: true,
			url: '/priser',
			views: {
				"main": {
					templateUrl: '/partials/priser.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('larere', {
			abstract: true,
			url: '/larere',
			views: {
				"main": {
					templateUrl: '/partials/larere.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('bestill', {
			abstract: true,
			url: '/bestill',
			views: {
				"main": {
					templateUrl: '/partials/bestill.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('manedensbestatt', {
			abstract: true,
			url: '/manedensbestatt',
			views: {
				"main": {
					templateUrl: '/partials/manedensbestatt.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('kontakt', {
			abstract: true,
			url: '/kontakt',
			views: {
				"main": {
					templateUrl: '/partials/kontakt.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})
	;

}
]
);

teammoldeApp
.controller('ContactCtrl',
[
'$scope',
function($scope) {
	$scope.id = '';

	$scope.change = function( name ) {
		if ( $scope.id === name ) {
			$scope.id = '';
		} else {
			$scope.id = name;
		}
	};

	$scope.isDeselected = function ( name ) {
		return $scope.id !== name && $scope.id != '';
	};

	$scope.isSelected = function ( name ) {
		return $scope.id === name;
	};
}
]
);
<commit_msg>proper app var name<commit_after>var teammoldeApp = angular.module(
	"teammoldeApp",
	[
		'ngAnimate', 'ui.router'
	]
);

teammoldeApp
.config(
[
'$stateProvider', '$urlRouterProvider',
function ($stateProvider, $urlRouterProvider)
{
	$urlRouterProvider
		.otherwise('/');

	$stateProvider
		.state('home', {
			url: '/',
			views: {
				"main": {
					templateUrl: '/partials/home.html'
				}
			}
		})

		.state('priser', {
			abstract: true,
			url: '/priser',
			views: {
				"main": {
					templateUrl: '/partials/priser.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('larere', {
			abstract: true,
			url: '/larere',
			views: {
				"main": {
					templateUrl: '/partials/larere.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('bestill', {
			abstract: true,
			url: '/bestill',
			views: {
				"main": {
					templateUrl: '/partials/bestill.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('manedensbestatt', {
			abstract: true,
			url: '/manedensbestatt',
			views: {
				"main": {
					templateUrl: '/partials/manedensbestatt.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})

		.state('kontakt', {
			abstract: true,
			url: '/kontakt',
			views: {
				"main": {
					templateUrl: '/partials/kontakt.html'
				},
				"header": {
					templateUrl: '/partials/header.html'
				}
			}
		})
	;

}
]
);

teammoldeApp
.controller('ContactCtrl',
[
'$scope',
function($scope) {
	$scope.id = '';

	$scope.change = function( name ) {
		if ( $scope.id === name ) {
			$scope.id = '';
		} else {
			$scope.id = name;
		}
	};

	$scope.isDeselected = function ( name ) {
		return $scope.id !== name && $scope.id != '';
	};

	$scope.isSelected = function ( name ) {
		return $scope.id === name;
	};
}
]
);
<|endoftext|>


<commit_before>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 * ======================================================================== */

(function($) {

  // Use this variable to set up the common and page specific functions. If you
  // rename this variable, you will also need to rename the namespace below.
  var Sage = {
    // All pages
    'common': {
      init: function() {
        // JavaScript to be fired on all pages
      },
      finalize: function() {
        // JavaScript to be fired on all pages, after page specific JS is fired
      }
    },
    // Home page
    'home': {
      init: function() {
        // JavaScript to be fired on the home page
      },
      finalize: function() {
        // JavaScript to be fired on the home page, after the init JS
      }
    },
    // About us page, note the change from about-us to about_us.
    'about_us': {
      init: function() {
        // JavaScript to be fired on the about us page
      }
    },
    'contact': {
      init: function() {
        // JavaScript to be fired on the about us page
        google.maps.event.addDomListener(window, 'load', init);
      }
    }
  };

  // Header
  var header = $('.header');
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 500) {
      header.addClass('slimmer');
    } else {
      header.removeClass('slimmer');
    }
  });

  // Home page slideshow
  $('.cycle-slideshow').cycle({
    slides: 'li',
    next: '.next',
    prev: '.prev',
    fx: 'scrollHorz',
    pager: '> .pager-container',
    pagerTemplate: ''
  });

  // Gallery
  $('.cycle-slideshow-gallery').cycle({
    slides: 'li',
    next: '.next',
    prev: '.prev',
    fx: 'scrollHorz',
    paused: true
  });

  // Client carousel
  $('.client-carousel').owlCarousel({
    stageElement: 'ul',
    itemElement: 'li',
    loop: true,
    nav: true,
    navText : ['', ''],
    autoplay: false,
    responsive: {
      0: { items: 1 },
      600: { items: 3 },
      1000: { items: 5 }
    }
  });

  // Mobile menu trigger
  var $menuTrigger = $('#main-menu-trigger'),
    $menu = $('.main-navigation'),
    activeClass = 'on-screen';

  $menuTrigger.on('click', function(e) {
    $(this).toggleClass('is-active');
    e.preventDefault();
    $menu.toggleClass(activeClass);
  });

  // Adds class of 'last-word' of main-heading
  $('.page-header.standard .main-heading').each(function(index, element) {
    var heading = $(element);
    var word_array, last_word, first_part;

    word_array = heading.html().split(/\s+/); // split on spaces
    last_word = word_array.pop();             // pop the last word
    first_part = word_array.join(' ');        // rejoin the first words together

    heading.html([first_part, ' ', last_word, ''].join(''));
  });

  var $container = $('.isotope').isotope({
    itemSelector: '.isotope-item'
  });
  $('.category-list').on( 'click', 'button', function() {
    var filterValue = $(this).data('filter');
    $('.category-list button').removeClass('is-active');
    if(!$(this).hasClass('is-active')) {
      $(this).addClass('is-active');
    }
    $container.isotope({ filter: filterValue });
  });

  $('.masonry').masonry({
    itemSelector: '.masonry-item',
    isOriginLeft: false
  });

  /**
   * Google Map
   */
  var map;
  function init() {
    var mapOptions = {
      center: new google.maps.LatLng(51.881154, 0.025315),
      zoom: 15,
      zoomControl: false,
      disableDoubleClickZoom: true,
      mapTypeControl: false,
      scaleControl: false,
      scrollwheel: false,
      panControl: false,
      streetViewControl: false,
      draggable: true,
      overviewMapControl: false,
      overviewMapControlOptions: {
        opened: false,
      },
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      styles: [{
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#d3d3d3"
        }]
      }, {
        "featureType": "transit",
        "stylers": [{
          "color": "#808080"
        }, {
          "visibility": "off"
        }]
      }, {
        "featureType": "road.highway",
        "elementType": "geometry.stroke",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#b3b3b3"
        }]
      }, {
        "featureType": "road.highway",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#ffffff"
        }]
      }, {
        "featureType": "road.local",
        "elementType": "geometry.fill",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#ffffff"
        }, {
          "weight": 1.8
        }]
      }, {
        "featureType": "road.local",
        "elementType": "geometry.stroke",
        "stylers": [{
          "color": "#d7d7d7"
        }]
      }, {
        "featureType": "poi",
        "elementType": "geometry.fill",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#ebebeb"
        }]
      }, {
        "featureType": "administrative",
        "elementType": "geometry",
        "stylers": [{
          "color": "#a7a7a7"
        }]
      }, {
        "featureType": "road.arterial",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#ffffff"
        }]
      }, {
        "featureType": "road.arterial",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#ffffff"
        }]
      }, {
        "featureType": "landscape",
        "elementType": "geometry.fill",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#efefef"
        }]
      }, {
        "featureType": "road",
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#696969"
        }]
      }, {
        "featureType": "administrative",
        "elementType": "labels.text.fill",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#737373"
        }]
      }, {
        "featureType": "poi",
        "elementType": "labels.icon",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "poi",
        "elementType": "labels",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "road.arterial",
        "elementType": "geometry.stroke",
        "stylers": [{
          "color": "#d6d6d6"
        }]
      }, {
        "featureType": "road",
        "elementType": "labels.icon",
        "stylers": [{
          "visibility": "off"
        }]
      }, {}, {
        "featureType": "poi",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#dadada"
        }]
      }],
    };
    var mapElement = document.getElementById('map');
    var map = new google.maps.Map(mapElement, mapOptions);
    var locations = [
      [
        'NOVO Construction',
        'undefined',
        'undefined',
        'undefined',
        'undefined',
        51.881154, 0.025315,
        'http://staging.novoconstruction.co.uk/wp-content/themes/novo-construction/dist/images/novo-pin.png'
      ]
    ];
    for (i = 0; i < locations.length; i++) {
      if (locations[i][1] === 'undefined') {
        description = '';
      } else {
        description = locations[i][1];
      }
      if (locations[i][2] === 'undefined') {
        telephone = '';
      } else {
        telephone = locations[i][2];
      }
      if (locations[i][3] === 'undefined') {
        email = '';
      } else {
        email = locations[i][3];
      }
      if (locations[i][4] === 'undefined') {
        web = '';
      } else {
        web = locations[i][4];
      }
      if (locations[i][7] === 'undefined') {
        markericon = '';
      } else {
        markericon = locations[i][7];
      }
      marker = new google.maps.Marker({
        icon: markericon,
        position: new google.maps.LatLng(locations[i][5], locations[i][6]),
        map: map,
        title: locations[i][0],
        desc: description,
        tel: telephone,
        email: email,
        web: web
      });
      link = '';
    }

  }

  // The routing fires all common scripts,
  // followed by the page specific scripts.
  // Add additional events for more control over timing e.g. a finalize event
  var UTIL = {
    fire: function(func, funcname, args) {
      var fire;
      var namespace = Sage;
      funcname = (funcname === undefined) ? 'init' : funcname;
      fire = func !== '';
      fire = fire && namespace[func];
      fire = fire && typeof namespace[func][funcname] === 'function';

      if (fire) {
        namespace[func][funcname](args);
      }
    },
    loadEvents: function() {
      // Fire common init JS
      UTIL.fire('common');

      // Fire page-specific init JS, and then finalize JS
      $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
        UTIL.fire(classnm);
        UTIL.fire(classnm, 'finalize');
      });

      // Fire common finalize JS
      UTIL.fire('common', 'finalize');
    }
  };

  // Load Events
  $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<commit_msg>Linked map pin to live site<commit_after>/* ========================================================================
 * DOM-based Routing
 * Based on http://goo.gl/EUTi53 by Paul Irish
 *
 * Only fires on body classes that match. If a body class contains a dash,
 * replace the dash with an underscore when adding it to the object below.
 *
 * .noConflict()
 * The routing is enclosed within an anonymous function so that you can
 * always reference jQuery with $, even when in .noConflict() mode.
 * ======================================================================== */

(function($) {

  // Use this variable to set up the common and page specific functions. If you
  // rename this variable, you will also need to rename the namespace below.
  var Sage = {
    // All pages
    'common': {
      init: function() {
        // JavaScript to be fired on all pages
      },
      finalize: function() {
        // JavaScript to be fired on all pages, after page specific JS is fired
      }
    },
    // Home page
    'home': {
      init: function() {
        // JavaScript to be fired on the home page
      },
      finalize: function() {
        // JavaScript to be fired on the home page, after the init JS
      }
    },
    // About us page, note the change from about-us to about_us.
    'about_us': {
      init: function() {
        // JavaScript to be fired on the about us page
      }
    },
    'contact': {
      init: function() {
        // JavaScript to be fired on the about us page
        google.maps.event.addDomListener(window, 'load', init);
      }
    }
  };

  // Header
  var header = $('.header');
  $(window).scroll(function() {
    var scroll = $(window).scrollTop();

    if (scroll >= 500) {
      header.addClass('slimmer');
    } else {
      header.removeClass('slimmer');
    }
  });

  // Home page slideshow
  $('.cycle-slideshow').cycle({
    slides: 'li',
    next: '.next',
    prev: '.prev',
    fx: 'scrollHorz',
    pager: '> .pager-container',
    pagerTemplate: ''
  });

  // Gallery
  $('.cycle-slideshow-gallery').cycle({
    slides: 'li',
    next: '.next',
    prev: '.prev',
    fx: 'scrollHorz',
    paused: true
  });

  // Client carousel
  $('.client-carousel').owlCarousel({
    stageElement: 'ul',
    itemElement: 'li',
    loop: true,
    nav: true,
    navText : ['', ''],
    autoplay: false,
    responsive: {
      0: { items: 1 },
      600: { items: 3 },
      1000: { items: 5 }
    }
  });

  // Mobile menu trigger
  var $menuTrigger = $('#main-menu-trigger'),
    $menu = $('.main-navigation'),
    activeClass = 'on-screen';

  $menuTrigger.on('click', function(e) {
    $(this).toggleClass('is-active');
    e.preventDefault();
    $menu.toggleClass(activeClass);
  });

  // Adds class of 'last-word' of main-heading
  $('.page-header.standard .main-heading').each(function(index, element) {
    var heading = $(element);
    var word_array, last_word, first_part;

    word_array = heading.html().split(/\s+/); // split on spaces
    last_word = word_array.pop();             // pop the last word
    first_part = word_array.join(' ');        // rejoin the first words together

    heading.html([first_part, ' ', last_word, ''].join(''));
  });

  var $container = $('.isotope').isotope({
    itemSelector: '.isotope-item'
  });
  $('.category-list').on( 'click', 'button', function() {
    var filterValue = $(this).data('filter');
    $('.category-list button').removeClass('is-active');
    if(!$(this).hasClass('is-active')) {
      $(this).addClass('is-active');
    }
    $container.isotope({ filter: filterValue });
  });

  $('.masonry').masonry({
    itemSelector: '.masonry-item',
    isOriginLeft: false
  });

  /**
   * Google Map
   */
  var map;
  function init() {
    var mapOptions = {
      center: new google.maps.LatLng(51.881154, 0.025315),
      zoom: 15,
      zoomControl: false,
      disableDoubleClickZoom: true,
      mapTypeControl: false,
      scaleControl: false,
      scrollwheel: false,
      panControl: false,
      streetViewControl: false,
      draggable: true,
      overviewMapControl: false,
      overviewMapControlOptions: {
        opened: false,
      },
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      styles: [{
        "featureType": "water",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#d3d3d3"
        }]
      }, {
        "featureType": "transit",
        "stylers": [{
          "color": "#808080"
        }, {
          "visibility": "off"
        }]
      }, {
        "featureType": "road.highway",
        "elementType": "geometry.stroke",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#b3b3b3"
        }]
      }, {
        "featureType": "road.highway",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#ffffff"
        }]
      }, {
        "featureType": "road.local",
        "elementType": "geometry.fill",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#ffffff"
        }, {
          "weight": 1.8
        }]
      }, {
        "featureType": "road.local",
        "elementType": "geometry.stroke",
        "stylers": [{
          "color": "#d7d7d7"
        }]
      }, {
        "featureType": "poi",
        "elementType": "geometry.fill",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#ebebeb"
        }]
      }, {
        "featureType": "administrative",
        "elementType": "geometry",
        "stylers": [{
          "color": "#a7a7a7"
        }]
      }, {
        "featureType": "road.arterial",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#ffffff"
        }]
      }, {
        "featureType": "road.arterial",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#ffffff"
        }]
      }, {
        "featureType": "landscape",
        "elementType": "geometry.fill",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#efefef"
        }]
      }, {
        "featureType": "road",
        "elementType": "labels.text.fill",
        "stylers": [{
          "color": "#696969"
        }]
      }, {
        "featureType": "administrative",
        "elementType": "labels.text.fill",
        "stylers": [{
          "visibility": "on"
        }, {
          "color": "#737373"
        }]
      }, {
        "featureType": "poi",
        "elementType": "labels.icon",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "poi",
        "elementType": "labels",
        "stylers": [{
          "visibility": "off"
        }]
      }, {
        "featureType": "road.arterial",
        "elementType": "geometry.stroke",
        "stylers": [{
          "color": "#d6d6d6"
        }]
      }, {
        "featureType": "road",
        "elementType": "labels.icon",
        "stylers": [{
          "visibility": "off"
        }]
      }, {}, {
        "featureType": "poi",
        "elementType": "geometry.fill",
        "stylers": [{
          "color": "#dadada"
        }]
      }],
    };
    var mapElement = document.getElementById('map');
    var map = new google.maps.Map(mapElement, mapOptions);
    var locations = [
      [
        'NOVO Construction',
        'undefined',
        'undefined',
        'undefined',
        'undefined',
        51.881154, 0.025315,
        'http://novoconstruction.co.uk/wp-content/themes/novo-construction/dist/images/novo-pin.png'
      ]
    ];
    for (i = 0; i < locations.length; i++) {
      if (locations[i][1] === 'undefined') {
        description = '';
      } else {
        description = locations[i][1];
      }
      if (locations[i][2] === 'undefined') {
        telephone = '';
      } else {
        telephone = locations[i][2];
      }
      if (locations[i][3] === 'undefined') {
        email = '';
      } else {
        email = locations[i][3];
      }
      if (locations[i][4] === 'undefined') {
        web = '';
      } else {
        web = locations[i][4];
      }
      if (locations[i][7] === 'undefined') {
        markericon = '';
      } else {
        markericon = locations[i][7];
      }
      marker = new google.maps.Marker({
        icon: markericon,
        position: new google.maps.LatLng(locations[i][5], locations[i][6]),
        map: map,
        title: locations[i][0],
        desc: description,
        tel: telephone,
        email: email,
        web: web
      });
      link = '';
    }

  }

  // The routing fires all common scripts,
  // followed by the page specific scripts.
  // Add additional events for more control over timing e.g. a finalize event
  var UTIL = {
    fire: function(func, funcname, args) {
      var fire;
      var namespace = Sage;
      funcname = (funcname === undefined) ? 'init' : funcname;
      fire = func !== '';
      fire = fire && namespace[func];
      fire = fire && typeof namespace[func][funcname] === 'function';

      if (fire) {
        namespace[func][funcname](args);
      }
    },
    loadEvents: function() {
      // Fire common init JS
      UTIL.fire('common');

      // Fire page-specific init JS, and then finalize JS
      $.each(document.body.className.replace(/-/g, '_').split(/\s+/), function(i, classnm) {
        UTIL.fire(classnm);
        UTIL.fire(classnm, 'finalize');
      });

      // Fire common finalize JS
      UTIL.fire('common', 'finalize');
    }
  };

  // Load Events
  $(document).ready(UTIL.loadEvents);

})(jQuery); // Fully reference jQuery after this point.
<|endoftext|>


<commit_before>(function() {

var GameComponent = {};
GameComponent.controller = function () {
  return {
    game: new Game({
      grid: new Grid({
        columnCount: 7,
        rowCount: 6
      })
    })
  };
};
GameComponent.view = function (ctrl) {
  return [
    m(GameControlsComponent, ctrl.game),
    m(GridComponent, ctrl.game)
  ];
};

var GameControlsComponent = {};
GameControlsComponent.controller = function () {
  return {
    startGame: function (game, playerCount) {
      game.startGame({playerCount: playerCount});
    },
    resetGame: function (game) {
      game.resetGame();
    }
  };
};
GameControlsComponent.view = function (ctrl, game) {
  return m('div', {id: 'game-controls'}, [
    game.players.length === 0 ? [
      // Initially ask user to choose number of players to start game
      m('label', 'Start Game:'),
      m('button', {onclick: _.partial(ctrl.startGame, game, 1)}, '1 Player'),
      m('button', {onclick: _.partial(ctrl.startGame, game, 2)}, '2 Players'),
      m('p', {id: 'game-message'}, 'Choose a number of players to start a game.')
    ] : [
      // If game is in progress, display the number of players are whose turn it
      // is (also provide an option to stop the game)
      m('label', (game.players[1].ai ? 1 : 2) + '-Player Game'),
      m('button', {onclick: _.partial(ctrl.resetGame, game)}, 'End Game'),
      m('p', {id: 'game-message'}, game.currentPlayer.ai ?
        'It\'s the AI\'s turn!'
        : ('It\'s player ' + game.currentPlayer.playerNum + '\'s turn!'))
    ]
  ]);
};

function Game(args) {
  this.grid = args.grid;
  this.players = [];
  // The current player is null when a game is not in progress
  this.currentPlayer = null;
  // Whether or not the game is in progress
  this.gameInProgress = false;
  // The chip above the grid that is about to be placed
  this.pendingChip = null;
  // Whether or not a chip is in the process of being placed on the grid
  this.pendingChipIsFalling = false;
  // The chip that was most recently placed in the board
  this.lastPlacedChip = null;
}
Game.prototype.startGame = function (args) {
  if (args.playerCount === 2) {
    // If 2-player game is selected, assume two human players
    this.players.push(new Player({color: 'red', playerNum: 1}));
    this.players.push(new Player({color: 'blue', playerNum: 2}));
  } else {
    // Otherwise, assume one human player and one AI player
    this.players.push(new Player({color: 'red', playerNum: 1}));
    // Set color of AI player to black to distinguish it from a human player
    this.players.push(new Player({color: 'black', playerNum: 2, ai: true}));
  }
  this.gameInProgress = true;
  this.currentPlayer = this.players[0];
  this.startTurn();
};
Game.prototype.startTurn = function () {
  this.pendingChip = new Chip({player: this.currentPlayer});
};
Game.prototype.resetGame = function (args) {
  this.gameInProgress = false;
  this.players.length = 0;
  this.currentPlayer = null;
  this.pendingChip = null;
  this.pendingChipIsFalling = false;
  this.lastPlacedChip = null;
  this.grid.resetGrid();
};

function Chip(args) {
  this.player = args.player;
}

function Player(args) {
  this.playerNum = args.playerNum;
  this.color = args.color;
  this.ai = !!args.ai;
}

function Grid(args) {
  this.columnCount = args.columnCount;
  this.rowCount = args.rowCount;
  // The columns array where columns containing placed chips are stored
  this.columns = [];
  this.resetGrid();
}
// Reset the grid by removing all placed chips
Grid.prototype.resetGrid = function () {
  this.columns.length = 0;
  for (var c = 0; c < this.columnCount; c += 1) {
    this.columns.push([]);
  }
};

var GridComponent = {};
GridComponent.controller = function () {
  return {
    // Get the left offset of the element (including its margin) relative to its
    // nearest non-static parent
    getOuterOffsetLeft: function (elem) {
        var marginLeft = parseInt(window.getComputedStyle(elem)['margin-left']);
        return elem.offsetLeft - marginLeft;
    },
    // Translate the pending chip to be aligned with whatever the user hovered
    // over (which is guaranteed to be either a chip, chip slot, or grid column)
    getPendingChipTranslate: function (ctrl, game, event) {
      if (game.pendingChip && !game.pendingChipIsFalling) {
        var pendingChipElem = event.currentTarget.querySelector('.chip.pending');
        // Ensure that the left margin of a chip or chip slot is included in the
        // offset measurement
        pendingChipElem.style.transform = 'translate(' + ctrl.getOuterOffsetLeft(event.target) + 'px,0)';
      }
    },
    placeChip: function (ctrl, game, event) {
      if (game.pendingChip && !game.pendingChipIsFalling) {
          game.pendingChipIsFalling = true;
          var pendingChipElem = event.currentTarget.querySelector('.chip.pending');
          var columnOffsetLeft = ctrl.getOuterOffsetLeft(event.target);
          // For testing, transition the chip down to an arbitrary slot in the
          // same column
          pendingChipElem.style.transform = 'translate(' + columnOffsetLeft + 'px,310px)';
      }
    }
  };
};
GridComponent.view = function (ctrl, game) {
  var grid = game.grid;
  return m('div', {
    id: 'grid',
    onmousemove: _.partial(ctrl.getPendingChipTranslate, ctrl, game),
    onclick: _.partial(ctrl.placeChip, ctrl, game)
  }, [
    // Area where to-be-placed chips are dropped from
    m('div', {id: 'pending-chip-zone'}, game.pendingChip ?
      m('div', {
        class: ['chip', 'pending', game.pendingChip.player.color, game.pendingChipIsFalling ? 'is-falling' : ''].join(' ')
      }) : null),
    // Bottom grid of slots (indicating space chips can occupy)
    m('div', {id: 'chip-slots'}, _.times(grid.columnCount, function (c) {
      return m('div', {class: 'grid-column'}, _.times(grid.rowCount, function (r) {
        return m('div', {class: 'chip-slot'});
      }));
    })),
    // Top grid of placed chips
    m('div', {id: 'chips'}, _.times(grid.columnCount, function (c) {
      return m('div', {class: 'grid-column'}, _.map(grid.columns[c], function (chip, r) {
        return m('div', {class: ['chip', chip.player.color].join(' ')});
      }));
    }))
  ]);
};

m.mount(document.getElementById('game'), GameComponent);

}());
<commit_msg>Move translate-setting logic into dedicated function<commit_after>(function() {

var GameComponent = {};
GameComponent.controller = function () {
  return {
    game: new Game({
      grid: new Grid({
        columnCount: 7,
        rowCount: 6
      })
    })
  };
};
GameComponent.view = function (ctrl) {
  return [
    m(GameControlsComponent, ctrl.game),
    m(GridComponent, ctrl.game)
  ];
};

var GameControlsComponent = {};
GameControlsComponent.controller = function () {
  return {
    startGame: function (game, playerCount) {
      game.startGame({playerCount: playerCount});
    },
    resetGame: function (game) {
      game.resetGame();
    }
  };
};
GameControlsComponent.view = function (ctrl, game) {
  return m('div', {id: 'game-controls'}, [
    game.players.length === 0 ? [
      // Initially ask user to choose number of players to start game
      m('label', 'Start Game:'),
      m('button', {onclick: _.partial(ctrl.startGame, game, 1)}, '1 Player'),
      m('button', {onclick: _.partial(ctrl.startGame, game, 2)}, '2 Players'),
      m('p', {id: 'game-message'}, 'Choose a number of players to start a game.')
    ] : [
      // If game is in progress, display the number of players are whose turn it
      // is (also provide an option to stop the game)
      m('label', (game.players[1].ai ? 1 : 2) + '-Player Game'),
      m('button', {onclick: _.partial(ctrl.resetGame, game)}, 'End Game'),
      m('p', {id: 'game-message'}, game.currentPlayer.ai ?
        'It\'s the AI\'s turn!'
        : ('It\'s player ' + game.currentPlayer.playerNum + '\'s turn!'))
    ]
  ]);
};

function Game(args) {
  this.grid = args.grid;
  this.players = [];
  // The current player is null when a game is not in progress
  this.currentPlayer = null;
  // Whether or not the game is in progress
  this.gameInProgress = false;
  // The chip above the grid that is about to be placed
  this.pendingChip = null;
  // Whether or not a chip is in the process of being placed on the grid
  this.pendingChipIsFalling = false;
  // The chip that was most recently placed in the board
  this.lastPlacedChip = null;
}
Game.prototype.startGame = function (args) {
  if (args.playerCount === 2) {
    // If 2-player game is selected, assume two human players
    this.players.push(new Player({color: 'red', playerNum: 1}));
    this.players.push(new Player({color: 'blue', playerNum: 2}));
  } else {
    // Otherwise, assume one human player and one AI player
    this.players.push(new Player({color: 'red', playerNum: 1}));
    // Set color of AI player to black to distinguish it from a human player
    this.players.push(new Player({color: 'black', playerNum: 2, ai: true}));
  }
  this.gameInProgress = true;
  this.currentPlayer = this.players[0];
  this.startTurn();
};
Game.prototype.startTurn = function () {
  this.pendingChip = new Chip({player: this.currentPlayer});
};
Game.prototype.resetGame = function (args) {
  this.gameInProgress = false;
  this.players.length = 0;
  this.currentPlayer = null;
  this.pendingChip = null;
  this.pendingChipIsFalling = false;
  this.lastPlacedChip = null;
  this.grid.resetGrid();
};

function Chip(args) {
  this.player = args.player;
}

function Player(args) {
  this.playerNum = args.playerNum;
  this.color = args.color;
  this.ai = !!args.ai;
}

function Grid(args) {
  this.columnCount = args.columnCount;
  this.rowCount = args.rowCount;
  // The columns array where columns containing placed chips are stored
  this.columns = [];
  this.resetGrid();
}
// Reset the grid by removing all placed chips
Grid.prototype.resetGrid = function () {
  this.columns.length = 0;
  for (var c = 0; c < this.columnCount; c += 1) {
    this.columns.push([]);
  }
};

var GridComponent = {};
GridComponent.controller = function () {
  return {
    // Set the CSS transform value for the given DOM element
    setTranslate: function (elem, coords) {
      elem.style.transform = 'translate(' + coords.x + 'px,' + coords.y + 'px)';
    },
    // Get the left offset of the element (including its margin) relative to its
    // nearest non-static parent
    getOuterOffsetLeft: function (elem) {
        var marginLeft = parseInt(window.getComputedStyle(elem)['margin-left']);
        return elem.offsetLeft - marginLeft;
    },
    // Translate the pending chip to be aligned with whatever the user hovered
    // over (which is guaranteed to be either a chip, chip slot, or grid column)
    getPendingChipTranslate: function (ctrl, game, event) {
      if (game.pendingChip && !game.pendingChipIsFalling) {
        var pendingChipElem = event.currentTarget.querySelector('.chip.pending');
        // Ensure that the left margin of a chip or chip slot is included in the
        // offset measurement
        ctrl.setTranslate(pendingChipElem, {
          x: ctrl.getOuterOffsetLeft(event.target),
          y: 0
        });
      }
    },
    placeChip: function (ctrl, game, event) {
      if (game.pendingChip && !game.pendingChipIsFalling) {
          game.pendingChipIsFalling = true;
          var pendingChipElem = event.currentTarget.querySelector('.chip.pending');
          // For testing, transition the chip down to an arbitrary slot in the
          // same column
          ctrl.setTranslate(pendingChipElem, {
            x: ctrl.getOuterOffsetLeft(event.target),
            y: 310
          });
      }
    }
  };
};
GridComponent.view = function (ctrl, game) {
  var grid = game.grid;
  return m('div', {
    id: 'grid',
    onmousemove: _.partial(ctrl.getPendingChipTranslate, ctrl, game),
    onclick: _.partial(ctrl.placeChip, ctrl, game)
  }, [
    // Area where to-be-placed chips are dropped from
    m('div', {id: 'pending-chip-zone'}, game.pendingChip ?
      m('div', {
        class: ['chip', 'pending', game.pendingChip.player.color, game.pendingChipIsFalling ? 'is-falling' : ''].join(' ')
      }) : null),
    // Bottom grid of slots (indicating space chips can occupy)
    m('div', {id: 'chip-slots'}, _.times(grid.columnCount, function (c) {
      return m('div', {class: 'grid-column'}, _.times(grid.rowCount, function (r) {
        return m('div', {class: 'chip-slot'});
      }));
    })),
    // Top grid of placed chips
    m('div', {id: 'chips'}, _.times(grid.columnCount, function (c) {
      return m('div', {class: 'grid-column'}, _.map(grid.columns[c], function (chip, r) {
        return m('div', {class: ['chip', chip.player.color].join(' ')});
      }));
    }))
  ]);
};

m.mount(document.getElementById('game'), GameComponent);

}());
<|endoftext|>