<commit_before>import fs from 'fs'
import mkdirp from 'mkdirp'
import path from 'path'

// import constants from './app-constants'

exports.getFilenames = function (dir) {
  const list = fs.readdirSync(dir)
  return list.filter(
    function (value) {
      return fs.statSync(dir + '/' + value).isFile()
    }
  )
}

exports.getDataDir = function (app) {
  return app.getPath('userData')
}

exports.save = function (filename, txt) {
  console.log('>>save()')
  try {
    mkdirp(path.getDirName(path), function (err) {
      if (err) {
        throw err
      }
      fs.writeFileSync(path.join(this.getDataDir(), filename), txt, 'utf-8')
    })
    fs.writeFileSync(path.join(this.getDataDir(), filename), txt, 'utf-8')
  } catch (err) {
    throw err
  }
}

exports.saveWithBase64 = function (path, buf) {
  const b = new Buffer(buf)
  const b64Txt = b.toString('base64')
  var obj = { 'buf': b64Txt }
  try {
    fs.writeFileSync(path, JSON.stringify(obj), 'utf-8')
    console.log('Saved to' + path)
  } catch (err) {
    throw err
  }
}

exports.load = function (path) {
  const encoding = 'UTF-8'
  console.log('load:' + path)
  try {
    const jsonStr = fs.readFileSync(path, encoding)
    const json = JSON.parse(jsonStr.toString())
    const b = new Buffer(json['buf'], 'base64')
    return b.toString()
  } catch (err) {
    console.log(err)
    // return empty string when the buffer file is not found
    return ''
  }
}

exports.prepareDirIfNotExist = function (target) {
  mkdirp(target, function (err) {
    if(err) {
      throw e
    } else {
      //success
    }
  })
}<commit_msg>Fix lint #143209677<commit_after>import fs from 'fs'
import mkdirp from 'mkdirp'
import path from 'path'

// import constants from './app-constants'

exports.getFilenames = function (dir) {
  const list = fs.readdirSync(dir)
  return list.filter(
    function (value) {
      return fs.statSync(dir + '/' + value).isFile()
    }
  )
}

exports.getDataDir = function (app) {
  return app.getPath('userData')
}

exports.save = function (filename, txt) {
  console.log('>>save()')
  try {
    mkdirp(path.getDirName(path), function (err) {
      if (err) {
        throw err
      }
      fs.writeFileSync(path.join(this.getDataDir(), filename), txt, 'utf-8')
    })
    fs.writeFileSync(path.join(this.getDataDir(), filename), txt, 'utf-8')
  } catch (err) {
    throw err
  }
}

exports.saveWithBase64 = function (path, buf) {
  const b = new Buffer(buf)
  const b64Txt = b.toString('base64')
  var obj = { 'buf': b64Txt }
  try {
    fs.writeFileSync(path, JSON.stringify(obj), 'utf-8')
    console.log('Saved to' + path)
  } catch (err) {
    throw err
  }
}

exports.load = function (path) {
  const encoding = 'UTF-8'
  console.log('load:' + path)
  try {
    const jsonStr = fs.readFileSync(path, encoding)
    const json = JSON.parse(jsonStr.toString())
    const b = new Buffer(json['buf'], 'base64')
    return b.toString()
  } catch (err) {
    console.log(err)
    // return empty string when the buffer file is not found
    return ''
  }
}

exports.prepareDirIfNotExist = function (target) {
  mkdirp(target, function (err) {
    if (err) {
      throw err
    } else {
      // success
    }
  })
}
<|endoftext|>


<commit_before>'using strict';

/* Directives */

angular.module('workbenchFilters', [])
	.filter('address', function() {
		return function(val, opts, bigendian) {
			var buf = [];
			bigendian = bigendian || false;

			switch (opts.encoding || "hex") {
				case "hex":
					buf = _.map(
							_.filter(parseInt(val, 10).toString(16).split(/(..)/),
							function(x) { return x !== ''; }),
						function(x) { return ("0" + x).substr(-2); });

					if (bigendian) {
						return (buf.reverse().join(":") + ":00:00:00").substr(11);
					} else {
						return ("00:00:00:" + buf.join(":")).substr(-11);
					}
					break;

				case "bytes":
					buf = _.map(
							_.filter(parseInt(val, 10).toString(16).split(/(..)/),
							function(x) { return x !== ''; }),
						function(x) { return parseInt(x, 16); });

					return (bigendian ? buf.reverse() : buf).join(".");

				default:
					return val;
			}
		};
	})
	.filter('byte', function() {
		return function(val, i, enc, base) {
			base = parseInt(base || 10, 10);
			if (undefined === val) {
				return "";
			}

			var ret = parseInt(val, base) >> (parseInt(i, 10)*8) & 255;

			switch (enc) {
				case "hex":   return ("0" + ret.toString(16)).substr(-2, 2);
				case "ascii": return String.fromCharCode(ret);
				default:      return ret;
			}
		};
	});
<commit_msg>Fix T14 - Address encoding<commit_after>'using strict';

/* Directives */

angular.module('workbenchFilters', [])
	.filter('address', function() {
		return function(val, opts, bigendian) {
			var buf;
			bigendian = bigendian || false;

			switch (opts.encoding || "hex") {
				case "hex":
					buf = ["00", "00", "00", "00"];
					_.each(_.filter(parseInt(val, 10).toString(16).split(/(..)/),
							function(x) { return x !== ''; }),
						function(x) {
							if (bigendian) {
								buf.push(("0" + x).substr(-2));
							} else {
								buf.unshift(("0" + x).substr(-2));
							}
						});

					return (bigendian ? buf.slice(-4, 7) : buf.slice(0, 4)).join(":");

				case "bytes":
					buf = [0, 0, 0, 0];
					_.each(_.filter(parseInt(val, 10).toString(16).split(/(..)/),
							function(x) { return x !== ''; }),
						function(x) {
							if (bigendian) {
								buf.push(parseInt(x, 16));
							} else {
								buf.unshift(parseInt(x, 16));
							}
						});

					return (bigendian ? buf.slice(-4, 7) : buf.slice(0, 4)).join(".");

				default:
					return val;
			}
		};
	})
	.filter('byte', function() {
		return function(val, i, enc, base) {
			base = parseInt(base || 10, 10);
			if (undefined === val) {
				return "";
			}

			var ret = parseInt(val, base) >> (parseInt(i, 10)*8) & 255;

			switch (enc) {
				case "hex":   return ("0" + ret.toString(16)).substr(-2, 2);
				case "ascii": return String.fromCharCode(ret);
				default:      return ret;
			}
		};
	});
<|endoftext|>


<commit_before>// Helper functions (github: anvaka/gist:3815296)
function functionReplacer(key, value) {
    if (typeof(value) === 'function') {
        return value.toString();
    }
    return value;
}

function functionReviver(key, value) {
    if (key === "") return value;

    if (typeof value === 'string') {
        var rfunc = /function[^\(]*\(([^\)]*)\)[^\{]*{([^\}]*)\}/,
            match = value.match(rfunc);

        if (match) {
            var args = match[1].split(',').map(function(arg) { return arg.replace(/\s+/, ''); });
            return new Function(args, match[2]);
        }
    }
    return value;
}

/*
var person = {
    name : 'John Smith',
    age : 42,
    isJohn: function() {
        return !!this.name.match(/John/);
    }
};

var jsonString = JSON.stringify(person, functionReplacer);
var restoredPerson = JSON.parse(jsonString, functionReviver);

console.log(restoredPerson.isJohn());
*/
<commit_msg>Final fixes and changes<commit_after>// Helper functions (github: anvaka/gist:3815296)
function functionReplacer(key, value) {
    if (typeof(value) === 'function') {
        return value.toString();
    }
    return value;
}

function functionReviver(key, value) {
    if (key === "") return value;

    if (typeof value === 'string') {
        var rfunc = /function[^\(]*\(([^\)]*)\)[^\{]*{([^\}]*)\}/,
            match = value.match(rfunc);

        if (match) {
            var args = match[1].split(',').map(function(arg) { return arg.replace(/\s+/, ''); });
            return new Function(args, match[2]);
        }
    }
    return value;
}
<|endoftext|>


<commit_before>(function (root, factory) {
	if ( typeof define === 'function' && define.amd ) {
		define('houdini', factory(root));
	} else if ( typeof exports === 'object' ) {
		module.exports = factory(root);
	} else {
		root.houdini = factory(root);
	}
})(this, function (root) {

	'use strict';

	//
	// Variables
	//

	var exports = {}; // Object for public APIs
	var supports = !!document.querySelector && !!root.addEventListener; // Feature test
	var settings; // Script settings
	var toggles; // Toggle nodes list
	var eventListeners = []; //Listeners array

	// Default settings
	var defaults = {
		toggleActiveClass: 'active',
		contentActiveClass: 'active',
		initClass: 'js-houdini',
		callbackBefore: function () {},
		callbackAfter: function () {}
	};

	//
	// Methods
	//

	/**
	 * A simple forEach() implementation for Arrays, Objects and NodeLists
	 * @private
	 * @param {Array|Object|NodeList} collection Collection of items to iterate
	 * @param {Function} callback Callback function for each iteration
	 * @param {Array|Object|NodeList} scope Object/NodeList/Array that forEach is iterating over (aka `this`)
	 */
	var forEach = function (collection, callback, scope) {
		if (Object.prototype.toString.call(collection) === '[object Object]') {
			for (var prop in collection) {
				if (Object.prototype.hasOwnProperty.call(collection, prop)) {
					callback.call(scope, collection[prop], prop, collection);
				}
			}
		} else {
			for (var i = 0, len = collection.length; i < len; i++) {
				callback.call(scope, collection[i], i, collection);
			}
		}
	};

	/**
	 * Merge defaults with user options
	 * @private
	 * @param {Object} defaults Default settings
	 * @param {Object} options User options
	 * @returns {Object} Merged values of defaults and options
	 */
	var extend = function ( defaults, options ) {
		var extended = {};
		forEach(defaults, function (value, prop) {
			extended[prop] = defaults[prop];
		});
		forEach(options, function (value, prop) {
			extended[prop] = options[prop];
		});
		return extended;
	};

	/**
	 * Stop YouTube, Vimeo, and HTML5 videos from playing when leaving the slide
	 * @private
	 * @param  {Element} content The content container the video is in
	 * @param  {String} activeClass The class asigned to expanded content areas
	 */
	var stopVideos = function ( content, activeClass ) {
		if ( !content.classList.contains( activeClass ) ) {
			var iframe = content.querySelector( 'iframe');
			var video = content.querySelector( 'video' );
			if ( iframe ) {
				var iframeSrc = iframe.src;
				iframe.src = iframeSrc;
			}
			if ( video ) {
				video.pause();
			}
		}
	};

	/**
	 * Close all content areas in an expand/collapse group
	 * @private
	 * @param  {Element} toggle The element that toggled the expand or collapse
	 * @param  {Object} settings
	 */
	var closeCollapseGroup = function ( toggle, settings ) {
		if ( !toggle.classList.contains( settings.toggleActiveClass ) && toggle.hasAttribute('data-group') ) {

			// Get all toggles in the group
			var groupName = toggle.getAttribute('data-group');
			var group = document.querySelectorAll('[data-group="' + groupName + '"]');

			// Deactivate each toggle and it's content area
			forEach(group, function (item) {
				var content = document.querySelector( item.getAttribute('data-collapse') );
				item.classList.remove( settings.toggleActiveClass );
				content.classList.remove( settings.contentActiveClass );
			});

		}
	};

	/**
	 * Toggle the collapse/expand widget
	 * @public
	 * @param  {Element} toggle The element that toggled the expand or collapse
	 * @param  {String} contentID The ID of the content area to expand or collapse
	 * @param  {Object} options
	 * @param  {Event} event
	 */
	exports.toggleContent = function (toggle, contentID, options, event) {

		var settings = extend( settings || defaults, options || {} );  // Merge user options with defaults
		var content = document.querySelector(contentID); // Get content area

		// If toggle is a link, prevent default click event
		if ( toggle && toggle.tagName.toLowerCase() === 'a' && event ) {
			event.preventDefault();
		}

		settings.callbackBefore( toggle, contentID ); // Run callbacks before toggling content

		// Toggle collapse element
		closeCollapseGroup(toggle, settings); // Close collapse group items
		toggle.classList.toggle( settings.toggleActiveClass );// Change text on collapse toggle
		content.classList.toggle( settings.contentActiveClass ); // Collapse or expand content area
		stopVideos( content, settings.contentActiveClass ); // If content area is closed, stop playing any videos

		settings.callbackAfter( toggle, contentID ); // Run callbacks after toggling content

	};

	/**
	 * Destroy the current initialization.
	 */
	exports.destroy = function () {
		if ( !settings ) return;
		document.documentElement.classList.remove( settings.initClass );
		if ( toggles ) {
			forEach( toggles, function ( toggle, index ) {
				toggle.removeEventListener( 'click', eventListeners[index], false );
			});
			eventListeners = [];
		}
		settings = null;
		toggles = null;
	};

	/**
	 * Initialize Houdini
	 * @public
	 * @param {Object} options User settings
	 */
	exports.init = function ( options ) {

		// feature test
		if ( !supports ) return;

		// Destroy any existing initializations
		exports.destroy();

		// Selectors and variables
		settings = extend( defaults, options || {} ); // Merge user options with defaults

		// Add class to HTML element to activate conditional CSS
		document.documentElement.classList.add( settings.initClass );

		// Whenever a toggle is clicked, run the expand/collapse function
		toggles = document.querySelectorAll('[data-collapse]'); // Get all collapse toggles
		forEach(toggles, function (toggle, index) {
			eventListeners[index] = exports.toggleContent.bind( null, toggle, toggle.getAttribute('data-collapse'), settings );
			toggle.addEventListener('click', eventListeners[index], false);
		});

	};

	//
	// Public APIs
	//

	return exports;

});<commit_msg>Added JSDoc tag<commit_after>(function (root, factory) {
	if ( typeof define === 'function' && define.amd ) {
		define('houdini', factory(root));
	} else if ( typeof exports === 'object' ) {
		module.exports = factory(root);
	} else {
		root.houdini = factory(root);
	}
})(this, function (root) {

	'use strict';

	//
	// Variables
	//

	var exports = {}; // Object for public APIs
	var supports = !!document.querySelector && !!root.addEventListener; // Feature test
	var settings; // Script settings
	var toggles; // Toggle nodes list
	var eventListeners = []; //Listeners array

	// Default settings
	var defaults = {
		toggleActiveClass: 'active',
		contentActiveClass: 'active',
		initClass: 'js-houdini',
		callbackBefore: function () {},
		callbackAfter: function () {}
	};

	//
	// Methods
	//

	/**
	 * A simple forEach() implementation for Arrays, Objects and NodeLists
	 * @private
	 * @param {Array|Object|NodeList} collection Collection of items to iterate
	 * @param {Function} callback Callback function for each iteration
	 * @param {Array|Object|NodeList} scope Object/NodeList/Array that forEach is iterating over (aka `this`)
	 */
	var forEach = function (collection, callback, scope) {
		if (Object.prototype.toString.call(collection) === '[object Object]') {
			for (var prop in collection) {
				if (Object.prototype.hasOwnProperty.call(collection, prop)) {
					callback.call(scope, collection[prop], prop, collection);
				}
			}
		} else {
			for (var i = 0, len = collection.length; i < len; i++) {
				callback.call(scope, collection[i], i, collection);
			}
		}
	};

	/**
	 * Merge defaults with user options
	 * @private
	 * @param {Object} defaults Default settings
	 * @param {Object} options User options
	 * @returns {Object} Merged values of defaults and options
	 */
	var extend = function ( defaults, options ) {
		var extended = {};
		forEach(defaults, function (value, prop) {
			extended[prop] = defaults[prop];
		});
		forEach(options, function (value, prop) {
			extended[prop] = options[prop];
		});
		return extended;
	};

	/**
	 * Stop YouTube, Vimeo, and HTML5 videos from playing when leaving the slide
	 * @private
	 * @param  {Element} content The content container the video is in
	 * @param  {String} activeClass The class asigned to expanded content areas
	 */
	var stopVideos = function ( content, activeClass ) {
		if ( !content.classList.contains( activeClass ) ) {
			var iframe = content.querySelector( 'iframe');
			var video = content.querySelector( 'video' );
			if ( iframe ) {
				var iframeSrc = iframe.src;
				iframe.src = iframeSrc;
			}
			if ( video ) {
				video.pause();
			}
		}
	};

	/**
	 * Close all content areas in an expand/collapse group
	 * @private
	 * @param  {Element} toggle The element that toggled the expand or collapse
	 * @param  {Object} settings
	 */
	var closeCollapseGroup = function ( toggle, settings ) {
		if ( !toggle.classList.contains( settings.toggleActiveClass ) && toggle.hasAttribute('data-group') ) {

			// Get all toggles in the group
			var groupName = toggle.getAttribute('data-group');
			var group = document.querySelectorAll('[data-group="' + groupName + '"]');

			// Deactivate each toggle and it's content area
			forEach(group, function (item) {
				var content = document.querySelector( item.getAttribute('data-collapse') );
				item.classList.remove( settings.toggleActiveClass );
				content.classList.remove( settings.contentActiveClass );
			});

		}
	};

	/**
	 * Toggle the collapse/expand widget
	 * @public
	 * @param  {Element} toggle The element that toggled the expand or collapse
	 * @param  {String} contentID The ID of the content area to expand or collapse
	 * @param  {Object} options
	 * @param  {Event} event
	 */
	exports.toggleContent = function (toggle, contentID, options, event) {

		var settings = extend( settings || defaults, options || {} );  // Merge user options with defaults
		var content = document.querySelector(contentID); // Get content area

		// If toggle is a link, prevent default click event
		if ( toggle && toggle.tagName.toLowerCase() === 'a' && event ) {
			event.preventDefault();
		}

		settings.callbackBefore( toggle, contentID ); // Run callbacks before toggling content

		// Toggle collapse element
		closeCollapseGroup(toggle, settings); // Close collapse group items
		toggle.classList.toggle( settings.toggleActiveClass );// Change text on collapse toggle
		content.classList.toggle( settings.contentActiveClass ); // Collapse or expand content area
		stopVideos( content, settings.contentActiveClass ); // If content area is closed, stop playing any videos

		settings.callbackAfter( toggle, contentID ); // Run callbacks after toggling content

	};

	/**
	 * Destroy the current initialization.
	 * @public
	 */
	exports.destroy = function () {
		if ( !settings ) return;
		document.documentElement.classList.remove( settings.initClass );
		if ( toggles ) {
			forEach( toggles, function ( toggle, index ) {
				toggle.removeEventListener( 'click', eventListeners[index], false );
			});
			eventListeners = [];
		}
		settings = null;
		toggles = null;
	};

	/**
	 * Initialize Houdini
	 * @public
	 * @param {Object} options User settings
	 */
	exports.init = function ( options ) {

		// feature test
		if ( !supports ) return;

		// Destroy any existing initializations
		exports.destroy();

		// Selectors and variables
		settings = extend( defaults, options || {} ); // Merge user options with defaults

		// Add class to HTML element to activate conditional CSS
		document.documentElement.classList.add( settings.initClass );

		// Whenever a toggle is clicked, run the expand/collapse function
		toggles = document.querySelectorAll('[data-collapse]'); // Get all collapse toggles
		forEach(toggles, function (toggle, index) {
			eventListeners[index] = exports.toggleContent.bind( null, toggle, toggle.getAttribute('data-collapse'), settings );
			toggle.addEventListener('click', eventListeners[index], false);
		});

	};

	//
	// Public APIs
	//

	return exports;

});<|endoftext|>


<commit_before>module.exports = {
    'da_DK': {
        months : "januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"),
            monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),
            weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),
            weekdaysShort : "søn_man_tir_ons_tor_fre_lør".split("_"),
            weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"),
            longDateFormat : {
            LT : "HH:mm",
            L : "DD-MM-YYYY",
            LL : "D MMM YYYY",
            LLL : "D MMMM YYYY LT",
            LLLL : "dddd D. MMMM, YYYY LT"
        },
        calendar : {
            sameDay : '[I dag kl.] LT',
            nextDay : '[I morgen kl.] LT',
            nextWeek : 'dddd [kl.] LT',
            lastDay : '[I går kl.] LT',
            lastWeek : '[sidste] dddd [kl] LT',
            sameElse : 'L'
        },
        relativeTime : {
            future : "om %s",
            past : "%s siden",
            s : "få sekunder",
            m : "et minut",
            mm : "%d minutter",
            h : "en time",
            hh : "%d timer",
            d : "en dag",
            dd : "%d dage",
            M : "en måned",
            MM : "%d måneder",
            y : "et år",
            yy : "%d år"
        },
        ordinal : '%d.',
            week : {
            dow : 1, // Monday is the first day of the week.
            doy : 4  // The week that contains Jan 4th is the first week of the year.
        }
    }
};<commit_msg>too much nesting<commit_after>module.exports = {
    months : "januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december".split("_"),
        monthsShort : "jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec".split("_"),
        weekdays : "søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag".split("_"),
        weekdaysShort : "søn_man_tir_ons_tor_fre_lør".split("_"),
        weekdaysMin : "sø_ma_ti_on_to_fr_lø".split("_"),
        longDateFormat : {
        LT : "HH:mm",
        L : "DD-MM-YYYY",
        LL : "D MMM YYYY",
        LLL : "D MMMM YYYY LT",
        LLLL : "dddd D. MMMM, YYYY LT"
    },
    calendar : {
        sameDay : '[I dag kl.] LT',
        nextDay : '[I morgen kl.] LT',
        nextWeek : 'dddd [kl.] LT',
        lastDay : '[I går kl.] LT',
        lastWeek : '[sidste] dddd [kl] LT',
        sameElse : 'L'
    },
    relativeTime : {
        future : "om %s",
        past : "%s siden",
        s : "få sekunder",
        m : "et minut",
        mm : "%d minutter",
        h : "en time",
        hh : "%d timer",
        d : "en dag",
        dd : "%d dage",
        M : "en måned",
        MM : "%d måneder",
        y : "et år",
        yy : "%d år"
    },
    ordinal : '%d.',
        week : {
        dow : 1, // Monday is the first day of the week.
        doy : 4  // The week that contains Jan 4th is the first week of the year.
    }
};<|endoftext|>


<commit_before>/*! jquery.js
 * jQuery JavaScript Library v1.9.1
 * http://jquery.com/
 *
 * Includes Sizzle.js
 * http://sizzlejs.com/
 *
 * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors
 * Released under the MIT license
 * http://jquery.org/license
 *
 * Date: 2013-2-4
 *
 * Sizzle CSS Selector Engine
 * Copyright 2012 jQuery Foundation and other contributors
 * Released under the MIT license
 * http://sizzlejs.com/
 */

/*! bowser.js
 * Bowser - a browser detector
 * https://github.com/ded/bowser
 * MIT License | (c) Dustin Diaz 2014
 */

/*! base64-binary.js
 * Sept 12 2013 (M. Martinez): Slight modification to better handle padding.

 Copyright (c) 2011, Daniel Guerrero
 All rights reserved.

 Redistribution and use in source and binary forms, with or without
 modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 notice, this list of conditions and the following disclaimer in the
 documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 DISCLAIMED. IN NO EVENT SHALL DANIEL GUERRERO BE LIABLE FOR ANY
 DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*! pako-inflate.js
 (The MIT License)

 Copyright (C) 2014 by Vitaly Puzrin

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

/*! numerics.js
 Numeric Javascript
 Copyright (C) 2011 by Sébastien Loisel

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 */

/*! papaya.js
Copyright (c) 2012-2013, RII-UTHSCSA
All rights reserved.

    THIS PRODUCT IS NOT FOR CLINICAL USE.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:

    - Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.

    - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided with the distribution.

- Neither the name of the RII-UTHSCSA nor the names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
    INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
    WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
<commit_msg>removed license file<commit_after><|endoftext|>


<commit_before>"use strict";

window.onload = function() {
    /* If someone includes the script twice (which has happened), the mega menu throws
     * open and close events simultaneously, meaning it doesn't work at all. So here
     * we'll make sure we don't accidentally draw it twice. */
    if(typeof mm !== 'undefined'){
        console.log("megamenu script already present");
        return;
    }
    else {
        var mm = "loaded";
    }

    if(!('classList' in document.body))
        return

    // This gets replaced by a gulp file.
    const menuBarHeight = MENUBARHEIGHT;

    document.head.insertAdjacentHTML('beforeend', '<style media="all">{$cssmin}</style>');
    document.body.insertAdjacentHTML('beforeend', '{$svg}');
    document.body.insertAdjacentHTML('beforeend', '<!-- Thanks https://github.com/FortAwesome/Font-Awesome for MegaMenu Icons -->');
    document.body.insertAdjacentHTML('beforeend', '{$lmm}');
    // add to the existing margin
    document.body.style.marginTop = (parseInt(window.getComputedStyle(document.body).marginTop) + menuBarHeight) + 'px';

    let $lmm = document.getElementsByClassName('lmm')[0];
    let $pane_underlay = document.getElementsByClassName('lmm-pane-underlay')[0];
    let $underlay = document.getElementsByClassName('lmm-underlay')[0];
    let $cats = $lmm.getElementsByClassName('lmm-cats')[0]
    let $homesPane = $lmm.getElementsByClassName('lmm-homes-pane')[0];
    let $searchBox = $lmm.getElementsByClassName('lmm-q')[0];

    // convenience function to loop over a set of elements
    let foreach = function (array, callback, scope) {
      for (let i = 0; i < array.length; i++) {
        callback.call(scope, i, array[i]);
      }
    };

    // make a couple site specific adjustments
    // Authenticated Drupal's file browser
    let makeRelative = true;
    if(window.location.pathname.indexOf('/imce') === 0){
        $lmm.style.display = 'none';
    }
    // Authenticated Drupal, 7 then 8
    else if(document.body.classList.contains('admin-menu') || document.getElementById('toolbar-administration')){
        $lmm.style.display = 'none';
    }
    // Moodle
    else if(window.location.hostname.indexOf('mrooms') >= 0 ||
            window.location.hostname.indexOf('classes.lanecc') >= 0){
        // some classes have an extra top menubar
        if(!! document.getElementById('yui_3_17_2_1_1469040182301_520')){
            document.getElementById('yui_3_17_2_1_1469040182301_520').style.marginTop = menuBarHeight + 'px';
        }

        // administering classes under some themes shows this
        if(!! document.querySelector('#page-content .block_settings')){
            document.querySelector('#page-content .block_settings').style.paddingTop = '3em';
        }

        //boost theme - push big page elements down some
        let cssFiles = document.getElementsByTagName('link');
        let boost=false;
        for(var i=0;i<cssFiles.length;i++){
            if(cssFiles[i].href.indexOf('boost')>0){
               boost=true;
            }
        }
        if(boost){
          document.querySelector('header').style.top = menuBarHeight + 'px';
          document.getElementById('page').style.marginTop = 50 + menuBarHeight + 'px';
          document.getElementById('nav-drawer').style.top = 50 + menuBarHeight + 'px';
        }
    }
    // Wordpress
    // I'm fairly confident this if block can be removed, but that's pending additional testing
    else if(document.body.classList.contains('admin-bar')){
        let adminBar = document.getElementById('wpadminbar');
        let cHeight = parseInt(window.getComputedStyle(adminBar, null).height);
        $lmm.style.top = cHeight + "px";
        $lmm.style.zIndex = 800;
        let underlayMargin = parseInt(window.getComputedStyle($pane_underlay, null).height);
        $pane_underlay.style.marginTop = (underlayMargin + cHeight) + "px";
    }
    else if(document.body.classList.contains('masthead-fixed') && document.body.classList.contains('blog')){
      document.getElementById('masthead').style.position = 'relative';
    }
    else if(!!document.getElementById('twentytwelve-fonts-css')){
      makeRelative = false;
    }
    else if(!!document.getElementById('wpadminbar')){
      $lmm.style.display = 'none';
    }

    /* It used to be that we'd check and see if the body was relative position, then slide up. But IE11 didn't like that,
     * so we'll just set all bodies to relative always - a trick google translate does - and then move ourselves up a little
     * more
     */
    if(makeRelative){
      document.body.style.position = 'relative';
      $lmm.style.top = '-' + (menuBarHeight + 1) + 'px';
      $pane_underlay.style.top = -1 + 'px';
    }

    // add GA tracking to each link
    let links = $lmm.querySelectorAll('a:not(.skip)');
    foreach(links, function(index, value){
        links[index].setAttribute('href', links[index].getAttribute('href') + "?itm_source=" + window.location.hostname + "&itm_campaign=megamenu");
    });

    //Stop random pane clicks from closing us, except on the closer
    let topLevelKids = $lmm.getElementsByClassName('lmm-toplevel');
    let combined = [];
    for(let i=0; i<topLevelKids.length; i++){
        combined = combined.concat(Array.prototype.slice.call(topLevelKids.item(i).children));
    }
    combined = combined.concat(Array.prototype.slice.call($lmm.getElementsByClassName('lmm-homes-pane')[0].children));
    foreach(combined, function(index, value){
        if(!combined[index].classList.contains('lmm-closer')){
            combined[index].addEventListener('click', function(e){
                e.stopPropagation();
            });
        }
    });

    function fadeOut(element) {
        if(window.getComputedStyle(element, null).opacity == 0 || window.getComputedStyle(element, null).display == 'none')
            return

        element.classList.add('fade-out');
        if(!element.classList.contains('lmm-side-pane'))
            element.style.height = 0;
        element.style.display = "none";
        if(element.classList.contains('fade-in')){
            element.classList.remove('fade-in');
        }
    }

    function fadeIn(element) {
        if(window.getComputedStyle(element, null).opacity > 0 && window.getComputedStyle(element, null).display != 'none')
            return

        element.classList.add('fade-in');
        if(!element.classList.contains('lmm-side-pane'))
            element.style.removeProperty('height');
        element.style.removeProperty('display');
        if(element.classList.contains('fade-out')){
            element.classList.remove('fade-out');
        }
    }

    function visible(element){
        return !(window.getComputedStyle(element, null).opacity == 0 || window.getComputedStyle(element, null).display == 'none');
    }

    /* Pop open a search options box
       This has been deliberately not put on a visibility toggle, because
       people tend to click on the search box after setting search options */
    $searchBox.addEventListener('click', function(e){
        $underlay.style.display = 'block';
        fadeOut($homesPane);

        $lmm.getElementsByClassName('lmm-search')[0].style.flex = "1 0 auto";

        let active = $lmm.getElementsByClassName('lmm-active');
        if(active.length){
            fadeOut($pane_underlay);
            fadeOut($lmm.querySelector('.lmm-active .lmm-pane-container'));
            active[0].classList.remove('lmm-active');
        }

        fadeIn($lmm.getElementsByClassName('lmm-searchops')[0]);
    }, false);

    /* Similarly, pop open the homes button box */
    $lmm.getElementsByClassName('lmm-logo')[0].addEventListener('click', function(e){
        let active = $lmm.getElementsByClassName('lmm-active');
        if(active.length){
            fadeOut($pane_underlay);
            fadeOut($lmm.querySelector('.lmm-active .lmm-pane-container'));
            active[0].classList.remove('lmm-active');
        }
        fadeOut($lmm.getElementsByClassName('lmm-searchops')[0]);
        $lmm.getElementsByClassName('lmm-search')[0].removeAttribute('style');

        if($homesPane.classList.contains('fade-in')){
            fadeOut($homesPane);
            $underlay.style.display = 'none';
        }
        else{
            $underlay.style.display = 'block';
            fadeIn($homesPane);
        }
    }, false);

    // closes everything
    function closeAll(e){
        var panes = $lmm.getElementsByClassName('lmm-side-pane');
        for(let i=0; i<panes.length; i++){
          fadeOut(panes[i]);
        }

        $lmm.getElementsByClassName('lmm-search')[0].removeAttribute('style');

        let active = $lmm.getElementsByClassName('lmm-active');
        if (active.length){
            fadeOut($pane_underlay);
            fadeOut($lmm.querySelector('.lmm-active .lmm-pane-container'));
            active[0].classList.remove('lmm-active');
        }
        $underlay.style.display = 'none';
    }
    $underlay.addEventListener('click', closeAll);
    $pane_underlay.getElementsByClassName('lmm-closer')[0].addEventListener('click', closeAll);

    /* Handle the radio buttons for the search box */
    function handleRadioClick(e){
        let dest = 'lmm-search-web';
        let opts = $lmm.querySelectorAll('.lmm-searchops input');
        for(let i=0;i<opts.length; i++){
          if(opts[i].checked)
              dest = opts[i].getAttribute('id');
        }

        if(dest == "lmm-search-web"){
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('method', 'get');
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('action', 'https://www.lanecc.edu/custom/search/');
            $searchBox.setAttribute('name','q');
            $lmm.getElementsByClassName('lmm-search-label')[0].textContent = 'Search Lane\'s websites';
            $searchBox.setAttribute('placeholder', 'search all Lane websites');
        }
        else if(dest == "lmm-search-ce"){
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('method', 'post');
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('action', 'https://lanecc.augusoft.net/index.cfm?method=ClassListing.ClassListingDisplay');
            $searchBox.setAttribute('name','Keywords');
            $lmm.getElementsByClassName('lmm-search-label')[0].textContent = 'Search Continuing Education classes';
            $searchBox.setAttribute('placeholder', 'search Continuing Education classes');
        }
        else if(dest == "lmm-search-people"){
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('method', 'get');
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('action', 'https://directory.lanecc.edu/search');
            $searchBox.setAttribute('name','search');
            $lmm.getElementsByClassName('lmm-search-label')[0].textContent = 'Search people at Lane';
            $searchBox.setAttribute('placeholder', 'search the Employee Directory');
        }
        $searchBox.focus();
        e.stopPropagation();
    }

    let radios = $lmm.querySelectorAll('.lmm-searchops input');
    for(let i=0;i<radios.length; i++){
        radios[i].addEventListener('click', handleRadioClick);
    }

    // Handle opening and closing panes
    function paneClick(e){

        // close up the sides
        let panes = $lmm.getElementsByClassName('lmm-side-pane');
        for(let i =0; i<panes.length; i++){
            fadeOut(panes[i]);
        }
        $lmm.getElementsByClassName('lmm-search')[0].removeAttribute('style');
        $searchBox.style.flex = "1 1 auto";

        let openPane = null;
        let containers = $lmm.getElementsByClassName('lmm-pane-container');
        for(let i=0;i<containers.length;i++){
            if(visible(containers[i])){
                openPane = containers[i];
            }
        }
        let clickedPane = this.getElementsByClassName('lmm-pane-container')[0];
        if (openPane != null){
            // if we're open, close us
            if(openPane == clickedPane){
                fadeOut($pane_underlay);
                fadeOut(clickedPane);
                this.classList.remove('lmm-active');
            }
            // swap us with this other one
            else {
                fadeOut(openPane);
                fadeIn(clickedPane);
                $lmm.getElementsByClassName('lmm-active')[0].classList.remove('lmm-active');
                this.classList.add('lmm-active');
            }
        }
        // open this pane
        else{
            this.classList.add('lmm-active');
            fadeIn(clickedPane);
            fadeIn($pane_underlay);
            $underlay.style.display = 'block';
        }
        e.stopPropagation();
    }

    let top = $lmm.getElementsByClassName('lmm-toplevel')
    for(let i=0;i<top.length;i++){
        top[i].addEventListener('click', paneClick);
    }

    // Figure out the left margin for lmm-cats.
    function onResize(){
        let width = 820;
        if(window.innerWidth < 820){
            let activeTab = $lmm.getElementsByClassName('lmm-active')[0];
            if (activeTab != null){
                activeTab.classList.remove('lmm-active');
                activeTab.getElementsByClassName('lmm-pane-container')[0].style.height = 0;
                activeTab.getElementsByClassName('lmm-pane-container')[0].style.display = 'none';
                fadeOut($pane_underlay);
                $underlay.style.display = 'none';
            }
        }
        if(window.innerWidth >= 940){
            width = 940;
        }
        if(window.innerWidth >= 1200){
            width = 1180;
        }
        let leftmargin = Math.floor(window.innerWidth - width) / 2 - 14;
        //keeps us from sliding under the logo
        if(leftmargin < 0){
            leftmargin = 0;
        }
        $cats.style.marginLeft = leftmargin + "px";

        /* On sites with a fixed width, if the document is wider than the viewport, it's possible for the MegaMenu to
        to be sized incorrectly. Make that adjustment here. Need to fire this on resize, since some sites render
        wider than they actually are, then shrink, so we may need to recalculate later. */
        if(window.innerWidth < document.width){
            $lmm.style.width = document.width;
            $pane_underlay.style.width = document.width;
            $underlay.style.width = document.width;
        }
        else {
            $lmm.style.width = "100%";
            $pane_underlay.style.width = "100%";
            $underlay.style.width = "100%";
        }
    }
    onResize();
    window.addEventListener('resize', onResize);
};<commit_msg>close #60, remove foreaach<commit_after>"use strict";

window.onload = function() {
    /* If someone includes the script twice (which has happened), the mega menu throws
     * open and close events simultaneously, meaning it doesn't work at all. So here
     * we'll make sure we don't accidentally draw it twice. */
    if(typeof mm !== 'undefined'){
        console.log("megamenu script already present");
        return;
    }
    else {
        var mm = "loaded";
    }

    if(!('classList' in document.body))
        return

    // This gets replaced by a gulp file.
    const menuBarHeight = MENUBARHEIGHT;

    document.head.insertAdjacentHTML('beforeend', '<style media="all">{$cssmin}</style>');
    document.body.insertAdjacentHTML('beforeend', '{$svg}');
    document.body.insertAdjacentHTML('beforeend', '<!-- Thanks https://github.com/FortAwesome/Font-Awesome for MegaMenu Icons -->');
    document.body.insertAdjacentHTML('beforeend', '{$lmm}');
    // add to the existing margin
    document.body.style.marginTop = (parseInt(window.getComputedStyle(document.body).marginTop) + menuBarHeight) + 'px';

    let $lmm = document.getElementsByClassName('lmm')[0];
    let $pane_underlay = document.getElementsByClassName('lmm-pane-underlay')[0];
    let $underlay = document.getElementsByClassName('lmm-underlay')[0];
    let $cats = $lmm.getElementsByClassName('lmm-cats')[0]
    let $homesPane = $lmm.getElementsByClassName('lmm-homes-pane')[0];
    let $searchBox = $lmm.getElementsByClassName('lmm-q')[0];

    // make a couple site specific adjustments
    // Authenticated Drupal's file browser
    let makeRelative = true;
    if(window.location.pathname.indexOf('/imce') === 0){
        $lmm.style.display = 'none';
    }
    // Authenticated Drupal, 7 then 8
    else if(document.body.classList.contains('admin-menu') || document.getElementById('toolbar-administration')){
        $lmm.style.display = 'none';
    }
    // Moodle
    else if(window.location.hostname.indexOf('mrooms') >= 0 ||
            window.location.hostname.indexOf('classes.lanecc') >= 0){
        // some classes have an extra top menubar
        if(!! document.getElementById('yui_3_17_2_1_1469040182301_520')){
            document.getElementById('yui_3_17_2_1_1469040182301_520').style.marginTop = menuBarHeight + 'px';
        }

        // administering classes under some themes shows this
        if(!! document.querySelector('#page-content .block_settings')){
            document.querySelector('#page-content .block_settings').style.paddingTop = '3em';
        }

        //boost theme - push big page elements down some
        let cssFiles = document.getElementsByTagName('link');
        let boost=false;
        for(var i=0;i<cssFiles.length;i++){
            if(cssFiles[i].href.indexOf('boost')>0){
               boost=true;
            }
        }
        if(boost){
          document.querySelector('header').style.top = menuBarHeight + 'px';
          document.getElementById('page').style.marginTop = 50 + menuBarHeight + 'px';
          document.getElementById('nav-drawer').style.top = 50 + menuBarHeight + 'px';
        }
    }
    // Wordpress
    // I'm fairly confident this if block can be removed, but that's pending additional testing
    else if(document.body.classList.contains('admin-bar')){
        let adminBar = document.getElementById('wpadminbar');
        let cHeight = parseInt(window.getComputedStyle(adminBar, null).height);
        $lmm.style.top = cHeight + "px";
        $lmm.style.zIndex = 800;
        let underlayMargin = parseInt(window.getComputedStyle($pane_underlay, null).height);
        $pane_underlay.style.marginTop = (underlayMargin + cHeight) + "px";
    }
    else if(document.body.classList.contains('masthead-fixed') && document.body.classList.contains('blog')){
      document.getElementById('masthead').style.position = 'relative';
    }
    else if(!!document.getElementById('twentytwelve-fonts-css')){
      makeRelative = false;
    }
    else if(!!document.getElementById('wpadminbar')){
      $lmm.style.display = 'none';
    }

    /* It used to be that we'd check and see if the body was relative position, then slide up. But IE11 didn't like that,
     * so we'll just set all bodies to relative always - a trick google translate does - and then move ourselves up a little
     * more
     */
    if(makeRelative){
      document.body.style.position = 'relative';
      $lmm.style.top = '-' + (menuBarHeight + 1) + 'px';
      $pane_underlay.style.top = -1 + 'px';
    }

    // add GA tracking to each link
    let links = $lmm.querySelectorAll('a:not(.skip)');
    for(let i=0; i<links.length; i++){
        links[i].setAttribute('href', links[i].getAttribute('href') + "?itm_source=" + window.location.hostname + "&itm_campaign=megamenu");
    }

    //Stop random pane clicks from closing us, except on the closer
    let topLevelKids = $lmm.getElementsByClassName('lmm-toplevel');
    let combined = [];
    for(let i=0; i<topLevelKids.length; i++){
        combined = combined.concat(Array.prototype.slice.call(topLevelKids.item(i).children));
    }
    combined = combined.concat(Array.prototype.slice.call($lmm.getElementsByClassName('lmm-homes-pane')[0].children));
    for(let i=0; i<combined.length; i++){
        if(!combined[i].classList.contains('lmm-closer')){
            combined[i].addEventListener('click', function(e){
                e.stopPropagation();
            });
        }
    }

    function fadeOut(element) {
        if(window.getComputedStyle(element, null).opacity == 0 || window.getComputedStyle(element, null).display == 'none')
            return

        element.classList.add('fade-out');
        if(!element.classList.contains('lmm-side-pane'))
            element.style.height = 0;
        element.style.display = "none";
        if(element.classList.contains('fade-in')){
            element.classList.remove('fade-in');
        }
    }

    function fadeIn(element) {
        if(window.getComputedStyle(element, null).opacity > 0 && window.getComputedStyle(element, null).display != 'none')
            return

        element.classList.add('fade-in');
        if(!element.classList.contains('lmm-side-pane'))
            element.style.removeProperty('height');
        element.style.removeProperty('display');
        if(element.classList.contains('fade-out')){
            element.classList.remove('fade-out');
        }
    }

    function visible(element){
        return !(window.getComputedStyle(element, null).opacity == 0 || window.getComputedStyle(element, null).display == 'none');
    }

    /* Pop open a search options box
       This has been deliberately not put on a visibility toggle, because
       people tend to click on the search box after setting search options */
    $searchBox.addEventListener('click', function(e){
        $underlay.style.display = 'block';
        fadeOut($homesPane);

        $lmm.getElementsByClassName('lmm-search')[0].style.flex = "1 0 auto";

        let active = $lmm.getElementsByClassName('lmm-active');
        if(active.length){
            fadeOut($pane_underlay);
            fadeOut($lmm.querySelector('.lmm-active .lmm-pane-container'));
            active[0].classList.remove('lmm-active');
        }

        fadeIn($lmm.getElementsByClassName('lmm-searchops')[0]);
    }, false);

    /* Similarly, pop open the homes button box */
    $lmm.getElementsByClassName('lmm-logo')[0].addEventListener('click', function(e){
        let active = $lmm.getElementsByClassName('lmm-active');
        if(active.length){
            fadeOut($pane_underlay);
            fadeOut($lmm.querySelector('.lmm-active .lmm-pane-container'));
            active[0].classList.remove('lmm-active');
        }
        fadeOut($lmm.getElementsByClassName('lmm-searchops')[0]);
        $lmm.getElementsByClassName('lmm-search')[0].removeAttribute('style');

        if($homesPane.classList.contains('fade-in')){
            fadeOut($homesPane);
            $underlay.style.display = 'none';
        }
        else{
            $underlay.style.display = 'block';
            fadeIn($homesPane);
        }
    }, false);

    // closes everything
    function closeAll(e){
        var panes = $lmm.getElementsByClassName('lmm-side-pane');
        for(let i=0; i<panes.length; i++){
          fadeOut(panes[i]);
        }

        $lmm.getElementsByClassName('lmm-search')[0].removeAttribute('style');

        let active = $lmm.getElementsByClassName('lmm-active');
        if (active.length){
            fadeOut($pane_underlay);
            fadeOut($lmm.querySelector('.lmm-active .lmm-pane-container'));
            active[0].classList.remove('lmm-active');
        }
        $underlay.style.display = 'none';
    }
    $underlay.addEventListener('click', closeAll);
    $pane_underlay.getElementsByClassName('lmm-closer')[0].addEventListener('click', closeAll);

    /* Handle the radio buttons for the search box */
    function handleRadioClick(e){
        let dest = 'lmm-search-web';
        let opts = $lmm.querySelectorAll('.lmm-searchops input');
        for(let i=0;i<opts.length; i++){
          if(opts[i].checked)
              dest = opts[i].getAttribute('id');
        }

        if(dest == "lmm-search-web"){
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('method', 'get');
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('action', 'https://www.lanecc.edu/custom/search/');
            $searchBox.setAttribute('name','q');
            $lmm.getElementsByClassName('lmm-search-label')[0].textContent = 'Search Lane\'s websites';
            $searchBox.setAttribute('placeholder', 'search all Lane websites');
        }
        else if(dest == "lmm-search-ce"){
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('method', 'post');
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('action', 'https://lanecc.augusoft.net/index.cfm?method=ClassListing.ClassListingDisplay');
            $searchBox.setAttribute('name','Keywords');
            $lmm.getElementsByClassName('lmm-search-label')[0].textContent = 'Search Continuing Education classes';
            $searchBox.setAttribute('placeholder', 'search Continuing Education classes');
        }
        else if(dest == "lmm-search-people"){
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('method', 'get');
            $lmm.getElementsByClassName('lmm-search-form')[0].setAttribute('action', 'https://directory.lanecc.edu/search');
            $searchBox.setAttribute('name','search');
            $lmm.getElementsByClassName('lmm-search-label')[0].textContent = 'Search people at Lane';
            $searchBox.setAttribute('placeholder', 'search the Employee Directory');
        }
        $searchBox.focus();
        e.stopPropagation();
    }

    let radios = $lmm.querySelectorAll('.lmm-searchops input');
    for(let i=0;i<radios.length; i++){
        radios[i].addEventListener('click', handleRadioClick);
    }

    // Handle opening and closing panes
    function paneClick(e){

        // close up the sides
        let panes = $lmm.getElementsByClassName('lmm-side-pane');
        for(let i =0; i<panes.length; i++){
            fadeOut(panes[i]);
        }
        $lmm.getElementsByClassName('lmm-search')[0].removeAttribute('style');
        $searchBox.style.flex = "1 1 auto";

        let openPane = null;
        let containers = $lmm.getElementsByClassName('lmm-pane-container');
        for(let i=0;i<containers.length;i++){
            if(visible(containers[i])){
                openPane = containers[i];
            }
        }
        let clickedPane = this.getElementsByClassName('lmm-pane-container')[0];
        if (openPane != null){
            // if we're open, close us
            if(openPane == clickedPane){
                fadeOut($pane_underlay);
                fadeOut(clickedPane);
                this.classList.remove('lmm-active');
            }
            // swap us with this other one
            else {
                fadeOut(openPane);
                fadeIn(clickedPane);
                $lmm.getElementsByClassName('lmm-active')[0].classList.remove('lmm-active');
                this.classList.add('lmm-active');
            }
        }
        // open this pane
        else{
            this.classList.add('lmm-active');
            fadeIn(clickedPane);
            fadeIn($pane_underlay);
            $underlay.style.display = 'block';
        }
        e.stopPropagation();
    }

    let top = $lmm.getElementsByClassName('lmm-toplevel')
    for(let i=0;i<top.length;i++){
        top[i].addEventListener('click', paneClick);
    }

    // Figure out the left margin for lmm-cats.
    function onResize(){
        let width = 820;
        if(window.innerWidth < 820){
            let activeTab = $lmm.getElementsByClassName('lmm-active')[0];
            if (activeTab != null){
                activeTab.classList.remove('lmm-active');
                activeTab.getElementsByClassName('lmm-pane-container')[0].style.height = 0;
                activeTab.getElementsByClassName('lmm-pane-container')[0].style.display = 'none';
                fadeOut($pane_underlay);
                $underlay.style.display = 'none';
            }
        }
        if(window.innerWidth >= 940){
            width = 940;
        }
        if(window.innerWidth >= 1200){
            width = 1180;
        }
        let leftmargin = Math.floor(window.innerWidth - width) / 2 - 14;
        //keeps us from sliding under the logo
        if(leftmargin < 0){
            leftmargin = 0;
        }
        $cats.style.marginLeft = leftmargin + "px";

        /* On sites with a fixed width, if the document is wider than the viewport, it's possible for the MegaMenu to
        to be sized incorrectly. Make that adjustment here. Need to fire this on resize, since some sites render
        wider than they actually are, then shrink, so we may need to recalculate later. */
        if(window.innerWidth < document.width){
            $lmm.style.width = document.width;
            $pane_underlay.style.width = document.width;
            $underlay.style.width = document.width;
        }
        else {
            $lmm.style.width = "100%";
            $pane_underlay.style.width = "100%";
            $underlay.style.width = "100%";
        }
    }
    onResize();
    window.addEventListener('resize', onResize);
};<|endoftext|>


<commit_before>/*======================================================
************   Navbars && Toolbars   ************
======================================================*/
// On Navbar Init Callback
app.navbarInitCallback = function (view, pageContainer, navbarContainer, navbarInnerContainer) {
    if (!navbarContainer && navbarInnerContainer) navbarContainer = $(navbarInnerContainer).parent('.navbar')[0];
    var navbarData = {
        container: navbarContainer,
        innerContainer: navbarInnerContainer
    };
    var pageData = pageContainer && pageContainer.f7PageData;

    var eventData = {
        page: pageData,
        navbar: navbarData
    };

    if (navbarInnerContainer.f7NavbarInitialized) {
        // Reinit Navbar
        app.reinitNavbar(navbarContainer, navbarInnerContainer);

        // Plugin hook
        app.pluginHook('navbarReinit', pageData);

        // Event
        $(pageData.container).trigger('navbarReinit', eventData);
        return;
    }
    navbarInnerContainer.f7NavbarInitialized = true;

    // Before Init
    app.pluginHook('navbarBeforeInit', navbarData, pageData);
    $(navbarInnerContainer).trigger('navbarBeforeInit', eventData);

    // Initialize Navbar
    app.initNavbar(navbarContainer, navbarInnerContainer);

    // On init
    app.pluginHook('navbarInit', navbarData, pageData);
    $(navbarInnerContainer).trigger('navbarInit', eventData);
};
// Navbar Remove Callback
app.navbarRemoveCallback = function (view, pageContainer, navbarContainer, navbarInnerContainer) {
    if (!navbarContainer && navbarInnerContainer) navbarContainer = $(navbarInnerContainer).parent('.navbar')[0];
    var navbarData = {
        container: navbarContainer,
        innerContainer: navbarInnerContainer
    };
    var pageData = pageContainer.f7PageData;

    var eventData = {
        page: pageData,
        navbar: navbarData
    };
    app.pluginHook('navbarBeforeRemove', navbarData, pageData);
    $(navbarInnerContainer).trigger('navbarBeforeRemove', eventData);
};
app.initNavbar = function (navbarContainer, navbarInnerContainer) {
    // Init Subnavbar Searchbar
    if (app.initSearchbar) app.initSearchbar(navbarInnerContainer);
};
app.reinitNavbar = function (navbarContainer, navbarInnerContainer) {
    // Re init navbar methods
};
app.initNavbarWithCallback = function (navbarContainer) {
    navbarContainer = $(navbarContainer);
    var viewContainer = navbarContainer.parents('.' + app.params.viewClass);
    if (viewContainer.length === 0) return;
    var view = viewContainer[0].f7View || undefined;
    navbarContainer.find('.navbar-inner').each(function () {
        app.navbarInitCallback(view, undefined, navbarContainer[0], this);
    });
};

// Size Navbars
app.sizeNavbars = function (viewContainer) {
    var navbarInner = viewContainer ? $(viewContainer).find('.navbar .navbar-inner:not(.cached)') : $('.navbar .navbar-inner:not(.cached)');
    navbarInner.each(function () {
        var n = $(this);
        if (n.hasClass('cached')) return;
        var left = app.rtl ? n.find('.right') : n.find('.left'),
            right = app.rtl ? n.find('.left') : n.find('.right'),
            center = n.find('.center'),
            subnavbar = n.find('.subnavbar'),
            noLeft = left.length === 0,
            noRight = right.length === 0,
            leftWidth = noLeft ? 0 : left.outerWidth(true),
            rightWidth = noRight ? 0 : right.outerWidth(true),
            centerWidth = center.outerWidth(true),
            navbarStyles = n.styles(),
            navbarWidth = n[0].offsetWidth - parseInt(navbarStyles.paddingLeft, 10) - parseInt(navbarStyles.paddingRight, 10),
            onLeft = n.hasClass('navbar-on-left'),
            currLeft, diff;

        if (noRight) {
            currLeft = navbarWidth - centerWidth;
        }
        if (noLeft) {
            currLeft = 0;
        }
        if (!noLeft && !noRight) {
            currLeft = (navbarWidth - rightWidth - centerWidth + leftWidth) / 2;
        }
        var requiredLeft = (navbarWidth - centerWidth) / 2;
        if (navbarWidth - leftWidth - rightWidth > centerWidth) {
            if (requiredLeft < leftWidth) {
                requiredLeft = leftWidth;
            }
            if (requiredLeft + centerWidth > navbarWidth - rightWidth) {
                requiredLeft = navbarWidth - rightWidth - centerWidth;
            }
            diff = requiredLeft - currLeft;
        }
        else {
            diff = 0;
        }
        // RTL inverter
        var inverter = app.rtl ? -1 : 1;

        if (center.hasClass('sliding')) {
            center[0].f7NavbarLeftOffset = -(currLeft + diff) * inverter;
            center[0].f7NavbarRightOffset = (navbarWidth - currLeft - diff - centerWidth) * inverter;
            if (onLeft) center.transform('translate3d(' + center[0].f7NavbarLeftOffset + 'px, 0, 0)');
        }
        if (!noLeft && left.hasClass('sliding')) {
            if (app.rtl) {
                left[0].f7NavbarLeftOffset = -(navbarWidth - left[0].offsetWidth) / 2 * inverter;
                left[0].f7NavbarRightOffset = leftWidth * inverter;
            }
            else {
                left[0].f7NavbarLeftOffset = -leftWidth;
                left[0].f7NavbarRightOffset = (navbarWidth - left[0].offsetWidth) / 2;
            }
            if (onLeft) left.transform('translate3d(' + left[0].f7NavbarLeftOffset + 'px, 0, 0)');
        }
        if (!noRight && right.hasClass('sliding')) {
            if (app.rtl) {
                right[0].f7NavbarLeftOffset = -rightWidth * inverter;
                right[0].f7NavbarRightOffset = (navbarWidth - right[0].offsetWidth) / 2 * inverter;
            }
            else {
                right[0].f7NavbarLeftOffset = -(navbarWidth - right[0].offsetWidth) / 2;
                right[0].f7NavbarRightOffset = rightWidth;
            }
            if (onLeft) right.transform('translate3d(' + right[0].f7NavbarLeftOffset + 'px, 0, 0)');
        }
        if (subnavbar.length && subnavbar.hasClass('sliding')) {
            subnavbar[0].f7NavbarLeftOffset = app.rtl ? subnavbar[0].offsetWidth : -subnavbar[0].offsetWidth;
            subnavbar[0].f7NavbarRightOffset = -subnavbar[0].f7NavbarLeftOffset;
        }

        // Center left
        var centerLeft = diff;
        if (app.rtl && noLeft && noRight && center.length > 0) centerLeft = -centerLeft;
        center.css({left: centerLeft + 'px'});

    });
};

// Hide/Show Navbars/Toolbars
app.hideNavbar = function (navbarContainer) {
    $(navbarContainer).addClass('navbar-hidden');
    return true;
};
app.showNavbar = function (navbarContainer) {
    var navbar = $(navbarContainer);
    navbar.addClass('navbar-hiding').removeClass('navbar-hidden').transitionEnd(function () {
        navbar.removeClass('navbar-hiding');
    });
    return true;
};
app.hideToolbar = function (toolbarContainer) {
    $(toolbarContainer).addClass('toolbar-hidden');
    return true;
};
app.showToolbar = function (toolbarContainer) {
    var toolbar = $(toolbarContainer);
    toolbar.addClass('toolbar-hiding').removeClass('toolbar-hidden').transitionEnd(function () {
        toolbar.removeClass('toolbar-hiding');
    });
};
<commit_msg>Fix navbarReinit<commit_after>/*======================================================
************   Navbars && Toolbars   ************
======================================================*/
// On Navbar Init Callback
app.navbarInitCallback = function (view, pageContainer, navbarContainer, navbarInnerContainer) {
    if (!navbarContainer && navbarInnerContainer) navbarContainer = $(navbarInnerContainer).parent('.navbar')[0];
    var navbarData = {
        container: navbarContainer,
        innerContainer: navbarInnerContainer
    };
    var pageData = pageContainer && pageContainer.f7PageData;

    var eventData = {
        page: pageData,
        navbar: navbarData
    };

    if (navbarInnerContainer.f7NavbarInitialized) {
        // Reinit Navbar
        app.reinitNavbar(navbarContainer, navbarInnerContainer);

        // Plugin hook
        app.pluginHook('navbarReinit', pageData);

        // Event
        $(navbarInnerContainer).trigger('navbarReinit', eventData);
        return;
    }
    navbarInnerContainer.f7NavbarInitialized = true;

    // Before Init
    app.pluginHook('navbarBeforeInit', navbarData, pageData);
    $(navbarInnerContainer).trigger('navbarBeforeInit', eventData);

    // Initialize Navbar
    app.initNavbar(navbarContainer, navbarInnerContainer);

    // On init
    app.pluginHook('navbarInit', navbarData, pageData);
    $(navbarInnerContainer).trigger('navbarInit', eventData);
};
// Navbar Remove Callback
app.navbarRemoveCallback = function (view, pageContainer, navbarContainer, navbarInnerContainer) {
    if (!navbarContainer && navbarInnerContainer) navbarContainer = $(navbarInnerContainer).parent('.navbar')[0];
    var navbarData = {
        container: navbarContainer,
        innerContainer: navbarInnerContainer
    };
    var pageData = pageContainer.f7PageData;

    var eventData = {
        page: pageData,
        navbar: navbarData
    };
    app.pluginHook('navbarBeforeRemove', navbarData, pageData);
    $(navbarInnerContainer).trigger('navbarBeforeRemove', eventData);
};
app.initNavbar = function (navbarContainer, navbarInnerContainer) {
    // Init Subnavbar Searchbar
    if (app.initSearchbar) app.initSearchbar(navbarInnerContainer);
};
app.reinitNavbar = function (navbarContainer, navbarInnerContainer) {
    // Re init navbar methods
};
app.initNavbarWithCallback = function (navbarContainer) {
    navbarContainer = $(navbarContainer);
    var viewContainer = navbarContainer.parents('.' + app.params.viewClass);
    if (viewContainer.length === 0) return;
    var view = viewContainer[0].f7View || undefined;
    navbarContainer.find('.navbar-inner').each(function () {
        app.navbarInitCallback(view, undefined, navbarContainer[0], this);
    });
};

// Size Navbars
app.sizeNavbars = function (viewContainer) {
    var navbarInner = viewContainer ? $(viewContainer).find('.navbar .navbar-inner:not(.cached)') : $('.navbar .navbar-inner:not(.cached)');
    navbarInner.each(function () {
        var n = $(this);
        if (n.hasClass('cached')) return;
        var left = app.rtl ? n.find('.right') : n.find('.left'),
            right = app.rtl ? n.find('.left') : n.find('.right'),
            center = n.find('.center'),
            subnavbar = n.find('.subnavbar'),
            noLeft = left.length === 0,
            noRight = right.length === 0,
            leftWidth = noLeft ? 0 : left.outerWidth(true),
            rightWidth = noRight ? 0 : right.outerWidth(true),
            centerWidth = center.outerWidth(true),
            navbarStyles = n.styles(),
            navbarWidth = n[0].offsetWidth - parseInt(navbarStyles.paddingLeft, 10) - parseInt(navbarStyles.paddingRight, 10),
            onLeft = n.hasClass('navbar-on-left'),
            currLeft, diff;

        if (noRight) {
            currLeft = navbarWidth - centerWidth;
        }
        if (noLeft) {
            currLeft = 0;
        }
        if (!noLeft && !noRight) {
            currLeft = (navbarWidth - rightWidth - centerWidth + leftWidth) / 2;
        }
        var requiredLeft = (navbarWidth - centerWidth) / 2;
        if (navbarWidth - leftWidth - rightWidth > centerWidth) {
            if (requiredLeft < leftWidth) {
                requiredLeft = leftWidth;
            }
            if (requiredLeft + centerWidth > navbarWidth - rightWidth) {
                requiredLeft = navbarWidth - rightWidth - centerWidth;
            }
            diff = requiredLeft - currLeft;
        }
        else {
            diff = 0;
        }
        // RTL inverter
        var inverter = app.rtl ? -1 : 1;

        if (center.hasClass('sliding')) {
            center[0].f7NavbarLeftOffset = -(currLeft + diff) * inverter;
            center[0].f7NavbarRightOffset = (navbarWidth - currLeft - diff - centerWidth) * inverter;
            if (onLeft) center.transform('translate3d(' + center[0].f7NavbarLeftOffset + 'px, 0, 0)');
        }
        if (!noLeft && left.hasClass('sliding')) {
            if (app.rtl) {
                left[0].f7NavbarLeftOffset = -(navbarWidth - left[0].offsetWidth) / 2 * inverter;
                left[0].f7NavbarRightOffset = leftWidth * inverter;
            }
            else {
                left[0].f7NavbarLeftOffset = -leftWidth;
                left[0].f7NavbarRightOffset = (navbarWidth - left[0].offsetWidth) / 2;
            }
            if (onLeft) left.transform('translate3d(' + left[0].f7NavbarLeftOffset + 'px, 0, 0)');
        }
        if (!noRight && right.hasClass('sliding')) {
            if (app.rtl) {
                right[0].f7NavbarLeftOffset = -rightWidth * inverter;
                right[0].f7NavbarRightOffset = (navbarWidth - right[0].offsetWidth) / 2 * inverter;
            }
            else {
                right[0].f7NavbarLeftOffset = -(navbarWidth - right[0].offsetWidth) / 2;
                right[0].f7NavbarRightOffset = rightWidth;
            }
            if (onLeft) right.transform('translate3d(' + right[0].f7NavbarLeftOffset + 'px, 0, 0)');
        }
        if (subnavbar.length && subnavbar.hasClass('sliding')) {
            subnavbar[0].f7NavbarLeftOffset = app.rtl ? subnavbar[0].offsetWidth : -subnavbar[0].offsetWidth;
            subnavbar[0].f7NavbarRightOffset = -subnavbar[0].f7NavbarLeftOffset;
        }

        // Center left
        var centerLeft = diff;
        if (app.rtl && noLeft && noRight && center.length > 0) centerLeft = -centerLeft;
        center.css({left: centerLeft + 'px'});

    });
};

// Hide/Show Navbars/Toolbars
app.hideNavbar = function (navbarContainer) {
    $(navbarContainer).addClass('navbar-hidden');
    return true;
};
app.showNavbar = function (navbarContainer) {
    var navbar = $(navbarContainer);
    navbar.addClass('navbar-hiding').removeClass('navbar-hidden').transitionEnd(function () {
        navbar.removeClass('navbar-hiding');
    });
    return true;
};
app.hideToolbar = function (toolbarContainer) {
    $(toolbarContainer).addClass('toolbar-hidden');
    return true;
};
app.showToolbar = function (toolbarContainer) {
    var toolbar = $(toolbarContainer);
    toolbar.addClass('toolbar-hiding').removeClass('toolbar-hidden').transitionEnd(function () {
        toolbar.removeClass('toolbar-hiding');
    });
};
<|endoftext|>


<commit_before>/*
 * gui-builder - A simple WYSIWYG HTML5 app creator
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */
"use strict";

/*
 * The palette.json properties are:
 *
 *   id:      String, internal reference this widget set
 *   name:    String, human readable name and/or description
 *   version: String, (XXX: Unused, possible future value?)
 *   widgets: Array of objects, each with the following properties:
 *
 *       name:   String, Human readable widget name (TODO: L10N?)
 *       type:   String, HTMLElement type to use with createElement()
 *       icon:   String, CSS class id for the icon representation
 *       helper: String, HTML to use for creating the drag helper
 *       code:   String, HTML to be created when inserting this widget
 *                       into the DOM
 */

function loadPalette(container) {
    var defaultContainer = '#palette-panel';
    var myContainer = container;

    if (!myContainer) {
	myContainer = $(defaultContainer);
    }

    if (!myContainer || !myContainer.get()) {
	return false;
    }

    console.log("Starting palette load...");
    myContainer.append('
Palette
');
    myContainer.append('

');

    var hdr = $('#palette_header');
    var acc = $('#palette_accordion');

    // Make use of the flex box model in CSS3 to allow the tabs
    // to grow/shrink with the window/container
    myContainer.addClass('vbox');
    hdr.addClass('flex0');
    acc.addClass('flex1');

    // FIXME: Eventually, all widgets should come from the BWidget
    //        global structure.  For now, we load them as their own
    //        subcategory in the palette
    $(acc).append('
Tizen Framework

');
    $.each(BWidget.getPaletteWidgetTypes(), function(n, id) {
        // Add new
 element to hold this widget
        var ul = $('#Tizen-widgets');
        var li = $('

').appendTo($(ul));
        $(li).button({
            label: BWidget.getDisplayLabel(id),
            icons: {primary: BWidget.getIcon(id)}
        });
        $(li).disableSelection();
        $(li).addClass('nrc-palette-widget');
        $(li).data("code", BWidget.getTemplate(id));
        $(li).data("adm-node", {type: id});

        // FIXME: This should probably be replaced by a more flexible
        //        concept of widget groups.
        if (BWidget.startsNewGroup(id)) {
            $(ul).append("
");
        }

        $(ul).append($(li));
    });

    $(acc).accordion({
        fillSpace: true
    });

    // Must explicitly react to window resize events to be
    // able to grow/shrink if we're in a flex box layout
    $(window).resize( function () { $(acc).accordion("resize"); });
}
<commit_msg>[Palette] Code format and style cleanup<commit_after>/*
 * gui-builder - A simple WYSIWYG HTML5 app creator
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */
"use strict";

/*
 * The palette.json properties are:
 *
 *   id:      String, internal reference this widget set
 *   name:    String, human readable name and/or description
 *   version: String, (XXX: Unused, possible future value?)
 *   widgets: Array of objects, each with the following properties:
 *
 *       name:   String, Human readable widget name (TODO: L10N?)
 *       type:   String, HTMLElement type to use with createElement()
 *       icon:   String, CSS class id for the icon representation
 *       helper: String, HTML to use for creating the drag helper
 *       code:   String, HTML to be created when inserting this widget
 *                       into the DOM
 */

function loadPalette(container) {
    var defaultContainer = '#palette-panel',
        myContainer = container, hdr, acc;

    if (!myContainer) {
        myContainer = $(defaultContainer);
    }

    if (!myContainer || !myContainer.get()) {
        return false;
    }

    console.log("Starting palette load...");
    myContainer.append('
Palette
');
    myContainer.append('

');

    hdr = $('#palette_header');
    acc = $('#palette_accordion');

    // Make use of the flex box model in CSS3 to allow the tabs
    // to grow/shrink with the window/container
    myContainer.addClass('vbox');
    hdr.addClass('flex0');
    acc.addClass('flex1');

    // FIXME: Eventually, all widgets should come from the BWidget
    //        global structure.  For now, we load them as their own
    //        subcategory in the palette
    $(acc).append('
Tizen Framework

');
    $.each(BWidget.getPaletteWidgetTypes(), function(n, id) {
        // Add new
 element to hold this widget
        var ul = $('#Tizen-widgets'),
            li = $('

').appendTo($(ul));
        $(li).button({
            label: BWidget.getDisplayLabel(id),
            icons: {primary: BWidget.getIcon(id)}
        });
        $(li).disableSelection();
        $(li).addClass('nrc-palette-widget');
        $(li).data("code", BWidget.getTemplate(id));
        $(li).data("adm-node", {type: id});

        // FIXME: This should probably be replaced by a more flexible
        //        concept of widget groups.
        if (BWidget.startsNewGroup(id)) {
            $(ul).append("
");
        }

        $(ul).append($(li));
    });

    $(acc).accordion({
        fillSpace: true
    });

    // Must explicitly react to window resize events to be
    // able to grow/shrink if we're in a flex box layout
    $(window).resize( function () { $(acc).accordion("resize"); });
}
<|endoftext|>


<commit_before>
/**
 * Small plugins
 *
 * @since Riiskit 1.0.0
 */

/**
 * Avoid console errors in browsers that lack a console.
 *
 * @since Riiskit 1.0.0
 */

(function() {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

/**
 * Better way to cache jQuery selectors
 *
 * Usage: $.selector_cache('.element');
 *
 * @link https://eamann.com/tech/selector-caching-jquery/#comment-41220
 * @todo https://gist.github.com/jtsternberg/14978579a9edf42ed069
 *
 * @since Riiskit 1.0.0
 */

(function ($) {
	$.selector_cache = function (selector) {
		if ( ! $.selector_cache[selector] ) {
			$.selector_cache[selector] = $(selector);
		}

		return $.selector_cache[selector];
	};
}(jQuery));

/**
 * Makes "skip to content" link work correctly in IE9, Chrome, and Opera
 * for better accessibility.
 *
 * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/
 *
 * @since Riiskit 1.0.0
 */

(function () {
	var ua = navigator.userAgent.toLowerCase();

	if ( ( ua.indexOf( 'webkit' ) > -1 || ua.indexOf( 'opera' ) > -1 || ua.indexOf( 'msie' ) > -1 ) &&
		document.getElementById && window.addEventListener ) {

		window.addEventListener( 'hashchange', function() {
			var element = document.getElementById( location.hash.substring( 1 ) );

			if ( element ) {
				if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.nodeName ) ) {
					element.tabIndex = -1;
				}

				element.focus();
			}
		}, false );
	}
}());
<commit_msg>Minor beautifying.<commit_after>
/**
 * Small helper plugins
 *
 * @since Riiskit 1.0.0
 */

/**
 * Avoid console errors in browsers that lack a console.
 *
 * @since Riiskit 1.0.0
 */

( function(){
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeline', 'timelineEnd', 'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

/**
 * Better way to cache jQuery selectors.
 *
 * Usage: $.selector_cache('.element');
 *
 * @link https://eamann.com/tech/selector-caching-jquery/#comment-41220
 * @todo https://gist.github.com/jtsternberg/14978579a9edf42ed069
 *
 * @since Riiskit 1.0.0
 */

( function ($){
	$.selector_cache = function (selector) {
		if ( ! $.selector_cache[selector] ) {
			$.selector_cache[selector] = $(selector);
		}

		return $.selector_cache[selector];
	};
}(jQuery));

/**
 * Makes "skip to content" link work correctly in IE9, Chrome, and Opera
 * for better accessibility.
 *
 * @link http://www.nczonline.net/blog/2013/01/15/fixing-skip-to-content-links/
 *
 * @since Riiskit 1.0.0
 */

( function (){
	var ua = navigator.userAgent.toLowerCase();

	if ( ( ua.indexOf( 'webkit' ) > -1 || ua.indexOf( 'opera' ) > -1 || ua.indexOf( 'msie' ) > -1 ) &&
		document.getElementById && window.addEventListener ) {

		window.addEventListener( 'hashchange', function() {
			var element = document.getElementById( location.hash.substring( 1 ) );

			if ( element ) {
				if ( ! /^(?:a|select|input|button|textarea)$/i.test( element.nodeName ) ) {
					element.tabIndex = -1;
				}

				element.focus();
			}
		}, false );
	}
}());
<|endoftext|>


<commit_before>'use strict';
/*global App*/

/*
-- App.postman --
Handles the fetching, storing and rendering of
all posts. The REST endpoint is passed as an
argument when it is initialized.
 */
function Postman (endpoint) {
  var url = document.URL + endpoint,
    models;
  function Constructor () { }
  Constructor.prototype.XHR = function (method, data, url, async, cb) {
    var req = new XMLHttpRequest();
    req.open(method, url, async);
    req.responseType = '';
    req.onload = function () {
      if (req.status >= 200 && req.status < 400) {
        if (req.responseText) {
          cb(req.responseText);
        } else {
          cb();
        }
      } else {
        return false;
      }
    };
    if (data) {
      req.send(data);
    } else {
      req.send();
    }
  };

  Constructor.prototype.fetch = function () {
    return this.XHR('GET', null, url, true, function (data) {
      models = JSON.parse(data);
    });
  };

  Constructor.prototype.show = function () {
    return models;
  };

  return new Constructor();
}
App.postman = new Postman('api/v1/posts');

// function microAjax(url, callbackFunction)
// {
//   this.bindFunction = function (caller, object) {
//     return function() {
//       return caller.apply(object, [object]);
//     };
//   };

//   this.stateChange = function (object) {
//     if (this.request.readyState==4)
//       this.callbackFunction(this.request.responseText);
//   };

//   this.getRequest = function() {
//     if (window.ActiveXObject)
//       return new ActiveXObject('Microsoft.XMLHTTP');
//     else if (window.XMLHttpRequest)
//       return new XMLHttpRequest();
//     return false;
//   };

//   this.postBody = (arguments[2] || "");

//   this.callbackFunction=callbackFunction;
//   this.url=url;
//   this.request = this.getRequest();

//   if(this.request) {
//     var req = this.request;
//     req.onreadystatechange = this.bindFunction(this.stateChange, this);

//     if (this.postBody!=="") {
//       req.open("POST", url, true);
//       req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
//       req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//       req.setRequestHeader('Connection', 'close');
//     } else {
//       req.open("GET", url, true);
//     }

//     req.send(this.postBody);
//   }

// request = new XMLHttpRequest();
// request.open('GET', '/my/url', true);

// request.onload = function() {
//   if (request.status >= 200 && request.status < 400){
//     // Success!
//     data = JSON.parse(request.responseText);
//   } else {
//     // We reached our target server, but it returned an error

//   }
// };

// request.onerror = function() {
//   // There was a connection error of some sort
// };

// request.send();
// }

<commit_msg>fixed callback function on postman fetch<commit_after>'use strict';
/*global App*/

/*
-- App.postman --
Handles the fetching, storing and rendering of
all posts. The REST endpoint is passed as an
argument when it is initialized.
 */
function Postman (endpoint) {
  var url = endpoint,
    models;
  function Constructor () { }
  Constructor.prototype.XHR = function (method, data, url, async, cb) {
    var req = new XMLHttpRequest();
    req.open(method, url, async);
    req.responseType = '';
    req.onload = function () {
      if (req.status >= 200 && req.status < 400) {
        models = JSON.parse(req.responseText);
        cb(models);
      } else {
        return false;
      }
    };
    if (data) {
      req.send(data);
    } else {
      req.send();
    }
  };

  Constructor.prototype.fetch = function (cb) {
    return this.XHR('GET', null, url, true, cb);
  };

  Constructor.prototype.show = function () {
    return models;
  };

  return new Constructor();
}
App.postman = new Postman('http://localhost:3000/api/v1/posts');

// function microAjax(url, callbackFunction)
// {
//   this.bindFunction = function (caller, object) {
//     return function() {
//       return caller.apply(object, [object]);
//     };
//   };

//   this.stateChange = function (object) {
//     if (this.request.readyState==4)
//       this.callbackFunction(this.request.responseText);
//   };

//   this.getRequest = function() {
//     if (window.ActiveXObject)
//       return new ActiveXObject('Microsoft.XMLHTTP');
//     else if (window.XMLHttpRequest)
//       return new XMLHttpRequest();
//     return false;
//   };

//   this.postBody = (arguments[2] || "");

//   this.callbackFunction=callbackFunction;
//   this.url=url;
//   this.request = this.getRequest();

//   if(this.request) {
//     var req = this.request;
//     req.onreadystatechange = this.bindFunction(this.stateChange, this);

//     if (this.postBody!=="") {
//       req.open("POST", url, true);
//       req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
//       req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
//       req.setRequestHeader('Connection', 'close');
//     } else {
//       req.open("GET", url, true);
//     }

//     req.send(this.postBody);
//   }

// request = new XMLHttpRequest();
// request.open('GET', '/my/url', true);

// request.onload = function() {
//   if (request.status >= 200 && request.status < 400){
//     // Success!
//     data = JSON.parse(request.responseText);
//   } else {
//     // We reached our target server, but it returned an error

//   }
// };

// request.onerror = function() {
//   // There was a connection error of some sort
// };

// request.send();
// }

<|endoftext|>


<commit_before>
var moment = require('moment');
var Vec2 = require('vec2');
var randgen = require('randgen');

var KILOMETERS_PER_DEGREE = 111;

// single refugee
var Refugee = function(startPoint, endPoint, destinationCountry, speed, endMoment, isAsylumSeeker) {
  this.startPoint = startPoint;
  this.endPoint = endPoint;
  this.destinationCountry = destinationCountry;
  this.speed = speed;
  this.endMoment = endMoment;
  this.isAsylumSeeker = isAsylumSeeker;

  if (window.SMART_SPREAD_ENABLED) {
    this.sideDeviation = randgen.rnorm(0, 1); // mean, std. deviation
    this.maxSideDeviation = 0.3;
  }
  this.arrived = false;

  this.startMoment = this._getStartMoment();
  this.startMomentUnix = this.startMoment.unix();
  this.endMomentUnix = this.endMoment.unix();

  this.onFinished = [];

  this.directionVector = Vec2(
    this.startPoint[0] - this.endPoint[0],
    this.startPoint[1] - this.endPoint[1])
      .normalize();
};

Refugee.prototype.getStartMoment = function() {
  return this.startMoment;
};

Refugee.prototype._getStartMoment = function() {
  var ret = moment(this.endMoment);
  return ret.subtract(this.getTravelTime(), 'hours');
};

Refugee.prototype.setRouteRefugeeCount = function(count) {
  this.maxSideDeviation = Math.min(Math.max(0.3, count / 3000), 1.0);
};

Refugee.prototype.getTravelTime = function(r) {
  return this.getTravelDistance(r) / this.speed;
};

/*
 * Get the distance travelled by the given
 * refugee in kilometers
 */
Refugee.prototype.getTravelDistance = function() {
  var x = this.endPoint[0] - this.startPoint[0];
  var y = this.startPoint[1] - this.endPoint[1];
  return Math.sqrt(x*x + y*y) * KILOMETERS_PER_DEGREE;
};

Refugee.prototype.isPastStartMoment = function(mom) {
  return mom.unix() > this.getStartMoment().unix();
};

Refugee.prototype.update = function(mom) {
  var r = this;

  if (mom.unix() > this.endMomentUnix) {
    r.arrived = true;
    this.location = r.endPoint;
    return;
  }

  var hours = this.getStartMoment().diff(mom) / (1000 * 60 * 60);
  var distance = hours * r.speed;
  var sideMotionVector, portionOfJourney;

  if (window.SMART_SPREAD_ENABLED) {
    sideMotionVector = Vec2(-this.directionVector.y, this.directionVector.x); // perpendicular vector
    portionOfJourney = hours / this.getTravelTime();
  }

  var v = Vec2(r.startPoint);
  v.add(this.directionVector.multiply(distance / KILOMETERS_PER_DEGREE, true));

  if (window.SMART_SPREAD_ENABLED) {
    sideMotionVector.multiply(
      Math.sin(portionOfJourney * Math.PI) * this.sideDeviation * this.maxSideDeviation);
    v.add(sideMotionVector);
  }

  this.location = v.toArray();
};

module.exports = Refugee;
<commit_msg>Simplify smart spread<commit_after>
var moment = require('moment');
var Vec2 = require('vec2');
var randgen = require('randgen');

var KILOMETERS_PER_DEGREE = 111;

// single refugee
var Refugee = function(startPoint, endPoint, destinationCountry, speed, endMoment, isAsylumSeeker) {
  this.startPoint = startPoint;
  this.endPoint = endPoint;
  this.destinationCountry = destinationCountry;
  this.speed = speed;
  this.endMoment = endMoment;
  this.isAsylumSeeker = isAsylumSeeker;

  if (window.SMART_SPREAD_ENABLED) {
    this.sideDeviation = randgen.rnorm(0, 1); // mean, std. deviation
    this.maxSideDeviation = 0.3;
  }
  this.arrived = false;

  this.startMoment = this._getStartMoment();
  this.startMomentUnix = this.startMoment.unix();
  this.endMomentUnix = this.endMoment.unix();

  this.onFinished = [];

  this.directionVector = Vec2(
    this.startPoint[0] - this.endPoint[0],
    this.startPoint[1] - this.endPoint[1])
      .normalize();
};

Refugee.prototype.getStartMoment = function() {
  return this.startMoment;
};

Refugee.prototype._getStartMoment = function() {
  var ret = moment(this.endMoment);
  return ret.subtract(this.getTravelTime(), 'hours');
};

Refugee.prototype.setRouteRefugeeCount = function(count) {
  this.maxSideDeviation = Math.min(Math.max(0.3, count / 3000), 1.0);
};

Refugee.prototype.getTravelTime = function(r) {
  return this.getTravelDistance(r) / this.speed;
};

/*
 * Get the distance travelled by the given
 * refugee in kilometers
 */
Refugee.prototype.getTravelDistance = function() {
  var x = this.endPoint[0] - this.startPoint[0];
  var y = this.startPoint[1] - this.endPoint[1];
  return Math.sqrt(x*x + y*y) * KILOMETERS_PER_DEGREE;
};

Refugee.prototype.isPastStartMoment = function(mom) {
  return mom.unix() > this.getStartMoment().unix();
};

Refugee.prototype.update = function(mom) {
  var r = this;

  if (mom.unix() > this.endMomentUnix) {
    r.arrived = true;
    this.location = r.endPoint;
    return;
  }

  var hours = this.getStartMoment().diff(mom) / (1000 * 60 * 60);
  var distance = hours * r.speed;
  var v = Vec2(r.startPoint);
  v.add(this.directionVector.multiply(distance / KILOMETERS_PER_DEGREE, true));

  if (window.SMART_SPREAD_ENABLED) {
    var sideMotionVector = Vec2(-this.directionVector.y, this.directionVector.x); // perpendicular vector
    var portionOfJourney = hours / this.getTravelTime();
    sideMotionVector.multiply(
      Math.sin(portionOfJourney * Math.PI) * this.sideDeviation * this.maxSideDeviation);
    v.add(sideMotionVector);
  }

  this.location = v.toArray();
};

module.exports = Refugee;
<|endoftext|>