<commit_before>import {Log} from '../infrastructure';
import {Command} from '../command';
import {RowEditor} from './edit.row.editor';

export class EditRowView {
	constructor(model, table, commandManager) {
		this.model = model;
		this.table = table;
		this.editor = RowEditor.empty;

		const shortcut = model.action().shortcut;
		const commands = this.commands;
		this.shortcutOff = shortcut.register(commandManager, commands);

		this.enter = commands.get('enter');
		this.commit = commands.get('commit');
		this.cancel = commands.get('cancel');
		this.reset = commands.get('reset');
	}

	get commands() {
		const model = this.model;
		const commands = {
			enter: new Command({
				shortcut: this.shortcutFactory('enter'),
				canExecute: row => {
					row = row || model.navigation().row;
					return row
						&& model.edit().mode === 'row'
						&& model.edit().state === 'view'
						&& model.edit().enter.canExecute(this.contextFactory(row));
				},
				execute: (row, e) => {
					Log.info('row.edit', 'edit mode');
					if (e) {
						e.stopImmediatePropagation();
					}

					const columns = this.model.data().columns;
					this.editor = new RowEditor(row, columns);
					model.edit({state: 'edit'});
				}
			}),
			commit: new Command({
				shortcut: this.shortcutFactory('commit'),
				// TODO: add validation support
				canExecute: row => {
					row = row || model.navigation().row;
					return row
						&& model.edit().mode === 'row'
						&& model.edit().state === 'edit'
						&& model.edit().commit.canExecute(this.contextFactory(row));
				},
				execute: (cell, e) => {
					Log.info('row.edit', 'commit');
					if (e) {
						e.stopImmediatePropagation();
					}

					this.editor.commit();
					this.editor = RowEditor.empty;
					model.edit({state: 'view'});
				}
			}),
			cancel: new Command({
				shortcut: this.shortcutFactory('cancel'),
				canExecute: row => {
					row = row || model.navigation().row;
					return row
						&& model.edit().mode === 'row'
						&& model.edit().state === 'edit'
						&& model.edit().cancel.canExecute(this.contextFactory(row));
				},
				execute: (row, e) => {
					Log.info('cell.edit', 'cancel');
					if (e) {
						e.stopImmediatePropagation();
					}

					this.editor.reset();
					this.editor = RowEditor.empty;
					model.edit({state: 'view'});
				}
			}),
			reset: new Command({
				canExecute: row => {
					row = row || model.navigation().row;
					return row
						&& model.edit().mode === 'row'
						&& model.edit().state === 'edit'
						&& model.edit().reset.canExecute(this.contextFactory(row));
				},
				execute: (row, e) => {
					Log.info('row.edit', 'reset');
					if (e) {
						e.stopImmediatePropagation();
					}

					if (row && model.edit().reset.execute(this.contextFactory(row)) !== false) {
						this.editor.reset();
						return false;
					}
				}
			})
		};
		return new Map(
			Object.entries(commands)
		);
	}

	contextFactory(row) {
		return {
			row: row,
			unit: 'row'
		};
	}

	shortcutFactory(type) {
		const edit = this.model.edit;
		return () => {
			const shortcuts = edit()[type + 'Shortcuts'];
			return shortcuts['row'] || shortcuts['$default'];
		};
	}

	destroy() {
		this.shortcutOff();
	}
}
<commit_msg>edit row view test<commit_after>import {Log} from '../infrastructure';
import {Command} from '../command';
import {RowEditor} from './edit.row.editor';

export class EditRowView {
	constructor(model, table, commandManager) {
		this.model = model;
		this.table = table;
		this.editor = RowEditor.empty;

		const shortcut = model.action().shortcut;
		const commands = this.commands;
		this.shortcutOff = shortcut.register(commandManager, commands);

		this.enter = commands.get('enter');
		this.commit = commands.get('commit');
		this.cancel = commands.get('cancel');
		this.reset = commands.get('reset');
	}

	get commands() {
		const model = this.model;
		const commands = {
			enter: new Command({
				shortcut: this.shortcutFactory('enter'),
				canExecute: row => {
					row = row || model.navigation().row;
					return row
						&& model.edit().mode === 'row'
						&& model.edit().state === 'view'
						&& model.edit().enter.canExecute(this.contextFactory(row));
				},
				execute: (row, e) => {
					Log.info('row.edit', 'edit mode');
					if (e) {
						e.stopImmediatePropagation();
					}

					const columns = this.model.data().columns;
					this.editor = new RowEditor(row, columns);
					model.edit({state: 'edit'});
				}
			}),
			commit: new Command({
				shortcut: this.shortcutFactory('commit'),
				// TODO: add validation support
				canExecute: row => {
					row = row || model.navigation().row;
					return row
						&& model.edit().mode === 'row'
						&& model.edit().state === 'edit'
						&& model.edit().commit.canExecute(this.contextFactory(row));
				},
				execute: (cell, e) => {
					Log.info('row.edit', 'commit');
					if (e) {
						e.stopImmediatePropagation();
					}

					this.editor.commit();
					this.editor = RowEditor.empty;
					model.edit({state: 'view'});
				}
			}),
			cancel: new Command({
				shortcut: this.shortcutFactory('cancel'),
				canExecute: row => {
					row = row || model.navigation().row;
					return row
						&& model.edit().mode === 'row'
						&& model.edit().state === 'edit'
						&& model.edit().cancel.canExecute(this.contextFactory(row));
				},
				execute: (row, e) => {
					Log.info('cell.edit', 'cancel');
					if (e) {
						e.stopImmediatePropagation();
					}

					this.editor.reset();
					this.editor = RowEditor.empty;
					model.edit({state: 'view'});
				}
			}),
			reset: new Command({
				canExecute: row => {
					row = row || model.navigation().row;
					return row
						&& model.edit().mode === 'row'
						&& model.edit().state === 'edit'
						&& model.edit().reset.canExecute(this.contextFactory(row));
				},
				execute: (row, e) => {
					Log.info('row.edit', 'reset');
					if (e) {
						e.stopImmediatePropagation();
					}

					if (row && model.edit().reset.execute(this.contextFactory(row)) !== false) {
						this.editor.reset();
						return false;
					}
				}
			})
		};
		return new Map(
			Object.entries(commands)
		);
	}

	contextFactory(row) {
		return {
			row: row,
			current: this.editor.current,
			unit: 'row'
		};
	}

	shortcutFactory(type) {
		const edit = this.model.edit;
		return () => {
			const shortcuts = edit()[type + 'Shortcuts'];
			return shortcuts['row'] || shortcuts['$default'];
		};
	}

	destroy() {
		this.shortcutOff();
	}
}
<|endoftext|>


<commit_before>import {
  initVueI18n,
  isI18nStr
} from '@dcloudio/uni-i18n'
import {
  isStr
} from 'uni-shared'

import {
  DC_LOCALE
} from '../constants'

import en from './en.json'
import es from './es.json'
import fr from './fr.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'

const messages = {
  en,
  es,
  fr,
  'zh-Hans': zhHans,
  'zh-Hant': zhHant
}

let locale

if (__PLATFORM__ === 'h5') {
  locale = (window.localStorage && localStorage[DC_LOCALE]) || __uniConfig.locale || navigator.language
} else if (__PLATFORM__ === 'app-plus') {
  if (typeof weex === 'object') {
    locale = weex.requireModule('plus').getLanguage()
  } else {
    locale = ''
  }
} else {
  locale = __GLOBAL__.getSystemInfoSync().language
}

export const i18n = initVueI18n(
  locale,
  __PLATFORM__ === 'app-plus' || __PLATFORM__ === 'h5' ? messages : {}
)
export const t = i18n.t
export const i18nMixin = (i18n.mixin = {
  beforeCreate () {
    const unwatch = i18n.i18n.watchLocale(() => {
      this.$forceUpdate()
    })
    this.$once('hook:beforeDestroy', function () {
      unwatch()
    })
  },
  methods: {
    $$t (key, values) {
      return t(key, values)
    }
  }
})
export const setLocale = i18n.setLocale
export const getLocale = i18n.getLocale

export function initAppLocale (Vue, appVm, locale) {
  const state = Vue.observable({
    locale: locale || i18n.getLocale()
  })
  const localeWatchers = []
  appVm.$watchLocale = fn => {
    localeWatchers.push(fn)
  }
  Object.defineProperty(appVm, '$locale', {
    get () {
      return state.locale
    },
    set (v) {
      state.locale = v
      localeWatchers.forEach(watch => watch(v))
    }
  })
}

export const I18N_JSON_DELIMITERS = ['%', '%']

function getLocaleMessage () {
  const locale = uni.getLocale()
  const locales = __uniConfig.locales
  return (
    locales[locale] || locales[__uniConfig.fallbackLocale] || locales.en || {}
  )
}

export function formatI18n (message) {
  if (isI18nStr(message, I18N_JSON_DELIMITERS)) {
    return i18n.f(message, getLocaleMessage(), I18N_JSON_DELIMITERS)
  }
  return message
}

function resolveJsonObj (jsonObj, names) {
  if (names.length === 1) {
    if (jsonObj) {
      const value = jsonObj[names[0]]
      if (isStr(value) && isI18nStr(value, I18N_JSON_DELIMITERS)) {
        return jsonObj
      }
    }
    return
  }
  const name = names.shift()
  return resolveJsonObj(jsonObj && jsonObj[name], names)
}

export function defineI18nProperties (obj, names) {
  return names.map(name => defineI18nProperty(obj, name))
}

export function defineI18nProperty (obj, names) {
  const jsonObj = resolveJsonObj(obj, names)
  if (!jsonObj) {
    return false
  }
  const prop = names[names.length - 1]
  let value = jsonObj[prop]
  Object.defineProperty(jsonObj, prop, {
    get () {
      return formatI18n(value)
    },
    set (v) {
      value = v
    }
  })
  return true
}

function isEnableLocale () {
  return __uniConfig.locales && !!Object.keys(__uniConfig.locales).length
}

export function initNavigationBarI18n (navigationBar) {
  if (isEnableLocale()) {
    return defineI18nProperties(navigationBar, [
      ['titleText'],
      ['searchInput', 'placeholder']
    ])
  }
}

export function initPullToRefreshI18n (pullToRefresh) {
  if (isEnableLocale()) {
    const CAPTION = 'caption'
    return defineI18nProperties(pullToRefresh, [
      ['contentdown', CAPTION],
      ['contentover', CAPTION],
      ['contentrefresh', CAPTION]
    ])
  }
}

export function initTabBarI18n (tabBar) {
  if (isEnableLocale()) {
    tabBar.list.forEach(item => {
      defineI18nProperty(item, ['text'])
    })
  }
  return tabBar
}

export function initI18n () {
  const localeKeys = Object.keys(__uniConfig.locales || {})
  if (localeKeys.length) {
    localeKeys.forEach((locale) =>
      i18n.add(locale, __uniConfig.locales[locale])
    )
  }
}
<commit_msg>fix: H5 i18n 没有配置tabbar报错的问题<commit_after>import {
  initVueI18n,
  isI18nStr
} from '@dcloudio/uni-i18n'
import {
  isStr
} from 'uni-shared'

import {
  DC_LOCALE
} from '../constants'

import en from './en.json'
import es from './es.json'
import fr from './fr.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'

const messages = {
  en,
  es,
  fr,
  'zh-Hans': zhHans,
  'zh-Hant': zhHant
}

let locale

if (__PLATFORM__ === 'h5') {
  locale = (window.localStorage && localStorage[DC_LOCALE]) || __uniConfig.locale || navigator.language
} else if (__PLATFORM__ === 'app-plus') {
  if (typeof weex === 'object') {
    locale = weex.requireModule('plus').getLanguage()
  } else {
    locale = ''
  }
} else {
  locale = __GLOBAL__.getSystemInfoSync().language
}

export const i18n = initVueI18n(
  locale,
  __PLATFORM__ === 'app-plus' || __PLATFORM__ === 'h5' ? messages : {}
)
export const t = i18n.t
export const i18nMixin = (i18n.mixin = {
  beforeCreate () {
    const unwatch = i18n.i18n.watchLocale(() => {
      this.$forceUpdate()
    })
    this.$once('hook:beforeDestroy', function () {
      unwatch()
    })
  },
  methods: {
    $$t (key, values) {
      return t(key, values)
    }
  }
})
export const setLocale = i18n.setLocale
export const getLocale = i18n.getLocale

export function initAppLocale (Vue, appVm, locale) {
  const state = Vue.observable({
    locale: locale || i18n.getLocale()
  })
  const localeWatchers = []
  appVm.$watchLocale = fn => {
    localeWatchers.push(fn)
  }
  Object.defineProperty(appVm, '$locale', {
    get () {
      return state.locale
    },
    set (v) {
      state.locale = v
      localeWatchers.forEach(watch => watch(v))
    }
  })
}

export const I18N_JSON_DELIMITERS = ['%', '%']

function getLocaleMessage () {
  const locale = uni.getLocale()
  const locales = __uniConfig.locales
  return (
    locales[locale] || locales[__uniConfig.fallbackLocale] || locales.en || {}
  )
}

export function formatI18n (message) {
  if (isI18nStr(message, I18N_JSON_DELIMITERS)) {
    return i18n.f(message, getLocaleMessage(), I18N_JSON_DELIMITERS)
  }
  return message
}

function resolveJsonObj (jsonObj, names) {
  if (names.length === 1) {
    if (jsonObj) {
      const value = jsonObj[names[0]]
      if (isStr(value) && isI18nStr(value, I18N_JSON_DELIMITERS)) {
        return jsonObj
      }
    }
    return
  }
  const name = names.shift()
  return resolveJsonObj(jsonObj && jsonObj[name], names)
}

export function defineI18nProperties (obj, names) {
  return names.map(name => defineI18nProperty(obj, name))
}

export function defineI18nProperty (obj, names) {
  const jsonObj = resolveJsonObj(obj, names)
  if (!jsonObj) {
    return false
  }
  const prop = names[names.length - 1]
  let value = jsonObj[prop]
  Object.defineProperty(jsonObj, prop, {
    get () {
      return formatI18n(value)
    },
    set (v) {
      value = v
    }
  })
  return true
}

function isEnableLocale () {
  return __uniConfig.locales && !!Object.keys(__uniConfig.locales).length
}

export function initNavigationBarI18n (navigationBar) {
  if (isEnableLocale()) {
    return defineI18nProperties(navigationBar, [
      ['titleText'],
      ['searchInput', 'placeholder']
    ])
  }
}

export function initPullToRefreshI18n (pullToRefresh) {
  if (isEnableLocale()) {
    const CAPTION = 'caption'
    return defineI18nProperties(pullToRefresh, [
      ['contentdown', CAPTION],
      ['contentover', CAPTION],
      ['contentrefresh', CAPTION]
    ])
  }
}

export function initTabBarI18n (tabBar) {
  if (isEnableLocale() && tabBar.list) {
    tabBar.list.forEach(item => {
      defineI18nProperty(item, ['text'])
    })
  }
  return tabBar
}

export function initI18n () {
  const localeKeys = Object.keys(__uniConfig.locales || {})
  if (localeKeys.length) {
    localeKeys.forEach((locale) =>
      i18n.add(locale, __uniConfig.locales[locale])
    )
  }
}
<|endoftext|>


<commit_before>/**
 * NetBIOS operations.
 *
 * @author n1474335 [n1474335@gmail.com]
 * @copyright Crown Copyright 2017
 * @license Apache-2.0
 *
 * @namespace
 */
const NetBIOS = {

    /**
     * @constant
     * @default
     */
    OFFSET: 65,

    /**
     * Encode NetBIOS Name operation.
     *
     * @param {byteArray} input
     * @param {Object[]} args
     * @returns {byteArray}
     */
    runEncodeName: function(input, args) {
        let output = [],
            offset = args[0];

        if (input.length <= 16) {
            let len = input.length;
            input.length = 16;
            input.fill(32, len, 16);
            for (let i = 0; i < input.length; i++) {
                output.push((input[i] >> 4) + offset);
                output.push((input[i] & 0xf) + offset);
            }
        }

        return output;
    },

    /**
     * Decode NetBIOS Name operation.
     *
     * @param {byteArray} input
     * @param {Object[]} args
     * @returns {byteArray}
     */
    runDecodeName: function(input, args) {
        let output = [],
            offset = args[0];

        if (input.length <= 32 && (input.length % 2) === 0) {
            for (let i = 0; i < input.length; i += 2) {
                output.push((((input[i] & 0xff) - offset) << 4) |
                            (((input[i + 1] & 0xff) - offset) & 0xf));
            }
            output = output.filter(x => x !== 32);
        }

        return output;
    },

};

export default NetBIOS;
<commit_msg>Fixed NetBIOS space removal<commit_after>/**
 * NetBIOS operations.
 *
 * @author n1474335 [n1474335@gmail.com]
 * @copyright Crown Copyright 2017
 * @license Apache-2.0
 *
 * @namespace
 */
const NetBIOS = {

    /**
     * @constant
     * @default
     */
    OFFSET: 65,

    /**
     * Encode NetBIOS Name operation.
     *
     * @param {byteArray} input
     * @param {Object[]} args
     * @returns {byteArray}
     */
    runEncodeName: function(input, args) {
        let output = [],
            offset = args[0];

        if (input.length <= 16) {
            let len = input.length;
            input.length = 16;
            input.fill(32, len, 16);
            for (let i = 0; i < input.length; i++) {
                output.push((input[i] >> 4) + offset);
                output.push((input[i] & 0xf) + offset);
            }
        }

        return output;
    },

    /**
     * Decode NetBIOS Name operation.
     *
     * @param {byteArray} input
     * @param {Object[]} args
     * @returns {byteArray}
     */
    runDecodeName: function(input, args) {
        let output = [],
            offset = args[0];

        if (input.length <= 32 && (input.length % 2) === 0) {
            for (let i = 0; i < input.length; i += 2) {
                output.push((((input[i] & 0xff) - offset) << 4) |
                            (((input[i + 1] & 0xff) - offset) & 0xf));
            }
            for (let i = output.length - 1; i > 0; i--) {
                if (output[i] === 32) output.splice(i, i);
                else break;
            }
        }

        return output;
    },

};

export default NetBIOS;
<|endoftext|>


<commit_before>var Hive = require('./index.js');
var util = require('util');
var ClimateControl = require('./climateControl');
var HotWaterControl = require('./hotwaterControl');
var Temperature = require('./temperature');
var hive = new Hive("adrian@lambeth.org", "h1v3user");

function HeatingEventHandler(controller) {
    if (controller != undefined)
    {
        var Modes = controller.Mode;

        controller.on('update', function(data){
            console.log(data);
        });

        controller.on('accepted', function(){
            controller.GetState();
        });

        controller.on('error', function(response){
            console.log(response);
        });

        controller.on('complete', function(response){
            console.log(response);
        });
    }
}

function HotWaterEventHandler(controller) {
    if (controller != undefined)
    {
        var Modes = controller.Mode;

        controller.on('update', function(data){
             console.log(data);
        });

        controller.on('accepted', function(){
            controller.GetState();
        });

        controller.on('error', function(response){
            console.log(response);
        });

        controller.on('complete', function(response){
            console.log(response);
        });
    }
}

function TemperatureEventHandler(controller) {

    if (controller != undefined)
    {
        controller.on('update', function(data){
            console.log(data);
        });

        controller.on('accepted', function(){
            controller.GetState();
        });

        controller.on('error', function(response){
            console.log(response);
        });

        controller.on('complete', function(response){
            console.log(response);
        });
    }

}

hive.on('login', function(context){
    console.log(context);
    var water = new HotWaterControl(context);
    var climate = new ClimateControl(context);
    var temp = new Temperature(context);

    HotWaterEventHandler(water);
    HeatingEventHandler(climate);
    TemperatureEventHandler(temp);

    //temp.GetState(temp.Period.Day);

    //climate.GetSchedule();
    water.GetState();

    setTimeout(function() {
        hive.Logout();
    }, 3000);
});

hive.on('logout', function(){
   console.log('closed');
});

hive.on('not_authorised', function(response){
    console.log(response.error.reason);
});

hive.on('locked', function(response){
    console.log('Your account is locked. You have had 5 successive login failures.');
});

hive.Login();<commit_msg>removed hivehome.js<commit_after><|endoftext|>


<commit_before>/*
 * PLATINO APPLICATIONWINDOW.JS
 */

var platino = require('co.lanica.platino');

function ApplicationWindow() {

   	var closing = false;											// a flag that ensures closing event is executed only once (Android)

	/*
	 * CREATE WINDOW INSTANCE
	 */

    var win = Ti.UI.createWindow({
        backgroundColor:'black',
        orientationModes: [Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT,/*Ti.UI.PORTRAIT, Ti.UI.UPSIDE_PORTRAIT*/],
		fullscreen:true,
		navBarHidden : true,
		keepScreenOn:true
    });

    win.addEventListener('android:back', androidBackButtonPressed);	// Show exit dialog when Android back button is pressed
    win.addEventListener('close', closeWindow);						// Listener when ApplicationWindow is closed

    /*
     * CREATE GAME INSTANCE
     * Only one GameView instance is allowed in your app. This is required for every Platino app. All Scene instances are added to the GameView to be displayed.
     */

    var game = platino.createGameView({
    	fps:60,	/*Set 30fps for Iphone4, iPad1 and old android devices*/// Game frame rate
		debug:false,													// Enable debug logs
		enableOnDrawFrameEvent: true,									// Disable / enable 'enterframe' event
		enableOnLoadSpriteEvent:false,									// Enable/Disable onloadsprite event
		enableOnLoadTextureEvent:false,									// Enable/Disable onloadtexture event
		textureFilter : platino.OPENGL_LINEAR, 			 				// update game view texture settings for smooth rendering
		TARGET_SCREEN : {width:2048, height:1536}, 						// set screen size for the game (in this case, iPad resolution)
		touchScaleX:1,													// TouchScaleX. Property to detect touches correctly on different resolutions (updateScreenSize)
		touchScaleY:1,													// TouchScaleY. Property to detect touches correctly on different resolutions (updateScreenSize)
		usePerspective:true,											// Sets/gets viewpoint type of the GameView (perspective or orthogonal).
		timerType: platino.ENGINE_TIMER_NSTIMER,						// iOS-only. Gets/sets timer type for drawing
		setupSpriteSize : function(sprite) {							// Adjust the size of sprite for different resolutions
			var width = sprite.width / game.screenScale;
			var height = sprite.height / game.screenScale;
			sprite.width = (width < 1) ? 1 : width;
			sprite.height = (height < 1) ? 1 : height;
		}

    });

    // game.color(1, 1, 1);											// set initial background color to white

    game.addEventListener('onload', onGameActivated);

    // game.addEventListener('onsurfacechanged',onSurfaceChanged);
    // game.addEventListener('onfps', showFPS);

	/*
	 * FUNCTIONS
	 */

	 function updateScreenSize() {

	 	// Your game screen size is set here if you did not specifiy game width and height using screen property.
        // Note: game.size.width and height may be changed due to the parent layout so check them here.

       var screenScale = game.size.height / game.TARGET_SCREEN.height;

       Ti.API.info("view size: " + game.size.width + "x" + game.size.height);
       Ti.API.info("game screen size: " + game.screen.width + "x" + game.screen.height);

       game.screen = {width:game.size.width / screenScale, height:game.size.height / screenScale};

    	if(Ti.Platform.osname==='android'){

    		 game.touchScaleX = game.screen.width  / Titanium.Platform.displayCaps.platformWidth;
        	 game.touchScaleY = game.screen.height / Titanium.Platform.displayCaps.platformHeight;

    	}else{

    		 game.touchScaleX = game.screen.width  / game.size.width;
        	 game.touchScaleY = game.screen.height / game.size.height;

    	};

        game.screenScale = game.screen.height / game.TARGET_SCREEN.height;

        game.STAGE_START = { x:0, y:0 };
        game.STAGE_END   = { x:game.TARGET_SCREEN.width, y:game.screen.height };

    };

    /*
     * LISTENERS
     */

    function onGameActivated(e){

    	updateScreenSize();												// Set game screen size

		var MainScene  = require("MainScene");							// Import the MainScene module into the current scope
        game.currentScene = new MainScene(win, game);					// Set MainScene as the current scene

        game.pushScene(game.currentScene);								// Pushes the specified Scene instance into the scene stack (places it at the very top). The scene (now at the top) will then become the currently shown (active) scene.
        game.start();													// Starts the game

    };

    function onSurfaceChanged(e){

    	game.orientation = e.orientation;
        updateScreenSize();

    };

    function showFPS(e){
    	Ti.API.info(e.fps.toFixed(2) + " fps");
    };

    function androidBackButtonPressed(e){

    	if (closing) return;

        closing = true;

        var dlg = Ti.UI.createAlertDialog({ message : 'Exit?', buttonNames : ['OK','Cancel']});
            dlg.addEventListener("click", function(e) {
            if (e.index === 0) {

				game.currentScene = null;
        		game.cleanupGarbage();

				win.remove(game);

        		dlg.hide();
        		win.close();

            } else {
                closing = false;
            }
        });

        dlg.show();

    };

    function closeWindow(){

    	Ti.API.info("ApplicationWindow is closed");

        game= null;
        win = null;

    };

    platino.addEventListener('onlowmemory', function(e) {
        Ti.API.warn("Low Memory");
    });

    win.add(game);

    return win;
};

//make constructor function the public component interface
module.exports = ApplicationWindow;
<commit_msg>Update comments<commit_after>/*
 * PLATINO APPLICATIONWINDOW.JS
 */

var platino = require('co.lanica.platino');

function ApplicationWindow() {

   	var closing = false;											// closing is a flag that ensures closing event is executed only once (Android)

	/*
	 * CREATE WINDOW INSTANCE
	 */

    var win = Ti.UI.createWindow({
        backgroundColor:'black',
        orientationModes: [Ti.UI.LANDSCAPE_LEFT, Ti.UI.LANDSCAPE_RIGHT,/*Ti.UI.PORTRAIT, Ti.UI.UPSIDE_PORTRAIT*/],
		fullscreen:true,
		navBarHidden : true,
		keepScreenOn:true
    });

    win.addEventListener('android:back', androidBackButtonPressed);	// Show exit dialog when Android back button is pressed
    win.addEventListener('close', closeWindow);						// Listener when ApplicationWindow is closed

    /*
     * CREATE GAME INSTANCE
     * Only one GameView instance is allowed in your app. This is required for every Platino app. All Scene instances are added to the GameView to be displayed.
     */

    var game = platino.createGameView({
    	fps:60,	/*Set 30fps for Iphone4, iPad1 and old android devices*/// Game frame rate
		debug:false,													// Enable debug logs
		enableOnDrawFrameEvent: true,									// Disable / enable 'enterframe' event
		enableOnLoadSpriteEvent:false,									// Enable/Disable onloadsprite event
		enableOnLoadTextureEvent:false,									// Enable/Disable onloadtexture event
		textureFilter : platino.OPENGL_LINEAR, 			 				// update game view texture settings for smooth rendering
		TARGET_SCREEN : {width:2048, height:1536}, 						// set screen size for the game (in this case, iPad resolution)
		touchScaleX:1,													// TouchScaleX. Property to detect touches correctly on different resolutions (updateScreenSize)
		touchScaleY:1,													// TouchScaleY. Property to detect touches correctly on different resolutions (updateScreenSize)
		usePerspective:true,											// Sets/gets viewpoint type of the GameView (perspective or orthogonal).
		timerType: platino.ENGINE_TIMER_NSTIMER,						// iOS-only. Gets/sets timer type for drawing
		setupSpriteSize : function(sprite) {							// Adjust the size of sprite for different resolutions
			var width = sprite.width / game.screenScale;
			var height = sprite.height / game.screenScale;
			sprite.width = (width < 1) ? 1 : width;
			sprite.height = (height < 1) ? 1 : height;
		}

    });

    // game.color(1, 1, 1);											// set initial background color to white

    game.addEventListener('onload', onGameActivated);

    // game.addEventListener('onsurfacechanged',onSurfaceChanged);
    // game.addEventListener('onfps', showFPS);

	/*
	 * FUNCTIONS
	 */

	 function updateScreenSize() {

	 	// Your game screen size is set here if you did not specifiy game width and height using screen property.
        // Note: game.size.width and height may be changed due to the parent layout so check them here.

       var screenScale = game.size.height / game.TARGET_SCREEN.height;

       Ti.API.info("view size: " + game.size.width + "x" + game.size.height);
       Ti.API.info("game screen size: " + game.screen.width + "x" + game.screen.height);

       game.screen = {width:game.size.width / screenScale, height:game.size.height / screenScale};

    	if(Ti.Platform.osname==='android'){

    		 game.touchScaleX = game.screen.width  / Titanium.Platform.displayCaps.platformWidth;
        	 game.touchScaleY = game.screen.height / Titanium.Platform.displayCaps.platformHeight;

    	}else{

    		 game.touchScaleX = game.screen.width  / game.size.width;
        	 game.touchScaleY = game.screen.height / game.size.height;

    	};

        game.screenScale = game.screen.height / game.TARGET_SCREEN.height;

        game.STAGE_START = { x:0, y:0 };
        game.STAGE_END   = { x:game.TARGET_SCREEN.width, y:game.screen.height };

    };

    /*
     * LISTENERS
     */

    function onGameActivated(e){

    	updateScreenSize();												// Set game screen size

		var MainScene  = require("MainScene");							// Import the MainScene module into the current scope
        game.currentScene = new MainScene(win, game);					// Set MainScene as the current scene

        game.pushScene(game.currentScene);								// Pushes the specified Scene instance into the scene stack (places it at the very top). The scene (now at the top) will then become the currently shown (active) scene.
        game.start();													// Starts the game

    };

    function onSurfaceChanged(e){

    	game.orientation = e.orientation;
        updateScreenSize();

    };

    function showFPS(e){
    	Ti.API.info(e.fps.toFixed(2) + " fps");
    };

    function androidBackButtonPressed(e){

    	if (closing) return;

        closing = true;

        var dlg = Ti.UI.createAlertDialog({ message : 'Exit?', buttonNames : ['OK','Cancel']});
            dlg.addEventListener("click", function(e) {
            if (e.index === 0) {

				game.currentScene = null;
        		game.cleanupGarbage();

				win.remove(game);

        		dlg.hide();
        		win.close();

            } else {
                closing = false;
            }
        });

        dlg.show();

    };

    function closeWindow(){

    	Ti.API.info("ApplicationWindow is closed");

        game= null;
        win = null;

    };

    platino.addEventListener('onlowmemory', function(e) {
        Ti.API.warn("Low Memory");
    });

    win.add(game);

    return win;
};

//make constructor function the public component interface
module.exports = ApplicationWindow;
<|endoftext|>


<commit_before>// Custom charge form
const customForm = getElementByClass('reg-form', 0),
customCode = getElementById('custom-code'),
customFirstName = getElementById('custom-firstname'),
customLastName = getElementById('custom-lastname'),
customEmail = getElementById('custom-email'),
customMobile = getElementById('custom-mobile'),
customSelect = getElementById('custom-select'),
customTerms = getElementById('custom-terms'),
customTermsValidation = getElementById('custom-terms-validation'),
customOptions = getText(getElementById('custom-options')).split(' | '),
customPrices = getText(getElementById('custom-prices')).split(' | ')

const formValidation = () => {
	if (!isBlank(customFirstName) && !isBlank(customLastName) && !isBlank(customEmail) && !isBlank(customMobile) && getValue(customSelect) && isChecked(customTerms) && billingValidation()) {
		emptyText(getElementById('billing-card-error'))
		setCss(paymentButton, { 'background-color': '#800000' })
		setCss(paymentButton, { 'color': '#ffffff' })
		return true
	}
	setCss(paymentButton, { 'background-color': '#f5f5f5' })
	setCss(paymentButton, { 'color': '#333333' })
	return false
}

const showErrorsInForm = () => {
	if (!isChecked(customTerms)) {
    setCss(customTermsValidation, { 'background-color': '#fdd' })
  }
  else {
    setCss(customTermsValidation, { 'background-color': 'transparent' })
  }
	formErrorValidation(customForm)
}

const setCustomChargeSelect = () => {
	//	Adds options & prices based on CMS input
	emptySelect(customSelect)
	let option = document.createElement('option')
	if (customOptions.length > 0) {
		option.text = 'Custom charge option...'
		option.value = ''
		appendSelect(eventStatus, option)
	}
	for (let i = 0; i < customOptions.length; i++) {
		option.text = customOptions[i] + ' - $' + customPrices[i]
		option.value = customPrices[i]
		appendSelect(eventStatus, option)
	}
}

const resetForm = () => {
	clearForm(page())
	repopulateForm(page())
	setCustomChargeSelect()
	formErrorInit(customForm)
	showElement(customForm)
	unCheckElement(customTerms)
	formValidation()
	setCss(paymentButton, { 'background-color': '#f5f5f5' })
	setCss(paymentButton, { 'color': '#333333' })
}

// CUSTOM CHARGE ONCHANGE EVENTS
onChange(customFirstName, () => setValue(billingFirstName, getValue(eventFirstName)))
onChange(customLastName, () => setValue(billingLastName, getValue(eventLastName)))

// If any fields have changed...
for (elem of [customFirstName, customLastName, customEmail, customMobile, customSelect, customTerms, billingFirstName, billingLastName, billingStreet, billingCity, billingState, billingPostal, billingCountry]) {
	// ...validate form to either activate or deactivate Pay Now button.
	onChange(elem, () => formValidation())
}

// RESET CUSTOM CHARGE
resetForm()

onClick(paymentButton, e => {

	if (!formValidation()) {
		showErrorsInForm()
		// If there’s no Stripe error message
		if (isBlank(getElementById('billing-card-error'))) {
			setText(getElementById('billing-card-error'), 'Oops! There’s some missing information.')
		}
		return false
	}

	// Stripe variables
	chargeAmount = getValue(customSelect) * 100
	customerDescription = getValue(customFirstName) + ' ' + getValue(customLastName) + ' <' + getValue(customEmail) + '>'
	customerEmail = getValue(customEmail)
	chargeDescription = 'Custom Charge: ' + getText(customSelect).substring(0, getText(customSelect).length - 16)

})<commit_msg>Removed parsley()<commit_after>// Custom charge form
const customForm = getElementByClass('reg-form', 0),
customCode = getElementById('custom-code'),
customFirstName = getElementById('custom-firstname'),
customLastName = getElementById('custom-lastname'),
customEmail = getElementById('custom-email'),
customMobile = getElementById('custom-mobile'),
customSelect = getElementById('custom-select'),
customTerms = getElementById('custom-terms'),
customTermsValidation = getElementById('custom-terms-validation'),
customOptions = getText(getElementById('custom-options')).split(' | '),
customPrices = getText(getElementById('custom-prices')).split(' | ')

const formValidation = () => {
	if (!isBlank(customFirstName) && !isBlank(customLastName) && !isBlank(customEmail) && !isBlank(customMobile) && getValue(customSelect) && isChecked(customTerms) && billingValidation()) {
		emptyText(getElementById('billing-card-error'))
		setCss(paymentButton, { 'background-color': '#800000' })
		setCss(paymentButton, { 'color': '#ffffff' })
		return true
	}
	setCss(paymentButton, { 'background-color': '#f5f5f5' })
	setCss(paymentButton, { 'color': '#333333' })
	return false
}

const showErrorsInForm = () => {
	if (!isChecked(customTerms)) {
    setCss(customTermsValidation, { 'background-color': '#fdd' })
  }
  else {
    setCss(customTermsValidation, { 'background-color': 'transparent' })
  }
	formErrorValidation(customForm)
}

const setCustomChargeSelect = () => {
	//	Adds options & prices based on CMS input
	emptySelect(customSelect)
	let option = document.createElement('option')
	if (customOptions.length > 0) {
		option.text = 'Custom charge option...'
		option.value = ''
		appendSelect(eventStatus, option)
	}
	for (let i = 0; i < customOptions.length; i++) {
		option.text = customOptions[i] + ' - $' + customPrices[i]
		option.value = customPrices[i]
		appendSelect(eventStatus, option)
	}
}

const resetForm = () => {
	clearForm(page())
	repopulateForm(page())
	setCustomChargeSelect()
	// formErrorInit(customForm)
	showElement(customForm)
	unCheckElement(customTerms)
	formValidation()
	setCss(paymentButton, { 'background-color': '#f5f5f5' })
	setCss(paymentButton, { 'color': '#333333' })
}

// CUSTOM CHARGE ONCHANGE EVENTS
onChange(customFirstName, () => setValue(billingFirstName, getValue(eventFirstName)))
onChange(customLastName, () => setValue(billingLastName, getValue(eventLastName)))

// If any fields have changed...
for (elem of [customFirstName, customLastName, customEmail, customMobile, customSelect, customTerms, billingFirstName, billingLastName, billingStreet, billingCity, billingState, billingPostal, billingCountry]) {
	// ...validate form to either activate or deactivate Pay Now button.
	onChange(elem, () => formValidation())
}

// RESET CUSTOM CHARGE
resetForm()

onClick(paymentButton, e => {

	if (!formValidation()) {
		showErrorsInForm()
		// If there’s no Stripe error message
		if (isBlank(getElementById('billing-card-error'))) {
			setText(getElementById('billing-card-error'), 'Oops! There’s some missing information.')
		}
		return false
	}

	// Stripe variables
	chargeAmount = getValue(customSelect) * 100
	customerDescription = getValue(customFirstName) + ' ' + getValue(customLastName) + ' <' + getValue(customEmail) + '>'
	customerEmail = getValue(customEmail)
	chargeDescription = 'Custom Charge: ' + getText(customSelect).substring(0, getText(customSelect).length - 16)

})<|endoftext|>


<commit_before>/**
 * bootbox.js [v4.x/master branch]
 *
 * http://bootboxjs.com/license.txt
 */
// @see https://github.com/makeusabrew/bootbox/issues/71
window.bootbox = window.bootbox || (function(document, $, undefined) {
  "use strict";

  // the base DOM structure needed to create a modal
  var template = [
    '
',
      '
',
        '
',
          '
',
            '<button type="button" class="close">×</button>',
            '

',
          '
',
          '
',
          '
',
          '
',
            '<button type="button" class="btn">A Button</button>',
          '
',
        '
',
      '
',
    '
'
  ].join("\n");

  // cache a reference to the jQueryfied body element
  var appendTo = $("body");

  // our public object; augmented after our private API
  var exports = {};

  function processCallback(e, elem, callback) {
    // by default we assume a callback will get rid of the dialog,
    // although they are given the opportunity to override this
    var preserveDialog = false;

    // so, if the callback can be invoked and it *explicitly returns false*
    // then we'll set a flag to keep the dialog active...
    if ($.isFunction(callback)) {
      preserveDialog = (callback(e) === false);
    }

    // ... otherwise we'll bin it
    if (!preserveDialog) {
      elem.modal("hide");
    }
  }

  function sanitize(options) {
    if (!options.message) {
      throw new Error("Please specify a message");
    }

    if (!options.buttons) {
      options.buttons = [];
    }

    if (!options.title) {
      // @FIXME gah; we need to pad the header a bit...
      options.title = " ";
    }

    if (options.show === undefined) {
      // auto show dialogs by default
      options.show = true;
    }

    var i = options.buttons.length;

    while (i--) {
      var button = options.buttons[i];

      if (!button.label) {
        throw new Error("Button at index " + i + " requires a label");
      }
    }

    return options;
  }

  /**
   * @private
   */
  function dialog(options) {
    options = sanitize(options);

    var elem = $(template);

    // buttons
    var buttons = options.buttons;
    var i = buttons.length;
    var button;
    var buttonStr = "";
    var callbacks = {};

    while (i--) {
      button = buttons[i];

      buttonStr = '<button data-bb-handler="' + i + '" type="button" class="btn ' + button.className + '">' + button.label + '</button>' + buttonStr;
      callbacks[i] = button.callback;
    }

    elem.find(".modal-body").html(options.message);
    elem.find(".modal-footer").html(buttonStr);

    // bootstrap event listeners

    elem.on("keyup.dismiss.bs.modal", function(e) {
      // @TODO make conditional
      if (e.which === 27) {
        elem.trigger("escape.close.bb");
      }
    });

    elem.on("hidden.bs.modal", function(e) {
      if (e.target === this) {
        elem.remove();
      }
    });

    elem.on("click", ".modal-footer button", function(e) {
      e.preventDefault();

      var callbackIndex = $(this).data("bb-handler");
      var callback = callbacks[callbackIndex];

      processCallback(e, elem, callback);

    });

    // bootbox event listeners
    elem.on("escape.close.bb", function(e) {
      processCallback(e, elem, options.onEscape);
    });

    appendTo.append(elem);

    elem.modal({
      backdrop: "static", // @TODO config
      keyboard: false,
      show: false
    });

    if (options.show) {
      elem.modal("show");
    }

    return elem;

  }

  // @NOTE all high level methods will now only
  // accept 1 or 2 args
  // if args.length === 2 then assume str, callback
  // if args.length === 1 then inspect for str Vs object
  exports.alert = function() {
    var options;
    var argv = arguments, argn = argv.length;

    if (argn < 1 || argn > 2) {
      throw new Error("Invalid argument length");
    }

    // @TODO all this arg handling has always been messy;
    // has to be a neater way

    if (argn === 1) {
      if (typeof argv[0] === "string") {
        options = {
          message: argv[0],
          buttons: [{
            label: "OK"
          }]
        };
      } else if ($.isPlainObject(argv[0])) {
        // @TODO actually want we want to do is pluck a couple of
        // specific options off the provided object and namespace
        // them as buttons: [] args; the rest should be mapped as-is
        options = {
          message: argv[0].message,
          buttons: [{
            label: argv[0].label || "OK",
            callback: argv[0].callback
          }],
          onEscape: argv[0].callback
        };
      }
    } else if (argn === 2) {
      options = {
        message: argv[0],
        buttons: [{
          label: "OK",
          callback: argv[1]
        }],
        onEscape: argv[1]
      };
    }

    return dialog(options);
  };

  exports.dialog = dialog;

  return exports;

}(document, window.jQuery));
<commit_msg>start of basic #confirm method<commit_after>/**
 * bootbox.js [v4.x/master branch]
 *
 * http://bootboxjs.com/license.txt
 */
// @see https://github.com/makeusabrew/bootbox/issues/71
window.bootbox = window.bootbox || (function(document, $, undefined) {
  "use strict";

  // the base DOM structure needed to create a modal
  var template = [
    '
',
      '
',
        '
',
          '
',
            '<button type="button" class="close">×</button>',
            '

',
          '
',
          '
',
          '
',
          '
',
            '<button type="button" class="btn">A Button</button>',
          '
',
        '
',
      '
',
    '
'
  ].join("\n");

  // cache a reference to the jQueryfied body element
  var appendTo = $("body");

  // our public object; augmented after our private API
  var exports = {};

  function processCallback(e, elem, callback) {
    // by default we assume a callback will get rid of the dialog,
    // although they are given the opportunity to override this
    var preserveDialog = false;

    // so, if the callback can be invoked and it *explicitly returns false*
    // then we'll set a flag to keep the dialog active...
    if ($.isFunction(callback)) {
      preserveDialog = (callback(e) === false);
    }

    // ... otherwise we'll bin it
    if (!preserveDialog) {
      elem.modal("hide");
    }
  }

  function sanitize(options) {
    if (!options.message) {
      throw new Error("Please specify a message");
    }

    if (!options.buttons) {
      options.buttons = [];
    }

    if (!options.title) {
      // @FIXME gah; we need to pad the header a bit...
      options.title = " ";
    }

    if (options.show === undefined) {
      // auto show dialogs by default
      options.show = true;
    }

    var i = options.buttons.length;

    while (i--) {
      var button = options.buttons[i];

      if (!button.label) {
        throw new Error("Button at index " + i + " requires a label");
      }
    }

    return options;
  }

  /**
   * @private
   */
  function dialog(options) {
    options = sanitize(options);

    var elem = $(template);

    // buttons
    var buttons = options.buttons;
    var i = buttons.length;
    var button;
    var buttonStr = "";
    var callbacks = {};

    while (i--) {
      button = buttons[i];

      buttonStr = '<button data-bb-handler="' + i + '" type="button" class="btn ' + button.className + '">' + button.label + '</button>' + buttonStr;
      callbacks[i] = button.callback;
    }

    elem.find(".modal-body").html(options.message);
    elem.find(".modal-footer").html(buttonStr);

    // bootstrap event listeners

    elem.on("keyup.dismiss.bs.modal", function(e) {
      // @TODO make conditional
      if (e.which === 27) {
        elem.trigger("escape.close.bb");
      }
    });

    elem.on("hidden.bs.modal", function(e) {
      if (e.target === this) {
        elem.remove();
      }
    });

    elem.on("click", ".modal-footer button", function(e) {
      e.preventDefault();

      var callbackIndex = $(this).data("bb-handler");
      var callback = callbacks[callbackIndex];

      processCallback(e, elem, callback);

    });

    // bootbox event listeners
    elem.on("escape.close.bb", function(e) {
      processCallback(e, elem, options.onEscape);
    });

    appendTo.append(elem);

    elem.modal({
      backdrop: "static", // @TODO config
      keyboard: false,
      show: false
    });

    if (options.show) {
      elem.modal("show");
    }

    return elem;

  }

  // @NOTE all high level methods will now only
  // accept 1 or 2 args
  // if args.length === 2 then assume str, callback
  // if args.length === 1 then inspect for str Vs object
  exports.alert = function() {
    var options, argv = arguments, argn = argv.length;

    if (argn < 1 || argn > 2) {
      throw new Error("Invalid argument length");
    }

    // @TODO all this arg handling has always been messy;
    // has to be a neater way. Revisit after implementing #confirm
    // and/or #prompt

    if (argn === 1) {
      if (typeof argv[0] === "string") {
        options = {
          message: argv[0],
          buttons: [{
            label: "OK"
          }]
        };
      } else if ($.isPlainObject(argv[0])) {
        // @TODO actually want we want to do is pluck a couple of
        // specific options off the provided object and namespace
        // them as buttons: [] args; the rest should be mapped as-is
        options = {
          message: argv[0].message,
          buttons: [{
            label: argv[0].label || "OK",
            callback: argv[0].callback
          }],
          onEscape: argv[0].callback
        };
      } else {
        throw new Error("Invalid argument type");
      }
    } else if (argn === 2) {
      options = {
        message: argv[0],
        buttons: [{
          label: "OK",
          callback: argv[1]
        }],
        onEscape: argv[1]
      };
    }

    return dialog(options);
  };

  exports.confirm = function() {
    var options, argv = arguments, argn = argv.length;

    var defaults = {
      cancel: {
        retVal: false,
        label: "Cancel"
      },
      confirm: {
        retVal: true,
        label: "Confirm"
      }
    };

    var message;
    var cbCancel;
    var cbConfirm;
    var callback;
    var buttons = [];

    if (argn < 1 || argn > 2) {
      throw new Error("Invalid argument length");
    }

    if (argn === 1) {
      // @TODO
      /*
      if ($.isPlainObject(argv[0])) {
        options = {
          message: argv[0].message,
          buttons: [{
            label: argv[0].label || "OK",
            callback: argv[0].callback
          }],
          onEscape: argv[0].callback
        };
      } else {
        throw new Error("Invalid argument type");
      }
      */
    } else if (argn === 2) {
      message = argv[0];

      callback = argv[1];

      // we'll care about the key when checking whether
      // to replace user supplied options or not, but not yet
      $.each(defaults, function(key, value) {
        buttons.push({
          label: value.label,
          callback: function() {
            return callback(value.retVal);
          }
        });
      });

    }

    // #confirm specific validation
    if (!$.isFunction(callback)) {
      throw new Error("Confirm method requires callback");
    }

    options = {
      message: message,
      buttons: buttons,
      onEscape: function() { return callback(false); }
    };

    // @NOTE I guess validation is a two-step process; first we get the options
    // ship-shape regardless of how they were passed (object Vs multiple args)
    // before applying any method-specific validation (e.g. confirm requires
    // a callback to be passed)

    return dialog(options);
  };

  exports.dialog = dialog;

  return exports;

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


<commit_before>var Lang = A.Lang,
	UA = A.UA,
	getClassName = A.ClassNameManager.getClassName,

	NAME = 'swf',

	ATTR_VERSION = '10.22',
	ATTR_EXPRESS_INSTALL_URL = 'http://fpdownload.macromedia.com/pub/flashplayer/update/current/swf/autoUpdater.swf?' + (+ new Date),
	ATTR_TYPE = 'application/x-shockwave-flash',
	ATTR_CLSID = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
	ATTR_EVENT_HANDLER = 'YUI.AUI._SWF.eventHandler',

	SF = 'ShockwaveFlash',
	VERSION = 0,

	SWF_INSTANCES = YUI.AUI.namespace('_SWF.instances'),

	CSS_SWF = getClassName(NAME);

YUI.AUI._SWF.eventHandler = function(id, event) {
	SWF_INSTANCES[id]._eventHandler(event);
};

if (UA.gecko || UA.webkit || UA.opera) {
	var flashMimeType = navigator.mimeTypes[ATTR_TYPE];

	if (flashMimeType) {
		var enabledPlugin = flashMimeType.enabledPlugin;

		var versions = [];
		versions = enabledPlugin.description.replace(/\s[rd]/g, '.');
		versions = versions.replace(/[A-Za-z\s]+/g, '');
		versions = versions.split('.');

		VERSION = versions[0] + '.';

		switch ((versions[2].toString()).length) {
			case 1:
				VERSION += '00';
			break;

			case 2:
				VERSION += '0';
			break;
		}

		VERSION += versions[2];
		VERSION = parseFloat(VERSION);
	}
}
else if (UA.ie) {
	try {
		var activeX6 = new ActiveXObject(SF + '.' + '6');
		activeX6.AllowScriptAccess = 'always';
	}
	catch (e) {
		if (activeX6 != null) {
			VERSION = 6.0;
		}
	}

	if (VERSION == 0) {
		try {
			var activeX = new ActiveXObject(SF + '.' + SF);
			var versions = [];

			versions = activeX.GetVariable('$version');
			versions = versions.replace(/[A-Za-z\s]+/g, '');
			versions = versions.split(',');

			VERSION = versions[0] + '.';

			switch ((versions[2].toString()).length) {
				case 1:
					VERSION += '00';
				break;

				case 2:
					VERSION += '0';
				break;
			}
		}
		catch (e) {
		}
	}
}

UA.flash = VERSION;

var SWF = A.Component.create(
	{
		NAME: NAME,

		ATTRS: {
			url: {
				value: ''
			},
			version: {
				value: VERSION
			},
			useExpressInstall: {
				value: false
			},
			fixedAttributes: {
				value: {}
			},
			flashVars: {
				value: {}
			},
			render: {
				value: true
			}
		},

		getFlashVersion: function() {
			return VERSION;
		},

		isFlashVersionAtLeast: function(ver) {
			return VERSION >= ver;
		},

		prototype: {
			CONTENT_TEMPLATE: null,

			renderUI: function() {
				var instance = this;

				var properFlashVersion = SWF.isFlashVersionAtLeast(instance.get('version'));
				var canExpressInstall = (UA.flash >= 8.0);

				var shouldExpressInstall = canExpressInstall && !properFlashVersion && instance.get('useExpressInstall');

				var flashURL = instance.get('url');

				if (shouldExpressInstall) {
					flashURL = ATTR_EXPRESS_INSTALL_URL;
				}

				var swfId = A.guid();

				SWF_INSTANCES[swfId] = this;

				instance._swfId = swfId;

				var contentBox = instance.get('contentBox');
				var flashVars = instance.get('flashVars');

				A.mix(
					flashVars,
					{
						YUISwfId: swfId,
						YUIBridgeCallback: ATTR_EVENT_HANDLER
					}
				);

				var flashVarString = A.QueryString.stringify(flashVars);

				var tplObj = '<object ';

				if ((properFlashVersion || shouldExpressInstall) && flashURL) {
					tplObj += 'id="' + swfId + '" ';

					if (UA.ie) {
						tplObj += 'classid="' + ATTR_CLSID + '" ';
					}
					else {
						tplObj += 'type="' + ATTR_TYPE + '" data="' + flashURL + '" ';
					}

					tplObj += 'height="100%" width="100%">';

					if (UA.ie) {
						tplObj += '<param name="movie" value="' + flashURL + '"/>';
					}

					var fixedAttributes = instance.get('fixedAttributes');

					for (var i in fixedAttributes) {
						tplObj += '<param name="' + i + '" value="' + fixedAttributes[i] + '" />';
					}

					if (flashVarString) {
						tplObj += '<param name="flashVars" value="' + flashVarString + '" />';
					}

					tplObj += '</object>';

					contentBox.set('innerHTML', tplObj);
				}

				instance._swf = A.one('#' + swfId);
			},

			bindUI: function() {
				var instance = this;

				instance.publish(
					'swfReady',
					{
						fireOnce: true
					}
				);
			},

			callSWF: function(fn, args) {
				var instance = this;

				args = args || [];

				var swf = instance._swf.getDOM();

				if (swf[fn]) {
					return swf[fn].apply(swf, args);
				}

				return null;
			},

			toString: function() {
				var instance = this;

				return 'SWF' + instance._swfId;
			},

			_eventHandler: function(event) {
				var instance = this;

				var eventType = event.type.replace(/Event$/, '');

				if (eventType != 'log') {
					instance.fire(eventType, event);
				}
			}
		}
	}
);

A.SWF = SWF;<commit_msg>AUI-278 - Added compatibility with YUI SWF library<commit_after>var Lang = A.Lang,
	UA = A.UA,
	getClassName = A.ClassNameManager.getClassName,

	NAME = 'swf',

	ATTR_VERSION = '10.22',
	ATTR_EXPRESS_INSTALL_URL = 'http://fpdownload.macromedia.com/pub/flashplayer/update/current/swf/autoUpdater.swf?' + (+ new Date),
	ATTR_TYPE = 'application/x-shockwave-flash',
	ATTR_CLSID = 'clsid:d27cdb6e-ae6d-11cf-96b8-444553540000',
	ATTR_EVENT_HANDLER = 'YUI.AUI._SWF.eventHandler',

	SF = 'ShockwaveFlash',
	VERSION = 0,

	SWF_INSTANCES = YUI.AUI.namespace('_SWF.instances'),

	CSS_SWF = getClassName(NAME);

YUI.AUI._SWF.eventHandler = function(id, event) {
	SWF_INSTANCES[id]._eventHandler(event);
};

if (UA.gecko || UA.webkit || UA.opera) {
	var flashMimeType = navigator.mimeTypes[ATTR_TYPE];

	if (flashMimeType) {
		var enabledPlugin = flashMimeType.enabledPlugin;

		var versions = [];
		versions = enabledPlugin.description.replace(/\s[rd]/g, '.');
		versions = versions.replace(/[A-Za-z\s]+/g, '');
		versions = versions.split('.');

		VERSION = versions[0] + '.';

		switch ((versions[2].toString()).length) {
			case 1:
				VERSION += '00';
			break;

			case 2:
				VERSION += '0';
			break;
		}

		VERSION += versions[2];
		VERSION = parseFloat(VERSION);
	}
}
else if (UA.ie) {
	try {
		var activeX6 = new ActiveXObject(SF + '.' + '6');
		activeX6.AllowScriptAccess = 'always';
	}
	catch (e) {
		if (activeX6 != null) {
			VERSION = 6.0;
		}
	}

	if (VERSION == 0) {
		try {
			var activeX = new ActiveXObject(SF + '.' + SF);
			var versions = [];

			versions = activeX.GetVariable('$version');
			versions = versions.replace(/[A-Za-z\s]+/g, '');
			versions = versions.split(',');

			VERSION = versions[0] + '.';

			switch ((versions[2].toString()).length) {
				case 1:
					VERSION += '00';
				break;

				case 2:
					VERSION += '0';
				break;
			}
		}
		catch (e) {
		}
	}
}

UA.flash = VERSION;

var SWF = A.Component.create(
	{
		NAME: NAME,

		ATTRS: {
			url: {
				value: ''
			},
			version: {
				value: VERSION
			},
			useExpressInstall: {
				value: false
			},
			fixedAttributes: {
				value: {}
			},
			flashVars: {
				value: {}
			},
			render: {
				value: true
			}
		},

		constructor: function() {
			var instance = this;

			if (arguments.length > 1) {
				var config = {
					boundingBox: arguments[0],
					url: arguments[1],
					fixedAttributes: (arguments[2] ? arguments[2].fixedAttributes : null),
					flashVars: (arguments[2] ? arguments[2].flashVars : null)
				};

				SWF.superclass.constructor.call(this, config);
			}
		},

		getFlashVersion: function() {
			return VERSION;
		},

		isFlashVersionAtLeast: function(ver) {
			return VERSION >= ver;
		},

		prototype: {
			CONTENT_TEMPLATE: null,

			renderUI: function() {
				var instance = this;

				var properFlashVersion = SWF.isFlashVersionAtLeast(instance.get('version'));
				var canExpressInstall = (UA.flash >= 8.0);

				var shouldExpressInstall = canExpressInstall && !properFlashVersion && instance.get('useExpressInstall');

				var flashURL = instance.get('url');

				if (shouldExpressInstall) {
					flashURL = ATTR_EXPRESS_INSTALL_URL;
				}

				var swfId = A.guid();

				SWF_INSTANCES[swfId] = this;

				instance._swfId = swfId;

				var contentBox = instance.get('contentBox');
				var flashVars = instance.get('flashVars');

				A.mix(
					flashVars,
					{
						YUISwfId: swfId,
						YUIBridgeCallback: ATTR_EVENT_HANDLER
					}
				);

				var flashVarString = A.QueryString.stringify(flashVars);

				var tplObj = '<object ';

				if ((properFlashVersion || shouldExpressInstall) && flashURL) {
					tplObj += 'id="' + swfId + '" ';

					if (UA.ie) {
						tplObj += 'classid="' + ATTR_CLSID + '" ';
					}
					else {
						tplObj += 'type="' + ATTR_TYPE + '" data="' + flashURL + '" ';
					}

					tplObj += 'height="100%" width="100%">';

					if (UA.ie) {
						tplObj += '<param name="movie" value="' + flashURL + '"/>';
					}

					var fixedAttributes = instance.get('fixedAttributes');

					for (var i in fixedAttributes) {
						tplObj += '<param name="' + i + '" value="' + fixedAttributes[i] + '" />';
					}

					if (flashVarString) {
						tplObj += '<param name="flashVars" value="' + flashVarString + '" />';
					}

					tplObj += '</object>';

					contentBox.set('innerHTML', tplObj);
				}

				instance._swf = A.one('#' + swfId);
			},

			bindUI: function() {
				var instance = this;

				instance.publish(
					'swfReady',
					{
						fireOnce: true
					}
				);
			},

			callSWF: function(fn, args) {
				var instance = this;

				args = args || [];

				var swf = instance._swf.getDOM();

				if (swf[fn]) {
					return swf[fn].apply(swf, args);
				}

				return null;
			},

			toString: function() {
				var instance = this;

				return 'SWF' + instance._swfId;
			},

			_eventHandler: function(event) {
				var instance = this;

				var eventType = event.type.replace(/Event$/, '');

				if (eventType != 'log') {
					instance.fire(eventType, event);
				}
			}
		}
	}
);

A.SWF = SWF;<|endoftext|>


<commit_before>var properties = ["current", "voltage", "cputemp", "hddtemp", "pmutemp", "cpu0freq",
"cpu1freq","txbytes","rxbytes","Free_RAM","Uptime","Users_logged_on","Load"];

var hosts = [];

var units = {"current": "[A]", "voltage": "[V]", "cputemp": "[°C]", "hddtemp" : "[°C]",
"pmutemp": "[°C]", "cpu0freq": "[MHz]","cpu1freq": "[MHz]","txbytes": "MB","rxbytes": "MB","Free_RAM": "MB","Uptime":"","Users_logged_on":"","Load":"[%]" };

var defaultValues = {
  properties: ["voltage", "current", "cputemp", "pmutemp", "hddtemp"]
};

var jsonData = {"x":[]};
var charts = {};
var dateRange = [];

var graphInformation = {}; // caches graph info before drawing
var charts = {}; // holds references to drawn charts
var progressbar;

function setupPropertySelection(){
  var citynames = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
      url: 'propertynames.json',
      filter: function(list) {
        return $.map(list, function(cityname) {
          return { name: cityname }; });
        }
      }
    });
  citynames.initialize();

  $( "#property-selection input[type='text']" ).tagsinput({
    typeaheadjs: {
      name: 'propertynames',
      displayKey: 'name',
      valueKey: 'name',
      source: citynames.ttAdapter()
    }
  });

  $("#property-selection input[type='text']").on('beforeItemAdd', function(event) {
    var propertyName = event.item;
    if(properties.indexOf(propertyName) === -1){
      event.cancel = true; // prevent item from being added, when it is not in the properties-array
    }
  });

  $("#property-selection input[type='text']" ).eq(2).on('itemAdded', function(event) {
    var propertyName = event.item;
    if($("#p_" + propertyName).length){
      $("#p_" + propertyName).show();
    }
    else{
      $("#sortable").append('
' +
      '

' +  propertyName +" "+ units[propertyName] + '

');

      // setup sortable divs
      $( "#sortable" ).sortable();

      $("#chk_" + propertyName).prop('checked', true);
      $("#chk_" + propertyName).button( "refresh" );

      setupChart(propertyName);
    }
    $.notify({title: "" + propertyName + "", message: ": Graph added"},
      {
        placement: {from: "bottom", align: "right"},
        newest_on_top: true,
        animate: {
          enter: 'animated fadeInDown',
          exit: 'animated fadeOutUp'
        },
        type: 'success'
      });
  });

  $("#property-selection input[type='text']").eq(2).on('itemRemoved', function(event) {
    if($("#p_" + event.item).length){
      $("#p_" + event.item).hide();
      $("#chk_" + event.item).prop('checked', false);
      $("#chk_" + event.item).button( "refresh" );

      $.notify({title: "" + event.item + "", message: ": Graph removed"},
        {
          placement: {from: "bottom", align: "right"},
          newest_on_top: true,
          animate: {
            enter: 'animated fadeInDown',
            exit: 'animated fadeOutUp'
          },
          type: 'danger'
        });
    }
  });

  $("#property-selection div.bootstrap-tagsinput").first().append(
    '<button id="propertyBtn" class="tagsBtn"></button>');

  $("#propertyBtn").button().on( "click", function() {
    propertyDialog.dialog( "open" );
  });

}

function setupPropertyDialog(){
  properties.forEach(function(property) {
    $("#dialog-properties form fieldset").append('' + property +'');
    $("#dialog-properties form fieldset").append('<input class="chkbox" id="chk_' + property +'" type="checkbox"' +
    'value="' + property +'">');
  });

  $( "#dialog-properties .chkbox" ).checkboxradio();

  $("#dialog-properties .chkbox").bind('change', function(){
    if($(this).is(':checked')){
      $("#property-selection input[type='text']").eq(2).tagsinput('add', $(this).attr('value'),{preventPost: true});
      console.log("adding tag" + $(this).attr('value'));
    }else{

      $("#property-selection input[type='text']").eq(2).tagsinput('remove', $(this).attr('value'));
    }
  });

  propertyDialog = $( "#dialog-properties" ).dialog({
    autoOpen: false,
    resizable: true,
    modal: false,
    height: 'auto',
    width:'500px'
  });
}

function setupHostSelection(){
  var hostnames = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    prefetch: {
      url: 'hostnames.json',
      filter: function(list) {
        return $.map(list, function(hostname) {
          return { name: hostname }; });
        }
      }
    });
  hostnames.initialize();

  $( "#host-selection input[type='text']" ).tagsinput({
    typeaheadjs: {
      name: 'hostnames',
      displayKey: 'name',
      valueKey: 'name',
      source: hostnames.ttAdapter()
    }
  });

  $("#host-selection input[type='text']").on('beforeItemAdd', function(event) {
    if(hosts.indexOf(event.item) === -1){
      event.cancel = true; // prevent item from being added, when it is not in the hosts-array
    }
  });

  $("#host-selection input[type='text']" ).eq(2).on('itemAdded', function(event) {
    var hostname = event.item;
    $("#chk_" + hostname).prop('checked', true);
    $("#chk_" + hostname).button( "refresh" );
    if(! jsonData.hasOwnProperty(hostname)){
      $.getJSON("history/" + hostname + "_hist.json").done(function(json){
        integrateJsonData(hostname, json);
      })
      .fail(function( jqxhr, textStatus, error ) {
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err );
      });
    }else{
      // immediately update existing charts (data is there)
      for(var propertyName in charts) {
        charts[propertyName].show([hostname],{withLegend: true});
      }
    }
    console.log(hostname + " added");
  });

  $("#host-selection input[type='text']" ).eq(2).on('itemRemoved', function(event) {
    var hostname = event.item;
    $("#chk_" + hostname).prop('checked', false);
    $("#chk_" + hostname).button( "refresh" );

    // update existing charts
    for(var propertyName in charts) {
      //charts[propertyName].unload({ids: [hostname]});
      charts[propertyName].hide([hostname],{withLegend: true});
    }
    console.log(hostname + " removed");
  });

  $("#host-selection div.bootstrap-tagsinput").first().append(
    '<button id="hostBtn" class="tagsBtn"></button>');

  $("#hostBtn").button().on( "click", function() {
    hostDialog.dialog( "open" );
  });

}

function conformJsonValue(propertyName, value){
  switch(propertyName){
    case "voltage":
    case "current":
    return value / 1000000;
    case "cpu0freq":
    case "cpu1freq":
    return value / 1000;
    case "cputemp":
    case "pmutemp":
    return value.replace("°C","");
    case "txbytes":
    case "rxbytes":
    return value / 1000000;
    default:
    return value;
  }
}

function setupHostDialog(){
  hosts.forEach(function(host) {
    $("#dialog-host form fieldset").append('' + host +'');
    $("#dialog-host form fieldset").append('<input class="chkbox" id="chk_' + host +'" type="checkbox"' +
    'value="' + host +'">');
  });

  $( "#dialog-host .chkbox" ).checkboxradio();

  $("#dialog-host .chkbox").bind('change', function(){
    if($(this).is(':checked')){
      $("#host-selection input[type='text']").eq(2).tagsinput('add', $(this).attr('value'),{preventPost: true});
      console.log("adding tag" + $(this).attr('value'));
    }else{

      $("#host-selection input[type='text']").eq(2).tagsinput('remove', $(this).attr('value'));
    }
  });

  hostDialog = $( "#dialog-host" ).dialog({
    autoOpen: false,
    resizable: true,
    modal: false,
    height: 'auto',
    width:'500px'
  });
}

function setupChart(propertyName){
  columns = [['x'].concat(jsonData.x)];
  console.log("setting up chart for " + propertyName);
  $("#host-selection input[type='text']").eq(2).tagsinput('items').forEach(function(hostname){
    console.log("adding data from " + hostname);
    if(jsonData.hasOwnProperty(hostname)){
      columns.push([hostname].concat(jsonData[hostname][propertyName]));
    }
  });

  charts[propertyName] = c3.generate({
    bindto: '#chart_' + propertyName,
    data: {
      x: 'x',
      xFormat: '%a %b %d %H:%M:%S %Y',
      columns: columns
    },
    point: {
      show: false
    },
    transition: {
      duration: 0
    },
    interaction: {
      enabled: false
    },
    axis: {
      x: {
        type: 'timeseries',
        min: dateRange[0],
        max: dateRange[1],
        tick: {
          format: '%d.%m.%Y %H:%M:%S',
        }
      },
      y: {
        tick: {
          format: d3.format(",.2f")
        }
      }
    },
    grid: {
      x: {
        show: false
      },
      y: {
        show: true
      }
    },
    padding: {
      bottom: 30
    }
  });
}

function integrateJsonData(hostname, json){
  if(Object.keys(jsonData).length == 1){
    // adding first PI
    json.history.forEach(function(histEntry){
      //TODO: reliably filter out zone, or find appropriate format-string!
      jsonData.x.push(histEntry.date.replace("CEST ",""));
    });

    $("#datefrom").datepicker({
      minDate: new Date(jsonData.x[0]),
      maxDate:  new Date(jsonData.x[jsonData.x.length-1]),
      onSelect: function(date) {
        dateRange[0] = new Date(date);

        // if the user selected the first day on record, do not start chart
        // with 00:00, start instead with time of first entry (e.g. 09:00) (no leading "empty-space")
        var firstdate = new Date(jsonData.x[0]);
        if(dateRange[0].toDateString() == firstdate.toDateString()){
          dateRange[0] = firstdate;
        }

        // update existing charts
        for(var propertyName in charts) {
          charts[propertyName].axis.range({min: {x: dateRange[0]}});
        }
      }
    });
    $("#datefrom").datepicker('setDate', new Date(jsonData.x[0]));

    $("#dateto").datepicker({
      value: new Date(jsonData.x[jsonData.x.length-1]),
      minDate: new Date(jsonData.x[0]),
      maxDate:  new Date(jsonData.x[jsonData.x.length-1]),
      onSelect: function(date) {
        dateRange[1] = new Date(date);

        // if the user selected the last day on record, do not end chart
        // with 00:00, end instead with time of last entry (e.g. 09:00) (no trailing "empty-space")
        var lastdate = new Date(jsonData.x[jsonData.x.length-1]);
        if(dateRange[1].toDateString() == lastdate.toDateString()){
          dateRange[1] = lastdate;
        }

        // update existing charts
        for(var propertyName in charts) {
          charts[propertyName].axis.range({max:{x: dateRange[1]}});
        }
      }
    });
    $("#dateto").datepicker('setDate', new Date(jsonData.x[jsonData.x.length-1]));

  }

  var data = {};
  properties.forEach(function(property){
    data[property.split("_").join(" ")] = [];
  });

  json.history.forEach(function(histEntry){
    data.voltage.push(histEntry.voltage / 1000000);
    data.current.push(histEntry.current / 1000000);
    data.cpu0freq.push(histEntry.cpu0freq / 1000);
    data.cpu1freq.push(histEntry.cpu1freq / 1000);
    data.cputemp.push(histEntry.cputemp.replace("°C",""));
    data.pmutemp.push(histEntry.pmutemp.replace("°C",""));
    data.txbytes.push(histEntry.txbytes / 1000000);
    data.rxbytes.push(histEntry.rxbytes / 1000000);

    data.hddtemp.push(histEntry.hddtemp);
    data["Free RAM"].push(histEntry["Free RAM"]);
    data.Uptime.push(histEntry.Uptime);
    data["Users logged on"].push(histEntry["Users logged on"]);
    data.Load.push(histEntry.Load);
  });

  jsonData[hostname] = data;
  console.log(hostname + " integrated");
  // hosts.length+1 ... compensate x-property present in jsonData
  progressbar.progressbar( "value", (Object.keys(jsonData).length / (hosts.length+1))*100);
}

function getHostHistoryInformation(){
  // start displaying progress indicator
  progressbar.show();

  // for host in hosts, request history_file
  hosts.forEach(function(host){
    $("#host-selection input[type='text']").eq(2).tagsinput('add', host);
  });

  // progress is updated when a file has been downloaded and integrated
  // progress 100% -> hide progressbar and display default-charts
}
<commit_msg>changed initialization of typeahead.js to use locally specified values (stop requesting two unneccessary JSON-files)<commit_after>var properties = ["current", "voltage", "cputemp", "hddtemp", "pmutemp", "cpu0freq",
"cpu1freq","txbytes","rxbytes","Free_RAM","Uptime","Users_logged_on","Load"];

var hosts = [];

var units = {"current": "[A]", "voltage": "[V]", "cputemp": "[°C]", "hddtemp" : "[°C]",
"pmutemp": "[°C]", "cpu0freq": "[MHz]","cpu1freq": "[MHz]","txbytes": "MB","rxbytes": "MB","Free_RAM": "MB","Uptime":"","Users_logged_on":"","Load":"[%]" };

var defaultValues = {
  properties: ["voltage", "current", "cputemp", "pmutemp", "hddtemp"]
};

var jsonData = {"x":[]};
var charts = {};
var dateRange = [];

var graphInformation = {}; // caches graph info before drawing
var charts = {}; // holds references to drawn charts
var progressbar;

function setupPropertySelection(){

  var propertyList = [];
  properties.forEach(function(property){
    propertyList.push({name: property});
  });

  var propertyNames = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      local: propertyList
    });
  propertyNames.initialize();

  $( "#property-selection input[type='text']" ).tagsinput({
    typeaheadjs: {
      name: 'propertynames',
      displayKey: 'name',
      valueKey: 'name',
      source: propertyNames.ttAdapter()
    }
  });

  $("#property-selection input[type='text']").on('beforeItemAdd', function(event) {
    var propertyName = event.item;
    if(properties.indexOf(propertyName) === -1){
      event.cancel = true; // prevent item from being added, when it is not in the properties-array
    }
  });

  $("#property-selection input[type='text']" ).eq(2).on('itemAdded', function(event) {
    var propertyName = event.item;
    if($("#p_" + propertyName).length){
      $("#p_" + propertyName).show();
    }
    else{
      $("#sortable").append('
' +
      '

' +  propertyName +" "+ units[propertyName] + '

');

      // setup sortable divs
      $( "#sortable" ).sortable();

      $("#chk_" + propertyName).prop('checked', true);
      $("#chk_" + propertyName).button( "refresh" );

      setupChart(propertyName);
    }
    $.notify({title: "" + propertyName + "", message: ": Graph added"},
      {
        placement: {from: "bottom", align: "right"},
        newest_on_top: true,
        animate: {
          enter: 'animated fadeInDown',
          exit: 'animated fadeOutUp'
        },
        type: 'success'
      });
  });

  $("#property-selection input[type='text']").eq(2).on('itemRemoved', function(event) {
    if($("#p_" + event.item).length){
      $("#p_" + event.item).hide();
      $("#chk_" + event.item).prop('checked', false);
      $("#chk_" + event.item).button( "refresh" );

      $.notify({title: "" + event.item + "", message: ": Graph removed"},
        {
          placement: {from: "bottom", align: "right"},
          newest_on_top: true,
          animate: {
            enter: 'animated fadeInDown',
            exit: 'animated fadeOutUp'
          },
          type: 'danger'
        });
    }
  });

  $("#property-selection div.bootstrap-tagsinput").first().append(
    '<button id="propertyBtn" class="tagsBtn"></button>');

  $("#propertyBtn").button().on( "click", function() {
    propertyDialog.dialog( "open" );
  });

}

function setupPropertyDialog(){
  properties.forEach(function(property) {
    $("#dialog-properties form fieldset").append('' + property +'');
    $("#dialog-properties form fieldset").append('<input class="chkbox" id="chk_' + property +'" type="checkbox"' +
    'value="' + property +'">');
  });

  $( "#dialog-properties .chkbox" ).checkboxradio();

  $("#dialog-properties .chkbox").bind('change', function(){
    if($(this).is(':checked')){
      $("#property-selection input[type='text']").eq(2).tagsinput('add', $(this).attr('value'),{preventPost: true});
      console.log("adding tag" + $(this).attr('value'));
    }else{

      $("#property-selection input[type='text']").eq(2).tagsinput('remove', $(this).attr('value'));
    }
  });

  propertyDialog = $( "#dialog-properties" ).dialog({
    autoOpen: false,
    resizable: true,
    modal: false,
    height: 'auto',
    width:'500px'
  });
}

function setupHostSelection(){
  var hostList = [];
  hosts.forEach(function(property){
    hostList.push({name: property});
  });

  var hostNames = new Bloodhound({
      datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
      queryTokenizer: Bloodhound.tokenizers.whitespace,
      local: hostList
    });
  hostNames.initialize();

  $( "#host-selection input[type='text']" ).tagsinput({
    typeaheadjs: {
      name: 'hostNames',
      displayKey: 'name',
      valueKey: 'name',
      source: hostNames.ttAdapter()
    }
  });

  $("#host-selection input[type='text']").on('beforeItemAdd', function(event) {
    if(hosts.indexOf(event.item) === -1){
      event.cancel = true; // prevent item from being added, when it is not in the hosts-array
    }
  });

  $("#host-selection input[type='text']" ).eq(2).on('itemAdded', function(event) {
    var hostname = event.item;
    $("#chk_" + hostname).prop('checked', true);
    $("#chk_" + hostname).button( "refresh" );
    if(! jsonData.hasOwnProperty(hostname)){
      $.getJSON("history/" + hostname + "_hist.json").done(function(json){
        integrateJsonData(hostname, json);
      })
      .fail(function( jqxhr, textStatus, error ) {
        var err = textStatus + ", " + error;
        console.log( "Request Failed: " + err );
      });
    }else{
      // immediately update existing charts (data is there)
      for(var propertyName in charts) {
        charts[propertyName].show([hostname],{withLegend: true});
      }
    }
    console.log(hostname + " added");
  });

  $("#host-selection input[type='text']" ).eq(2).on('itemRemoved', function(event) {
    var hostname = event.item;
    $("#chk_" + hostname).prop('checked', false);
    $("#chk_" + hostname).button( "refresh" );

    // update existing charts
    for(var propertyName in charts) {
      charts[propertyName].hide([hostname],{withLegend: true});
    }
    console.log(hostname + " removed");
  });

  $("#host-selection div.bootstrap-tagsinput").first().append(
    '<button id="hostBtn" class="tagsBtn"></button>');

  $("#hostBtn").button().on( "click", function() {
    hostDialog.dialog( "open" );
  });

}

function conformJsonValue(propertyName, value){
  switch(propertyName){
    case "voltage":
    case "current":
    return value / 1000000;
    case "cpu0freq":
    case "cpu1freq":
    return value / 1000;
    case "cputemp":
    case "pmutemp":
    return value.replace("°C","");
    case "txbytes":
    case "rxbytes":
    return value / 1000000;
    default:
    return value;
  }
}

function setupHostDialog(){
  hosts.forEach(function(host) {
    $("#dialog-host form fieldset").append('' + host +'');
    $("#dialog-host form fieldset").append('<input class="chkbox" id="chk_' + host +'" type="checkbox"' +
    'value="' + host +'">');
  });

  $( "#dialog-host .chkbox" ).checkboxradio();

  $("#dialog-host .chkbox").bind('change', function(){
    if($(this).is(':checked')){
      $("#host-selection input[type='text']").eq(2).tagsinput('add', $(this).attr('value'),{preventPost: true});
      console.log("adding tag" + $(this).attr('value'));
    }else{

      $("#host-selection input[type='text']").eq(2).tagsinput('remove', $(this).attr('value'));
    }
  });

  hostDialog = $( "#dialog-host" ).dialog({
    autoOpen: false,
    resizable: true,
    modal: false,
    height: 'auto',
    width:'500px'
  });
}

function setupChart(propertyName){
  columns = [['x'].concat(jsonData.x)];
  console.log("setting up chart for " + propertyName);
  $("#host-selection input[type='text']").eq(2).tagsinput('items').forEach(function(hostname){
    console.log("adding data from " + hostname);
    if(jsonData.hasOwnProperty(hostname)){
      columns.push([hostname].concat(jsonData[hostname][propertyName]));
    }
  });

  charts[propertyName] = c3.generate({
    bindto: '#chart_' + propertyName,
    data: {
      x: 'x',
      xFormat: '%a %b %d %H:%M:%S %Y',
      columns: columns
    },
    point: {
      show: false
    },
    transition: {
      duration: 0
    },
    interaction: {
      enabled: false
    },
    axis: {
      x: {
        type: 'timeseries',
        min: dateRange[0],
        max: dateRange[1],
        tick: {
          format: '%d.%m.%Y %H:%M:%S',
        }
      },
      y: {
        tick: {
          format: d3.format(",.2f")
        }
      }
    },
    grid: {
      x: {
        show: false
      },
      y: {
        show: true
      }
    },
    padding: {
      bottom: 30
    }
  });
}

function integrateJsonData(hostname, json){
  if(Object.keys(jsonData).length == 1){
    // adding first PI
    json.history.forEach(function(histEntry){
      //TODO: reliably filter out zone, or find appropriate format-string!
      jsonData.x.push(histEntry.date.replace("CEST ",""));
    });

    $("#datefrom").datepicker({
      minDate: new Date(jsonData.x[0]),
      maxDate:  new Date(jsonData.x[jsonData.x.length-1]),
      onSelect: function(date) {
        dateRange[0] = new Date(date);

        // if the user selected the first day on record, do not start chart
        // with 00:00, start instead with time of first entry (e.g. 09:00) (no leading "empty-space")
        var firstdate = new Date(jsonData.x[0]);
        if(dateRange[0].toDateString() == firstdate.toDateString()){
          dateRange[0] = firstdate;
        }

        // update existing charts
        for(var propertyName in charts) {
          charts[propertyName].axis.range({min: {x: dateRange[0]}});
        }
      }
    });
    $("#datefrom").datepicker('setDate', new Date(jsonData.x[0]));

    $("#dateto").datepicker({
      value: new Date(jsonData.x[jsonData.x.length-1]),
      minDate: new Date(jsonData.x[0]),
      maxDate:  new Date(jsonData.x[jsonData.x.length-1]),
      onSelect: function(date) {
        dateRange[1] = new Date(date);

        // if the user selected the last day on record, do not end chart
        // with 00:00, end instead with time of last entry (e.g. 09:00) (no trailing "empty-space")
        var lastdate = new Date(jsonData.x[jsonData.x.length-1]);
        if(dateRange[1].toDateString() == lastdate.toDateString()){
          dateRange[1] = lastdate;
        }

        // update existing charts
        for(var propertyName in charts) {
          charts[propertyName].axis.range({max:{x: dateRange[1]}});
        }
      }
    });
    $("#dateto").datepicker('setDate', new Date(jsonData.x[jsonData.x.length-1]));

  }

  var data = {};
  properties.forEach(function(property){
    data[property.split("_").join(" ")] = [];
  });

  json.history.forEach(function(histEntry){
    data.voltage.push(histEntry.voltage / 1000000);
    data.current.push(histEntry.current / 1000000);
    data.cpu0freq.push(histEntry.cpu0freq / 1000);
    data.cpu1freq.push(histEntry.cpu1freq / 1000);
    data.cputemp.push(histEntry.cputemp.replace("°C",""));
    data.pmutemp.push(histEntry.pmutemp.replace("°C",""));
    data.txbytes.push(histEntry.txbytes / 1000000);
    data.rxbytes.push(histEntry.rxbytes / 1000000);

    data.hddtemp.push(histEntry.hddtemp);
    data["Free RAM"].push(histEntry["Free RAM"]);
    data.Uptime.push(histEntry.Uptime);
    data["Users logged on"].push(histEntry["Users logged on"]);
    data.Load.push(histEntry.Load);
  });

  jsonData[hostname] = data;
  console.log(hostname + " integrated");
  // hosts.length+1 ... compensate x-property present in jsonData
  progressbar.progressbar( "value", (Object.keys(jsonData).length / (hosts.length+1))*100);
}

function getHostHistoryInformation(){
  // start displaying progress indicator
  progressbar.show();

  // for host in hosts, request history_file
  hosts.forEach(function(host){
    $("#host-selection input[type='text']").eq(2).tagsinput('add', host);
  });

  // progress is updated when a file has been downloaded and integrated
  // progress 100% -> hide progressbar and display default-charts
}
<|endoftext|>