<commit_before>/* JavaScript for simple project
 */

var globals = {
    scrollValInit: 40,
    didScroll: '',
    eventType: 'click'
};

var helpers = {

    // Uniwersal hider
    // ============================================================
    hider: function (targetToHide, triggerNode, e) {
        var receivedTargetToHide = targetToHide;
        var _hiderFunc = function (e) {
            var targetToHide = function () {
                var slector = document.querySelectorAll(receivedTargetToHide);
                for (var i = 0; i < slector.length; i++) {
                    if (slector[i].classList.contains('active')) {
                        return slector[i];
                    }
                }
            }();

            if (targetToHide === undefined) {
                document.removeEventListener('mouseup', _hiderFunc, false);
                return false
            }

            // Hide element
            if (!(targetToHide === e.target)             // if the target of the click isn't the container...
                && !(targetToHide.contains(e.target))    // ... nor a descendant of the container
                && !(triggerNode === e.target)           // ... nor a trigger of the container
                && !(triggerNode.contains(e.target))     // ... nor a container contain trigger
            ) {
                targetToHide.classList.remove('active');
                triggerNode.classList.remove('active');
            }
        };

        document.addEventListener('mouseup', _hiderFunc, false);
    },

    // Debounce is needed for performance improvments for scroll & resize events
    // ============================================================
    debounce: function (func, wait, immediate) {
        var timeout;
        return function () {
            var context = this, args = arguments;
            var later = function () {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    },

    // GET USER OS, BROWSER & SCREEN
    // ============================================================
    userEnvironment: function () {

        var userOS = '';
        var userBrowser = '';

        getDeviceSize = function () {
            var htmlTag = document.getElementsByTagName('html')[0];
            var deviceSize = window.getComputedStyle(
                document.querySelector('html'), ':after' // Magic!
            ).getPropertyValue('content').slice(1, -1);

            htmlTag.setAttribute('data-device-size', deviceSize);
            return deviceSize;
        };

        // Get user's mobile data
        var mobile = {

            isPhone: function () {

            },

            isTablet: function () {

            }
        };

        // Get user's system
        var system = function () {
            if (navigator.appVersion.indexOf("Win") != -1) userOS = "windows";
            if (navigator.appVersion.indexOf("Mac") != -1) userOS = "mac";
            if (navigator.userAgent.match(/Mobi/)) userOS = "mobile";

            document.documentElement.setAttribute('data-os', userOS);
            return userOS;
        };

        // Get user's browser
        var browser = function () {
            //console.log(navigator.appVersion);
            if (navigator.appVersion.indexOf("MSIE") != -1) userBrowser = "oldIE"; // IE =< 10

            document.documentElement.setAttribute('data-browser', userBrowser);
        };

        return {
            getDeviceSize: getDeviceSize(),
            isPhone: mobile.isPhone(),
            isTablet: mobile.isTablet(),
            system: system(),
            browser: browser()
        };
    }
};

// ---------------------------------------------------------
// Page events
// ---------------------------------------------------------
var pageEvents = {

    collection: function () {

        // Events only for mobile devices!
        if (helpers.userEnvironment.system === 'mobile') {
            console.log('pageTools.collection for mobile');
        }

        // a lot of events goes here
    },

    someEvent: function () {
        // event code
    },

    init: function () {
        this.collection();
        this.someEvent();
    }
};

// ---------------------------------------------------------
// Page tools
// ---------------------------------------------------------
var pageTools = {

    /*
     Common js trigger, do something with target
     "data-js-trigger" is a namespace for synchronized actions,
     in "data-js-target" please precise class or id of target,
     "data-js-target" can get additional attribute called "parent"
     example use:
     */
    pullTheTrigger: function () {
        $('[data-js-trigger]').on(globals.eventType, function () {
            var triggerNode = this;
            var triggerTarget = triggerNode.getAttribute("data-js-target");
            var triggerData = triggerNode.getAttribute("data-js-trigger");

            if (triggerTarget) {
                var triggerTargetArray = triggerTarget.split(/[\s,]+/); // comas and trim
            } else {
                console.warn('pullTheTrigger: clicked element missed attr "data-js-target"');
                return false
            }

            // check if namespace for trigger is defined
            if (triggerData) {
                var triggerDataArr = document.querySelectorAll('[data-js-trigger=' + triggerData + ']');
                for (var i = 0; i < triggerDataArr.length; i++) {
                    triggerDataArr[i].classList.toggle('active');
                }
            }

            // check if triggerTarget is for parent only (use second attribute "parent")
            if (triggerTargetArray.indexOf('parent') > -1) {
                triggerTarget = triggerTargetArray[0];
                $(triggerNode).closest(triggerTarget).toggleClass('active');
                //trigger.closest(triggerTarget).classList.toggle('active'); // Future js
            } else {
                document.querySelector(triggerTarget).classList.toggle('active');
            }

            helpers.hider(triggerTarget, triggerNode);
        });
    },

    somePublicMethod: function () {

    },

    init: function () {
        this.pullTheTrigger();
        this.somePublicMethod();
    }
};

// ---------------------------------------------------------
// SPECIFIC PLUGINS
// ---------------------------------------------------------
var vendors = {

    // Slick
    slick: function () {
        //slick configuration goes here
    },

    init: function () {
        this.slick();
    }
};

// ---------------------------------------------------------
// WHEN WINDOW SCROLL
// ---------------------------------------------------------
window.addEventListener('scroll', function () {
    helpers.debounce(function () {

        // Set of function initialized on page scroll:
        pageEvents.someEvent();

    }, 250)();
});

// ---------------------------------------------------------
// WHEN WINDOW RESIZE
// ---------------------------------------------------------
window.addEventListener('resize', function () {
    helpers.debounce(function () {

        // Set of function initialized on page scroll:
        helpers.userEnvironment();

    }, 250)();
});

// ---------------------------------------------------------
// WHEN DOCUMENT READY
// ---------------------------------------------------------
document.addEventListener('DOMContentLoaded', function () {
    helpers.userEnvironment();
    pageEvents.init();
    pageTools.init();
    vendors.init();
}, false);<commit_msg>userEnvironment function call fix<commit_after>/* JavaScript for simple project
 */

var globals = {
    scrollValInit: 40,
    didScroll: '',
    eventType: 'click'
};

var helpers = {

    // Uniwersal hider
    // ============================================================
    hider: function (targetToHide, triggerNode, e) {
        var receivedTargetToHide = targetToHide;
        var _hiderFunc = function (e) {
            var targetToHide = function () {
                var slector = document.querySelectorAll(receivedTargetToHide);
                for (var i = 0; i < slector.length; i++) {
                    if (slector[i].classList.contains('active')) {
                        return slector[i];
                    }
                }
            }();

            if (targetToHide === undefined) {
                document.removeEventListener('mouseup', _hiderFunc, false);
                return false
            }

            // Hide element
            if (!(targetToHide === e.target)             // if the target of the click isn't the container...
                && !(targetToHide.contains(e.target))    // ... nor a descendant of the container
                && !(triggerNode === e.target)           // ... nor a trigger of the container
                && !(triggerNode.contains(e.target))     // ... nor a container contain trigger
            ) {
                targetToHide.classList.remove('active');
                triggerNode.classList.remove('active');
            }
        };

        document.addEventListener('mouseup', _hiderFunc, false);
    },

    // Debounce is needed for performance improvments for scroll & resize events
    // ============================================================
    debounce: function (func, wait, immediate) {
        var timeout;
        return function () {
            var context = this, args = arguments;
            var later = function () {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    },

    // GET USER OS, BROWSER & SCREEN
    // ============================================================
    userEnvironment: function () {

        var userOS = '';
        var userBrowser = '';

        getDeviceSize = function () {
            var htmlTag = document.getElementsByTagName('html')[0];
            var deviceSize = window.getComputedStyle(
                document.querySelector('html'), ':after' // Magic!
            ).getPropertyValue('content').slice(1, -1);

            htmlTag.setAttribute('data-device-size', deviceSize);
            return deviceSize;
        };

        // Get user's mobile data
        var mobile = {

            isPhone: function () {

            },

            isTablet: function () {

            }
        };

        // Get user's system
        var system = function () {
            if (navigator.appVersion.indexOf("Win") != -1) userOS = "windows";
            if (navigator.appVersion.indexOf("Mac") != -1) userOS = "mac";
            if (navigator.userAgent.match(/Mobi/)) userOS = "mobile";

            document.documentElement.setAttribute('data-os', userOS);
            return userOS;
        };

        // Get user's browser
        var browser = function () {
            //console.log(navigator.appVersion);
            if (navigator.appVersion.indexOf("MSIE") != -1) userBrowser = "oldIE"; // IE =< 10

            document.documentElement.setAttribute('data-browser', userBrowser);
        };

        return {
            getDeviceSize: getDeviceSize(),
            isPhone: mobile.isPhone(),
            isTablet: mobile.isTablet(),
            system: system(),
            browser: browser()
        };
    }
};

// ---------------------------------------------------------
// Page events
// ---------------------------------------------------------
var pageEvents = {

    collection: function () {

        // Events only for mobile devices!
        if (helpers.userEnvironment().system === 'mobile') {
            console.log('pageTools.collection for mobile');
        }

        // a lot of events goes here
    },

    someEvent: function () {
        // event code
    },

    init: function () {
        this.collection();
        this.someEvent();
    }
};

// ---------------------------------------------------------
// Page tools
// ---------------------------------------------------------
var pageTools = {

    /*
     Common js trigger, do something with target
     "data-js-trigger" is a namespace for synchronized actions,
     in "data-js-target" please precise class or id of target,
     "data-js-target" can get additional attribute called "parent"
     example use:
     */
    pullTheTrigger: function () {
        $('[data-js-trigger]').on(globals.eventType, function () {
            var triggerNode = this;
            var triggerTarget = triggerNode.getAttribute("data-js-target");
            var triggerData = triggerNode.getAttribute("data-js-trigger");

            if (triggerTarget) {
                var triggerTargetArray = triggerTarget.split(/[\s,]+/); // comas and trim
            } else {
                console.warn('pullTheTrigger: clicked element missed attr "data-js-target"');
                return false
            }

            // check if namespace for trigger is defined
            if (triggerData) {
                var triggerDataArr = document.querySelectorAll('[data-js-trigger=' + triggerData + ']');
                for (var i = 0; i < triggerDataArr.length; i++) {
                    triggerDataArr[i].classList.toggle('active');
                }
            }

            // check if triggerTarget is for parent only (use second attribute "parent")
            if (triggerTargetArray.indexOf('parent') > -1) {
                triggerTarget = triggerTargetArray[0];
                $(triggerNode).closest(triggerTarget).toggleClass('active');
                //trigger.closest(triggerTarget).classList.toggle('active'); // Future js
            } else {
                document.querySelector(triggerTarget).classList.toggle('active');
            }

            helpers.hider(triggerTarget, triggerNode);
        });
    },

    somePublicMethod: function () {

    },

    init: function () {
        this.pullTheTrigger();
        this.somePublicMethod();
    }
};

// ---------------------------------------------------------
// SPECIFIC PLUGINS
// ---------------------------------------------------------
var vendors = {

    // Slick
    slick: function () {
        //slick configuration goes here
    },

    init: function () {
        this.slick();
    }
};

// ---------------------------------------------------------
// WHEN WINDOW SCROLL
// ---------------------------------------------------------
window.addEventListener('scroll', function () {
    helpers.debounce(function () {

        // Set of function initialized on page scroll:
        pageEvents.someEvent();

    }, 250)();
});

// ---------------------------------------------------------
// WHEN WINDOW RESIZE
// ---------------------------------------------------------
window.addEventListener('resize', function () {
    helpers.debounce(function () {

        // Set of function initialized on page scroll:
        helpers.userEnvironment();

    }, 250)();
});

// ---------------------------------------------------------
// WHEN DOCUMENT READY
// ---------------------------------------------------------
document.addEventListener('DOMContentLoaded', function () {
    helpers.userEnvironment();
    pageEvents.init();
    pageTools.init();
    vendors.init();
}, false);
<|endoftext|>


<commit_before>/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox()
 *  })
 *
 *  Terms
 *    Loads the #terms div in the box
 *
 *  Terms
 *    Loads the terms.html page in the box
 *
 *  Terms
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 *
 *    jQuery.facebox('some html')
 *    jQuery.facebox('some html', 'my-groovy-style')
 *
 *  The above will open a facebox with "some html" as the content.
 *
 *    jQuery.facebox(function($) {
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page, an image, or the contents of a div:
 *
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style')
 *    jQuery.facebox({ image: 'stairs.jpg' })
 *    jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style')
 *    jQuery.facebox({ div: '#box' })
 *    jQuery.facebox({ div: '#box' }, 'my-groovy-style')
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax, klass)
    else if (data.image) fillFaceboxFromImage(data.image, klass)
    else if (data.div) fillFaceboxFromHref(data.div, klass)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0.2,
      overlay      : true,
      loadingImage : '/facebox/loading.gif',
      closeImage   : '/facebox/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\

 \

 \

 \

 \

 \

 \

'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('

')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	$(window).width() / 2 - 205
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox table').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    if ($(this).length == 0) return

    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.bind('click.facebox', clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }

  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      if (target == '#') return
      $.facebox.reveal($(target).html(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('

', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('#facebox_overlay').length == 0)
      $("body").append('

')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide")
      $("#facebox_overlay").remove()
    })

    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);
<commit_msg>Use new HTML to center<commit_after>/*
 * Facebox (for jQuery)
 * version: 1.2 (05/05/2008)
 * @requires jQuery v1.2 or later
 *
 * Examples at http://famspam.com/facebox/
 *
 * Licensed under the MIT:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2007, 2008 Chris Wanstrath [ chris@ozmm.org ]
 *
 * Usage:
 *
 *  jQuery(document).ready(function() {
 *    jQuery('a[rel*=facebox]').facebox()
 *  })
 *
 *  Terms
 *    Loads the #terms div in the box
 *
 *  Terms
 *    Loads the terms.html page in the box
 *
 *  Terms
 *    Loads the terms.png image in the box
 *
 *
 *  You can also use it programmatically:
 *
 *    jQuery.facebox('some html')
 *    jQuery.facebox('some html', 'my-groovy-style')
 *
 *  The above will open a facebox with "some html" as the content.
 *
 *    jQuery.facebox(function($) {
 *      $.get('blah.html', function(data) { $.facebox(data) })
 *    })
 *
 *  The above will show a loading screen before the passed function is called,
 *  allowing for a better ajaxy experience.
 *
 *  The facebox function can also display an ajax page, an image, or the contents of a div:
 *
 *    jQuery.facebox({ ajax: 'remote.html' })
 *    jQuery.facebox({ ajax: 'remote.html' }, 'my-groovy-style')
 *    jQuery.facebox({ image: 'stairs.jpg' })
 *    jQuery.facebox({ image: 'stairs.jpg' }, 'my-groovy-style')
 *    jQuery.facebox({ div: '#box' })
 *    jQuery.facebox({ div: '#box' }, 'my-groovy-style')
 *
 *  Want to close the facebox?  Trigger the 'close.facebox' document event:
 *
 *    jQuery(document).trigger('close.facebox')
 *
 *  Facebox also has a bunch of other hooks:
 *
 *    loading.facebox
 *    beforeReveal.facebox
 *    reveal.facebox (aliased as 'afterReveal.facebox')
 *    init.facebox
 *
 *  Simply bind a function to any of these hooks:
 *
 *   $(document).bind('reveal.facebox', function() { ...stuff to do after the facebox and contents are revealed... })
 *
 */
(function($) {
  $.facebox = function(data, klass) {
    $.facebox.loading()

    if (data.ajax) fillFaceboxFromAjax(data.ajax, klass)
    else if (data.image) fillFaceboxFromImage(data.image, klass)
    else if (data.div) fillFaceboxFromHref(data.div, klass)
    else if ($.isFunction(data)) data.call($)
    else $.facebox.reveal(data, klass)
  }

  /*
   * Public, $.facebox methods
   */

  $.extend($.facebox, {
    settings: {
      opacity      : 0.2,
      overlay      : true,
      loadingImage : '/facebox/loading.gif',
      closeImage   : '/facebox/closelabel.gif',
      imageTypes   : [ 'png', 'jpg', 'jpeg', 'gif' ],
      faceboxHtml  : '\

 \

 \

 \

 \

 \

 \

'
    },

    loading: function() {
      init()
      if ($('#facebox .loading').length == 1) return true
      showOverlay()

      $('#facebox .content').empty()
      $('#facebox .body').children().hide().end().
        append('

')

      $('#facebox').css({
        top:	getPageScroll()[1] + (getPageHeight() / 10),
        left:	$(window).width() / 2 - 205
      }).show()

      $(document).bind('keydown.facebox', function(e) {
        if (e.keyCode == 27) $.facebox.close()
        return true
      })
      $(document).trigger('loading.facebox')
    },

    reveal: function(data, klass) {
      $(document).trigger('beforeReveal.facebox')
      if (klass) $('#facebox .content').addClass(klass)
      $('#facebox .content').append(data)
      $('#facebox .loading').remove()
      $('#facebox .body').children().fadeIn('normal')
      $('#facebox').css('left', $(window).width() / 2 - ($('#facebox .popup').width() / 2))
      $(document).trigger('reveal.facebox').trigger('afterReveal.facebox')
    },

    close: function() {
      $(document).trigger('close.facebox')
      return false
    }
  })

  /*
   * Public, $.fn methods
   */

  $.fn.facebox = function(settings) {
    if ($(this).length == 0) return

    init(settings)

    function clickHandler() {
      $.facebox.loading(true)

      // support for rel="facebox.inline_popup" syntax, to add a class
      // also supports deprecated "facebox[.inline_popup]" syntax
      var klass = this.rel.match(/facebox\[?\.(\w+)\]?/)
      if (klass) klass = klass[1]

      fillFaceboxFromHref(this.href, klass)
      return false
    }

    return this.bind('click.facebox', clickHandler)
  }

  /*
   * Private methods
   */

  // called one time to setup facebox on this page
  function init(settings) {
    if ($.facebox.settings.inited) return true
    else $.facebox.settings.inited = true

    $(document).trigger('init.facebox')
    makeCompatible()

    var imageTypes = $.facebox.settings.imageTypes.join('|')
    $.facebox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i')

    if (settings) $.extend($.facebox.settings, settings)
    $('body').append($.facebox.settings.faceboxHtml)

    var preload = [ new Image(), new Image() ]
    preload[0].src = $.facebox.settings.closeImage
    preload[1].src = $.facebox.settings.loadingImage

    $('#facebox').find('.b:first, .bl').each(function() {
      preload.push(new Image())
      preload.slice(-1).src = $(this).css('background-image').replace(/url\((.+)\)/, '$1')
    })

    $('#facebox .close').click($.facebox.close)
    $('#facebox .close_image').attr('src', $.facebox.settings.closeImage)
  }

  // getPageScroll() by quirksmode.com
  function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
  }

  // Adapted from getPageSize() by quirksmode.com
  function getPageHeight() {
    var windowHeight
    if (self.innerHeight) {	// all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
  }

  // Backwards compatibility
  function makeCompatible() {
    var $s = $.facebox.settings

    $s.loadingImage = $s.loading_image || $s.loadingImage
    $s.closeImage = $s.close_image || $s.closeImage
    $s.imageTypes = $s.image_types || $s.imageTypes
    $s.faceboxHtml = $s.facebox_html || $s.faceboxHtml
  }

  // Figures out what you want to display and displays it
  // formats are:
  //     div: #id
  //   image: blah.extension
  //    ajax: anything else
  function fillFaceboxFromHref(href, klass) {
    // div
    if (href.match(/#/)) {
      var url    = window.location.href.split('#')[0]
      var target = href.replace(url,'')
      if (target == '#') return
      $.facebox.reveal($(target).html(), klass)

    // image
    } else if (href.match($.facebox.settings.imageTypesRegexp)) {
      fillFaceboxFromImage(href, klass)
    // ajax
    } else {
      fillFaceboxFromAjax(href, klass)
    }
  }

  function fillFaceboxFromImage(href, klass) {
    var image = new Image()
    image.onload = function() {
      $.facebox.reveal('

', klass)
    }
    image.src = href
  }

  function fillFaceboxFromAjax(href, klass) {
    $.get(href, function(data) { $.facebox.reveal(data, klass) })
  }

  function skipOverlay() {
    return $.facebox.settings.overlay == false || $.facebox.settings.opacity === null
  }

  function showOverlay() {
    if (skipOverlay()) return

    if ($('#facebox_overlay').length == 0)
      $("body").append('

')

    $('#facebox_overlay').hide().addClass("facebox_overlayBG")
      .css('opacity', $.facebox.settings.opacity)
      .click(function() { $(document).trigger('close.facebox') })
      .fadeIn(200)
    return false
  }

  function hideOverlay() {
    if (skipOverlay()) return

    $('#facebox_overlay').fadeOut(200, function(){
      $("#facebox_overlay").removeClass("facebox_overlayBG")
      $("#facebox_overlay").addClass("facebox_hide")
      $("#facebox_overlay").remove()
    })

    return false
  }

  /*
   * Bindings
   */

  $(document).bind('close.facebox', function() {
    $(document).unbind('keydown.facebox')
    $('#facebox').fadeOut(function() {
      $('#facebox .content').removeClass().addClass('content')
      hideOverlay()
      $('#facebox .loading').remove()
    })
  })

})(jQuery);
<|endoftext|>


<commit_before>/**
 * Copyright: (c) 2016-2017 Max Klein
 * License: MIT
 */

define([
	'lib/SvgUtil',
	'App',
	'editor/components/AndComponent',
	'editor/components/ClockComponent',
	'editor/components/ConstComponent',
	'editor/components/DFlipFlopComponent',
	'editor/components/FullAdderComponent',
	'editor/components/HalfAdderComponent',
	'editor/components/NotComponent',
	'editor/components/OrComponent'
], function (SvgUtil, App, AndComponent, ClockComponent, ConstComponent, DFlipFlopComponent, FullAdderComponent, HalfAdderComponent, NotComponent, OrComponent) {
	var app = new App();
	app.editor.addComponent(new AndComponent(), 10, 10);
	app.editor.addComponent(new ClockComponent(), 20, 10);
	app.editor.addComponent(new ConstComponent(true), 10, 30);
	app.editor.addComponent(new DFlipFlopComponent(), 20, 30);
	app.editor.addComponent(new FullAdderComponent(), 10, 50);
	app.editor.addComponent(new HalfAdderComponent(), 20, 50);
	app.editor.addComponent(new NotComponent(), 10, 70);
	app.editor.addComponent(new OrComponent(), 20, 70);
});
<commit_msg>Don't add components at startup<commit_after>/**
 * Copyright: (c) 2016-2017 Max Klein
 * License: MIT
 */

define([
	'App'
], function (App) {
	var app = new App();
});
<|endoftext|>


<commit_before>var app = (function ($, L, document) {
    var _map;
    var _markers;
    var _markerMap = {};
    var _markerList = [];
    var _activeIcon;
    var _defaultIcon;

    function init() {
        articleList.init();
        _map = L.mapbox.map('map', 'sharkins.map-uwias8cf', {maxZoom:12});
        _map.on('ready', function() {
            var miniMap = new L.Control.MiniMap(L.mapbox.tileLayer(
                'sharkins.hc52c67l'), {position: 'bottomleft'})
                .addTo(_map);
        });
        _defaultIcon = new L.Icon.Default();
        _activeIcon = new L.Icon.Default({iconUrl:
                                        './images/marker-icon-red.png'});
        _markers = new L.MarkerClusterGroup({
            spiderfyDistanceMultiplier:1,
            showCoverageOnHover:false
        });

        $(document)
            .hide()
            .ajaxStart(function() {
                $('#ajaxloader').show();
            })
            .ajaxStop(function() {
                $('#ajaxloader').hide();
            });

        $.ajax(buildRSSUrl())
            .done(function(xml) {
                processRSSXML(xml);
                _markers.addLayers(_markerList);
                _map.addLayer(_markers);
        });
    }
    function processRSSXML(xml) {
        $(xml)
            .find('item')
                .each(function(index) {
                    var xmlitem = $(this);
                    if (xmlitem.children('geo\\:long').length > 0) {
                        createFeature(index, xmlitem, _markerList, _markerMap);
                        articleList.addListItem(index, xmlitem);
                    }
                 });
        articleList.sortByDate();
    }

    function markerClick(e) {
        clearActive();
        var articles = $('#articles');
        var activeLi = $('#articlelist' + ' #' + this.options.id);
        articles.scrollTop(0);
        articles.animate({
            duration: 'slow',
            scrollTop: activeLi.position().top
        });
        activeLi.addClass('active');
        this.setIcon(_activeIcon);
    }
    function clearActive() {
        var previousActiveLi = $('li.active');
        previousActiveMarker = _markerMap[previousActiveLi.attr('id')];
        if (previousActiveMarker) {
            previousActiveMarker.setIcon(_defaultIcon);
        }
        previousActiveLi.removeClass('active');
    }
    function buildRSSUrl() {
        function buildQueryString(data) {
            var params = [];
            for (var d in data) {
                params.push(d + '=' + data[d]);
            }
            return params.join('&');
        }
        var googleUrl = 'https://news.google.com/news/feeds';
        var googleParams = {
            gl: 'ca',
            q: 'peru+mining+protests',
            um: 1,
            ie: 'UTF-8',
            output: 'rss',
            num: 40
        };
        var encodedGoogleUrl = encodeURIComponent(googleUrl + '?' +
                                                  buildQueryString(googleParams));
        var geonamesUrl = 'http://api.geonames.org/rssToGeoRSS';
        var geonamesParams = {
            feedUrl: encodedGoogleUrl,
            username: 'sharkinsgis',
            feedLanguage: 'en',
            country: 'pe',
            addUngeocodedItems: 'false'
        };
        geonamesUrl = geonamesUrl + '?' + buildQueryString(geonamesParams);
        return geonamesUrl;
    }
    function createFeature(index, xmlitem, markerList, markerMap) {
        var latlng = new L.LatLng(parseFloat(xmlitem
                                             .children('geo\\:lat').text()),
                                  parseFloat(xmlitem
                                             .children('geo\\:long').text()));
                                  var marker = L.marker(latlng, {id: index});
                                  marker.on('click', markerClick);
                                  markerList.push(marker);
                                  markerMap[index] = marker;
    }
    var articleList = (function ($) {
        var _list;
        function init() {
            _list = $('<ul/>', {'id': 'articlelist'});
            $('#articles').append(_list);
        }

        function addListItem(index, xmlitem) {
            var titleComponents = xmlitem
                                    .children('title')
                                    .text()
                                    .split(' - ');
            var articleTitle = titleComponents[0];
            var articleOrigin = titleComponents[1];
            var pubdate = new Date(xmlitem.children('pubDate').text());
            var articleOriginUrl = xmlitem.children('link').text();
            var articleSpan = $('<span/>', {
                html: articleTitle
            });
            var listItem = $('<li/>', {
                html: articleSpan,
                'id': index,
                'datetime': pubdate
            });
            var itemLink = $('<a/>', {
                html: articleOrigin,
                'href': articleOriginUrl,
                'target': '_blank'
            });
            listItem.on('click', articleClick);
            listItem.append(itemLink);
            _list.append(listItem);
        }

        function sortByDate() {
            var listItems = $('#articlelist li');
            var list = _list;
            if(listItems.length && list.length) {
                listItems.sort(function(a,b) {
                    return new Date($(a).attr('datetime')) -
                        new Date($(b).attr('datetime'));
                }).each(function() {
                    list.prepend(this);
                });
            }
            else {
                throw new Error('Invalid list and target div');
            }
        }
        function articleClick(e) {
                clearActive();
                var activeLi = $(this);
                activeLi.addClass('active');
                activeMarker = _markerMap[activeLi.attr('id')];
                _markers.zoomToShowLayer(activeMarker, function(){
                    activeMarker.setIcon(_activeIcon);
                });
        }

        return {
            init: init,
            addListItem: addListItem,
            sortByDate: sortByDate
        };
    })($);

    return {
        init: init,
        createFeature: createFeature
    };
})($, L, this.document);
<commit_msg>Big refactor for composability with articleMarkers, still more<commit_after>var app = (function ($, L, document) {
    var _map;
    var _markers;
    var _markerMap = {};
    var _markerList = [];
    var _activeIcon;
    var _defaultIcon;

    function init() {
        articleList.init();
        _map = L.mapbox.map('map', 'sharkins.map-uwias8cf', {maxZoom:12});
        _map.on('ready', function() {
            var miniMap = new L.Control.MiniMap(L.mapbox.tileLayer(
                'sharkins.hc52c67l'), {position: 'bottomleft'})
                .addTo(_map);
        });
        _defaultIcon = new L.Icon.Default();
        _activeIcon = new L.Icon.Default({iconUrl:
                                        './images/marker-icon-red.png'});
        _markers = new L.MarkerClusterGroup({
            spiderfyDistanceMultiplier:1,
            showCoverageOnHover:false
        });

        $(document)
            .hide()
            .ajaxStart(function() {
                $('#ajaxloader').show();
            })
            .ajaxStop(function() {
                $('#ajaxloader').hide();
            });

        $.ajax(buildRSSUrl())
            .done(function(xml) {
                processRSSXML(xml);
                _markers.addLayers(_markerList);
                _map.addLayer(_markers);
        });
        $(document).on('articleMarkerClick', function(e, id) {
            articleList.scrollToArticle(id);
        });
        $(document).on('articleDeactivated', function(e, id) {
            articleMarkers.deactivateMarker(id);
        });
        $(document).on('articleActivated', function(e, id) {
            articleMarkers.activateMarker(id);
        });
    }
    function processRSSXML(xml) {
        $(xml)
            .find('item')
                .each(function(index) {
                    var xmlitem = $(this);
                    if (xmlitem.children('geo\\:long').length > 0) {
                        articleMarkers.createMarker(
                            index, xmlitem, _markerList, _markerMap);
                        articleList.addListItem(index, xmlitem);
                    }
                 });
        articleList.sortByDate();
    }

    //function markerClick(e) {
        //clearActive();
        //var articles = $('#articles');
        //var activeLi = $('#articlelist' + ' #' + this.options.id);
        //articles.scrollTop(0);
        //articles.animate({
            //duration: 'slow',
            //scrollTop: activeLi.position().top
        //});
        //activeLi.addClass('active');
        //this.setIcon(_activeIcon);
    //}
    //function clearActive() {
        //var previousActiveLi = $('li.active');
        //previousActiveMarker = _markerMap[previousActiveLi.attr('id')];
        //if (previousActiveMarker) {
            //previousActiveMarker.setIcon(_defaultIcon);
        //}
        //previousActiveLi.removeClass('active');
    //}
    function buildRSSUrl() {
        function buildQueryString(data) {
            var params = [];
            for (var d in data) {
                params.push(d + '=' + data[d]);
            }
            return params.join('&');
        }
        var googleUrl = 'https://news.google.com/news/feeds';
        var googleParams = {
            gl: 'ca',
            q: 'peru+mining+protests',
            um: 1,
            ie: 'UTF-8',
            output: 'rss',
            num: 40
        };
        var encodedGoogleUrl = encodeURIComponent(googleUrl + '?' +
                                                  buildQueryString(googleParams));
        var geonamesUrl = 'http://api.geonames.org/rssToGeoRSS';
        var geonamesParams = {
            feedUrl: encodedGoogleUrl,
            username: 'sharkinsgis',
            feedLanguage: 'en',
            country: 'pe',
            addUngeocodedItems: 'false'
        };
        geonamesUrl = geonamesUrl + '?' + buildQueryString(geonamesParams);
        return geonamesUrl;
    }

    var articleMarkers = (function ($, document) {
        function createMarker(index, xmlitem, markerList, markerMap) {
            var latlng = new L.LatLng(parseFloat(xmlitem
                                                 .children('geo\\:lat').text()),
                                                 parseFloat(xmlitem.
                                                 children('geo\\:long').text()));
            var marker = L.marker(latlng, {id: index});
            //marker.on('click', markerClick);
            marker.on('click', function() {
                this.setIcon(_activeIcon);
                $(document).trigger('articleMarkerClick', [this.options.id]);
            });
            markerList.push(marker);
            markerMap[index] = marker;
        }
        function activateMarker(id) {
            var activeMarker = _markerMap[id];
            _markers.zoomToShowLayer(activeMarker, function(){
                activeMarker.setIcon(_activeIcon);
            });
        }
        function deactivateMarker(id) {
            var previousActiveMarker = _markerMap[id];
            if (previousActiveMarker) {
                previousActiveMarker.setIcon(_defaultIcon);
            }
        }
        return {
            createMarker: createMarker,
            activateMarker: activateMarker,
            deactivateMarker: deactivateMarker
        };
    })($, document);

    var articleList = (function ($, document) {
        var _list;
        function init() {
            _list = $('<ul/>', {'id': 'articlelist'});
            $('#articles').append(_list);
        }

        function addListItem(index, xmlitem) {
            var titleComponents = xmlitem
                                    .children('title')
                                    .text()
                                    .split(' - ');
            var articleTitle = titleComponents[0];
            var articleOrigin = titleComponents[1];
            var pubdate = new Date(xmlitem.children('pubDate').text());
            var articleOriginUrl = xmlitem.children('link').text();
            var articleSpan = $('<span/>', {
                html: articleTitle
            });
            var listItem = $('<li/>', {
                html: articleSpan,
                'id': index,
                'datetime': pubdate
            });
            var itemLink = $('<a/>', {
                html: articleOrigin,
                'href': articleOriginUrl,
                'target': '_blank'
            });
            listItem.on('click', articleClick);
            listItem.append(itemLink);
            _list.append(listItem);
        }

        function sortByDate() {
            var listItems = $('#articlelist li');
            var list = _list;
            if(listItems.length && list.length) {
                listItems.sort(function(a,b) {
                    return new Date($(a).attr('datetime')) -
                        new Date($(b).attr('datetime'));
                }).each(function() {
                    list.prepend(this);
                });
            }
            else {
                throw new Error('Invalid list and target div');
            }
        }
        function deactivatePreviousArticle() {
            var previousActiveLi = $('li.active');
            $(document).trigger('articleDeactivated',
                                [previousActiveLi.attr('id')]);
            previousActiveLi.removeClass('active');
        }
        function scrollToArticle(id) {
            deactivatePreviousArticle();
            var articles = $('#articles');
            var activeLi = $('#articlelist' + ' #' + id);
            activeLi.addClass('active');
            articles.scrollTop(0);
            articles.animate({
                duration: 'slow',
                scrollTop: activeLi.position().top
            });
        }
        function articleClick(e) {
            deactivatePreviousArticle();
            var activeLi = $(this);
            activeLi.addClass('active');
            $(document).trigger('articleActivated', [activeLi.attr('id')]);
            //activeMarker = _markerMap[activeLi.attr('id')];
            //_markers.zoomToShowLayer(activeMarker, function(){
                //activeMarker.setIcon(_activeIcon);
            //});
        }

        return {
            init: init,
            addListItem: addListItem,
            sortByDate: sortByDate,
            scrollToArticle: scrollToArticle
        };
    })($, document);

    return {
        init: init
    };
})($, L, this.document);
<|endoftext|>


<commit_before>var fs = require('fs'),
    hosts = require('./js/hosts.js');

require('./js/rename.js').init(jQuery);

var filepath = '/Users/witcher42/tmp/hosts',
    options = { encoding: 'utf8' },
    hosts = null,
    list = null,
    $doc,
    $content;

// 替换模版
function render(template, textHashArr) {
  var i, result = '', textHash;

  function replaceFunc($0, $1) {
    return textHash[$1] || '';
  }

  if (!Array.isArray(textHashArr)) {
    textHashArr = [ textHashArr ];
  }
  for (i=0; i<textHashArr.length; i++) {
    textHash = textHashArr[i];
    result += template.replace(/{{(.*?)}}/g, replaceFunc);
  }
  return result;
};

$doc = $(document);

$content = $('#js-content');
$content.text(fs.readFileSync(filepath, options));

var $item,
    hosts,
    html = $('#tpl-list').html();

hosts = {

  hosts: [],

  defaultHosts: [
    {
      name: 'Common',
      host: '',
      active: false,
      toggle: false
    },
    {
      name: 'QA',
      host: '',
      using: true,
      active: true,
      custom: true
    },
    {
      name: 'Dev',
      host: '',
      using: false,
      active: false,
      custom: true
    },
  ],

  init: function() {
    this.hosts = this.get() || this.defaultHosts.slice(0);
    this.show();
  },

  show: function() {

    this.hosts.forEach(function(element, index) {

      var template,
          hashArr,
          $host;

      hashArr = {
        hostname: element.name
      };

      template = render(html, hashArr);

      $host = $(template);

      if (element.active) {
        $host.addClass('active');
      }

      if (element.custom) {
        $host.addClass('js-custom');
      }

      if (element.using) {
        $host.addClass('using');
      }

      $host.data('hosts', element.host);

      $host.insertBefore('#tpl-list');

    });

  },

  set: function() {
    try {
      localStorage.setItem('hosts', JSON.stringify(this.hosts));
    } catch(e) {
      // Do nothing
    }
  },

  get: function() {
    try {
      return JSON.parse(localStorage.getItem('hosts'));
    } catch(e) {
      return null;
    }
  },

  change: function(index, key, value) {
    var host = this.hosts[index];

    if (!host) {
      return false;
    }

    host[key] = value;

    this.set();
  },

  del: function(index) {
    this.hosts.splice(index, 1);
    this.set();
  },

  add: function() {
    var template,
        hashArr,
        element,
        $host;

    element = {
      name: 'New One',
      host: '',
      using: false,
      active: false,
      custom: true
    }

    this.hosts.push(element);

    this.set();

    hashArr = {
      hostname: element.name
    };

    template = render(html, hashArr);

    $host = $(template);

    if (element.active) {
      $host.addClass('active');
    }

    if (element.custom) {
      $host.addClass('js-custom');
    }

    if (element.using) {
      $host.addClass('using');
    }

    $host.data('hosts', element.host);

    $host.insertBefore('#tpl-list');

    $host.children('a').rename({
      stop: function() {
        this.change(hosts.hosts.length - 1, 'name', this.text());
      }
    });

  }

};

$doc.on('click', '#js-list a', function(e) {
  e.preventDefault();
  $(this).tab('show');
});

$doc.on('dblclick', '.js-custom a', function(e) {
  e.preventDefault();
  $('.using').removeClass('using');
  $(this).parent().addClass('using');
});

$doc.on('click', '.js-add', function(e) {
  hosts.add();
});

$doc.on('click', '.js-del', function(e) {
  hosts.del($('.active').prevAll('li:not(#js-list-hosts)').length);
});

hosts.init();
<commit_msg>1. Change hosts.show to hosts.refresh<commit_after>var fs = require('fs'),
    hosts = require('./js/hosts.js');

require('./js/rename.js').init(jQuery);

var filepath = '/Users/witcher42/tmp/hosts',
    options = { encoding: 'utf8' },
    hosts = null,
    list = null,
    $doc,
    $content;

// 替换模版
function render(template, textHashArr) {
  var i, result = '', textHash;

  function replaceFunc($0, $1) {
    return textHash[$1] || '';
  }

  if (!Array.isArray(textHashArr)) {
    textHashArr = [ textHashArr ];
  }
  for (i=0; i<textHashArr.length; i++) {
    textHash = textHashArr[i];
    result += template.replace(/{{(.*?)}}/g, replaceFunc);
  }
  return result;
};

$doc = $(document);

$content = $('#js-content');
$content.text(fs.readFileSync(filepath, options));

var $item,
    hosts,
    html = $('#tpl-list').html();

hosts = {

  hosts: [],

  defaultHosts: [
    {
      name: 'Common',
      host: '',
      active: false,
      toggle: false
    },
    {
      name: 'QA',
      host: '',
      using: true,
      active: true,
      custom: true
    },
    {
      name: 'Dev',
      host: '',
      using: false,
      active: false,
      custom: true
    },
  ],

  init: function() {
    this.hosts = this.get() || this.defaultHosts.slice(0);
    this.refresh();
  },

  refresh: function() {

    this.hosts.forEach(function(element, index) {

      var template,
          hashArr,
          $host;

      hashArr = {
        hostname: element.name
      };

      template = render(html, hashArr);

      $host = $(template);

      if (element.active) {
        $host.addClass('active');
      }

      if (element.custom) {
        $host.addClass('js-custom');
      }

      if (element.using) {
        $host.addClass('using');
      }

      $host.data('hosts', element.host);

      $host.insertBefore('#tpl-list');

    });

  },

  set: function() {
    try {
      localStorage.setItem('hosts', JSON.stringify(this.hosts));
    } catch(e) {
      // Do nothing
    }
  },

  get: function() {
    try {
      return JSON.parse(localStorage.getItem('hosts'));
    } catch(e) {
      return null;
    }
  },

  change: function(index, key, value) {
    var host = this.hosts[index];

    if (!host) {
      return false;
    }

    host[key] = value;

    this.set();
  },

  del: function(index) {
    this.hosts.splice(index, 1);
    this.set();
  },

  add: function() {
    var template,
        hashArr,
        element,
        $host;

    element = {
      name: 'New One',
      host: '',
      using: false,
      active: false,
      custom: true
    }

    this.hosts.push(element);

    this.set();

    hashArr = {
      hostname: element.name
    };

    template = render(html, hashArr);

    $host = $(template);

    if (element.active) {
      $host.addClass('active');
    }

    if (element.custom) {
      $host.addClass('js-custom');
    }

    if (element.using) {
      $host.addClass('using');
    }

    $host.data('hosts', element.host);

    $host.insertBefore('#tpl-list');

    $host.children('a').rename({
      stop: function() {
        this.change(hosts.hosts.length - 1, 'name', this.text());
      }
    });

  }

};

$doc.on('click', '#js-list a', function(e) {
  e.preventDefault();
  $(this).tab('show');
});

$doc.on('dblclick', '.js-custom a', function(e) {
  e.preventDefault();
  $('.using').removeClass('using');
  $(this).parent().addClass('using');
});

$doc.on('click', '.js-add', function(e) {
  hosts.add();
});

$doc.on('click', '.js-del', function(e) {
  hosts.del($('.active').prevAll('li:not(#js-list-hosts)').length);
});

hosts.init();
<|endoftext|>


<commit_before>// Load wetfish basic
var $ = require('wetfish-basic');

// Load custom modules
var Webcam = require('./webcam');
var helper = require('./helper');
var menu = require('./menu');
var overlay = require('./overlay');
var presets = require('./presets');
var pool = require('./pool');

// A map of currently pressed keys
var pressed = {};

// Global timeout cache
var timeout =
{
    // The durations of the different explosion animations
    explosion:
    {
        1: 1600,
        2: 1200,
        3: 860,
        4: 1060,
        5: 1600,
        6: 900,
        7: 1090
    }
};

// Key codes for control characters
var keys =
{
    8: 'backspace',
    9: 'tab',
    16: 'shift',
    17: 'control',
    18: 'alt',
    20: 'caps',
    27: 'escape',
    46: 'delete',
    91: 'system',
};

$(document).ready(function()
{
    menu.init();
    overlay.init();
    presets.init();

    var explosion = $('.preload .explosion').el[0];
    var hitmarker = $('.preload .hitmarker').el[0];

    pool.init(explosion, 'explosion', 16);
    pool.init(hitmarker, 'hitmarker', 7);

    // Hitmarkers
    $('body').on('mousedown touchstart', '.workspace, .workspace *', function(event)
    {
        // If left click was pressed, or this is a touch event
        if(!event.buttons || event.buttons == 1)
        {
            // If the click timeout is defined, this must be a double click!
            if(timeout.click)
            {
                // If this is an audio or video element
                if(this.nodeName && this.nodeName.toLowerCase() == 'audio' || this.nodeName.toLowercase() == 'video')
                {
                    // Toggle playing state
                    if(this.paused)
                    {
                        this.play();
                    }
                    else
                    {
                        this.pause();
                    }
                }

                timeout.click = false;
            }
            else
            {
                // Create a timeout to determine if the user is double clicking
                timeout.click = setTimeout(function()
                {
                    timeout.click = false;
                }, 150);
            }

            // If the user is holding control while clicking
            if(pressed.control)
            {
                var image = document.createElement('img');
                $(image).style({'top': event.clientY + 'px', 'left': event.clientX + 'px'});
                $(image).addClass('hitmarker');
                $(image).attr('src', 'img/hitmarker.png');
                $('.workspace').el[0].appendChild(image);

                pool.play('hitmarker');

                // Remove the image after a bit
                setTimeout(function()
                {
                    $(image).remove();
                }, 500);
            }
        }
    });

    // Deleting things
    $('body').on('mousedown', '.workspace *', function(event)
    {
        // If right click was pressed
        if(event.buttons == 2)
        {
            // If the user is holding control while deleting an image
            if(pressed.control)
            {
                // Save the size and position of the current element
                var size = $(this).size();
                var position = $(this).position();

                // Increase the size of the explosion a little bit
                size.width += 50;
                size.height += 50;
                position.top -= 25;
                position.left -= 25;

                // Create an image to overlay the explosion over the current element
                var image = document.createElement('img');
                var options =
                {
                    'position': 'absolute',
                    'top': position.top + 'px',
                    'left': position.left + 'px',
                    'width': size.width + 'px',
                    'height': size.height + 'px',
                };

                $(image).style(options);
                $(image).addClass('explosion');

                // Generate a random explosion image
                var random = helper.random(1, 7);
                $(image).attr('src', 'img/explosion-' + random + '.gif');

                // EXPLODE!
                $('.workspace').el[0].appendChild(image);

                pool.play('explosion');

                // Remove the original element, if it's not an explosion
                if(!$(this).hasClass('explosion'))
                {
                    $(this).remove();
                }

                // Remove the explosion after the animation is finished
                setTimeout(function()
                {
                    $(image).remove();
                }, timeout.explosion[random])
            }
            else
            {
                // Otherwise just remove it
                $(this).remove();
            }
        }
    });

    $('body').on('contextmenu', function(event)
    {
        event.preventDefault();
    });

    $('body').on('keydown', function(event)
    {
        var key = (event.key) ? event.key.toLowerCase() : keys[event.which];
        pressed[key] = true;

        // Toggle the menu when pressing escape
        if(key == 'escape')
        {
            $('.menu').toggle('hidden');
        }
    });

    $('body').on('keyup', function(event)
    {
        var key = (event.key) ? event.key.toLowerCase() : keys[event.which];
        delete pressed[key];
    });
});
<commit_msg>Some doubleclick fixes<commit_after>// Load wetfish basic
var $ = require('wetfish-basic');

// Load custom modules
var Webcam = require('./webcam');
var helper = require('./helper');
var menu = require('./menu');
var overlay = require('./overlay');
var presets = require('./presets');
var pool = require('./pool');

// A map of currently pressed keys
var pressed = {};

// Global timeout cache
var timeout =
{
    // The durations of the different explosion animations
    explosion:
    {
        1: 1600,
        2: 1200,
        3: 860,
        4: 1060,
        5: 1600,
        6: 900,
        7: 1090
    }
};

// Key codes for control characters
var keys =
{
    8: 'backspace',
    9: 'tab',
    16: 'shift',
    17: 'control',
    18: 'alt',
    20: 'caps',
    27: 'escape',
    46: 'delete',
    91: 'system',
};

$(document).ready(function()
{
    menu.init();
    overlay.init();
    presets.init();

    var explosion = $('.preload .explosion').el[0];
    var hitmarker = $('.preload .hitmarker').el[0];

    pool.init(explosion, 'explosion', 16);
    pool.init(hitmarker, 'hitmarker', 7);

    // Hitmarkers
    $('body').on('mousedown touchstart', '.workspace, .workspace *', function(event)
    {
        // If left click was pressed, or this is a touch event
        if(!event.buttons || event.buttons == 1)
        {
            // If the click timeout is defined, this must be a double click!
            if(timeout.click)
            {
                // If this is an audio or video element
                if(this.nodeName && this.nodeName.toLowerCase() == 'audio' || this.nodeName.toLowerCase() == 'video')
                {
                    // Toggle playing state
                    if(this.paused)
                    {
                        this.play();
                    }
                    else
                    {
                        this.pause();
                    }
                }

                timeout.click = null;
            }
            else
            {
                // Create a timeout to determine if the user is double clicking
                timeout.click = setTimeout(function()
                {
                    timeout.click = null;
                }, 250);
            }

            // If the user is holding control while clicking
            if(pressed.control)
            {
                var image = document.createElement('img');
                $(image).style({'top': event.clientY + 'px', 'left': event.clientX + 'px'});
                $(image).addClass('hitmarker');
                $(image).attr('src', 'img/hitmarker.png');
                $('.workspace').el[0].appendChild(image);

                pool.play('hitmarker');

                // Remove the image after a bit
                setTimeout(function()
                {
                    $(image).remove();
                }, 500);
            }
        }
    });

    // Deleting things
    $('body').on('mousedown', '.workspace *', function(event)
    {
        // If right click was pressed
        if(event.buttons == 2)
        {
            // If the user is holding control while deleting an image
            if(pressed.control)
            {
                // Save the size and position of the current element
                var size = $(this).size();
                var position = $(this).position();

                // Increase the size of the explosion a little bit
                size.width += 50;
                size.height += 50;
                position.top -= 25;
                position.left -= 25;

                // Create an image to overlay the explosion over the current element
                var image = document.createElement('img');
                var options =
                {
                    'position': 'absolute',
                    'top': position.top + 'px',
                    'left': position.left + 'px',
                    'width': size.width + 'px',
                    'height': size.height + 'px',
                };

                $(image).style(options);
                $(image).addClass('explosion');

                // Generate a random explosion image
                var random = helper.random(1, 7);
                $(image).attr('src', 'img/explosion-' + random + '.gif');

                // EXPLODE!
                $('.workspace').el[0].appendChild(image);

                pool.play('explosion');

                // Remove the original element, if it's not an explosion
                if(!$(this).hasClass('explosion'))
                {
                    $(this).remove();
                }

                // Remove the explosion after the animation is finished
                setTimeout(function()
                {
                    $(image).remove();
                }, timeout.explosion[random])
            }
            else
            {
                // Otherwise just remove it
                $(this).remove();
            }
        }
    });

    $('body').on('contextmenu', function(event)
    {
        event.preventDefault();
    });

    $('body').on('keydown', function(event)
    {
        var key = (event.key) ? event.key.toLowerCase() : keys[event.which];
        pressed[key] = true;

        // Toggle the menu when pressing escape
        if(key == 'escape')
        {
            $('.menu').toggle('hidden');
        }
    });

    $('body').on('keyup', function(event)
    {
        var key = (event.key) ? event.key.toLowerCase() : keys[event.which];
        delete pressed[key];
    });
});
<|endoftext|>


<commit_before>

// does all the various elements we need doing

// Apply stick to the side bar
// basically don't deliver the sticky fill if we're not going multicolumn
if (window.innerWidth >= 768) {
    var sidebar = document.getElementById('sidebar');
    Stickyfill.add(sidebar);
}

// This injects a class onto p tags that contain images in the main article
// part of the page. Markup doesn't really allow class addition to standard
// tags so this is worth doing progressively.
var article_items = document.querySelectorAll("article p * img");
var article_arr_items = Array.from(article_items);

article_arr_items.forEach(function(item) {
	if (item.parentNode.localName == "p") {
		item.parentNode.classList.add("imagep");
	} else if (item.parentNode.localName == "a") {
		if (item.parentNode.parentNode.localName == "p") {
			item.parentNode.parentNode.classList.add("imagep");
		} else {
			console.log(item.parentNode.parentNode.localName);
		}
	}
});

// now we do the pull quotes to extract them from the document and then
// set the appropriate CSS etc
var pullquote_list = Array.from(document.querySelectorAll("article p b"));

pullquote_list.forEach(function(pq) {
    pq.parentNode.classList.add("has-pullquote");
    // make sure it's upper case on first char so it reads right.
    var quote = pq.innerHTML;
    console.log(quote);
    quote = "" + quote[0].toUpperCase() + quote.substring(1)

    // now assign to the pq
    pq.parentNode.dataset.pullquote = quote;
});

<commit_msg>fix around pull quote generator<commit_after>

// does all the various elements we need doing

// Apply stick to the side bar
// basically don't deliver the sticky fill if we're not going multicolumn
if (window.innerWidth >= 768) {
    var sidebar = document.getElementById('sidebar');
    Stickyfill.add(sidebar);
}

// This injects a class onto p tags that contain images in the main article
// part of the page. Markup doesn't really allow class addition to standard
// tags so this is worth doing progressively.
var article_items = document.querySelectorAll("article p * img");
var article_arr_items = Array.from(article_items);

article_arr_items.forEach(function(item) {
	if (item.parentNode.localName == "p") {
		item.parentNode.classList.add("imagep");
	} else if (item.parentNode.localName == "a") {
		if (item.parentNode.parentNode.localName == "p") {
			item.parentNode.parentNode.classList.add("imagep");
		} else {
			console.log(item.parentNode.parentNode.localName);
		}
	}
});

// now we do the pull quotes to extract them from the document and then
// set the appropriate CSS etc
var pullquote_list = Array.from(document.querySelectorAll("article p b"));

pullquote_list.forEach(function(pq) {
    pq.parentNode.classList.add("has-pullquote");
    // make sure it's upper case on first char so it reads right.
    var quote = pq.textContent;
    console.log(quote);
    quote = "" + quote[0].toUpperCase() + quote.substring(1)

    // now assign to the pq
    pq.parentNode.dataset.pullquote = quote;
});

<|endoftext|>


<commit_before>/* global moment */

var heading = document.querySelector('.countdown .heading')
var message = document.querySelector('.countdown .message')
var remaining = document.querySelector('.countdown .remaining')
var image = document.querySelector('.countdown .special-image')

var riverbendEvents = {
  '2016': {
    start: moment('2016-06-10T17:00:00-04:00'),
    end: moment('2016-06-18T23:30:00-04:00')
  },
  '2017': {
    start: moment('2017-06-09T01:45:00-04:00'),
    end: moment('2017-06-18T23:30:00-04:00')
  },
  '2018': {
    start: moment('2017-06-18T23:30:00-04:00')
  }
}

var snarkyMessages = [
  {
    message: "Get out your clean tank top and polish up the ol' pontoon - Riverbend fever is in full swing. Penicillin can be purchased with tokens at first aid tent. "
  },
  {
    message: 'Downtown Chattanooga now leads the nation in truck-nuts per capita.'
  },
  {
    message: "Did you know? Riverbend is home to the 8th Wonder of The World. That's right, the Porta-John lines are so long, they can be seen from outer space. #dadjoke"
  },
  {
    message: "Pause for Riverbend's bastard child, The Strut - which ironically is the only tolerable day of of the festival.",
    image: '/images/dance.gif'
  },
  {
    message: 'The chicken plant smell has been overtaken by the sweet smell of funnel cakes and regret.'
  },
  {
    message: "Judging by how flush with cash the panhandlers are... I'm guessing 'no'."
  },
  {
    message: 'Not as long as the world contains one original, living member of Lynyrd Skynyrd.'
  },
  {
    message: 'As tumbleweeds of trash blow down Broad Street, the end is near.'
  },
  {
    message: "If you weren't able to make it to the Riverbend Run this morning, don't worry! You can still get the runs from any of the concession stands located throughout the festival grounds."
  }
]

function updatePage () {
  var now = moment()
  var days = now.diff(riverbendEvents['2017'].start, 'days')
  message.dataset.days = days

  if (now.isAfter(riverbendEvents['2017'].start) && now.isBefore(riverbendEvents['2017'].end)) {
    if (days >= 0 && days < snarkyMessages.length) {
      message.innerHTML = snarkyMessages[days].message
      updateImage(snarkyMessages[days].image)
    }
    heading.innerHTML = 'Nope.'
    remaining.innerHTML = formatDateDiff(now, riverbendEvents['2017'].end)
  } else if (now.isBefore(riverbendEvents['2017'].start)) {
    heading.innerHTML = 'Yep.'
    message.innerHTML = "But don't get too excited. The whole thing starts again in:"
    remaining.innerHTML = formatDateDiff(now, riverbendEvents['2017'].start)
  } else if (now.isAfter(riverbendEvents['2017'])) {
    heading.innerHTML = 'Yep.'
    message.innerHTML = "But don't get too excited. The whole thing starts again in:"
    remaining.innerHTML = formatDateDiff(now, riverbendEvents['2018'].start)
  }
}

function updateImage (src) {
  if (!src) {
    image.src = ''
    image.classList.remove('d-block')
    image.classList.add('hidden')
    return
  }

  if (image.classList.contains('hidden')) {
    image.classList.remove('hidden')
    image.classList.add('d-block')
  }

  if (!image.src.endsWith(src)) {
    image.src = src
  }
}

function pluralize (count, singular, plural) {
  var word = ''
  if (count === 1) {
    word = singular
  } else {
    word = plural || (singular + 's')
  }
  return (count || 0) + ' ' + word
}

function formatDateDiff (start, end) {
  var duration = moment.duration(end.diff(start))
  var diffStr = ''

  if (duration.years() > 0) {
    diffStr += pluralize(duration.years(), 'year') + ' '
  }
  if (duration.months() > 0) {
    diffStr += pluralize(duration.months(), 'month') + ' '
  }
  if (duration.days() > 0) {
    diffStr += pluralize(duration.days(), 'day') + ' '
  }
  if (duration.hours() > 0) {
    diffStr += pluralize(duration.hours(), 'hr') + ' '
  }
  if (duration.minutes() > 0) {
    diffStr += pluralize(duration.minutes(), 'min') + ' '
  }

  diffStr += pluralize(duration.seconds(), 'sec')

  return diffStr
}

/**
 * Entrypoint
 */
updatePage()
window.setInterval(updatePage, 500)
<commit_msg>Bump 2018 date<commit_after>/* global moment */

var heading = document.querySelector('.countdown .heading')
var message = document.querySelector('.countdown .message')
var remaining = document.querySelector('.countdown .remaining')
var image = document.querySelector('.countdown .special-image')

var riverbendEvents = {
  '2016': {
    start: moment('2016-06-10T17:00:00-04:00'),
    end: moment('2016-06-18T23:30:00-04:00')
  },
  '2017': {
    start: moment('2017-06-09T01:45:00-04:00'),
    end: moment('2017-06-18T23:30:00-04:00')
  },
  '2018': {
    start: moment('2017-06-09T01:45:00-04:00')
  }
}

var snarkyMessages = [
  {
    message: "Get out your clean tank top and polish up the ol' pontoon - Riverbend fever is in full swing. Penicillin can be purchased with tokens at first aid tent. "
  },
  {
    message: 'Downtown Chattanooga now leads the nation in truck-nuts per capita.'
  },
  {
    message: "Did you know? Riverbend is home to the 8th Wonder of The World. That's right, the Porta-John lines are so long, they can be seen from outer space. #dadjoke"
  },
  {
    message: "Pause for Riverbend's bastard child, The Strut - which ironically is the only tolerable day of of the festival.",
    image: '/images/dance.gif'
  },
  {
    message: 'The chicken plant smell has been overtaken by the sweet smell of funnel cakes and regret.'
  },
  {
    message: "Judging by how flush with cash the panhandlers are... I'm guessing 'no'."
  },
  {
    message: 'Not as long as the world contains one original, living member of Lynyrd Skynyrd.'
  },
  {
    message: 'As tumbleweeds of trash blow down Broad Street, the end is near.'
  },
  {
    message: "If you weren't able to make it to the Riverbend Run this morning, don't worry! You can still get the runs from any of the concession stands located throughout the festival grounds."
  }
]

function updatePage () {
  var now = moment()
  var days = now.diff(riverbendEvents['2017'].start, 'days')
  message.dataset.days = days

  if (now.isAfter(riverbendEvents['2017'].start) && now.isBefore(riverbendEvents['2017'].end)) {
    if (days >= 0 && days < snarkyMessages.length) {
      message.innerHTML = snarkyMessages[days].message
      updateImage(snarkyMessages[days].image)
    }
    heading.innerHTML = 'Nope.'
    remaining.innerHTML = formatDateDiff(now, riverbendEvents['2017'].end)
  } else if (now.isBefore(riverbendEvents['2017'].start)) {
    heading.innerHTML = 'Yep.'
    message.innerHTML = "But don't get too excited. The whole thing starts again in:"
    remaining.innerHTML = formatDateDiff(now, riverbendEvents['2017'].start)
  } else if (now.isAfter(riverbendEvents['2017'])) {
    heading.innerHTML = 'Yep.'
    message.innerHTML = "But don't get too excited. The whole thing starts again in:"
    remaining.innerHTML = formatDateDiff(now, riverbendEvents['2018'].start)
  }
}

function updateImage (src) {
  if (!src) {
    image.src = ''
    image.classList.remove('d-block')
    image.classList.add('hidden')
    return
  }

  if (image.classList.contains('hidden')) {
    image.classList.remove('hidden')
    image.classList.add('d-block')
  }

  if (!image.src.endsWith(src)) {
    image.src = src
  }
}

function pluralize (count, singular, plural) {
  var word = ''
  if (count === 1) {
    word = singular
  } else {
    word = plural || (singular + 's')
  }
  return (count || 0) + ' ' + word
}

function formatDateDiff (start, end) {
  var duration = moment.duration(end.diff(start))
  var diffStr = ''

  if (duration.years() > 0) {
    diffStr += pluralize(duration.years(), 'year') + ' '
  }
  if (duration.months() > 0) {
    diffStr += pluralize(duration.months(), 'month') + ' '
  }
  if (duration.days() > 0) {
    diffStr += pluralize(duration.days(), 'day') + ' '
  }
  if (duration.hours() > 0) {
    diffStr += pluralize(duration.hours(), 'hr') + ' '
  }
  if (duration.minutes() > 0) {
    diffStr += pluralize(duration.minutes(), 'min') + ' '
  }

  diffStr += pluralize(duration.seconds(), 'sec')

  return diffStr
}

/**
 * Entrypoint
 */
updatePage()
window.setInterval(updatePage, 500)
<|endoftext|>


<commit_before>$(function () {

    var socket;
    function initSocket() {
        // connect to local osc bridge
        socket = io.connect('http://127.0.0.1', { port: 8081, rememberTransport: false});
        socket.on('connect', function() {
            // sends to socket.io server the host/port of oscServer
            // and oscClient
            socket.emit('config',
                {
                    //vastaanotto proxylta
                    server: {
                        port: 3333,
                        host: '127.0.0.1'
                    },
                    //lahetys eli mikserin ip
                    client: {
                        port: 10023,
                        host: '127.0.0.1'
                    }
                }
            );
        });
        socket.on('message', function(obj) {
            console.log('got message', obj);
            triggerMessage(obj[0], obj[1]);
        });
    }
    initSocket();

    interact('.slider')                   // target the matches of that selector
        .origin('self')                     // (0, 0) will be the element's top-left
        .draggable({                        // make the element fire drag events
            max: Infinity,                     // allow drags on multiple elements
            restrict: {
                restriction: 'self'
            }
        })
        .on('dragmove', function (event) {  // call this function on every move
            var sliderHeight = interact.getElementRect(event.target).height;
            var value = event.pageY / sliderHeight;

            $(event.target).data('handler')($(event.target), (1 - value));
        });

    interact('.toggle')
        .on('tap', function (event) {
            var isSet = (1 == event.target.getAttribute('data-value'));
            $(event.target).data('handler')($(event.target), isSet ? 0 : 1);
        })
    ;

    interact('.momentary')
        .on('down', function (event) {
            $(event.target).data('handler')($(event.target), 1);
        })
        .on('up', function (event) {
            $(event.target).data('handler')($(event.target), 0);
        })
    ;

    function sendMessage(parameter, value, type) {
        type = type || 'f'
        var message = {address: parameter, args: [{type: type, value: value}]};
        $('.log').text(parameter + ' ' + value);
        socket.emit('message', message);
    }

    function triggerMessage(parameter, value) {
        console.log('triggering message', parameter, value);
        $('.log').text(parameter + ' ' + value);
        events.triggerHandler(parameter, value);
    }

    interact.maxInteractions(Infinity);   // Allow multiple interactions

    var events = $({});

    var controlWrapperTemplate = '

';
    var sliderTemplate = '

';
    var momentaryTemplate = '

';
    var toggleTemplate = '

;'

    function addControl(container, elementBuilder, name, parameter) {
        var control = elementBuilder(parameter);
        var wrapped = $(controlWrapperTemplate).prepend(control);
        wrapped.find('.control-name').text(name);
        container.append(wrapped);
    }

    var momentaryControl = function(parameter) {
        return buttonControl(momentaryTemplate, parameter);

    };

    var toggleControl = function(parameter) {
        return buttonControl(toggleTemplate, parameter);
    };

    var buttonControl = function(template, parameter) {
        var element = $(template);
        var handleValue = function (element, value, skipSend) {
            element.attr('data-value', value);
            if (value === 1) {
                element.css('background', 'red');
            } else if (value === 0) {
                element.css('background', '#29e');
            }

            if (!skipSend) sendMessage(parameter, value, 'i');

        };
        events.on(parameter, function (event, value) {
            console.log('received value', value, 'for parameter', parameter);
            handleValue(element, value, true);
        });
        element.data('handler', handleValue);
        return element;
    };

    var sliderControl = function(parameter) {
        var element = $(sliderTemplate);
        var content = element.find('.slider_content');
        var handleValue = function (element, value, skipSend) {
            element.attr('data-value', value);
            content.css('top', ((1 - value) * 100) + '%');

            if (!skipSend) sendMessage(parameter, value, 'f');
        };
        events.on(parameter, function (event, value) {
            console.log('received value', value, 'for parameter', parameter);
            handleValue(element, value, true);
        });
        element.data('handler', handleValue);
        return element;
    };

    var mainContainer = $('.container');
    var leftGroup = $('

');
    var rightGroup = $('

');

    var group1 = $('

');
    var group2 = $('

');
    var group3 = $('

');
    var group4 = $('

');

    mainContainer
        .append(leftGroup)
        .append(rightGroup);

    leftGroup
        .append(group1)
        .append(group3);
    rightGroup
        .append(group2)
        .append(group4);

    addControl(group1, momentaryControl, 'intercom', '/ch/11/mix/on');
    addControl(group1, toggleControl, 'on air', '/ch/01/mix/on');

    addControl(group2, momentaryControl, 'intercom', '/ch/12/mix/on');
    addControl(group2, toggleControl, 'on air', '/ch/02/mix/on');

    addControl(group3, sliderControl, 'caster 2', '/ch/02/mix/01/level');
    addControl(group3, sliderControl, 'game', '/ch/03/mix/01/level');
    addControl(group3, sliderControl, 'program', '/ch/10/mix/01/level');
    addControl(group3, sliderControl, 'talkback', '/ch/17/mix/01/level');

    addControl(group4, sliderControl, 'caster 1', '/ch/01/mix/02/level');
    addControl(group4, sliderControl, 'game', '/ch/03/mix/02/level');
    addControl(group4, sliderControl, 'program', '/ch/10/mix/02/level');
    addControl(group4, sliderControl, 'talkback', '/ch/17/mix/02/level');

    window.setTimeout(function () {
        console.log('triggering handlers');
        triggerMessage('/ch/02/mix/01/level', 0.5);
        triggerMessage('/ch/01/mix/on', 1);
    }, 5000);
});
<commit_msg>Fix osc data types<commit_after>$(function () {

    var socket;
    function initSocket() {
        // connect to local osc bridge
        socket = io.connect('http://127.0.0.1', { port: 8081, rememberTransport: false});
        socket.on('connect', function() {
            // sends to socket.io server the host/port of oscServer
            // and oscClient
            socket.emit('config',
                {
                    //vastaanotto proxylta
                    server: {
                        port: 3333,
                        host: '127.0.0.1'
                    },
                    //lahetys eli mikserin ip
                    client: {
                        port: 10023,
                        host: '127.0.0.1'
                    }
                }
            );
        });
        socket.on('message', function(obj) {
            console.log('got message', obj);
            triggerMessage(obj[0], obj[1]);
        });
    }
    initSocket();

    interact('.slider')                   // target the matches of that selector
        .origin('self')                     // (0, 0) will be the element's top-left
        .draggable({                        // make the element fire drag events
            max: Infinity,                     // allow drags on multiple elements
            restrict: {
                restriction: 'self'
            }
        })
        .on('dragmove', function (event) {  // call this function on every move
            var sliderHeight = interact.getElementRect(event.target).height;
            var value = event.pageY / sliderHeight;

            $(event.target).data('handler')($(event.target), (1 - value));
        });

    interact('.toggle')
        .on('tap', function (event) {
            var isSet = (1 == event.target.getAttribute('data-value'));
            $(event.target).data('handler')($(event.target), isSet ? 0 : 1);
        })
    ;

    interact('.momentary')
        .on('down', function (event) {
            $(event.target).data('handler')($(event.target), 1);
        })
        .on('up', function (event) {
            $(event.target).data('handler')($(event.target), 0);
        })
    ;

    function sendMessage(parameter, value, type) {
        type = type || 'float';
        var message = {address: parameter, args: [{type: type, value: value}]};
        $('.log').text(parameter + ' ' + value);
        socket.emit('message', message);
    }

    function triggerMessage(parameter, value) {
        console.log('triggering message', parameter, value);
        $('.log').text(parameter + ' ' + value);
        events.triggerHandler(parameter, value);
    }

    interact.maxInteractions(Infinity);   // Allow multiple interactions

    var events = $({});

    var controlWrapperTemplate = '

';
    var sliderTemplate = '

';
    var momentaryTemplate = '

';
    var toggleTemplate = '

;'

    function addControl(container, elementBuilder, name, parameter) {
        var control = elementBuilder(parameter);
        var wrapped = $(controlWrapperTemplate).prepend(control);
        wrapped.find('.control-name').text(name);
        container.append(wrapped);
    }

    var momentaryControl = function(parameter) {
        return buttonControl(momentaryTemplate, parameter);

    };

    var toggleControl = function(parameter) {
        return buttonControl(toggleTemplate, parameter);
    };

    var buttonControl = function(template, parameter) {
        var element = $(template);
        var handleValue = function (element, value, skipSend) {
            element.attr('data-value', value);
            if (value === 1) {
                element.css('background', 'red');
            } else if (value === 0) {
                element.css('background', '#29e');
            }

            if (!skipSend) sendMessage(parameter, value, 'integer');

        };
        events.on(parameter, function (event, value) {
            console.log('received value', value, 'for parameter', parameter);
            handleValue(element, value, true);
        });
        element.data('handler', handleValue);
        return element;
    };

    var sliderControl = function(parameter) {
        var element = $(sliderTemplate);
        var content = element.find('.slider_content');
        var handleValue = function (element, value, skipSend) {
            element.attr('data-value', value);
            content.css('top', ((1 - value) * 100) + '%');

            if (!skipSend) sendMessage(parameter, value, 'float');
        };
        events.on(parameter, function (event, value) {
            console.log('received value', value, 'for parameter', parameter);
            handleValue(element, value, true);
        });
        element.data('handler', handleValue);
        return element;
    };

    var mainContainer = $('.container');
    var leftGroup = $('

');
    var rightGroup = $('

');

    var group1 = $('

');
    var group2 = $('

');
    var group3 = $('

');
    var group4 = $('

');

    mainContainer
        .append(leftGroup)
        .append(rightGroup);

    leftGroup
        .append(group1)
        .append(group3);
    rightGroup
        .append(group2)
        .append(group4);

    addControl(group1, momentaryControl, 'intercom', '/ch/11/mix/on');
    addControl(group1, toggleControl, 'on air', '/ch/01/mix/on');

    addControl(group2, momentaryControl, 'intercom', '/ch/12/mix/on');
    addControl(group2, toggleControl, 'on air', '/ch/02/mix/on');

    addControl(group3, sliderControl, 'caster 2', '/ch/02/mix/01/level');
    addControl(group3, sliderControl, 'game', '/ch/03/mix/01/level');
    addControl(group3, sliderControl, 'program', '/ch/10/mix/01/level');
    addControl(group3, sliderControl, 'talkback', '/ch/17/mix/01/level');

    addControl(group4, sliderControl, 'caster 1', '/ch/01/mix/02/level');
    addControl(group4, sliderControl, 'game', '/ch/03/mix/02/level');
    addControl(group4, sliderControl, 'program', '/ch/10/mix/02/level');
    addControl(group4, sliderControl, 'talkback', '/ch/17/mix/02/level');

    window.setTimeout(function () {
        console.log('triggering handlers');
        triggerMessage('/ch/02/mix/01/level', 0.5);
        triggerMessage('/ch/01/mix/on', 1);
    }, 5000);
});
<|endoftext|>


<commit_before>/**
 * POST to the query endpoint to get information on whether or not it is going to snow.
 */
function queryData() {
    var zipCode = $("#zip-input").val();
    var zipData = { zip: zipCode };
    $.post("weather/query.php", zipData, function(data) {
        try {
            var parsedData = JSON.parse(data);
        } catch (e) {
            $("#response").css("display", "block");
            $("#text-response").html("
Please enter a valid zip code.
");
            return;
        }
        $("#response").css("display", "block");
        var town = parsedData.town;
        var state = parsedData.state;
        if (parsedData.snow) {
            $("#text-response").html("
Yes, there is a " + parsedData.chance + "% chance it will snow today in " + town + ", " + state + "
");
            $("#weather_image").attr("src", parsedData.img);
        } else {
            $("#text-response").html("
No, it is not forecasted to snow in " + town + ", " + state + "
");
            $("#weather_image").attr("src", "");
        }
    });
}

$( document ).ready(function() {
        $("#button").click(queryData);
    }
);
<commit_msg>Add loading message while retrieving data, support enter key on zip field<commit_after>/**
 * POST to the query endpoint to get information on whether or not it is going to snow.
 */
function queryData() {
    var zipCode = $("#zip-input").val();
    var zipData = { zip: zipCode };
    $("#response").css("display", "block");
    $("#text-response").html("
Loading..
");
    $.post("weather/query.php", zipData, function(data) {
        try {
            var parsedData = JSON.parse(data);
        } catch (e) {
            $("#text-response").html("
Please enter a valid zip code.
");
            return;
        }
        var town = parsedData.town;
        var state = parsedData.state;
        if (parsedData.snow) {
            $("#text-response").html("
Yes, there is a " + parsedData.chance + "% chance it will snow today in " + town + ", " + state + "
");
            $("#weather_image").attr("src", parsedData.img);
        } else {
            $("#text-response").html("
No, it is not forecasted to snow in " + town + ", " + state + "
");
            $("#weather_image").attr("src", "");
        }
    });
}

$( document ).ready(function() {
        $("#button").click(queryData);
        $("#zip-input").keyup(function(event) {
            if (event.keyCode == 13) {
                queryData();
            }
        });
    }
);
<|endoftext|>


<commit_before>var paths = {
	backbone: '../lib/backbone-optamd3-min',
    jquery:'../lib/jquery-1.9.1.min',
	underscore: '../lib/underscore-min',
	handlebars: '../lib/handlebars.runtime',
	helpers: 'util/helpers'
}

var shim = {
	handlebars: {
		exports: 'Handlebars'
	}
}

// set up require.js
require.config({
    baseUrl: '/src/js/',
    paths: paths,
    shim: shim
});

require(["app"],function(App){
	// initialize our application
	App.initialize();
});<commit_msg>updated with latest dev version of backbone in a shim<commit_after>var paths = {
	backbone: '../lib/backbone',
    jquery:'../lib/jquery-1.9.1.min',
	underscore: '../lib/underscore-min',
	handlebars: '../lib/handlebars.runtime',
	helpers: 'util/helpers'
}

var shim = {
	handlebars: {
		exports: 'Handlebars'
	},
	Backbone: {
		deps: ['underscore', 'jquery'],
		exports: 'Backbone'
	},
	underscore: {
		exports: '_'
	}
}

// set up require.js
require.config({
    baseUrl: '/src/js/',
    paths: paths,
    shim: shim
});

require(["app"],function(App){
	// initialize our application
	App.initialize();
});<|endoftext|>