<commit_before>// Copyright (C) 2010 Combodo SARL
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; version 3 of the License.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program; if not, write to the Free Software
//   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function ExtKeyWidget(id, sClass, sAttCode, sSuffix, bSelectMode, oWizHelper)
{
	this.id = id;
	this.sClass = sClass;
	this.sAttCode = sAttCode;
	this.sSuffix = sSuffix;
	this.emptyHtml = ''; // content to be displayed when the search results are empty (when opening the dialog)
	this.emptyOnClose = true; // Workaround for the JQuery dialog being very slow when opening and closing if the content contains many INPUT tags
	this.oWizardHelper = oWizHelper;
	this.ajax_request = null;
	this.bSelectMode = bSelectMode; // true if the edited field is a SELECT, false if it's an autocomplete
	this.v_html = '';
	var me = this;

	this.Init = function()
	{
		// make sure that the form is clean
		$('#'+this.id+'_btnRemove').attr('disabled','disabled');
		$('#'+this.id+'_linksToRemove').val('');
	}

	this.StopPendingRequest = function()
	{
		if (me.ajax_request)
		{
			me.ajax_request.Abort();
			me.ajax_request = null;
		}
	}

	this.Search = function()
	{
		if($('#'+me.id).attr('disabled')) return; // Disabled, do nothing
		var value = $('#'+me.id).val(); // Current value

		// Query the server to get the form to search for target objects
		if (me.bSelectMode)
		{
			me.v_html = $('#v_'+me.id).html();
			$('#v_'+me.id).html('');
		}
		else
		{
			$('#label_'+me.id).addClass('ac_dlg_loading');
		}
		var theMap = { sAttCode: me.sAttCode,
				   iInputId: me.id,
				   sSuffix: me.sSuffix,
				   'class': me.sClass,
				   sValue: value,
				   operation: 'objectSearchForm'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in HTML
		me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
			function(data)
			{
				$('#ac_dlg_'+me.id).html(data);
				$('#ac_dlg_'+me.id).dialog('open');
				me.UpdateSizes();
				me.UpdateButtons();
				me.ajax_request = null;
			},
			'html'
		);
	}

	this.UpdateSizes = function()
	{
		var dlg = $('#ac_dlg_'+me.id);
		// Adjust the dialog's size to fit into the screen
		if (dlg.width() > ($(window).width()-40))
		{
			dlg.width($(window).width()-40);
		}
		if (dlg.height() > ($(window).height()-70))
		{
			dlg.height($(window).height()-70);
		}
		var searchForm = dlg.find('div.display_block:first'); // Top search form, enclosing display_block
		var results = $('#dr_'+me.id);
		padding_right = parseInt(dlg.css('padding-right').replace('px', ''));
		padding_left = parseInt(dlg.css('padding-left').replace('px', ''));
		padding_top = parseInt(dlg.css('padding-top').replace('px', ''));
		padding_bottom = parseInt(dlg.css('padding-bottom').replace('px', ''));
		width = dlg.innerWidth() - padding_right - padding_left - 22; // 5 (margin-left) + 5 (padding-left) + 5 (padding-right) + 5 (margin-right) + 2 for rounding !
		height = dlg.innerHeight() - padding_top - padding_bottom -22;
		form_height = searchForm.outerHeight();
		results.height(height - form_height - 40); // Leave some space for the buttons
	}

	this.UpdateButtons = function()
	{
		var okBtn = $('#btn_ok_'+me.id);
		if ($('#fr_'+me.id+' input[name=selectObject]:checked').length > 0)
		{
			okBtn.attr('disabled', '');
		}
		else
		{
			okBtn.attr('disabled', 'disabled');
		}
	}

	this.DoSearchObjects = function(id)
	{
		var theMap = { sAttCode: me.sAttCode,
					   iInputId: me.id,
					   sSuffix: me.sSuffix
					 }

		// Gather the parameters from the search form
		$('#fs_'+me.id+' :input').each(
			function(i)
			{
				if (this.name != '')
				{
					theMap[this.name] = this.value;
				}
			}
		);

		if (me.oWizardHelper == null)
		{
			theMap['json'] = '';
		}
		else
		{
			// Not inside a "search form", updating a real object
			me.oWizardHelper.UpdateWizard();
			theMap['json'] = me.oWizardHelper.ToJSON();
		}

		theMap['sRemoteClass'] = theMap['class'];  // swap 'class' (defined in the form) and 'remoteClass'
		theMap['class'] = me.sClass;
		theMap.operation = 'searchObjectsToSelect'; // Override what is defined in the form itself

		sSearchAreaId = '#dr_'+me.id;
		//$(sSearchAreaId).html('

');
		$(sSearchAreaId).block();
		me.UpdateButtons();

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and display the results
		me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
			function(data)
			{
				$(sSearchAreaId).html(data);
				$(sSearchAreaId+' .listResults').tableHover();
				$(sSearchAreaId+' .listResults').tablesorter( { headers: {0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
				$('#fr_'+me.id+' input:radio').click(function() { me.UpdateButtons(); });
				me.UpdateButtons();
				me.ajax_request = null;
			},
			'html'
		);

		return false; // Don't submit the form, stay in the current page !
	}

	this.DoOk = function()
	{
		var iObjectId = $('#fr_'+me.id+' input[name=selectObject]:checked').val();
		$('#ac_dlg_'+this.id).dialog('close');
		$('#label_'+this.id).addClass('ac_dlg_loading');

		// Query the server again to get the display name of the selected object
		var theMap = { sAttCode: me.sAttCode,
				   iInputId: me.id,
				   iObjectId: iObjectId,
				   sSuffix: me.sSuffix,
				   'class': me.sClass,
				   operation: 'getObjectName'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in JSON
		me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
			function(data)
			{
				$('#label_'+me.id).val(data.name);
				$('#label_'+me.id).removeClass('ac_dlg_loading');
				$('#'+me.id).val(iObjectId);
				$('#'+me.id).trigger('validate');
				$('#label_'+me.id).focus();
				me.ajax_request = null;
			},
			'json'
		);

		return false; // Do NOT submit the form in case we are called by OnSubmit...
	}

	// Workaround for a ui.jquery limitation: if the content of
	// the dialog contains many INPUTs, closing and opening the
	// dialog is very slow. So empty it each time.
	this.OnClose = function()
	{
		me.StopPendingRequest();
		// called by the dialog, so in the context 'this' points to the jQueryObject
		if (me.emptyOnClose)
		{
			$('#dr_'+me.id).html(me.emptyHtml);
		}
		$('#label_'+me.id).removeClass('ac_dlg_loading');
		$('#label_'+me.id).focus();
		me.ajax_request = null;
	}

	this.CreateObject = function(oWizHelper)
	{
		if($('#'+me.id).attr('disabled')) return; // Disabled, do nothing
		// Query the server to get the form to create a target object
		if (me.bSelectMode)
		{
			me.v_html = $('#v_'+me.id).html();
			$('#v_'+me.id).html('');
		}
		else
		{
			$('#label_'+me.id).addClass('ac_dlg_loading');
		}
		me.oWizardHelper.UpdateWizard();
		var theMap = { sAttCode: me.sAttCode,
				   iInputId: me.id,
				   sSuffix: me.sSuffix,
				   'class': me.sClass,
				   'json': me.oWizardHelper.ToJSON(),
				   operation: 'objectCreationForm'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in HTML
		me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
			function(data)
			{
				$('#ajax_'+me.id).html(data);
				$('#ac_create_'+me.id).dialog('open');
				$('#ac_create_'+me.id).dialog( "option", "close", me.OnCloseCreateObject );
				// Modify the action of the cancel button
				$('#ac_create_'+me.id+' button.cancel').unbind('click').click( me.CloseCreateObject );
				me.ajax_request = null;
				// Adjust the dialog's size to fit into the screen
				if ($('#ac_create_'+me.id).width() > ($(window).width()-40))
				{
					$('#ac_create_'+me.id).width($(window).width()-40);
				}
				if ($('#ac_create_'+me.id).height() > ($(window).height()-70))
				{
					$('#ac_create_'+me.id).height($(window).height()-70);
				}
			},
			'html'
		);
	}

	this.CloseCreateObject = function()
	{
		$('#ac_create_'+me.id).dialog( "close" );
	}

	this.OnCloseCreateObject = function()
	{
		if (me.bSelectMode)
		{
			$('#v_'+me.id).html(me.v_html);
		}
		else
		{
			$('#label_'+me.id).removeClass('ac_dlg_loading');
		}
		$('#label_'+me.id).focus();
		$('#ac_create_'+me.id).dialog("destroy");
		$('#ac_create_'+me.id).remove();
		$('#ajax_'+me.id).html('');
	}

	this.DoCreateObject = function()
	{
		var sFormId = $('#dcr_'+me.id+' form').attr('id');
		if (CheckFields(sFormId, true))
		{
			$('#'+sFormId).block();
			var theMap = { sAttCode: me.sAttCode,
					   iInputId: me.id,
					   sSuffix: me.sSuffix,
					   'class': me.sClass,
					   'json': me.oWizardHelper.ToJSON()
					 }

			// Gather the values from the form
			// Gather the parameters from the search form
			$('#'+sFormId+' :input').each(
				function(i)
				{
					if (this.name != '')
					{
						theMap[this.name] = this.value;
					}
				}
			);
			// Override the 'operation' code
			theMap['operation'] = 'doCreateObject';
			theMap['class'] = me.sClass;

			$('#ac_create_'+me.id).dialog('close');

			// Make sure that we cancel any pending request before issuing another
			// since responses may arrive in arbitrary order
			me.StopPendingRequest();

			// Run the query and get the result back directly in JSON
			me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
				function(data)
				{
					if (me.bSelectMode)
					{
						// Add the newly created object to the drop-down list and select it
						$('<option/>', { value : data.id }).text(data.name).appendTo('#'+me.id);
						$('#'+me.id+' option[value="'+data.id+'"]').attr('selected', 'selected');
						$('#'+me.id).focus();
					}
					else
					{
						// Put the value corresponding to the newly created object in the autocomplete
						$('#label_'+me.id).val(data.name);
						$('#'+me.id).val(data.id);
						$('#label_'+me.id).removeClass('ac_dlg_loading');
						$('#label_'+me.id).focus();
					}
					$('#'+me.id).trigger('validate');
					me.ajax_request = null;
				},
				'json'
			);
		}
		return false; // do NOT submit the form
	}

	this.Update = function()
	{
		if ($('#'+me.id).attr('disabled'))
		{
			$('#v_'+me.id).html('');
			$('#label_'+me.id).attr('disabled', 'disabled');
			$('#label_'+me.id).css({'background': 'transparent'});
			$('#mini_add_'+me.id).hide();
			$('#mini_search_'+me.id).hide();
		}
		else
		{
			$('#label_'+me.id).attr('disabled', '');
			$('#label_'+me.id).css({'background': '#fff url(../images/ac-background.gif) no-repeat right'});
			$('#mini_add_'+me.id).show();
			$('#mini_search_'+me.id).show();
		}
	}
}<commit_msg>- New implementation of the UIExtKeyWidget that is no longer limited to editing an attribute of an object - When needed the drop-down list of organizations is replaced by an autocomplete<commit_after>// Copyright (C) 2010 Combodo SARL
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; version 3 of the License.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public License
//   along with this program; if not, write to the Free Software
//   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

function ExtKeyWidget(id, sTargetClass, sFilter, sTitle, bSelectMode, oWizHelper)
{
	this.id = id;
	this.sTargetClass = sTargetClass;
	this.sFilter = sFilter;
	this.sTitle = sTitle;
	this.emptyHtml = ''; // content to be displayed when the search results are empty (when opening the dialog)
	this.emptyOnClose = true; // Workaround for the JQuery dialog being very slow when opening and closing if the content contains many INPUT tags
	this.oWizardHelper = oWizHelper;
	this.ajax_request = null;
	this.bSelectMode = bSelectMode; // true if the edited field is a SELECT, false if it's an autocomplete
	this.v_html = '';
	var me = this;

	this.Init = function()
	{
		// make sure that the form is clean
		$('#'+this.id+'_btnRemove').attr('disabled','disabled');
		$('#'+this.id+'_linksToRemove').val('');
	}

	this.StopPendingRequest = function()
	{
		if (me.ajax_request)
		{
			me.ajax_request.Abort();
			me.ajax_request = null;
		}
	}

	this.Search = function()
	{
		if($('#'+me.id).attr('disabled')) return; // Disabled, do nothing
		var value = $('#'+me.id).val(); // Current value

		// Query the server to get the form to search for target objects
		if (me.bSelectMode)
		{
			me.v_html = $('#v_'+me.id).html();
			$('#v_'+me.id).html('');
		}
		else
		{
			$('#label_'+me.id).addClass('ac_dlg_loading');
		}
		var theMap = { sAttCode: me.sAttCode,
				   iInputId: me.id,
				   sTitle: me.sTitle,
				   sTargetClass: me.sTargetClass,
				   operation: 'objectSearchForm'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in HTML
		me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
			function(data)
			{
				$('#ac_dlg_'+me.id).html(data);
				$('#ac_dlg_'+me.id).dialog('open');
				me.UpdateSizes();
				me.UpdateButtons();
				me.ajax_request = null;
			},
			'html'
		);
	}

	this.UpdateSizes = function()
	{
		var dlg = $('#ac_dlg_'+me.id);
		// Adjust the dialog's size to fit into the screen
		if (dlg.width() > ($(window).width()-40))
		{
			dlg.width($(window).width()-40);
		}
		if (dlg.height() > ($(window).height()-70))
		{
			dlg.height($(window).height()-70);
		}
		var searchForm = dlg.find('div.display_block:first'); // Top search form, enclosing display_block
		var results = $('#dr_'+me.id);
		padding_right = parseInt(dlg.css('padding-right').replace('px', ''));
		padding_left = parseInt(dlg.css('padding-left').replace('px', ''));
		padding_top = parseInt(dlg.css('padding-top').replace('px', ''));
		padding_bottom = parseInt(dlg.css('padding-bottom').replace('px', ''));
		width = dlg.innerWidth() - padding_right - padding_left - 22; // 5 (margin-left) + 5 (padding-left) + 5 (padding-right) + 5 (margin-right) + 2 for rounding !
		height = dlg.innerHeight() - padding_top - padding_bottom -22;
		form_height = searchForm.outerHeight();
		results.height(height - form_height - 40); // Leave some space for the buttons
	}

	this.UpdateButtons = function()
	{
		var okBtn = $('#btn_ok_'+me.id);
		if ($('#fr_'+me.id+' input[name=selectObject]:checked').length > 0)
		{
			okBtn.attr('disabled', '');
		}
		else
		{
			okBtn.attr('disabled', 'disabled');
		}
	}

	this.DoSearchObjects = function(id)
	{
		var theMap = { sTargetClass: me.sTargetClass,
					   iInputId: me.id,
					   sFilter: me.sFilter
					 }

		// Gather the parameters from the search form
		$('#fs_'+me.id+' :input').each(
			function(i)
			{
				if (this.name != '')
				{
					theMap[this.name] = this.value;
				}
			}
		);

		if (me.oWizardHelper == null)
		{
			theMap['json'] = '';
		}
		else
		{
			// Not inside a "search form", updating a real object
			me.oWizardHelper.UpdateWizard();
			theMap['json'] = me.oWizardHelper.ToJSON();
		}

		theMap['sRemoteClass'] = theMap['class'];  // swap 'class' (defined in the form) and 'remoteClass'
		theMap.operation = 'searchObjectsToSelect'; // Override what is defined in the form itself

		sSearchAreaId = '#dr_'+me.id;
		//$(sSearchAreaId).html('

');
		$(sSearchAreaId).block();
		me.UpdateButtons();

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and display the results
		me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
			function(data)
			{
				$(sSearchAreaId).html(data);
				$(sSearchAreaId+' .listResults').tableHover();
				$(sSearchAreaId+' .listResults').tablesorter( { headers: {0: {sorter: false}}, widgets: ['myZebra', 'truncatedList']} ); // sortable and zebra tables
				$('#fr_'+me.id+' input:radio').click(function() { me.UpdateButtons(); });
				me.UpdateButtons();
				me.ajax_request = null;
			},
			'html'
		);

		return false; // Don't submit the form, stay in the current page !
	}

	this.DoOk = function()
	{
		var iObjectId = $('#fr_'+me.id+' input[name=selectObject]:checked').val();
		$('#ac_dlg_'+this.id).dialog('close');
		$('#label_'+this.id).addClass('ac_dlg_loading');

		// Query the server again to get the display name of the selected object
		var theMap = { sTargetClass: me.sTargetClass,
				   iInputId: me.id,
				   iObjectId: iObjectId,
				   operation: 'getObjectName'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in JSON
		me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
			function(data)
			{
				$('#label_'+me.id).val(data.name);
				$('#label_'+me.id).removeClass('ac_dlg_loading');
				$('#'+me.id).val(iObjectId);
				$('#'+me.id).trigger('validate');
				$('#label_'+me.id).focus();
				me.ajax_request = null;
			},
			'json'
		);

		return false; // Do NOT submit the form in case we are called by OnSubmit...
	}

	// Workaround for a ui.jquery limitation: if the content of
	// the dialog contains many INPUTs, closing and opening the
	// dialog is very slow. So empty it each time.
	this.OnClose = function()
	{
		me.StopPendingRequest();
		// called by the dialog, so in the context 'this' points to the jQueryObject
		if (me.emptyOnClose)
		{
			$('#dr_'+me.id).html(me.emptyHtml);
		}
		$('#label_'+me.id).removeClass('ac_dlg_loading');
		$('#label_'+me.id).focus();
		me.ajax_request = null;
	}

	this.CreateObject = function(oWizHelper)
	{
		if($('#'+me.id).attr('disabled')) return; // Disabled, do nothing
		// Query the server to get the form to create a target object
		if (me.bSelectMode)
		{
			me.v_html = $('#v_'+me.id).html();
			$('#v_'+me.id).html('');
		}
		else
		{
			$('#label_'+me.id).addClass('ac_dlg_loading');
		}
		me.oWizardHelper.UpdateWizard();
		var theMap = { sTargetClass: me.sTargetClass,
				   iInputId: me.id,
				   'json': me.oWizardHelper.ToJSON(),
				   operation: 'objectCreationForm'
				 }

		// Make sure that we cancel any pending request before issuing another
		// since responses may arrive in arbitrary order
		me.StopPendingRequest();

		// Run the query and get the result back directly in HTML
		me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
			function(data)
			{
				$('#ajax_'+me.id).html(data);
				$('#ac_create_'+me.id).dialog('open');
				$('#ac_create_'+me.id).dialog( "option", "close", me.OnCloseCreateObject );
				// Modify the action of the cancel button
				$('#ac_create_'+me.id+' button.cancel').unbind('click').click( me.CloseCreateObject );
				me.ajax_request = null;
				// Adjust the dialog's size to fit into the screen
				if ($('#ac_create_'+me.id).width() > ($(window).width()-40))
				{
					$('#ac_create_'+me.id).width($(window).width()-40);
				}
				if ($('#ac_create_'+me.id).height() > ($(window).height()-70))
				{
					$('#ac_create_'+me.id).height($(window).height()-70);
				}
			},
			'html'
		);
	}

	this.CloseCreateObject = function()
	{
		$('#ac_create_'+me.id).dialog( "close" );
	}

	this.OnCloseCreateObject = function()
	{
		if (me.bSelectMode)
		{
			$('#v_'+me.id).html(me.v_html);
		}
		else
		{
			$('#label_'+me.id).removeClass('ac_dlg_loading');
		}
		$('#label_'+me.id).focus();
		$('#ac_create_'+me.id).dialog("destroy");
		$('#ac_create_'+me.id).remove();
		$('#ajax_'+me.id).html('');
	}

	this.DoCreateObject = function()
	{
		var sFormId = $('#dcr_'+me.id+' form').attr('id');
		if (CheckFields(sFormId, true))
		{
			$('#'+sFormId).block();
			var theMap = { sTargetClass: me.sTargetClass,
					   iInputId: me.id,
					   'json': me.oWizardHelper.ToJSON()
					 }

			// Gather the values from the form
			// Gather the parameters from the search form
			$('#'+sFormId+' :input').each(
				function(i)
				{
					if (this.name != '')
					{
						theMap[this.name] = this.value;
					}
				}
			);
			// Override the 'operation' code
			theMap['operation'] = 'doCreateObject';
			theMap['class'] = me.sClass;

			$('#ac_create_'+me.id).dialog('close');

			// Make sure that we cancel any pending request before issuing another
			// since responses may arrive in arbitrary order
			me.StopPendingRequest();

			// Run the query and get the result back directly in JSON
			me.ajax_request = $.post( '../pages/ajax.render.php', theMap,
				function(data)
				{
					if (me.bSelectMode)
					{
						// Add the newly created object to the drop-down list and select it
						$('<option/>', { value : data.id }).text(data.name).appendTo('#'+me.id);
						$('#'+me.id+' option[value="'+data.id+'"]').attr('selected', 'selected');
						$('#'+me.id).focus();
					}
					else
					{
						// Put the value corresponding to the newly created object in the autocomplete
						$('#label_'+me.id).val(data.name);
						$('#'+me.id).val(data.id);
						$('#label_'+me.id).removeClass('ac_dlg_loading');
						$('#label_'+me.id).focus();
					}
					$('#'+me.id).trigger('validate');
					me.ajax_request = null;
				},
				'json'
			);
		}
		return false; // do NOT submit the form
	}

	this.Update = function()
	{
		if ($('#'+me.id).attr('disabled'))
		{
			$('#v_'+me.id).html('');
			$('#label_'+me.id).attr('disabled', 'disabled');
			$('#label_'+me.id).css({'background': 'transparent'});
			$('#mini_add_'+me.id).hide();
			$('#mini_search_'+me.id).hide();
		}
		else
		{
			$('#label_'+me.id).attr('disabled', '');
			$('#label_'+me.id).css({'background': '#fff url(../images/ac-background.gif) no-repeat right'});
			$('#mini_add_'+me.id).show();
			$('#mini_search_'+me.id).show();
		}
	}
}<|endoftext|>


<commit_before>/////////////////////
//Require Statement//
/////////////////////
var sanity = require('../index.js')
var assert = require("assert")

///////////////
//Stress Test//
///////////////
describe('Sanity Stress', function(){

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

});

////////////////
//Sanity Check//
////////////////
describe('Actual Sanity Check', function(){

  describe('Sanity 1', function () {
    it('should return 0 when called', function () {
      assert.equal(0, sanity.sanity1());
    });
  });

  describe('Sanity 2', function () {
    it('Should return "Sanity 2" when called',function () {
      assert.equal("Sanity 2", sanity.sanity2());
    });
  });

  describe('Sanity 3', function () {
    it('Should return true', function(){
      assert.equal(true, sanity.sanity3());
    });
  });

  describe('Sanity 4', function () {
    it('Should return if a number is pos, neg, or 0',function () {
      assert.equal('0', sanity.sanity4(0));
      assert.equal('positive', sanity.sanity4(1));
      assert.equal('negative', sanity.sanity4(-1));
    });
  });

});<commit_msg>updated the description on the test<commit_after>/////////////////////
//Require Statement//
/////////////////////
var sanity = require('../index.js')
var assert = require("assert")

///////////////
//Stress Test//
///////////////
describe('Sanity Stress', function(){

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

  describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
      assert.equal(-1, [1,2,3].indexOf(5));
      assert.equal(-1, [1,2,3].indexOf(0));
    });
  });

});

////////////////
//Sanity Check//
////////////////
describe('Actual Sanity Check', function(){

  describe('Sanity 1', function () {
    it('should return 0 when called', function () {
      assert.equal(0, sanity.sanity1());
    });
  });

  describe('Sanity 2', function () {
    it('Should return "Sanity 2" when called',function () {
      assert.equal("Sanity 2", sanity.sanity2());
    });
  });

  describe('Sanity 3', function () {
    it('Should return true', function(){
      assert.equal(true, sanity.sanity3());
    });
  });

  describe('Sanity 4', function () {
    it('Should return 0, positive, or negative if a number is pos, neg, or 0',function () {
      assert.equal('0', sanity.sanity4(0));
      assert.equal('positive', sanity.sanity4(1));
      assert.equal('negative', sanity.sanity4(-1));
    });
  });

});<|endoftext|>


<commit_before>/**
 * Created by josh.horecny on 11/2/15.
 */
angular.module('pollApp.controllers', []).controller('PollListController', function($scope, $state, $window, Poll) {
    $scope.polls = Poll.query(); //fetch all polls. Issues a GET to /collections/Polls

}).controller('PollCreateController',function($scope,$http, $state,$stateParams,Poll){

    $scope.poll=new Poll();
    $scope.poll.pollValues = [];
    $scope.poll.timeStamp = "22222222";
    $scope.poll.totalVotes = "0";
    $scope.poll.poll_id = "222";
    $scope.addPoll=function(){
        $scope.poll.$save(function(){
            $scope.uploadFile(poll.pollImage);
            $state.go('polls');
        });
    }

    $scope.uploadFile = function(files) {
        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[0]);

        $http.post('/images/', fd, {
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(' ...all right!... ').error(' ..damn!... ');

    }
});

<commit_msg>Added images<commit_after>/**
 * Created by josh.horecny on 11/2/15.
 */
angular.module('pollApp.controllers', []).controller('PollListController', function($scope, $state, $window, Poll) {
    $scope.polls = Poll.query(); //fetch all polls. Issues a GET to /collections/Polls

}).controller('PollCreateController',function($scope,$http, $state,$stateParams,Poll){

    $scope.poll=new Poll();
    $scope.poll.pollValues = [];
    $scope.poll.timeStamp = "22222222";
    $scope.poll.totalVotes = "0";
    $scope.poll.poll_id = "222";
    $scope.uploadFile(poll.pollImage);
    $scope.addPoll=function(){
        $scope.poll.$save(function(){

            $state.go('polls');
        });
    }

    $scope.uploadFile = function(files) {
        var fd = new FormData();
        //Take the first selected file
        fd.append("file", files[0]);

        $http.post('/images/', fd, {
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(' ...all right!... ').error(' ..damn!... ');

    }
});

<|endoftext|>


<commit_before>var runtime = require('../src/runtime.js');

        runtime.require('logger').level('debug');

        var metamodel = runtime.require('metamodel');

        metamodel.type({
            'name': 'address',
            'type': 'object',
            'schema': {
                'planet': { 'type': 'string', 'mandatory': true }
            }
        });

        metamodel.type({
            'name': 'sex',
            'type': 'string',
            'value': ['male', 'female']
        });

        metamodel.schema({
            '_name': 'Person',
            '_inherit': ['RuntimeComponent'],
            'sex': 'property',
            'firstName': 'property',
            'lastName': 'property',
            'address': 'property'
        });

        metamodel.model({
            '_name': 'Person',
            '_inherit': ['RuntimeComponent'],
            'sex': {
                'type': 'sex',
                'readOnly': true,
                'mandatory': true,
                'default': 'male'
            },
            'firstName': {
                'type': 'string',
                'readOnly': false,
                'mandatory': true,
                'default': ''
            },
            'lastName': {
                'type': 'string',
                'readOnly': true,
                'mandatory': true,
                'default': ''
            },
            'address': {
                'type': 'address',
                'readOnly': true,
                'mandatory': false,
                'default': {
                    planet: ''
                }
            }
        });

        metamodel.create();

        var Person = runtime.require('Person');

        var yoda = new Person({
            'sex': 'male',
            'firstName': 'Yoda',
            'lastName': 'Master',
            'address': {
                'planet': 'Dagobah'
            }
        });

        console.log(yoda.address().planet());<commit_msg>remove test file<commit_after><|endoftext|>


<commit_before>var guestControllers = angular.module("guestControllers", []);

guestControllers.controller("ListController", [
  "$scope",
  "$http",
  "$timeout",
  function($scope, $http, $timeout, analytics) {
    $scope.data = $scope.data ? $scope.data : {};
    $scope.actions = $scope.actions ? $scope.actions : {};
    var d = $scope.data;
    var a = $scope.actions;

    d.portfolioItems = [];

    $http.get("js/projects/projects.json").then(function(response) {
      d.portfolioItems = response.data;

      d.dateString = function() {
        var d = new Date();
        return d.getFullYear();
      };

      a.selectProj = function(ind) {
        d.selectedProj = d.portfolioItems[ind];
        d.loadedProj = true;
      };

      a.scrollTo = function(section) {
        $("html, body").animate(
          {
            scrollTop: $("#" + section).offset().top
          },
          500
        );
      };

      $scope.showListIcon = true;

      $scope.go_back = function() {
        window.history.back();
      };
    });

    let blog = window.location.hash.indexOf("blog");

    // If navigate to blog
    if (blog) {
      $(function() {
        var $content = $("#jsonContent");

        var dateOptions = {
          weekday: "short",
          year: "numeric",
          month: "short",
          day: "numeric"
        };

        google.load("feeds", "1");

        function initialize() {
          var feed = new google.feeds.Feed("https://medium.com/feed/@uchi");
          feed.load(function(result) {
            d.json = result;
            if (!result.error) {
              var output = "";
              var author = result.feed.description
                .replace("Stories by ", "")
                .replace(" on Medium", "");
              result.feed.entries.forEach(function(item, k) {
                var tagIndex = item.content.indexOf("<img"); // Find where the img tag starts
                var srcIndex =
                  item.content.substring(tagIndex).indexOf('src="') + tagIndex; // Find where the src attribute starts
                var srcStart = srcIndex + 5; // Find where the actual image URL starts; 5 for the length of 'src="'
                var srcEnd =
                  item.content.substring(srcStart).indexOf('"') + srcStart; // Find where the URL ends

                var div = document.createElement("div");
                div.innerHTML = item.content;
                var firstImage = div.getElementsByTagName("img")[0];
                var imgSrc = firstImage ? firstImage.src : "";
                // or, if you want the unresolved src, as it appears in the original HTML:
                var rawImgSrc = firstImage
                  ? firstImage.getAttribute("src")
                  : "";
                console.log(firstImage);
                console.log(rawImgSrc);
                if (
                  rawImgSrc.endsWith("png") ||
                  rawImgSrc.endsWith("jpg") ||
                  rawImgSrc.endsWith("jpeg")
                ) {
                  var src = rawImgSrc; //item.content.substring(srcStart, srcEnd); // Extract just the URL
				  output += '';
				  output += '
';
				  output += '
';
				  output +=
					'
' +
					(new Date(item.publishedDate).toLocaleDateString(
					  "en-US",
					  dateOptions
					) || "") +
					"
";
                  output +=
                    '

';
                  output +=
                    '

' +
                    item.title +
                    "
";
                  output +=
                    '
By ' +
                    author +
                    "
";
                  var yourString = div
                    .getElementsByTagName("p")[0]
                    .innerText.replace(/]*>/g, ""); //replace with your string.
                  var maxLength = 120; // maximum number of characters to extract
                  //trim the string to the maximum length
                  var trimmedString = yourString.substr(0, maxLength);
                  //re-trim if we are in the middle of a word
                  trimmedString = trimmedString.substr(
                    0,
                    Math.min(
                      trimmedString.length,
                      trimmedString.lastIndexOf(" ")
                    )
                  );
                  output += '
';
                  output += trimmedString + "...
";

                  output += "

";
                }
                return k < 3;
              });
              $content.html(output);
            }
          });
        }
        google.setOnLoadCallback(initialize);
      });
    }
  }
]);
<commit_msg>New website<commit_after>var guestControllers = angular.module("guestControllers", []);

guestControllers.controller("ListController", [
  "$scope",
  "$http",
  "$timeout",
  function($scope, $http, $timeout, analytics) {
    $scope.data = $scope.data ? $scope.data : {};
    $scope.actions = $scope.actions ? $scope.actions : {};
    var d = $scope.data;
    var a = $scope.actions;

    d.portfolioItems = [];

    $http.get("js/projects/projects.json").then(function(response) {
      d.portfolioItems = response.data;

      d.dateString = function() {
        var d = new Date();
        return d.getFullYear();
      };

      a.selectProj = function(ind) {
        d.selectedProj = d.portfolioItems[ind];
        d.loadedProj = true;
      };

      a.scrollTo = function(section) {
        $("html, body").animate(
          {
            scrollTop: $("#" + section).offset().top
          },
          500
        );
      };

      $scope.showListIcon = true;

      $scope.go_back = function() {
        window.history.back();
      };
    });

    let blog = window.location.hash.indexOf("blog");

    // If navigate to blog
    if (blog) {
      $(function() {
        var $content = $("#jsonContent");

        var dateOptions = {
          weekday: "short",
          year: "numeric",
          month: "short",
          day: "numeric"
        };

        google.load("feeds", "1");

        function initialize() {
          var feed = new google.feeds.Feed("https://medium.com/feed/@uchi");
          feed.load(function(result) {
            d.json = result;
            if (!result.error) {
              var output = "";
              var author = result.feed.description
                .replace("Stories by ", "")
                .replace(" on Medium", "");
              result.feed.entries.forEach(function(item, k) {
                var tagIndex = item.content.indexOf("<img"); // Find where the img tag starts
                var srcIndex =
                  item.content.substring(tagIndex).indexOf('src="') + tagIndex; // Find where the src attribute starts
                var srcStart = srcIndex + 5; // Find where the actual image URL starts; 5 for the length of 'src="'
                var srcEnd =
                  item.content.substring(srcStart).indexOf('"') + srcStart; // Find where the URL ends

                var div = document.createElement("div");
                div.innerHTML = item.content;
                var firstImage = div.getElementsByTagName("img")[0];
                var imgSrc = firstImage ? firstImage.src : "";
                // or, if you want the unresolved src, as it appears in the original HTML:
                var rawImgSrc = firstImage
                  ? firstImage.getAttribute("src")
                  : "";
                console.log(firstImage);
                console.log(rawImgSrc);
                if (
                  rawImgSrc.endsWith("png") ||
                  rawImgSrc.endsWith("jpg") ||
                  rawImgSrc.endsWith("jpeg")
                ) {
                  var src = rawImgSrc; //item.content.substring(srcStart, srcEnd); // Extract just the URL
                  output += '';
                  output += '
';
                  output += '
';
                  dt =
                    '
' +
                    (new Date(item.publishedDate).toLocaleDateString(
                      "en-US",
                      dateOptions
                    ) || "") +
                    "
";
                  output += dt.indexOf(',') > -1 ? dt : '';
                  output +=
                    '

';
                  output +=
                    '

' +
                    item.title +
                    "
";
                  output +=
                    '
By ' +
                    author +
                    "
";
                  var yourString = div
                    .getElementsByTagName("p")[0]
                    .innerText.replace(/]*>/g, ""); //replace with your string.
                  var maxLength = 120; // maximum number of characters to extract
                  //trim the string to the maximum length
                  var trimmedString = yourString.substr(0, maxLength);
                  //re-trim if we are in the middle of a word
                  trimmedString = trimmedString.substr(
                    0,
                    Math.min(
                      trimmedString.length,
                      trimmedString.lastIndexOf(" ")
                    )
                  );
                  output += '
';
                  output += trimmedString + "...
";

                  output += "

";
                }
                return k < 3;
              });
              $content.html(output);
            }
          });
        }
        google.setOnLoadCallback(initialize);
      });
    }
  }
]);
<|endoftext|>


<commit_before>(function () {
    TRAFFICSIM_APP.game = TRAFFICSIM_APP.game || {};

    var logger = TRAFFICSIM_APP.utils.logger;
    var math = TRAFFICSIM_APP.utils.math;
    var Vector3 = TRAFFICSIM_APP.utils.Vector3;

    TRAFFICSIM_APP.game.VehicleType = {
        "CAR": 1
    };

    TRAFFICSIM_APP.game.Vehicle = function (worldController, model, vehicleType) {
        var self = this;

        this._vehicleType = vehicleType;
        this._currentNode = null;
        this._currentRoute = null;
        this._nextRoute = null;
        this._currentRouteTargetNode = null;
        this._speed = 0;
        this._acceleratorPedal = 0; // Between 0 and 1
        this._maxSpeed = math.randomValue(4, 7);
        this._acceleration = math.randomValue(2, 7);
        this._deceleration = this._acceleration;

        TRAFFICSIM_APP.game.GameplayObject.call(self, worldController, model);

        this._setCollisionMask();
    };

    TRAFFICSIM_APP.game.Vehicle.prototype = Object.create(TRAFFICSIM_APP.game.GameplayObject.prototype);

    TRAFFICSIM_APP.game.Vehicle.prototype._setCollisionMask = function () {
        var self = this;
        switch (self._vehicleType) {
            case TRAFFICSIM_APP.game.VehicleType.CAR:
                var collisionMask = [
                    {
                        "x": -1,
                        "z": -1
                    },
                    {
                        "x": 1,
                        "z": -1
                    },
                    {
                        "x": 1,
                        "z": 1
                    },
                    {
                        "x": -1,
                        "z": 1
                    }
                ];
                self._collisionMask = collisionMask;
                self._collisionMaskTemplate = collisionMask;
                break;
        }
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.getVehicleType = function () {
        return this._vehicleType;
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.setNode = function (node) {
        this._currentNode = node;
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.updateCollisionMask = function () {

    };

    TRAFFICSIM_APP.game.Vehicle.prototype.onCollision = function () {
        var self = this;
        var otherVehicles = self._worldController.getVehicleController().getVehicles().filter(function(vehicle) {
            return vehicle != self;
        });

        return otherVehicles.some(function (vehicle) {
            var pointTowards = new Vector3(self._position.x + Math.cos(self._angle) * 3.3,
                self._position.y,
                self._position.z - Math.sin(self._angle) * 3.3);
            return pointTowards.x >= vehicle.getPosition().x + vehicle.getCollisionMask()[0].x
                && pointTowards.x <= vehicle.getPosition().x + vehicle.getCollisionMask()[1].x
                && pointTowards.x <= vehicle.getPosition().x + vehicle.getCollisionMask()[2].x
                && pointTowards.x >= vehicle.getPosition().x + vehicle.getCollisionMask()[3].x
                && pointTowards.z >= vehicle.getPosition().z + vehicle.getCollisionMask()[0].z
                && pointTowards.z >= vehicle.getPosition().z + vehicle.getCollisionMask()[1].z
                && pointTowards.z <= vehicle.getPosition().z + vehicle.getCollisionMask()[2].z
                && pointTowards.z <= vehicle.getPosition().z + vehicle.getCollisionMask()[3].z;
        });
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.getCollisionMask = function() {
        return this._collisionMask;
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.update = function (deltaTime) {
        var self = this;

        handleRouteFinding();
        handleLogicalMotion(); // How the driver controls the car
        handlePhysicalMotion(); // How the car's physical position is changed according to the current speed etc.
        handleTargetReached();

        function handleLogicalMotion() {

            self._acceleratorPedal = 1; // Full acceleration by default, the following functions may modify this.
            handleCollisionPrediction();
            stopAtNextPointIfNeeded();
            handleSteeringWheel();

            function handleCollisionPrediction() {
                // Release acceleration pedal if about to crash to another car
                // TODO
            }

            function stopAtNextPointIfNeeded() {
                /* Sometimes we want to release the accelerator pedal at a specific point so that the car
                 * stops on the next target node. */
                if (!self._nextRoute.isFree()) {
                    // How much time does it take for the car to stop
                    var timeToStopInSeconds = self._speed / self._deceleration;

                    // Calculate distance between current point and the next point
                    var distanceBetweenCurrentPointAndTargetPoint = math.distance(
                        self._position.x,
                        self._position.y,
                        self._nextRoute.startNode.getPosition().x,
                        self._nextRoute.startNode.getPosition().y);

                    if (distanceBetweenCurrentPointAndTargetPoint <= self._speed * timeToStopInSeconds) {
                        self._acceleratorPedal = 0;
                    }
                }
            }

            function handleSteeringWheel() {
                // Currently there is no "real" steering wheel, we just hardly rotate the car to the next target point.
                if (self._currentRouteTargetNode) {
                    var angleBetweenCurrentAndTargetPoint = math.angleBetweenPointsWhenYIncreasesDown(
                        self._position.x,
                        self._position.z,
                        self._currentRouteTargetNode.position.x,
                        self._currentRouteTargetNode.position.z);
                    self.setAngle(angleBetweenCurrentAndTargetPoint);
                }
            }

        }

        function handlePhysicalMotion() {
            handleAcceleration();
            handleDeceleration();
            handleSpeed();

            function handleAcceleration() {
                if (self._acceleratorPedal > 0) {
                    self._speed += self._acceleration * deltaTime;

                    if (self._speed > self._maxSpeed) {
                        self._speed = self._maxSpeed;
                    }
                }
            }

            function handleDeceleration() {
                if (self._acceleratorPedal == 0) {
                    self._speed -= self._deceleration * deltaTime;

                    if (self._speed < 0) {
                        self._speed = 0;
                    }
                }
            }

            function handleSpeed() {
                // Store current position and angle
                var oldPosition = new Vector3(self._position.x, self._position.y, self._position.z);
                var oldAngle = self._angle;

                // Move towards next target point
                self.setPosition(new Vector3(self._position.x + Math.cos(self._angle) * self._speed * deltaTime,
                    self._position.y,
                    self._position.z - Math.sin(self._angle) * self._speed * deltaTime));

                // Rollback if on collision
                if (self.onCollision()) {
                    self.setPosition(oldPosition);
                    self.setAngle(oldAngle);
                }
            }
        }

        function handleTargetReached() {
            if (isDestinationReached()) {
                self._currentNode = self._currentRouteTargetNode;
                self._currentRoute = null;
                self._currentRouteTargetNode = null;
            }

            function isDestinationReached() {
                if (self._currentRouteTargetNode) {
                    return math.distance(
                            self._position.x,
                            self._position.y,
                            self._position.z,
                            self._currentRouteTargetNode.position.x,
                            self._currentRouteTargetNode.position.y,
                            self._currentRouteTargetNode.position.z) <= 0.2;
                }

                return false;
            }
        }

        function handleRouteFinding() {
            if (!self._nextRoute) {
                self._nextRoute = findNextRoute();
            }

            if (self._currentNode) {
                setNextRoute();
            }
        }

        function setNextRoute() {
            self._currentRoute = self._nextRoute;
            self._currentRouteTargetNode = self._nextRoute.endNode;
            self._currentNode = null;
            self._nextRoute = findNextRoute();
        }

        function findNextRoute() {
            // Randomly pick one of the routes connected to the current node (but not the one that we just drove).
            var startingConnections = null;
            if (self._currentNode) {
                startingConnections = self._currentNode.getConnectedStartingRoutes();
            } else if (self._currentRoute) {
                startingConnections = self._currentRoute.endNode.getConnectedStartingRoutes();
            }

            if (startingConnections.length > 0) {
                return startingConnections[TRAFFICSIM_APP.utils.math.randomValue(0, startingConnections.length - 1)];
            }

            return null;
        }

    };
})();<commit_msg>Finish vehicle acceleration & deceleration.<commit_after>(function () {
    TRAFFICSIM_APP.game = TRAFFICSIM_APP.game || {};

    var logger = TRAFFICSIM_APP.utils.logger;
    var math = TRAFFICSIM_APP.utils.math;
    var Vector3 = TRAFFICSIM_APP.utils.Vector3;

    TRAFFICSIM_APP.game.VehicleType = {
        "CAR": 1
    };

    TRAFFICSIM_APP.game.Vehicle = function (worldController, model, vehicleType) {
        var self = this;

        this._vehicleType = vehicleType;
        this._currentNode = null;
        this._currentRoute = null;
        this._nextRoute = null;
        this._currentRouteTargetNode = null;
        this._speed = 0;
        this._acceleratorPedal = 0; // Between 0 and 1
        this._maxSpeed = math.randomValue(4, 8);
        this._acceleration = math.randomValue(2, 8);
        this._deceleration = this._acceleration;

        TRAFFICSIM_APP.game.GameplayObject.call(self, worldController, model);

        this._setCollisionMask();
    };

    TRAFFICSIM_APP.game.Vehicle.prototype = Object.create(TRAFFICSIM_APP.game.GameplayObject.prototype);

    TRAFFICSIM_APP.game.Vehicle.prototype._setCollisionMask = function () {
        var self = this;
        switch (self._vehicleType) {
            case TRAFFICSIM_APP.game.VehicleType.CAR:
                var collisionMask = [
                    {
                        "x": -1,
                        "z": -1
                    },
                    {
                        "x": 1,
                        "z": -1
                    },
                    {
                        "x": 1,
                        "z": 1
                    },
                    {
                        "x": -1,
                        "z": 1
                    }
                ];
                self._collisionMask = collisionMask;
                self._collisionMaskTemplate = collisionMask;
                break;
        }
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.getVehicleType = function () {
        return this._vehicleType;
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.setNode = function (node) {
        this._currentNode = node;
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.updateCollisionMask = function () {

    };

    TRAFFICSIM_APP.game.Vehicle.prototype.onCollision = function () {
        var self = this;
        var otherVehicles = self._worldController.getVehicleController().getVehicles().filter(function(vehicle) {
            return vehicle != self;
        });

        return otherVehicles.some(function (vehicle) {
            var pointTowards = new Vector3(self._position.x + Math.cos(self._angle) * 3.3,
                self._position.y,
                self._position.z - Math.sin(self._angle) * 3.3);
            return pointTowards.x >= vehicle.getPosition().x + vehicle.getCollisionMask()[0].x
                && pointTowards.x <= vehicle.getPosition().x + vehicle.getCollisionMask()[1].x
                && pointTowards.x <= vehicle.getPosition().x + vehicle.getCollisionMask()[2].x
                && pointTowards.x >= vehicle.getPosition().x + vehicle.getCollisionMask()[3].x
                && pointTowards.z >= vehicle.getPosition().z + vehicle.getCollisionMask()[0].z
                && pointTowards.z >= vehicle.getPosition().z + vehicle.getCollisionMask()[1].z
                && pointTowards.z <= vehicle.getPosition().z + vehicle.getCollisionMask()[2].z
                && pointTowards.z <= vehicle.getPosition().z + vehicle.getCollisionMask()[3].z;
        });
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.getCollisionMask = function() {
        return this._collisionMask;
    };

    TRAFFICSIM_APP.game.Vehicle.prototype.update = function (deltaTime) {
        var self = this;

        handleRouteFinding();
        handleLogicalMotion(); // How the driver controls the car
        handlePhysicalMotion(); // How the car's physical position is changed according to the current speed etc.
        handleTargetReached();

        function handleLogicalMotion() {

            self._acceleratorPedal = 1; // Full acceleration by default, the following functions may modify this.
            handleCollisionPrediction();
            stopAtNextPointIfNeeded();
            handleSteeringWheel();

            function handleCollisionPrediction() {
                // Release acceleration pedal if about to crash to another car
                // TODO
            }

            function stopAtNextPointIfNeeded() {
                /* Sometimes we want to release the accelerator pedal at a specific point so that the car
                 * stops on the next target node. */
                if (!self._nextRoute.isFree()) {
                    if (self._currentNode == self._nextRoute.startNode) {
                        self._acceleratorPedal = 0;
                    }

                    // Moving towards next route. How much time does it take for the car to stop
                    var timeToStopInSeconds = self._speed / self._deceleration;

                    // Calculate distance between current point and the next point
                    var distanceBetweenCurrentPointAndTargetPoint = math.distance(
                        self._position.x,
                        self._position.z,
                        0,
                        self._nextRoute.startNode.position.x,
                        self._nextRoute.startNode.position.z,
                        0);

                    if (distanceBetweenCurrentPointAndTargetPoint <= self._speed * timeToStopInSeconds) {
                        self._acceleratorPedal = 0;
                    }
                }
            }

            function handleSteeringWheel() {
                // Currently there is no "real" steering wheel, we just hardly rotate the car to the next target point.
                if (self._currentRouteTargetNode) {
                    var angleBetweenCurrentAndTargetPoint = math.angleBetweenPointsWhenYIncreasesDown(
                        self._position.x,
                        self._position.z,
                        self._currentRouteTargetNode.position.x,
                        self._currentRouteTargetNode.position.z);
                    self.setAngle(angleBetweenCurrentAndTargetPoint);
                }
            }

        }

        function handlePhysicalMotion() {
            handleAcceleration();
            handleDeceleration();
            handleSpeed();

            function handleAcceleration() {
                if (self._acceleratorPedal > 0) {
                    self._speed += self._acceleration * deltaTime;

                    if (self._speed > self._maxSpeed) {
                        self._speed = self._maxSpeed;
                    }
                }
            }

            function handleDeceleration() {
                if (self._acceleratorPedal == 0) {
                    self._speed -= self._deceleration * deltaTime;

                    if (self._speed < 0) {
                        self._speed = 0;
                    }
                }
            }

            function handleSpeed() {
                // Store current position and angle
                var oldPosition = new Vector3(self._position.x, self._position.y, self._position.z);
                var oldAngle = self._angle;

                // Move towards next target point
                self.setPosition(new Vector3(self._position.x + Math.cos(self._angle) * self._speed * deltaTime,
                    self._position.y,
                    self._position.z - Math.sin(self._angle) * self._speed * deltaTime));

                // Rollback if on collision
                if (self.onCollision()) {
                    self.setPosition(oldPosition);
                    self.setAngle(oldAngle);
                }
            }
        }

        function handleTargetReached() {
            if (isDestinationReached()) {
                self._currentNode = self._currentRouteTargetNode;
                self._currentRoute = null;
                self._currentRouteTargetNode = null;
            }

            function isDestinationReached() {
                if (self._currentRouteTargetNode) {
                    return math.distance(
                            self._position.x,
                            self._position.y,
                            self._position.z,
                            self._currentRouteTargetNode.position.x,
                            self._currentRouteTargetNode.position.y,
                            self._currentRouteTargetNode.position.z) <= 0.2;
                }

                return false;
            }
        }

        function handleRouteFinding() {
            if (!self._nextRoute) {
                self._nextRoute = findNextRoute();
            }

            if (self._currentNode && self._nextRoute.isFree()) {
                takeNextRoute();
            }
        }

        function takeNextRoute() {
            self._currentRoute = self._nextRoute;
            self._currentRouteTargetNode = self._nextRoute.endNode;
            self._currentNode = null;
            self._nextRoute = findNextRoute();
        }

        function findNextRoute() {
            // Randomly pick one of the routes connected to the current node (but not the one that we just drove).
            var startingConnections = null;
            if (self._currentNode) {
                startingConnections = self._currentNode.getConnectedStartingRoutes();
            } else if (self._currentRoute) {
                startingConnections = self._currentRoute.endNode.getConnectedStartingRoutes();
            }

            if (startingConnections.length > 0) {
                return startingConnections[TRAFFICSIM_APP.utils.math.randomValue(0, startingConnections.length - 1)];
            }

            return null;
        }

    };
})();<|endoftext|>


<commit_before>'use strict';

var Bitly = require('../libs/Bitly');
var assert = require('assert');

describe('Bitly', function() {

    it('shorten test', function(done) {
        new Bitly('f6d8b8c4fac30062943ced3d7fff1798e97494ae')
            .shorten('http://www.hfworks.cn/about')
            .then(function(data) {
                assert.equal('http://bit.ly/1N9Wr1j', data.url);
                done();
            })
            .catch(function(err) {
                done(err);
            });
    });

    it('expand test', function(done) {
        new Bitly('f6d8b8c4fac30062943ced3d7fff1798e97494ae')
            .expand('http://bit.ly/1N9Wr1j', '1N9Wr1j')
            .then(function(data) {
                assert.equal('http://www.hfworks.cn/about', data.long_url);
                done();
            })
            .catch(function(err) {
                done(err);
            });
    });

    it('exception test', function(done) {
        new Bitly()
            .expand('http://bit.ly/1N9Wr1j', '1N9Wr1j')
            .catch(function(err) {
                assert(!!err);
                done();
            });
    });

});
<commit_msg>update test case<commit_after>'use strict';

var Bitly = require('../libs/Bitly');
var assert = require('assert');

describe('Bitly', function() {

    it('shorten test', function(done) {
        new Bitly('f6d8b8c4fac30062943ced3d7fff1798e97494ae')
            .shorten('http://www.hfworks.cn/about')
            .then(function(data) {
                assert.equal('http://bit.ly/1N9Wr1j', data.url);
                done();
            })
            .catch(function(err) {
                done(err);
            });
    });

    it('expand test', function(done) {
        new Bitly('f6d8b8c4fac30062943ced3d7fff1798e97494ae')
            .expand('http://bit.ly/1N9Wr1j', '1N9Wr1j')
            .then(function(data) {
                assert.equal('http://www.hfworks.cn/about', data.long_url);
                done();
            })
            .catch(function(err) {
                done(err);
            });
    });

    it('exception test', function(done) {
        new Bitly()
            .expand('http://bit.ly/1N9Wr1j', '1N9Wr1j')
            .catch(function(err) {
                assert(!!err);
                done();

            });
    });

});
<|endoftext|>


<commit_before>'use strict';

angular.module('chronontology.controllers', [])

.controller('SearchFormController', function($scope, $location) {

	$scope.search = function(fq) {
		if ($scope.q) {
			var url = '/search?q=' + $scope.q;
			$scope.q = null;
			$location.url(url);
		}
	}

})

.controller("SearchController", function($scope, $location, $http) {

	$http.get('/data/period/?' + $location.search()['q']).success(function(result) {
		$scope.periods = result.results;
	});

})

.controller("PeriodController", function($scope, $location, $routeParams, $http, periodUtils) {

	$http.get('/data/period/' + $routeParams.id).success( function(result) {

		$scope.period = result;

		console.log(result.resource)

		if (result.resource.fallsWithin) {
			$http.get('/data'+result.resource.fallsWithin).success(function(result) {
				$scope.fallsWithin = result;
			});
		}

		if (result.resource.meetsInTimeWith) {
			$http.get('/data'+result.resource.meetsInTimeWith).success(function(result) {
				$scope.meetsInTimeWith = result;
			});
		}

		if (result.resource.isMetInTimeBy) {
			$http.get('/data'+result.resource.isMetInTimeBy).success(function(result) {
				$scope.isMetInTimeBy = result;
			});
		}

<!--
		$http.get('/data/period/', { params: { q: "fallsWithin:\"" + result['@id'] + "\"", size: 1000 } }).success( function(result) {
			$scope.contains = periodUtils.buildTree(result.results);
		});
-->
		$scope.contains = [];
		angular.forEach(result.resource.contains, function(id, nr) {
			$http.get('/data' + id).success( function(res) {
				$scope.contains.push(res);
			});
		});

	});

	$scope.save = function() {
		$http.put('/data' + $scope.period['@id'], $scope.period).success(function(result) {
			$scope.period = result;
		});
	};

})

.controller("ThesaurusController", function($scope, $routeParams, $http) {

	$http.get('/data/period/?size=1000&q=provenance:' + $routeParams.provenance).success( function(result) {
		$scope.periods = result.results;
	});

})
;
<commit_msg>fixed generation of children list<commit_after>'use strict';

angular.module('chronontology.controllers', [])

.controller('SearchFormController', function($scope, $location) {

	$scope.search = function(fq) {
		if ($scope.q) {
			var url = '/search?q=' + $scope.q;
			$scope.q = null;
			$location.url(url);
		}
	}

})

.controller("SearchController", function($scope, $location, $http) {

	$http.get('/data/period/?' + $location.search()['q']).success(function(result) {
		$scope.periods = result.results;
	});

})

.controller("PeriodController", function($scope, $location, $routeParams, $http) {

	$http.get('/data/period/' + $routeParams.id).success( function(result) {

		$scope.period = result;

		if (result.resource.fallsWithin) {
			$http.get('/data'+result.resource.fallsWithin).success(function(result) {
				$scope.fallsWithin = result;
			});
		}

		if (result.resource.meetsInTimeWith) {
			$http.get('/data'+result.resource.meetsInTimeWith).success(function(result) {
				$scope.meetsInTimeWith = result;
			});
		}

		if (result.resource.isMetInTimeBy) {
			$http.get('/data'+result.resource.isMetInTimeBy).success(function(result) {
				$scope.isMetInTimeBy = result;
			});
		}

		$scope.contains = [];
		angular.forEach(result.resource.contains, function(id) {
			$http.get('/data' + id).success(function(result) {
				$scope.contains.push(result);
			});
		});

	});

	$scope.save = function() {
		$http.put('/data' + $scope.period['@id'], $scope.period).success(function(result) {
			$scope.period = result;
		});
	};

})

.controller("ThesaurusController", function($scope, $routeParams, $http) {

	$http.get('/data/period/?size=1000&q=provenance:' + $routeParams.provenance).success( function(result) {
		$scope.periods = result.results;
	});

})
;
<|endoftext|>


<commit_before>Jsonix.Model.AbstractElementRefsPropertyInfo = Jsonix.Class(Jsonix.Model.PropertyInfo, {
	wrapperElementName : null,
	mixed : false,
	// TODO
	initialize : function(options) {
		Jsonix.Util.Ensure.ensureObject(options, 'Options argument must be an object.');
		Jsonix.Model.PropertyInfo.prototype.initialize.apply(this, [ options ]);
		if (Jsonix.Util.Type.isObject(options.wrapperElementName)) {
			Jsonix.Util.Ensure.ensureString(options.wrapperElementName.localPart, 'Wrapper element name must contain a string property [localPart].');
			this.wrapperElementName = Jsonix.XML.QName.fromObject(options.wrapperElementName);
		} else if (Jsonix.Util.Type.isString(options.wrapperElementName)) {
			this.wrapperElementName = new Jsonix.XML.QName(this.defaultElementNamespaceURI, options.wrapperElementName);
		} else {
			this.wrapperElementName = null;
		}
		if (Jsonix.Util.Type.isBoolean(options.mixed)) {
			this.mixed = options.mixed;
		} else {
			this.mixed = false;
		}
	},
	unmarshal : function(context, input, scope) {
		var et = input.eventType;

		if (et === Jsonix.XML.Input.START_ELEMENT) {
			if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
				return this.unmarshalWrapperElement(context, input, scope);
			} else {
				return this.unmarshalElement(context, input, scope);
			}
		} else if (this.mixed && (et === Jsonix.XML.Input.CHARACTERS || et === Jsonix.XML.Input.CDATA || et === Jsonix.XML.Input.ENTITY_REFERENCE)) {
			var value = input.getText();
			if (this.collection) {
				return [ value ];

			} else {
				return value;
			}
		} else if (et === Jsonix.XML.Input.SPACE || et === Jsonix.XML.Input.COMMENT || et === Jsonix.XML.Input.PROCESSING_INSTRUCTION) {
			// Skip whitespace
		} else {
			// TODO better exception
			throw new Error("Illegal state: unexpected event type [" + et + "].");
		}
	},
	unmarshalWrapperElement : function(context, input, scope) {
		var result = null;
		var et = input.next();
		while (et !== Jsonix.XML.Input.END_ELEMENT) {
			if (et === Jsonix.XML.Input.START_ELEMENT) {
				var value = this.unmarshalElement(context, input, scope);
				if (this.collection) {
					if (result === null) {
						result = [];
					}
					for ( var index = 0; index < value.length; index++) {
						result.push(value[index]);
					}

				} else {
					if (result === null) {
						result = value;
					} else {
						// TODO Report validation error
						throw new Error("Value already set.");
					}
				}
			} else
			// Characters
			if (this.mixed && (et === Jsonix.XML.Input.CHARACTERS || et === Jsonix.XML.Input.CDATA || et === Jsonix.XML.Input.ENTITY_REFERENCE)) {
				var text = input.getText();
				if (this.collection) {
					if (result === null) {
						result = [];
					}
					result.push(text);
				} else {
					if (result === null) {
						result = text;
					} else {
						// TODO Report validation error
						throw new Error("Value already set.");
					}
				}
			} else if (et === Jsonix.XML.Input.SPACE || et === Jsonix.XML.Input.COMMENT || et === Jsonix.XML.Input.PROCESSING_INSTRUCTION) {
				// Skip whitespace
			} else {
				throw new Error("Illegal state: unexpected event type [" + et + "].");
			}
			et = input.next();
		}
		return result;
	},
	unmarshalElement : function(context, input, scope) {
		var name = input.getName();
		var typeInfo = this.getElementTypeInfo(context, name, scope);
		var value = {
			name : name,
			value : typeInfo.unmarshal(context, input, scope)
		};
		if (this.collection) {
			return [ value ];
		} else {
			return value;
		}
	},
	marshal : function(value, context, output, scope) {

		if (Jsonix.Util.Type.exists(value)) {
			if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
				output.writeStartElement(this.wrapperElementName);
			}

			if (!this.collection) {
				this.marshalItem(value, context, output, scope);
			} else {
				Jsonix.Util.Ensure.ensureArray(value, 'Collection property requires an array value.');
				for ( var index = 0; index < value.length; index++) {
					var item = value[index];
					this.marshalItem(item, context, output, scope);
				}
			}

			if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
				output.writeEndElement();
			}
		}

	},
	marshalItem : function(value, context, output, scope) {

		if (Jsonix.Util.Type.isString(value)) {
			if (!this.mixed) {
				// TODO
				throw new Error("Property is not mixed, can't handle string values.");
			} else {
				output.writeCharacters(value);
			}
		} else if (Jsonix.Util.Type.isObject(value)) {
			this.marshalElement(value, context, output, scope);

		} else {
			if (this.mixed) {
				throw new Error("Unsupported content type, either objects or strings are supported.");
			} else {
				throw new Error("Unsupported content type, only objects are supported.");
			}
		}

	},
	marshalElement : function(value, context, output, scope) {
		var elementName = Jsonix.XML.QName.fromObject(value.name);
		var typeInfo = this.getElementTypeInfo(context, elementName, scope);
		return this.marshalElementTypeInfo(elementName, typeInfo, value, context, output, scope);
	},
	marshalElementTypeInfo : function(elementName, typeInfo, value, context, output, scope) {
		output.writeStartElement(elementName);
		if (Jsonix.Util.Type.exists(value.value)) {
			typeInfo.marshal(value.value, context, output, scope);
		}
		output.writeEndElement();

	},
	getElementTypeInfo : function(context, elementName, scope) {
		var propertyElementTypeInfo = this.getPropertyElementTypeInfo(elementName);
		if (Jsonix.Util.Type.exists(propertyElementTypeInfo)) {
			return propertyElementTypeInfo.typeInfo;
		} else {
			var contextElementTypeInfo = context.getElementInfo(elementName, scope);
			if (Jsonix.Util.Type.exists(contextElementTypeInfo)) {
				return contextElementTypeInfo.typeInfo;
			} else {
				throw new Error("Element [" + elementName.key + "] is not known in this context.");
			}
		}

	},
	getPropertyElementTypeInfo : function(elementName) {
		throw new Error("Abstract method [getPropertyElementTypeInfo].");
	},
	buildStructure : function(context, structure) {
		Jsonix.Util.Ensure.ensureObject(structure);
		if (Jsonix.Util.Type.exists(structure.value)) {
			// TODO better exception
			throw new Error("The structure already defines a value property.");
		} else if (!Jsonix.Util.Type.exists(structure.elements)) {
			structure.elements = {};
		}

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			structure.elements[this.wrapperElementName.key] = this;
		} else {
			this.buildStructureElements(context, structure);
		}

		// if (Jsonix.Util.Type.exists(structure.elements[key]))
		// {
		// // TODO better exception
		// throw new Error("The structure already defines an element for
		// the key ["
		// + key + "].");
		// } else
		// {
		// structure.elements[key] = this;
		// }

		if (this.mixed && !Jsonix.Util.Type.exists(this.wrapperElementName)) {
			// if (Jsonix.Util.Type.exists(structure.mixed)) {
			// // TODO better exception
			// throw new Error("The structure already defines the mixed
			// property.");
			// } else
			// {
			structure.mixed = this;
			// }
		}
	},
	buildStructureElements : function(context, structure) {
		throw new Error("Abstract method [buildStructureElements].");
	},
	buildStructureElementTypeInfos : function(context, structure, elementTypeInfo) {
		structure.elements[elementTypeInfo.elementName.key] = this;
		var substitutionMembers = context.getSubstitutionMembers(elementTypeInfo.elementName);
		if (Jsonix.Util.Type.isArray(substitutionMembers)) {
			for ( var jndex = 0; jndex < substitutionMembers.length; jndex++) {
				var substitutionElementInfo = substitutionMembers[jndex];
				this.buildStructureElementTypeInfos(context, structure, substitutionElementInfo);
			}

		}
	},
	CLASS_NAME : 'Jsonix.Model.ElementRefPropertyInfo'
});
<commit_msg>Implementing compact naming.<commit_after>Jsonix.Model.AbstractElementRefsPropertyInfo = Jsonix.Class(Jsonix.Model.PropertyInfo, {
	wrapperElementName : null,
	mixed : false,
	// TODO
	initialize : function(options) {
		Jsonix.Util.Ensure.ensureObject(options, 'Options argument must be an object.');
		Jsonix.Model.PropertyInfo.prototype.initialize.apply(this, [ options ]);
		var wen = options.wrapperElementName||options.wen||null;
		if (Jsonix.Util.Type.isObject(wen)) {
			Jsonix.Util.Ensure.ensureString(wen.localPart, 'Wrapper element name must contain a string property [localPart].');
			this.wrapperElementName = Jsonix.XML.QName.fromObject(wen);
		} else if (Jsonix.Util.Type.isString(wen)) {
			this.wrapperElementName = new Jsonix.XML.QName(this.defaultElementNamespaceURI, wen);
		} else {
			this.wrapperElementName = null;
		}
		var mx = options.mixed||options.mx;
		if (Jsonix.Util.Type.isBoolean(mx)) {
			this.mixed = mx;
		} else {
			this.mixed = false;
		}
	},
	unmarshal : function(context, input, scope) {
		var et = input.eventType;

		if (et === Jsonix.XML.Input.START_ELEMENT) {
			if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
				return this.unmarshalWrapperElement(context, input, scope);
			} else {
				return this.unmarshalElement(context, input, scope);
			}
		} else if (this.mixed && (et === Jsonix.XML.Input.CHARACTERS || et === Jsonix.XML.Input.CDATA || et === Jsonix.XML.Input.ENTITY_REFERENCE)) {
			var value = input.getText();
			if (this.collection) {
				return [ value ];

			} else {
				return value;
			}
		} else if (et === Jsonix.XML.Input.SPACE || et === Jsonix.XML.Input.COMMENT || et === Jsonix.XML.Input.PROCESSING_INSTRUCTION) {
			// Skip whitespace
		} else {
			// TODO better exception
			throw new Error("Illegal state: unexpected event type [" + et + "].");
		}
	},
	unmarshalWrapperElement : function(context, input, scope) {
		var result = null;
		var et = input.next();
		while (et !== Jsonix.XML.Input.END_ELEMENT) {
			if (et === Jsonix.XML.Input.START_ELEMENT) {
				var value = this.unmarshalElement(context, input, scope);
				if (this.collection) {
					if (result === null) {
						result = [];
					}
					for ( var index = 0; index < value.length; index++) {
						result.push(value[index]);
					}

				} else {
					if (result === null) {
						result = value;
					} else {
						// TODO Report validation error
						throw new Error("Value already set.");
					}
				}
			} else
			// Characters
			if (this.mixed && (et === Jsonix.XML.Input.CHARACTERS || et === Jsonix.XML.Input.CDATA || et === Jsonix.XML.Input.ENTITY_REFERENCE)) {
				var text = input.getText();
				if (this.collection) {
					if (result === null) {
						result = [];
					}
					result.push(text);
				} else {
					if (result === null) {
						result = text;
					} else {
						// TODO Report validation error
						throw new Error("Value already set.");
					}
				}
			} else if (et === Jsonix.XML.Input.SPACE || et === Jsonix.XML.Input.COMMENT || et === Jsonix.XML.Input.PROCESSING_INSTRUCTION) {
				// Skip whitespace
			} else {
				throw new Error("Illegal state: unexpected event type [" + et + "].");
			}
			et = input.next();
		}
		return result;
	},
	unmarshalElement : function(context, input, scope) {
		var name = input.getName();
		var typeInfo = this.getElementTypeInfo(context, name, scope);
		var value = {
			name : name,
			value : typeInfo.unmarshal(context, input, scope)
		};
		if (this.collection) {
			return [ value ];
		} else {
			return value;
		}
	},
	marshal : function(value, context, output, scope) {

		if (Jsonix.Util.Type.exists(value)) {
			if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
				output.writeStartElement(this.wrapperElementName);
			}

			if (!this.collection) {
				this.marshalItem(value, context, output, scope);
			} else {
				Jsonix.Util.Ensure.ensureArray(value, 'Collection property requires an array value.');
				for ( var index = 0; index < value.length; index++) {
					var item = value[index];
					this.marshalItem(item, context, output, scope);
				}
			}

			if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
				output.writeEndElement();
			}
		}

	},
	marshalItem : function(value, context, output, scope) {

		if (Jsonix.Util.Type.isString(value)) {
			if (!this.mixed) {
				// TODO
				throw new Error("Property is not mixed, can't handle string values.");
			} else {
				output.writeCharacters(value);
			}
		} else if (Jsonix.Util.Type.isObject(value)) {
			this.marshalElement(value, context, output, scope);

		} else {
			if (this.mixed) {
				throw new Error("Unsupported content type, either objects or strings are supported.");
			} else {
				throw new Error("Unsupported content type, only objects are supported.");
			}
		}

	},
	marshalElement : function(value, context, output, scope) {
		var elementName = Jsonix.XML.QName.fromObject(value.name);
		var typeInfo = this.getElementTypeInfo(context, elementName, scope);
		return this.marshalElementTypeInfo(elementName, typeInfo, value, context, output, scope);
	},
	marshalElementTypeInfo : function(elementName, typeInfo, value, context, output, scope) {
		output.writeStartElement(elementName);
		if (Jsonix.Util.Type.exists(value.value)) {
			typeInfo.marshal(value.value, context, output, scope);
		}
		output.writeEndElement();

	},
	getElementTypeInfo : function(context, elementName, scope) {
		var propertyElementTypeInfo = this.getPropertyElementTypeInfo(elementName);
		if (Jsonix.Util.Type.exists(propertyElementTypeInfo)) {
			return propertyElementTypeInfo.typeInfo;
		} else {
			var contextElementTypeInfo = context.getElementInfo(elementName, scope);
			if (Jsonix.Util.Type.exists(contextElementTypeInfo)) {
				return contextElementTypeInfo.typeInfo;
			} else {
				throw new Error("Element [" + elementName.key + "] is not known in this context.");
			}
		}

	},
	getPropertyElementTypeInfo : function(elementName) {
		throw new Error("Abstract method [getPropertyElementTypeInfo].");
	},
	buildStructure : function(context, structure) {
		Jsonix.Util.Ensure.ensureObject(structure);
		if (Jsonix.Util.Type.exists(structure.value)) {
			// TODO better exception
			throw new Error("The structure already defines a value property.");
		} else if (!Jsonix.Util.Type.exists(structure.elements)) {
			structure.elements = {};
		}

		if (Jsonix.Util.Type.exists(this.wrapperElementName)) {
			structure.elements[this.wrapperElementName.key] = this;
		} else {
			this.buildStructureElements(context, structure);
		}

		// if (Jsonix.Util.Type.exists(structure.elements[key]))
		// {
		// // TODO better exception
		// throw new Error("The structure already defines an element for
		// the key ["
		// + key + "].");
		// } else
		// {
		// structure.elements[key] = this;
		// }

		if (this.mixed && !Jsonix.Util.Type.exists(this.wrapperElementName)) {
			// if (Jsonix.Util.Type.exists(structure.mixed)) {
			// // TODO better exception
			// throw new Error("The structure already defines the mixed
			// property.");
			// } else
			// {
			structure.mixed = this;
			// }
		}
	},
	buildStructureElements : function(context, structure) {
		throw new Error("Abstract method [buildStructureElements].");
	},
	buildStructureElementTypeInfos : function(context, structure, elementTypeInfo) {
		structure.elements[elementTypeInfo.elementName.key] = this;
		var substitutionMembers = context.getSubstitutionMembers(elementTypeInfo.elementName);
		if (Jsonix.Util.Type.isArray(substitutionMembers)) {
			for ( var jndex = 0; jndex < substitutionMembers.length; jndex++) {
				var substitutionElementInfo = substitutionMembers[jndex];
				this.buildStructureElementTypeInfos(context, structure, substitutionElementInfo);
			}

		}
	},
	CLASS_NAME : 'Jsonix.Model.ElementRefPropertyInfo'
});
<|endoftext|>


<commit_before>/**
 * We.js config and resouces loader
 */

var path = require('path');
var fs = require('fs')
var _ = require('lodash');
var requireAll = require('require-all');
var async = require('async');
var EmailTemplate = require('./email/EmailTemplate.js');
var Controller = require('./class/Controller.js');

module.exports = {
  loadModels: function loadModels(we, cb) {
    var models = {};
    async.parallel([
      function loadPluginModels(done) {
        var pluginNames = Object.keys(we.plugins);
        async.each(pluginNames, function(pluginName, next) {
          if (!we.plugins[pluginName].models) return next();
          _.merge(models, we.plugins[pluginName].models);
          next();
        }, done);
      },
      function loadProjectModels(done) {
        var PMP = path.resolve(we.projectPath, 'server', 'models');
        fs.exists(PMP, function (exists) {
          // this project dont have models and the models folder
          if (!exists) return done();
          // load and merge all models
          _.merge(models, requireAll({
            dirname     :  PMP,
            filter      :  /(.+)\.js$/,
            resolve     : function (model) {
              return model(we);
            }
          }));
          done();
        });
      }
    ], function (err) {
      return cb(err, models);
    });
  },

  loadControllers: function loadControllers(we, cb) {
    var controllers = {};
    async.parallel([
      function loadPluginControllers(done) {
        var pluginNames = Object.keys(we.plugins);
        async.each(pluginNames, function(pluginName, next) {
          if (!we.plugins[pluginName].controllers) return next();
          _.merge(controllers, we.plugins[pluginName].controllers);
          next();
        }, done);
      },
      function loadProjectControllers(done) {
        var PMP = path.resolve(we.projectPath, 'server', 'controllers');
        fs.exists(PMP, function(exists) {
          // this project dont have controllers and the controllers folder
          if (!exists) return done();
          // load and merge all controllers
          _.merge(controllers, requireAll({
            dirname     :  PMP,
            filter      :  /(.+)\.js$/
          }));

          done();
        });
      }
    ], function (err) {
      var controllerOO = {};
      var controllerNames = Object.keys(controllers);
      controllerNames.forEach(function(n) {
        controllerOO[n] = new Controller(controllers[n]);
      });

      return cb(err, controllerOO);
    });
  },

  loadEmailTemplates: function loadEmailTemplates(we, cb) {
    var templates = {};
    async.parallel([
      function loadPluginEmailTemplates(done) {
        try {
          async.each(we.pluginPaths, function(npmModulePath, next) {
            var PMP = path.resolve(npmModulePath, 'server', 'emails');
            fs.readdir(PMP, function(err, paths) {
              if (err) {
                if (err.code != 'ENOENT') {
                  return next(err);
                } else {
                  return next()
                }
              }
              for (var i = paths.length - 1; i >= 0; i--) {
                templates[paths[i]] = new EmailTemplate(PMP, paths[i]);
              }

              next();
            });
          }, function(err){
            return done(err);
          });
        } catch(e) {
          done();
        }
      },
      function loadProjectEmailTemplates(done) {
        var PMP = path.resolve(we.projectPath, 'server', 'emails');
        fs.readdir(PMP, function(err, paths) {
          if (err) {
            if (err.code != 'ENOENT') {
              return done(err);
            } else {
              return done()
            }
          }

          for (var i = paths.length - 1; i >= 0; i--) {
            templates[paths[i]] = new EmailTemplate(PMP, paths[i]);
          }

          done();
        });
      }
    ], function (err) {
      return cb(err, templates);
    });
  }
}
<commit_msg>update template loaders helper function<commit_after>/**
 * We.js config and resouces loader
 */

var path = require('path');
var fs = require('fs')
var _ = require('lodash');
var requireAll = require('require-all');
var async = require('async');
var EmailTemplate = require('./email/EmailTemplate.js');
var Controller = require('./class/Controller.js');

module.exports = {
  loadModels: function loadModels(we, cb) {
    var models = {};
    async.parallel([
      function loadPluginModels(done) {
        var pluginNames = Object.keys(we.plugins);
        async.each(pluginNames, function(pluginName, next) {
          if (!we.plugins[pluginName].models) return next();
          _.merge(models, we.plugins[pluginName].models);
          next();
        }, done);
      },
      function loadProjectModels(done) {
        var PMP = path.resolve(we.projectPath, 'server', 'models');
        fs.exists(PMP, function (exists) {
          // this project dont have models and the models folder
          if (!exists) return done();
          // load and merge all models
          _.merge(models, requireAll({
            dirname     :  PMP,
            filter      :  /(.+)\.js$/,
            resolve     : function (model) {
              return model(we);
            }
          }));
          done();
        });
      }
    ], function (err) {
      return cb(err, models);
    });
  },

  loadControllers: function loadControllers(we, cb) {
    var controllers = {};
    async.parallel([
      function loadPluginControllers(done) {
        var pluginNames = Object.keys(we.plugins);
        async.each(pluginNames, function(pluginName, next) {
          if (!we.plugins[pluginName].controllers) return next();
          _.merge(controllers, we.plugins[pluginName].controllers);
          next();
        }, done);
      },
      function loadProjectControllers(done) {
        var PMP = path.resolve(we.projectPath, 'server', 'controllers');
        fs.exists(PMP, function(exists) {
          // this project dont have controllers and the controllers folder
          if (!exists) return done();
          // load and merge all controllers
          _.merge(controllers, requireAll({
            dirname     :  PMP,
            filter      :  /(.+)\.js$/
          }));

          done();
        });
      }
    ], function (err) {
      var controllerOO = {};
      var controllerNames = Object.keys(controllers);
      controllerNames.forEach(function(n) {
        controllerOO[n] = new Controller(controllers[n]);
      });

      return cb(err, controllerOO);
    });
  },

  loadEmailTemplates: function loadEmailTemplates(we, cb) {
    var templates = {};
    async.parallel([
      function loadPluginEmailTemplates(done) {
        try {
          async.each(we.pluginPaths, function(npmModulePath, next) {
            var PMP = path.resolve(npmModulePath, 'server', 'emails');
            return fs.readdir(PMP, function(err, paths) {
              if (err) {
                if (err.code != 'ENOENT') {
                  return next(err);
                } else {
                  return next();
                }
              }
              for (var i = paths.length - 1; i >= 0; i--) {
                templates[paths[i]] = new EmailTemplate(PMP, paths[i]);
              }
              return next();
            });
          }, function (err) {
            return done(err);
          });
        } catch(e) {
          if (e) console.error(e);
          done();
        }
      },
      function loadProjectEmailTemplates(done) {
        var PMP = path.resolve(we.projectPath, 'server', 'emails');
        fs.readdir(PMP, function(err, paths) {
          if (err) {
            if (err.code != 'ENOENT') {
              return done(err);
            } else {
              return done()
            }
          }
          for (var i = paths.length - 1; i >= 0; i--) {
            templates[paths[i]] = new EmailTemplate(PMP, paths[i]);
          }
          done();
        });
      }
    ], function (err) {
      return cb(err, templates);
    });
  }
}
<|endoftext|>