<commit_before>/** @module delite/Selection */
define(["dcl/dcl", "./sniff", "./Widget"], function (dcl, has, Widget) {
	/**
	 * Mixin for widgets that manage a list of selected data items.
	 * @mixin module:delite/Selection
	 * @augments module:delite/Widget
	 */
	return dcl(Widget, /** @lends module:delite/Selection# */{
		preCreate: function () {
			this._set("selectedItems", []);
		},

		/**
		 * The chosen selection mode.
		 *
		 * Valid values are:
		 *
		 * 1. "none": No selection can be done.
		 * 2. "single": Only one item can be selected at a time.
		 * 3. "multiple": Several item can be selected using the control key modifier.
		 *
		 * Changing this value impacts the current selected items to adapt the selection to the new mode. However
		 * whatever the selection mode is you can always set several selected items using the selectItem(s) API.
		 * The mode will be enforced only when using setSelected and/or selectFromEvent APIs.
		 *
		 * @member {string}
		 * @default "single"
		 */
		selectionMode: "single",

		_setSelectionModeAttr: function (value) {
			if (value !== "none" && value !== "single" && value !== "multiple") {
				throw new TypeError("selectionMode invalid value");
			}
			if (value !== this.selectionMode) {
				this._set("selectionMode", value);
				if (value === "none") {
					this.selectedItems = null;
				} else if (value === "single" && this.selectedItem) {
					this.selectedItems = [this.selectedItem];
				}
			}
		},

		/**
		 * In single selection mode, the selected item or in multiple selection mode the last selected item.
		 * @member {Object}
		 * @default null
		 */
		selectedItem: null,

		_setSelectedItemAttr: function (value) {
			if (this.selectedItem !== value) {
				this.selectedItems = (value == null ? null : [value]);
			}
		},

		/**
		 * The list of selected items.
		 * @member {Object[]}
		 * @default null
		 */
		selectedItems: null,

		_setSelectedItemsAttr: function (value) {
			var oldSelectedItems = this.selectedItems;

			this._set("selectedItems", value);

			if (oldSelectedItems != null && oldSelectedItems.length > 0) {
				this.updateRenderers(oldSelectedItems);
			}
			if (this.selectedItems && this.selectedItems.length > 0) {
				this._set("selectedItem", this.selectedItems[0]);
				this.updateRenderers(this.selectedItems);
			} else {
				this._set("selectedItem", null);
			}
		},

		_getSelectedItemsAttr: function () {
			return this._get("selectedItems") == null ? [] : this._get("selectedItems").concat();
		},

		/**
		 * Tests if an event has a selection modifier.
		 *
		 * If it has a selection modifier, that means that:
		 *
		 * * if selectionMode is "single", the event will be able to deselect a selected item
		 * * if selectionMode is "multiple", the event will trigger the selection state of the item
		 *
		 * The default implementation of this method returns true if the event.ctrlKey attribute is
		 * true, which means that:
		 *
		 * * if selectionMode is "single", the Ctrl (or Command on MacOS) key must be pressed for the
		 * * event to deselect the currently selected item
		 * * if selectionMode is "multiple", the Ctrl (or Command on MacOS) key must be pressed for the
		 *     event to toggle the selection status of the item.
		 *
		 * @param {Event} event - The event that led to the selection .
		 * @returns {boolean} Whether the event has selection modifier.
		 * @protected
		 */
		hasSelectionModifier: function (event) {
			return !has("mac") ? event.ctrlKey : event.metaKey;
		},

		/**
		 * Returns whether an item is selected or not.
		 * @param {item} object The item to test.
		 * @returns {Object} The item to test the selection for.
		 */
		isSelected: function (item) {
			if (this.selectedItems == null || this.selectedItems.length === 0) {
				return false;
			}
			var identity = this.getIdentity(item);
			return this.selectedItems.some(function (sitem) {
				return this.getIdentity(sitem) === identity;
			}, this);
		},

		/**
		 * This function must be implemented to return the id of a item.
		 * @param {item} object - The item the identity of must be returned.
		 * @returns {string} The identity of the item.
		 */
		getIdentity: function (/*jshint unused: vars */item) {
		},

		/**
		 * This function must be implemented to update the rendering of the items based on whether they are
		 * selected or not. The implementation must check for their new selection state and update
		 * accordingly.
		 * @param {Object[]} items - The array of items changing their selection state.
		 * @protected
		 */
		updateRenderers: function (/*jshint unused: vars */items) {
		},

		/**
		 * Change the selection state of an item.
		 * @param {Object} item - The item to change the selection state for.
		 * @param {boolean} value - True to select the item, false to deselect it.
		 */
		setSelected: function (item, value) {
			if (this.selectionMode === "none" || item == null) {
				return;
			}

			this._setSelected(item, value);
		},

		_setSelected: function (item, value) {
			// copy is returned
			var sel = this.selectedItems, res, identity;

			if (this.selectionMode === "single") {
				if (value) {
					this.selectedItem = item;
				} else if (this.isSelected(item)) {
					this.selectedItems = null;
				}
			} else { // multiple
				if (value) {
					if (this.isSelected(item)) {
						return; // already selected
					}
					if (sel == null) {
						sel = [item];
					} else {
						sel.unshift(item);
					}
					this.selectedItems = sel;
				} else {
					identity = this.getIdentity(item);
					res = sel ? sel.filter(function (sitem) {
						return this.getIdentity(sitem) !== identity;
					}, this) : [];
					if (res == null || res.length === sel.length) {
						return; // already not selected
					}
					this.selectedItems = res;
				}
			}
		},

		/**
		 * Applies selection triggered by an user interaction.
		 * @param {Event} event - The source event of the user interaction.
		 * @param {Object} item - The item that has been selected/deselected.
		 * @param {Object} renderer - The visual renderer of the selected/deselected item.
		 * @param {boolean} dispatch - Whether an event must be dispatched or not.
		 * @returns {boolean} True if the selection has changed and false otherwise.
		 * @protected
		 */
		selectFromEvent: function (event, item, renderer, dispatch) {
			if (this.selectionMode === "none") {
				return false;
			}

			return this._selectFromEvent(event, item, renderer, dispatch);
		},

		_selectFromEvent: function (event, item, renderer, dispatch) {
			var changed;
			var oldSelectedItem = this.selectedItem;
			var selected = item == null ? false : this.isSelected(item);

			if (item == null) {
				if ((this.selectionMode === "multiple" && !this.hasSelectionModifier(event))
					&& this.selectedItem != null) {
					this.selectedItem = null;
					changed = true;
				}
			} else if (this.selectionMode === "multiple") {
				if (this.hasSelectionModifier(event)) {
					this.setSelected(item, !selected);
					changed = true;
				} else {
					this.selectedItem = item;
					changed = true;
				}
			} else { // single
				if (this.hasSelectionModifier(event)) {
					//if the object is selected deselects it.
					this.selectedItem = (selected ? null : item);
					changed = true;
				} else {
					if (!selected) {
						this.selectedItem = item;
						changed = true;
					}
				}
			}

			if (dispatch && changed) {
				this.dispatchSelectionChange(oldSelectedItem, this.selectedItem, renderer, event);
			}

			return changed;
		},

		/**
		 * Dispatch a selection change event.
		 * @param {Object} oldSelectedItem - The previously selected item.
		 * @param {Object} newSelectedItem - The new selected item.
		 * @param {Object} renderer - The visual renderer of the selected/deselected item.
		 * @param {Event} triggerEvent - The event that lead to the selection of the item.
		 * @protected
		 */
		dispatchSelectionChange: function (oldSelectedItem, newSelectedItem, renderer, triggerEvent) {
			this.emit("selection-change", {
				oldValue: oldSelectedItem,
				newValue: newSelectedItem,
				renderer: renderer,
				triggerEvent: triggerEvent
			});
		}
	});
});<commit_msg>add a hook so that selection-change event listener can be setup in markup<commit_after>/** @module delite/Selection */
define(["dcl/dcl", "./sniff", "./Widget"], function (dcl, has, Widget) {
	/**
	 * Mixin for widgets that manage a list of selected data items.
	 * @mixin module:delite/Selection
	 * @augments module:delite/Widget
	 */
	return dcl(Widget, /** @lends module:delite/Selection# */{
		preCreate: function () {
			this._set("selectedItems", []);
		},

		/**
		 * The chosen selection mode.
		 *
		 * Valid values are:
		 *
		 * 1. "none": No selection can be done.
		 * 2. "single": Only one item can be selected at a time.
		 * 3. "multiple": Several item can be selected using the control key modifier.
		 *
		 * Changing this value impacts the current selected items to adapt the selection to the new mode. However
		 * whatever the selection mode is you can always set several selected items using the selectItem(s) API.
		 * The mode will be enforced only when using setSelected and/or selectFromEvent APIs.
		 *
		 * @member {string}
		 * @default "single"
		 */
		selectionMode: "single",

		_setSelectionModeAttr: function (value) {
			if (value !== "none" && value !== "single" && value !== "multiple") {
				throw new TypeError("selectionMode invalid value");
			}
			if (value !== this.selectionMode) {
				this._set("selectionMode", value);
				if (value === "none") {
					this.selectedItems = null;
				} else if (value === "single" && this.selectedItem) {
					this.selectedItems = [this.selectedItem];
				}
			}
		},

		/**
		 * In single selection mode, the selected item or in multiple selection mode the last selected item.
		 * @member {Object}
		 * @default null
		 */
		selectedItem: null,

		_setSelectedItemAttr: function (value) {
			if (this.selectedItem !== value) {
				this.selectedItems = (value == null ? null : [value]);
			}
		},

		/**
		 * The list of selected items.
		 * @member {Object[]}
		 * @default null
		 */
		selectedItems: null,

		_setSelectedItemsAttr: function (value) {
			var oldSelectedItems = this.selectedItems;

			this._set("selectedItems", value);

			if (oldSelectedItems != null && oldSelectedItems.length > 0) {
				this.updateRenderers(oldSelectedItems);
			}
			if (this.selectedItems && this.selectedItems.length > 0) {
				this._set("selectedItem", this.selectedItems[0]);
				this.updateRenderers(this.selectedItems);
			} else {
				this._set("selectedItem", null);
			}
		},

		_getSelectedItemsAttr: function () {
			return this._get("selectedItems") == null ? [] : this._get("selectedItems").concat();
		},

		/**
		 * Tests if an event has a selection modifier.
		 *
		 * If it has a selection modifier, that means that:
		 *
		 * * if selectionMode is "single", the event will be able to deselect a selected item
		 * * if selectionMode is "multiple", the event will trigger the selection state of the item
		 *
		 * The default implementation of this method returns true if the event.ctrlKey attribute is
		 * true, which means that:
		 *
		 * * if selectionMode is "single", the Ctrl (or Command on MacOS) key must be pressed for the
		 * * event to deselect the currently selected item
		 * * if selectionMode is "multiple", the Ctrl (or Command on MacOS) key must be pressed for the
		 *     event to toggle the selection status of the item.
		 *
		 * @param {Event} event - The event that led to the selection .
		 * @returns {boolean} Whether the event has selection modifier.
		 * @protected
		 */
		hasSelectionModifier: function (event) {
			return !has("mac") ? event.ctrlKey : event.metaKey;
		},

		/**
		 * Returns whether an item is selected or not.
		 * @param {item} object The item to test.
		 * @returns {Object} The item to test the selection for.
		 */
		isSelected: function (item) {
			if (this.selectedItems == null || this.selectedItems.length === 0) {
				return false;
			}
			var identity = this.getIdentity(item);
			return this.selectedItems.some(function (sitem) {
				return this.getIdentity(sitem) === identity;
			}, this);
		},

		/**
		 * This function must be implemented to return the id of a item.
		 * @param {item} object - The item the identity of must be returned.
		 * @returns {string} The identity of the item.
		 */
		getIdentity: function (/*jshint unused: vars */item) {
		},

		/**
		 * This function must be implemented to update the rendering of the items based on whether they are
		 * selected or not. The implementation must check for their new selection state and update
		 * accordingly.
		 * @param {Object[]} items - The array of items changing their selection state.
		 * @protected
		 */
		updateRenderers: function (/*jshint unused: vars */items) {
		},

		/**
		 * Change the selection state of an item.
		 * @param {Object} item - The item to change the selection state for.
		 * @param {boolean} value - True to select the item, false to deselect it.
		 */
		setSelected: function (item, value) {
			if (this.selectionMode === "none" || item == null) {
				return;
			}

			this._setSelected(item, value);
		},

		_setSelected: function (item, value) {
			// copy is returned
			var sel = this.selectedItems, res, identity;

			if (this.selectionMode === "single") {
				if (value) {
					this.selectedItem = item;
				} else if (this.isSelected(item)) {
					this.selectedItems = null;
				}
			} else { // multiple
				if (value) {
					if (this.isSelected(item)) {
						return; // already selected
					}
					if (sel == null) {
						sel = [item];
					} else {
						sel.unshift(item);
					}
					this.selectedItems = sel;
				} else {
					identity = this.getIdentity(item);
					res = sel ? sel.filter(function (sitem) {
						return this.getIdentity(sitem) !== identity;
					}, this) : [];
					if (res == null || res.length === sel.length) {
						return; // already not selected
					}
					this.selectedItems = res;
				}
			}
		},

		/**
		 * Applies selection triggered by an user interaction.
		 * @param {Event} event - The source event of the user interaction.
		 * @param {Object} item - The item that has been selected/deselected.
		 * @param {Object} renderer - The visual renderer of the selected/deselected item.
		 * @param {boolean} dispatch - Whether an event must be dispatched or not.
		 * @returns {boolean} True if the selection has changed and false otherwise.
		 * @protected
		 */
		selectFromEvent: function (event, item, renderer, dispatch) {
			if (this.selectionMode === "none") {
				return false;
			}

			return this._selectFromEvent(event, item, renderer, dispatch);
		},

		_selectFromEvent: function (event, item, renderer, dispatch) {
			var changed;
			var oldSelectedItem = this.selectedItem;
			var selected = item == null ? false : this.isSelected(item);

			if (item == null) {
				if ((this.selectionMode === "multiple" && !this.hasSelectionModifier(event))
					&& this.selectedItem != null) {
					this.selectedItem = null;
					changed = true;
				}
			} else if (this.selectionMode === "multiple") {
				if (this.hasSelectionModifier(event)) {
					this.setSelected(item, !selected);
					changed = true;
				} else {
					this.selectedItem = item;
					changed = true;
				}
			} else { // single
				if (this.hasSelectionModifier(event)) {
					//if the object is selected deselects it.
					this.selectedItem = (selected ? null : item);
					changed = true;
				} else {
					if (!selected) {
						this.selectedItem = item;
						changed = true;
					}
				}
			}

			if (dispatch && changed) {
				this.dispatchSelectionChange(oldSelectedItem, this.selectedItem, renderer, event);
			}

			return changed;
		},

		/**
		 * Dispatch a selection change event.
		 * @param {Object} oldSelectedItem - The previously selected item.
		 * @param {Object} newSelectedItem - The new selected item.
		 * @param {Object} renderer - The visual renderer of the selected/deselected item.
		 * @param {Event} triggerEvent - The event that lead to the selection of the item.
		 * @protected
		 */
		dispatchSelectionChange: function (oldSelectedItem, newSelectedItem, renderer, triggerEvent) {
			this.emit("selection-change", {
				oldValue: oldSelectedItem,
				newValue: newSelectedItem,
				renderer: renderer,
				triggerEvent: triggerEvent
			});
		},

		/**
		 * Hook for selection-change event in markup.
		 */
		"onselection-change": function () {}
	});
});<|endoftext|>


<commit_before>/*

THIS IS A WORK IN PROGRESS...

*/
var mingy = require('../lib/mingy')
  , Parser = mingy.Parser
  , Command = mingy.Command
  , http = require('http')
  , url = require('url')
  , querystring = require('querystring')

var parser = new Parser()

// define commands (which function as routes)
parser.addCommand('home')
.set('syntax', ['GET', 'POST'])
.set('logic', function(args, env) {

  var output = ''

  if (env.request.method == 'GET') {

    output += '
Hello World!
'+
              '
Check out the news.
'+
              '
Add Story
'+
              '<form action="/" method="post">'+
              '
Slug: <input type="text" name="slug" />
'+
              '
Title: <input type="text" name="title" />
'+
              '
Body: <textarea name="body"></textarea>
'+
              '
<input type="submit" value="Post" />
'+
              '</form>'
  }
  else if(env.request.method == 'POST') {

    var dataRaw = ''

    // receive chunks of data
    env.request.on('data', function(data) {
      dataRaw += data.toString()
    })

    // process data
    env.request.on('end', function() {

      // add story to in-memory stories
      var storyData = querystring.parse(dataRaw)
      env.news[storyData.slug] = {
        "title": storyData.title,
        "body": storyData.body
      }

      output += 'Story added. Check out the news.'

      // send response
      env.response.writeHead(200, {'Content-Type': 'text/html'})
      env.response.end(output)
    })
  }

  return output
})

parser.addCommand('news')
.set('syntax', ['GET news', 'GET news <story>'])
.set('logic', function(args, env) {

  var output = ''

  if (args['story']) {

    output += "
" + env.news[args.story].title + "
"
    output += "
" + env.news[args.story].body + "
"
  }
  else {

    output += "
News!
"

    for (var story in env.news) {
      output += "" + env.news[story].title + "
"
    }
  }

  return output
})

// in-memory store of stories
parser.setEnv(
  'news',
  {
    "earthquake": {
      "title": "Horrid Earthquake",
      "body": "The earthquake was depressing."
    },
    "disease": {
      "title": "That Disease isn't such a Problem Anymore",
      "body": "The disease was cured."
    }
  }
)

http.createServer(function (request, response) {

  parser.env['request']  = request
  parser.env['response'] = response

  // dispatch request
  var output = parser.parseLexemes(
    parser.webRequestToLexemes(request)
  )

  // allow POST requests to handle their own output
  if (request.method != 'POST') {
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(output)
  }
}).listen(8000);

console.log('Server running at http://127.0.0.1:8000/');
<commit_msg>Made ugly bit of webserver demo a bit less so.<commit_after>/*

THIS IS A WORK IN PROGRESS...

*/
var mingy = require('../lib/mingy')
  , Parser = mingy.Parser
  , Command = mingy.Command
  , http = require('http')
  , url = require('url')
  , querystring = require('querystring')

var parser = new Parser()

// define commands (which function as routes)
parser.addCommand('home')
.set('syntax', ['<method>'])
.set('logic', function(args, env) {

  var output = ''

  if (args.method == 'GET') {

    output += '
Hello World!
'+
              '
Check out the news.
'+
              '
Add Story
'+
              '<form action="/" method="post">'+
              '
Slug: <input type="text" name="slug" />
'+
              '
Title: <input type="text" name="title" />
'+
              '
Body: <textarea name="body"></textarea>
'+
              '
<input type="submit" value="Post" />
'+
              '</form>'
  }
  else if(args.method == 'POST') {

    var dataRaw = ''

    // receive chunks of data
    env.request.on('data', function(data) {
      dataRaw += data.toString()
    })

    // process data
    env.request.on('end', function() {

      // add story to in-memory stories
      var storyData = querystring.parse(dataRaw)
      env.news[storyData.slug] = {
        "title": storyData.title,
        "body": storyData.body
      }

      output += 'Story added. Check out the news.'

      // send response
      env.response.writeHead(200, {'Content-Type': 'text/html'})
      env.response.end(output)
    })
  }

  return output
})

parser.addCommand('news')
.set('syntax', ['GET news', 'GET news <story>'])
.set('logic', function(args, env) {

  var output = ''

  if (args['story']) {

    output += "
" + env.news[args.story].title + "
"
    output += "
" + env.news[args.story].body + "
"
  }
  else {

    output += "
News!
"

    for (var story in env.news) {
      output += "" + env.news[story].title + "
"
    }
  }

  return output
})

// in-memory store of stories
parser.setEnv(
  'news',
  {
    "earthquake": {
      "title": "Horrid Earthquake",
      "body": "The earthquake was depressing."
    },
    "disease": {
      "title": "That Disease isn't such a Problem Anymore",
      "body": "The disease was cured."
    }
  }
)

http.createServer(function (request, response) {

  parser.env['request']  = request
  parser.env['response'] = response

  // dispatch request
  var output = parser.parseLexemes(
    parser.webRequestToLexemes(request)
  )

  // allow POST requests to handle their own output
  if (request.method != 'POST') {
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(output)
  }
}).listen(8000);

console.log('Server running at http://127.0.0.1:8000/');
<|endoftext|>


<commit_before>var app = {
  pages: {},
  appBoard: $('#appMain'),
  header: $('#appHeader'),
  pageBoard: $('#appBody'),
  mainMenuAsGoBack: false,
  currentPageMgr: undefined,
  pageViewStack: [],

  begin: function() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    document.addEventListener('pause', this.onPause, false);
    document.addEventListener('resume', this.onResume, false);
    document.addEventListener('backbutton', this.onBackKeyDown, false);
    document.addEventListener('menubutton', this.onMenuKeyDown, false);
  },

  onDeviceReady: function() {
    console.log('device is ready to use on ' + device.platform + '. language: ' + navigator.language);
    app.initialize();
  },

  initialize: function() {
    runningOnBrowser = !isValid(device) || device.platform == 'browser';

    $(window).off('resize').on('resize', function(){ app.adjustLayout(); });

    // set up Language Pack
    R.setLocale(navigator.language);

    app.header.find('li:nth-child(1)').off('click').on('click', app.clickMainMenu);
    app.header.find('li:nth-child(2)').html('' + R.text('appTitle') + '');

    // TODO when you need to add a new page, edit following codes.
    app.addPage(pageMain);
    app.addPage(recvMgr);
    app.addPage(sendMgr);

    app.showPage(pageMain);

    $('#mm1').on('click', function(){ app.showPage(pageMain); }).html(R.text('appTitle'));
    $('#mm2').on('click', function(){ app.showPage(recvMgr);  }).html(R.text('recvPage'));
    $('#mm3').on('click', function(){ app.showPage(sendMgr);  }).html(R.text('sendPage'));

    if( !isRunningOnBrowser() && window.plugins && window.plugins.shareit ) {
      window.plugins.shareit.getRecvText(function(data) {
        window.plugins.shareit.clearText();
        app._showNext(data['text']);
      },
      function(error) {
        window.plugins.shareit.clearText();
      });
    } else {
      app._showNext();
    }
  },

  _showNext: function(recvText) {
    var curUrl = location.href;

    if( curUrl.indexOf('/send') > 0 || isValid2(recvText) ) {
      app.showPage(sendMgr, {'text':recvText});
    } else if( curUrl.indexOf('/receive') > 0 ) {
      app.showPage(recvMgr);
    }

    app.adjustLayout();
  },

  adjustLayout: function() {
    const appHeaderHeight = 50;

    var w = $(window).width();
    var h = $(window).height();

    // TODO iOS: consider status bar height. adjust header top padding, header height.

    place(app.appBoard, undefined, undefined, w, h);
    place(app.header, undefined, undefined, w, appHeaderHeight);
    place(app.pageBoard, undefined, undefined, w, h - appHeaderHeight);
    place(app.pageBoard.find('.x-main-view'), undefined, undefined, w, h - appHeaderHeight);

    app.pageBoard.css({'position':'relative', 'top':appHeaderHeight + cUnit});

    for(var x in app.pages) {
      if( app.pages[x].adjustLayout ) {
        app.pages[x].adjustLayout(w, h);
      }
    }
  },

  onPause: function(event) {
    //
  },

  onResume: function(event) {
    console.log('onResum');
    if( window.plugins && window.plugins.shareit ) {
      window.plugins.shareit.getRecvText(function(data) {
        window.plugins.shareit.clearText();
        app.showPage(sendMgr, {'text':data['text']});
      },
      function(error) {
        window.plugins.shareit.clearText();
      });
    }
  },

  onBackKeyDown: function(event) {
    app.goBack();
  },

  onMenuKeyDown: function(event) {
    //
  },

  clickMainMenu: function() {
    if( app.mainMenuAsGoBack ) {
      app.onBackKeyDown();
    } else {
      // TODO
    }
  },

  addPage: function(pageMgr) {
    if( app.pages[pageMgr.getPageID()] ) {
      throw 'already defined page.';
    }

    app.pages[pageMgr.getPageID()] = pageMgr;

    var board = $('

').addClass('x-main-view').attr('id', pageMgr.getPageID()).hide();
    app.pageBoard.append(board);
    pageMgr.initialize(board);
  },

  showPage: function(pageMrg, options) {
    var pageID = pageMrg.getPageID();
    var newMgr = app.pages[pageID];

    if( newMgr == undefined ) {
      console.log('unregistered page manager: ' + pageID);
      return;
    }

    app.switchHeader(newMgr);
    newMgr.onActivated(app.currentPageMgr, options);

    if( app.currentPageMgr && app.currentPageMgr != newMgr ) {
      app.currentPageMgr.onDeactivated(newMgr);
    }

    app.pageBoard.find('.x-main-view').hide();
    app.pageBoard.find('#' + pageID).show();

    if( app.currentPageMgr && app.currentPageMgr.isMainContent && app.currentPageMgr.isMainContent() ) {
      if( app.pageViewStack.length <= 0 || app.pageViewStack[app.pageViewStack.length - 1] != app.currentPageMgr ) {
        app.pageViewStack.push(app.currentPageMgr);
      }
    }

    app.currentPageMgr = newMgr;
  },

  switchHeader: function(pageMgr) {
    var hi = pageMgr.getHeaderInfo();

    if( hi['mainButton'] == 'back' ) {
      app.header.find('li:nth-child(1)').html('').off('click').on('click', app.clickMainMenu);
      app.mainMenuAsGoBack = true;
    } else {
      app.header.find('li:nth-child(1)').html('').off('click').on('click', app.clickMainMenu);
      app.mainMenuAsGoBack = false;
    }

    app.header.find('li:nth-child(2)').html('' + hi['title'] + '');
  },

  goBack: function() {
    if( app.pageViewStack.length < 1 ) { return; }

    app.showPage(app.pageViewStack.pop());
  }
};

app.begin();
<commit_msg>minor bug fixed<commit_after>var app = {
  pages: {},
  appBoard: $('#appMain'),
  header: $('#appHeader'),
  pageBoard: $('#appBody'),
  mainMenuAsGoBack: false,
  currentPageMgr: undefined,
  pageViewStack: [],

  begin: function() {
    document.addEventListener('deviceready', this.onDeviceReady.bind(this), false);
    document.addEventListener('pause', this.onPause, false);
    document.addEventListener('resume', this.onResume, false);
    document.addEventListener('backbutton', this.onBackKeyDown, false);
    document.addEventListener('menubutton', this.onMenuKeyDown, false);
  },

  onDeviceReady: function() {
    console.log('device is ready to use on ' + device.platform + '. language: ' + navigator.language);
    app.initialize();
  },

  initialize: function() {
    runningOnBrowser = !isValid(device) || device.platform == 'browser';

    $(window).off('resize').on('resize', function(){ app.adjustLayout(); });

    // set up Language Pack
    R.setLocale(navigator.language);

    app.header.find('li:nth-child(1)').off('click').on('click', app.clickMainMenu);
    app.header.find('li:nth-child(2)').html('' + R.text('appTitle') + '');

    // TODO when you need to add a new page, edit following codes.
    app.addPage(pageMain);
    app.addPage(recvMgr);
    app.addPage(sendMgr);

    app.showPage(pageMain);

    $('#mm1').on('click', function(){ app.showPage(pageMain); }).html(R.text('appTitle'));
    $('#mm2').on('click', function(){ app.showPage(recvMgr);  }).html(R.text('recvPage'));
    $('#mm3').on('click', function(){ app.showPage(sendMgr);  }).html(R.text('sendPage'));

    if( !isRunningOnBrowser() && window.plugins && window.plugins.shareit ) {
      window.plugins.shareit.getRecvText(function(data) {
        window.plugins.shareit.clearText();
        app._showNext(data['text']);
      },
      function(error) {
        window.plugins.shareit.clearText();
      });
    } else {
      app._showNext();
    }
  },

  _showNext: function(recvText) {
    var curUrl = location.href;

    if( curUrl.indexOf('/send') > 0 || isValid2(recvText) ) {
      app.showPage(sendMgr, {'text':recvText});
    } else if( curUrl.indexOf('/receive') > 0 ) {
      app.showPage(recvMgr);
    }

    app.adjustLayout();
  },

  adjustLayout: function() {
    const appHeaderHeight = 50;

    var w = $(window).width();
    var h = $(window).height();

    // TODO iOS: consider status bar height. adjust header top padding, header height.

    place(app.appBoard, undefined, undefined, w, h);
    place(app.header, undefined, undefined, w, appHeaderHeight);
    place(app.pageBoard, undefined, undefined, w, h - appHeaderHeight);
    place(app.pageBoard.find('.x-main-view'), undefined, undefined, w, h - appHeaderHeight);

    app.pageBoard.css({'position':'relative', 'top':appHeaderHeight + cUnit});

    for(var x in app.pages) {
      if( app.pages[x].adjustLayout ) {
        app.pages[x].adjustLayout(w, h);
      }
    }
  },

  onPause: function(event) {
    //
  },

  onResume: function(event) {
    if( !isRunningOnBrowser() && window.plugins && window.plugins.shareit ) {
      window.plugins.shareit.getRecvText(function(data) {
        window.plugins.shareit.clearText();
        app.showPage(sendMgr, {'text':data['text']});
      },
      function(error) {
        window.plugins.shareit.clearText();
      });
    }
  },

  onBackKeyDown: function(event) {
    app.goBack();
  },

  onMenuKeyDown: function(event) {
    //
  },

  clickMainMenu: function() {
    if( app.mainMenuAsGoBack ) {
      app.onBackKeyDown();
    } else {
      // TODO
    }
  },

  addPage: function(pageMgr) {
    if( app.pages[pageMgr.getPageID()] ) {
      throw 'already defined page.';
    }

    app.pages[pageMgr.getPageID()] = pageMgr;

    var board = $('

').addClass('x-main-view').attr('id', pageMgr.getPageID()).hide();
    app.pageBoard.append(board);
    pageMgr.initialize(board);
  },

  showPage: function(pageMrg, options) {
    var pageID = pageMrg.getPageID();
    var newMgr = app.pages[pageID];

    if( newMgr == undefined ) {
      console.log('unregistered page manager: ' + pageID);
      return;
    }

    app.switchHeader(newMgr);
    newMgr.onActivated(app.currentPageMgr, options);

    if( app.currentPageMgr && app.currentPageMgr != newMgr ) {
      app.currentPageMgr.onDeactivated(newMgr);
    }

    app.pageBoard.find('.x-main-view').hide();
    app.pageBoard.find('#' + pageID).show();

    if( app.currentPageMgr && app.currentPageMgr.isMainContent && app.currentPageMgr.isMainContent() ) {
      if( app.pageViewStack.length <= 0 || app.pageViewStack[app.pageViewStack.length - 1] != app.currentPageMgr ) {
        app.pageViewStack.push(app.currentPageMgr);
      }
    }

    app.currentPageMgr = newMgr;
  },

  switchHeader: function(pageMgr) {
    var hi = pageMgr.getHeaderInfo();

    if( hi['mainButton'] == 'back' ) {
      app.header.find('li:nth-child(1)').html('').off('click').on('click', app.clickMainMenu);
      app.mainMenuAsGoBack = true;
    } else {
      app.header.find('li:nth-child(1)').html('').off('click').on('click', app.clickMainMenu);
      app.mainMenuAsGoBack = false;
    }

    app.header.find('li:nth-child(2)').html('' + hi['title'] + '');
  },

  goBack: function() {
    if( app.pageViewStack.length < 1 ) { return; }

    app.showPage(app.pageViewStack.pop());
  }
};

app.begin();
<|endoftext|>


<commit_before>var fs = require('fs'),
    events = require('events'),
    buffer = require('buffer'),
    http = require('http'),
    url = require('url'),
    path = require('path');

this.version = [0, 5, 3];

var mime = require('./node-static/mime');
var util = require('./node-static/util');

var serverInfo = 'node-static/' + this.version.join('.');

// In-memory file store
this.store = {};
this.indexStore = {};

this.Server = function (root, options) {
    if (root && (typeof(root) === 'object')) { options = root, root = null }

    this.root    = path.normalize(root || '.');
    this.options = options || {};
    this.cache   = 3600;

    this.defaultHeaders  = {};
    this.options.headers = this.options.headers || {};
    this.options.AutoIndex = this.options.AutoIndex || false;

    if ('cache' in this.options) {
        if (typeof(this.options.cache) === 'number') {
            this.cache = this.options.cache;
        } else if (! this.options.cache) {
            this.cache = false;
        }
    }

    if (this.cache !== false) {
        this.defaultHeaders['Cache-Control'] = 'max-age=' + this.cache;
    }
    this.defaultHeaders['Server'] = serverInfo;

    for (var k in this.defaultHeaders) {
        this.options.headers[k] = this.options.headers[k] ||
                                  this.defaultHeaders[k];
    }
};

this.Server.prototype.serveDir = function (pathname, req, res, finish) {
    var htmlIndex = path.join(pathname, 'index.html'),
        that = this;

    fs.stat(htmlIndex, function (e, stat) {
        if (!e) {
            that.respond(null, 200, {}, [htmlIndex], stat, req, res, finish);
        } else {
            if (pathname in exports.store) {
                streamFiles(exports.indexStore[pathname].files);
            } else {
                // Stream a directory of files as a single file.
                fs.readFile(path.join(pathname, 'index.json'), function (e, contents) {
                    if (e) {
                      if (that.options.AutoIndex === true || that.options.AutoIndex === "true") {
                        return that.serveAutoIndex(pathname, res, req, finish);
                      } else {
                        return finish(404, {});
                      }
                    }
                    var index = JSON.parse(contents);
                    exports.indexStore[pathname] = index;
                    streamFiles(index.files);
                });
            }
        }
    });
    function streamFiles(files) {
        util.mstat(pathname, files, function (e, stat) {
            that.respond(pathname, 200, {}, files, stat, req, res, finish);
        });
    }
};
this.Server.prototype.serveFile = function (pathname, status, headers, req, res) {
    var that = this;
    var promise = new(events.EventEmitter);

    pathname = this.normalize(pathname);

    fs.stat(pathname, function (e, stat) {
        if (e) {
            return promise.emit('error', e);
        }
        that.respond(null, status, headers, [pathname], stat, req, res, function (status, headers) {
            that.finish(status, headers, req, res, promise);
        });
    });
    return promise;
};
this.Server.prototype.finish = function (status, headers, req, res, promise, callback) {
    var result = {
        status:  status,
        headers: headers,
        message: http.STATUS_CODES[status]
    };

    headers['Server'] = serverInfo;

    if (!status || status >= 400) {
        if (callback) {
            callback(result);
        } else {
            if (promise.listeners('error').length > 0) {
                promise.emit('error', result);
            }
            res.writeHead(status, headers);
            res.end();
        }
    } else {
        // Don't end the request here, if we're streaming;
        // it's taken care of in `prototype.stream`.
        if (status !== 200 || req.method !== 'GET') {
            res.writeHead(status, headers);
            res.end();
        }
        callback && callback(null, result);
        promise.emit('success', result);
    }
};

this.Server.prototype.servePath = function (pathname, status, headers, req, res, finish) {
    var that = this,
        promise = new(events.EventEmitter);

    pathname = this.normalize(pathname);
    // Only allow GET and HEAD requests
    if (req.method !== 'GET' && req.method !== 'HEAD') {
        finish(405, { 'Allow': 'GET, HEAD' });
        return promise;
    }

    // Make sure we're not trying to access a
    // file outside of the root.
    if (new(RegExp)('^' + that.root).test(pathname)) {
        fs.stat(pathname, function (e, stat) {
            if (e) {
                finish(404, {});
            } else if (stat.isFile()) {      // Stream a single file.
                that.respond(null, status, headers, [pathname], stat, req, res, finish);
            } else if (stat.isDirectory()) { // Stream a directory of files.
                that.serveDir(pathname, req, res, finish);
            } else {
                finish(400, {});
            }
        });
    } else {
        // Forbidden
        finish(403, {});
    }
    return promise;
};
this.Server.prototype.normalize = function (pathname) {
    return path.normalize(path.join(this.root, pathname));
};
this.Server.prototype.serve = function (req, res, callback) {
    var that = this,
        promise = new(events.EventEmitter);

    var pathname = url.parse(req.url).pathname;

    var finish = function (status, headers) {
        that.finish(status, headers, req, res, promise, callback);
    };

    process.nextTick(function () {
        that.servePath(pathname, 200, {}, req, res, finish).on('success', function (result) {
            promise.emit('success', result);
        }).on('error', function (err) {
            promise.emit('error');
        });
    });
    if (! callback) { return promise }
};

this.Server.prototype.respond = function (pathname, status, _headers, files, stat, req, res, finish) {
    var mtime   = Date.parse(stat.mtime),
        key     = pathname || files[0],
        headers = {};
    // Copy default headers
    for (var k in this.options.headers) {  headers[k] = this.options.headers[k] }

    headers['Etag']          = JSON.stringify([stat.ino, stat.size, mtime].join('-'));
    headers['Date']          = new(Date)().toUTCString();
    headers['Last-Modified'] = new(Date)(stat.mtime).toUTCString();

    // Conditional GET
    // If both the "If-Modified-Since" and "If-None-Match" headers
    // match the conditions, send a 304 Not Modified.
    if (req.headers['if-none-match'] === headers['Etag'] &&
        Date.parse(req.headers['if-modified-since']) >= mtime) {
        finish(304, headers);
    } else if (req.method === 'HEAD') {
        finish(200, headers);
    } else {
        headers['Content-Length'] = stat.size;
        headers['Content-Type']   = mime.contentTypes[path.extname(files[0]).slice(1)] ||
                                   'application/octet-stream';

        for (var k in headers) { _headers[k] = headers[k] }

        res.writeHead(status, _headers);

        // If the file was cached and it's not older
        // than what's on disk, serve the cached version.
        if (this.cache && (key in exports.store) &&
            exports.store[key].stat.mtime >= stat.mtime) {
            res.end(exports.store[key].buffer);
            finish(status, _headers);
        } else {
            this.stream(pathname, files, new(buffer.Buffer)(stat.size), res, function (e, buffer) {
                if (e) {
                  return finish(200, {});
                }
                exports.store[key] = {
                    stat:      stat,
                    buffer:    buffer,
                    timestamp: Date.now()
                };
                finish(status, _headers);
            });
        }
    }
};
this.Server.prototype.serveAutoIndex = function (dirPath, res, req, finish) {
 var html,
     self = this,
     newPath;
 html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\
 "http://www.w3.org/TR/html4/loose.dtd">\
  \
   \
   <title>Index of ' + dirPath +'</title> \
   \
   \

Index of ' + dirPath + '
';
 html += '
';
  newPath = dirPath.replace(self.root, '');
  if (newPath[newPath.length - 1] !== '/') {
    newPath += '/';
  }
 fs.readdir(dirPath, function(err, result) {
   if (err) { return finish(404, {})}
   result.forEach(function(v, i) {
     html += ('
' + '' + v + '
');
   });
   html += '
';
   html += '\
   <address>Node.js ' + process.version + ' http-server server running @ ' + req.headers.host + '</address> \
   ';
   res.writeHead(200, { "Content-Type": "text/html" });
   res.write(html);
   res.end();
 });
};
this.Server.prototype.stream = function (pathname, files, buffer, res, callback) {
    (function streamFile(files, offset) {
        var file = files.shift();
        if (file) {
            // Stream the file to the client
            if (file[0] === '/') {
              file = '/' + path.join(pathname || '.', file);;
            }
            else {
              file = path.join(pathname || '.', file);
            }
            fs.createReadStream(file, {
                flags: 'r',
                encoding: 'binary',
                mode: 0666,
                bufferSize: 4096
            }).addListener('data', function (chunk) {
                buffer.write(chunk, offset, 'binary');
                res.write   (chunk, 'binary');
                offset    += chunk.length;
            }).addListener('close', function () {
                streamFile(files, offset);
            }).addListener('error', function (err) {
                callback(err);
                console.error(err);
            });
        } else {
            res.end();
            callback(null, buffer, offset);
        }
    })(files.slice(0), 0);
};
<commit_msg>[fix] Fix to nested subdirectory paths in links.<commit_after>var fs = require('fs'),
    events = require('events'),
    buffer = require('buffer'),
    http = require('http'),
    url = require('url'),
    path = require('path');

this.version = [0, 5, 3];

var mime = require('./node-static/mime');
var util = require('./node-static/util');

var serverInfo = 'node-static/' + this.version.join('.');

// In-memory file store
this.store = {};
this.indexStore = {};

this.Server = function (root, options) {
    if (root && (typeof(root) === 'object')) { options = root, root = null }

    this.root    = path.normalize(root || '.');
    this.options = options || {};
    this.cache   = 3600;

    this.defaultHeaders  = {};
    this.options.headers = this.options.headers || {};
    this.options.AutoIndex = this.options.AutoIndex || false;

    if ('cache' in this.options) {
        if (typeof(this.options.cache) === 'number') {
            this.cache = this.options.cache;
        } else if (! this.options.cache) {
            this.cache = false;
        }
    }

    if (this.cache !== false) {
        this.defaultHeaders['Cache-Control'] = 'max-age=' + this.cache;
    }
    this.defaultHeaders['Server'] = serverInfo;

    for (var k in this.defaultHeaders) {
        this.options.headers[k] = this.options.headers[k] ||
                                  this.defaultHeaders[k];
    }
};

this.Server.prototype.serveDir = function (pathname, req, res, finish) {
    var htmlIndex = path.join(pathname, 'index.html'),
        that = this;

    fs.stat(htmlIndex, function (e, stat) {
        if (!e) {
            that.respond(null, 200, {}, [htmlIndex], stat, req, res, finish);
        } else {
            if (pathname in exports.store) {
                streamFiles(exports.indexStore[pathname].files);
            } else {
                // Stream a directory of files as a single file.
                fs.readFile(path.join(pathname, 'index.json'), function (e, contents) {
                    if (e) {
                      if (that.options.AutoIndex === true || that.options.AutoIndex === "true") {
                        return that.serveAutoIndex(pathname, res, req, finish);
                      } else {
                        return finish(404, {});
                      }
                    }
                    var index = JSON.parse(contents);
                    exports.indexStore[pathname] = index;
                    streamFiles(index.files);
                });
            }
        }
    });
    function streamFiles(files) {
        util.mstat(pathname, files, function (e, stat) {
            that.respond(pathname, 200, {}, files, stat, req, res, finish);
        });
    }
};
this.Server.prototype.serveFile = function (pathname, status, headers, req, res) {
    var that = this;
    var promise = new(events.EventEmitter);

    pathname = this.normalize(pathname);

    fs.stat(pathname, function (e, stat) {
        if (e) {
            return promise.emit('error', e);
        }
        that.respond(null, status, headers, [pathname], stat, req, res, function (status, headers) {
            that.finish(status, headers, req, res, promise);
        });
    });
    return promise;
};
this.Server.prototype.finish = function (status, headers, req, res, promise, callback) {
    var result = {
        status:  status,
        headers: headers,
        message: http.STATUS_CODES[status]
    };

    headers['Server'] = serverInfo;

    if (!status || status >= 400) {
        if (callback) {
            callback(result);
        } else {
            if (promise.listeners('error').length > 0) {
                promise.emit('error', result);
            }
            res.writeHead(status, headers);
            res.end();
        }
    } else {
        // Don't end the request here, if we're streaming;
        // it's taken care of in `prototype.stream`.
        if (status !== 200 || req.method !== 'GET') {
            res.writeHead(status, headers);
            res.end();
        }
        callback && callback(null, result);
        promise.emit('success', result);
    }
};

this.Server.prototype.servePath = function (pathname, status, headers, req, res, finish) {
    var that = this,
        promise = new(events.EventEmitter);

    pathname = this.normalize(pathname);
    // Only allow GET and HEAD requests
    if (req.method !== 'GET' && req.method !== 'HEAD') {
        finish(405, { 'Allow': 'GET, HEAD' });
        return promise;
    }

    // Make sure we're not trying to access a
    // file outside of the root.
    if (new(RegExp)('^' + that.root).test(pathname)) {
        fs.stat(pathname, function (e, stat) {
            if (e) {
                finish(404, {});
            } else if (stat.isFile()) {      // Stream a single file.
                that.respond(null, status, headers, [pathname], stat, req, res, finish);
            } else if (stat.isDirectory()) { // Stream a directory of files.
                that.serveDir(pathname, req, res, finish);
            } else {
                finish(400, {});
            }
        });
    } else {
        // Forbidden
        finish(403, {});
    }
    return promise;
};
this.Server.prototype.normalize = function (pathname) {
    return path.normalize(path.join(this.root, pathname));
};
this.Server.prototype.serve = function (req, res, callback) {
    var that = this,
        promise = new(events.EventEmitter);

    var pathname = url.parse(req.url).pathname;

    var finish = function (status, headers) {
        that.finish(status, headers, req, res, promise, callback);
    };

    process.nextTick(function () {
        that.servePath(pathname, 200, {}, req, res, finish).on('success', function (result) {
            promise.emit('success', result);
        }).on('error', function (err) {
            promise.emit('error');
        });
    });
    if (! callback) { return promise }
};

this.Server.prototype.respond = function (pathname, status, _headers, files, stat, req, res, finish) {
    var mtime   = Date.parse(stat.mtime),
        key     = pathname || files[0],
        headers = {};
    // Copy default headers
    for (var k in this.options.headers) {  headers[k] = this.options.headers[k] }

    headers['Etag']          = JSON.stringify([stat.ino, stat.size, mtime].join('-'));
    headers['Date']          = new(Date)().toUTCString();
    headers['Last-Modified'] = new(Date)(stat.mtime).toUTCString();

    // Conditional GET
    // If both the "If-Modified-Since" and "If-None-Match" headers
    // match the conditions, send a 304 Not Modified.
    if (req.headers['if-none-match'] === headers['Etag'] &&
        Date.parse(req.headers['if-modified-since']) >= mtime) {
        finish(304, headers);
    } else if (req.method === 'HEAD') {
        finish(200, headers);
    } else {
        headers['Content-Length'] = stat.size;
        headers['Content-Type']   = mime.contentTypes[path.extname(files[0]).slice(1)] ||
                                   'application/octet-stream';

        for (var k in headers) { _headers[k] = headers[k] }

        res.writeHead(status, _headers);

        // If the file was cached and it's not older
        // than what's on disk, serve the cached version.
        if (this.cache && (key in exports.store) &&
            exports.store[key].stat.mtime >= stat.mtime) {
            res.end(exports.store[key].buffer);
            finish(status, _headers);
        } else {
            this.stream(pathname, files, new(buffer.Buffer)(stat.size), res, function (e, buffer) {
                if (e) {
                  return finish(200, {});
                }
                exports.store[key] = {
                    stat:      stat,
                    buffer:    buffer,
                    timestamp: Date.now()
                };
                finish(status, _headers);
            });
        }
    }
};
this.Server.prototype.serveAutoIndex = function (dirPath, res, req, finish) {
 var html,
     self = this,
     urlBase = '',
     newPath;
 html = '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"\
 "http://www.w3.org/TR/html4/loose.dtd">\
  \
   \
   <title>Index of ' + dirPath +'</title> \
   \
   \

Index of ' + dirPath + '
';
 html += '
';
  urlBase = dirPath.replace(self.root, '');
  newPath = (urlBase.split('/').length > 1)
            ? urlBase.split('/').pop()
            : urlBase;
  if (newPath[newPath.length - 1] !== '/') {
    newPath += '/';
  }
 fs.readdir(dirPath, function(err, result) {
   if (err) { return finish(404, {})}
   result.forEach(function(v, i) {
     html += ('
' + '' + v + '
');
   });
   html += '
';
   html += '\
   <address>Node.js ' + process.version + ' http-server server running @ ' + req.headers.host + '</address> \
   ';
   res.writeHead(200, { "Content-Type": "text/html" });
   res.write(html);
   res.end();
 });
};
this.Server.prototype.stream = function (pathname, files, buffer, res, callback) {
    (function streamFile(files, offset) {
        var file = files.shift();
        if (file) {
            // Stream the file to the client
            if (file[0] === '/') {
              file = '/' + path.join(pathname || '.', file);;
            }
            else {
              file = path.join(pathname || '.', file);
            }
            fs.createReadStream(file, {
                flags: 'r',
                encoding: 'binary',
                mode: 0666,
                bufferSize: 4096
            }).addListener('data', function (chunk) {
                buffer.write(chunk, offset, 'binary');
                res.write   (chunk, 'binary');
                offset    += chunk.length;
            }).addListener('close', function () {
                streamFile(files, offset);
            }).addListener('error', function (err) {
                callback(err);
                console.error(err);
            });
        } else {
            res.end();
            callback(null, buffer, offset);
        }
    })(files.slice(0), 0);
};
<|endoftext|>


<commit_before>
var queryPage="server.php"
var geoObj=null
var resultsId=null
var resultsObj=null

function initialise()
{
	getLocation()
    hideResults()
}

function hideHome()
{
	//This is to be replaced with a fancier style e.g.

	var homeScreen=$("#home")
	homeScreen.css("display", "none")

}

function hideResults()
{
	//This is to be replaced with a fancier style e.g.

	$("#resultsdiv").hide()

}
function setGeoObject(object)
{
	geoObj=object

}
function getLocation()
{
	if (navigator.geolocation)
	{
		navigator.geolocation.getCurrentPosition(setGeoObject)
	}
}

function showResults(show)
{
	var resultsBox=$("#resultscontainer")
	if (!show)
	{

		resultsBox.css("display", "none")
	}else{
		resultsBox.css("display", "block")
	}

}

function showError(show)
{
	var errorMessage=$("#errormessage")

	if (show)
	{
		errorMessage.css("display", "block")
	}else{

		errorMessage.css("display", "none")
	}
}

function sendSearch(boxid)
{

	var sendQuery=$.trim($("#"+boxid).val())
	if (sendQuery!=null && sendQuery!="")
	{
		//Delete all cards and possible error
		cardRemoveAll()
		showError(false)
		showResults(false)
		showLoading(true)

		$.get(queryPage, { query: sendQuery, lat: geoObj.coords.latitude, lon: geoObj.coords.longitude }, function(data)
		{

			showLoading(false)
			showResults(true)
			if (data!="-1")
			{
				resultsObj=data

				Object.keys(resultsObj).forEach(function(key) {
					//Here you will need to add a card for each result...
					cardAdd(resultsObj[key])

				})
			}else{
				showError(true)
				showResults(false)

			}

		})

	}
    else
    {
        return -1 // no search query entered
    }

}

//Do simulations of the div adding functions and whatnot

function showLoading(show)
{
	var loadGif=$("#loading")
	if (show)
	{
		loadGif.css("display", "block")
	}else{
		loadGif.css("display", "none")
	}
}

function cardRemoveAll()
{

	$(function(){
	  $("div.card").remove()
	  $("div.smallcard").remove()
	})

}

function setResultsToHome()
{
	$("#searchterm").val($("#homesearch").val())

}
<commit_msg>Fixed support for devices with no geolocation<commit_after>
var queryPage="server.php"
var geoObj=null
var resultsId=null
var resultsObj=null

function initialise()
{
	getLocation()
    hideResults()
}

function hideHome()
{
	//This is to be replaced with a fancier style e.g.

	var homeScreen=$("#home")
	homeScreen.css("display", "none")

}

function hideResults()
{
	//This is to be replaced with a fancier style e.g.

	$("#resultsdiv").hide()

}
function setGeoObject(object)
{
	geoObj=object

}
function getLocation()
{
	if (navigator.geolocation)
	{
		navigator.geolocation.getCurrentPosition(setGeoObject)
	}
    else
    {
        geoObj={coords:{latitude:"",longitude:""}}
    }
}

function showResults(show)
{
	var resultsBox=$("#resultscontainer")
	if (!show)
	{

		resultsBox.css("display", "none")
	}else{
		resultsBox.css("display", "block")
	}

}

function showError(show)
{
	var errorMessage=$("#errormessage")

	if (show)
	{
		errorMessage.css("display", "block")
	}else{

		errorMessage.css("display", "none")
	}
}

function sendSearch(boxid)
{

	var sendQuery=$.trim($("#"+boxid).val())
	if (sendQuery!=null && sendQuery!="")
	{
		//Delete all cards and possible error
		cardRemoveAll()
		showError(false)
		showResults(false)
		showLoading(true)

		$.get(queryPage, { query: sendQuery, lat: geoObj.coords.latitude, lon: geoObj.coords.longitude }, function(data)
		{

			showLoading(false)
			showResults(true)
			if (data!="-1")
			{
				resultsObj=data

				Object.keys(resultsObj).forEach(function(key) {
					//Here you will need to add a card for each result...
					cardAdd(resultsObj[key])

				})
			}else{
				showError(true)
				showResults(false)

			}

		})

	}
    else
    {
        return -1 // no search query entered
    }

}

//Do simulations of the div adding functions and whatnot

function showLoading(show)
{
	var loadGif=$("#loading")
	if (show)
	{
		loadGif.css("display", "block")
	}else{
		loadGif.css("display", "none")
	}
}

function cardRemoveAll()
{

	$(function(){
	  $("div.card").remove()
	  $("div.smallcard").remove()
	})

}

function setResultsToHome()
{
	$("#searchterm").val($("#homesearch").val())

}
<|endoftext|>


<commit_before>if (typeof Test == 'undefined') {
    Test = {};
}
if (typeof Test.TAP == 'undefined') {
    if (typeof JSAN != 'undefined') {
        JSAN.use('Test.TAP');
    } else {
        throw new ReferenceError('Test.TAP.Runner is dependent on Test.TAP');
    }
}

/*

=head1 NAME

    Test.TAP.Runner - A Simple Test Harness for Test.TAP

=head1 Synopsis

    var r = new Test.TAP.Runner().

    var testobj = {};
    testobj.runtests = function() {
        var t = new Test.TAP();
        t.plan(2);
        t.ok(true, 'true is true');
        t.is(1, 1, 'one is one');
        return t;
    }
    r.run_tests(obj);
=cut

*/

Test.TAP.Class = function() {
    var self = this;
    // call our superclasses constructor as well
    Test.TAP.apply(self, arguments);
};

/*

=head1 Methods

=head2 out()

internal method inherited from L<Test.TAP> see L<Test.TAP> for useage

=cut

=head2 diag()

internal method inherited from L<Test.TAP> see L<Test.TAP> for useage

=cut

=head2 run_it()

runs the tests in a test object and reports on the results

=cut

*/

Test.TAP.Class.prototype = new Test.TAP();

Test.TAP.Class.prototype.run_it = function(method) {
    var self = this;
    var fun = self[method];
    self.diag("trying to run "+method+" tests");
    try {
        if (typeof this.setup == 'function') {
            self.setup();
        }
        fun.call(self);
        if (typeof this.teardown == 'function') {
            self.teardown();
        }
    }
    catch(err) {
        this.diag("Test Suite Crashed!!! (" + err + ")");
    }
};

/*

=head2 run_tests()

    r.run_tests(obj1, obj2);

runs the tests in a list of test objects and reports on the results

=cut

*/

Test.TAP.Class.prototype.run_tests = function() {
    var self = this;
    var counter = 0;

    var methods = [];
    for (m in self) {
        if (m.match(/^test.+/)) {
            methods.push(m)
        }
    }

    this.finished = true;

    var onFinish = function () {
        if (self.planned > self.counter) {
            self.diag('looks like you planned ' + self.planned + ' tests but only ran '
            + self.counter + ' tests');
        } else if (self.planned < self.counter) {
            self.diag('looks like you planned ' + self.planned + ' tests but ran '
            + (self.counter - self.planned) + ' tests extra');
        }
        self.diag('ran ' + self.counter + ' tests out of ' + self.planned);
        self.diag('passed ' + self.passed + ' tests out of ' + self.planned)
        self.diag('failed ' + self.failed + ' tests out of ' + self.planned)
    }

    var count = 0;
    var testRunInterval
    if (typeof setInterval == 'undefined') {
        setInterval = function() {
        };
    }
    if (typeof clearInterval == 'undefined') {
        clearInterval = function() {
        }
    }
    var run = function () {
        if(self.finished) {
            if(count > 0) {
                if(self.on_finished) {
                    onFinish()
                    self.on_finished()
                }
            }
            if(methods.length == 0) {
                clearInterval(testRunInterval)
                if(self.on_finished_all) {
                    self.on_finished_all()
                }
            } else {
                self.finished = false;
            }
        } else {
            if(self.planned == "no_plan" || self.planned == 0 || self.counter >= self.planned) {
                self.finished = true
            }
        }
    };
    testRunInterval = setInterval(run, 10)
    run();
    var methodname;
    while (methodname = methods.shift()) {
        self.run_it(methodname);
        count++
    }

    return self;
};
<commit_msg>added license info to TAP/Class.js<commit_after>if (typeof Test == 'undefined') {
    Test = {};
}
if (typeof Test.TAP == 'undefined') {
    if (typeof JSAN != 'undefined') {
        JSAN.use('Test.TAP');
    } else {
        throw new ReferenceError('Test.TAP.Runner is dependent on Test.TAP');
    }
}

/*

=head1 NAME

    Test.TAP.Runner - A Simple Test Harness for Test.TAP

=head1 Synopsis

    var r = new Test.TAP.Runner().

    var testobj = {};
    testobj.runtests = function() {
        var t = new Test.TAP();
        t.plan(2);
        t.ok(true, 'true is true');
        t.is(1, 1, 'one is one');
        return t;
    }
    r.run_tests(obj);
=cut

*/

Test.TAP.Class = function() {
    var self = this;
    // call our superclasses constructor as well
    Test.TAP.apply(self, arguments);
};

/*

=head1 Methods

=head2 out()

internal method inherited from L<Test.TAP> see L<Test.TAP> for useage

=cut

=head2 diag()

internal method inherited from L<Test.TAP> see L<Test.TAP> for useage

=cut

=head2 run_it()

runs the tests in a test object and reports on the results

=cut

*/

Test.TAP.Class.prototype = new Test.TAP();

Test.TAP.Class.prototype.run_it = function(method) {
    var self = this;
    var fun = self[method];
    self.diag("trying to run "+method+" tests");
    try {
        if (typeof this.setup == 'function') {
            self.setup();
        }
        fun.call(self);
        if (typeof this.teardown == 'function') {
            self.teardown();
        }
    }
    catch(err) {
        this.diag("Test Suite Crashed!!! (" + err + ")");
    }
};

/*

=head2 run_tests()

    r.run_tests(obj1, obj2);

runs the tests in a list of test objects and reports on the results

=cut

*/

Test.TAP.Class.prototype.run_tests = function() {
    var self = this;
    var counter = 0;

    var methods = [];
    for (m in self) {
        if (m.match(/^test.+/)) {
            methods.push(m)
        }
    }

    this.finished = true;

    var onFinish = function () {
        if (self.planned > self.counter) {
            self.diag('looks like you planned ' + self.planned + ' tests but only ran '
            + self.counter + ' tests');
        } else if (self.planned < self.counter) {
            self.diag('looks like you planned ' + self.planned + ' tests but ran '
            + (self.counter - self.planned) + ' tests extra');
        }
        self.diag('ran ' + self.counter + ' tests out of ' + self.planned);
        self.diag('passed ' + self.passed + ' tests out of ' + self.planned)
        self.diag('failed ' + self.failed + ' tests out of ' + self.planned)
    }

    var count = 0;
    var testRunInterval
    if (typeof setInterval == 'undefined') {
        setInterval = function() {
        };
    }
    if (typeof clearInterval == 'undefined') {
        clearInterval = function() {
        }
    }
    var run = function () {
        if(self.finished) {
            if(count > 0) {
                if(self.on_finished) {
                    onFinish()
                    self.on_finished()
                }
            }
            if(methods.length == 0) {
                clearInterval(testRunInterval)
                if(self.on_finished_all) {
                    self.on_finished_all()
                }
            } else {
                self.finished = false;
            }
        } else {
            if(self.planned == "no_plan" || self.planned == 0 || self.counter >= self.planned) {
                self.finished = true
            }
        }
    };
    testRunInterval = setInterval(run, 10)
    run();
    var methodname;
    while (methodname = methods.shift()) {
        self.run_it(methodname);
        count++
    }

    return self;
};

/*

=head1 SEE ALSO

L<Test.Simple>
L<Test.AnotherWay>

=head1 AUTHOR

Jeremy Wall L<< jeremy@marzhillstudios.com >>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2007 Jeremy Wall

This library is free software; you can redistribute it and/or modify
it under the same terms as Perl itself, either Perl version 5.8.4 or,
at your option, any later version of Perl 5 you may have available.

=cut

*/
<|endoftext|>


<commit_before>// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * A jsfs.Entry subclass that proxies to a wam file system connected via a
 * wam.Channel.
 *
 * @param {wam.Channel} channel The channel hosting the wam file system.
 */
wam.jsfs.RemoteFileSystem = function(channel) {
  wam.jsfs.Entry.call(this);

  this.channel = channel;
  this.channel.readyBinding.onReady.addListener(this.onChannelReady_, this);

  this.remoteName = null;

  this.handshakeRequest_ = null;
  this.remoteFileSystem_ = null;

  this.pendingOperations_ = [];

  this.onReady = new lib.Event();
  this.onClose = new lib.Event();

  if (this.channel.readyBinding.isReadyState('READY'))
    this.offerHandshake();
};

/**
 * We're an Entry subclass that is able to FORWARD and LIST.
 */
wam.jsfs.RemoteFileSystem.prototype = wam.jsfs.Entry.subclass(
    ['FORWARD', 'LIST']);

/**
 * Return a wam 'stat' value for the FileSystem itself.
 *
 * This is a jsfs.Entry method needed as part of the 'LIST' action.
 */
wam.jsfs.RemoteFileSystem.prototype.getStat = function(onSuccess, onError) {
  var readyState = 'UNEDFINED';
  if (this.remoteFileSystem_)
    readyState = this.remoteFileSystem_.readyState;

  wam.async(onSuccess,
            [null,
             {abilities: this.abilities,
              state: readyState,
              channel: this.channel.name,
              source: 'wamfs'
             }]);
};

/**
 * Reconnect the wam.Channel if necessary, then offer a wam.FileSystem
 * 'handshake' message.
 *
 * @param {function()} onSuccess
 * @param {function(wam.Error)} onError
 */
wam.jsfs.RemoteFileSystem.prototype.connect = function(onSuccess, onError) {
  if (this.remoteFileSystem_ && this.remoteFileSystem_.isReadyState('READY'))
    throw new Error('Already connected');

  this.pendingOperations_.push([onSuccess, onError]);

  if (this.remoteFileSystem_ && this.remoteFileSystem_.isReadyState('WAIT'))
    return;

  if (this.channel.readyBinding.isReadyState('READY')) {
    this.offerHandshake();
  } else {
    this.channel.reconnect();
  }
};

/**
 * Offer a wam.FileSystem 'handshake' message over the associated channel.
 */
wam.jsfs.RemoteFileSystem.prototype.offerHandshake = function() {
  if (this.remoteFileSystem_) {
    if (this.remoteFileSystem_.isReadyState('READY'))
      throw new Error('Already ready.');

    this.remoteFileSystem_.onReady.removeListener(
        this.onFileSystemReady_, this);
  }

  this.handshakeRequest_ = new wam.remote.fs.handshake.Request(this.channel);
  this.remoteFileSystem_ = this.handshakeRequest_.fileSystem;
  this.remoteFileSystem_.onReady.addListener(this.onFileSystemReady_, this);
  this.remoteFileSystem_.onClose.addListener(this.onFileSystemClose_, this);
  this.handshakeRequest_.sendRequest();
};

/**
 * Handle the onReady event from the channel's ready binding.
 */
wam.jsfs.RemoteFileSystem.prototype.onChannelReady_ = function() {
  this.offerHandshake();
};

/**
 * Handle the onReady event from the handshake offer.
 */
wam.jsfs.RemoteFileSystem.prototype.onFileSystemReady_ = function(value) {
  if (typeof value == 'object' && value.name)
    this.remoteName = value.name;

  while (this.pendingOperations_.length) {
    var onSuccess = this.pendingOperations_.shift()[0];
    onSuccess();
  }

  this.onReady(value);
};

/**
 * Handle an onClose from the handshake offer.
 */
wam.jsfs.RemoteFileSystem.prototype.onFileSystemClose_ = function(
    reason, value) {
  this.remoteFileSystem_.onReady.removeListener(this.onFileSystemReady_, this);
  this.remoteFileSystem_.onClose.removeListener(this.onFileSystemClose_, this);

  this.onClose(reason, value);

  this.handshakeRequest_ = null;
  this.remoteFileSystem_ = null;

  if (reason == 'error') {
    while (this.pendingOperations_.length) {
      var onError = this.pendingOperations_.shift()[1];
      onError();
    }
  }
};

/**
 * If this FileSystem isn't ready, try to make it ready and queue the callback
 * for later, otherwise call it right now.
 *
 * @param {function()} callback The function to invoke when the file system
 *   becomes ready.
 * @param {function(wam.Error)} onError The function to invoke if the
 *   file system fails to become ready.
 */
wam.jsfs.RemoteFileSystem.prototype.doOrQueue_ = function(callback, onError) {
  if (this.remoteFileSystem_ && this.remoteFileSystem_.isReadyState('READY')) {
    callback();
  } else {
    this.connect(callback, onError);
  }
};

/**
 * Forward a stat call to the file system.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardStat = function(
    arg, onSuccess, onError) {
  this.doOrQueue_(function() {
      this.remoteFileSystem_.stat({path: arg.forwardPath}, onSuccess, onError);
    }.bind(this), onError);
};

/**
 * Forward an unlink call to the file system.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardUnlink = function(
    arg, onSuccess, onError) {
  this.doOrQueue_(function() {
      this.remoteFileSystem_.unlink({path: arg.forwardPath},
                                    onSuccess, onError);
    }.bind(this),
    onError);
};

/**
 * Forward a list call to the LocalFileSystem.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardList = function(
    arg, onSuccess, onError) {
  this.doOrQueue_(function() {
      this.remoteFileSystem_.list({path: arg.forwardPath}, onSuccess, onError);
    }.bind(this),
    onError);
};

/**
 * Forward a wam 'execute' to this file system.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardExecute = function(arg) {
  this.doOrQueue_(function() {
      arg.executeContext.path = arg.forwardPath;
      var executeRequest = new wam.remote.fs.execute.Request(
          this.handshakeRequest_, arg.executeContext);
      executeRequest.onExecute_();
    }.bind(this),
    function(value) { arg.executeContext.closeError(value) });
};

/**
 * Forward a wam 'open' to this file system.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardOpen = function(arg) {
  this.doOrQueue_(function() {
      arg.openContext.path = arg.forwardPath;
      var openRequest = new wam.remote.fs.open.Request(
          this.handshakeRequest_, arg.openContext);
      openRequest.onOpen_();
    }.bind(this),
    function(value) { arg.openContext.closeError(value) });
};
<commit_msg>wam: Fix typo, conver lib.Event to wam.Event<commit_after>// Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

'use strict';

/**
 * A jsfs.Entry subclass that proxies to a wam file system connected via a
 * wam.Channel.
 *
 * @param {wam.Channel} channel The channel hosting the wam file system.
 */
wam.jsfs.RemoteFileSystem = function(channel) {
  wam.jsfs.Entry.call(this);

  this.channel = channel;
  this.channel.readyBinding.onReady.addListener(this.onChannelReady_, this);

  this.remoteName = null;

  this.handshakeRequest_ = null;
  this.remoteFileSystem_ = null;

  this.pendingOperations_ = [];

  this.onReady = new wam.Event();
  this.onClose = new wam.Event();

  if (this.channel.readyBinding.isReadyState('READY'))
    this.offerHandshake();
};

/**
 * We're an Entry subclass that is able to FORWARD and LIST.
 */
wam.jsfs.RemoteFileSystem.prototype = wam.jsfs.Entry.subclass(
    ['FORWARD', 'LIST']);

/**
 * Return a wam 'stat' value for the FileSystem itself.
 *
 * This is a jsfs.Entry method needed as part of the 'LIST' action.
 */
wam.jsfs.RemoteFileSystem.prototype.getStat = function(onSuccess, onError) {
  var readyState = 'UNDEFINED';
  if (this.remoteFileSystem_)
    readyState = this.remoteFileSystem_.readyState;

  wam.async(onSuccess,
            [null,
             {abilities: this.abilities,
              state: readyState,
              channel: this.channel.name,
              source: 'wamfs'
             }]);
};

/**
 * Reconnect the wam.Channel if necessary, then offer a wam.FileSystem
 * 'handshake' message.
 *
 * @param {function()} onSuccess
 * @param {function(wam.Error)} onError
 */
wam.jsfs.RemoteFileSystem.prototype.connect = function(onSuccess, onError) {
  if (this.remoteFileSystem_ && this.remoteFileSystem_.isReadyState('READY'))
    throw new Error('Already connected');

  this.pendingOperations_.push([onSuccess, onError]);

  if (this.remoteFileSystem_ && this.remoteFileSystem_.isReadyState('WAIT'))
    return;

  if (this.channel.readyBinding.isReadyState('READY')) {
    this.offerHandshake();
  } else {
    this.channel.reconnect();
  }
};

/**
 * Offer a wam.FileSystem 'handshake' message over the associated channel.
 */
wam.jsfs.RemoteFileSystem.prototype.offerHandshake = function() {
  if (this.remoteFileSystem_) {
    if (this.remoteFileSystem_.isReadyState('READY'))
      throw new Error('Already ready.');

    this.remoteFileSystem_.onReady.removeListener(
        this.onFileSystemReady_, this);
  }

  this.handshakeRequest_ = new wam.remote.fs.handshake.Request(this.channel);
  this.remoteFileSystem_ = this.handshakeRequest_.fileSystem;
  this.remoteFileSystem_.onReady.addListener(this.onFileSystemReady_, this);
  this.remoteFileSystem_.onClose.addListener(this.onFileSystemClose_, this);
  this.handshakeRequest_.sendRequest();
};

/**
 * Handle the onReady event from the channel's ready binding.
 */
wam.jsfs.RemoteFileSystem.prototype.onChannelReady_ = function() {
  this.offerHandshake();
};

/**
 * Handle the onReady event from the handshake offer.
 */
wam.jsfs.RemoteFileSystem.prototype.onFileSystemReady_ = function(value) {
  if (typeof value == 'object' && value.name)
    this.remoteName = value.name;

  while (this.pendingOperations_.length) {
    var onSuccess = this.pendingOperations_.shift()[0];
    onSuccess();
  }

  this.onReady(value);
};

/**
 * Handle an onClose from the handshake offer.
 */
wam.jsfs.RemoteFileSystem.prototype.onFileSystemClose_ = function(
    reason, value) {
  this.remoteFileSystem_.onReady.removeListener(this.onFileSystemReady_, this);
  this.remoteFileSystem_.onClose.removeListener(this.onFileSystemClose_, this);

  this.onClose(reason, value);

  this.handshakeRequest_ = null;
  this.remoteFileSystem_ = null;

  if (reason == 'error') {
    while (this.pendingOperations_.length) {
      var onError = this.pendingOperations_.shift()[1];
      onError();
    }
  }
};

/**
 * If this FileSystem isn't ready, try to make it ready and queue the callback
 * for later, otherwise call it right now.
 *
 * @param {function()} callback The function to invoke when the file system
 *   becomes ready.
 * @param {function(wam.Error)} onError The function to invoke if the
 *   file system fails to become ready.
 */
wam.jsfs.RemoteFileSystem.prototype.doOrQueue_ = function(callback, onError) {
  if (this.remoteFileSystem_ && this.remoteFileSystem_.isReadyState('READY')) {
    callback();
  } else {
    this.connect(callback, onError);
  }
};

/**
 * Forward a stat call to the file system.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardStat = function(
    arg, onSuccess, onError) {
  this.doOrQueue_(function() {
      this.remoteFileSystem_.stat({path: arg.forwardPath}, onSuccess, onError);
    }.bind(this), onError);
};

/**
 * Forward an unlink call to the file system.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardUnlink = function(
    arg, onSuccess, onError) {
  this.doOrQueue_(function() {
      this.remoteFileSystem_.unlink({path: arg.forwardPath},
                                    onSuccess, onError);
    }.bind(this),
    onError);
};

/**
 * Forward a list call to the LocalFileSystem.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardList = function(
    arg, onSuccess, onError) {
  this.doOrQueue_(function() {
      this.remoteFileSystem_.list({path: arg.forwardPath}, onSuccess, onError);
    }.bind(this),
    onError);
};

/**
 * Forward a wam 'execute' to this file system.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardExecute = function(arg) {
  this.doOrQueue_(function() {
      arg.executeContext.path = arg.forwardPath;
      var executeRequest = new wam.remote.fs.execute.Request(
          this.handshakeRequest_, arg.executeContext);
      executeRequest.onExecute_();
    }.bind(this),
    function(value) { arg.executeContext.closeError(value) });
};

/**
 * Forward a wam 'open' to this file system.
 *
 * This is a jsfs.Entry method needed as part of the 'FORWARD' action.
 */
wam.jsfs.RemoteFileSystem.prototype.forwardOpen = function(arg) {
  this.doOrQueue_(function() {
      arg.openContext.path = arg.forwardPath;
      var openRequest = new wam.remote.fs.open.Request(
          this.handshakeRequest_, arg.openContext);
      openRequest.onOpen_();
    }.bind(this),
    function(value) { arg.openContext.closeError(value) });
};
<|endoftext|>