<commit_before>// @flow
import React from 'react'
import {ScrollView, Text, StyleSheet} from 'react-native'
import moment from 'moment'
import {HtmlView} from '../components/html-view'
import {Cell} from 'react-native-tableview-simple'
import {Card} from '../components/card'
import * as c from '../components/colors'
import type {StudentOrgType} from './types'
import type {TopLevelViewPropsType} from '../types'
import Communications from 'react-native-communications'
import openUrl from '../components/open-url'
import cleanOrg from './clean-org'

const styles = StyleSheet.create({
  name: {
    textAlign: 'center',
    marginTop: 20,
    marginBottom: 15,
    paddingHorizontal: 5,
    color: c.black,
    fontSize: 32,
    fontWeight: '300',
  },
  card: {
    marginBottom: 20,
  },
  cardBody: {
    color: c.black,
    paddingTop: 13,
    paddingBottom: 13,
    paddingLeft: 16,
    paddingRight: 16,
    fontSize: 16,
  },
  description: {
    paddingTop: 13,
    paddingBottom: 13,
    paddingLeft: 16,
    paddingRight: 16,
    backgroundColor: c.white,
    height: 200,
  },
  footer: {
    fontSize: 10,
    color: c.iosDisabledText,
    textAlign: 'center',
  },
  lastUpdated: {
    paddingBottom: 10,
  },
  poweredBy: {
    paddingBottom: 20,
  },
})

export class StudentOrgsDetailView extends React.Component {
  props: TopLevelViewPropsType & {
    org: StudentOrgType,
  }

  // Using Communications because `mailTo` complains about
  // the lack of an available Activity...
  openEmail = (email: string, org: string) => {
    Communications.email([email], null, null, org, '')
  }

  render() {
    const {
      name: orgName,
      category,
      meetings,
      website,
      contacts,
      advisors,
      description,
      lastUpdated: orgLastUpdated,
    } = cleanOrg(this.props.org)

    return (
      <ScrollView>
        <Text style={styles.name}>{orgName}</Text>

        {category
          ? <Card header="Category" style={styles.card}>
              <Text style={styles.cardBody}>{category}</Text>
            </Card>
          : null}

        {meetings
          ? <Card header="Meetings" style={styles.card}>
              <Cell cellStyle="Basic" title={meetings} />
            </Card>
          : null}

        {website
          ? <Card header="Website" style={styles.card}>
              <Text onPress={() => openUrl(website)} style={styles.cardBody}>
                {website}
              </Text>
            </Card>
          : null}

        {contacts.length
          ? <Card header="Contact" style={styles.card}>
              {contacts.map((c, i) => (
                <Text
                  key={i}
                  selectable={true}
                  style={styles.cardBody}
                  onPress={() => this.openEmail(c.email, orgName)}
                >
                  {c.title ? c.title + ': ' : ''}
                  {c.firstName} {c.lastName} ({c.email})
                </Text>
              ))}
            </Card>
          : null}

        {advisors.length
          ? <Card
              header={advisors.length === 1 ? 'Advisor' : 'Advisors'}
              style={styles.card}
            >
              {advisors.map((c, i) => (
                <Text
                  key={i}
                  selectable={true}
                  style={styles.cardBody}
                  onPress={() => this.openEmail(c.email, orgName)}
                >
                  {c.name} ({c.email})
                </Text>
              ))}
            </Card>
          : null}

        {description
          ? <Card header="Description" style={styles.card}>
              <HtmlView
                style={styles.description}
                html={`
                  <style>
                    body {
                      margin: 10px 15px 10px;
                      font-family: -apple-system;
                    }
                    * {
                      max-width: 100%;
                    }
                  </style>
                  ${description}
                `}
              />
            </Card>
          : null}

        <Text selectable={true} style={[styles.footer, styles.lastUpdated]}>
          Last updated:
          {' '}
          {moment(orgLastUpdated, 'MMMM, DD YYYY HH:mm:ss').calendar()}
        </Text>

        <Text selectable={true} style={[styles.footer, styles.poweredBy]}>
          Powered by the St. Olaf Student Orgs Database
        </Text>
      </ScrollView>
    )
  }
}
<commit_msg>expand meeting times on android<commit_after>// @flow
import React from 'react'
import {ScrollView, Text, StyleSheet} from 'react-native'
import moment from 'moment'
import {HtmlView} from '../components/html-view'
import {Card} from '../components/card'
import * as c from '../components/colors'
import type {StudentOrgType} from './types'
import type {TopLevelViewPropsType} from '../types'
import Communications from 'react-native-communications'
import openUrl from '../components/open-url'
import cleanOrg from './clean-org'

const styles = StyleSheet.create({
  name: {
    textAlign: 'center',
    marginTop: 20,
    marginBottom: 15,
    paddingHorizontal: 5,
    color: c.black,
    fontSize: 32,
    fontWeight: '300',
  },
  card: {
    marginBottom: 20,
  },
  cardBody: {
    color: c.black,
    paddingTop: 13,
    paddingBottom: 13,
    paddingLeft: 16,
    paddingRight: 16,
    fontSize: 16,
  },
  description: {
    paddingTop: 13,
    paddingBottom: 13,
    paddingLeft: 16,
    paddingRight: 16,
    backgroundColor: c.white,
    height: 200,
  },
  footer: {
    fontSize: 10,
    color: c.iosDisabledText,
    textAlign: 'center',
  },
  lastUpdated: {
    paddingBottom: 10,
  },
  poweredBy: {
    paddingBottom: 20,
  },
})

export class StudentOrgsDetailView extends React.Component {
  props: TopLevelViewPropsType & {
    org: StudentOrgType,
  }

  // Using Communications because `mailTo` complains about
  // the lack of an available Activity...
  openEmail = (email: string, org: string) => {
    Communications.email([email], null, null, org, '')
  }

  render() {
    const {
      name: orgName,
      category,
      meetings,
      website,
      contacts,
      advisors,
      description,
      lastUpdated: orgLastUpdated,
    } = cleanOrg(this.props.org)

    return (
      <ScrollView>
        <Text style={styles.name}>{orgName}</Text>

        {category
          ? <Card header="Category" style={styles.card}>
              <Text style={styles.cardBody}>{category}</Text>
            </Card>
          : null}

        {meetings
          ? <Card header="Meetings" style={styles.card}>
              <Text style={styles.cardBody}>{meetings}</Text>
            </Card>
          : null}

        {website
          ? <Card header="Website" style={styles.card}>
              <Text onPress={() => openUrl(website)} style={styles.cardBody}>
                {website}
              </Text>
            </Card>
          : null}

        {contacts.length
          ? <Card header="Contact" style={styles.card}>
              {contacts.map((c, i) => (
                <Text
                  key={i}
                  selectable={true}
                  style={styles.cardBody}
                  onPress={() => this.openEmail(c.email, orgName)}
                >
                  {c.title ? c.title + ': ' : ''}
                  {c.firstName} {c.lastName} ({c.email})
                </Text>
              ))}
            </Card>
          : null}

        {advisors.length
          ? <Card
              header={advisors.length === 1 ? 'Advisor' : 'Advisors'}
              style={styles.card}
            >
              {advisors.map((c, i) => (
                <Text
                  key={i}
                  selectable={true}
                  style={styles.cardBody}
                  onPress={() => this.openEmail(c.email, orgName)}
                >
                  {c.name} ({c.email})
                </Text>
              ))}
            </Card>
          : null}

        {description
          ? <Card header="Description" style={styles.card}>
              <HtmlView
                style={styles.description}
                html={`
                  <style>
                    body {
                      margin: 10px 15px 10px;
                      font-family: -apple-system;
                    }
                    * {
                      max-width: 100%;
                    }
                  </style>
                  ${description}
                `}
              />
            </Card>
          : null}

        <Text selectable={true} style={[styles.footer, styles.lastUpdated]}>
          Last updated:
          {' '}
          {moment(orgLastUpdated, 'MMMM, DD YYYY HH:mm:ss').calendar()}
        </Text>

        <Text selectable={true} style={[styles.footer, styles.poweredBy]}>
          Powered by the St. Olaf Student Orgs Database
        </Text>
      </ScrollView>
    )
  }
}
<|endoftext|>


<commit_before>// +----------------------------------------------------------------------+
// | Bitflux Editor                                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | This software is published under the terms of the Apache Software    |
// | License a copy of which has been included with this distribution in  |
// | the LICENSE file and is available through the web at                 |
// | http://bitflux.ch/editor/license.html                                |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                        |
// +----------------------------------------------------------------------+
//
// $Id: bxeLoader.js,v 1.235 2004/02/17 13:42:44 chregu Exp $

const BXE_VERSION = "0.9.1";
const BXE_BUILD = "200402171442"

const E_FATAL = 1;

if (window.location.protocol == "file:" || window.location.host.match(/localhost.*/)) {
	var DebugOutput = false;
} else {
	var DebugOutput = false;
}

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;
var bxe_editable_page = true;

var startTimer = new Date();

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	defaultContainerName = "p";

	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG " + bxe_config.validationfile + " ");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	bxe_history_snapshot();
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("appendChildNode",bxe_appendChildNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("DeleteLink",bxe_DeleteLink,false);
	document.eDOMaddEventListener("CleanInline",bxe_CleanInline,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertObject,false);
	document.eDOMaddEventListener("InsertAsset",bxe_InsertAsset,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_history_undo()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_history_redo()}, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (!vali) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
		bxe_disableEditablePage();
	}
	else {
		bxe_about_box.addText("<br/>Document is valid.");

	}
	var endTimer = new Date();
	debug ("startTime: " + startTimer);
	debug ("endTime  : " + endTimer);
	dump ("Total Start Time: " + (endTimer - startTimer)/1000 + " sec\n");
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}

function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<commit_msg>automatic BuildDate Update<commit_after>// +----------------------------------------------------------------------+
// | Bitflux Editor                                                       |
// +----------------------------------------------------------------------+
// | Copyright (c) 2003 Bitflux GmbH                                      |
// +----------------------------------------------------------------------+
// | This software is published under the terms of the Apache Software    |
// | License a copy of which has been included with this distribution in  |
// | the LICENSE file and is available through the web at                 |
// | http://bitflux.ch/editor/license.html                                |
// +----------------------------------------------------------------------+
// | Author: Christian Stocker <chregu@bitflux.ch>                        |
// +----------------------------------------------------------------------+
//
// $Id: bxeLoader.js,v 1.236 2004/02/17 13:43:11 chregu Exp $

const BXE_VERSION = "0.9.1";
const BXE_BUILD = "200402171443"

const E_FATAL = 1;

if (window.location.protocol == "file:" || window.location.host.match(/localhost.*/)) {
	var DebugOutput = false;
} else {
	var DebugOutput = false;
}

mozile_js_files = new Array();

mozile_js_files.push("mozile/mozWrappers.js");
mozile_js_files.push("js/widget.js");

mozile_js_files.push("mozile/eDOM.js");
mozile_js_files.push("js/bxeConfig.js");
mozile_js_files.push("mozile/eDOMXHTML.js");
mozile_js_files.push("js/bxeXMLNode.js");
mozile_js_files.push("js/bxeNodeElements.js");
mozile_js_files.push("js/bxeXMLDocument.js");
mozile_js_files.push("mozile/mozileTransportDriver.js");
mozile_js_files.push("mozile/td/http.js");
mozile_js_files.push("mozile/domlevel3.js");
mozile_js_files.push("mozile/mozCE.js");
mozile_js_files.push("mozile/mozIECE.js");
//mozile_js_files.push("mozile/mozileModify.js");
mozile_js_files.push("js/eDOMEvents.js");
mozile_js_files.push("js/bxeFunctions.js");

var mozile_root_dir = "./";

// some global vars, no need to change them
var mozile_corescript_loaded = 0;
var mozile_script_loaded = 0;
var bxe_config = new Object();
var bxe_about_box = null;
var bxe_format_list = null;
var bxe_context_menu = null;
var bxe_delayedUpdate = false;
var eDOM_bxe_mode = true;
var bxe_editable_page = true;

var startTimer = new Date();

function bxe_start(config_file,fromUrl, configArray) {

	/*if (! (BX_checkUnsupportedBrowsers())) {
		return false;
	}*/

	if((navigator.product == 'Gecko') && (navigator.userAgent.indexOf("Safari") == -1))
	{
		// navigator.productSub > '20020801' (test to see what the date should be)

		// POST04: if document.documentElement != HTML then ... or no "head" ...
		var head = document.getElementsByTagName("head")[0];
		bxe_config.file = config_file;
		bxe_config.fromUrl = fromUrl;
		bxe_config.configArray = configArray;
		if(head)
		{
			// get the location of this script and reuse it for the others
			for(var i=0; i<head.childNodes.length; i++)
			{
				var mozileLoaderRE = /(.*)bxeLoader.js$/;
				if(head.childNodes[i].localName == "SCRIPT")
				{
					var src = head.childNodes[i].src;
					var result = mozileLoaderRE.exec(src);
					if(result)
					{
						mozile_root_dir = result[1];
						break;
					}
				}
			}
			for (var i=0; i < mozile_js_files.length; i++)
			{
				var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
				var src = mozile_root_dir + mozile_js_files[i];
				if (mozile_js_files[i] == "js/widget.js") {
					scr.onload = widget_loaded;
				} else {
					scr.onload = corescript_loaded;
				}
				scr.setAttribute("src", src);

				scr.setAttribute("language","JavaScript");
				head.appendChild(scr);
			}
			//when last include src is loaded, call onload handler

		}
		else {
			alert("*** ALERT: MozileLoader only works in XHTML - load Mozile JS explicitly in XML files");
		}
	}

}

// Detect Gecko but exclude Safari (for now); for now, only support XHTML

function bxe_load_xml (xmlfile) {

	var td = new mozileTransportDriver("webdav");
	function callback (e) {
		if (e.isError) {
			alert("Error loading xml file \n"+e.statusText);
			return false;
		}
		var xmldoc =  e.document;
		bxe_config.xmldoc = xmldoc;
		xmldoc.init();
		if (bxe_config.xhtmlfile) {
			xmldoc.importXHTMLDocument(bxe_config.xhtmlfile)
		} else if (bxe_config.xslfile) {
			xmldoc.transformToXPathMode(bxe_config.xslfile)
		} else {
			xmldoc.insertIntoHTMLDocument();
			xml_loaded(xmldoc);
		}

	}
	td.load(xmlfile,callback);

	return true;
}

function widget_loaded(e) {
	bxe_about_box = new Widget_AboutBox();
	bxe_about_box.draw();
	bxe_about_box.setText("Loading files ...");
	corescript_loaded(e);

}

function corescript_loaded(e) {
	mozile_corescript_loaded++;
	debug("from core script " + mozile_corescript_loaded + " of " + mozile_js_files.length  + "loaded: " + e.currentTarget.src);
	if ( mozile_js_files.length == mozile_corescript_loaded) {
		debug("call mozile_core_loaded()");
		mozile_core_loaded();
	} else {
		if (bxe_about_box) {
			bxe_about_box.addText(mozile_corescript_loaded );
		}
	}
}

function script_loaded(e) {
	mozile_script_loaded++;
	debug("from config script " + mozile_script_loaded + " loaded: " + e.currentTarget.src );
	if ( bxe_config.scriptfiles.length == mozile_script_loaded ) {
		debug("call mozile_loaded()");
		mozile_loaded();
	} else {
		bxe_about_box.addText(mozile_script_loaded );
	}
}

function mozile_core_loaded() {
	bxe_about_box.addText("Scripts loaded ...");
	bxe_about_box.addText("Load Config ");
	try {
		bxe_config = new bxeConfig(bxe_config.file, bxe_config.fromUrl, bxe_config.configArray);
	} catch (e) {
		bxe_catch_alert(e);
	}
}

function mozile_loaded() {
	defaultContainerName = "p";

	bxe_about_box.addText("Load XML ...");
	bxe_load_xml(bxe_config.xmlfile);

}

function xml_loaded(xmldoc) {
	bxe_about_box.addText("Load RelaxNG " + bxe_config.validationfile + " ");
	if (!(bxe_config.validationfile && xmldoc.XMLNode.loadSchema(bxe_config.validationfile,validation_loaded))) {
		bxe_about_box.addText("RelaxNG File was not found");
	}
	bxe_history_snapshot();
	document.eDOMaddEventListener("toggleSourceMode",bxe_toggleSourceMode,false);
	document.eDOMaddEventListener("toggleTagMode",bxe_toggleTagMode,false);
	document.eDOMaddEventListener("toggleNormalMode",bxe_toggleNormalMode,false);
	document.eDOMaddEventListener("DocumentSave",__bxeSave,false);
	document.eDOMaddEventListener("ToggleTextClass",bxe_toggleTextClass,false);
	document.eDOMaddEventListener("appendNode",bxe_appendNode,false);
	document.eDOMaddEventListener("appendChildNode",bxe_appendChildNode,false);
	document.eDOMaddEventListener("InsertLink",bxe_InsertLink,false);
	document.eDOMaddEventListener("DeleteLink",bxe_DeleteLink,false);
	document.eDOMaddEventListener("CleanInline",bxe_CleanInline,false);
	document.eDOMaddEventListener("InsertTable",bxe_InsertTable,false);
	document.eDOMaddEventListener("InsertImage",bxe_InsertObject,false);
	document.eDOMaddEventListener("InsertAsset",bxe_InsertAsset,false);
	document.eDOMaddEventListener("OrderedList",bxe_OrderedList,false);
	document.eDOMaddEventListener("UnorderedList",bxe_UnorderedList,false);

	document.eDOMaddEventListener("changeLinesContainer",bxe_changeLinesContainer,false);
	document.eDOMaddEventListener("Exit",bxe_exit,false);

	document.eDOMaddEventListener("ClipboardCopy",function(e) { window.getSelection().copy()},false);
	document.eDOMaddEventListener("ClipboardPaste",function(e) { window.getSelection().paste()},false);
	document.eDOMaddEventListener("ClipboardCut",function(e) { window.getSelection().cut()},false);

	document.eDOMaddEventListener("Undo",function(e) { bxe_history_undo()}, false);
	document.eDOMaddEventListener("Redo",function(e) { bxe_history_redo()}, false);

	//document.eDOMaddEventListener("NodeInsertedParent",bxe_NodeInsertedParent, false);
	document.eDOMaddEventListener("NodeInsertedBefore",bxe_NodeInsertedBefore,false);
	document.eDOMaddEventListener("NodeBeforeDelete",bxe_NodeBeforeDelete,false);
	/*document.eDOMaddEventListener("NodeChanged",bxe_NodeChanged,false);

	document.eDOMaddEventListener("NodeRemovedChildOnly",bxe_NodeRemovedChildOnly,false);
	*/
	//document.eDOMaddEventListener("NodeAppendedChild",bxe_NodeAppendedChild,false);
	document.eDOMaddEventListener("NodePositionChanged",bxe_NodePositionChanged,false);

	document.eDOMaddEventListener("ContextPopup",bxe_ContextPopup,false);
	document.addEventListener("contextmenu",bxe_ContextMenuEvent, false);

	bxe_context_menu = new Widget_ContextMenu();
}

function validation_loaded(vdom) {
	bxe_about_box.addText("Validation Loaded ...");

	var vali = bxe_config.xmldoc.XMLNode.validateDocument();
	if (!vali) {
		bxe_about_box.addText("Document is *not* valid.");
		//alert(vali.getErrorMessagesAsText());
		bxe_disableEditablePage();
	}
	else {
		bxe_about_box.addText("<br/>Document is valid.");

	}
	var endTimer = new Date();
	debug ("startTime: " + startTimer);
	debug ("endTime  : " + endTimer);
	dump ("Total Start Time: " + (endTimer - startTimer)/1000 + " sec\n");
}

function config_loaded(bxe_config_in) {
	bxe_about_box.addText("& Parsed ...");

	bxe_config = bxe_config_in;
	var head = document.getElementsByTagName("head")[0];
	for (var i=0; i < bxe_config.cssfiles.length; i++)
	{
		var scr = document.createElementNS(XHTMLNS,"link");
		scr.setAttribute("type","text/css");
		scr.setAttribute("rel","stylesheet");
		scr.setAttribute("href",bxe_config.cssfiles[i]);
		head.appendChild(scr);
	}

	for (var i=0; i < bxe_config.scriptfiles.length; i++)
	{
		var scr = document.createElementNS("http://www.w3.org/1999/xhtml","script");
		var src = mozile_root_dir + bxe_config.scriptfiles[i];
		scr.onload = script_loaded;
		scr.setAttribute("src", src);
		scr.setAttribute("language","JavaScript");
		head.appendChild(scr);
	}

}

debug = function (text, options) {

	if (DebugOutput) {

		fn =  bxe_getCaller(debug);

		dump( fn.getName() +  ": " + text + "\n");
		if (options) {

			if (options.evalArguments) {
				var fname= fn.getName();
					dump("  Arguments: (");
					for (var i = 0; i < fn.arguments.length; i++) {
						dump("[" + typeof fn.arguments[i] + "] ");
						switch( typeof( fn.arguments[i] )) {
							case "function":
								dump (fn.arguments[i].getName());
								break;
							case "string":
								dump('"' + fn.arguments[i] + '"');
								break;
							default:
								dump(fn.arguments[i]);
						}
						if (i < fn.arguments.length - 1 ) {
							dump(", ");
						}
					}
					dump (")\n");

			}

			if (options.callstack) {
				var callstack =  new Array();
				dump ("  Callstack: \n");
				dump ("  ----------\n");
				while (fn) {

					callstack.unshift(fn.getName() + "\n");
					var newfn = JsUtil_getCaller(fn);
					if (fn == newfn) {
						callstack.unshift ("  [javascript recursion]\n");
						break;
					}
					fn = newfn;
				}
				for (var i = 0; i < callstack.length; i++) {
					dump("  " +i +": " +callstack[i]);
				}
				dump ("  ----------\n");

			}

		}

	}
}

Function.prototype.getName = function () {
	var r = /function (\w*)([^\{\}]*\))/
	var s = new String( this);
	var m = s.match( r );
	if (m) {
		var f = "";
		if (m[1]) {
			f = m[1];
		} else {
			r = /var id = "(.+)"/;
			var n = s.match(r);
			if (n && n[1]) {
				f = n[1];
			} else {
				f = "anoynmous function";
			}
		}
		var args = m[2];
		return (f+args);
	} else {
		return "anonymous function";
	}
}

function bxe_getCaller( fn )
{
	switch( typeof( fn ))
	{
		case "undefined":
			return bxe_getCaller( bxe_getCaller );

		case "function":
			if( fn.caller )
				return fn.caller;
			if( fn.arguments && fn.arguments.caller )
				return fn.arguments.caller;
	}
	return undefined;
}

<|endoftext|>


<commit_before>Brick.util.Language.add('ru',{'mod':{'money': {
	'title': 'Задачи',
	'roles':{
		'10': 'Чтение',
		'30': 'Запись',
		'50': 'Администрирование'
	}
}}});
<commit_msg>Финансы: мелкие правки<commit_after>Brick.util.Language.add('ru',{'mod':{'money': {
	'title': 'Финансы',
	'roles':{
		'10': 'Чтение',
		'30': 'Запись',
		'50': 'Администрирование'
	}
}}});
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2002-2019 "Neo4j,"
 * Neo4j Sweden AB [http://neo4j.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import neo4j from '../../../src/v1';
import {READ, WRITE} from '../../../src/v1/driver';
import boltStub from '../bolt-stub';
import { SERVICE_UNAVAILABLE } from '../../../src/v1/error';

describe('direct driver with stub server', () => {

  let originalTimeout;

  beforeAll(() => {
    originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
  });

  afterAll(() => {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
  });

  it('should run query', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    // Given
    const server = boltStub.start('./test/resources/boltstub/return_x.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      // When
      const session = driver.session();
      // Then
      session.run('RETURN {x}', {'x': 1}).then(res => {
        expect(res.records[0].get('x').toInt()).toEqual(1);
        session.close();
        driver.close();
        server.exit(code => {
          expect(code).toEqual(0);
          done();
        });
      });
    });
  });

  it('should send and receive bookmark for read transaction', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/read_tx_with_bookmarks.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(READ, 'neo4j:bookmark:v1:tx42');
      const tx = session.beginTransaction();
      tx.run('MATCH (n) RETURN n.name AS name').then(result => {
        const records = result.records;
        expect(records.length).toEqual(2);
        expect(records[0].get('name')).toEqual('Bob');
        expect(records[1].get('name')).toEqual('Alice');

        tx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          session.close(() => {
            driver.close();
            server.exit(code => {
              expect(code).toEqual(0);
              done();
            });
          });
        });
      });
    });
  });

  it('should send and receive bookmark for write transaction', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/write_tx_with_bookmarks.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(WRITE, 'neo4j:bookmark:v1:tx42');
      const tx = session.beginTransaction();
      tx.run('CREATE (n {name:\'Bob\'})').then(result => {
        const records = result.records;
        expect(records.length).toEqual(0);

        tx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          session.close(() => {
            driver.close();
            server.exit(code => {
              expect(code).toEqual(0);
              done();
            });
          });
        });
      });
    });
  });

  it('should send and receive bookmark between write and read transactions', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/write_read_tx_with_bookmarks.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(WRITE, 'neo4j:bookmark:v1:tx42');
      const writeTx = session.beginTransaction();
      writeTx.run('CREATE (n {name:\'Bob\'})').then(result => {
        const records = result.records;
        expect(records.length).toEqual(0);

        writeTx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          const readTx = session.beginTransaction();
          readTx.run('MATCH (n) RETURN n.name AS name').then(result => {
            const records = result.records;
            expect(records.length).toEqual(1);
            expect(records[0].get('name')).toEqual('Bob');

            readTx.commit().then(() => {
              expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx424242');

              session.close(() => {
                driver.close();
                server.exit(code => {
                  expect(code).toEqual(0);
                  done();
                });
              });
            });
          });
        });
      });
    });
  });

  it('should be possible to override bookmark', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/write_read_tx_with_bookmark_override.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(WRITE, 'neo4j:bookmark:v1:tx42');
      const writeTx = session.beginTransaction();
      writeTx.run('CREATE (n {name:\'Bob\'})').then(result => {
        const records = result.records;
        expect(records.length).toEqual(0);

        writeTx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          const readTx = session.beginTransaction('neo4j:bookmark:v1:tx99');
          readTx.run('MATCH (n) RETURN n.name AS name').then(result => {
            const records = result.records;
            expect(records.length).toEqual(1);
            expect(records[0].get('name')).toEqual('Bob');

            readTx.commit().then(() => {
              expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx424242');

              session.close(() => {
                driver.close();
                server.exit(code => {
                  expect(code).toEqual(0);
                  done();
                });
              });
            });
          });
        });
      });
    });

  });

  it('should not be possible to override bookmark with null', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/write_read_tx_with_bookmarks.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(WRITE, 'neo4j:bookmark:v1:tx42');
      const writeTx = session.beginTransaction();
      writeTx.run('CREATE (n {name:\'Bob\'})').then(result => {
        const records = result.records;
        expect(records.length).toEqual(0);

        writeTx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          const readTx = session.beginTransaction(null);
          readTx.run('MATCH (n) RETURN n.name AS name').then(result => {
            const records = result.records;
            expect(records.length).toEqual(1);
            expect(records[0].get('name')).toEqual('Bob');

            readTx.commit().then(() => {
              expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx424242');

              session.close(() => {
                driver.close();
                server.exit(code => {
                  expect(code).toEqual(0);
                  done();
                });
              });
            });
          });
        });
      });
    });
  });

  it('should throw service unavailable when server dies', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/dead_read_server.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session();
      session.run('MATCH (n) RETURN n.name').catch(error => {
        expect(error.code).toEqual(neo4j.error.SERVICE_UNAVAILABLE);

        driver.close();
        server.exit(code => {
          expect(code).toEqual(0);
          done();
        });
      });
    });
  });

  it('should close connection when RESET fails', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/reset_error.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session();

      session.run('RETURN 42 AS answer').then(result => {
        const records = result.records;
        expect(records.length).toEqual(1);
        expect(records[0].get(0).toNumber()).toEqual(42);
        session.close(() => {

          expect(driver._pool._pools['127.0.0.1:9001'].length).toEqual(0);
          driver.close();
          server.exit(code => {
            expect(code).toEqual(0);
            done();
          });

        });
      }).catch(error => done.fail(error));
    });
  });

  it('should send RESET on error', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/query_with_error.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session();

      session.run('RETURN 10 / 0').then(result => {
        done.fail('Should fail but received a result: ' + JSON.stringify(result));
      }).catch(error => {
        expect(error.code).toEqual('Neo.ClientError.Statement.ArithmeticError');
        expect(error.message).toEqual('/ by zero');

        session.close(() => {
          driver.close();
          server.exit(code => {
            expect(code).toEqual(0);
            done();
          });
        });
      });
    });
  });

  it('should include database connection id in logs', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/hello_run_exit.script', 9001);

    boltStub.run(() => {
      const messages = [];
      const logging = {
        level: 'debug',
        logger: (level, message) => messages.push(message)
      };

      const driver = boltStub.newDriver('bolt://127.0.0.1:9001', {logging: logging});
      const session = driver.session();

      session.run('MATCH (n) RETURN n.name').then(result => {
        const names = result.records.map(record => record.get(0));
        expect(names).toEqual(['Foo', 'Bar']);
        session.close(() => {
          driver.close();
          server.exit(code => {
            expect(code).toEqual(0);

            // logged messages should contain connection_id supplied by the database
            const containsDbConnectionIdMessage = messages.find(message => message.match(/Connection \[[0-9]+]\[bolt-123456789]/));
            if (!containsDbConnectionIdMessage) {
              console.log(messages);
            }
            expect(containsDbConnectionIdMessage).toBeTruthy();

            done();
          });
        });
      }).catch(error => done.fail(error));
    });
  });

  describe('should fail if commit fails due to broken connection', () => {
    it('v1', done => {
      verifyFailureOnConnectionFailureWhenExplicitTransactionIsCommitted('v1', done);
    });

    it('v3', done => {
      verifyFailureOnConnectionFailureWhenExplicitTransactionIsCommitted('v3', done);
    });
  });

  function verifyFailureOnConnectionFailureWhenExplicitTransactionIsCommitted(version, done) {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start(`./test/resources/boltstub/connection_error_on_commit_${version}.script`, 9001);

    boltStub.run(() => {
        const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
        const session = driver.session();

        const writeTx = session.beginTransaction();

        writeTx.run('CREATE (n {name: \'Bob\'})').then(() =>
          writeTx.commit().then(result => fail('expected an error'), (error) => {
            expect(error.code).toBe(SERVICE_UNAVAILABLE);
            expect(error.message).toContain('Connection was closed by server');
          })
        ).finally(() =>
          session.close(() => {
            driver.close();

            server.exit(code => {
              expect(code).toEqual(0);
              done();
            });
          })).catch(error => done.fail(error));
      }
    );
  }
});
<commit_msg>Remove error message assertion<commit_after>/**
 * Copyright (c) 2002-2019 "Neo4j,"
 * Neo4j Sweden AB [http://neo4j.com]
 *
 * This file is part of Neo4j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import neo4j from '../../../src/v1';
import {READ, WRITE} from '../../../src/v1/driver';
import boltStub from '../bolt-stub';
import { SERVICE_UNAVAILABLE } from '../../../src/v1/error';

describe('direct driver with stub server', () => {

  let originalTimeout;

  beforeAll(() => {
    originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 60000;
  });

  afterAll(() => {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
  });

  it('should run query', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    // Given
    const server = boltStub.start('./test/resources/boltstub/return_x.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      // When
      const session = driver.session();
      // Then
      session.run('RETURN {x}', {'x': 1}).then(res => {
        expect(res.records[0].get('x').toInt()).toEqual(1);
        session.close();
        driver.close();
        server.exit(code => {
          expect(code).toEqual(0);
          done();
        });
      });
    });
  });

  it('should send and receive bookmark for read transaction', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/read_tx_with_bookmarks.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(READ, 'neo4j:bookmark:v1:tx42');
      const tx = session.beginTransaction();
      tx.run('MATCH (n) RETURN n.name AS name').then(result => {
        const records = result.records;
        expect(records.length).toEqual(2);
        expect(records[0].get('name')).toEqual('Bob');
        expect(records[1].get('name')).toEqual('Alice');

        tx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          session.close(() => {
            driver.close();
            server.exit(code => {
              expect(code).toEqual(0);
              done();
            });
          });
        });
      });
    });
  });

  it('should send and receive bookmark for write transaction', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/write_tx_with_bookmarks.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(WRITE, 'neo4j:bookmark:v1:tx42');
      const tx = session.beginTransaction();
      tx.run('CREATE (n {name:\'Bob\'})').then(result => {
        const records = result.records;
        expect(records.length).toEqual(0);

        tx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          session.close(() => {
            driver.close();
            server.exit(code => {
              expect(code).toEqual(0);
              done();
            });
          });
        });
      });
    });
  });

  it('should send and receive bookmark between write and read transactions', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/write_read_tx_with_bookmarks.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(WRITE, 'neo4j:bookmark:v1:tx42');
      const writeTx = session.beginTransaction();
      writeTx.run('CREATE (n {name:\'Bob\'})').then(result => {
        const records = result.records;
        expect(records.length).toEqual(0);

        writeTx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          const readTx = session.beginTransaction();
          readTx.run('MATCH (n) RETURN n.name AS name').then(result => {
            const records = result.records;
            expect(records.length).toEqual(1);
            expect(records[0].get('name')).toEqual('Bob');

            readTx.commit().then(() => {
              expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx424242');

              session.close(() => {
                driver.close();
                server.exit(code => {
                  expect(code).toEqual(0);
                  done();
                });
              });
            });
          });
        });
      });
    });
  });

  it('should be possible to override bookmark', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/write_read_tx_with_bookmark_override.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(WRITE, 'neo4j:bookmark:v1:tx42');
      const writeTx = session.beginTransaction();
      writeTx.run('CREATE (n {name:\'Bob\'})').then(result => {
        const records = result.records;
        expect(records.length).toEqual(0);

        writeTx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          const readTx = session.beginTransaction('neo4j:bookmark:v1:tx99');
          readTx.run('MATCH (n) RETURN n.name AS name').then(result => {
            const records = result.records;
            expect(records.length).toEqual(1);
            expect(records[0].get('name')).toEqual('Bob');

            readTx.commit().then(() => {
              expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx424242');

              session.close(() => {
                driver.close();
                server.exit(code => {
                  expect(code).toEqual(0);
                  done();
                });
              });
            });
          });
        });
      });
    });

  });

  it('should not be possible to override bookmark with null', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/write_read_tx_with_bookmarks.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session(WRITE, 'neo4j:bookmark:v1:tx42');
      const writeTx = session.beginTransaction();
      writeTx.run('CREATE (n {name:\'Bob\'})').then(result => {
        const records = result.records;
        expect(records.length).toEqual(0);

        writeTx.commit().then(() => {
          expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx4242');

          const readTx = session.beginTransaction(null);
          readTx.run('MATCH (n) RETURN n.name AS name').then(result => {
            const records = result.records;
            expect(records.length).toEqual(1);
            expect(records[0].get('name')).toEqual('Bob');

            readTx.commit().then(() => {
              expect(session.lastBookmark()).toEqual('neo4j:bookmark:v1:tx424242');

              session.close(() => {
                driver.close();
                server.exit(code => {
                  expect(code).toEqual(0);
                  done();
                });
              });
            });
          });
        });
      });
    });
  });

  it('should throw service unavailable when server dies', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/dead_read_server.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session();
      session.run('MATCH (n) RETURN n.name').catch(error => {
        expect(error.code).toEqual(neo4j.error.SERVICE_UNAVAILABLE);

        driver.close();
        server.exit(code => {
          expect(code).toEqual(0);
          done();
        });
      });
    });
  });

  it('should close connection when RESET fails', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/reset_error.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session();

      session.run('RETURN 42 AS answer').then(result => {
        const records = result.records;
        expect(records.length).toEqual(1);
        expect(records[0].get(0).toNumber()).toEqual(42);
        session.close(() => {

          expect(driver._pool._pools['127.0.0.1:9001'].length).toEqual(0);
          driver.close();
          server.exit(code => {
            expect(code).toEqual(0);
            done();
          });

        });
      }).catch(error => done.fail(error));
    });
  });

  it('should send RESET on error', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/query_with_error.script', 9001);

    boltStub.run(() => {
      const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
      const session = driver.session();

      session.run('RETURN 10 / 0').then(result => {
        done.fail('Should fail but received a result: ' + JSON.stringify(result));
      }).catch(error => {
        expect(error.code).toEqual('Neo.ClientError.Statement.ArithmeticError');
        expect(error.message).toEqual('/ by zero');

        session.close(() => {
          driver.close();
          server.exit(code => {
            expect(code).toEqual(0);
            done();
          });
        });
      });
    });
  });

  it('should include database connection id in logs', done => {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start('./test/resources/boltstub/hello_run_exit.script', 9001);

    boltStub.run(() => {
      const messages = [];
      const logging = {
        level: 'debug',
        logger: (level, message) => messages.push(message)
      };

      const driver = boltStub.newDriver('bolt://127.0.0.1:9001', {logging: logging});
      const session = driver.session();

      session.run('MATCH (n) RETURN n.name').then(result => {
        const names = result.records.map(record => record.get(0));
        expect(names).toEqual(['Foo', 'Bar']);
        session.close(() => {
          driver.close();
          server.exit(code => {
            expect(code).toEqual(0);

            // logged messages should contain connection_id supplied by the database
            const containsDbConnectionIdMessage = messages.find(message => message.match(/Connection \[[0-9]+]\[bolt-123456789]/));
            if (!containsDbConnectionIdMessage) {
              console.log(messages);
            }
            expect(containsDbConnectionIdMessage).toBeTruthy();

            done();
          });
        });
      }).catch(error => done.fail(error));
    });
  });

  describe('should fail if commit fails due to broken connection', () => {
    it('v1', done => {
      verifyFailureOnConnectionFailureWhenExplicitTransactionIsCommitted('v1', done);
    });

    it('v3', done => {
      verifyFailureOnConnectionFailureWhenExplicitTransactionIsCommitted('v3', done);
    });
  });

  function verifyFailureOnConnectionFailureWhenExplicitTransactionIsCommitted(version, done) {
    if (!boltStub.supported) {
      done();
      return;
    }

    const server = boltStub.start(`./test/resources/boltstub/connection_error_on_commit_${version}.script`, 9001);

    boltStub.run(() => {
        const driver = boltStub.newDriver('bolt://127.0.0.1:9001');
        const session = driver.session();

        const writeTx = session.beginTransaction();

        writeTx.run('CREATE (n {name: \'Bob\'})').then(() =>
          writeTx.commit().then(result => fail('expected an error'), (error) => {
            expect(error.code).toBe(SERVICE_UNAVAILABLE);
          })
        ).finally(() =>
          session.close(() => {
            driver.close();

            server.exit(code => {
              expect(code).toEqual(0);
              done();
            });
          })).catch(error => done.fail(error));
      }
    );
  }
});
<|endoftext|>


<commit_before>$(document).ready(function(){
  var $logo = $('.navbar-logo');

  // $logo.hover(function(){
  //   console.log("you're hovering");
  //   $(this).attr('src', $(this).attr('src').replace());
  // });

  $logo.click(function(){
    location.href="http://sputterputtredux.github.io/#top";
  });
});<commit_msg>Remove commented-out code<commit_after>$(document).ready(function(){
  var $logo = $('.navbar-logo');

  $logo.click(function(){
    location.href="http://sputterputtredux.github.io/#top";
  });
});<|endoftext|>


<commit_before>//  parms
var audioIsJPlayer = "true";

// control set
var audioStartRecFieldId= null;
var audioStopRecFieldId=null;
var audioJPlayerFieldId=null;
var audioPlayerFieldId=null;
var audioDebugFieldId=null;
var audioRecordStatusDiv=null;
var audioRecordStatusCounterDiv=null;

// 'prviate' instance variables
var audioRecorder = null;
var audioPlayer = null;
var progressTimer = null;
var recTime = 0;
var mediaFileFullName = null;

// const
var audioStateEnum= {start: 1,
                    recording: 2,
                    finishRec: 3
                    }
var audioMaxRecordSecs =  900;  // maximum is 15 minutes
var mediaRecFile = "myRecording.wav";

function audioLogLine(msg) {

    console.log(msg);
    $('#'+audioDebugFieldId).val($('#'+ audioDebugFieldId).val() + msg + '\n');
}

function audioInitialize(_audioStartRecFieldId, _audioStopRecFieldId, _audioPlayerFieldId, _audioJPlayerFieldId,
         _audioRecordStatusDiv, _audioRecordStatusCounterDiv, _audioDebugFieldId) {

   audioDebugFieldId = _audioDebugFieldId;

    audioLogLine( "audioRecordApp: initialize(): start: audioStart: " + _audioStartRecFieldId);

    audioRecorder = null;
    progressTimer = null;
    recTime = null;
    mediaFileFullName = null;

    audioStartRecFieldId = _audioStartRecFieldId;
    audioStopRecFieldId = _audioStopRecFieldId;
    audioPlayerFieldId = _audioPlayerFieldId;
    audioJPlayerFieldId = _audioJPlayerFieldId;
    audioRecordStatusDiv = _audioRecordStatusDiv;
    audioRecordStatusCounterDiv = _audioRecordStatusCounterDiv;

    if (audioIsJPlayer == "true")
        audioJsCreateJPlayer("no.wav");

    audioJsSetButtonState(audioStateEnum.start);

    audioLogLine("audioRecordApp: initialize(): end: audioStart: " + audioStartRecFieldId);
}

function playMusic() {

    audioLogLine("audioRecordApp: playMusic: start");
    if (audioPlayer === null) { // play existing media recorded from previous session
       audioPlayer = new Media(mediaFileFullName, null,null);
    }

    // Play audio
    if (audioPlayer) {
        audioPlayer.play();

//        document.getElementById('PlayStatusID').innerHTML = "

Status: playing...";
//
//        setButtonState(myMediaState.playback);
//
//        // Update media position every second
//        clearProgressTimmer();
//        progressTimmer = setInterval(function () {
//            // get my_player position
//            my_player.getCurrentPosition(
//                // success callback
//                function (position) {
//                    if (position >= 0)
//                        setAudioPosition('media_pos', (position) + " sec");
//                    else {
//                        // reached end of media: same as clicked stop-music
//                        clearProgressTimmer();
//                        setAudioPosition('media_pos', "0 sec");
//                        document.getElementById('PlayStatusID').innerHTML = "
Status: stopped<\p>";
//                        setButtonState(myMediaState.stopped);
//                    }
//                },
//                // error callback
//                function (e) {
//                    document.getElementById('PlayStatusID').innerHTML = "

Status: Error on getting position - " + e;
//                    setAudioPosition("Error: " + e);
//                });
//        }, 1000);
    }
}

function audioJsCreateJPlayer(fileName) {

    audioLogLine("audioJs: audioCreateJPlayer(): start called with: " + fileName + " JPlayer control field: " + audioJPlayerFieldId);

    $('#'+audioJPlayerFieldId).jPlayer({
        ready: function (event) {
            $(this).jPlayer("setMedia", {
//                        m4a:"http://www.jplayer.org/audio/m4a/TSP-01-Cro_magnon_man.m4a",
//                        oga:"http://www.jplayer.org/audio/ogg/TSP-01-Cro_magnon_man.ogg"
                wav: fileName
            });
        },
        swfPath: "js",
        //supplied: "m4a, oga",
        supplied: "wav",
        wmode: "window",
        smoothPlayBar: true,
        keyEnabled: true
    });

    audioLogLine("audioJs: audioCreateJPlayer(): end called with: " + fileName);

}

function audioJsSwitchFile() {

    audioLogLine("audioJs: audioSwitchFile(): start");

    audioSetPlayerFileName(audioJPlayerFieldId, "G2MTestSound.wav");

    audioLogLine("audioJs: audioSwitchFile(): end");

}

function audioSetPlayerFileName(playerName, fileName) {

    audioLogLine("audioJs: audioSetPlayerFileName(): start called with: Player: " + playerName + " File: " + fileName);

    var fullPlayerName = '#' + playerName;
    $(fullPlayerName).jPlayer("setMedia", {
//                        m4a:"http://www.jplayer.org/audio/m4a/TSP-01-Cro_magnon_man.m4a",
//                        oga:"http://www.jplayer.org/audio/ogg/TSP-01-Cro_magnon_man.ogg"
        wav: fileName
    });

    audioLogLine( "audioJs: audioSetPlayerFileName(): end called with: " + fileName);
}

function audioJsStartRecording() {

    audioLogLine("audioJs: audioJsStartRecording(): start");

    // change buttons state
    audioJsSetButtonState(audioStateEnum.recording);

    // create media object - overwrite existing recording
    if (audioRecorder)
        audioRecorder.release();

    //first create the file   then the success handler will launch recording to the file
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, audioJsOnSuccessContinueRecordingInit, function() {
        audioLogLine("audioJs: audioJsStartRecording(): failed in requestFileSystem call");
    });

    audioLogLine("audioJs: audioJsStartRecording(): end");
}

function audioJsOnSuccessContinueRecordingInit(fileSystem) {

    audioLogLine("audioJs: audioJsOnSuccessContinueRecordingInit(): start");
    audioLogLine("audioJs: audioJsOnSuccessContinueRecordingInit(): Root File System Name: " + fileSystem.root.name);

    fileSystem.root.getFile(mediaRecFile, { create: true, exclusive: false }, audioJsOnSuccessCompleteRecordingInit, function() {
        audioLogLine("audioJs: audioJsOnSuccessContinueRecordingInit(): failed in getFile() call");
    });

    audioLogLine("audioJs: audioJsOnSuccessContinueRecordingInit(): end");
}

function audioJsOnSuccessCompleteRecordingInit(fileEntry) {

    audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): start");
    audioLogLine( "audioJs: audioJsonSuccessCompleteRecordingInit(): File Name: " + mediaRecFile + " at " + fileEntry.fullPath);

    // save the full file name
    mediaFileFullName = fileEntry.fullPath;
    mediaRecFile = mediaFileFullName;

    audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): about the create Media object");
    // create media object using full media file name
    audioRecorder = new Media(mediaRecFile, function() {
       audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): Media Object Create: success");
    }, function() {
        audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): Media Object Create: fail");
    });

    // specific for iOS device: recording start here in call-back function
    audioJsRecordLaunch();

    audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): end");

}

function audioJsRecordLaunch() {

    audioLogLine("audioJs: audioJsRecordLaunch(): start");

    if (audioRecorder) {
        audioRecorder.startRecord();
        document.getElementById(audioRecordStatusDiv).innerHTML = "Recording .....";
        audioLogLine("audioJs: audioJsRecordLaunch(): recorder.startRecord()");
    }
    else   {
        //console.log("***test:  my_recorder==null: in audioJsStartRecording()***");
        audioLogLine("audioJs: audioJsRecordLaunch(): recorder.startRecord(): NULL RECORDER");
    }

    // reset the recTime every time when recording
    recTime = 0;
    // Stop recording after 10 sec
    progressTimer = setInterval(function() {
        recTime = recTime + 1;
        document.getElementById(audioRecordStatusCounterDiv).innerHTML = "

Recording Length: "+ recTime + " sec";
//        if (recTime >= audioMaxRecordSecs)
//            audioJsStopRecording();
    }, 1000);

    audioLogLine("audioJs: audioJsRecordLaunch(): end");
}

function audioJsClearProgressTimer() {
    if (progressTimer) {
        clearInterval(progressTimer);
        progressTimer = null;
    }
}

// Stop recording
function audioJsStopRecording() {
    // enable "record" button but disable "stop"

    audioLogLine("audioJs: audioJsStopRecording(): start. ");

    if (audioRecorder)
        audioRecorder.stopRecord(); // the file should be moved to "/sdcard/"+mediaRecFile

    audioPlayer = new Media(mediaFileFullName, null,null);
    audioPlayer.play();
    audioPlayer.release();

    if (audioIsJPlayer == "false")
        $('#'+audioPlayerFieldId).attr("src", mediaFileFullName);
    else
        audioSetPlayerFileName(audioJPlayerFieldId, mediaFileFullName);

    audioJsSetButtonState(audioStateEnum.finishRec);

    audioJsClearProgressTimer();

    document.getElementById(audioRecordStatusDiv).innerHTML = "
Recording stopped.
";

    audioLogLine("audioJs: audioJsStopRecording(): end. ");
}

function audioJsSetButtonState(targetState)
{

    audioLogLine("audioRecordApp: setButtonState(): start: state requested: " + targetState);

    if (targetState == audioStateEnum.start) // only "record" is enabled
    {
        $('#'+audioStartRecFieldId).removeClass('ui-disabled') ;
        $('#'+audioStopRecFieldId).addClass('ui-disabled') ;

    }
    else if (targetState == audioStateEnum.recording) // only "stoprec" is enabled
    {
        $('#'+audioStartRecFieldId).addClass('ui-disabled') ;
        $('#'+audioStopRecFieldId).removeClass('ui-disabled') ;
    }
    else if (targetState == this.audioStateEnum.finishRec)      // this could be used to enable a remove or restart button
    {
        $('#'+audioStartRecFieldId).removeClass('ui-disabled') ;
        $('#'+audioStopRecFieldId).addClass('ui-disabled') ;
    }

    audioLogLine("audioRecordApp: setButtonState(): end: state requested: " + targetState);

}<commit_msg>formatting of status line<commit_after>//  parms
var audioIsJPlayer = "true";

// control set
var audioStartRecFieldId= null;
var audioStopRecFieldId=null;
var audioJPlayerFieldId=null;
var audioPlayerFieldId=null;
var audioDebugFieldId=null;
var audioRecordStatusDiv=null;
var audioRecordStatusCounterDiv=null;

// 'prviate' instance variables
var audioRecorder = null;
var audioPlayer = null;
var progressTimer = null;
var recTime = 0;
var mediaFileFullName = null;

// const
var audioStateEnum= {start: 1,
                    recording: 2,
                    finishRec: 3
                    }
var audioMaxRecordSecs =  900;  // maximum is 15 minutes
var mediaRecFile = "myRecording.wav";

function audioLogLine(msg) {

    console.log(msg);
    $('#'+audioDebugFieldId).val($('#'+ audioDebugFieldId).val() + msg + '\n');
}

function audioInitialize(_audioStartRecFieldId, _audioStopRecFieldId, _audioPlayerFieldId, _audioJPlayerFieldId,
         _audioRecordStatusDiv, _audioRecordStatusCounterDiv, _audioDebugFieldId) {

   audioDebugFieldId = _audioDebugFieldId;

    audioLogLine( "audioRecordApp: initialize(): start: audioStart: " + _audioStartRecFieldId);

    audioRecorder = null;
    progressTimer = null;
    recTime = null;
    mediaFileFullName = null;

    audioStartRecFieldId = _audioStartRecFieldId;
    audioStopRecFieldId = _audioStopRecFieldId;
    audioPlayerFieldId = _audioPlayerFieldId;
    audioJPlayerFieldId = _audioJPlayerFieldId;
    audioRecordStatusDiv = _audioRecordStatusDiv;
    audioRecordStatusCounterDiv = _audioRecordStatusCounterDiv;

    if (audioIsJPlayer == "true")
        audioJsCreateJPlayer("no.wav");

    audioJsSetButtonState(audioStateEnum.start);

    audioLogLine("audioRecordApp: initialize(): end: audioStart: " + audioStartRecFieldId);
}

function playMusic() {

    audioLogLine("audioRecordApp: playMusic: start");
    if (audioPlayer === null) { // play existing media recorded from previous session
       audioPlayer = new Media(mediaFileFullName, null,null);
    }

    // Play audio
    if (audioPlayer) {
        audioPlayer.play();

//        document.getElementById('PlayStatusID').innerHTML = "

Status: playing...";
//
//        setButtonState(myMediaState.playback);
//
//        // Update media position every second
//        clearProgressTimmer();
//        progressTimmer = setInterval(function () {
//            // get my_player position
//            my_player.getCurrentPosition(
//                // success callback
//                function (position) {
//                    if (position >= 0)
//                        setAudioPosition('media_pos', (position) + " sec");
//                    else {
//                        // reached end of media: same as clicked stop-music
//                        clearProgressTimmer();
//                        setAudioPosition('media_pos', "0 sec");
//                        document.getElementById('PlayStatusID').innerHTML = "
Status: stopped<\p>";
//                        setButtonState(myMediaState.stopped);
//                    }
//                },
//                // error callback
//                function (e) {
//                    document.getElementById('PlayStatusID').innerHTML = "

Status: Error on getting position - " + e;
//                    setAudioPosition("Error: " + e);
//                });
//        }, 1000);
    }
}

function audioJsCreateJPlayer(fileName) {

    audioLogLine("audioJs: audioCreateJPlayer(): start called with: " + fileName + " JPlayer control field: " + audioJPlayerFieldId);

    $('#'+audioJPlayerFieldId).jPlayer({
        ready: function (event) {
            $(this).jPlayer("setMedia", {
//                        m4a:"http://www.jplayer.org/audio/m4a/TSP-01-Cro_magnon_man.m4a",
//                        oga:"http://www.jplayer.org/audio/ogg/TSP-01-Cro_magnon_man.ogg"
                wav: fileName
            });
        },
        swfPath: "js",
        //supplied: "m4a, oga",
        supplied: "wav",
        wmode: "window",
        smoothPlayBar: true,
        keyEnabled: true
    });

    audioLogLine("audioJs: audioCreateJPlayer(): end called with: " + fileName);

}

function audioJsSwitchFile() {

    audioLogLine("audioJs: audioSwitchFile(): start");

    audioSetPlayerFileName(audioJPlayerFieldId, "G2MTestSound.wav");

    audioLogLine("audioJs: audioSwitchFile(): end");

}

function audioSetPlayerFileName(playerName, fileName) {

    audioLogLine("audioJs: audioSetPlayerFileName(): start called with: Player: " + playerName + " File: " + fileName);

    var fullPlayerName = '#' + playerName;
    $(fullPlayerName).jPlayer("setMedia", {
//                        m4a:"http://www.jplayer.org/audio/m4a/TSP-01-Cro_magnon_man.m4a",
//                        oga:"http://www.jplayer.org/audio/ogg/TSP-01-Cro_magnon_man.ogg"
        wav: fileName
    });

    audioLogLine( "audioJs: audioSetPlayerFileName(): end called with: " + fileName);
}

function audioJsStartRecording() {

    audioLogLine("audioJs: audioJsStartRecording(): start");

    // change buttons state
    audioJsSetButtonState(audioStateEnum.recording);

    // create media object - overwrite existing recording
    if (audioRecorder)
        audioRecorder.release();

    //first create the file   then the success handler will launch recording to the file
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, audioJsOnSuccessContinueRecordingInit, function() {
        audioLogLine("audioJs: audioJsStartRecording(): failed in requestFileSystem call");
    });

    audioLogLine("audioJs: audioJsStartRecording(): end");
}

function audioJsOnSuccessContinueRecordingInit(fileSystem) {

    audioLogLine("audioJs: audioJsOnSuccessContinueRecordingInit(): start");
    audioLogLine("audioJs: audioJsOnSuccessContinueRecordingInit(): Root File System Name: " + fileSystem.root.name);

    fileSystem.root.getFile(mediaRecFile, { create: true, exclusive: false }, audioJsOnSuccessCompleteRecordingInit, function() {
        audioLogLine("audioJs: audioJsOnSuccessContinueRecordingInit(): failed in getFile() call");
    });

    audioLogLine("audioJs: audioJsOnSuccessContinueRecordingInit(): end");
}

function audioJsOnSuccessCompleteRecordingInit(fileEntry) {

    audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): start");
    audioLogLine( "audioJs: audioJsonSuccessCompleteRecordingInit(): File Name: " + mediaRecFile + " at " + fileEntry.fullPath);

    // save the full file name
    mediaFileFullName = fileEntry.fullPath;
    mediaRecFile = mediaFileFullName;

    audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): about the create Media object");
    // create media object using full media file name
    audioRecorder = new Media(mediaRecFile, function() {
       audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): Media Object Create: success");
    }, function() {
        audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): Media Object Create: fail");
    });

    // specific for iOS device: recording start here in call-back function
    audioJsRecordLaunch();

    audioLogLine("audioJs: audioJsonSuccessCompleteRecordingInit(): end");

}

function audioJsRecordLaunch() {

    audioLogLine("audioJs: audioJsRecordLaunch(): start");

    if (audioRecorder) {
        audioRecorder.startRecord();
        document.getElementById(audioRecordStatusDiv).innerHTML = "Recording .....";
        audioLogLine("audioJs: audioJsRecordLaunch(): recorder.startRecord()");
    }
    else   {
        //console.log("***test:  my_recorder==null: in audioJsStartRecording()***");
        audioLogLine("audioJs: audioJsRecordLaunch(): recorder.startRecord(): NULL RECORDER");
    }

    // reset the recTime every time when recording
    recTime = 0;
    // Stop recording after 10 sec
    progressTimer = setInterval(function() {
        recTime = recTime + 1;
        document.getElementById(audioRecordStatusCounterDiv).innerHTML = "Recording Length: "+ recTime + " sec";
//        if (recTime >= audioMaxRecordSecs)
//            audioJsStopRecording();
    }, 1000);

    audioLogLine("audioJs: audioJsRecordLaunch(): end");
}

function audioJsClearProgressTimer() {
    if (progressTimer) {
        clearInterval(progressTimer);
        progressTimer = null;
    }
}

// Stop recording
function audioJsStopRecording() {
    // enable "record" button but disable "stop"

    audioLogLine("audioJs: audioJsStopRecording(): start. ");

    if (audioRecorder)
        audioRecorder.stopRecord(); // the file should be moved to "/sdcard/"+mediaRecFile

    audioPlayer = new Media(mediaFileFullName, null,null);
    audioPlayer.play();
    audioPlayer.release();

    if (audioIsJPlayer == "false")
        $('#'+audioPlayerFieldId).attr("src", mediaFileFullName);
    else
        audioSetPlayerFileName(audioJPlayerFieldId, mediaFileFullName);

    audioJsSetButtonState(audioStateEnum.finishRec);

    audioJsClearProgressTimer();

    document.getElementById(audioRecordStatusDiv).innerHTML = "Recording stopped.";

    audioLogLine("audioJs: audioJsStopRecording(): end. ");
}

function audioJsSetButtonState(targetState)
{

    audioLogLine("audioRecordApp: setButtonState(): start: state requested: " + targetState);

    if (targetState == audioStateEnum.start) // only "record" is enabled
    {
        $('#'+audioStartRecFieldId).removeClass('ui-disabled') ;
        $('#'+audioStopRecFieldId).addClass('ui-disabled') ;

    }
    else if (targetState == audioStateEnum.recording) // only "stoprec" is enabled
    {
        $('#'+audioStartRecFieldId).addClass('ui-disabled') ;
        $('#'+audioStopRecFieldId).removeClass('ui-disabled') ;
    }
    else if (targetState == this.audioStateEnum.finishRec)      // this could be used to enable a remove or restart button
    {
        $('#'+audioStartRecFieldId).removeClass('ui-disabled') ;
        $('#'+audioStopRecFieldId).addClass('ui-disabled') ;
    }

    audioLogLine("audioRecordApp: setButtonState(): end: state requested: " + targetState);

}<|endoftext|>


<commit_before>define([
    'underscore',
    'jquery',
    'exif',
    'drp-plugin-api'
], function (_, $, Exif, PluginApi) {
    'use strict';

    var MetaEditor = function (imboApp) {
        this.initialize(imboApp);
    };

    _.extend(MetaEditor.prototype, {
        MAX_IMAGE_WIDTH: 1464,
        MAX_IMAGE_HEIGHT: 1104,

        initialize: function (imboApp) {
            _.bindAll(this);
            this.editorPane = $('.meta-editor');
            this.tabCtrl = $('.tab-controller');
            this.exifPane = $('.exif-pane');
            this.inputPane = $('.input-pane');
            this.imageBox = this.editorPane.find('.image-container');
            this.imageView = this.imageBox.find('.source');
            this.events = $({});
            this.bindEvents();
            this.imboApp = imboApp;
        },

        bindEvents: function () {
            $(window)
                .on('resize', _.debounce(this.resizePanes, 150))
                .trigger('resize');

            this.editorPane
                .find('.close')
                .on('click', this.hide);

            this.editorPane
                .find('.save')
                .on('click', this.saveMetadata);

            this.tabCtrl
                .find('button')
                .on('click', this.switchTab);
        },

        setTranslator: function (translator) {
            this.translator = translator;
        },

        setImboClient: function (imboClient) {
            this.imbo = imboClient;
        },

        resizePanes: function () {
            this.imageBox.css('height', $(window).height() - 50);
        },

        switchTab: function (e) {
            var el = $(e.currentTarget),
                tab = el.data('tab'),
                tabEl = this.editorPane.find('.tab[data-tab="' + tab + '"]');

            tabEl.removeClass('hidden')
                .siblings('.tab')
                .addClass('hidden');

            el
                .closest('.tab-controller')
                .find('button[data-tab]')
                .removeClass('active');

            el.addClass('active');
        },

        imboApp: null,

        show: function () {
            // Maximize app window (if in app context)
            //PluginApi.Article.maximizeAppWindow(
            //    this.translator.translate('META_EDITOR_TITLE'),
            //    this.hide
            //);

            // Focus the first tab
            this.tabCtrl
                .find('button[data-tab]:first')
                .trigger('click');

            // Show the editor pane and trigger a show-event
            this.editorPane.removeClass('hidden');
            this.trigger('show');
        },

        hide: function () {
            this.imboApp.imageEditor.hide();
        },

        resetState: function () {
            this.inputPane.find('input, textarea').val('');
            this.imageView.css('background-image', '');
            this.tabCtrl.find('button[data-tab]').removeClass('hidden');
        },

        loadDataForImage: function (imageId) {
            // Reset state so we're not showing old data
            this.resetState();
            // Ensure app knows which image to change metadata on
            this.imageIdentifier = imageId;
            this.imbo.getMetadata(imageId, this.onImageDataLoaded);
        },

        setImageViewUrl: function (url) {
            this.imageView.css(
                'background-image',
                'url(' + url.toString() + ')'
            );
        },

        onImageDataLoaded: function (err, data) {
            if (!data) {
                return;
            }
            this.inputPane.find('input, textarea').each(function (i, el) {
                var name = el.getAttribute('name');
                if (data[name]) {
                    el.value = data[name];
                } else if (name === 'title' && data['filename']) {
                    el.value = data['filename'];
                } else if (name === 'photographer' && data['exif:Artist']) {
                    el.value = data['exif:Artist'];
                }
            });
            this.populateExifData(data);
        },

        populateExifData: function (data) {
            this.exifPane.empty();

            var dl = $('<dl />'), table, value, parts, tags = 0;
            for (var exifTag in Exif.TagMap) {
                if (!data[exifTag]) {
                    continue;
                }

                table = Exif.TagTable[exifTag];
                value = data[exifTag];

                // GPS location?
                if (exifTag === 'gps:location') {
                    value = ($('<a />')
                        .attr('target', '_blank')
                        .attr('href', 'http://maps.google.com/?q=' + value.reverse().join(','))
                        .text(value.reverse().map(function (i) {
                            return i.toFixed(5);
                        }).join(', ')));
                } else {
                    value = (value + '').replace(/^\s+|\s+$/g, '');
                }

                // Should we cast to integer?
                if (!isNaN(value)) {
                    value = parseInt(data[exifTag], 10);
                }

                // Do we have a lookup table with our value in it?
                if (table && table[value]) {
                    value = this.translator.translate(table[value]);
                }

                // Is the value dividable, to get a decimal variant?
                if (typeof value === 'string' && value.match(/^\d+\/\d+$/)) {
                    parts = value.split('/');
                    value = (parts[0] / parts[1]) + ' (' + value + ')';
                }

                // GPS altitude? Add suffix (unit)
                if (exifTag === 'gps:altitude') {
                    value += 'm';
                }

                $('<dt />')
                    .text(this.translator.translate(Exif.TagMap[exifTag]))
                    .appendTo(dl);

                $('<dd />')
                    .html(value)
                    .appendTo(dl);

                tags++;
            }

            if (tags > 0) {
                this.exifPane.append(dl);
            } else {
                this.tabCtrl
                    .find('[data-tab="exif"]')
                    .addClass('hidden');
            }
        },

        getMetadataFromInputs: function () {
            return _.reduce(
                this.inputPane.find('input, textarea'),
                function (data, el) {
                    data[el.getAttribute('name')] = el.value;
                    return data;
                }, {}
            );
        },

        saveMetadata: function () {
            if (!this.imageIdentifier) {
                return console.error('Tried to save metadata, no image active');
            }

            PluginApi.showLoader(
                this.translator.translate('META_EDITOR_SAVING_METADATA')
            );

            var callback = function () {
                PluginAPI.hideLoader();
            }

            this.imbo.editMetadata(
                this.imageIdentifier,
                this.getMetadataFromInputs(),
                callback
            );
        },

        on: function (e, handler) {
            this.events.on(e, handler);
            return this;
        },

        off: function (e, handler) {
            this.events.off(e, handler);
            return this;
        },

        trigger: function (e, handler) {
            this.events.trigger(e, handler);
            return this;
        }
    });

    return MetaEditor;

});
<commit_msg>Hide tab controller when only one pane has data<commit_after>define([
    'underscore',
    'jquery',
    'exif',
    'drp-plugin-api'
], function (_, $, Exif, PluginApi) {
    'use strict';

    var MetaEditor = function (imboApp) {
        this.initialize(imboApp);
    };

    _.extend(MetaEditor.prototype, {
        MAX_IMAGE_WIDTH: 1464,
        MAX_IMAGE_HEIGHT: 1104,

        initialize: function (imboApp) {
            _.bindAll(this);
            this.editorPane = $('.meta-editor');
            this.tabCtrl = $('.tab-controller');
            this.exifPane = $('.exif-pane');
            this.inputPane = $('.input-pane');
            this.imageBox = this.editorPane.find('.image-container');
            this.imageView = this.imageBox.find('.source');
            this.events = $({});
            this.bindEvents();
            this.imboApp = imboApp;
        },

        bindEvents: function () {
            $(window)
                .on('resize', _.debounce(this.resizePanes, 150))
                .trigger('resize');

            this.editorPane
                .find('.close')
                .on('click', this.hide);

            this.editorPane
                .find('.save')
                .on('click', this.saveMetadata);

            this.tabCtrl
                .find('button')
                .on('click', this.switchTab);
        },

        setTranslator: function (translator) {
            this.translator = translator;
        },

        setImboClient: function (imboClient) {
            this.imbo = imboClient;
        },

        resizePanes: function () {
            this.imageBox.css('height', $(window).height() - 50);
        },

        switchTab: function (e) {
            var el = $(e.currentTarget),
                tab = el.data('tab'),
                tabEl = this.editorPane.find('.tab[data-tab="' + tab + '"]');

            tabEl.removeClass('hidden')
                .siblings('.tab')
                .addClass('hidden');

            el
                .closest('.tab-controller')
                .find('button[data-tab]')
                .removeClass('active');

            el.addClass('active');
        },

        imboApp: null,

        show: function () {
            // Maximize app window (if in app context)
            //PluginApi.Article.maximizeAppWindow(
            //    this.translator.translate('META_EDITOR_TITLE'),
            //    this.hide
            //);

            // Focus the first tab
            this.tabCtrl
                .find('button[data-tab]:first')
                .trigger('click');

            // Show the editor pane and trigger a show-event
            this.editorPane.removeClass('hidden');
            this.trigger('show');
        },

        hide: function () {
            this.imboApp.imageEditor.hide();
        },

        resetState: function () {
            this.tabCtrl
                .find('button[data-tab]:first')
                .trigger('click');

            this.inputPane.find('input, textarea').val('');
            this.imageView.css('background-image', '');
            this.tabCtrl.removeClass('hidden');
        },

        loadDataForImage: function (imageId) {
            // Reset state so we're not showing old data
            this.resetState();
            // Ensure app knows which image to change metadata on
            this.imageIdentifier = imageId;
            this.imbo.getMetadata(imageId, this.onImageDataLoaded);
        },

        setImageViewUrl: function (url) {
            this.imageView.css(
                'background-image',
                'url(' + url.toString() + ')'
            );
        },

        onImageDataLoaded: function (err, data) {
            if (!data) {
                return;
            }
            this.inputPane.find('input, textarea').each(function (i, el) {
                var name = el.getAttribute('name');
                if (data[name]) {
                    el.value = data[name];
                } else if (name === 'title' && data['filename']) {
                    el.value = data['filename'];
                } else if (name === 'photographer' && data['exif:Artist']) {
                    el.value = data['exif:Artist'];
                }
            });
            this.populateExifData(data);
        },

        populateExifData: function (data) {
            this.exifPane.empty();

            var dl = $('<dl />'), table, value, parts, tags = 0;
            for (var exifTag in Exif.TagMap) {
                if (!data[exifTag]) {
                    continue;
                }

                table = Exif.TagTable[exifTag];
                value = data[exifTag];

                // GPS location?
                if (exifTag === 'gps:location') {
                    value = ($('<a />')
                        .attr('target', '_blank')
                        .attr('href', 'http://maps.google.com/?q=' + value.reverse().join(','))
                        .text(value.reverse().map(function (i) {
                            return i.toFixed(5);
                        }).join(', ')));
                } else {
                    value = (value + '').replace(/^\s+|\s+$/g, '');
                }

                // Should we cast to integer?
                if (!isNaN(value)) {
                    value = parseInt(data[exifTag], 10);
                }

                // Do we have a lookup table with our value in it?
                if (table && table[value]) {
                    value = this.translator.translate(table[value]);
                }

                // Is the value dividable, to get a decimal variant?
                if (typeof value === 'string' && value.match(/^\d+\/\d+$/)) {
                    parts = value.split('/');
                    value = (parts[0] / parts[1]) + ' (' + value + ')';
                }

                // GPS altitude? Add suffix (unit)
                if (exifTag === 'gps:altitude') {
                    value += 'm';
                }

                $('<dt />')
                    .text(this.translator.translate(Exif.TagMap[exifTag]))
                    .appendTo(dl);

                $('<dd />')
                    .html(value)
                    .appendTo(dl);

                tags++;
            }

            if (tags > 0) {
                this.exifPane.append(dl);
            } else {
                this.tabCtrl.addClass('hidden');
            }
        },

        getMetadataFromInputs: function () {
            return _.reduce(
                this.inputPane.find('input, textarea'),
                function (data, el) {
                    data[el.getAttribute('name')] = el.value;
                    return data;
                }, {}
            );
        },

        saveMetadata: function () {
            if (!this.imageIdentifier) {
                return console.error('Tried to save metadata, no image active');
            }

            PluginApi.showLoader(
                this.translator.translate('META_EDITOR_SAVING_METADATA')
            );

            var callback = function () {
                PluginAPI.hideLoader();
            }

            this.imbo.editMetadata(
                this.imageIdentifier,
                this.getMetadataFromInputs(),
                callback
            );
        },

        on: function (e, handler) {
            this.events.on(e, handler);
            return this;
        },

        off: function (e, handler) {
            this.events.off(e, handler);
            return this;
        },

        trigger: function (e, handler) {
            this.events.trigger(e, handler);
            return this;
        }
    });

    return MetaEditor;

});
<|endoftext|>