<commit_before>// @flow
import { app, Menu, shell, BrowserWindow } from 'electron';

export default class MenuBuilder {
  mainWindow: BrowserWindow;

  constructor(mainWindow: BrowserWindow) {
    this.mainWindow = mainWindow;
  }

  buildMenu() {
    if (process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true') {
      this.setupDevelopmentEnvironment();
    }

    let template;

    if (process.platform === 'darwin') {
      template = this.buildDarwinTemplate();
    } else {
      template = this.buildDefaultTemplate();
    }

    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);

    return menu;
  }

  setupDevelopmentEnvironment() {
    this.mainWindow.openDevTools();
    this.mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu
        .buildFromTemplate([{
          label: 'Inspect element',
          click: () => {
            this.mainWindow.inspectElement(x, y);
          }
        }])
        .popup(this.mainWindow);
    });
  }

  buildDarwinTemplate() {
    const subMenuAbout = {
      label: 'Electron',
      submenu: [
        { label: 'About ElectronReact', selector: 'orderFrontStandardAboutPanel:' },
        { type: 'separator' },
        { label: 'Services', submenu: [] },
        { type: 'separator' },
        { label: 'Hide ElectronReact', accelerator: 'Command+H', selector: 'hide:' },
        { label: 'Hide Others', accelerator: 'Command+Shift+H', selector: 'hideOtherApplications:' },
        { label: 'Show All', selector: 'unhideAllApplications:' },
        { type: 'separator' },
        { label: 'Quit', accelerator: 'Command+Q', click: () => { app.quit(); } }
      ]
    };
    const subMenuEdit = {
      label: 'Edit',
      submenu: [
        { label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' },
        { label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' },
        { type: 'separator' },
        { label: 'Cut', accelerator: 'Command+X', selector: 'cut:' },
        { label: 'Copy', accelerator: 'Command+C', selector: 'copy:' },
        { label: 'Paste', accelerator: 'Command+V', selector: 'paste:' },
        { label: 'Select All', accelerator: 'Command+A', selector: 'selectAll:' }
      ]
    };
    const subMenuViewDev = {
      label: 'View',
      submenu: [
        { label: 'Reload', accelerator: 'Command+R', click: () => { this.mainWindow.webContents.reload(); } },
        { label: 'Toggle Full Screen', accelerator: 'Ctrl+Command+F', click: () => { this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); } },
        { label: 'Toggle Developer Tools', accelerator: 'Alt+Command+I', click: () => { this.mainWindow.toggleDevTools(); } }
      ]
    };
    const subMenuViewProd = {
      label: 'View',
      submenu: [
        { label: 'Toggle Full Screen', accelerator: 'Ctrl+Command+F', click: () => { this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); } }
      ]
    };
    const subMenuWindow = {
      label: 'Window',
      submenu: [
        { label: 'Minimize', accelerator: 'Command+M', selector: 'performMiniaturize:' },
        { label: 'Close', accelerator: 'Command+W', selector: 'performClose:' },
        { type: 'separator' },
        { label: 'Bring All to Front', selector: 'arrangeInFront:' }
      ]
    };
    const subMenuHelp = {
      label: 'Help',
      submenu: [
        { label: 'Learn More', click() { shell.openExternal('http://electron.atom.io'); } },
        { label: 'Documentation', click() { shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme'); } },
        { label: 'Community Discussions', click() { shell.openExternal('https://discuss.atom.io/c/electron'); } },
        { label: 'Search Issues', click() { shell.openExternal('https://github.com/atom/electron/issues'); } }
      ]
    };

    const subMenuView = process.env.NODE_ENV === 'development'
      ? subMenuViewDev
      : subMenuViewProd;

    return [
      subMenuAbout,
      subMenuEdit,
      subMenuView,
      subMenuWindow,
      subMenuHelp
    ];
  }

  buildDefaultTemplate() {
    const templateDefault = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click: () => {
          this.mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click: () => {
          this.mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click: () => {
          this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click: () => {
          this.mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click: () => {
          this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    return templateDefault;
  }
}
<commit_msg>Misc code style changes to menu.js<commit_after>// @flow
import { app, Menu, shell, BrowserWindow } from 'electron';

export default class MenuBuilder {
  mainWindow: BrowserWindow;

  constructor(mainWindow: BrowserWindow) {
    this.mainWindow = mainWindow;
  }

  buildMenu() {
    if (process.env.NODE_ENV === 'development' || process.env.DEBUG_PROD === 'true') {
      this.setupDevelopmentEnvironment();
    }

    const template = process.platform === 'darwin'
      ? this.buildDarwinTemplate()
      : this.buildDefaultTemplate();

    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);

    return menu;
  }

  setupDevelopmentEnvironment() {
    this.mainWindow.openDevTools();
    this.mainWindow.webContents.on('context-menu', (e, props) => {
      const { x, y } = props;

      Menu
        .buildFromTemplate([{
          label: 'Inspect element',
          click: () => {
            this.mainWindow.inspectElement(x, y);
          }
        }])
        .popup(this.mainWindow);
    });
  }

  buildDarwinTemplate() {
    const subMenuAbout = {
      label: 'Electron',
      submenu: [
        { label: 'About ElectronReact', selector: 'orderFrontStandardAboutPanel:' },
        { type: 'separator' },
        { label: 'Services', submenu: [] },
        { type: 'separator' },
        { label: 'Hide ElectronReact', accelerator: 'Command+H', selector: 'hide:' },
        { label: 'Hide Others', accelerator: 'Command+Shift+H', selector: 'hideOtherApplications:' },
        { label: 'Show All', selector: 'unhideAllApplications:' },
        { type: 'separator' },
        { label: 'Quit', accelerator: 'Command+Q', click: () => { app.quit(); } }
      ]
    };
    const subMenuEdit = {
      label: 'Edit',
      submenu: [
        { label: 'Undo', accelerator: 'Command+Z', selector: 'undo:' },
        { label: 'Redo', accelerator: 'Shift+Command+Z', selector: 'redo:' },
        { type: 'separator' },
        { label: 'Cut', accelerator: 'Command+X', selector: 'cut:' },
        { label: 'Copy', accelerator: 'Command+C', selector: 'copy:' },
        { label: 'Paste', accelerator: 'Command+V', selector: 'paste:' },
        { label: 'Select All', accelerator: 'Command+A', selector: 'selectAll:' }
      ]
    };
    const subMenuViewDev = {
      label: 'View',
      submenu: [
        { label: 'Reload', accelerator: 'Command+R', click: () => { this.mainWindow.webContents.reload(); } },
        { label: 'Toggle Full Screen', accelerator: 'Ctrl+Command+F', click: () => { this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); } },
        { label: 'Toggle Developer Tools', accelerator: 'Alt+Command+I', click: () => { this.mainWindow.toggleDevTools(); } }
      ]
    };
    const subMenuViewProd = {
      label: 'View',
      submenu: [
        { label: 'Toggle Full Screen', accelerator: 'Ctrl+Command+F', click: () => { this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen()); } }
      ]
    };
    const subMenuWindow = {
      label: 'Window',
      submenu: [
        { label: 'Minimize', accelerator: 'Command+M', selector: 'performMiniaturize:' },
        { label: 'Close', accelerator: 'Command+W', selector: 'performClose:' },
        { type: 'separator' },
        { label: 'Bring All to Front', selector: 'arrangeInFront:' }
      ]
    };
    const subMenuHelp = {
      label: 'Help',
      submenu: [
        { label: 'Learn More', click() { shell.openExternal('http://electron.atom.io'); } },
        { label: 'Documentation', click() { shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme'); } },
        { label: 'Community Discussions', click() { shell.openExternal('https://discuss.atom.io/c/electron'); } },
        { label: 'Search Issues', click() { shell.openExternal('https://github.com/atom/electron/issues'); } }
      ]
    };

    const subMenuView = process.env.NODE_ENV === 'development'
      ? subMenuViewDev
      : subMenuViewProd;

    return [
      subMenuAbout,
      subMenuEdit,
      subMenuView,
      subMenuWindow,
      subMenuHelp
    ];
  }

  buildDefaultTemplate() {
    const templateDefault = [{
      label: '&File',
      submenu: [{
        label: '&Open',
        accelerator: 'Ctrl+O'
      }, {
        label: '&Close',
        accelerator: 'Ctrl+W',
        click: () => {
          this.mainWindow.close();
        }
      }]
    }, {
      label: '&View',
      submenu: (process.env.NODE_ENV === 'development') ? [{
        label: '&Reload',
        accelerator: 'Ctrl+R',
        click: () => {
          this.mainWindow.webContents.reload();
        }
      }, {
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click: () => {
          this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
        }
      }, {
        label: 'Toggle &Developer Tools',
        accelerator: 'Alt+Ctrl+I',
        click: () => {
          this.mainWindow.toggleDevTools();
        }
      }] : [{
        label: 'Toggle &Full Screen',
        accelerator: 'F11',
        click: () => {
          this.mainWindow.setFullScreen(!this.mainWindow.isFullScreen());
        }
      }]
    }, {
      label: 'Help',
      submenu: [{
        label: 'Learn More',
        click() {
          shell.openExternal('http://electron.atom.io');
        }
      }, {
        label: 'Documentation',
        click() {
          shell.openExternal('https://github.com/atom/electron/tree/master/docs#readme');
        }
      }, {
        label: 'Community Discussions',
        click() {
          shell.openExternal('https://discuss.atom.io/c/electron');
        }
      }, {
        label: 'Search Issues',
        click() {
          shell.openExternal('https://github.com/atom/electron/issues');
        }
      }]
    }];

    return templateDefault;
  }
}
<|endoftext|>


<commit_before>var Spaz;
if (!Spaz) Spaz = {};

/**
 * localization helper. Not yet implemented; just returns the passed string
 */
function $L(str) {
	return str;
}

// Spaz.verified = false;
Spaz.startReloadTimer = function() {
	var refreshInterval = Spaz.Prefs.getRefreshInterval();
	sch.debug('started timer with refresh of ' + refreshInterval + ' msecs');
	reloadID = window.setInterval(Spaz.UI.autoReloadCurrentTab, refreshInterval);
	return reloadID;
};

Spaz.stopReloadTimer = function() {
	if (reloadID) {
		window.clearInterval(reloadID);
		sch.debug('stopped timer');
	}
};

Spaz.restartReloadTimer = function() {
	sch.debug('trying to restart timer');
	Spaz.stopReloadTimer();
	Spaz.startReloadTimer();
};

Spaz.createUserDirs = function() {
	var appStore = air.File.applicationStorageDirectory;
	var userThemesDir = appStore.resolvePath(USERDIR_THEMES);
	userThemesDir.createDirectory();

	var userPluginsDir = appStore.resolvePath(USERDIR_PLUGINS);
	userPluginsDir.createDirectory();

	var userSmileysDir = appStore.resolvePath(USERDIR_SMILEYS);
	userSmileysDir.createDirectory();

	var userSoundsDir = appStore.resolvePath(USERDIR_SOUND);
	userSoundsDir.createDirectory();

	sch.debug(userThemesDir.nativePath);
	sch.debug(userPluginsDir.nativePath);
	sch.debug(userSmileysDir.nativePath);
	sch.debug(userSoundsDir.nativePath);
};

/**
 * loads the user.js file, if it exists, and injects it into the script tag with id='userjs'
 */
Spaz.loadUserJS = function() {
	var userjsfile = air.File.applicationStorageDirectory.resolvePath('user.js');

	if (userjsfile.exists) {
		var userJS = Spaz.Sys.getFileContents(userjsfile.url);
		$('#userjs').text(userJS);
	}

};

Spaz.loadOAuthServices = function() {
	SpazAuth.addService(SPAZCORE_ACCOUNT_TWITTER, {
        authType: SPAZCORE_AUTHTYPE_OAUTH,
        consumerKey: SPAZCORE_CONSUMERKEY_TWITTER,
        consumerSecret: SPAZCORE_CONSUMERSECRET_TWITTER,
        accessURL: 'https://twitter.com/oauth/access_token'
    });
}

/**
 * Bootstraps the app
 */
Spaz.initialize = function() {

	sch.debug('root init begin');

	air.NativeApplication.nativeApplication.autoExit = true;

	// create user themes and plugins dirs if necessary
	Spaz.createUserDirs();

	/***************************
	 * Load prefs
	 **************************/
	sch.debug('init prefs');
	Spaz.loadOAuthServices();
	Spaz.Prefs.init();
	Spaz.AccountPrefs.init();

	// sch.debug('init Sections');
	// Spaz.Section.init();

	// turn on debugging
	if (Spaz.Prefs.get('debug-enabled')) {
		sc.setDumpLevel(5);
		Spaz.Debug.insertDebugScripts();
	}

	// Database initialization
	sch.debug("database initialization");
	Spaz.DB.init();

    sch.debug('JazzRecord initialization');
    JazzRecord.adapter = new JazzRecord.AirAdapter({dbFile: "spaz_jr.db"});
    if (Spaz.Prefs.get('debug-enabled')) {
     JazzRecord.debug = true;
    }
    JazzRecord.depth = 0;
    JazzRecord.migrate();
    // JazzRecord.addIndex('tweets', 'twitter_id');
    // JazzRecord.addIndex('twusers', 'twitter_id');
    // JazzRecord.addIndex('twusers', 'screen_name');
    JazzRecord.addIndex('drafts', 'updated_at_unixtime');

    Spaz.TweetsModel = new Tweets();

	// Docking initialization
	sch.debug("docking initialization");
	Spaz.Dock.init();

	window.htmlLoader.manageCookies = false;
	window.htmlLoader.paintsDefaultBackground = false;
	window.htmlLoader.cacheResponse = true;
	window.htmlLoader.useCache = true;
	window.htmlLoader.authenticate = Spaz.Prefs.get('network-airhandlehttpauth');
	Spaz.Sys.initUserAgentString();

	air.URLRequestDefaults.manageCookies = false;
	air.URLRequestDefaults.cacheResponse = true;
	air.URLRequestDefaults.useCache = true;

	Spaz.Windows.makeSystrayIcon();

	// ***************************************************************
	// Keyboard shortcut handling
	// ***************************************************************
	Spaz.Controller.setKeyboardShortcuts();

	// insert theme CSS links
	Spaz.Themes.init();

	/***************************
	 * Apply prefs
	 **************************/
	window.moveTo(Spaz.Prefs.get('window-x'), Spaz.Prefs.get('window-y'));
	window.resizeTo(Spaz.Prefs.get('window-width'), Spaz.Prefs.get('window-height'));
	$('#username').val(Spaz.Prefs.getUsername());
	// $('#password').val(Spaz.Prefs.getPassword());

	//DONE: Check for Update
	if (Spaz.Prefs.get('checkupdate')) {
		sch.debug('Starting check for update');
		// Spaz.Update.updater.checkForUpdate();
		sch.debug('Ending check for update');
	}

	/************************
	 * Other stuff to do when document is ready
	 ***********************/
	Spaz.UI.playSoundStartup();
	sch.debug('Played startup sound');

	Spaz.Windows.makeWindowVisible();
	sch.debug('Made window visible');

	window.nativeWindow.visible = true;
	Spaz.Windows.setWindowOpacity(Spaz.Prefs.get('window-alpha'));
	Spaz.Windows.enableDropShadow(Spaz.Prefs.get('window-dropshadow'));
	Spaz.Windows.enableRestoreOnActivate(Spaz.Prefs.get('window-restoreonactivate'));
	Spaz.Windows.enableMinimizeOnBackground(Spaz.Prefs.get('window-minimizeonbackground'));

	if (Spaz.Prefs.get('window-minimizeatstartup')) {
		Spaz.Windows.windowMinimize();
	}

	/*
		this displays the body
	*/
	// $('body').addClass('visible');

	Spaz.UI.tabbedPanels = new Spry.Widget.TabbedPanels("tabs");

	Spaz.UI.prefsCPG = new Spry.Widget.CollapsiblePanelGroup("prefsCPG", {
		contentIsOpen: false,
		duration: 200
	});

	Spaz.UI.buildToolsMenu();

	// $('.panelmenu form input[title="filter"]').hint();

	$('.TabbedPanelsTab').each(function(i) {
		this.title = this.title + '
Shortcut: CMD or CTRL+' + (parseInt(i, 10) + 1) + '';
	});
	sch.debug('Set shortcut info in tab titles');

	/*
		set-up window and app events
	*/
	window.nativeWindow.addEventListener(air.Event.EXITING, Spaz.Windows.onWindowClose);
	// air.NativeApplication.nativeApplication.addEventListener(air.Event.EXITING, Spaz.Windows.onAppExit);
	window.nativeWindow.addEventListener(air.Event.CLOSING, Spaz.Windows.onWindowClose);
	window.nativeWindow.addEventListener(air.Event.ACTIVATE, Spaz.Windows.onWindowActive);
	window.nativeWindow.addEventListener(air.NativeWindowBoundsEvent.RESIZE, Spaz.Windows.onWindowResize);
	window.nativeWindow.addEventListener(air.NativeWindowBoundsEvent.MOVE, Spaz.Windows.onWindowMove);
	window.nativeWindow.addEventListener(air.Event.DEACTIVATE, Spaz.Windows.onWindowDeactivate);

	/*
		Initialize native menus
	*/
	Spaz.Menus.initAll();

	/*
		Set up event delegation stuff
	*/
	Spaz.Controller.initIntercept();

	/*
		Start check for updates process
	*/
	if (Spaz.Prefs.get('checkupdate')) {
		Spaz.Update.go();
	}

	/*
		if we have a username and password set, trigger an "account_switched" event
		to kick things off
	*/
	if (Spaz.Prefs.getUsername() && Spaz.Prefs.getAccountType()) {
		sch.trigger('account_switched', document, Spaz.Prefs.getCurrentAccount());
	}

	/*
		set-up usernameCompleter
	*/
	Spaz.uc = new usernameCompleter({
		'usernames':Spaz.Autocomplete.getScreenNames(),
		'hashtags':Spaz.Autocomplete.getHashTags(),
		'displayDiv':'#suggestions',
		'textarea':'#entrybox',
		'maxMatches':15
	});

	/*
		set-up post panel
	*/
	Spaz.postPanel = new SpazPostPanel({
		on_submit:function() {
			this.disable();
			var status = sch.trim(this.getMessageText());
			var auth = Spaz.Prefs.getAuthObject();
			var twit = new SpazTwit({'auth':auth});
			Spaz.Data.setAPIUrl(twit);
			var source = Spaz.Prefs.get('twitter-source');
			var irt_id = this.irt_status_id;
			twit.update(status, source, irt_id);
		}
	});
	Spaz.Drafts.updateCounter();

	/*
		Set up timeline calls to action
	*/
	Spaz.Timelines.toggleNewUserCTAs();

	/*
		Initialize indicators of current account
	*/
	(function(){
		var account = Spaz.Prefs.getCurrentAccount();
		if(account){
			Spaz.AccountPrefs.updateWindowTitleAndToolsMenu(account.id);
		}
	})();

	/*
		About popbox
	*/
	$('#about-version').text("v"+Spaz.Sys.getVersion());

	/*
		initialinze URL shortener
	*/
	var initUrlShortener = function() {

		var method;

		// get the pref
		var service = Spaz.Prefs.get('url-shortener');
		sch.debug("service is "+ service);

			if (service == 'shortie') {
				$('#shorten-custom-hidden').css({display: 'block', visibility: 'visible'});
			}

		// populate the dropdown
		for (method in Spaz.Shortlink.services) {
			sch.debug(method);

			if (method[0] != '$') {
				if (method == service) {
					$('#url-shortener').append('<option value="'+method+'" selected="selected">'+method+'</option>');
				} else {
					$('#url-shortener').append('<option value="'+method+'">'+method+'</option>');
				}
			}
		}

		$('#url-shortener').bind('change', function() {

			sch.debug($('#url-shortener').val());
			Spaz.Prefs.set('url-shortener', $('#url-shortener').val());
			if ($('#url-shortener').val() != 'shortie') {
				$('#shorten-custom-hidden').css({display: 'none', visibility: 'hidden'});
			} else {
				$('#shorten-custom-hidden').css({display: 'block', visibility: 'visible'});
			}
		});

		$('#shorten-original-link').focus();
		$('#shorten-original-link').val('http://');
		$('#shortenLink-form').bind('submit', function() {
		var service = Spaz.Prefs.get('url-shortener');
			sch.debug("service is "+ service);
				var custom = $('#shorten-custom-link').val();
				if (custom != '') {
				Spaz.Shortlink.services[service]($('#shorten-original-link').val(), custom);
				} else {
				Spaz.Shortlink.services[service]($('#shorten-original-link').val());
				}
		});

		// sch.debug(air.NativeApplication.nativeApplication.spazPrefs);
	};

	initUrlShortener();

	/*
		initialize Image uploader popbox
	*/
	var SpazImageUploader = new Spaz.ImageUploader();
	SpazImageUploader.init();

	// load User JS file
	Spaz.loadUserJS();

	sch.debug('ended document.ready()');
};<commit_msg>put SpazImageUploader obj in window.SpazImgUpl so can access from outside to init uploads<commit_after>var Spaz;
if (!Spaz) Spaz = {};

/**
 * localization helper. Not yet implemented; just returns the passed string
 */
function $L(str) {
	return str;
}

// Spaz.verified = false;
Spaz.startReloadTimer = function() {
	var refreshInterval = Spaz.Prefs.getRefreshInterval();
	sch.debug('started timer with refresh of ' + refreshInterval + ' msecs');
	reloadID = window.setInterval(Spaz.UI.autoReloadCurrentTab, refreshInterval);
	return reloadID;
};

Spaz.stopReloadTimer = function() {
	if (reloadID) {
		window.clearInterval(reloadID);
		sch.debug('stopped timer');
	}
};

Spaz.restartReloadTimer = function() {
	sch.debug('trying to restart timer');
	Spaz.stopReloadTimer();
	Spaz.startReloadTimer();
};

Spaz.createUserDirs = function() {
	var appStore = air.File.applicationStorageDirectory;
	var userThemesDir = appStore.resolvePath(USERDIR_THEMES);
	userThemesDir.createDirectory();

	var userPluginsDir = appStore.resolvePath(USERDIR_PLUGINS);
	userPluginsDir.createDirectory();

	var userSmileysDir = appStore.resolvePath(USERDIR_SMILEYS);
	userSmileysDir.createDirectory();

	var userSoundsDir = appStore.resolvePath(USERDIR_SOUND);
	userSoundsDir.createDirectory();

	sch.debug(userThemesDir.nativePath);
	sch.debug(userPluginsDir.nativePath);
	sch.debug(userSmileysDir.nativePath);
	sch.debug(userSoundsDir.nativePath);
};

/**
 * loads the user.js file, if it exists, and injects it into the script tag with id='userjs'
 */
Spaz.loadUserJS = function() {
	var userjsfile = air.File.applicationStorageDirectory.resolvePath('user.js');

	if (userjsfile.exists) {
		var userJS = Spaz.Sys.getFileContents(userjsfile.url);
		$('#userjs').text(userJS);
	}

};

Spaz.loadOAuthServices = function() {
	SpazAuth.addService(SPAZCORE_ACCOUNT_TWITTER, {
        authType: SPAZCORE_AUTHTYPE_OAUTH,
        consumerKey: SPAZCORE_CONSUMERKEY_TWITTER,
        consumerSecret: SPAZCORE_CONSUMERSECRET_TWITTER,
        accessURL: 'https://twitter.com/oauth/access_token'
    });
}

/**
 * Bootstraps the app
 */
Spaz.initialize = function() {

	sch.debug('root init begin');

	air.NativeApplication.nativeApplication.autoExit = true;

	// create user themes and plugins dirs if necessary
	Spaz.createUserDirs();

	/***************************
	 * Load prefs
	 **************************/
	sch.debug('init prefs');
	Spaz.loadOAuthServices();
	Spaz.Prefs.init();
	Spaz.AccountPrefs.init();

	// sch.debug('init Sections');
	// Spaz.Section.init();

	// turn on debugging
	if (Spaz.Prefs.get('debug-enabled')) {
		sc.setDumpLevel(5);
		Spaz.Debug.insertDebugScripts();
	}

	// Database initialization
	sch.debug("database initialization");
	Spaz.DB.init();

    sch.debug('JazzRecord initialization');
    JazzRecord.adapter = new JazzRecord.AirAdapter({dbFile: "spaz_jr.db"});
    if (Spaz.Prefs.get('debug-enabled')) {
     JazzRecord.debug = true;
    }
    JazzRecord.depth = 0;
    JazzRecord.migrate();
    // JazzRecord.addIndex('tweets', 'twitter_id');
    // JazzRecord.addIndex('twusers', 'twitter_id');
    // JazzRecord.addIndex('twusers', 'screen_name');
    JazzRecord.addIndex('drafts', 'updated_at_unixtime');

    Spaz.TweetsModel = new Tweets();

	// Docking initialization
	sch.debug("docking initialization");
	Spaz.Dock.init();

	window.htmlLoader.manageCookies = false;
	window.htmlLoader.paintsDefaultBackground = false;
	window.htmlLoader.cacheResponse = true;
	window.htmlLoader.useCache = true;
	window.htmlLoader.authenticate = Spaz.Prefs.get('network-airhandlehttpauth');
	Spaz.Sys.initUserAgentString();

	air.URLRequestDefaults.manageCookies = false;
	air.URLRequestDefaults.cacheResponse = true;
	air.URLRequestDefaults.useCache = true;

	Spaz.Windows.makeSystrayIcon();

	// ***************************************************************
	// Keyboard shortcut handling
	// ***************************************************************
	Spaz.Controller.setKeyboardShortcuts();

	// insert theme CSS links
	Spaz.Themes.init();

	/***************************
	 * Apply prefs
	 **************************/
	window.moveTo(Spaz.Prefs.get('window-x'), Spaz.Prefs.get('window-y'));
	window.resizeTo(Spaz.Prefs.get('window-width'), Spaz.Prefs.get('window-height'));
	$('#username').val(Spaz.Prefs.getUsername());
	// $('#password').val(Spaz.Prefs.getPassword());

	//DONE: Check for Update
	if (Spaz.Prefs.get('checkupdate')) {
		sch.debug('Starting check for update');
		// Spaz.Update.updater.checkForUpdate();
		sch.debug('Ending check for update');
	}

	/************************
	 * Other stuff to do when document is ready
	 ***********************/
	Spaz.UI.playSoundStartup();
	sch.debug('Played startup sound');

	Spaz.Windows.makeWindowVisible();
	sch.debug('Made window visible');

	window.nativeWindow.visible = true;
	Spaz.Windows.setWindowOpacity(Spaz.Prefs.get('window-alpha'));
	Spaz.Windows.enableDropShadow(Spaz.Prefs.get('window-dropshadow'));
	Spaz.Windows.enableRestoreOnActivate(Spaz.Prefs.get('window-restoreonactivate'));
	Spaz.Windows.enableMinimizeOnBackground(Spaz.Prefs.get('window-minimizeonbackground'));

	if (Spaz.Prefs.get('window-minimizeatstartup')) {
		Spaz.Windows.windowMinimize();
	}

	/*
		this displays the body
	*/
	// $('body').addClass('visible');

	Spaz.UI.tabbedPanels = new Spry.Widget.TabbedPanels("tabs");

	Spaz.UI.prefsCPG = new Spry.Widget.CollapsiblePanelGroup("prefsCPG", {
		contentIsOpen: false,
		duration: 200
	});

	Spaz.UI.buildToolsMenu();

	// $('.panelmenu form input[title="filter"]').hint();

	$('.TabbedPanelsTab').each(function(i) {
		this.title = this.title + '
Shortcut: CMD or CTRL+' + (parseInt(i, 10) + 1) + '';
	});
	sch.debug('Set shortcut info in tab titles');

	/*
		set-up window and app events
	*/
	window.nativeWindow.addEventListener(air.Event.EXITING, Spaz.Windows.onWindowClose);
	// air.NativeApplication.nativeApplication.addEventListener(air.Event.EXITING, Spaz.Windows.onAppExit);
	window.nativeWindow.addEventListener(air.Event.CLOSING, Spaz.Windows.onWindowClose);
	window.nativeWindow.addEventListener(air.Event.ACTIVATE, Spaz.Windows.onWindowActive);
	window.nativeWindow.addEventListener(air.NativeWindowBoundsEvent.RESIZE, Spaz.Windows.onWindowResize);
	window.nativeWindow.addEventListener(air.NativeWindowBoundsEvent.MOVE, Spaz.Windows.onWindowMove);
	window.nativeWindow.addEventListener(air.Event.DEACTIVATE, Spaz.Windows.onWindowDeactivate);

	/*
		Initialize native menus
	*/
	Spaz.Menus.initAll();

	/*
		Set up event delegation stuff
	*/
	Spaz.Controller.initIntercept();

	/*
		Start check for updates process
	*/
	if (Spaz.Prefs.get('checkupdate')) {
		Spaz.Update.go();
	}

	/*
		if we have a username and password set, trigger an "account_switched" event
		to kick things off
	*/
	if (Spaz.Prefs.getUsername() && Spaz.Prefs.getAccountType()) {
		sch.trigger('account_switched', document, Spaz.Prefs.getCurrentAccount());
	}

	/*
		set-up usernameCompleter
	*/
	Spaz.uc = new usernameCompleter({
		'usernames':Spaz.Autocomplete.getScreenNames(),
		'hashtags':Spaz.Autocomplete.getHashTags(),
		'displayDiv':'#suggestions',
		'textarea':'#entrybox',
		'maxMatches':15
	});

	/*
		set-up post panel
	*/
	Spaz.postPanel = new SpazPostPanel({
		on_submit:function() {
			this.disable();
			var status = sch.trim(this.getMessageText());
			var auth = Spaz.Prefs.getAuthObject();
			var twit = new SpazTwit({'auth':auth});
			Spaz.Data.setAPIUrl(twit);
			var source = Spaz.Prefs.get('twitter-source');
			var irt_id = this.irt_status_id;
			twit.update(status, source, irt_id);
		}
	});
	Spaz.Drafts.updateCounter();

	/*
		Set up timeline calls to action
	*/
	Spaz.Timelines.toggleNewUserCTAs();

	/*
		Initialize indicators of current account
	*/
	(function(){
		var account = Spaz.Prefs.getCurrentAccount();
		if(account){
			Spaz.AccountPrefs.updateWindowTitleAndToolsMenu(account.id);
		}
	})();

	/*
		About popbox
	*/
	$('#about-version').text("v"+Spaz.Sys.getVersion());

	/*
		initialinze URL shortener
	*/
	var initUrlShortener = function() {

		var method;

		// get the pref
		var service = Spaz.Prefs.get('url-shortener');
		sch.debug("service is "+ service);

			if (service == 'shortie') {
				$('#shorten-custom-hidden').css({display: 'block', visibility: 'visible'});
			}

		// populate the dropdown
		for (method in Spaz.Shortlink.services) {
			sch.debug(method);

			if (method[0] != '$') {
				if (method == service) {
					$('#url-shortener').append('<option value="'+method+'" selected="selected">'+method+'</option>');
				} else {
					$('#url-shortener').append('<option value="'+method+'">'+method+'</option>');
				}
			}
		}

		$('#url-shortener').bind('change', function() {

			sch.debug($('#url-shortener').val());
			Spaz.Prefs.set('url-shortener', $('#url-shortener').val());
			if ($('#url-shortener').val() != 'shortie') {
				$('#shorten-custom-hidden').css({display: 'none', visibility: 'hidden'});
			} else {
				$('#shorten-custom-hidden').css({display: 'block', visibility: 'visible'});
			}
		});

		$('#shorten-original-link').focus();
		$('#shorten-original-link').val('http://');
		$('#shortenLink-form').bind('submit', function() {
		var service = Spaz.Prefs.get('url-shortener');
			sch.debug("service is "+ service);
				var custom = $('#shorten-custom-link').val();
				if (custom != '') {
				Spaz.Shortlink.services[service]($('#shorten-original-link').val(), custom);
				} else {
				Spaz.Shortlink.services[service]($('#shorten-original-link').val());
				}
		});

		// sch.debug(air.NativeApplication.nativeApplication.spazPrefs);
	};

	initUrlShortener();

	/*
		initialize Image uploader popbox
	*/
	window.SpazImgUpl = new Spaz.ImageUploader();
	window.SpazImgUpl.init();

	// load User JS file
	Spaz.loadUserJS();

	sch.error('ended document.ready()');
};<|endoftext|>


<commit_before>/*
 *  Copyright (C) 2011-2012 The Animo Project
 *  http://animotron.org
 *
 *  This file is part of Animotron.
 *
 *  Animotron is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of
 *  the License, or (at your option) any later version.
 *
 *  Animotron is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of
 *  the GNU Affero General Public License along with Animotron.
 *  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Dmitriy Shabanov
 * @author Evgeny Gazdovsky
 *
 */
 (function($){

   /*
    *  The simple socket management system
    */

    if (window.MozWebSocket) {
        window.WebSocket = window.MozWebSocket;
    }

    $.socket = {

        pool  : [],
        uri   : "ws://" + window.location.host + "/ws",

        close : function (protocol) {
            var s = $.socket.pool[protocol];
            if (s) {
                s.close();
                clearInterval(s.ping);
            }
        },

        send  : function (message, protocol, callback) {
            var s = $.socket.pool[protocol];
            var send = function () {
                s.onmessage = function(event){
                    if (s.readyState == 1) {
                        callback(event);
                    }
                };
                s.send(message);
            }
            if (s && s.readyState == 1) {
                send();
            } else {
                s = new WebSocket($.socket.uri, protocol);
                s.onopen = function() {
                    send();
                    s.ping = setInterval(function(){
                        if (s.readyState == 1) {
                            s.send("");
                        }
                    }, 44000)
                };
                s.onclose = function() {
                    clearInterval(s.ping);
                };
                $.socket.pool[protocol] = s;
            }
        }

    };

   /*
    *  The live change JQuery plugin
    */

    $.fn.liveChange = function(callback) {
        return $(this).each(function(){
            var self = $(this);
            if (callback) {
                self.bind("liveChange", callback);
            }
            var timer;
            self.focus(function(){
                var value = self.val();
                function callback(){
                    var val = self.val();
                    if (val != value) {
                        value = val;
                        clearInterval(timer);
                        setTimeout(function(){
                            var v = self.val();
                            if (v == val) {
                                self.trigger("liveChange");
                            }
                            timer = setInterval(callback, 250);
                        }, 250);
                    }
                };
                timer = setInterval(callback, 250);
            }).blur(function(){
                clearInterval(timer);
            });
        });
    };

   /*
    *  The dynamic application environment
    */

    $.app = {

        context : function(root) {
            function build(root) {
                var a = [];
                $.each(root, function(){
                    var item = $(this);
                    var id = item.attr("id");
                    var c = build(item.children());
                    if (id) {
                        var o = {};
                        var v = item.val();
                        if (c.length > 0) {
                            c = c.length == 1 ? c[0] : c;
                            o[id] = v ? [v, c] : c;
                        } else {
                            o[id] = v;
                        }
                        a.push(o);
                    } else {
                        for (var i = 0; i < c.length; i++) {
                            a.push(c[i]);
                        }
                    }
                });
                return a;
            }
            return build(root ? root : $("body"));
        },

        eval : function (action, id, value) {
            $.socket.send(action + " " + id + " " + value, "app" ,function(event){
                eval("(function($){" + event.data + "})(jQuery);");
            });
        }

    };

})(jQuery);
<commit_msg>simplify<commit_after>/*
 *  Copyright (C) 2011-2012 The Animo Project
 *  http://animotron.org
 *
 *  This file is part of Animotron.
 *
 *  Animotron is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of
 *  the License, or (at your option) any later version.
 *
 *  Animotron is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of
 *  the GNU Affero General Public License along with Animotron.
 *  If not, see <http://www.gnu.org/licenses/>.
 *
 * @author Dmitriy Shabanov
 * @author Evgeny Gazdovsky
 *
 */
 (function($){

   /*
    *  The simple socket management system
    */

    if (window.MozWebSocket) {
        window.WebSocket = window.MozWebSocket;
    }

    $.socket = {

        pool  : [],
        uri   : "ws://" + window.location.host + "/ws",

        close : function (protocol) {
            var s = $.socket.pool[protocol];
            if (s) {
                s.close();
                clearInterval(s.ping);
            }
        },

        send  : function (message, protocol, callback) {
            var s = $.socket.pool[protocol];
            var send = function () {
                s.onmessage = function(event){
                    if (s.readyState == 1) {
                        callback(event);
                    }
                };
                s.send(message);
            }
            if (s && s.readyState == 1) {
                send();
            } else {
                s = new WebSocket($.socket.uri, protocol);
                s.onopen = function() {
                    send();
                    s.ping = setInterval(function(){
                        if (s.readyState == 1) {
                            s.send("");
                        }
                    }, 44000)
                };
                s.onclose = function() {
                    clearInterval(s.ping);
                };
                $.socket.pool[protocol] = s;
            }
        }

    };

   /*
    *  The live change JQuery plugin
    */

    $.fn.liveChange = function(callback) {
        return $(this).each(function(){
            var self = $(this);
            if (callback) {
                self.bind("liveChange", callback);
            }
            var timer;
            self.focus(function(){
                var value = self.val();
                function callback(){
                    var val = self.val();
                    if (val != value) {
                        value = val;
                        clearInterval(timer);
                        setTimeout(function(){
                            var v = self.val();
                            if (v == val) {
                                self.trigger("liveChange");
                            }
                            timer = setInterval(callback, 250);
                        }, 250);
                    }
                };
                timer = setInterval(callback, 250);
            }).blur(function(){
                clearInterval(timer);
            });
        });
    };

   /*
    *  The dynamic application environment
    */

    $.app = {

        context : function(root) {
            function build(root) {
                var a = [];
                $.each(root, function(){
                    var item = $(this);
                    var id = item.attr("id");
                    var c = build(item.children());
                    if (id) {
                        var o = {};
                        var v = item.val();
                        if (c.length > 0) {
                            c = c.length == 1 ? c[0] : c;
                            o[id] = v ? [v, c] : c;
                        } else {
                            o[id] = v;
                        }
                        a.push(o);
                    } else {
                        for (var i = 0; i < c.length; i++) {
                            a.push(c[i]);
                        }
                    }
                });
                return a;
            }
            var c = build(root ? root : $("body"));
            return c.length == 1 ? c[0] : c;
        },

        eval : function (action, id, value) {
            $.socket.send(action + " " + id + " " + value, "app" ,function(event){
                eval("(function($){" + event.data + "})(jQuery);");
            });
        }

    };

})(jQuery);
<|endoftext|>


<commit_before>/*
 * ADB for debug
 * adb logcat Cordova:* DroidGap:* CordovaLog:* *:S
var plabBTMode = {
		id : "",
		name : "",
		status : {
			initialized : false,
			connected : false,
			ready : false,
			failure : false
		},

		// serviceInfo : {
		//	serviceUUID : "FFE0", // for the Service
		//	txUUID :  "FFE1", // for the TX Characteristic (Property = Notify)
		//	rxUUID : "FFE1" // for the RX Characteristic (Property = Write without response)
		//},

		// timers : {
		//	scanning : null,
		//	connecting : null
		// }
		// address : null

		// subscriptions : []
		// startSubscribe : function() {},

		openMode : function () {},
		closeMode : function () {},

		listDevices : function (listCallback, scanTime) {},
		stopListDevices : function () {},

		connectDevice : function (id) {},
		disconnectDevice : function () {},

		send : function (text) {},
		receiveCallback : function (callback) {}
}
 *
 */
try {
function plabAddBT4_0(debugOut, updateScreen) {
	// See if necessary plugin is installed
	alert("add");
	if (typeof bluetoothle === "undefined") {
		return;
	}
	alert("typeof ok");
	/*
	// Creating a prototype object
	var btMode = Object.create(plabBTMode);
	btMode.id = "BlueTooth_4.0_randdusing";
	btMode.name = "BlueTooth LE";

	// Adding info since this is init
	btMode.status.started = false;
	btMode.status.scanning = false;
	btMode.timers = {
			scanning : null,
			connecting : null
	};
	btMode.address = null;
	btMode.serviceInfo = {
		serviceUUID : "FFE0", // for the Service
		txUUID :  "FFE1", // for the TX Characteristic (Property = Notify)
		rxUUID : "FFE1" // for the RX Characteristic (Property = Write without response)
	};
	btMode.subscriptions = [];

	btMode.startSubscribe = function () {
		var params = {
				"address":btMode.address,
				"serviceUuid":btMode.serviceInfo.serviceUUID,
				"characteristicUuid":btMode.serviceInfo.rxUUID,
				"isNotification":true
		};

		// Callback funksjonen for subscribes
		bluetoothle.subscribe(
				function (obj) {
					try {
						if (obj.status == "subscribedResult") {
							// Debug output
							debugOut.notify.print("Mottok data: ");
							debugOut.notify.println(JSON.stringify(obj));
							// Pass to subscribers
							for (var i = 0; i < btMode.subscriptions.length; i++) {
								btMode.subscriptions[i](bluetoothle.bytesToString(bluetoothle.encodedStringToBytes(obj.value)));
							}
						} else if (obj.status == "subscribed") {
							// Nothing here
						} else {
							debugOut.err.println("UnknownSubscribeStatus");
						}
					} catch (e) {
						debugOut.err.println("SubscribeFailure: " + e.message);
					}
				},
				function (obj) {
					debugOut.err.println"SubscribeFailure: " + obj.error + " - " + obj.message);
				},
				params
		);
	};
	alert("HOHO");

	// Replacing the open mode function -> init the mode
	btMode.openMode = function () {
		if (!btMode.status.started) {
			btMode.status.started = true;
			// First run -> set up
			btMode.closeMode = function () {
				// Remove all listeners
				// TODO
				// Close open connections
				btMode.disconnectDevice();

				// Update status
				btMode.status.connected = false;
				btMode.status.ready = false;
				btMode.status.failure = false;

				// Call and clear scanners
				if (btMode.timers.scanning !== null) {
					clearTimeout(btMode.timers.scanning);
					btMode.timers.scanning = null;
					btMode.stopListDevices();
				}
			};

			// ------------------ SCAN ------------------------
			btMode.listDevices = function (listCallback, scanTime) {
				btMode.timers.scanning = "";
				bluetoothle.startScan(
						function(obj) {
							if (obj.status == "scanResult") {
								// Create the descriptor
								var name = obj.name === null ? "? - " + obj.address : obj.name;
								var desc = plabBT.createDeviceDescriptor(obj.address, name);
								listCallback(desc);
							} else if (obj.status == "scanStarted") {
								btMode.timers.scanning = setTimeout(btMode.stopListDevices, scanTime);
							} else {
								debugOut.warn.println("StartScanFailure: Unknown status: " + obj.status);
							}
						},
						function(obj) {
							btMode.status.failure = true;
							debugOut.err.println("ScanFailure: " + obj.error + " - " + obj.message);
							updateScreen();
						},
						null
				);
			};
			btMode.stopListDevices = function () {
				bluetoothle.stopScan (
					function (obj) {
						if (obj.status !== "scanStopped") {
							debugOut.warn.println("StopScanFailure: Unknown status: " + obj.status);
						}
					},
					function(obj){
						debugOut.err.println("StopScanFailure: " + obj.error + " - " + obj.message);
					}
				);
			};
			// ------------------ END SCAN ------------------------

			// ------------------ CONNECT ------------------
			btMode.connectDevice = function (id, successCallback) {
				// Remember address
				btMode.address = id;

				// Stop scan if needed
				if (btMode.timers.scanning !== null){
					clearTimeout(btMode.timers.scanning);
					btMode.timers.scanning = null;
					btMode.stopListDevices();
				}
				// Connect
				bluetoothle.connect (
						function(obj) {
							if (obj.status == "connected") {

								// Clear connect timeout
								if (btMode.timers.connecting !== null) {
									clearTimeout(btMode.timers.connecting);
									btMode.timers.connecting = null;
								}

								// Update status
								btMode.status.connected = true;
								btMode.status.failure = false;
								updateScreen();

								// common function after discovery
								var common = function (success) {
									if (success) {
										// Do callback
										successCallback();
										// Start message subscription
										btMode.startSubscribe();
									} else {
										// Alert that UART failed
										debugOut.err.println("DiscoverFailure: Failed to discover UART service");
										btMode.status.failure = true;
									}
								};

								// The path from here is platform dependent
								if (window.device.platform == plab.platforms.iOS) {
									// iOS: Discover only the service we want to connect to
									bluetoothle.services (
											function (obj) {
												// TODO Make more robust
												// Assuming correct service was discovered
												if (obj.status == "services") {
													var params = {
															"address" : btMode.address,
															"serviceUuid" : btMode.serviceInfo.serviceUUID,
															"characteristicUuids" : [ btMode.serviceInfo.txUUID, btMode.serviceInfo.rxUUID ]
													};
													bluetoothle.characteristics (
															function (obj) {
																// TODO Make more robust
																// Assuming correct characteristic discovered
																if (obj.status == "characteristics") {
																	var params1 = {
																			"address" : btMode.address,
																			"serviceUuid" : btMode.serviceInfo.serviceUUID,
																			"characteristicUuid" : btMode.serviceInfo.txUUID
																	};
																	var params2 = {
																			"address" : btMode.address,
																			"serviceUuid" : btMode.serviceInfo.serviceUUID,
																			"characteristicUuid" : btMode.serviceInfo.rxUUID
																	};
																	// Bruteforcer gjennom listen
																	bluetoothle.descriptors (

																			function (obj) {
																				if (obj.status == "descriptors") {
																					bluetoothle.descriptors (

																							function (obj1) {
																								if (obj1.status == "descriptors") {
																									common(true);
																								} else {
																									debugOut.err.println("DescriptorsFailure: Unknown status: " + obj1.status);
																									btMode.disconnectDevice();
																								}
																							},

																							function (obj1) {
																								debugOut.err.println("DescriptorsFailure: " + obj1.error + " - " + obj1.message);
																								btMode.disconnectDevice ();
																							},
																							params2
																					);
																				} else {
																					debugOut.err.println("DescriptorsFailure: Unknown status: " + obj.status);
																					btMode.disconnectDevice ();
																				}
																			},

																			function (obj) {
																				debugOut.err.println("DescriptorsFailure: " + obj.error + " - " + obj.message);
																				btMode.disconnectDevice ();
																			},
																			params1
																	);
																} else {
																	debugOut.err.println("CharacteristicsFailure: Unknown status: " + obj.status);
																	btMode.disconnectDevice ();
																}
															},
															function (obj) {
																debugOut.err.println("CharacteristicsFailure: " + obj.error + " - " + obj.message);
																btMode.disconnectDevice ();
															},
															params
													);
												} else {
													debugOut.err.println("ServicesFailure: Unknown status: " + obj.status);
													btMode.disconnectDevice ();
												}
											},
											function (obj) {
												debugOut.err.println("ServicesFailure: " + obj.error + " - " + obj.message);
												btMode.disconnectDevice ();
											},
											{"address":id , "serviceUuids":[btMode.serviceInfo.serviceUUID]}
									);
								} else if (window.device.platform == plab.platforms.android) {
									// android: discover discovers all services and descriptors
									bluetoothle.discover (
											function (obj) {
												if (obj.status == "discovered") {
													// TODO check if service is available
													common(true);
												} else {
													debugOut.err.println("DiscoverFailure: Unknown status: " + obj.status);
													btMode.disconnectDevice ();
												}
											},
											function (obj) {
												debugOut.err.println("DiscoverFailure: " + obj.error + " - " + obj.message);
												btMode.disconnectDevice ();
											},
											{"address" : id}
									);
								} else {
									// Greit aa si ifra om at dette ikke vil fungere, vi stoetter bare iOS/android
									alert ("This platform is not supported");
								}

							} else if (obj.status != "connecting") {
								// Holder paa med tilkobling enda, ikke gjoer noe spesielt
								btMode.status.connected = false;
								btMode.status.ready = false;
								updateScreen();
							}
						},
						function(obj) {
							btMode.status.connected = false;
							btMode.status.ready = false;
							btMode.status.failure = true;
							debugOut.err.println("ConnectFailure: " + obj.error + " - " + obj.message);
							// Clear connect timeout
							if (btMode.timers.connecting !== null) {
								clearTimeout(btMode.timers.connecting);
								btMode.timers.connecting = null;
							}
							updateScreen ();
						},
						{"address":id}
				);
				plab.timers.connect = setTimeout(btMode.stopListDevices, 5000);
			};
			// ------------------ END CONNECT ------------------

			// ------------------ DICCONNECT ------------------
			btMode.disconnectDevice = function () {
				var closeDev = function() {
					btMode.status.connected = false;
					btMode.status.ready = false;
					bluetoothle.close(
							function (obj) {
								if (obj.status == "closed") {
									btMode.address = null;
								} else {
									debugOut.warn("CloseFailure: Unknown status: " + obj.status);
								}
							},
							function (obj) {
								debugOut.err.println("CloseFailure: " + obj.error + " - " + obj.message);
							},
							{"address":btMode.address}
					);
				};
				if (btMode.status.connected || btMode.address !== null) {
					bluetoothle.disconnect(
						function (obj) {
							if (obj.status == "disconnected") {
								closeDev();
							} else if (obj.status == "disconnecting") {
								// Allowed to stand if needed later
							} else {
								// Allowed to stand if needed later
							}
						},
						function (obj) {
							// Ensure the connection is closed
							debugOut.err.println("DisconnectFailure: " + obj.error + " - " + obj.message);
							closeDev();
						},
						{"address":btMode.address}
					);
				}
				btMode.status.ready = false;
			};
			// ------------------ END DICCONNECT ------------------

			// -------------- SEND / RECEIVE ------------
			btMode.send = function (text) {
					if (btMode.status.connected) {
						var params = {
								"address" : btMode.address,
								"value" : bluetoothle.bytesToEncodedString(bluetoothle.stringToBytes(text)),
								"serviceUuid" : btMode.serviceInfo.serviceUUID,
								"characteristicUuid" : btMode.serviceInfo.txUUID,
								"type" : "noResponse"
						};
						bluetoothle.write (
								function (obj) {},
								function (obj) {
									debugOut.err.println("WriteFailure: " + obj.error + " - " + obj.message);
								},
								params
						);
						/*
						bluetoothle.isConnected (
							function (conn) {
								if (conn.isConnected) {
									bluetoothle.write (
											function (obj) {},
											function (obj) {
												plab.notifyErrorString ("WriteFailure: " + obj.error + " - " + obj.message);
											},
											params
									);
								} else {
									plab.afterReconnect[plab.afterReconnect.length] = function() {
										plab.write(string);
									};
									plab.reconnect ();
								}
							}
						);
						*/
						/*
					} else {
						debugOut.warn.println("WriteFailure: Not connected");
					}
			};
			btMode.receiveCallback = function (callback) {
				btMode.subscriptions[btMode.subscriptions.length] = callback;
			};
			// -------------- END SEND / RECEIVE ------------
			// TODO
		}

		// -------------- INIT -------------------
		if (!btMode.status.initialized) {
			bluetoothle.initialize(

					function(obj) {
						if (obj.status == "enabled") {
							btMode.status.initialized = true;
							updateScreen();
						} else {
							debugOut.warn.println("InitializeFailure: Unknown status: " + obj.status);
						}
					},

					function(obj) {
						btMode.status.failure = true;
						debugOut.err.println("InitializeFailure: " + obj.error + " - " + obj.message);
						updateScreen();
					},

					{"request":false}
			);
		}
		// -------------- END INIT -------------------
	};
	*/
	plabBT.addMode(btMode);
}

document.addEventListener(
		"deviceready",
		function() {
			plabAddBT4_0(plab.out, plab.updateScreen);
		},
		false
);

} catch (e) {
	alert(e);
}<commit_msg>Removed erronous code, code now run<commit_after>/*
 * ADB for debug
 * adb logcat Cordova:* DroidGap:* CordovaLog:* *:S
var plabBTMode = {
		id : "",
		name : "",
		status : {
			initialized : false,
			connected : false,
			ready : false,
			failure : false
		},

		// serviceInfo : {
		//	serviceUUID : "FFE0", // for the Service
		//	txUUID :  "FFE1", // for the TX Characteristic (Property = Notify)
		//	rxUUID : "FFE1" // for the RX Characteristic (Property = Write without response)
		//},

		// timers : {
		//	scanning : null,
		//	connecting : null
		// }
		// address : null

		// subscriptions : []
		// startSubscribe : function() {},

		openMode : function () {},
		closeMode : function () {},

		listDevices : function (listCallback, scanTime) {},
		stopListDevices : function () {},

		connectDevice : function (id) {},
		disconnectDevice : function () {},

		send : function (text) {},
		receiveCallback : function (callback) {}
}
 *
 */
try {
function plabAddBT4_0(debugOut, updateScreen) {
	// See if necessary plugin is installed
	if (typeof bluetoothle === "undefined") {
		return;
	}

	// Creating a prototype object
	var btMode = Object.create(plabBTMode);
	btMode.id = "BlueTooth_4.0_randdusing";
	btMode.name = "BlueTooth LE";

	// Adding info since this is init
	btMode.status.started = false;
	btMode.status.scanning = false;
	btMode.timers = {
			scanning : null,
			connecting : null
	};
	btMode.address = null;
	btMode.serviceInfo = {
		serviceUUID : "FFE0", // for the Service
		txUUID :  "FFE1", // for the TX Characteristic (Property = Notify)
		rxUUID : "FFE1" // for the RX Characteristic (Property = Write without response)
	};
	btMode.subscriptions = [];

	btMode.startSubscribe = function () {
		var params = {
				"address":btMode.address,
				"serviceUuid":btMode.serviceInfo.serviceUUID,
				"characteristicUuid":btMode.serviceInfo.rxUUID,
				"isNotification":true
		};

		// Callback functions for subscribe
		bluetoothle.subscribe(
				function (obj) {
					try {
						if (obj.status == "subscribedResult") {
							// Debug output
							debugOut.notify.print("Mottok data: ");
							debugOut.notify.println(JSON.stringify(obj));
							// Pass to subscribers
							for (var i = 0; i < btMode.subscriptions.length; i++) {
								btMode.subscriptions[i](bluetoothle.bytesToString(bluetoothle.encodedStringToBytes(obj.value)));
							}
						} else if (obj.status == "subscribed") {
							// Nothing here
						} else {
							debugOut.err.println("UnknownSubscribeStatus");
						}
					} catch (e) {
						debugOut.err.println("SubscribeFailure: " + e.message);
					}
				},
				function (obj) {
					debugOut.err.println("SubscribeFailure: " + obj.error + " - " + obj.message);
				},
				params
		);

	};

	// Replacing the open mode function -> init the mode
	btMode.openMode = function () {
		if (!btMode.status.started) {
			btMode.status.started = true;
			// First run -> set up
			btMode.closeMode = function () {
				// Remove all listeners
				// TODO
				// Close open connections
				btMode.disconnectDevice();

				// Update status
				btMode.status.connected = false;
				btMode.status.ready = false;
				btMode.status.failure = false;

				// Call and clear scanners
				if (btMode.timers.scanning !== null) {
					clearTimeout(btMode.timers.scanning);
					btMode.timers.scanning = null;
					btMode.stopListDevices();
				}
			};

			// ------------------ SCAN ------------------------
			btMode.listDevices = function (listCallback, scanTime) {
				btMode.timers.scanning = "";
				bluetoothle.startScan(
						function(obj) {
							if (obj.status == "scanResult") {
								// Create the descriptor
								var name = obj.name === null ? "? - " + obj.address : obj.name;
								var desc = plabBT.createDeviceDescriptor(obj.address, name);
								listCallback(desc);
							} else if (obj.status == "scanStarted") {
								btMode.timers.scanning = setTimeout(btMode.stopListDevices, scanTime);
							} else {
								debugOut.warn.println("StartScanFailure: Unknown status: " + obj.status);
							}
						},
						function(obj) {
							btMode.status.failure = true;
							debugOut.err.println("ScanFailure: " + obj.error + " - " + obj.message);
							updateScreen();
						},
						null
				);
			};
			btMode.stopListDevices = function () {
				bluetoothle.stopScan (
					function (obj) {
						if (obj.status !== "scanStopped") {
							debugOut.warn.println("StopScanFailure: Unknown status: " + obj.status);
						}
					},
					function(obj){
						debugOut.err.println("StopScanFailure: " + obj.error + " - " + obj.message);
					}
				);
			};
			// ------------------ END SCAN ------------------------

			// ------------------ CONNECT ------------------
			btMode.connectDevice = function (id, successCallback) {
				// Remember address
				btMode.address = id;

				// Stop scan if needed
				if (btMode.timers.scanning !== null){
					clearTimeout(btMode.timers.scanning);
					btMode.timers.scanning = null;
					btMode.stopListDevices();
				}
				// Connect
				bluetoothle.connect (
						function(obj) {
							if (obj.status == "connected") {

								// Clear connect timeout
								if (btMode.timers.connecting !== null) {
									clearTimeout(btMode.timers.connecting);
									btMode.timers.connecting = null;
								}

								// Update status
								btMode.status.connected = true;
								btMode.status.failure = false;
								updateScreen();

								// common function after discovery
								var common = function (success) {
									if (success) {
										// Do callback
										successCallback();
										// Start message subscription
										btMode.startSubscribe();
									} else {
										// Alert that UART failed
										debugOut.err.println("DiscoverFailure: Failed to discover UART service");
										btMode.status.failure = true;
									}
								};

								// The path from here is platform dependent
								if (window.device.platform == plab.platforms.iOS) {
									// iOS: Discover only the service we want to connect to
									bluetoothle.services (
											function (obj) {
												// TODO Make more robust
												// Assuming correct service was discovered
												if (obj.status == "services") {
													var params = {
															"address" : btMode.address,
															"serviceUuid" : btMode.serviceInfo.serviceUUID,
															"characteristicUuids" : [ btMode.serviceInfo.txUUID, btMode.serviceInfo.rxUUID ]
													};
													bluetoothle.characteristics (
															function (obj) {
																// TODO Make more robust
																// Assuming correct characteristic discovered
																if (obj.status == "characteristics") {
																	var params1 = {
																			"address" : btMode.address,
																			"serviceUuid" : btMode.serviceInfo.serviceUUID,
																			"characteristicUuid" : btMode.serviceInfo.txUUID
																	};
																	var params2 = {
																			"address" : btMode.address,
																			"serviceUuid" : btMode.serviceInfo.serviceUUID,
																			"characteristicUuid" : btMode.serviceInfo.rxUUID
																	};
																	// Bruteforcer gjennom listen
																	bluetoothle.descriptors (

																			function (obj) {
																				if (obj.status == "descriptors") {
																					bluetoothle.descriptors (

																							function (obj1) {
																								if (obj1.status == "descriptors") {
																									common(true);
																								} else {
																									debugOut.err.println("DescriptorsFailure: Unknown status: " + obj1.status);
																									btMode.disconnectDevice();
																								}
																							},

																							function (obj1) {
																								debugOut.err.println("DescriptorsFailure: " + obj1.error + " - " + obj1.message);
																								btMode.disconnectDevice ();
																							},
																							params2
																					);
																				} else {
																					debugOut.err.println("DescriptorsFailure: Unknown status: " + obj.status);
																					btMode.disconnectDevice ();
																				}
																			},

																			function (obj) {
																				debugOut.err.println("DescriptorsFailure: " + obj.error + " - " + obj.message);
																				btMode.disconnectDevice ();
																			},
																			params1
																	);
																} else {
																	debugOut.err.println("CharacteristicsFailure: Unknown status: " + obj.status);
																	btMode.disconnectDevice ();
																}
															},
															function (obj) {
																debugOut.err.println("CharacteristicsFailure: " + obj.error + " - " + obj.message);
																btMode.disconnectDevice ();
															},
															params
													);
												} else {
													debugOut.err.println("ServicesFailure: Unknown status: " + obj.status);
													btMode.disconnectDevice ();
												}
											},
											function (obj) {
												debugOut.err.println("ServicesFailure: " + obj.error + " - " + obj.message);
												btMode.disconnectDevice ();
											},
											{"address":id , "serviceUuids":[btMode.serviceInfo.serviceUUID]}
									);
								} else if (window.device.platform == plab.platforms.android) {
									// android: discover discovers all services and descriptors
									bluetoothle.discover (
											function (obj) {
												if (obj.status == "discovered") {
													// TODO check if service is available
													common(true);
												} else {
													debugOut.err.println("DiscoverFailure: Unknown status: " + obj.status);
													btMode.disconnectDevice ();
												}
											},
											function (obj) {
												debugOut.err.println("DiscoverFailure: " + obj.error + " - " + obj.message);
												btMode.disconnectDevice ();
											},
											{"address" : id}
									);
								} else {
									// Greit aa si ifra om at dette ikke vil fungere, vi stoetter bare iOS/android
									alert ("This platform is not supported");
								}

							} else if (obj.status != "connecting") {
								// Holder paa med tilkobling enda, ikke gjoer noe spesielt
								btMode.status.connected = false;
								btMode.status.ready = false;
								updateScreen();
							}
						},
						function(obj) {
							btMode.status.connected = false;
							btMode.status.ready = false;
							btMode.status.failure = true;
							debugOut.err.println("ConnectFailure: " + obj.error + " - " + obj.message);
							// Clear connect timeout
							if (btMode.timers.connecting !== null) {
								clearTimeout(btMode.timers.connecting);
								btMode.timers.connecting = null;
							}
							updateScreen ();
						},
						{"address":id}
				);
				plab.timers.connect = setTimeout(btMode.stopListDevices, 5000);
			};
			// ------------------ END CONNECT ------------------

			// ------------------ DICCONNECT ------------------
			btMode.disconnectDevice = function () {
				var closeDev = function() {
					btMode.status.connected = false;
					btMode.status.ready = false;
					bluetoothle.close(
							function (obj) {
								if (obj.status == "closed") {
									btMode.address = null;
								} else {
									debugOut.warn("CloseFailure: Unknown status: " + obj.status);
								}
							},
							function (obj) {
								debugOut.err.println("CloseFailure: " + obj.error + " - " + obj.message);
							},
							{"address":btMode.address}
					);
				};
				if (btMode.status.connected || btMode.address !== null) {
					bluetoothle.disconnect(
						function (obj) {
							if (obj.status == "disconnected") {
								closeDev();
							} else if (obj.status == "disconnecting") {
								// Allowed to stand if needed later
							} else {
								// Allowed to stand if needed later
							}
						},
						function (obj) {
							// Ensure the connection is closed
							debugOut.err.println("DisconnectFailure: " + obj.error + " - " + obj.message);
							closeDev();
						},
						{"address":btMode.address}
					);
				}
				btMode.status.ready = false;
			};
			// ------------------ END DICCONNECT ------------------

			// -------------- SEND / RECEIVE ------------
			btMode.send = function (text) {
					if (btMode.status.connected) {
						var params = {
								"address" : btMode.address,
								"value" : bluetoothle.bytesToEncodedString(bluetoothle.stringToBytes(text)),
								"serviceUuid" : btMode.serviceInfo.serviceUUID,
								"characteristicUuid" : btMode.serviceInfo.txUUID,
								"type" : "noResponse"
						};
						bluetoothle.write (
								function (obj) {},
								function (obj) {
									debugOut.err.println("WriteFailure: " + obj.error + " - " + obj.message);
								},
								params
						);
						/*
						bluetoothle.isConnected (
							function (conn) {
								if (conn.isConnected) {
									bluetoothle.write (
											function (obj) {},
											function (obj) {
												plab.notifyErrorString ("WriteFailure: " + obj.error + " - " + obj.message);
											},
											params
									);
								} else {
									plab.afterReconnect[plab.afterReconnect.length] = function() {
										plab.write(string);
									};
									plab.reconnect ();
								}
							}
						);
						*/

					} else {
						debugOut.warn.println("WriteFailure: Not connected");
					}
			};
			btMode.receiveCallback = function (callback) {
				btMode.subscriptions[btMode.subscriptions.length] = callback;
			};
			// -------------- END SEND / RECEIVE ------------

			// TODO
		}

		// -------------- INIT -------------------
		if (!btMode.status.initialized) {
			bluetoothle.initialize(

					function(obj) {
						if (obj.status == "enabled") {
							btMode.status.initialized = true;
							updateScreen();
						} else {
							debugOut.warn.println("InitializeFailure: Unknown status: " + obj.status);
						}
					},

					function(obj) {
						btMode.status.failure = true;
						debugOut.err.println("InitializeFailure: " + obj.error + " - " + obj.message);
						updateScreen();
					},

					{"request":false}
			);
		}
		// -------------- END INIT -------------------

	};
	plabBT.addMode(btMode);
}

document.addEventListener(
		"deviceready",
		function() {
			plabAddBT4_0(plab.out, plab.updateScreen);
		},
		false
);

} catch (e) {
	alert(e);
}<|endoftext|>


<commit_before>/**
 * Created by mzeyen on 3/5/16.
 */
var TargetDB = {
    targets: [
        {
            name: 'first',
            descr: 'Find the lala. It matters a little.',
            position: {
                longitude: 0,
                latitude: 0
            },
            points: 0
        }
    ],
    rewards: [
        {
            shopName: McDonalds,
            descr: '50% Off a Happy Meal',
            points: 10
        },
        {
            shopName: Engelhorn,
            descr: '5% Off',
            points: 100
        }
    ]
};

var Quest = {
    // assign a quest to the player
    acquire: function(duration, currentPosition) {
        // based on interests and available time select quest/target
        return target;
    },
    // track the position of the current quest
    follow: function(target, currentPosition) {
        // get direction to target based on current position
        // get current position
        // return normalized 2d direction vector
        return direction;
    },
    // finish quest if correct qr code is scanned
    finish: function(scanned) {
        // compare scanned to current target id
        // if they are the same reset current target and add to history
    }
};

var Game = {
    log: {
        currentTarget: 0,
        targetHistory: new Array(),
        currentPoints: 0,
        totalPoints: 0,
        currentRewards: new Array()
    },
    start: function() {
        // start game
    },
    gatherItems: function() {
        // gather shop items
    },
    buyItem: function(id) {
        // buy item with given id
    }
};<commit_msg>added follow function for quests and finish criteria.<commit_after>/**
 * Created by mzeyen on 3/5/16.
 */
var TargetDB = {
    targets: [
        {
            name: 'first',
            descr: 'Find the lala. It matters a little.',
            position: {
                longitude: 0,
                latitude: 0
            },
            points: 0
        }
    ],
    rewards: [
        {
            shopName: McDonalds,
            descr: '50% Off a Happy Meal',
            points: 10
        },
        {
            shopName: Engelhorn,
            descr: '5% Off',
            points: 100
        }
    ]
};

var Quest = {
    // assign a quest to the player
    acquire: function(duration, currentPosition) {
        // based on interests and available time select quest/target
        return target;
    },
    // track the position of the current quest and draw an arrow on map in radius l and with width u.
    follow: function(target, currentPosition, u, l) {
        var normalize = function(vec) {
            var len = Math.sqrt(vec.long * vec.long + vec.lati * vec.lati);
            return {
                long:vec.long / len,
                lati:vec.lati / len
            };
        };
        var direction = {
            long: target.long - currentPosition.long,
            lati: target.lati - currentPosition.lati
        };
        direction = normalize(direction);
        var normal = {
            long: direction.lati,
            lati: - direction.long
        };
        var p = {
            long: currentPosition.long + l * direction.long,
            lati: currentPosition.lati + l * direction.lati
        };
        var e_1 = {
            long: currentPosition.long - u * normal.long,
            lati: currentPosition.lati - u * normal.lati
        };
        var e_2 = {
            long: currentPosition.long + u * normal.long,
            lati: currentPosition.lati + u * normal.lati
        };
        drawArrow(p.lati, p.long, e_1.lati, e_1.long, e_2.lati, e_2.long);
    },
    // finish quest if correct qr code is scanned
    finish: function(scanned, currentTarget) {
        // compare scanned to current target id
        // if they are the same reset current target and add to history
        if(scanned == currentTarget) {
            return {success: True, points: TargetDB.targets[currentTarget].points};
        }
        return {success: False, points: 0};
    }
};

var Game = {
    log: {
        currentTarget: 0,
        targetHistory: new Array(),
        currentPoints: 0,
        totalPoints: 0,
        currentRewards: new Array()
    },
    start: function(duration) {
        // start game
    },
    gatherItems: function() {
        // gather shop items
    },
    buyItem: function(id) {
        // buy item with given id
    }
};<|endoftext|>


<commit_before>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

// Firebase go online whenever the application is open
document.addEventListener("deviceready", function () {
    Firebase.goOnline();
});

// Puskesmas form action
function puskesmas() {
	// Firebase
	var ref = new Firebase("https://cepatsembuh.firebaseio.com/");
	var puskesmas = ref.child("puskesmas");
	var pasien = puskesmas.child("pasien")

	// Input value
	var nama = $('#nama').val();
	var nik = $('#nik').val();
	var lokasi = $('#lokasi').val();
	var input = $('.input-puskesmas').val();

	if (input == '') {
		// Validate name input
		alert('Input is not filled');
	} else {
      // Log input value for testing
      console.log('Nama: ' + nama);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        nik: nik,
       lokasi: lokasi
     });

			// Get lokasi dropdown value
			switch (lokasi) {
				default:
					window.location.href = 'option/' + 'available.html';
					break;
		  }
	}
};

// RSUD form action
function rsud() {
	// Firebase
	var ref = new Firebase("https://cepatsembuh.firebaseio.com/");
	var rsud = ref.child("rsud");
	var pasien = rsud.child("pasien")

	// Input value
	var rujuk = $('#rujuk').val();
	var nik = $('#nik').val();
	var lokasi = $('#lokasi').val();
	var input = $('.input-rsud').val();

	if (input == '') {
		// Validate rujuk rsud input
		alert('Input is not filled');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });

			// Get lokasi dropdown value
			switch (lokasi) {
				default:
					window.location.href = 'option/' + 'available.html';
					break;
		 }
	}
};

// RSUK form action
function rsuk() {
	// Firebase
	var ref = new Firebase("https://cepatsembuh.firebaseio.com/");
	var rsuk = ref.child("rsuk");
	var pasien = rsuk.child("pasien");

	// Input value
	var rujuk = $('#rujuk').val();
	var nik = $('#nik').val();
	var lokasi = $('#lokasi').val();
	var input = $('.input-rsuk').val();

	if (input == '') {
		// Validate rujuk rsuk input
		alert('Input is not filled');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });
				// Get lokasi dropdown value
				switch (lokasi) {
					default:
						window.location.href = 'option/' + 'available.html';
						break;
			 }
	}
};

// RSS form action
function rss() {
	// Firebase
	var ref = new Firebase("https://cepatsembuh.firebaseio.com/");
	var rss = ref.child("rss");
	var pasien = rss.child("pasien");

	// Input value
	var rujuk = $('#rujuk').val();
	var nik = $('#nik').val();
	var lokasi = $('#lokasi').val();
	var input = $('.input-rss').val();

	if (input == '') {
		// Validate rujuk rss input
		alert('Input is not filled');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });
				// Get lokasi dropdown value
				switch (lokasi) {
					default:
						window.location.href = 'option/' + 'available.html';
						break;
			 }
	}
}
<commit_msg>Semicolon at the end of switch<commit_after>/*
* Cepat Sembuh v1.0
* Copyright 2016 Cepat Sembuh
*/

// Firebase go online whenever the application is open
document.addEventListener("deviceready", function () {
    Firebase.goOnline();
});

// Puskesmas form action
function puskesmas() {
	// Firebase
	var ref = new Firebase("https://cepatsembuh.firebaseio.com/");
	var puskesmas = ref.child("puskesmas");
	var pasien = puskesmas.child("pasien")

	// Input value
	var nama = $('#nama').val();
	var nik = $('#nik').val();
	var lokasi = $('#lokasi').val();
	var input = $('.input-puskesmas').val();

	if (input == '') {
		// Validate name input
		alert('Input is not filled');
	} else {
      // Log input value for testing
      console.log('Nama: ' + nama);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        nama: nama,
        nik: nik,
       lokasi: lokasi
     });

			// Get lokasi dropdown value
			switch (lokasi) {
				default:
					window.location.href = 'option/' + 'available.html';
					break;
		  };
	}
};

// RSUD form action
function rsud() {
	// Firebase
	var ref = new Firebase("https://cepatsembuh.firebaseio.com/");
	var rsud = ref.child("rsud");
	var pasien = rsud.child("pasien")

	// Input value
	var rujuk = $('#rujuk').val();
	var nik = $('#nik').val();
	var lokasi = $('#lokasi').val();
	var input = $('.input-rsud').val();

	if (input == '') {
		// Validate rujuk rsud input
		alert('Input is not filled');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });

			// Get lokasi dropdown value
			switch (lokasi) {
				default:
					window.location.href = 'option/' + 'available.html';
					break;
		 };
	}
};

// RSUK form action
function rsuk() {
	// Firebase
	var ref = new Firebase("https://cepatsembuh.firebaseio.com/");
	var rsuk = ref.child("rsuk");
	var pasien = rsuk.child("pasien");

	// Input value
	var rujuk = $('#rujuk').val();
	var nik = $('#nik').val();
	var lokasi = $('#lokasi').val();
	var input = $('.input-rsuk').val();

	if (input == '') {
		// Validate rujuk rsuk input
		alert('Input is not filled');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });
				// Get lokasi dropdown value
				switch (lokasi) {
					default:
						window.location.href = 'option/' + 'available.html';
						break;
			 };
	}
};

// RSS form action
function rss() {
	// Firebase
	var ref = new Firebase("https://cepatsembuh.firebaseio.com/");
	var rss = ref.child("rss");
	var pasien = rss.child("pasien");

	// Input value
	var rujuk = $('#rujuk').val();
	var nik = $('#nik').val();
	var lokasi = $('#lokasi').val();
	var input = $('.input-rss').val();

	if (input == '') {
		// Validate rujuk rss input
		alert('Input is not filled');
	} else {
      // Log input value for testing
      console.log('No Rujuk: ' + rujuk);
      console.log('NIK: ' + nik);
      console.log('Lokasi: ' + lokasi);

      // Push input value to firebase
      pasien.push().set({
        no_rujuk: rujuk,
        nik: nik,
        lokasi: lokasi
      });
				// Get lokasi dropdown value
				switch (lokasi) {
					default:
						window.location.href = 'option/' + 'available.html';
						break;
			 };
	}
}
<|endoftext|>