<commit_before>// BITS Server-JavaScript Document
try{
	bitsVersion = 12;
bitsInstall = function(event){

	}

	bitsFetch= function(event,cache){
		//console.log(resolve);
		//var orReq=event.request.clone();

		var url = new URL(event.request.clone().url);

if (url.pathname.substring(0, 2) == '/p' && url.hostname == location.hostname) {

		console.log('physical web url!!');
		var bid=url.pathname.substring(2, 5);
		//resolve(Response.redirect('http://bitsoko.io/bits/#m='+bid));
//orReq.url='https://bitsoko.io/p'+bid+'?f=j';

  return cache.match(event.request.clone()).then(function (response) {

console.log(response);
 return response || fetch('https://bitsoko.io/p'+bid+'?f=j').then(function(response) {
//response=Response.redirect('https://bitsoko.io/p='+bid+'?format=json');

//console.log(response);
if(response.clone().url=='https://bitsoko.io/p'+bid+'?f=j' && event.request.clone().url=='https://bitsoko.io/p'+bid){

return response.clone().text().then(function(d){

var respJ = JSON.parse(d);
 // console.log(respJ);
url = location.origin+'/bits/index.html#s='+respJ.s+'&a='+respJ.a;
var trResp=Response.redirect(url);
cache.put(event.request.clone(), trResp.clone());

return trResp;

 });

}

  }).catch(function(err){

//url = 'https://bitsoko.io/bits/index.html#s=3&a=404';
return Response.redirect('https://bitsoko.io/bits/index.html#s=3&a=404');
  });
//cache.put(orReq, response.clone());
//  console.log(resp.clone());

  });

}

 }
}catch(err){console.log(err)}
<commit_msg>update 13<commit_after>// BITS Server-JavaScript Document
try{
	bitsVersion = 13;
bitsInstall = function(event){

	}
	bitsMessage = function(event){

	}
	bitsPush = function(event){

	}
		bitsNotification = function(title,body,tag,icon,actions,sticky,silent){

	 var note = self.registration.showNotification(title, {
          body: body,
          icon:  icon,
          tag: tag,
          actions: [{action: 'signIn', title: "Sign In"}],
            sticky: sticky,
            silent: silent
        });

	}

	bitsFetch= function(event,cache){
		//console.log(resolve);
		//var orReq=event.request.clone();

		var url = new URL(event.request.clone().url);

if (url.pathname.substring(0, 2) == '/p' && url.hostname == location.hostname) {

		console.log('physical web url!!');
		var bid=url.pathname.substring(2, 5);
		//resolve(Response.redirect('http://bitsoko.io/bits/#m='+bid));
//orReq.url='https://bitsoko.io/p'+bid+'?f=j';

  return cache.match(event.request.clone()).then(function (response) {

console.log(response);
 return response || fetch('https://bitsoko.io/p'+bid+'?f=j').then(function(response) {
//response=Response.redirect('https://bitsoko.io/p='+bid+'?format=json');

//console.log(response);
if(response.clone().url=='https://bitsoko.io/p'+bid+'?f=j' && event.request.clone().url=='https://bitsoko.io/p'+bid){

return response.clone().text().then(function(d){

var respJ = JSON.parse(d);
 // console.log(respJ);
url = location.origin+'/bits/index.html#s='+respJ.s+'&a='+respJ.a;
var trResp=Response.redirect(url);
cache.put(event.request.clone(), trResp.clone());

return trResp;

 });

}

  }).catch(function(err){

//url = 'https://bitsoko.io/bits/index.html#s=3&a=404';
return Response.redirect('https://bitsoko.io/bits/index.html#s=3&a=404');
  });
//cache.put(orReq, response.clone());
//  console.log(resp.clone());

  });

}

 }
}catch(err){console.log(err)}
<|endoftext|>


<commit_before>(function($) {

if (Echo.Utils.isComponentDefined("Echo.StreamServer.Controls.Counter")) return;

var counter = Echo.Control.skeleton("Echo.StreamServer.Controls.Counter");

counter.config = {
	"liveUpdatesTimeout": 10,
	"infoMessages": {"layout": "compact"}
};

$.map(["onPostComplete", "Plugins.Edit.onEditComplete"], function(name) {
	counter.events["Echo.StreamServer.Controls.Submit." + name] = {
		"context" : "global",
		"handler" : function() {
			this.get("request").send({"force": true});
		}
	};
});

counter.templates.main = "{data:count}";

/**
* @class Echo.StreamServer.Controls.Counter
* Echo Counter class which encapsulates interaction with the
* Echo Count API
*
* @constructor
* Counter constructor initializing Echo.StreamServer.Controls.Counter class
* @param {Object} config
* @param {String} config.target Specifies the DOM element where the control will be displayed.
* @param {String} config.appkey Specifies the customer application key. You can use the "test.echoenabled.com" appkey for testing purposes.
* @param {String} config.query Specifies the search query to generate the necessary data set. It must be constructed according to the "search" API method specification.
* @param {Number} [config.liveUpdatesTimeout=10] Specifies the timeout between the live updates requests (in seconds).
* @param {Object} [config.infoMessages] Customizes the look and feel of info messages, for example "loading" and "error".
* @param {String} [config.infoMessages.layout="compact"] Specifies the layout of the info message. By default can be set to "compact" or "full".
* @param {Boolean} [config.infoMessages.enabled=true] Specifies if info messages should be rendered.
* @return {Object} Returns the reference to the corresponding Echo.StreamServer.Controls.Counter instance.
*/

counter.constructor = function() {
	// data can be defined explicitly
	// in this case we do not make API requests
	// TODO: no live updates for now if data is passed as a config value
	if ($.isEmptyObject(this.get("data"))) {
		this._request();
	} else {
		this.render();
	}
};

/**
* @method refresh
* Method implements the refresh logic for the Counter control.
* It should be used for example after some config params were changed.
*/

counter.methods.refresh = function() {
	this.showMessage({"type": "loading"});
	this.set("data", {});
	this.get("request").abort();
	this.remove("request");
	this._request();
	var component = Echo.Utils.getComponent("Echo.StreamServer.Controls.Counter");
	component.parent.refresh.call(this);
};

// internal functions

counter.methods._request = function() {
	var request = this.get("request");
	if (!request) {
		request = Echo.StreamServer.API.request({
			"endpoint": "count",
			"data": {
				"q": this.config.get("query"),
				"appkey": this.config.get("appkey")
			},
			"liveUpdatesTimeout": this.config.get("liveUpdatesTimeout"),
			"recurring": true,
			"onError": $.proxy(this._error, this),
			"onData": $.proxy(this._update, this)
		});
		this.set("request", request);
	}
	request.send();
};

counter.methods._update = function(data) {
	if ($.isEmptyObject(this.data) || this.data.count != data.count) {
		this.set("data", data);
		this.render();
		this.events.publish({
			"topic": "onUpdate",
			"data": {
				"data": data,
				"query": this.config.get("query"),
				"target": this.config.get("target").get(0)
			}
		});
	}
};

counter.methods._error = function(data) {
	if (data.errorCode === "more_than") {
		this.set("data.count", data.errorMessage + "+");
		this.render();
	} else {
		this.showMessage({"type": "error", "data": data, "message": data.errorMessage});
	}
	this.events.publish({
		"topic": "onError",
		"data": {
			"data": data,
			"query": this.config.get("query"),
			"target": this.config.get("target").get(0)
		}
	});
};

Echo.Control.create(counter);

})(jQuery);
<commit_msg>further counter inline docs updates<commit_after>(function($) {

if (Echo.Utils.isComponentDefined("Echo.StreamServer.Controls.Counter")) return;

var counter = Echo.Control.skeleton("Echo.StreamServer.Controls.Counter");

counter.config = {
	"liveUpdatesTimeout": 10,
	"infoMessages": {"layout": "compact"}
};

$.map(["onPostComplete", "Plugins.Edit.onEditComplete"], function(name) {
	counter.events["Echo.StreamServer.Controls.Submit." + name] = {
		"context" : "global",
		"handler" : function() {
			this.get("request").send({"force": true});
		}
	};
});

counter.templates.main = "{data:count}";

/**
* @class Echo.StreamServer.Controls.Counter
* Echo Counter class which encapsulates interaction with the
* Echo Count API
*
* @constructor
* Counter constructor initializing Echo.StreamServer.Controls.Counter class
* @param {Object} config
* @param {String} config.target Specifies the DOM element where the control will be displayed.
* @param {String} config.appkey Specifies the customer application key. You can use the "test.echoenabled.com" appkey for testing purposes.
* @param {String} config.query Specifies the search query to generate the necessary data set. It must be constructed according to the "search" API method specification.
*
*     new Echo.StreamServer.Controls.Counter({
*         "target": document.getElementById("container"),
*         "appkey": "test.aboutecho.com",
*         "query" : "childrenof:http://example.com/test/*"
*     });
* @param {Object} config.data Specifies predefined items count which should be displayed by the application.
*     new Echo.Counter({
*         ...
*         "data": {"count": 100},
*         ...
*     });
* @param {Number} [config.liveUpdatesTimeout=10] Specifies the timeout between the live updates requests (in seconds).
* @param {Object} [config.infoMessages] Customizes the look and feel of info messages, for example "loading" and "error".
* @param {String} [config.infoMessages.layout="compact"] Specifies the layout of the info message. By default can be set to "compact" or "full".
* @param {Boolean} [config.infoMessages.enabled=true] Specifies if info messages should be rendered.
*     new Echo.StreamServer.Controls.Counter({
*         ...
*         "infoMessages" : {
*             "enabled" : true,
*             "layout" : "full"
*         }
*     });
* @return {Object} Returns the reference to the corresponding Echo.StreamServer.Controls.Counter instance.
*/

counter.constructor = function() {
	// data can be defined explicitly
	// in this case we do not make API requests
	// TODO: no live updates for now if data is passed as a config value
	if ($.isEmptyObject(this.get("data"))) {
		this._request();
	} else {
		this.render();
	}
};

/**
* @method refresh
* Method implements the refresh logic for the Counter control.
* It should be used for example after some config params were changed.
*/

counter.methods.refresh = function() {
	this.showMessage({"type": "loading"});
	this.set("data", {});
	this.get("request").abort();
	this.remove("request");
	this._request();
	var component = Echo.Utils.getComponent("Echo.StreamServer.Controls.Counter");
	component.parent.refresh.call(this);
};

// internal functions

counter.methods._request = function() {
	var request = this.get("request");
	if (!request) {
		request = Echo.StreamServer.API.request({
			"endpoint": "count",
			"data": {
				"q": this.config.get("query"),
				"appkey": this.config.get("appkey")
			},
			"liveUpdatesTimeout": this.config.get("liveUpdatesTimeout"),
			"recurring": true,
			"onError": $.proxy(this._error, this),
			"onData": $.proxy(this._update, this)
		});
		this.set("request", request);
	}
	request.send();
};

counter.methods._update = function(data) {
	if ($.isEmptyObject(this.data) || this.data.count != data.count) {
		this.set("data", data);
		this.render();
		this.events.publish({
			"topic": "onUpdate",
			"data": {
				"data": data,
				"query": this.config.get("query"),
				"target": this.config.get("target").get(0)
			}
		});
	}
};

counter.methods._error = function(data) {
	if (data.errorCode === "more_than") {
		this.set("data.count", data.errorMessage + "+");
		this.render();
	} else {
		this.showMessage({"type": "error", "data": data, "message": data.errorMessage});
	}
	this.events.publish({
		"topic": "onError",
		"data": {
			"data": data,
			"query": this.config.get("query"),
			"target": this.config.get("target").get(0)
		}
	});
};

Echo.Control.create(counter);

})(jQuery);
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from './template';
import Component from 'ember-component';
import MergeSupport, { REMOVE_ACTION } from 'flood-simple-form/mixins/merge-support';
const { guidFor, get, run } = Ember;

const SectionComponent = Component.extend(MergeSupport, {
  layout,
  tagName: 'div',
  classNames: ['SimpleForm-section'],

  changeset: null,

  form: null,

  /**
   * Indicates that we should keep this around even when not showing the section.
   *
   * @public
   * @type {Boolean}
   */
  isNeeded: false,

  /**
   * Called before this section is disabled
   * @public
   */
  sectionWillDisable() {
    let changeset = get(this, 'changeset');
    let isNeeded = get(this, 'isNeeded');

    if (!isNeeded) {
      changeset.rollback();
      this.sendAction(REMOVE_ACTION, { id: guidFor(changeset) });
    }
  },

  willDestroyElement() {
    this.trigger('sectionWillDisable');
  },

  didInsertElement() {
    run.next(() => {
      this.send('_sendUpdate');
    });
  },

  actions: {
    propagateEnter() {
      this.sendAction('enter', ...arguments);
    },

    propagateCancel() {
      this.sendAction('cancel', ...arguments);
    }

  }
});

SectionComponent.reopenClass({
  positionalParams: ['changeset', 'isEnabled']
});

export default SectionComponent;
<commit_msg>Don’t send update on section insertion<commit_after>import Ember from 'ember';
import layout from './template';
import Component from 'ember-component';
import MergeSupport, { REMOVE_ACTION } from 'flood-simple-form/mixins/merge-support';
const { guidFor, get } = Ember;

const SectionComponent = Component.extend(MergeSupport, {
  layout,
  tagName: 'div',
  classNames: ['SimpleForm-section'],

  changeset: null,

  form: null,

  /**
   * Indicates that we should keep this around even when not showing the section.
   *
   * @public
   * @type {Boolean}
   */
  isNeeded: false,

  /**
   * Called before this section is disabled
   * @public
   */
  sectionWillDisable() {
    let changeset = get(this, 'changeset');
    let isNeeded = get(this, 'isNeeded');

    if (!isNeeded) {
      changeset.rollback();
      this.sendAction(REMOVE_ACTION, { id: guidFor(changeset) });
    }
  },

  willDestroyElement() {
    this.trigger('sectionWillDisable');
  },

  didInsertElement() {
    // run.next(() => {
    //   this.send('_sendUpdate');
    // });
  },

  actions: {
    propagateEnter() {
      this.sendAction('enter', ...arguments);
    },

    propagateCancel() {
      this.sendAction('cancel', ...arguments);
    }

  }
});

SectionComponent.reopenClass({
  positionalParams: ['changeset', 'isEnabled']
});

export default SectionComponent;
<|endoftext|>


<commit_before>describe("Tests primitive type conversion", function () {

	var myCustomEquality = function(first, second) {
		return first == second;
	};

	beforeEach(function() {
		jasmine.addCustomEqualityTester(myCustomEquality);
	});

	it("convert_char", function () {

		var logged =  null;

		var logger = new com.tns.tests.CharConversionTest.Logger({
		    print: function(value) {
		        logged = value;
		    }
		});

		com.tns.tests.CharConversionTest.printWithChar(logger, 'x');

		expect(logged).toBe(char('x'));
	});

});<commit_msg>fix unit test<commit_after>describe("Tests primitive type conversion", function () {

	var myCustomEquality = function(first, second) {
		return first == second;
	};

	beforeEach(function() {
		jasmine.addCustomEqualityTester(myCustomEquality);
	});

	it("convert_char", function () {

		var logged =  null;

		var logger = new com.tns.tests.CharConversionTest.Logger({
		    print: function(value) {
		        logged = value;
		    }
		});

		com.tns.tests.CharConversionTest.printWithChar(logger, char('x'));

		expect(logged).toBe('x');
	});

});<|endoftext|>


<commit_before>/* global describe, it, before */

const Brave = require('./lib/brave')
const Config = require('../js/constants/config').default
const {urlInput, activeWebview, activeTabFavicon, activeTab} = require('./lib/selectors')
const assert = require('assert')

describe('urlbar', function () {
  function * setup (client) {
    yield client
      .waitUntilWindowLoaded()
      .waitForVisible('#browser')
      .waitForVisible(urlInput)
  }

  function * newFrame (client, frameKey = 2) {
    yield client
      .ipcSend('shortcut-new-frame')
      // wait for correct urlInput based on frameKey
      .waitForVisible('div[id="navigator"][data-frame-key="' + frameKey + '"] ' + urlInput)
      // wait for selection
      .waitUntil(function () {
        return this.getAttribute('div[id="navigator"][data-frame-key="' + frameKey + '"] ' + urlInput, 'selectionEnd').then(function (value) { return value > 0 })
      })
    // wait for focus
    yield hasFocus(client)
  }

  function blur (client, text = Config.defaultUrl) {
    return client
      .keys('\uE007') // clear focus
      .waitUntil(function () {
        return this.getSelectedText().then(function (value) { return value === '' })
      })
  }

  function hasFocus (client) {
    return client.waitUntil(function () {
      return this.getAttribute(':focus', 'id').then(function (value) { return value === 'urlInput' })
    })
  }

  function defaultUrl (client) {
    return client.waitForValue(urlInput, Config.defaultUrl)
  }

  function * navigate (client, url) {
    yield client.ipcSend('shortcut-focus-url')
      .setValue(urlInput, url)
      // hit enter
      .keys('\uE007')
      .waitUntil(function () {
        return this.getAttribute(activeWebview, 'src').then(src => src === url)
      })
  }

  function selectsText (client, text = Config.defaultUrl) {
    return client.waitUntil(function () {
      return this.getSelectedText().then(function (value) { return value === text })
    })
  }

  describe('navigation', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
    })

    it('loads a page with a title', function *() {
      const page1Url = Brave.server.url('page1.html')
      yield navigate(this.app.client, page1Url)
      return yield this.app.client.waitForValue(urlInput)
        .getValue(urlInput)
        .should.eventually.be.equal('Page 1')
        .moveToObject(urlInput)
        .getValue(urlInput)
        .should.eventually.be.equal(page1Url)
    })

    it('exits title mode when focused', function *() {
      const page1Url = Brave.server.url('page1.html')
      yield navigate(this.app.client, page1Url)
      return yield this.app.client.ipcSend('shortcut-focus-url')
        .getValue(urlInput)
        .should.eventually.be.equal(page1Url)
    })

    it('loads a page with no title', function *() {
      const page1Url = Brave.server.url('page_no_title.html')
      yield navigate(this.app.client, page1Url)
      return yield this.app.client.waitForValue(urlInput)
        .getValue(urlInput)
        .should.eventually.be.equal(page1Url)
    })
  })

  describe('favicon', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
    })

    it('Uses the default favicon when one is not specified', function *() {
      const page1Url = Brave.server.url('page1.html')
      yield navigate(this.app.client, page1Url)
      let backgroundImage = yield this.app.client.getCssProperty(activeTabFavicon, 'background-image')
      assert.equal(backgroundImage.value, `url("${Brave.server.url('favicon.ico')}")`)
    })
    it('Parses favicon when one is present', function *() {
      const pageWithFavicon = Brave.server.url('favicon.html')
      yield navigate(this.app.client, pageWithFavicon)
      yield this.app.client.waitUntil(() =>
        this.app.client.getCssProperty(activeTabFavicon, 'background-image').then(backgroundImage =>
          backgroundImage.value === `url("${Brave.server.url('img/test.ico')}")`
      ))
    })
  })

  describe('themeColor', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
    })

    it('Uses the default tab color when one is not specified', function *() {
      const page1Url = Brave.server.url('page1.html')
      yield navigate(this.app.client, page1Url)
      let backgroundColor = yield this.app.client.getCssProperty(activeTab, 'background-color')
      assert.equal(backgroundColor.parsed.hex, '#ffffff')
    })

    it('Parses theme-color meta tag when one is present', function *() {
      const pageWithFavicon = Brave.server.url('theme_color.html')
      yield navigate(this.app.client, pageWithFavicon)
      yield this.app.client.waitUntil(() =>
        this.app.client.getCssProperty(activeTab, 'background-color').then(backgroundColor =>
          backgroundColor.parsed.hex === '#4d90fe'
      ))
    })
  })

  describe('new window', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
    })

    it('displays the default url', function *() {
      yield defaultUrl(this.app.client)
    })

    it('has focus', function *() {
      yield hasFocus(this.app.client)
    })

    it('selects the text', function *() {
      this.app.client
    })
  })

  describe('new tab', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
      yield newFrame(this.app.client)
    })

    it('displays the default url', function *() {
      yield defaultUrl(this.app.client)
    })

    it('has focus', function *() {
      yield hasFocus(this.app.client)
    })

    it('selects the text', function *() {
      yield selectsText(this.app.client)
    })
  })

  describe('submit', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
      // wait for the urlInput to be fully initialized
      yield selectsText(this.app.client)
      // hit enter
      yield this.app.client.keys('\uE007')
    })

    it('clears the selected text', function *() {
      yield selectsText(this.app.client, '')
    })

    it('gives focus to the webview')

    describe('url input value', function () {

    })

    describe('non-url input value', function () {

    })
  })

  describe('typing', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
      // wait for the urlInput to be fully initialized
      yield selectsText(this.app.client)
      // now type something
      yield this.app.client.keys('a')
    })

    it('sets the value', function *() {
      yield this.app.client.waitForValue(urlInput, 'a')
    })

    it('clears the selected text', function *() {
      yield selectsText(this.app.client, '')
    })

    describe('shortcut-focus-url', function () {
      before(function *() {
        yield this.app.client
          .ipcSend('shortcut-focus-url')
      })

      it('has focus', function *() {
        yield hasFocus(this.app.client)
      })

      it('selects the text', function *() {
        yield selectsText(this.app.client, 'a')
      })
    })

    describe('escape', function *() {
      before(function *() {
        yield this.app.client.ipcSend('shortcut-active-frame-stop')
      })

      it('reverts typing on escape', function *() {
        yield this.app.client.getValue(urlInput).should.eventually.be.equal(Config.defaultUrl)
        yield selectsText(this.app.client)
      })
    })
  })

  // need to move urlbar state to frame before enabling these
  describe('change tabs', function () {
    Brave.beforeAll(this)

    before(function *() {
      // default tab
      yield setup(this.app.client)
      // tab with typing
      yield newFrame(this.app.client)
      yield this.app.client.keys('a').waitForValue(urlInput, 'a')
    })

    describe('switch to default state tab', function () {
      before(function *() {
        yield this.app.client
          .ipcSend('shortcut-set-active-frame-by-index', 0)
          .waitForVisible('div[id="navigator"][data-frame-key="1"] ' + urlInput)
          // wait for selection??
      })

      it('preserves focused state', function *() {
        yield defaultUrl(this.app.client)
        yield hasFocus(this.app.client)
        yield selectsText(this.app.client)
      })
    })

    describe('switch to typing tab', function () {
      before(function *() {
        yield this.app.client
          .ipcSend('shortcut-set-active-frame-by-index', 1)
          .waitForVisible('div[id="navigator"][data-frame-key="2"] ' + urlInput)
      })

      it('preserves typing state', function *() {
        yield this.app.client.getValue(urlInput).should.eventually.be.equal('a')
        yield selectsText(this.app.client, '')
      })
    })
  })

  describe('click', function () {
    describe('blurred', function () {
      Brave.beforeAll(this)

      before(function *() {
        yield setup(this.app.client)
        yield blur(this.app.client)
        yield this.app.client
          .leftClick(urlInput)
      })

      it('displays the default url', function *() {
        yield defaultUrl(this.app.client)
      })

      it('has focus', function *() {
        yield hasFocus(this.app.client)
      })

      it('selects the text', function *() {
        yield selectsText(this.app.client)
      })
    })

    describe('focused', function () {
      Brave.beforeAll(this)

      before(function *() {
        yield setup(this.app.client)
        yield this.app.client
          .leftClick(urlInput)
      })

      it('displays the default url', function *() {
        yield defaultUrl(this.app.client)
      })

      it('has focus', function *() {
        yield hasFocus(this.app.client)
      })

      it('unselects the text', function *() {
        yield selectsText(this.app.client, '')
      })
    })
  })

  describe('shortcut-focus-url', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
      yield blur(this.app.client)
      yield this.app.client.ipcSend('shortcut-focus-url')
    })

    it('displays the default url', function *() {
      yield defaultUrl(this.app.client)
    })

    it('has focus', function *() {
      yield hasFocus(this.app.client)
    })

    it('selects the text', function *() {
      yield selectsText(this.app.client)
    })
  })
})
<commit_msg>Comment out test until we get a new electron build<commit_after>/* global describe, it, before */

const Brave = require('./lib/brave')
const Config = require('../js/constants/config').default
const {urlInput, activeWebview, activeTabFavicon, activeTab} = require('./lib/selectors')
const assert = require('assert')

describe('urlbar', function () {
  function * setup (client) {
    yield client
      .waitUntilWindowLoaded()
      .waitForVisible('#browser')
      .waitForVisible(urlInput)
  }

  function * newFrame (client, frameKey = 2) {
    yield client
      .ipcSend('shortcut-new-frame')
      // wait for correct urlInput based on frameKey
      .waitForVisible('div[id="navigator"][data-frame-key="' + frameKey + '"] ' + urlInput)
      // wait for selection
      .waitUntil(function () {
        return this.getAttribute('div[id="navigator"][data-frame-key="' + frameKey + '"] ' + urlInput, 'selectionEnd').then(function (value) { return value > 0 })
      })
    // wait for focus
    yield hasFocus(client)
  }

  function blur (client, text = Config.defaultUrl) {
    return client
      .keys('\uE007') // clear focus
      .waitUntil(function () {
        return this.getSelectedText().then(function (value) { return value === '' })
      })
  }

  function hasFocus (client) {
    return client.waitUntil(function () {
      return this.getAttribute(':focus', 'id').then(function (value) { return value === 'urlInput' })
    })
  }

  function defaultUrl (client) {
    return client.waitForValue(urlInput, Config.defaultUrl)
  }

  function * navigate (client, url) {
    yield client.ipcSend('shortcut-focus-url')
      .setValue(urlInput, url)
      // hit enter
      .keys('\uE007')
      .waitUntil(function () {
        return this.getAttribute(activeWebview, 'src').then(src => src === url)
      })
  }

  function selectsText (client, text = Config.defaultUrl) {
    return client.waitUntil(function () {
      return this.getSelectedText().then(function (value) { return value === text })
    })
  }

  describe('navigation', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
    })

    it('loads a page with a title', function *() {
      const page1Url = Brave.server.url('page1.html')
      yield navigate(this.app.client, page1Url)
      return yield this.app.client.waitForValue(urlInput)
        .getValue(urlInput)
        .should.eventually.be.equal('Page 1')
        .moveToObject(urlInput)
        .getValue(urlInput)
        .should.eventually.be.equal(page1Url)
    })

    it('exits title mode when focused', function *() {
      const page1Url = Brave.server.url('page1.html')
      yield navigate(this.app.client, page1Url)
      return yield this.app.client.ipcSend('shortcut-focus-url')
        .getValue(urlInput)
        .should.eventually.be.equal(page1Url)
    })

    it('loads a page with no title', function *() {
      const page1Url = Brave.server.url('page_no_title.html')
      yield navigate(this.app.client, page1Url)
      return yield this.app.client.waitForValue(urlInput)
        .getValue(urlInput)
        .should.eventually.be.equal(page1Url)
    })
  })

  describe('favicon', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
    })

    it('Uses the default favicon when one is not specified', function *() {
      const page1Url = Brave.server.url('page1.html')
      yield navigate(this.app.client, page1Url)
      let backgroundImage = yield this.app.client.getCssProperty(activeTabFavicon, 'background-image')
      assert.equal(backgroundImage.value, `url("${Brave.server.url('favicon.ico')}")`)
    })
    it('Parses favicon when one is present', function *() {
      const pageWithFavicon = Brave.server.url('favicon.html')
      yield navigate(this.app.client, pageWithFavicon)
      yield this.app.client.waitUntil(() =>
        this.app.client.getCssProperty(activeTabFavicon, 'background-image').then(backgroundImage =>
          backgroundImage.value === `url("${Brave.server.url('img/test.ico')}")`
      ))
    })
  })

  describe('themeColor', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
    })

    it('Uses the default tab color when one is not specified', function *() {
      const page1Url = Brave.server.url('page1.html')
      yield navigate(this.app.client, page1Url)
      let backgroundColor = yield this.app.client.getCssProperty(activeTab, 'background-color')
      assert.equal(backgroundColor.parsed.hex, '#ffffff')
    })

    /*
    // We need a newer electron build first
    it('Parses theme-color meta tag when one is present', function *() {
      const pageWithFavicon = Brave.server.url('theme_color.html')
      yield navigate(this.app.client, pageWithFavicon)
      yield this.app.client.waitUntil(() =>
        this.app.client.getCssProperty(activeTab, 'background-color').then(backgroundColor =>
          backgroundColor.parsed.hex === '#4d90fe'
      ))
    })
    */
  })

  describe('new window', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
    })

    it('displays the default url', function *() {
      yield defaultUrl(this.app.client)
    })

    it('has focus', function *() {
      yield hasFocus(this.app.client)
    })

    it('selects the text', function *() {
      this.app.client
    })
  })

  describe('new tab', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
      yield newFrame(this.app.client)
    })

    it('displays the default url', function *() {
      yield defaultUrl(this.app.client)
    })

    it('has focus', function *() {
      yield hasFocus(this.app.client)
    })

    it('selects the text', function *() {
      yield selectsText(this.app.client)
    })
  })

  describe('submit', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
      // wait for the urlInput to be fully initialized
      yield selectsText(this.app.client)
      // hit enter
      yield this.app.client.keys('\uE007')
    })

    it('clears the selected text', function *() {
      yield selectsText(this.app.client, '')
    })

    it('gives focus to the webview')

    describe('url input value', function () {

    })

    describe('non-url input value', function () {

    })
  })

  describe('typing', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
      // wait for the urlInput to be fully initialized
      yield selectsText(this.app.client)
      // now type something
      yield this.app.client.keys('a')
    })

    it('sets the value', function *() {
      yield this.app.client.waitForValue(urlInput, 'a')
    })

    it('clears the selected text', function *() {
      yield selectsText(this.app.client, '')
    })

    describe('shortcut-focus-url', function () {
      before(function *() {
        yield this.app.client
          .ipcSend('shortcut-focus-url')
      })

      it('has focus', function *() {
        yield hasFocus(this.app.client)
      })

      it('selects the text', function *() {
        yield selectsText(this.app.client, 'a')
      })
    })

    describe('escape', function *() {
      before(function *() {
        yield this.app.client.ipcSend('shortcut-active-frame-stop')
      })

      it('reverts typing on escape', function *() {
        yield this.app.client.getValue(urlInput).should.eventually.be.equal(Config.defaultUrl)
        yield selectsText(this.app.client)
      })
    })
  })

  // need to move urlbar state to frame before enabling these
  describe('change tabs', function () {
    Brave.beforeAll(this)

    before(function *() {
      // default tab
      yield setup(this.app.client)
      // tab with typing
      yield newFrame(this.app.client)
      yield this.app.client.keys('a').waitForValue(urlInput, 'a')
    })

    describe('switch to default state tab', function () {
      before(function *() {
        yield this.app.client
          .ipcSend('shortcut-set-active-frame-by-index', 0)
          .waitForVisible('div[id="navigator"][data-frame-key="1"] ' + urlInput)
          // wait for selection??
      })

      it('preserves focused state', function *() {
        yield defaultUrl(this.app.client)
        yield hasFocus(this.app.client)
        yield selectsText(this.app.client)
      })
    })

    describe('switch to typing tab', function () {
      before(function *() {
        yield this.app.client
          .ipcSend('shortcut-set-active-frame-by-index', 1)
          .waitForVisible('div[id="navigator"][data-frame-key="2"] ' + urlInput)
      })

      it('preserves typing state', function *() {
        yield this.app.client.getValue(urlInput).should.eventually.be.equal('a')
        yield selectsText(this.app.client, '')
      })
    })
  })

  describe('click', function () {
    describe('blurred', function () {
      Brave.beforeAll(this)

      before(function *() {
        yield setup(this.app.client)
        yield blur(this.app.client)
        yield this.app.client
          .leftClick(urlInput)
      })

      it('displays the default url', function *() {
        yield defaultUrl(this.app.client)
      })

      it('has focus', function *() {
        yield hasFocus(this.app.client)
      })

      it('selects the text', function *() {
        yield selectsText(this.app.client)
      })
    })

    describe('focused', function () {
      Brave.beforeAll(this)

      before(function *() {
        yield setup(this.app.client)
        yield this.app.client
          .leftClick(urlInput)
      })

      it('displays the default url', function *() {
        yield defaultUrl(this.app.client)
      })

      it('has focus', function *() {
        yield hasFocus(this.app.client)
      })

      it('unselects the text', function *() {
        yield selectsText(this.app.client, '')
      })
    })
  })

  describe('shortcut-focus-url', function () {
    Brave.beforeAll(this)

    before(function *() {
      yield setup(this.app.client)
      yield blur(this.app.client)
      yield this.app.client.ipcSend('shortcut-focus-url')
    })

    it('displays the default url', function *() {
      yield defaultUrl(this.app.client)
    })

    it('has focus', function *() {
      yield hasFocus(this.app.client)
    })

    it('selects the text', function *() {
      yield selectsText(this.app.client)
    })
  })
})
<|endoftext|>


<commit_before>var winston = require('winston');

var util = require('util');

//var category1 = winston.loggers.get('category1');

var logger = winston.loggers.get('app_debug');

var qs = require('qs');
var session = require('koa-session');

function *call (func, params){

        var sql = util.format("select %s as rdata from %s('%s')", func, func, params);

        logger.log('debug', sql);

        var result = yield this.pg.db.client.query_(sql);

     yield this.pg.db.client.query_("commit");

        return result;

        }

module.exports = {

    pgtime:function *(){

            //how to catch?

            //throw("in test");
            //this.throw("in test", 500);

            var params = this.params; //qs.parse(this.request.body);
            logger.log(params);

            sql = "select now()";
            var result = yield this.pg.db.client.query_(sql);

            this.body = {"pgtime":result.rows[0].now};

    },

    call:function  (func, params){

        var sql = util.format("select %s as rdata from %s('%s')", func, func, params);

        logger.debug('debug', sql);
       // logger.debug("session", session);
       // var result = this.pg.db.client.query_(sql);

        //yield this.pg.db.client.query_("commit");

        //return result;

        },

    //web call
    wcall: function * () {
        /*
         * query db with yield
         */

        //default loggers

        var params = this.jsonrpc_params; //qs.parse(this.request.body);
        var method;

        if(params == undefined){

         this.throw("please provide params to callproc.call", 500)
        }

        if ("method" in params){
            method = params.method;
        }
        else{

            this.throw("please provide method to callproc.call", 500)
        }

        //var json_data = params.params;

        //console.log(typeof(json_data));  object

        logger.log('debug', JSON.stringify(params));

        logger.log('debug', this.jsonrpc_params);

    //var params2 = qs.parse(this.request.body);

    //logger.log('debug', JSON.stringify(params2.params));
        /*
        var func_name = "mtp_find_cf1";

        var json_data = {"table":"company",
            "kv":{
                "company":'abc1'
            },
            "context":{"user":'u1', "languageid":"1033", "sessionid":"123" }
            };
        */
        json_str = JSON.stringify(params);

        //escape "single quote"(')
        //modified on 2014-04-29 15:13:45
        if ( typeof (json_str) == 'string'){

            json_str = json_str.replace("'", "''");
            console.log(json_str);
        }
        else{

            this.throw("params undefined", 500);

        }

        /*
        var sql = util.format("select %s as rdata from %s('%s')", method, method, json_str);

        logger.log('debug', sql);

        var result = yield this.pg.db.client.query_(sql);
        */

        var result = yield callproc(method, json_str);

        logger.log(result);
        /*
        if(result.rowCount==0){
            this.body = {"error":"no data"};
        }
        *-/

        //console.log("result: %s", result);
        //var db_time = result.rows[0].now.toISOString();
        logger.log('debug', JSON.stringify(result));
        var data = result.rows[0].rdata;
        */
        //if (!data) return this.throw ('{"error":"no data"}', 404);

        error = {
            "code":"errorcode",
            "message":"error msg",
            "data":"error data"
        };

        this.body = result.rows[0].rdata;
        /*{
            //"error": null,
            //"result":params, // result or error, only one could be sent to client.
            "data":
        };*/
    }
};
<commit_msg>call proc<commit_after>var winston = require('winston');

var util = require('util');

//var category1 = winston.loggers.get('category1');

var logger = winston.loggers.get('app_debug');

var qs = require('qs');
//var session = require('koa-session');

function *call (func, params){

        var sql = util.format("select %s as rdata from %s('%s')", func, func, params);

        logger.log('debug', sql);

        var result = yield this.pg.db.client.query_(sql);

     yield this.pg.db.client.query_("commit");

        return result;

        }

module.exports = {

    pgtime:function *(){

            //how to catch?

            //throw("in test");
            //this.throw("in test", 500);

            var params = this.params; //qs.parse(this.request.body);
            logger.log(params);

            sql = "select now()";
            var result = yield this.pg.db.client.query_(sql);

            this.body = {"pgtime":result.rows[0].now};

    },

    call:function  (func, params){

        var sql = util.format("select %s as rdata from %s('%s')", func, func, params);

        logger.debug('debug', sql);
       // logger.debug("session", session);
       // var result = this.pg.db.client.query_(sql);

        //yield this.pg.db.client.query_("commit");

        //return result;

        },

    //web call
    wcall: function * () {
        /*
         * query db with yield
         */

        //default loggers

        var params = this.jsonrpc_params; //qs.parse(this.request.body);

         logger.log('debug', JSON.stringify(params));

        var method;

        if(params == undefined){

         this.throw("please provide params to callproc.call", 500)
        }

        if ("method" in params){
            method = params.method;
        }
        else{

            this.throw("please provide method to callproc.call", 500)
        }

        //var json_data = params.params;

        //console.log(typeof(json_data));  object

        logger.log('debug', JSON.stringify(params));

    //var params2 = qs.parse(this.request.body);

    //logger.log('debug', JSON.stringify(params2.params));
        /*
        var func_name = "mtp_find_cf1";

        var json_data = {"table":"company",
            "kv":{
                "company":'abc1'
            },
            "context":{"user":'u1', "languageid":"1033", "sessionid":"123" }
            };
        */
        json_str = JSON.stringify(params);

        //escape "single quote"(')
        //modified on 2014-04-29 15:13:45
        if ( typeof (json_str) == 'string'){

            json_str = json_str.replace("'", "''");
            console.log(json_str);
        }
        else{

            this.throw("params undefined", 500);

        }

        /*
        var sql = util.format("select %s as rdata from %s('%s')", method, method, json_str);

        logger.log('debug', sql);

        var result = yield this.pg.db.client.query_(sql);
        */

        //var result = yield call(method, json_str);

            var sql = util.format("select %s as rdata from %s('%s')", method, method, json_str);
            var result = yield this.pg.db.client.query_(sql);

            this.body = {"result":result};

        logger.log(result);
        /*
        if(result.rowCount==0){
            this.body = {"error":"no data"};
        }
        *-/

        //console.log("result: %s", result);
        //var db_time = result.rows[0].now.toISOString();
        logger.log('debug', JSON.stringify(result));
        var data = result.rows[0].rdata;
        */
        //if (!data) return this.throw ('{"error":"no data"}', 404);

        error = {
            "code":"errorcode",
            "message":"error msg",
            "data":"error data"
        };

        this.body = result.rows[0].rdata;
        /*{
            //"error": null,
            //"result":params, // result or error, only one could be sent to client.
            "data":
        };*/
    }
};
<|endoftext|>


<commit_before>import $ from 'jquery';
import _ from 'underscore';
import loadTemplate from '../../utils/loadTemplate';
import { clipboard } from 'electron';
import BaseVw from '../baseVw';
import app from '../../app';
import UserCard from '../userCard';
import { launchModeratorDetailsModal } from '../../utils/modalManager';
import { openSimpleMessage } from '../modals/SimpleMessage';

export default class extends BaseVw {
  constructor(options = {}) {
    super(options);
    this.options = options;

    this.ownPage = options.ownPage;

    this.userCard = new UserCard({ model: this.model, hideControls: true });

    this.settings = app.settings.clone();

    this.listenTo(this.settings, 'sync', () => {
      app.settings.set(this.settings.toJSON());
      this.$addModeratorLbl.toggleClass('hide', this.ownMod);
      this.$removeModeratorLbl.toggleClass('hide', !this.ownMod);
    });
  }

  className() {
    return 'userPageHome';
  }

  events() {
    return {
      'click .js-termsLink': 'termsClick',
      'click .js-addModerator': 'changeModeratorClick',
      'click .js-guid': 'guidClick',
      'mouseleave .js-guid': 'guidLeave',
    };
  }

  get ownMod() {
    return app.settings.get('storeModerators').indexOf(this.model.id) !== -1;
  }

  termsClick() {
    // show the moderator details modal
    const modModal = launchModeratorDetailsModal({ model: this.model });
    this.listenTo(modModal, 'addAsModerator', () => {
      this.$modBtn.addClass('processing');
      this.saveModeratorList(true);
    });
  }

  changeModeratorClick() {
    if (this.ownMod) {
      this.$modBtn.addClass('processing');
      this.saveModeratorList(false);
    } else {
      // show the moderator details modal
      const modModal = launchModeratorDetailsModal({ model: this.model });
      this.listenTo(modModal, 'addAsModerator', () => {
        this.$modBtn.addClass('processing');
        this.saveModeratorList(true);
      });
    }
  }

  saveModeratorList(add = false) {
    let modList = app.settings.get('storeModerators');

    if (add && !this.ownMod) {
      modList.push(this.model.id);
    } else {
      modList = _.without(modList, this.model.id);
    }

    const formData = { storeModerators: modList };
    this.settings.set(formData);

    if (!this.settings.validationError) {
      const msg = {
        msg: app.polyglot.t('userPage.status.saving'),
        type: 'message',
      };

      const statusMessage = app.statusBar.pushMessage({
        ...msg,
        duration: 9999999999999999,
      });

      this.settings.save(formData, {
        attrs: formData,
        type: 'PATCH',
      })
          .done(() => {
            statusMessage.update({
              msg: app.polyglot.t('userPage.status.done'),
              type: 'confirmed',
            });
          })
          .fail((...args) => {
            const errMsg = args[0] && args[0].responseJSON &&
                args[0].responseJSON.reason || '';
            openSimpleMessage(app.polyglot.t('userPage.status.error'), { errMsg });

            statusMessage.update({
              msg: app.polyglot.t('userPage.status.fail'),
              type: 'warning',
            });
          })
          .always(() => {
            this.$modBtn.removeClass('processing');
            setTimeout(() => statusMessage.remove(), 3000);
          });
    }
  }

  guidClick(e) {
    const guid = $(e.target).data('guid');
    clipboard.writeText(guid);
    this.$('.js-guidCopied').fadeIn(600);
  }

  guidLeave() {
    this.$('.js-guidCopied').fadeOut(600);
  }

  render() {
    loadTemplate('userPage/home.html', (t) => {
      this.$el.html(t({
        currentModerator: this.ownMod,
        displayCurrency: app.settings.get('localCurrency'),
        ...this.model.toJSON(),
      }));

      this.$('.js-userCard').append(this.userCard.render().$el)

      this.$modBtn = this.$('.js-addModerator');
      this.$addModeratorLbl = this.$('.js-addModeratorLbl');
      this.$removeModeratorLbl = this.$('.js-removeModeratorLbl');
    });

    return this;
  }
}

<commit_msg>fix missing semi colon<commit_after>import $ from 'jquery';
import _ from 'underscore';
import loadTemplate from '../../utils/loadTemplate';
import { clipboard } from 'electron';
import BaseVw from '../baseVw';
import app from '../../app';
import UserCard from '../userCard';
import { launchModeratorDetailsModal } from '../../utils/modalManager';
import { openSimpleMessage } from '../modals/SimpleMessage';

export default class extends BaseVw {
  constructor(options = {}) {
    super(options);
    this.options = options;

    this.ownPage = options.ownPage;

    this.userCard = new UserCard({ model: this.model, hideControls: true });

    this.settings = app.settings.clone();

    this.listenTo(this.settings, 'sync', () => {
      app.settings.set(this.settings.toJSON());
      this.$addModeratorLbl.toggleClass('hide', this.ownMod);
      this.$removeModeratorLbl.toggleClass('hide', !this.ownMod);
    });
  }

  className() {
    return 'userPageHome';
  }

  events() {
    return {
      'click .js-termsLink': 'termsClick',
      'click .js-addModerator': 'changeModeratorClick',
      'click .js-guid': 'guidClick',
      'mouseleave .js-guid': 'guidLeave',
    };
  }

  get ownMod() {
    return app.settings.get('storeModerators').indexOf(this.model.id) !== -1;
  }

  termsClick() {
    // show the moderator details modal
    const modModal = launchModeratorDetailsModal({ model: this.model });
    this.listenTo(modModal, 'addAsModerator', () => {
      this.$modBtn.addClass('processing');
      this.saveModeratorList(true);
    });
  }

  changeModeratorClick() {
    if (this.ownMod) {
      this.$modBtn.addClass('processing');
      this.saveModeratorList(false);
    } else {
      // show the moderator details modal
      const modModal = launchModeratorDetailsModal({ model: this.model });
      this.listenTo(modModal, 'addAsModerator', () => {
        this.$modBtn.addClass('processing');
        this.saveModeratorList(true);
      });
    }
  }

  saveModeratorList(add = false) {
    let modList = app.settings.get('storeModerators');

    if (add && !this.ownMod) {
      modList.push(this.model.id);
    } else {
      modList = _.without(modList, this.model.id);
    }

    const formData = { storeModerators: modList };
    this.settings.set(formData);

    if (!this.settings.validationError) {
      const msg = {
        msg: app.polyglot.t('userPage.status.saving'),
        type: 'message',
      };

      const statusMessage = app.statusBar.pushMessage({
        ...msg,
        duration: 9999999999999999,
      });

      this.settings.save(formData, {
        attrs: formData,
        type: 'PATCH',
      })
          .done(() => {
            statusMessage.update({
              msg: app.polyglot.t('userPage.status.done'),
              type: 'confirmed',
            });
          })
          .fail((...args) => {
            const errMsg = args[0] && args[0].responseJSON &&
                args[0].responseJSON.reason || '';
            openSimpleMessage(app.polyglot.t('userPage.status.error'), { errMsg });

            statusMessage.update({
              msg: app.polyglot.t('userPage.status.fail'),
              type: 'warning',
            });
          })
          .always(() => {
            this.$modBtn.removeClass('processing');
            setTimeout(() => statusMessage.remove(), 3000);
          });
    }
  }

  guidClick(e) {
    const guid = $(e.target).data('guid');
    clipboard.writeText(guid);
    this.$('.js-guidCopied').fadeIn(600);
  }

  guidLeave() {
    this.$('.js-guidCopied').fadeOut(600);
  }

  render() {
    loadTemplate('userPage/home.html', (t) => {
      this.$el.html(t({
        currentModerator: this.ownMod,
        displayCurrency: app.settings.get('localCurrency'),
        ...this.model.toJSON(),
      }));

      this.$('.js-userCard').append(this.userCard.render().$el);

      this.$modBtn = this.$('.js-addModerator');
      this.$addModeratorLbl = this.$('.js-addModeratorLbl');
      this.$removeModeratorLbl = this.$('.js-removeModeratorLbl');
    });

    return this;
  }
}

<|endoftext|>


<commit_before>// namespace :
var GNOVEL = GNOVEL || {};

(function() {
	"use strict";

	/**
	 * Transition to next scene over certain time
	 * @class Transition
	 * @constructor
	 * @param {time} time for transition to play, in milliseconds
	 **/
	var Transition = function(time, scene, curPageRT, nextPageRT) {
		this.time = time || 400;

		this._width = 1920;
		this._height = 1080;
		this._scene = scene;

		var texture = THREE.ImageUtils.loadTexture("/static/gnovel/res/textures/ui/comic book with panels.png");
		var material = new THREE.MeshBasicMaterial({
			color: 0xffffff,
			transparent: true,
			map: texture
		});

		var plane = new THREE.PlaneBufferGeometry(this._width, this._height);
		this.transitionPanel = new THREE.Mesh(plane, material);
		this.transitionPanel.name = "transitionPanel";
		var transitionPanel = this.transitionPanel;

		var redMaterial = new THREE.MeshBasicMaterial({
			transparent: true,
			map: curPageRT,
		});

		var blueMaterial = new THREE.MeshBasicMaterial({
			// color: 0x0000ff,
			transparent: true,
			map: nextPageRT,
		});
		var plane1 = new THREE.PlaneBufferGeometry(this._width, this._height);
		var plane2 = new THREE.PlaneBufferGeometry(this._width, this._height);

		var curPageBg = new THREE.Mesh(plane1, redMaterial);
		curPageBg.position.setX(-10);
		curPageBg.position.setZ(3);
		curPageBg.scale.set(0.33, 0.33, 1);
		curPageBg.name = "curPageBg";
		transitionPanel.add(curPageBg);
		this._curPageBg = curPageBg;

		var nextPageBg = new THREE.Mesh(plane2, blueMaterial);
		nextPageBg.position.setX(635);
		nextPageBg.position.setZ(3);
		nextPageBg.scale.set(0.33, 0.33, 1);
		nextPageBg.name = "nextPageBg";
		transitionPanel.add(nextPageBg);
		this._nextPageBg = nextPageBg;

		var container = new THREE.Object3D();
		this._container = container;
	};

	/**
	 * Do Transition
	 * @param {currentPage} currentPage, the current page to be tansitioned from
	 * @param {nextPage} the new page to show
	 **/
	Transition.prototype.run = function(currentPage, nextPage, params) {
		if (params.transitionType === GNOVEL.TransitionType.COMIC_SLIDE) {
			this._comicSlide(currentPage, nextPage, params);
		} else {
			this._fade(currentPage, nextPage, params);
		}
	};

	Transition.prototype._fade = function(currentPage, nextPage, params) {
		var duration = this.time;
		var transition = this;
		var gnovelObj = currentPage.getOwner();

		var geometry = new THREE.PlaneBufferGeometry(1920, 1080);
		var material = new THREE.MeshBasicMaterial({
			color: 0x000000,
			transparent: true,
		});
		var transitionBgImg = new THREE.Mesh(geometry, material);
		transitionBgImg.material.opacity = 0;
		transitionBgImg.position.z = 210;

		// fade out current scene
		gnovelObj._scene.add(transitionBgImg);

		this._runOnHierarchy(transitionBgImg, {
			opacity: 1,
		}, {
			duration: duration / 2,
			onComplete: function() {

				params.onSafeToUnload();
				params.onComplete();

				transition._runOnHierarchy(transitionBgImg, {
					opacity: 0,
				}, {
					duration: duration / 2,
					onComplete: function() {
						gnovelObj._scene.remove(transitionBgImg);
					}
				});
			}
		});

	};

	Transition.prototype._comicSlide = function(currentPage, nextPage, params) {
		var duration = this.time;
		var transition = this;
		var transitionPanel = this.transitionPanel;
		var gnovelObj = currentPage.getOwner();
		var scene = this._scene;
		var container = this._container;

		var farZ = -300;
		var leftX = -633;
		var initialScale = 1.65;
		var initialX = 18;
		var toScale = 1.2;
		var initialZ = 270;

		console.log("transition is running");

		// transitionPanel.position.set(0, 0, initialZ);
		// transitionPanel.scale.set(initialScale, initialScale, 1);
		// this._scene.add(transitionPanel);

		var nextPageTexture = THREE.ImageUtils.loadTexture(nextPage.nextPageMaterialPath);
		var nextPageMaterial = new THREE.MeshBasicMaterial({
			transparent: true,
			map: nextPageTexture,
		});
		transitionPanel.children[1].material = nextPageMaterial;

		container.position.set(initialX, 0, initialZ);
		container.scale.set(initialScale, initialScale, 1);
		container.add(transitionPanel);
		this._scene.add(container);
		transitionPanel.position.set(0, 0, 0);

		this._runOnHierarchy(container, {
			opacity: 1
		}, {
			duration: duration,
			onComplete: function() {

				params.onSafeToUnload();

				//zoom out the transition panel
				transition._scale(container, {
					duration: duration,
					easing: TWEEN.Easing.Cubic.Out,
					// z: farZ,
					x: toScale,
					y: toScale,
					onComplete: function() {

						// wait for several second
						transition._wait({
							duration: .5,
							onComplete: function() {

								// move transition panel to the left
								transition._move(transitionPanel, {
									x: leftX,
									duration: duration,
									easing: TWEEN.Easing.Cubic.Out,
									onComplete: function() {

										// zoom in transition panel
										transition._scale(container, {
											duration: duration,
											// z: initialZ,
											x: initialScale,
											y: initialScale,
											easing: TWEEN.Easing.Cubic.Out,
											onComplete: function() {

												params.onComplete();

												transition._runOnHierarchy(container, {
													opacity: 0
												}, {
													duration: duration,
													onComplete: function() {
														//remove transitionPanel
														// gnovelObj._scene.remove(transitionPanel);
														scene.remove(container);
														// scene.remove(transitionPanel);
														//params.onComplete();
													}
												});

											}
										});

									}
								});
							}
						});
					}
				});
			}
		});
	};

	//pause tween
	Transition.prototype._wait = function(params) {
		var o = {
			val: 0
		};
		var waitDuration = params.duration || .5;
		var wait = new TWEEN.Tween(o)
			.to({
				val: 1,
			}, waitDuration * 1000);

		if (params.onComplete != null) {
			wait.onComplete(params.onComplete);
		};

		wait.start();
	};

	Transition.prototype._move = function(obj, params) {
		var duration = params.duration || 1000;

		var tween = new TWEEN.Tween(obj.position)
			.to({
				x: (params.x !== null ? params.x : obj.position.x),
				y: (params.y !== null ? params.y : obj.positions.y),
				z: (params.z !== null ? params.z : obj.position.z),
			}, duration)
			.easing(params.easing || TWEEN.Easing.Linear.None);
		if (params.onComplete != null) {
			tween.onComplete(params.onComplete);
		}
		tween.start();
	};

	Transition.prototype._scale = function(obj, params) {
		var duration = params.duration || 1000;

		var tween = new TWEEN.Tween(obj.scale)
			.to({
				x: (params.x !== null ? params.x : obj.scale.x),
				y: (params.y !== null ? params.y : obj.scale.y),
				z: (params.z !== null ? params.z : obj.scale.z),
			}, duration)
			.easing(params.easing || TWEEN.Easing.Linear.None);
		if (params.onComplete != null) {
			tween.onComplete(params.onComplete);
		}
		tween.start();
	};

	Transition.prototype._runOnHierarchy = function(h, toObj, params) {
		var duration = params.duration;
		var isOnCompleteAdded = false;

		h.traverseVisible(function(obj3d) {
			if (obj3d.material == null)
				return;

			if (toObj.opacity == 1)
				obj3d.material.opacity = 0;
			else
				obj3d.material.opacity = 1;

			//tween opacity for fade over duration time
			var tween = new TWEEN.Tween(obj3d.material)
				.to(toObj, duration).easing(TWEEN.Easing.Cubic.Out);

			if (params != null) {
				if (params.onComplete != null && !isOnCompleteAdded) {
					tween.onComplete(params.onComplete);
					isOnCompleteAdded = true;
				}
			}
			tween.start();
		});

	};

	// transition type
	GNOVEL.TransitionType = {};
	GNOVEL.TransitionType.FADE = 0;
	GNOVEL.TransitionType.COMIC_SLIDE = 1;

	GNOVEL.Transition = Transition;

}());
<commit_msg>Remove unnecesary code in transition<commit_after>// namespace :
var GNOVEL = GNOVEL || {};

(function() {
	"use strict";

	/**
	 * Transition to next scene over certain time
	 * @class Transition
	 * @constructor
	 * @param {time} time for transition to play, in milliseconds
	 **/
	var Transition = function(time, scene, curPageRT, nextPageRT) {
		this.time = time || 400;

		this._width = 1920;
		this._height = 1080;
		this._scene = scene;

		var texture = THREE.ImageUtils.loadTexture("/static/gnovel/res/textures/ui/comic book with panels.png");
		var material = new THREE.MeshBasicMaterial({
			color: 0xffffff,
			transparent: true,
			map: texture
		});

		var plane = new THREE.PlaneBufferGeometry(this._width, this._height);
		this.transitionPanel = new THREE.Mesh(plane, material);
		this.transitionPanel.name = "transitionPanel";
		var transitionPanel = this.transitionPanel;

		var redMaterial = new THREE.MeshBasicMaterial({
			transparent: true,
			map: curPageRT,
		});

		var blueMaterial = new THREE.MeshBasicMaterial({
			// color: 0x0000ff,
			transparent: true,
			map: nextPageRT,
		});
		var plane1 = new THREE.PlaneBufferGeometry(this._width, this._height);
		var plane2 = new THREE.PlaneBufferGeometry(this._width, this._height);

		var curPageBg = new THREE.Mesh(plane1, redMaterial);
		curPageBg.position.setX(-10);
		curPageBg.position.setZ(3);
		curPageBg.scale.set(0.33, 0.33, 1);
		curPageBg.name = "curPageBg";
		transitionPanel.add(curPageBg);
		this._curPageBg = curPageBg;

		var nextPageBg = new THREE.Mesh(plane2, blueMaterial);
		nextPageBg.position.setX(635);
		nextPageBg.position.setZ(3);
		nextPageBg.scale.set(0.33, 0.33, 1);
		nextPageBg.name = "nextPageBg";
		transitionPanel.add(nextPageBg);
		this._nextPageBg = nextPageBg;

		var container = new THREE.Object3D();
		this._container = container;
	};

	/**
	 * Do Transition
	 * @param {currentPage} currentPage, the current page to be tansitioned from
	 * @param {nextPage} the new page to show
	 **/
	Transition.prototype.run = function(currentPage, nextPage, params) {
		if (params.transitionType === GNOVEL.TransitionType.COMIC_SLIDE) {
			this._comicSlide(currentPage, nextPage, params);
		} else {
			this._fade(currentPage, nextPage, params);
		}
	};

	Transition.prototype._fade = function(currentPage, nextPage, params) {
		var duration = this.time;
		var transition = this;
		var gnovelObj = currentPage.getOwner();

		var geometry = new THREE.PlaneBufferGeometry(1920, 1080);
		var material = new THREE.MeshBasicMaterial({
			color: 0x000000,
			transparent: true,
		});
		var transitionBgImg = new THREE.Mesh(geometry, material);
		transitionBgImg.material.opacity = 0;
		transitionBgImg.position.z = 210;

		// fade out current scene
		gnovelObj._scene.add(transitionBgImg);

		this._runOnHierarchy(transitionBgImg, {
			opacity: 1,
		}, {
			duration: duration / 2,
			onComplete: function() {

				params.onSafeToUnload();
				params.onComplete();

				transition._runOnHierarchy(transitionBgImg, {
					opacity: 0,
				}, {
					duration: duration / 2,
					onComplete: function() {
						gnovelObj._scene.remove(transitionBgImg);
					}
				});
			}
		});

	};

	Transition.prototype._comicSlide = function(currentPage, nextPage, params) {
		var duration = this.time;
		var transition = this;
		var transitionPanel = this.transitionPanel;
		var gnovelObj = currentPage.getOwner();
		var scene = this._scene;
		var container = this._container;

		var farZ = -300;
		var leftX = -633;
		var initialScale = 1.65;
		var initialX = 18;
		var toScale = 1.2;
		var initialZ = 270;

		console.log("transition is running");

		// transitionPanel.position.set(0, 0, initialZ);
		// transitionPanel.scale.set(initialScale, initialScale, 1);
		// this._scene.add(transitionPanel);

		var nextPageTexture = THREE.ImageUtils.loadTexture(nextPage.nextPageMaterialPath);
		this._nextPageBg.material.map = nextPageTexture;

		container.position.set(initialX, 0, initialZ);
		container.scale.set(initialScale, initialScale, 1);
		container.add(transitionPanel);
		this._scene.add(container);
		transitionPanel.position.set(0, 0, 0);

		this._runOnHierarchy(container, {
			opacity: 1
		}, {
			duration: duration,
			onComplete: function() {

				params.onSafeToUnload();

				//zoom out the transition panel
				transition._scale(container, {
					duration: duration,
					easing: TWEEN.Easing.Cubic.Out,
					// z: farZ,
					x: toScale,
					y: toScale,
					onComplete: function() {

						// wait for several second
						transition._wait({
							duration: .5,
							onComplete: function() {

								// move transition panel to the left
								transition._move(transitionPanel, {
									x: leftX,
									duration: duration,
									easing: TWEEN.Easing.Cubic.Out,
									onComplete: function() {

										// zoom in transition panel
										transition._scale(container, {
											duration: duration,
											// z: initialZ,
											x: initialScale,
											y: initialScale,
											easing: TWEEN.Easing.Cubic.Out,
											onComplete: function() {

												params.onComplete();

												transition._runOnHierarchy(container, {
													opacity: 0
												}, {
													duration: duration,
													onComplete: function() {
														//remove transitionPanel
														// gnovelObj._scene.remove(transitionPanel);
														scene.remove(container);
														// scene.remove(transitionPanel);
														//params.onComplete();
													}
												});

											}
										});

									}
								});
							}
						});
					}
				});
			}
		});
	};

	//pause tween
	Transition.prototype._wait = function(params) {
		var o = {
			val: 0
		};
		var waitDuration = params.duration || .5;
		var wait = new TWEEN.Tween(o)
			.to({
				val: 1,
			}, waitDuration * 1000);

		if (params.onComplete != null) {
			wait.onComplete(params.onComplete);
		};

		wait.start();
	};

	Transition.prototype._move = function(obj, params) {
		var duration = params.duration || 1000;

		var tween = new TWEEN.Tween(obj.position)
			.to({
				x: (params.x !== null ? params.x : obj.position.x),
				y: (params.y !== null ? params.y : obj.positions.y),
				z: (params.z !== null ? params.z : obj.position.z),
			}, duration)
			.easing(params.easing || TWEEN.Easing.Linear.None);
		if (params.onComplete != null) {
			tween.onComplete(params.onComplete);
		}
		tween.start();
	};

	Transition.prototype._scale = function(obj, params) {
		var duration = params.duration || 1000;

		var tween = new TWEEN.Tween(obj.scale)
			.to({
				x: (params.x !== null ? params.x : obj.scale.x),
				y: (params.y !== null ? params.y : obj.scale.y),
				z: (params.z !== null ? params.z : obj.scale.z),
			}, duration)
			.easing(params.easing || TWEEN.Easing.Linear.None);
		if (params.onComplete != null) {
			tween.onComplete(params.onComplete);
		}
		tween.start();
	};

	Transition.prototype._runOnHierarchy = function(h, toObj, params) {
		var duration = params.duration;
		var isOnCompleteAdded = false;

		h.traverseVisible(function(obj3d) {
			if (obj3d.material == null)
				return;

			if (toObj.opacity == 1)
				obj3d.material.opacity = 0;
			else
				obj3d.material.opacity = 1;

			//tween opacity for fade over duration time
			var tween = new TWEEN.Tween(obj3d.material)
				.to(toObj, duration).easing(TWEEN.Easing.Cubic.Out);

			if (params != null) {
				if (params.onComplete != null && !isOnCompleteAdded) {
					tween.onComplete(params.onComplete);
					isOnCompleteAdded = true;
				}
			}
			tween.start();
		});

	};

	// transition type
	GNOVEL.TransitionType = {};
	GNOVEL.TransitionType.FADE = 0;
	GNOVEL.TransitionType.COMIC_SLIDE = 1;

	GNOVEL.Transition = Transition;

}());
<|endoftext|>


<commit_before>FuzzyOctoTribble.CombatControlCreatorConstructor = function () {
    var that = {};

    var selectingTarget = false;
    var onTargetSelected;
    var $currentDefaultScreen, $currentCommandScreen;
    var gameOver = false;
    var inCombat = false;

    var createCommand = function (currentCommand, currentCharacter, sendingCommand, onComplete) {
        var executeFinalCommand = function (cmd) {
            selectingTarget = false;
            $.ajax({
                type: 'POST',
                url: 'Game/executeCommand',
                cache: false,
                data: JSON.stringify(cmd),
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    fullData = data;
                    $.ajax("Game/getCommands", {
                        success: function (commandData) {
                            fullData.commands = commandData;
                            that.create(fullData);
                        }
                    });
                }
            });
        }

        if (!sendingCommand) {
            var sendingCommand = {};
        }
        if (!onComplete) {
            var onComplete = function () {
                executeFinalCommand(sendingCommand);
            }
        }

        var commandText;
        commandText = currentCommand.name;
        if (currentCommand.mpNeeded) {
            commandText = currentCommand.mpCost + ' MP - ' + currentCommand.name;
        }
        if (currentCommand.limitedUsage) {
            commandText += " " + currentCommand.uses + "/" + currentCommand.totalUses;
        }

        var item = {
            text: commandText,
            selected: function () {
                sendingCommand.commandName = currentCommand.name;
                sendingCommand.hasSubCommand = false;
                sendingCommand.subCommand = {};
                sendingCommand.targets = [];

                if (currentCommand.hasTarget) {
                    selectingTarget = true;
                    $currentDefaultScreen.isCombat = true;
                    FuzzyOctoTribble.KeyControl.addController($currentDefaultScreen);
                    $currentDefaultScreen.onCurrentControl();
                    onTargetSelected = function (characterUniq) {
                        sendingCommand.targets.push(characterUniq);
                        $currentDefaultScreen.onComplete();
                        $currentDefaultScreen.clearCurrentControl();
                        onComplete();
                    }
                }
                else if (currentCommand.hasChildCommands) {
                    $currentCommandScreen = createCommandSelectionScreen(currentCommand.childCommands, currentCharacter, sendingCommand.subCommand, onComplete);
                    $currentCommandScreen.show();
                    FuzzyOctoTribble.KeyControl.addController($currentCommandScreen);
                }
                else {
                    onComplete();
                }
            },
            isDisabled: currentCommand.isDisabled
        }
        return item;
    }

    var createCommandSelectionScreen = function (commands, currentCharacter, sendingCommand, onComplete) {
        var items = [];
        for (var i = 0; i < commands.length; i++) {
            var currentCommand = commands[i];
            items.push(createCommand(currentCommand, currentCharacter, sendingCommand, onComplete));
        }
        var spec = {
            items: items,
            closeOnMenu: true,
            header: currentCharacter + ":",
            isCombat: true,
            additionalClasses: 'combat-screen',
            delayShow: true
        }
        var my = {};

        return FuzzyOctoTribble.Menu(spec, my);
    }

    var processEffects = function (effects) {
        if (effects.length === 0) {
            return;
        }
        var currentEffect = effects.shift();
        switch (currentEffect.type) {
            case 0: //Simple Message effects
                var messageSpec = {};
                messageSpec.dialogContent = currentEffect.message;
                messageSpec.onComplete = function () {
                    if (effects.length !== 0) {
                        processEffects(effects);
                    }
                }

                FuzzyOctoTribble.KeyControl.addController(FuzzyOctoTribble.DialogBox(messageSpec, {}));
                break;
            case 1: //Deal damage to target
                var targetUniq = currentEffect.targetUniq;
                var damage = currentEffect.value;
                FuzzyOctoTribble.CombatScreenCreator.numberAnimation('-' + damage, targetUniq, '#FF0000', 32);
                processEffects(effects);
                break;
            case 2: //Heal the target
                var targetUniq = currentEffect.targetUniq;
                var heal = currentEffect.value;
                FuzzyOctoTribble.CombatScreenCreator.numberAnimation('+' + heal, targetUniq, '#00FF00', 32);
                processEffects(effects);
                break;
            case 3: //Destroy the character
                var targetUniq = currentEffect.targetUniq;
                FuzzyOctoTribble.CombatScreenCreator.numberAnimation('DEFEATED', targetUniq, '#FF0000', 44);
                processEffects(effects);
                break;
            case 4: //Combat has ended
                FuzzyOctoTribble.KeyControl.removeCombat();
                if (gameOver) {
                    FuzzyOctoTribble.MaintainState.updateMap();
                }
                inCombat = false;
                break;
            case 5: //Game over
                FuzzyOctoTribble.CombatScreenCreator.gameOverAnimation();
                gameOver = true;
                processEffects(effects);
                inCombat = false;
                break;
            case 6: //Show Command Screen
                $currentCommandScreen.show();
                FuzzyOctoTribble.KeyControl.addController($currentCommandScreen);
                processEffects(effects);
                break;
            case 7: //End turn
                FuzzyOctoTribble.CombatAccess.continueCombat();
                break;

        }
    }

    that.createCommandSelectionScreen = createCommandSelectionScreen;

    that.createCharacterDetailScreen = function($detailScreen) {
        var that = {};

        $('.game-window').append($detailScreen);

        that.isCombat = true;
        that.isDetailWindow = true;

        that.close = function () {
            that.cancel();
        }

        that.cancel = function () {
            $detailScreen.remove();
            if (that.onComplete) {
                that.onComplete();
            }
        }

        that.menu = function () {
            that.cancel();
        }
        return that;
    }

    that.createBaseScreen = function (allies, enemies, commands, currentCharacter) {
        var that = {};

        var pcCurrentlySelected = false;
        var currentSelection = 0;

        var onCharacterSelect = function (character) {
            if (selectingTarget) {
                onTargetSelected(character.uniq);
            }
            else if (that.hasCurrentControl) {
                var $detailScreen = FuzzyOctoTribble.CombatScreenCreator.getDetailedScreen(character);
                FuzzyOctoTribble.KeyControl.removeWindows('isDetailWindow');
                FuzzyOctoTribble.KeyControl.addController(FuzzyOctoTribble.CombatControlCreator.createCharacterDetailScreen($detailScreen));
            }
        }

        for (var i = 0; i < allies.length; i++) {
            allies[i].selected = onCharacterSelect;
        }

        for (var i = 0; i < enemies.length; i++) {
            enemies[i].selected = onCharacterSelect;
        }

        $('.combat-screen').remove();
        var $initialScreen = FuzzyOctoTribble.CombatScreenCreator.loadInitialScreen({
            allies: allies,
            enemies: enemies
        });

        $('.game-window').append($initialScreen);

        that.isCombat = true;

        that.close = function () {
            $initialScreen.remove();
            if (that.onComplete) {
                that.onComplete();
            }
        }

        that.onCurrentControl = function () {
            $initialScreen.find('.character-display-screen').addClass('character-display-screen-selectable');
            selectCurrent();
        }

        that.clearCurrentControl = function () {
            $initialScreen.find('.character-display-screen').removeClass('character-display-screen-selectable');
        }

        var deselectCurrent = function () {
            if (pcCurrentlySelected) {
                allies[currentSelection].onDeselect();
            }
            else {
                enemies[currentSelection].onDeselect();
            }
        }

        var selectCurrent = function () {
            if (pcCurrentlySelected) {
                allies[currentSelection].onSelect();
            }
            else {
                enemies[currentSelection].onSelect();
            }
        }

        that.pressLeft = function () {

        }

        that.pressUp = function () {

        }

        that.pressRight = function () {

        }

        that.pressDown = function () {

        }

        that.releaseLeft = function () {
            if (currentSelection != 0) {
                deselectCurrent();
                currentSelection--;
                selectCurrent();
            }
        }

        that.releaseUp = function () {
            deselectCurrent();
            pcCurrentlySelected = false;
            if (currentSelection >= enemies.length) {
                currentSelection = enemies.length - 1;
            }
            selectCurrent();
        }

        that.releaseDown = function () {
            deselectCurrent();
            pcCurrentlySelected = true;
            if (currentSelection >= allies.length) {
                currentSelection = allies.length - 1;
            }
            selectCurrent();
        }

        that.releaseRight = function () {
            if ((pcCurrentlySelected && currentSelection < allies.length - 1) ||
                (!pcCurrentlySelected && currentSelection < enemies.length - 1)) {
                deselectCurrent();
                currentSelection++;
                selectCurrent();
            }
        }

        that.confirm = function () {
            if (pcCurrentlySelected) {
                allies[currentSelection].click();
            }
            else {
                enemies[currentSelection].click();
            }
        }

        that.cancel = function () {
            if (FuzzyOctoTribble.KeyControl.previousIsCombat()) {
                if (this.onComplete) {
                    this.onComplete();
                }
            }
            else {
                that.menu();
            }
        }

        that.menu = function () {
            $currentCommandScreen = createCommandSelectionScreen(commands, currentCharacter);
            $currentCommandScreen.show();
            FuzzyOctoTribble.KeyControl.addController($currentCommandScreen);
        }

        return that;
    }

    that.create = function (spec, my) {
        $currentDefaultScreen = that.createBaseScreen(spec.characterDisplays, spec.npcDisplays, spec.commands, spec.currentCharacter);
        FuzzyOctoTribble.KeyControl.addController($currentDefaultScreen);
        $currentCommandScreen = that.createCommandSelectionScreen(spec.commands, spec.currentCharacter);
        if (spec.effects.length !== 0) {
            processEffects(spec.effects);
        }
        inCombat = true;
    }

    that.inCombat = function () {
        return inCombat;
    }

    return that;
}<commit_msg>Fixed a bug with key controls in the combat gui<commit_after>FuzzyOctoTribble.CombatControlCreatorConstructor = function () {
    var that = {};

    var selectingTarget = false;
    var onTargetSelected;
    var $currentDefaultScreen, $currentCommandScreen;
    var gameOver = false;
    var inCombat = false;

    var createCommand = function (currentCommand, currentCharacter, sendingCommand, onComplete) {
        var executeFinalCommand = function (cmd) {
            selectingTarget = false;
            $.ajax({
                type: 'POST',
                url: 'Game/executeCommand',
                cache: false,
                data: JSON.stringify(cmd),
                dataType: 'json',
                contentType: 'application/json; charset=utf-8',
                success: function (data) {
                    fullData = data;
                    $.ajax("Game/getCommands", {
                        success: function (commandData) {
                            fullData.commands = commandData;
                            that.create(fullData);
                        }
                    });
                }
            });
        }

        if (!sendingCommand) {
            var sendingCommand = {};
        }
        if (!onComplete) {
            var onComplete = function () {
                executeFinalCommand(sendingCommand);
            }
        }

        var commandText;
        commandText = currentCommand.name;
        if (currentCommand.mpNeeded) {
            commandText = currentCommand.mpCost + ' MP - ' + currentCommand.name;
        }
        if (currentCommand.limitedUsage) {
            commandText += " " + currentCommand.uses + "/" + currentCommand.totalUses;
        }

        var item = {
            text: commandText,
            selected: function () {
                sendingCommand.commandName = currentCommand.name;
                sendingCommand.hasSubCommand = false;
                sendingCommand.subCommand = {};
                sendingCommand.targets = [];

                if (currentCommand.hasTarget) {
                    selectingTarget = true;
                    $currentDefaultScreen.isCombat = true;
                    FuzzyOctoTribble.KeyControl.addController($currentDefaultScreen);
                    $currentDefaultScreen.onCurrentControl();
                    onTargetSelected = function (characterUniq) {
                        sendingCommand.targets.push(characterUniq);
                        $currentDefaultScreen.onComplete();
                        $currentDefaultScreen.clearCurrentControl();
                        onComplete();
                    }
                }
                else if (currentCommand.hasChildCommands) {
                    $currentCommandScreen = createCommandSelectionScreen(currentCommand.childCommands, currentCharacter, sendingCommand.subCommand, onComplete);
                    $currentCommandScreen.show();
                    FuzzyOctoTribble.KeyControl.addController($currentCommandScreen);
                }
                else {
                    onComplete();
                }
            },
            isabled: currentCommand.isDisabled
        }
        return item;
    }

    var createCommandSelectionScreen = function (commands, currentCharacter, sendingCommand, onComplete) {
        var items = [];
        for (var i = 0; i < commands.length; i++) {
            var currentCommand = commands[i];
            items.push(createCommand(currentCommand, currentCharacter, sendingCommand, onComplete));
        }
        var spec = {
            items: items,
            closeOnMenu: true,
            header: currentCharacter + ":",
            isCombat: true,
            additionalClasses: 'combat-screen',
            delayShow: true
        }
        var my = {};

        return FuzzyOctoTribble.Menu(spec, my);
    }

    var processEffects = function (effects) {
        if (effects.length === 0) {
            return;
        }
        var currentEffect = effects.shift();
        switch (currentEffect.type) {
            case 0: //Simple Message effects
                var messageSpec = {};
                messageSpec.dialogContent = currentEffect.message;
                messageSpec.onComplete = function () {
                    if (effects.length !== 0) {
                        processEffects(effects);
                    }
                }

                FuzzyOctoTribble.KeyControl.addController(FuzzyOctoTribble.DialogBox(messageSpec, {}));
                break;
            case 1: //Deal damage to target
                var targetUniq = currentEffect.targetUniq;
                var damage = currentEffect.value;
                FuzzyOctoTribble.CombatScreenCreator.numberAnimation('-' + damage, targetUniq, '#FF0000', 32);
                processEffects(effects);
                break;
            case 2: //Heal the target
                var targetUniq = currentEffect.targetUniq;
                var heal = currentEffect.value;
                FuzzyOctoTribble.CombatScreenCreator.numberAnimation('+' + heal, targetUniq, '#00FF00', 32);
                processEffects(effects);
                break;
            case 3: //Destroy the character
                var targetUniq = currentEffect.targetUniq;
                FuzzyOctoTribble.CombatScreenCreator.numberAnimation('DEFEATED', targetUniq, '#FF0000', 44);
                processEffects(effects);
                break;
            case 4: //Combat has ended
                FuzzyOctoTribble.KeyControl.removeCombat();
                if (gameOver) {
                    FuzzyOctoTribble.MaintainState.updateMap();
                }
                inCombat = false;
                break;
            case 5: //Game over
                FuzzyOctoTribble.CombatScreenCreator.gameOverAnimation();
                gameOver = true;
                processEffects(effects);
                inCombat = false;
                break;
            case 6: //Show Command Screen
                $currentCommandScreen.show();
                FuzzyOctoTribble.KeyControl.addController($currentCommandScreen);
                processEffects(effects);
                break;
            case 7: //End turn
                FuzzyOctoTribble.CombatAccess.continueCombat();
                break;

        }
    }

    that.createCommandSelectionScreen = createCommandSelectionScreen;

    that.createCharacterDetailScreen = function($detailScreen) {
        var that = {};

        $('.game-window').append($detailScreen);

        that.isCombat = true;
        that.isDetailWindow = true;

        that.close = function () {
            that.cancel();
        }

        that.cancel = function () {
            $detailScreen.remove();
            if (that.onComplete) {
                that.onComplete();
            }
        }

        that.menu = function () {
            that.cancel();
        }
        return that;
    }

    that.createBaseScreen = function (allies, enemies, commands, currentCharacter) {
        var that = {};

        var pcCurrentlySelected = false;
        var currentSelection = 0;

        var onCharacterSelect = function (character) {
            if (selectingTarget) {
                onTargetSelected(character.uniq);
            }
            else if (that.hasCurrentControl) {
                var $detailScreen = FuzzyOctoTribble.CombatScreenCreator.getDetailedScreen(character);
                FuzzyOctoTribble.KeyControl.removeWindows('isDetailWindow');
                FuzzyOctoTribble.KeyControl.addController(FuzzyOctoTribble.CombatControlCreator.createCharacterDetailScreen($detailScreen));
            }
        }

        for (var i = 0; i < allies.length; i++) {
            allies[i].selected = onCharacterSelect;
        }

        for (var i = 0; i < enemies.length; i++) {
            enemies[i].selected = onCharacterSelect;
        }

        $('.combat-screen').remove();
        var $initialScreen = FuzzyOctoTribble.CombatScreenCreator.loadInitialScreen({
            allies: allies,
            enemies: enemies
        });

        $('.game-window').append($initialScreen);

        that.isCombat = true;

        that.close = function () {
            $initialScreen.remove();
            if (that.onComplete) {
                that.onComplete();
            }
        }

        that.onCurrentControl = function () {
            $initialScreen.find('.character-display-screen').addClass('character-display-screen-selectable');
            selectCurrent();
        }

        that.clearCurrentControl = function () {
            $initialScreen.find('.character-display-screen').removeClass('character-display-screen-selectable');
        }

        var deselectCurrent = function () {
            if (pcCurrentlySelected) {
                allies[currentSelection].onDeselect();
            }
            else {
                enemies[currentSelection].onDeselect();
            }
        }

        var selectCurrent = function () {
            if (pcCurrentlySelected) {
                allies[currentSelection].onSelect();
            }
            else {
                enemies[currentSelection].onSelect();
            }
        }

        that.pressLeft = function () {

        }

        that.pressUp = function () {

        }

        that.pressRight = function () {

        }

        that.pressDown = function () {

        }

        that.releaseLeft = function () {
            if (currentSelection != 0) {
                deselectCurrent();
                currentSelection--;
                selectCurrent();
            }
        }

        that.releaseUp = function () {
            deselectCurrent();
            pcCurrentlySelected = false;
            if (currentSelection >= enemies.length) {
                currentSelection = enemies.length - 1;
            }
            selectCurrent();
        }

        that.releaseDown = function () {
            deselectCurrent();
            pcCurrentlySelected = true;
            if (currentSelection >= allies.length) {
                currentSelection = allies.length - 1;
            }
            selectCurrent();
        }

        that.releaseRight = function () {
            if ((pcCurrentlySelected && currentSelection < allies.length - 1) ||
                (!pcCurrentlySelected && currentSelection < enemies.length - 1)) {
                deselectCurrent();
                currentSelection++;
                selectCurrent();
            }
        }

        that.confirm = function () {
            if (pcCurrentlySelected) {
                allies[currentSelection].click();
            }
            else {
                enemies[currentSelection].click();
            }
        }

        that.cancel = function () {
            if (selectingTarget) {
                if (this.onComplete) {
                    this.onComplete();
                }
                selectingTarget = false;
            }
            else {
                that.menu();
            }
        }

        that.menu = function () {
            $currentCommandScreen = createCommandSelectionScreen(commands, currentCharacter);
            $currentCommandScreen.show();
            FuzzyOctoTribble.KeyControl.addController($currentCommandScreen);
        }

        return that;
    }

    that.create = function (spec, my) {
        $currentDefaultScreen = that.createBaseScreen(spec.characterDisplays, spec.npcDisplays, spec.commands, spec.currentCharacter);
        FuzzyOctoTribble.KeyControl.addController($currentDefaultScreen);
        $currentCommandScreen = that.createCommandSelectionScreen(spec.commands, spec.currentCharacter);
        if (spec.effects.length !== 0) {
            processEffects(spec.effects);
        }
        inCombat = true;
    }

    that.inCombat = function () {
        return inCombat;
    }

    return that;
}<|endoftext|>