<commit_before>/**
 * This kind provide a widget to tune project properties (phonegap
 * stuff included).
 *
 * By default, this widget is tuned for project modification.  In case
 * of project *creation*, the method setupCreate must be called after
 * construction. Since the widget is re-used between call for creation
 * or modification, the methos setupModif must be called also.
 */

enyo.kind({
	name: "ProjectProperties",
	classes: "enyo-unselectable",
	fit: true,
	events: {
		onModifiedConfig: "",
		onSaveGeneratedXml: "",
		onDone: ""
	},
	createMode: true,

	components: [
		{kind: "onyx.RadioGroup", onActivate: "switchDrawers", name: "thumbnail", components: [
			{content: "Project", active: true, attributes: {title: 'project attributes...'}},
			{content: "PhoneGap", attributes: {title: 'phonegap build parameters...'}},
			{content: "Preview", attributes: {title: 'project preview parameters...'}}
		]},
		{name: "projectDrawer", kind: "onyx.Drawer", open:true, components: [
			{tag: 'table', components: [
				{tag: "tr" , components: [
					 {tag: "td" , content: "Name: "},
					 {tag: 'td', components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", defaultFocus: true, name: "projectName"}
						  ]}
					 ]},
					 {tag: 'td', content: "Title: "},
					 {tag: "td" , components: [
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", defaultFocus: true, name: "projectTitle"}
						   ]}
					  ]}
				]},
				{tag: "tr" , components: [
					 {tag: "td" , content: "Version: "},
					 {tag: 'td', components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", defaultFocus: true, name: "projectVersion"}
						  ]}
					 ]},
					 {tag: 'td', content: "Id: "},
					 {tag: "td" , components: [
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", defaultFocus: true, name: "projectId",
								attributes: {title: "Application ID in reverse domain-name format: com.example.apps.myapp"}}
						   ]}
					  ]}
				]},
				{tag: "tr" , components: [
					 {tag: "td" , content: "Author name: "},
					 {tag: 'td', attributes: {colspan: 1}, components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", name: "projectAuthor",
								attributes: {title: "Vendor / Committer Name"}
							   }
						   ]}
					 ]},
					 {tag: "td" , content: "Contact: "},
					 {tag: 'td', attributes: {colspan: 2}, components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", name: "projectContact",
								attributes: {title: "mail address or home page of the author"}
							   }
						   ]}
					 ]}
				]},
				{tag: "tr" , name:'directoryEntry', canGenerate:false, components: [
					 {tag: "td", content: "Directory: "},
					 {tag: 'td', attributes: {colspan: 3}, content: "", name: "projectDirectory" }
				]}
			]}
		]},

		{name: "phonegapDrawer", kind: "onyx.Drawer", open: false, components: [
			{
				kind: "onyx.ToggleButton",
				name: 'pgConfEnabled',
				onContent: "enabled",
				offContent: "disabled",
				style: "margin-top: 10px;"
			},
			{tag: 'table', components: [
				{tag: "tr" , components: [
					 {tag: "td" , content: "AppId: "},
					 {tag: 'td', attributes: {colspan: 1}, components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", name: "pgConfId", placeholder: "com.example.myapp",
								attributes: {title: "unique identifier, assigned by build.phonegap.com"}
							   }
						   ]}
					 ]},
					 {tag: "td" , content: "Icon URL: "},
					 {tag: 'td', attributes: {colspan: 2}, components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", name: "pgIconUrl",
								attributes: {title: "Relative location of the application icon. Defaults to Enyo icon."}
							   }
						   ]}
					 ]}
				]}
			]},
			{content: "Targets:"},
			{
				kind: "FittableRows", attributes: {'class': 'ares_projectView_switches'},
				onChange: "enablePhoneGap",
				components: [
					{kind: "onyx.ToggleButton", name: 'androidTarget', onContent: "Android", offContent: "Android"},
					{kind: "onyx.ToggleButton", name: 'iosTarget', onContent: "Ios", offContent: "Ios"},
					{kind: "onyx.ToggleButton", name: 'winphoneTarget', onContent: "Winphone", offContent: "Winphone"},
					{kind: "onyx.ToggleButton", name: 'blackberryTarget', onContent: "Blackberry", offContent: "Blackberry"},
					{kind: "onyx.ToggleButton", name: 'webosTarget',onContent: "Webos", offContent: "Webos"}
				]
			}
		]},

		{name: "previewDrawer", kind: "onyx.Drawer", open: false, components: [
			{tag: 'table', components: [
				{tag: "tr" , components: [
					{tag: "td" , content: "top application file: "},
					{tag: 'td', attributes: {colspan: 1}, components:[
						{kind: "onyx.InputDecorator", components: [
							{kind: "Input", name: "ppTopFile",
							attributes: {title: 'top file of your application. Typically index.html'}
							}
						]}
					]}
				]}
			]}
		]},

		// FIXME: there should be an HTML/CSS way to avoid using FittableStuff...
		{kind: "FittableRows", style: "margin-top: 10px; width: 100%", fit: true, components: [
			{kind: "onyx.Button", classes: "onyx-negative", content: "Cancel", ontap: "doDone"},
			{name: "ok", kind: "onyx.Button", classes: "onyx-affirmative", content: "OK", ontap: "confirmTap"}
		]},

		{kind: "Ares.ErrorPopup", name: "errorPopup", msg: "unknown error"}
	],

	debug: false,

	/**
	 * Tune the widget for project creation
	 */
	setupCreate: function() {
		//this.$.ok.setDisabled(true) ;
		this.$.directoryEntry.show() ;
	},

	/**
	 * Tune the widget for project modification
	 */
	setupModif: function() {
		//this.$.ok.setDisabled(true) ;
		this.$.directoryEntry.hide() ;
	},

	/**
	 * close one drawer and open the other depending on which radio button was tapped
	 */
	switchDrawers: function(inSender, inEvent) {
		if (inEvent.originator.active === true ) {
			var status = {
				project: false,
				phonegap: false,
				preview: false
			} ;

			status[inEvent.originator.getContent().toLowerCase()] = true ;

			for (drawer in status) {
				this.$[drawer + 'Drawer'].setOpen(status[drawer]) ;
			}
		}
	},

	// switch Phonegap to "enabled" whenever user validates a target
	enablePhoneGap: function(inSender, inEvent) {
		if (inEvent.value === true ) {
			this.$.pgConfEnabled.setValue(true) ;
		}
	},

	/**
	 * pre-fill the widget with configuration data
	 * @param {Object} config is configuration data (typically from project.json)
	 *  can be a json string or an object.
	 */
	preFill: function(inData) {
		this.config = typeof inData === 'object' ? inData : JSON.parse(inData) ;
		var pgConf ;
		var pgTarget ;
		var conf = this.config ;
		var confDefault = ProjectConfig.PREFILLED_CONFIG_FOR_UI ;

		 // avoid storing 'undefined' in there
		this.$.projectId.     setValue(conf.id      || '' );
		this.$.projectVersion.setValue(conf.version || '' );
		this.$.projectName.   setValue(conf.name    || '' );
		this.$.projectTitle.  setValue(conf.title   || '' );

		if (! conf.author) { conf.author =  {} ;}
		this.$.projectAuthor. setValue(conf.author.name || '') ;
		this.$.projectContact.setValue(conf.author.href || '') ;

		if (! conf.build) {conf.build = {} ;}
		if (! conf.build.phonegap) { conf.build.phonegap = {}; }

		pgConf = this.config.build.phonegap ;
		this.$.pgConfEnabled.setValue(pgConf.enabled);
		this.$.pgConfId.setValue(pgConf.appId || '' );
		this.$.pgIconUrl.setValue(pgConf.icon.src || confDefault.icon.src );

		if (! pgConf.targets) { pgConf.targets = {} ;}
		// pgTarget is a key of object pgConf.targets
		for (pgTarget in pgConf.targets ) {
			this.$[ pgTarget + 'Target' ].setValue(pgConf.targets[pgTarget]) ;
		}

		if (! conf.preview ) {conf.preview = {} ;}
		this.$.ppTopFile.setValue( conf.preview['top_file'] || confDefault.preview['top-file'] ) ;

		return this ;
	},

	confirmTap: function(inSender, inEvent) {
		var pgConf, tglist, ppConf ;
		// retrieve modified values
		this.log('ok tapped') ;

		this.config.id       = this.$.projectId     .getValue();
		this.config.version  = this.$.projectVersion.getValue();
		this.config.name     = this.$.projectName   .getValue();
		this.config.title    = this.$.projectTitle  .getValue();

		this.config.author.name = this.$.projectAuthor.getValue();
		this.config.author.href = this.$.projectContact.getValue();

		this.config.build.enabled = this.$.pgConfEnabled.getValue();
		this.config.build.appId   = this.$.pgConfId.getValue();

		pgConf = this.config.build.phonegap ;
		pgConf.icon.src = this.$.pgIconUrl.getValue();

		tglist = ['android','ios','winphone','blackberry','webos'] ;
		for ( i in tglist) {
			this.log('copy data from ' + tglist[i] +'Target') ;
			pgConf.targets[tglist[i]] = this.$[ tglist[i] + 'Target' ].getValue() ;
		}

		ppConf = this.config.preview ;
		ppConf['top_file'] = this.$.ppTopFile.getValue();

		// to be handled by a ProjectWizard
		this.doModifiedConfig({data: this.config}) ;

		this.doDone();

		if (inEvent.callBack) {
			inEvent.callBack() ;
		}

		// handled here (don't bubble)
		return true;
	}
});

<commit_msg>ENYO-1712: fix jshint errors<commit_after>/**
 * This kind provide a widget to tune project properties (phonegap
 * stuff included).
 *
 * By default, this widget is tuned for project modification.  In case
 * of project *creation*, the method setupCreate must be called after
 * construction. Since the widget is re-used between call for creation
 * or modification, the methos setupModif must be called also.
 */

enyo.kind({
	name: "ProjectProperties",
	classes: "enyo-unselectable",
	fit: true,
	events: {
		onModifiedConfig: "",
		onSaveGeneratedXml: "",
		onDone: ""
	},
	createMode: true,

	components: [
		{kind: "onyx.RadioGroup", onActivate: "switchDrawers", name: "thumbnail", components: [
			{content: "Project", active: true, attributes: {title: 'project attributes...'}},
			{content: "PhoneGap", attributes: {title: 'phonegap build parameters...'}},
			{content: "Preview", attributes: {title: 'project preview parameters...'}}
		]},
		{name: "projectDrawer", kind: "onyx.Drawer", open:true, components: [
			{tag: 'table', components: [
				{tag: "tr" , components: [
					 {tag: "td" , content: "Name: "},
					 {tag: 'td', components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", defaultFocus: true, name: "projectName"}
						  ]}
					 ]},
					 {tag: 'td', content: "Title: "},
					 {tag: "td" , components: [
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", defaultFocus: true, name: "projectTitle"}
						   ]}
					  ]}
				]},
				{tag: "tr" , components: [
					 {tag: "td" , content: "Version: "},
					 {tag: 'td', components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", defaultFocus: true, name: "projectVersion"}
						  ]}
					 ]},
					 {tag: 'td', content: "Id: "},
					 {tag: "td" , components: [
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", defaultFocus: true, name: "projectId",
								attributes: {title: "Application ID in reverse domain-name format: com.example.apps.myapp"}}
						   ]}
					  ]}
				]},
				{tag: "tr" , components: [
					 {tag: "td" , content: "Author name: "},
					 {tag: 'td', attributes: {colspan: 1}, components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", name: "projectAuthor",
								attributes: {title: "Vendor / Committer Name"}
							   }
						   ]}
					 ]},
					 {tag: "td" , content: "Contact: "},
					 {tag: 'td', attributes: {colspan: 2}, components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", name: "projectContact",
								attributes: {title: "mail address or home page of the author"}
							   }
						   ]}
					 ]}
				]},
				{tag: "tr" , name:'directoryEntry', canGenerate:false, components: [
					 {tag: "td", content: "Directory: "},
					 {tag: 'td', attributes: {colspan: 3}, content: "", name: "projectDirectory" }
				]}
			]}
		]},

		{name: "phonegapDrawer", kind: "onyx.Drawer", open: false, components: [
			{
				kind: "onyx.ToggleButton",
				name: 'pgConfEnabled',
				onContent: "enabled",
				offContent: "disabled",
				style: "margin-top: 10px;"
			},
			{tag: 'table', components: [
				{tag: "tr" , components: [
					 {tag: "td" , content: "AppId: "},
					 {tag: 'td', attributes: {colspan: 1}, components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", name: "pgConfId", placeholder: "com.example.myapp",
								attributes: {title: "unique identifier, assigned by build.phonegap.com"}
							   }
						   ]}
					 ]},
					 {tag: "td" , content: "Icon URL: "},
					 {tag: 'td', attributes: {colspan: 2}, components:[
						  {kind: "onyx.InputDecorator", components: [
							   {kind: "Input", name: "pgIconUrl",
								attributes: {title: "Relative location of the application icon. Defaults to Enyo icon."}
							   }
						   ]}
					 ]}
				]}
			]},
			{content: "Targets:"},
			{
				kind: "FittableRows", attributes: {'class': 'ares_projectView_switches'},
				onChange: "enablePhoneGap",
				components: [
					{kind: "onyx.ToggleButton", name: 'androidTarget', onContent: "Android", offContent: "Android"},
					{kind: "onyx.ToggleButton", name: 'iosTarget', onContent: "Ios", offContent: "Ios"},
					{kind: "onyx.ToggleButton", name: 'winphoneTarget', onContent: "Winphone", offContent: "Winphone"},
					{kind: "onyx.ToggleButton", name: 'blackberryTarget', onContent: "Blackberry", offContent: "Blackberry"},
					{kind: "onyx.ToggleButton", name: 'webosTarget',onContent: "Webos", offContent: "Webos"}
				]
			}
		]},

		{name: "previewDrawer", kind: "onyx.Drawer", open: false, components: [
			{tag: 'table', components: [
				{tag: "tr" , components: [
					{tag: "td" , content: "top application file: "},
					{tag: 'td', attributes: {colspan: 1}, components:[
						{kind: "onyx.InputDecorator", components: [
							{kind: "Input", name: "ppTopFile",
							attributes: {title: 'top file of your application. Typically index.html'}
							}
						]}
					]}
				]}
			]}
		]},

		// FIXME: there should be an HTML/CSS way to avoid using FittableStuff...
		{kind: "FittableRows", style: "margin-top: 10px; width: 100%", fit: true, components: [
			{kind: "onyx.Button", classes: "onyx-negative", content: "Cancel", ontap: "doDone"},
			{name: "ok", kind: "onyx.Button", classes: "onyx-affirmative", content: "OK", ontap: "confirmTap"}
		]},

		{kind: "Ares.ErrorPopup", name: "errorPopup", msg: "unknown error"}
	],

	debug: false,

	/**
	 * Tune the widget for project creation
	 */
	setupCreate: function() {
		//this.$.ok.setDisabled(true) ;
		this.$.directoryEntry.show() ;
	},

	/**
	 * Tune the widget for project modification
	 */
	setupModif: function() {
		//this.$.ok.setDisabled(true) ;
		this.$.directoryEntry.hide() ;
	},

	/**
	 * close one drawer and open the other depending on which radio button was tapped
	 */
	switchDrawers: function(inSender, inEvent) {
		if (inEvent.originator.active === true ) {
			var status = {
				project: false,
				phonegap: false,
				preview: false
			} ;

			status[inEvent.originator.getContent().toLowerCase()] = true ;

			for (var drawer in status) {
				this.$[drawer + 'Drawer'].setOpen(status[drawer]) ;
			}
		}
	},

	// switch Phonegap to "enabled" whenever user validates a target
	enablePhoneGap: function(inSender, inEvent) {
		if (inEvent.value === true ) {
			this.$.pgConfEnabled.setValue(true) ;
		}
	},

	/**
	 * pre-fill the widget with configuration data
	 * @param {Object} config is configuration data (typically from project.json)
	 *  can be a json string or an object.
	 */
	preFill: function(inData) {
		this.config = typeof inData === 'object' ? inData : JSON.parse(inData) ;
		var pgConf ;
		var pgTarget ;
		var conf = this.config ;
		var confDefault = ProjectConfig.PREFILLED_CONFIG_FOR_UI ;

		 // avoid storing 'undefined' in there
		this.$.projectId.     setValue(conf.id      || '' );
		this.$.projectVersion.setValue(conf.version || '' );
		this.$.projectName.   setValue(conf.name    || '' );
		this.$.projectTitle.  setValue(conf.title   || '' );

		if (! conf.author) { conf.author =  {} ;}
		this.$.projectAuthor. setValue(conf.author.name || '') ;
		this.$.projectContact.setValue(conf.author.href || '') ;

		if (! conf.build) {conf.build = {} ;}
		if (! conf.build.phonegap) { conf.build.phonegap = {}; }

		pgConf = this.config.build.phonegap ;
		this.$.pgConfEnabled.setValue(pgConf.enabled);
		this.$.pgConfId.setValue(pgConf.appId || '' );
		this.$.pgIconUrl.setValue(pgConf.icon.src || confDefault.icon.src );

		if (! pgConf.targets) { pgConf.targets = {} ;}
		// pgTarget is a key of object pgConf.targets
		for (pgTarget in pgConf.targets ) {
			this.$[ pgTarget + 'Target' ].setValue(pgConf.targets[pgTarget]) ;
		}

		if (! conf.preview ) {conf.preview = {} ;}
		this.$.ppTopFile.setValue(conf.preview.top_file);

		return this ;
	},

	confirmTap: function(inSender, inEvent) {
		var pgConf, tglist, ppConf ;
		// retrieve modified values
		this.log('ok tapped') ;

		this.config.id       = this.$.projectId     .getValue();
		this.config.version  = this.$.projectVersion.getValue();
		this.config.name     = this.$.projectName   .getValue();
		this.config.title    = this.$.projectTitle  .getValue();

		this.config.author.name = this.$.projectAuthor.getValue();
		this.config.author.href = this.$.projectContact.getValue();

		this.config.build.enabled = this.$.pgConfEnabled.getValue();
		this.config.build.appId   = this.$.pgConfId.getValue();

		pgConf = this.config.build.phonegap ;
		pgConf.icon.src = this.$.pgIconUrl.getValue();

		tglist = ['android','ios','winphone','blackberry','webos'] ;
		for (var i in tglist) {
			this.log('copy data from ' + tglist[i] +'Target') ;
			pgConf.targets[tglist[i]] = this.$[ tglist[i] + 'Target' ].getValue() ;
		}

		ppConf = this.config.preview ;
		ppConf.top_file = this.$.ppTopFile.getValue();

		// to be handled by a ProjectWizard
		this.doModifiedConfig({data: this.config}) ;

		this.doDone();

		if (inEvent.callBack) {
			inEvent.callBack() ;
		}

		// handled here (don't bubble)
		return true;
	}
});

<|endoftext|>


<commit_before>let replaceWords = {};
let USE_CAPITALIZE_WORDS = false;

function updateReplaceWords() {
  browser.runtime.sendMessage({'action': 'get_list'}).then((data) => {
    // console.log('force update', data);
    replaceWords = data;
  });
}

// get config
function canCapitalize() {
  browser.storage.local.get('can_capitalize')
  .then(can_capitalize => {
    USE_CAPITALIZE_WORDS = !can_capitalize.can_capitalize;
  })
}

// @see https://stackoverflow.com/a/33704783
function capitalizeFirstLetter(string) {
  if (USE_CAPITALIZE_WORDS)
    return string[0].toUpperCase() + string.slice(1);

  return string;
}

function beforeIsPoint(string, start, end) {
  let s = string.slice(start, end).trim();

  return s[s.length-1] == '.';
}

// do it manually
updateReplaceWords();

// run when the storage is updated
browser.storage.onChanged.addListener(() => {
  // update words
  updateReplaceWords();
  canCapitalize();
});

let BACKSPACE_KEY = 8,
    SPACE_KEY = 32,
    ENTER_KEY = 13,
    NON_ALPHANUM_KEY = 0,
    ESC_KEY = 27,
    A_SHIFT_KEY = 65,
    A_KEY = 97;

var addTextBetween = function(text, p1, p2, p3, p4, newPart) {
    return text.substr(p1, p2) + newPart + text.substr(p3, p4);
}

var textReplacer = function(element, wordsToReplace, typedWord, way_back) {
    'use strict';

    // default value
    way_back = way_back ? way_back : 0;

    if (typedWord.length == 0)
        return;

    let stringTyped = typedWord.join('');

    if (Object.keys(wordsToReplace).indexOf(stringTyped) == -1 || way_back && !Object.keys(wordsToReplace).find(key => key === stringTyped))
        return;

    let initialPoint,
      beforeWord,
      afterWord,
      finalPoint,
      replacement,
      value,
      selectionRange;

      let space_size = 1;

    if (element.isContentEditable) {
      selectionRange = document.getSelection();

      // github usa CodeMirror
      // https://stackoverflow.com/9a/24987585/3618650 - https://stackoverflow.com/a/42675264/3618650
      // https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically/19883789#19883789

      value = element.textContent;
      initialPoint = 0;
      beforeWord = selectionRange.getRangeAt(0).endOffset - typedWord.length;
      afterWord = selectionRange.getRangeAt(0).endOffset;
      finalPoint = value.length;
      replacement = unescape(wordsToReplace[stringTyped]);

      // return to shortcut
      if (way_back) {
        // change what is needed
        beforeWord = selectionRange.getRangeAt(0).endOffset - wordsToReplace[stringTyped].length - space_size;
        replacement = stringTyped;
      }

    } else {
      // all kind of inputs

      value = element.value;
      initialPoint = 0;
      beforeWord = element.selectionStart - typedWord.length;
      afterWord = element.selectionStart;
      finalPoint = element.textLength;
      // @todo remove unescape from here
      replacement = unescape(wordsToReplace[stringTyped]);

      // return to shortcut
      if (way_back) {
        // change what is needed
        beforeWord = element.selectionStart - wordsToReplace[stringTyped].length - space_size;
        replacement = stringTyped;
      }
    }

    if (!way_back && (beforeWord == initialPoint || beforeIsPoint(value, initialPoint, beforeWord))) {
      replacement = capitalizeFirstLetter(replacement);
    }
    // console.log(value,initialPoint,beforeWord,afterWord,finalPoint,replacement);

    let newContent = addTextBetween(
        value,
        initialPoint,
        beforeWord,
        afterWord,
        finalPoint,
        replacement
    );

    if (element.isContentEditable) {
      element.textContent = newContent;
    } else {
      element.value = newContent;
    }

    let cursor;
    if (way_back) {
      cursor = afterWord + (stringTyped.length - wordsToReplace[stringTyped].length) - space_size;
    } else {
      cursor = afterWord + (replacement.length - stringTyped.length)
    }

    if (element.isContentEditable) {
      let new_range = document.createRange();
      new_range.setStart(element.childNodes[0], cursor);
      new_range.setEnd(element.childNodes[0], cursor);

      selectionRange.removeAllRanges();
      selectionRange.addRange(new_range);
    } else {
      element.setSelectionRange(cursor, cursor);
    }
}

// @todo: find a better name
var settingUpReplacer = function() {
    'use strict';

    // init word
    let word = [];
    let old_word = [];

    return function(event) {
        let key = event.which;
        // osx's user => windows: event.ctrlKey
        let superKey = event.metaKey;

        // console.log('keypress');
        // console.log(key);

        switch(key) {
            case BACKSPACE_KEY:
              if (!superKey && word.length)
                  word.pop();

              if (superKey
                  // when the user select a part of the text and delete it
                  || event.target.selectionStart != event.target.selectionEnd)
                  word = [];

              break;

            case ENTER_KEY:
            case SPACE_KEY:
              textReplacer(event.target, replaceWords, word);
              old_word = word;
              word = [];
              break;

            case NON_ALPHANUM_KEY:
              // check if arrow is pressed
              // that helps cleaning the wordsToReplace
              if (event.code.toLowerCase().indexOf('arrow') >= 0)
                word = [];

              /* ESC pressed */
              // return the replaced word
              if (event.keyCode == ESC_KEY) {
                if (old_word.length > 0)
                  textReplacer(event.target, replaceWords, old_word, 1);
                old_word = word = [];
              }

              break;

            default:
              if (superKey && (key == A_SHIFT_KEY || key == A_KEY))
                // cleans words, because the user selected the whole text
                word = [];
              else
                // default behavior
                word.push(String.fromCharCode(key));
              break;
        }
    }
}

/* constante which checks if the website is supported by the plugin */
const websitesNotWorking = !(window.location.href.indexOf('facebook') >= 0
    || window.location.href.indexOf('messenger') >= 0
    || window.location.href.indexOf('github') >= 0
    || window.location.href.indexOf('slack') >= 0);

function isSupportedElement(e) {
  return websitesNotWorking
      && (e.isContentEditable
      || e.tagName.toLowerCase() == 'input'
      || e.tagName.toLowerCase() == 'textarea');
}

let replacerFnc = settingUpReplacer();

document.body.addEventListener('focus', function(e) {
  let elem = e.target
  if (isSupportedElement(elem)) {
    elem.addEventListener('keypress', replacerFnc, true)
  }
}, true);

document.body.addEventListener('blur', function(e) {
  let elem = e.target
  if (isSupportedElement(elem)) {
    elem.removeEventListener('keypress', replacerFnc, true)
  }
}, true);

// page already have an element in focus
if (isSupportedElement(document.activeElement)) {
  document.activeElement.addEventListener('keypress', replacerFnc, true);
  document.activeElement.addEventListener('blur', e => e.target.removeEventListener('keypress', replacerFnc, true), true);
}
<commit_msg>Filter some functions when some features are disabled<commit_after>let replaceWords = {};
let USE_CAPITALIZE_WORDS = false;

function updateReplaceWords() {
  browser.runtime.sendMessage({'action': 'get_list'}).then((data) => {
    // console.log('force update', data);
    replaceWords = data;
  });
}

// get config
function canCapitalize() {
  browser.storage.local.get('can_capitalize')
  .then(can_capitalize => {
    USE_CAPITALIZE_WORDS = !can_capitalize.can_capitalize;
  })
}

// @see https://stackoverflow.com/a/33704783
function capitalizeFirstLetter(string) {
  if (USE_CAPITALIZE_WORDS)
    return string[0].toUpperCase() + string.slice(1);

  return string;
}

function beforeIsPoint(string, start, end) {
  if (!USE_CAPITALIZE_WORDS)
    return;

  let s = string.slice(start, end).trim();

  return s[s.length-1] == '.';
}

// do it manually
updateReplaceWords();

// run when the storage is updated
browser.storage.onChanged.addListener(() => {
  // update words
  updateReplaceWords();
  canCapitalize();
});

let BACKSPACE_KEY = 8,
    SPACE_KEY = 32,
    ENTER_KEY = 13,
    NON_ALPHANUM_KEY = 0,
    ESC_KEY = 27,
    A_SHIFT_KEY = 65,
    A_KEY = 97;

var addTextBetween = function(text, p1, p2, p3, p4, newPart) {
    return text.substr(p1, p2) + newPart + text.substr(p3, p4);
}

var textReplacer = function(element, wordsToReplace, typedWord, way_back) {
    'use strict';

    // default value
    way_back = way_back ? way_back : 0;

    if (typedWord.length == 0)
        return;

    let stringTyped = typedWord.join('');

    if (Object.keys(wordsToReplace).indexOf(stringTyped) == -1 || way_back && !Object.keys(wordsToReplace).find(key => key === stringTyped))
        return;

    let initialPoint,
      beforeWord,
      afterWord,
      finalPoint,
      replacement,
      value,
      selectionRange;

      let space_size = 1;

    if (element.isContentEditable) {
      selectionRange = document.getSelection();

      // github usa CodeMirror
      // https://stackoverflow.com/9a/24987585/3618650 - https://stackoverflow.com/a/42675264/3618650
      // https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically/19883789#19883789

      value = element.textContent;
      initialPoint = 0;
      beforeWord = selectionRange.getRangeAt(0).endOffset - typedWord.length;
      afterWord = selectionRange.getRangeAt(0).endOffset;
      finalPoint = value.length;
      replacement = unescape(wordsToReplace[stringTyped]);

      // return to shortcut
      if (way_back) {
        // change what is needed
        beforeWord = selectionRange.getRangeAt(0).endOffset - wordsToReplace[stringTyped].length - space_size;
        replacement = stringTyped;
      }

    } else {
      // all kind of inputs

      value = element.value;
      initialPoint = 0;
      beforeWord = element.selectionStart - typedWord.length;
      afterWord = element.selectionStart;
      finalPoint = element.textLength;
      // @todo remove unescape from here
      replacement = unescape(wordsToReplace[stringTyped]);

      // return to shortcut
      if (way_back) {
        // change what is needed
        beforeWord = element.selectionStart - wordsToReplace[stringTyped].length - space_size;
        replacement = stringTyped;
      }
    }

    if (!way_back && (beforeWord == initialPoint || beforeIsPoint(value, initialPoint, beforeWord))) {
      replacement = capitalizeFirstLetter(replacement);
    }
    // console.log(value,initialPoint,beforeWord,afterWord,finalPoint,replacement);

    let newContent = addTextBetween(
        value,
        initialPoint,
        beforeWord,
        afterWord,
        finalPoint,
        replacement
    );

    if (element.isContentEditable) {
      element.textContent = newContent;
    } else {
      element.value = newContent;
    }

    let cursor;
    if (way_back) {
      cursor = afterWord + (stringTyped.length - wordsToReplace[stringTyped].length) - space_size;
    } else {
      cursor = afterWord + (replacement.length - stringTyped.length)
    }

    if (element.isContentEditable) {
      let new_range = document.createRange();
      new_range.setStart(element.childNodes[0], cursor);
      new_range.setEnd(element.childNodes[0], cursor);

      selectionRange.removeAllRanges();
      selectionRange.addRange(new_range);
    } else {
      element.setSelectionRange(cursor, cursor);
    }
}

// @todo: find a better name
var settingUpReplacer = function() {
    'use strict';

    // init word
    let word = [];
    let old_word = [];

    return function(event) {
        let key = event.which;
        // osx's user => windows: event.ctrlKey
        let superKey = event.metaKey;

        // console.log('keypress');
        // console.log(key);

        switch(key) {
            case BACKSPACE_KEY:
              if (!superKey && word.length)
                  word.pop();

              if (superKey
                  // when the user select a part of the text and delete it
                  || event.target.selectionStart != event.target.selectionEnd)
                  word = [];

              break;

            case ENTER_KEY:
            case SPACE_KEY:
              textReplacer(event.target, replaceWords, word);
              old_word = word;
              word = [];
              break;

            case NON_ALPHANUM_KEY:
              // check if arrow is pressed
              // that helps cleaning the wordsToReplace
              if (event.code.toLowerCase().indexOf('arrow') >= 0)
                word = [];

              /* ESC pressed */
              // return the replaced word
              if (event.keyCode == ESC_KEY) {
                if (old_word.length > 0)
                  textReplacer(event.target, replaceWords, old_word, 1);
                old_word = word = [];
              }

              break;

            default:
              if (superKey && (key == A_SHIFT_KEY || key == A_KEY))
                // cleans words, because the user selected the whole text
                word = [];
              else
                // default behavior
                word.push(String.fromCharCode(key));
              break;
        }
    }
}

/* constante which checks if the website is supported by the plugin */
const websitesNotWorking = !(window.location.href.indexOf('facebook') >= 0
    || window.location.href.indexOf('messenger') >= 0
    || window.location.href.indexOf('github') >= 0
    || window.location.href.indexOf('slack') >= 0);

function isSupportedElement(e) {
  return websitesNotWorking
      && (e.isContentEditable
      || e.tagName.toLowerCase() == 'input'
      || e.tagName.toLowerCase() == 'textarea');
}

let replacerFnc = settingUpReplacer();

document.body.addEventListener('focus', function(e) {
  let elem = e.target
  if (isSupportedElement(elem)) {
    elem.addEventListener('keypress', replacerFnc, true)
  }
}, true);

document.body.addEventListener('blur', function(e) {
  let elem = e.target
  if (isSupportedElement(elem)) {
    elem.removeEventListener('keypress', replacerFnc, true)
  }
}, true);

// page already have an element in focus
if (isSupportedElement(document.activeElement)) {
  document.activeElement.addEventListener('keypress', replacerFnc, true);
  document.activeElement.addEventListener('blur', e => e.target.removeEventListener('keypress', replacerFnc, true), true);
}
<|endoftext|>


<commit_before>const path = require('path')
const pify = require('pify')
const fs = pify(require('fs-extra'))
const R = require('ramda')
const { TerminalUtils, ChildProcessUtils, AppUtils } = require('constellate-dev-utils')

module.exports = async function test({ watch, passThroughArgs }) {
  TerminalUtils.title('Running test...')

  const jestPath = path.resolve(process.cwd(), './node_modules/.bin/jest')
  const jestExists = await fs.pathExists(jestPath)
  if (!jestExists) {
    throw new Error('Could not find Jest. You may need to reinstall your dependencies.')
  }

  const appConfig = AppUtils.getConfig()
  const preTestHook = R.path(['commands', 'test', 'pre'], appConfig)
  const postTestHook = R.path(['commands', 'test', 'pre'], appConfig)

  if (preTestHook) {
    TerminalUtils.info('Running the pre test hook')
    await preTestHook()
  }

  const args = watch ? ['--watch'] : passThroughArgs

  TerminalUtils.verbose(`Executing jest with args: [${args.join(', ')}]`)

  try {
    await ChildProcessUtils.spawn(jestPath, args, {
      cwd: process.cwd(),
      stdio: 'inherit',
      env: process.env,
    })
  } catch (err) {
    console.error(err)
  }

  if (postTestHook) {
    TerminalUtils.info('Running the post test hook')
    await postTestHook()
  }
}
<commit_msg>Continuing to try to fix jest testing.<commit_after>const path = require('path')
const pify = require('pify')
const fs = pify(require('fs-extra'))
const R = require('ramda')
const { TerminalUtils, ChildProcessUtils, AppUtils } = require('constellate-dev-utils')

module.exports = async function test({ watch, passThroughArgs }) {
  TerminalUtils.title('Running test...')

  const jestPath = path.resolve(process.cwd(), './node_modules/.bin/jest')
  const jestExists = await fs.pathExists(jestPath)
  if (!jestExists) {
    throw new Error('Could not find Jest. You may need to reinstall your dependencies.')
  }

  const appConfig = AppUtils.getConfig()
  const preTestHook = R.path(['commands', 'test', 'pre'], appConfig)
  const postTestHook = R.path(['commands', 'test', 'pre'], appConfig)

  if (preTestHook) {
    TerminalUtils.info('Running the pre test hook')
    await preTestHook()
  }

  const args = watch ? ['--watch'] : passThroughArgs

  TerminalUtils.verbose(`Executing jest with args: [${args.join(', ')}]`)

  try {
    await ChildProcessUtils.spawn(jestPath, args, {
      cwd: process.cwd(),
      stdio: 'inherit',
      env: process.env,
    })
  } catch (err) {
    TerminalUtils.verbose(console.error(err))
  }

  if (postTestHook) {
    TerminalUtils.info('Running the post test hook')
    await postTestHook()
  }
}
<|endoftext|>


<commit_before>import initTinymce from '../../libs/tinymce';
import Dialog from '../../libs/dialog';

$(function() {
    initTinymce();

    let form = $('<form />', {method: 'post', 'action': $('#uploader').data('upload-url')});
    $('<input />', {type: 'file', name: 'cv', id: 'input-file', style: 'visibility: hidden; height: 0'}).appendTo(form);

    form.appendTo('body');

    $('#uploader')
        .click(function() {
            $('#input-file').click();
        })
        .text($(':hidden[name="cv"]').val().split('_', 2)[1]);

    $('#input-file').change(function() {
        if (!$(this).val()) {
            return;
        }

        let formData = new FormData(form[0]);

        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: data => {
                $('#uploader').text(data.name);
                $(':hidden[name="cv"]').val(data.filename);
            },
            error: err => {
                Dialog.alert({message: err.responseJSON.cv[0]}).show();
            }
        }, 'json');
    });
});
<commit_msg>incjalizacja tinymce<commit_after>import { default as tinyConfig } from '../../libs/tinymce';
import Dialog from '../../libs/dialog';

$(function() {
    tinymce.init(tinyConfig);

    let form = $('<form />', {method: 'post', 'action': $('#uploader').data('upload-url')});
    $('<input />', {type: 'file', name: 'cv', id: 'input-file', style: 'visibility: hidden; height: 0'}).appendTo(form);

    form.appendTo('body');

    $('#uploader')
        .click(function() {
            $('#input-file').click();
        })
        .text($(':hidden[name="cv"]').val().split('_', 2)[1]);

    $('#input-file').change(function() {
        if (!$(this).val()) {
            return;
        }

        let formData = new FormData(form[0]);

        $.ajax({
            url: form.attr('action'),
            type: 'POST',
            data: formData,
            cache: false,
            contentType: false,
            processData: false,
            success: data => {
                $('#uploader').text(data.name);
                $(':hidden[name="cv"]').val(data.filename);
            },
            error: err => {
                Dialog.alert({message: err.responseJSON.cv[0]}).show();
            }
        }, 'json');
    });
});
<|endoftext|>


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

exports.getCurrentDateTime = function() {
  return new tizen.TZDate();
};

exports.getLocalTimezone = function() {
  return _sendSyncMessage('GetLocalTimeZone').value;
};

var _availableTimezonesCache = [];

exports.getAvailableTimezones = function() {
  if (_availableTimezonesCache.length)
    return _availableTimezonesCache;
  _availableTimezonesCache = _sendSyncMessage('GetAvailableTimeZones').value;
  return _availableTimezonesCache;
};

exports.getDateFormat = function(shortformat) {
  if (shortformat)
    return 'd/m/y';
  return 'D, M d y';
};

exports.getTimeFormat = function() {
  return 'h:m:s';
};

exports.isLeapYear = function(year) {
  if (!(year % 400))
    return true;
  if (!(year % 100))
    return false;
  if (!(year % 4))
    return true;
  return false;
};

function _throwProperTizenException(e) {
  if (e instanceof TypeError)
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  else if (e instanceof RangeError)
    throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR);
  else
    throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR);
}

function _sendSyncMessage(cmd, timezone, value, trans) {
  var msg = {
    'cmd': cmd,
    'timezone': timezone || '',
    'value': value || '',
    'trans': trans || ''
  };
  return JSON.parse(extension.internal.sendSyncMessage(JSON.stringify(msg)));
}

var TimeDurationUnit = [
  'MSECS',
  'SECS',
  'MINS',
  'HOURS',
  'DAYS'
];

tizen.TimeDuration = function(length, unit) {
  this.length = length || 0;
  this.unit = unit || 'MSECS';

  Object.defineProperty(this, 'length', {
    get: function() {
      return length; },
    set: function(NewValue) {
      if (NewValue != null)
        length = NewValue; }});

  Object.defineProperty(this, 'unit', {
    get: function() {
      return unit; },
    set: function(NewValue) {
      if (TimeDurationUnit.indexOf(NewValue) >= 0)
        unit = NewValue; }});

  if (TimeDurationUnit.indexOf(this.unit) == -1)
    this.unit = 'MSECS';
};

function getMultiplier(unit) {
  if (unit == 'MSECS')
    return 1.0;
  if (unit == 'SECS')
    return 1.0 * 1000.0;
  if (unit == 'MINS')
    return 60.0 * 1000.0;
  if (unit == 'HOURS')
    return 3600.0 * 1000.0;
  return 86400.0 * 1000.0;
}

function makeMillisecondsDurationObject(length) {
  var dayInMsecs = 1000 * 60 * 60 * 24;

  if ((length % dayInMsecs) == 0)
    return new tizen.TimeDuration(length / dayInMsecs, 'DAYS');

  return new tizen.TimeDuration(length, 'MSECS');
}

tizen.TimeDuration.prototype.getMilliseconds = function() {
  return getMultiplier(this.unit) * this.length;
};

tizen.TimeDuration.prototype.difference = function(other) {
  try {
    return makeMillisecondsDurationObject(this.getMilliseconds() -
                                          other.getMilliseconds());
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.equalsTo = function(other) {
  try {
    return this.getMilliseconds() == other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.lessThan = function(other) {
  try {
    return this.getMilliseconds() < other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.greaterThan = function(other) {
  try {
    return this.getMilliseconds() > other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.toString = function() {
  return this.length + ' ' + this.unit;
};

tizen.TZDate = function(year, month, day, hours, minutes, seconds, milliseconds, timezone) {
    this.date_;
    this.timezone_ = timezone || tizen.time.getLocalTimezone();

    var hours = hours || 0;
    var minutes = minutes || 0;
    var seconds = seconds || 0;
    var milliseconds = milliseconds || 0;

    if (!arguments.length)
      this.date_ = new Date();
    else if (arguments.length == 1 || arguments.length == 2) {
      if (arguments[0] instanceof Date)
        this.date_ = arguments[0];
      else
        this.date_ = new Date();
      if (arguments[1])
        this.timezone_ = arguments[1];
    }
    else
      this.date_ = new Date(year, month, day, hours, minutes, seconds, milliseconds);

    if (tizen.time.getAvailableTimezones().indexOf(this.timezone_) < 0)
      throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR);
};

function getTimezoneRawOffset(timezone) {
  return _sendSyncMessage('GetTimeZoneRawOffset', timezone).value;
};

tizen.TZDate.prototype.getDate = function() {
  return this.date_.getDate();
};

tizen.TZDate.prototype.setDate = function(date) {
  this.date_.setDate(date);
};

tizen.TZDate.prototype.getDay = function() {
  return this.date_.getDay();
};

tizen.TZDate.prototype.getFullYear = function() {
  return this.date_.getFullYear();
};

tizen.TZDate.prototype.setFullYear = function(year) {
  this.date_.setFullYear(year);
};

tizen.TZDate.prototype.getHours = function() {
  return this.date_.getHours();
};

tizen.TZDate.prototype.setHours = function(hours) {
  this.date_.setHours(hours);
};

tizen.TZDate.prototype.getMilliseconds = function() {
  return this.date_.getMilliseconds();
};

tizen.TZDate.prototype.setMilliseconds = function(ms) {
  this.date_.setMilliseconds(ms);
};

tizen.TZDate.prototype.getMonth = function() {
  return this.date_.getMonth();
};

tizen.TZDate.prototype.setMonth = function(month) {
  this.date_.setMonth(month);
};

tizen.TZDate.prototype.getMinutes = function() {
  return this.date_.getMinutes();
};

tizen.TZDate.prototype.setMinutes = function(minutes) {
  this.date_.setMinutes(minutes);
};

tizen.TZDate.prototype.getSeconds = function() {
  return this.date_.getSeconds();
};

tizen.TZDate.prototype.setSeconds = function(seconds) {
  this.date_.setSeconds(seconds);
};

tizen.TZDate.prototype.getUTCDate = function() {
  return this.date_.getUTCDate();
};

tizen.TZDate.prototype.setUTCDate = function(date) {
  this.date_.setUTCDate(date);
};

tizen.TZDate.prototype.getUTCDay = function() {
  return this.date_.getUTCDay();
};

tizen.TZDate.prototype.setUTCDay = function(day) {
  this.date_.setUTCDay(day);
};

tizen.TZDate.prototype.getUTCFullYear = function() {
  return this.date_.getUTCFullYear();
};

tizen.TZDate.prototype.setUTCFullYear = function(year) {
  this.date_.setUTCFullYear(year);
};

tizen.TZDate.prototype.getUTCHours = function() {
  return this.date_.getUTCHours();
};

tizen.TZDate.prototype.setUTCHours = function(hours) {
  this.date_.setUTCHours(hours);
};

tizen.TZDate.prototype.getUTCMilliseconds = function() {
  return this.date_.getUTCMilliseconds();
};

tizen.TZDate.prototype.setUTCMilliseconds = function(ms) {
  this.date_.setUTCMilliseconds(ms);
};

tizen.TZDate.prototype.getUTCMinutes = function() {
  return this.date_.getUTCMinutes();
};

tizen.TZDate.prototype.setUTCMinutes = function(minutes) {
  this.date_.setUTCMinutes(minutes);
};

tizen.TZDate.prototype.getUTCMonth = function() {
  return this.date_.getUTCMonth();
};

tizen.TZDate.prototype.setUTCMonth = function(month) {
  this.date_.setUTCMonth(month);
};

tizen.TZDate.prototype.getUTCSeconds = function() {
  return this.date_.getUTCSeconds();
};

tizen.TZDate.prototype.setUTCSeconds = function(secs) {
  this.date_.setUTCSeconds(secs);
};

tizen.TZDate.prototype.getTime = function() {
  return this.date_.getTime();
};

tizen.TZDate.prototype.getTimezone = function() {
  return this.timezone_;
};

tizen.TZDate.prototype.toTimezone = function(timezone) {
  if (!timezone)
    throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR);
  if (this.timezone_ == timezone)
    return this;
  var d = new tizen.TZDate(new Date(this.date_.getTime()), timezone);
  return d.addDuration(new tizen.TimeDuration((getTimezoneRawOffset(timezone) * 1) +
                                              (getTimezoneRawOffset(this.timezone_) * -1)));
};

tizen.TZDate.prototype.toLocalTimezone = function() {
  return this.toTimezone(tizen.time.getLocalTimezone());
};

tizen.TZDate.prototype.toUTC = function() {
  return this.toTimezone('GMT');
};

tizen.TZDate.prototype.difference = function(other) {
  try {
    return makeMillisecondsDurationObject(this.getTime() - other.getTime());
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.equalsTo = function(other) {
  try {
    return this.getTime() == other.getTime();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.earlierThan = function(other) {
  try {
    return this.getTime() < other.getTime();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.laterThan = function(other) {
  try {
    return this.getTime() > other.getTime();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.addDuration = function(duration) {
  try {
    var date = new tizen.TZDate(new Date(this.date_.getTime()), this.timezone_);
    date.setMilliseconds(duration.getMilliseconds() + date.getMilliseconds());
    return date;
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.toLocaleDateString = function() {
  return this.date_.toLocaleDateString();
};

tizen.TZDate.prototype.toLocaleTimeString = function() {
  return this.date_.toLocaleTimeString();
};

tizen.TZDate.prototype.toLocaleString = function() {
  return this.date_.toLocaleString();
};

tizen.TZDate.prototype.toDateString = function() {
  return this.date_.toDateString();
};

tizen.TZDate.prototype.toTimeString = function() {
  return this.date_.toTimeString();
};

tizen.TZDate.prototype.toString = function() {
  var weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][this.date_.getDay()];
  var month = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
               'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][this.date_.getMonth()];
  function pad2(num) {
    return (100 + num).toString().substring(1);
  };
  var day = pad2(this.date_.getDate());
  var year = this.date_.getFullYear();
  var hour = pad2(this.date_.getHours());
  var minute = pad2(this.date_.getMinutes());
  var second = pad2(this.date_.getSeconds());
  var dateAsString = weekday + ', ' + month + ' ' + day + ' ' + year;
  var timeAsString = hour + ' =' + minute + ' =' + second;

  return dateAsString + ' ' + timeAsString;
};

tizen.TZDate.prototype.getTimezoneAbbreviation = function() {
  var result = _sendSyncMessage('GetTimeZoneAbbreviation', this.timezone,
                                this.date_.getTime());

  if (result.error)
    return '';
  return result.value;
};

tizen.TZDate.prototype.secondsFromUTC = function() {
  return this.date_.getTimezoneOffset() * 60;
};

tizen.TZDate.prototype.isDST = function() {
  var result = _sendSyncMessage('IsDST', this.timezone, this.date_.getTime());

  if (result.error)
    return false;
  return result.value;
};

tizen.TZDate.prototype.getPreviousDSTTransition = function() {
  var result = _sendSyncMessage('GetDSTTransition', this.timezone,
                                this.date_.getTime(), 'NEXT_TRANSITION');

  if (result.error || result.value == 0)
    return undefined;
  return new tizen.TZDate(new Date(result.value), this.timezone_);
};

tizen.TZDate.prototype.getNextDSTTransition = function() {
  var result = _sendSyncMessage('GetDSTTransition', this.timezone,
                                this.date_.getTime(), 'PREV_TRANSITION');

  if (result.error || result.value == 0)
    return undefined;
  return new tizen.TZDate(new Date(result.value), this.timezone_);
};
<commit_msg>[Time] Fix timezone -> timezone_ mistype<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

exports.getCurrentDateTime = function() {
  return new tizen.TZDate();
};

exports.getLocalTimezone = function() {
  return _sendSyncMessage('GetLocalTimeZone').value;
};

var _availableTimezonesCache = [];

exports.getAvailableTimezones = function() {
  if (_availableTimezonesCache.length)
    return _availableTimezonesCache;
  _availableTimezonesCache = _sendSyncMessage('GetAvailableTimeZones').value;
  return _availableTimezonesCache;
};

exports.getDateFormat = function(shortformat) {
  if (shortformat)
    return 'd/m/y';
  return 'D, M d y';
};

exports.getTimeFormat = function() {
  return 'h:m:s';
};

exports.isLeapYear = function(year) {
  if (!(year % 400))
    return true;
  if (!(year % 100))
    return false;
  if (!(year % 4))
    return true;
  return false;
};

function _throwProperTizenException(e) {
  if (e instanceof TypeError)
    throw new tizen.WebAPIException(tizen.WebAPIException.TYPE_MISMATCH_ERR);
  else if (e instanceof RangeError)
    throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR);
  else
    throw new tizen.WebAPIException(tizen.WebAPIException.UNKNOWN_ERR);
}

function _sendSyncMessage(cmd, timezone, value, trans) {
  var msg = {
    'cmd': cmd,
    'timezone': timezone || '',
    'value': value || '',
    'trans': trans || ''
  };
  return JSON.parse(extension.internal.sendSyncMessage(JSON.stringify(msg)));
}

var TimeDurationUnit = [
  'MSECS',
  'SECS',
  'MINS',
  'HOURS',
  'DAYS'
];

tizen.TimeDuration = function(length, unit) {
  this.length = length || 0;
  this.unit = unit || 'MSECS';

  Object.defineProperty(this, 'length', {
    get: function() {
      return length; },
    set: function(NewValue) {
      if (NewValue != null)
        length = NewValue; }});

  Object.defineProperty(this, 'unit', {
    get: function() {
      return unit; },
    set: function(NewValue) {
      if (TimeDurationUnit.indexOf(NewValue) >= 0)
        unit = NewValue; }});

  if (TimeDurationUnit.indexOf(this.unit) == -1)
    this.unit = 'MSECS';
};

function getMultiplier(unit) {
  if (unit == 'MSECS')
    return 1.0;
  if (unit == 'SECS')
    return 1.0 * 1000.0;
  if (unit == 'MINS')
    return 60.0 * 1000.0;
  if (unit == 'HOURS')
    return 3600.0 * 1000.0;
  return 86400.0 * 1000.0;
}

function makeMillisecondsDurationObject(length) {
  var dayInMsecs = 1000 * 60 * 60 * 24;

  if ((length % dayInMsecs) == 0)
    return new tizen.TimeDuration(length / dayInMsecs, 'DAYS');

  return new tizen.TimeDuration(length, 'MSECS');
}

tizen.TimeDuration.prototype.getMilliseconds = function() {
  return getMultiplier(this.unit) * this.length;
};

tizen.TimeDuration.prototype.difference = function(other) {
  try {
    return makeMillisecondsDurationObject(this.getMilliseconds() -
                                          other.getMilliseconds());
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.equalsTo = function(other) {
  try {
    return this.getMilliseconds() == other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.lessThan = function(other) {
  try {
    return this.getMilliseconds() < other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.greaterThan = function(other) {
  try {
    return this.getMilliseconds() > other.getMilliseconds();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TimeDuration.prototype.toString = function() {
  return this.length + ' ' + this.unit;
};

tizen.TZDate = function(year, month, day, hours, minutes, seconds, milliseconds, timezone) {
    this.date_;
    this.timezone_ = timezone || tizen.time.getLocalTimezone();

    var hours = hours || 0;
    var minutes = minutes || 0;
    var seconds = seconds || 0;
    var milliseconds = milliseconds || 0;

    if (!arguments.length)
      this.date_ = new Date();
    else if (arguments.length == 1 || arguments.length == 2) {
      if (arguments[0] instanceof Date)
        this.date_ = arguments[0];
      else
        this.date_ = new Date();
      if (arguments[1])
        this.timezone_ = arguments[1];
    }
    else
      this.date_ = new Date(year, month, day, hours, minutes, seconds, milliseconds);

    if (tizen.time.getAvailableTimezones().indexOf(this.timezone_) < 0)
      throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR);
};

function getTimezoneRawOffset(timezone) {
  return _sendSyncMessage('GetTimeZoneRawOffset', timezone).value;
};

tizen.TZDate.prototype.getDate = function() {
  return this.date_.getDate();
};

tizen.TZDate.prototype.setDate = function(date) {
  this.date_.setDate(date);
};

tizen.TZDate.prototype.getDay = function() {
  return this.date_.getDay();
};

tizen.TZDate.prototype.getFullYear = function() {
  return this.date_.getFullYear();
};

tizen.TZDate.prototype.setFullYear = function(year) {
  this.date_.setFullYear(year);
};

tizen.TZDate.prototype.getHours = function() {
  return this.date_.getHours();
};

tizen.TZDate.prototype.setHours = function(hours) {
  this.date_.setHours(hours);
};

tizen.TZDate.prototype.getMilliseconds = function() {
  return this.date_.getMilliseconds();
};

tizen.TZDate.prototype.setMilliseconds = function(ms) {
  this.date_.setMilliseconds(ms);
};

tizen.TZDate.prototype.getMonth = function() {
  return this.date_.getMonth();
};

tizen.TZDate.prototype.setMonth = function(month) {
  this.date_.setMonth(month);
};

tizen.TZDate.prototype.getMinutes = function() {
  return this.date_.getMinutes();
};

tizen.TZDate.prototype.setMinutes = function(minutes) {
  this.date_.setMinutes(minutes);
};

tizen.TZDate.prototype.getSeconds = function() {
  return this.date_.getSeconds();
};

tizen.TZDate.prototype.setSeconds = function(seconds) {
  this.date_.setSeconds(seconds);
};

tizen.TZDate.prototype.getUTCDate = function() {
  return this.date_.getUTCDate();
};

tizen.TZDate.prototype.setUTCDate = function(date) {
  this.date_.setUTCDate(date);
};

tizen.TZDate.prototype.getUTCDay = function() {
  return this.date_.getUTCDay();
};

tizen.TZDate.prototype.setUTCDay = function(day) {
  this.date_.setUTCDay(day);
};

tizen.TZDate.prototype.getUTCFullYear = function() {
  return this.date_.getUTCFullYear();
};

tizen.TZDate.prototype.setUTCFullYear = function(year) {
  this.date_.setUTCFullYear(year);
};

tizen.TZDate.prototype.getUTCHours = function() {
  return this.date_.getUTCHours();
};

tizen.TZDate.prototype.setUTCHours = function(hours) {
  this.date_.setUTCHours(hours);
};

tizen.TZDate.prototype.getUTCMilliseconds = function() {
  return this.date_.getUTCMilliseconds();
};

tizen.TZDate.prototype.setUTCMilliseconds = function(ms) {
  this.date_.setUTCMilliseconds(ms);
};

tizen.TZDate.prototype.getUTCMinutes = function() {
  return this.date_.getUTCMinutes();
};

tizen.TZDate.prototype.setUTCMinutes = function(minutes) {
  this.date_.setUTCMinutes(minutes);
};

tizen.TZDate.prototype.getUTCMonth = function() {
  return this.date_.getUTCMonth();
};

tizen.TZDate.prototype.setUTCMonth = function(month) {
  this.date_.setUTCMonth(month);
};

tizen.TZDate.prototype.getUTCSeconds = function() {
  return this.date_.getUTCSeconds();
};

tizen.TZDate.prototype.setUTCSeconds = function(secs) {
  this.date_.setUTCSeconds(secs);
};

tizen.TZDate.prototype.getTime = function() {
  return this.date_.getTime();
};

tizen.TZDate.prototype.getTimezone = function() {
  return this.timezone_;
};

tizen.TZDate.prototype.toTimezone = function(timezone) {
  if (!timezone)
    throw new tizen.WebAPIException(tizen.WebAPIException.INVALID_VALUES_ERR);
  if (this.timezone_ == timezone)
    return this;
  var d = new tizen.TZDate(new Date(this.date_.getTime()), timezone);
  return d.addDuration(new tizen.TimeDuration((getTimezoneRawOffset(timezone) * 1) +
                                              (getTimezoneRawOffset(this.timezone_) * -1)));
};

tizen.TZDate.prototype.toLocalTimezone = function() {
  return this.toTimezone(tizen.time.getLocalTimezone());
};

tizen.TZDate.prototype.toUTC = function() {
  return this.toTimezone('GMT');
};

tizen.TZDate.prototype.difference = function(other) {
  try {
    return makeMillisecondsDurationObject(this.getTime() - other.getTime());
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.equalsTo = function(other) {
  try {
    return this.getTime() == other.getTime();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.earlierThan = function(other) {
  try {
    return this.getTime() < other.getTime();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.laterThan = function(other) {
  try {
    return this.getTime() > other.getTime();
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.addDuration = function(duration) {
  try {
    var date = new tizen.TZDate(new Date(this.date_.getTime()), this.timezone_);
    date.setMilliseconds(duration.getMilliseconds() + date.getMilliseconds());
    return date;
  } catch (e) {
    _throwProperTizenException(e);
  }
};

tizen.TZDate.prototype.toLocaleDateString = function() {
  return this.date_.toLocaleDateString();
};

tizen.TZDate.prototype.toLocaleTimeString = function() {
  return this.date_.toLocaleTimeString();
};

tizen.TZDate.prototype.toLocaleString = function() {
  return this.date_.toLocaleString();
};

tizen.TZDate.prototype.toDateString = function() {
  return this.date_.toDateString();
};

tizen.TZDate.prototype.toTimeString = function() {
  return this.date_.toTimeString();
};

tizen.TZDate.prototype.toString = function() {
  var weekday = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'][this.date_.getDay()];
  var month = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
               'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][this.date_.getMonth()];
  function pad2(num) {
    return (100 + num).toString().substring(1);
  };
  var day = pad2(this.date_.getDate());
  var year = this.date_.getFullYear();
  var hour = pad2(this.date_.getHours());
  var minute = pad2(this.date_.getMinutes());
  var second = pad2(this.date_.getSeconds());
  var dateAsString = weekday + ', ' + month + ' ' + day + ' ' + year;
  var timeAsString = hour + ' =' + minute + ' =' + second;

  return dateAsString + ' ' + timeAsString;
};

tizen.TZDate.prototype.getTimezoneAbbreviation = function() {
  var result = _sendSyncMessage('GetTimeZoneAbbreviation', this.timezone_,
                                this.date_.getTime());

  if (result.error)
    return '';
  return result.value;
};

tizen.TZDate.prototype.secondsFromUTC = function() {
  return this.date_.getTimezoneOffset() * 60;
};

tizen.TZDate.prototype.isDST = function() {
  var result = _sendSyncMessage('IsDST', this.timezone_, this.date_.getTime());

  if (result.error)
    return false;
  return result.value;
};

tizen.TZDate.prototype.getPreviousDSTTransition = function() {
  var result = _sendSyncMessage('GetDSTTransition', this.timezone_,
                                this.date_.getTime(), 'NEXT_TRANSITION');

  if (result.error || result.value == 0)
    return undefined;
  return new tizen.TZDate(new Date(result.value), this.timezone_);
};

tizen.TZDate.prototype.getNextDSTTransition = function() {
  var result = _sendSyncMessage('GetDSTTransition', this.timezone_,
                                this.date_.getTime(), 'PREV_TRANSITION');

  if (result.error || result.value == 0)
    return undefined;
  return new tizen.TZDate(new Date(result.value), this.timezone_);
};
<|endoftext|>


<commit_before>import _ from 'lodash';

let fakeIndex = 0;

export const addItemToCategories = (categories, item) => {
	let newCategories = [].concat(categories);
	let added = false;
	//// add to existing category
	for (let i = 0; i < newCategories.length; i++) {
		let category = newCategories[i];
		if (category.id === item.category_id) {
			category.items.push(item);
			category.items.sort(sortByNameKey);
			added = true;
			break;
		}
	}
	//// add to new category
	if (!added) {
		newCategories.push({
			name: item.category,
			id: item.category_id,
			items: [item]
		});
		newCategories = sortCategories(newCategories);
	}
	return newCategories;
};

export const removeItemFromCategories = (categories, item) => {
	let newCategories = [];
	let removed = false;
	//// remove from existing category
	for (let i = 0; i < categories.length; i++) {
		let category = categories[i];
		if (!removed && (category.name === item.category)) {
			const items = _.filter(category.items, catitem => catitem.id !== item.id);
			category = {
				...category,
				items
			};
			removed = true;
		}
		if (category.items.length > 0) {
			newCategories.push(category);
		}
	}
	return newCategories;
};

export const updateItemInCategories = (categories, item) => {
	const newCategories = [];
	//// index of new category
	const newCategoryIndex = _.findIndex(categories, category => category.name === item.category);
	//// index of old category
	let oldCategoryIndex;
	for (let i = 0; i < categories.length; i++) {
		let category = categories[i];
		let index = _.findIndex(category.items, catitem => catitem.id === item.id);
		if (index > -1) {
			oldCategoryIndex = index;
			break;
		}
	}
	//// build new categories array
	for (let i = 0; i < categories.length; i++) {
		let newItem, container_id;
		let category = categories[i];
		let newCategory = {...category};
		if (i === oldCategoryIndex) {
			let itemIndex = _.findIndex(category.items, catitem => catitem.id === item.id);
			container_id = category.container_id;
			//// category is same, update existing item
			if (oldCategoryIndex === newCategoryIndex) {
				newItem = {
					...item,
					category_id: category.id
				};
				newCategory.items[itemIndex] = newItem;

			//// category is different, remove old item
			} else {
				newCategory.items = _.filter(newCategory.items, catitem => catitem.id !== item.id);
			}
		//// category is different, add new item
		} else if (i === newCategoryIndex) {
				newItem = {
					...item,
					category_id: category.id
				};
				newCategory.items.push(newItem);
				newCategory.items.sort(sortByNameKey);
		}
		//// add if category has items
		if (newCategory.items.length) {
			newCategories.push(newCategory);
		}

	}
	//// add new category
	if (newCategoryIndex === -1) {
		const category_id = fakeIndex++;
		const newItem = {
			...item,
			category_id,
		};
		const newCategory = {
			id: category_id,
			name: item.category,
			container_id,
			items: [newItem]
		};
		newCategories.push(newCategory);
		newCategories.sort(sortByNameKey);
	}
	return newCategories;
};

const sortByNameKey = (x, y) => {
	if (x.name.toUpperCase() < y.name.toUpperCase()) return -1;
	else if (x.name.toUpperCase() > y.name.toUpperCase()) return 1;
	else return 0;
}

export const sortCategories = categories => {
	const newCategories = categories.filter(category => category.items.length > 0);
	newCategories.sort(sortByNameKey);
	newCategories.forEach(category => {
		category.items.sort(sortByNameKey);
	});
	return newCategories;
};

export const filterCategories = (categories, text) => {
	if (!text) {
		return categories;
	}
	text = text.toUpperCase();

	const newCategories = [];
	categories.forEach(category => {
		if (matchesFilterByName(category, text)) {
			newCategories.push(category);
		} else {
			const filteredItems = category.items.filter(item => matchesFilterByName(item, text));
			if (filteredItems.length > 0) {
				const newCategory = {
					...category,
					items: filteredItems
				};
				newCategories.push(newCategory);
			}
		}
	});
	return newCategories;
};

const matchesFilterByName = (item, text) => item.name.toUpperCase().indexOf(text) > -1;

export const sortCategory = category => {

};<commit_msg>fix issue with adding item to existing category<commit_after>import _ from 'lodash';

let fakeIndex = 0;

export const addItemToCategories = (categories, item) => {
	let newCategories = [].concat(categories);
	let added = false;
	//// add to existing category
	for (let i = 0; i < newCategories.length; i++) {
		let category = newCategories[i];
		if (category.name === item.category) {
			category.items.push(item);
			category.items.sort(sortByNameKey);
			added = true;
			break;
		}
	}
	//// add to new category
	if (!added) {
		newCategories.push({
			name: item.category,
			id: item.category_id,
			items: [item]
		});
		newCategories = sortCategories(newCategories);
	}
	return newCategories;
};

export const removeItemFromCategories = (categories, item) => {
	let newCategories = [];
	let removed = false;
	//// remove from existing category
	for (let i = 0; i < categories.length; i++) {
		let category = categories[i];
		if (!removed && (category.name === item.category)) {
			const items = _.filter(category.items, catitem => catitem.id !== item.id);
			category = {
				...category,
				items
			};
			removed = true;
		}
		if (category.items.length > 0) {
			newCategories.push(category);
		}
	}
	return newCategories;
};

export const updateItemInCategories = (categories, item) => {
	const newCategories = [];
	//// index of new category
	const newCategoryIndex = _.findIndex(categories, category => category.name === item.category);
	//// index of old category
	let oldCategoryIndex;
	for (let i = 0; i < categories.length; i++) {
		let category = categories[i];
		let index = _.findIndex(category.items, catitem => catitem.id === item.id);
		if (index > -1) {
			oldCategoryIndex = index;
			break;
		}
	}
	//// build new categories array
	for (let i = 0; i < categories.length; i++) {
		let newItem, container_id;
		let category = categories[i];
		let newCategory = {...category};
		if (i === oldCategoryIndex) {
			let itemIndex = _.findIndex(category.items, catitem => catitem.id === item.id);
			container_id = category.container_id;
			//// category is same, update existing item
			if (oldCategoryIndex === newCategoryIndex) {
				newItem = {
					...item,
					category_id: category.id
				};
				newCategory.items[itemIndex] = newItem;

			//// category is different, remove old item
			} else {
				newCategory.items = _.filter(newCategory.items, catitem => catitem.id !== item.id);
			}
		//// category is different, add new item
		} else if (i === newCategoryIndex) {
				newItem = {
					...item,
					category_id: category.id
				};
				newCategory.items.push(newItem);
				newCategory.items.sort(sortByNameKey);
		}
		//// add if category has items
		if (newCategory.items.length) {
			newCategories.push(newCategory);
		}

	}
	//// add new category
	if (newCategoryIndex === -1) {
		const category_id = fakeIndex++;
		const newItem = {
			...item,
			category_id,
		};
		const newCategory = {
			id: category_id,
			name: item.category,
			container_id,
			items: [newItem]
		};
		newCategories.push(newCategory);
		newCategories.sort(sortByNameKey);
	}
	return newCategories;
};

const sortByNameKey = (x, y) => {
	if (x.name.toUpperCase() < y.name.toUpperCase()) return -1;
	else if (x.name.toUpperCase() > y.name.toUpperCase()) return 1;
	else return 0;
}

export const sortCategories = categories => {
	const newCategories = categories.filter(category => category.items.length > 0);
	newCategories.sort(sortByNameKey);
	newCategories.forEach(category => {
		category.items.sort(sortByNameKey);
	});
	return newCategories;
};

export const filterCategories = (categories, text) => {
	if (!text) {
		return categories;
	}
	text = text.toUpperCase();

	const newCategories = [];
	categories.forEach(category => {
		if (matchesFilterByName(category, text)) {
			newCategories.push(category);
		} else {
			const filteredItems = category.items.filter(item => matchesFilterByName(item, text));
			if (filteredItems.length > 0) {
				const newCategory = {
					...category,
					items: filteredItems
				};
				newCategories.push(newCategory);
			}
		}
	});
	return newCategories;
};

const matchesFilterByName = (item, text) => item.name.toUpperCase().indexOf(text) > -1;

export const sortCategory = category => {

};<|endoftext|>


<commit_before>/*!
* Copyright 2014 - 2014 Ivy Information Systems Ltd.  All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to  http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
var gaugeComponent = BaseComponent.extend({

	GUID: function(){
		function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); };
		return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
	},

	gaugeChartObj: [],

	gridSize: function(rowNum){
		if(rowNum == 1){
			return [1, "100%"];
		}else if(rowNum > 3){
			return [4, "25%"];
		}

		return [2, "50%"];
	},

	update : function() {
		var myself=this;

		$("#"+myself.htmlObject).empty();

		if(!myself.queryDefinition){
			console.log("query not defined");
			dataViewerHTML = "We need to set a query with two fields of data!";
		} else {

			if(Dashboards.debug!=1)Dashboards.log("Datasource has been added");

			var query = new Query(myself.queryDefinition);

			if(Dashboards.debug!=1)Dashboards.log("Parameters: " + JSON.stringify(myself.parameters)||"<no parameters>");

			query.fetchData(myself.parameters, function(values) {

				var gridConf = myself.gridSize(values.resultset.length);

				var currRow, currCol;
				for(var idx = 0; idx<values.resultset.length; idx++){
					if(idx==0||idx%gridConf[0]==0){
						currRow = myself.GUID();
						$("#"+myself.htmlObject).append("

");
					}

					currCol = myself.GUID();
					$("#"+currRow).append("

");

					var actualValue, minValue, maxValue, title, subtitle;
					if(myself.label == undefined){
						title = values.resultset[idx][0];
					} else {
						title = myself.label;
					}

					if(myself.subTitle == undefined){
						subTitle = "";
					} else {
						subTitle = myself.subTitle;
					}

					if(myself.maxValue == undefined){
						minValue = values.resultset[idx][2];
					} else {
						minValue = myself.minValue;
					}

					if(myself.maxValue == undefined){
						maxValue = values.resultset[idx][3];
					} else {
						maxValue = myself.maxValue;
					}

					var gageConf = {
						id: currCol,
						value: values.resultset[idx][1],
						min: minValue,
						max: maxValue,
						title: title,
						label:subTitle,
						gaugeWidthScale:myself.gaugeWidthScale,
	          			symbol: myself.gaugeSymbol,
	        			relativeGaugeSize: true,
	        			formatNumber: myself.formatNumber,
	        			donut: myself.gaugeType == "doughnut"
					};

					if(myself.textRenderer != undefined && typeof myself.textRenderer == "function"){
						gageConf.textRenderer = myself.textRenderer;
					}

					if(values.resultset[idx][4] !== undefined){
						gageConf.gaugeColor = values.resultset[idx][4];
					}

					if(values.resultset[idx][5] !== undefined){
						var lvlColors = [values.resultset[idx][5]];
						if(values.resultset[idx][6] !== undefined){
							lvlColors.push(values.resultset[idx][6]);
						}
						if(values.resultset[idx][7] !== undefined){
							lvlColors.push(values.resultset[idx][7]);
						}
						gageConf.levelColors = lvlColors;
					}

					var extension = {};
					if(myself.extensionPoints != undefined && myself.extensionPoints[0] != undefined){
						for(var i = 0; i < myself.extensionPoints.length; i++){
							extension[myself.extensionPoints[i][0]] = typeof myself.extensionPoints[i][1] === 'function'?myself.extensionPoints[i][1]():myself.extensionPoints[i][1];
						}
					}

					gageConf = $.extend({}, gageConf, extension);

					if(Dashboards.debug!=1)Dashboards.log("Final gage properties: " + JSON.stringify(gageConf, function(key, val) { if (typeof val === 'function') {return val.toString();}return val;})||"<no properties>");

					myself.gaugeChartObj[idx] = new JustGage(gageConf);
					if(myself.expression!==undefined){
						$("#"+currCol).click(function(e){
							myself.expression(e);
						});
					}
				}
			});
		}
	}
});<commit_msg>#38 Exposing better the gage data object<commit_after>/*!
* Copyright 2014 - 2014 Ivy Information Systems Ltd.  All rights reserved.
*
* This software was developed by Webdetails and is provided under the terms
* of the Mozilla Public License, Version 2.0, or any later version. You may not use
* this file except in compliance with the license. If you need a copy of the license,
* please go to  http://mozilla.org/MPL/2.0/. The Initial Developer is Webdetails.
*
* Software distributed under the Mozilla Public License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or  implied. Please refer to
* the license for the specific language governing your rights and limitations.
*/
var gaugeComponent = BaseComponent.extend({

	GUID: function(){
		function S4() { return (((1+Math.random())*0x10000)|0).toString(16).substring(1); };
		return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0,3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase();
	},

	gaugeChartObj: [],

	gridSize: function(rowNum){
		if(rowNum == 1){
			return [1, "100%"];
		}else if(rowNum > 3){
			return [4, "25%"];
		}

		return [2, "50%"];
	},

	update : function() {
		var myself=this;

		$("#"+myself.htmlObject).empty();

		if(!myself.queryDefinition){
			console.log("query not defined");
			dataViewerHTML = "We need to set a query with two fields of data!";
		} else {

			if(Dashboards.debug!=1)Dashboards.log("Datasource has been added");

			var query = new Query(myself.queryDefinition);

			if(Dashboards.debug!=1)Dashboards.log("Parameters: " + JSON.stringify(myself.parameters)||"<no parameters>");

			query.fetchData(myself.parameters, function(values) {

				var gridConf = myself.gridSize(values.resultset.length);

				var currRow, currCol;
				for(var idx = 0; idx<values.resultset.length; idx++){
					if(idx==0||idx%gridConf[0]==0){
						currRow = myself.GUID();
						$("#"+myself.htmlObject).append("

");
					}

					currCol = myself.GUID();
					$("#"+currRow).append("

");

					var actualValue, minValue, maxValue, title, subtitle;
					if(myself.label == undefined){
						title = values.resultset[idx][0];
					} else {
						title = myself.label;
					}

					if(myself.subTitle == undefined){
						subTitle = "";
					} else {
						subTitle = myself.subTitle;
					}

					if(myself.maxValue == undefined){
						minValue = values.resultset[idx][2];
					} else {
						minValue = myself.minValue;
					}

					if(myself.maxValue == undefined){
						maxValue = values.resultset[idx][3];
					} else {
						maxValue = myself.maxValue;
					}

					var gageConf = {
						id: currCol,
						value: values.resultset[idx][1],
						min: minValue,
						max: maxValue,
						title: title,
						label:subTitle,
						gaugeWidthScale:myself.gaugeWidthScale,
	          			symbol: myself.gaugeSymbol,
	        			relativeGaugeSize: true,
	        			formatNumber: myself.formatNumber,
	        			donut: myself.gaugeType == "doughnut"
					};

					if(myself.textRenderer != undefined && typeof myself.textRenderer == "function"){
						gageConf.textRenderer = myself.textRenderer;
					}

					if(values.resultset[idx][4] !== undefined){
						gageConf.gaugeColor = values.resultset[idx][4];
					}

					if(values.resultset[idx][5] !== undefined){
						var lvlColors = [values.resultset[idx][5]];
						if(values.resultset[idx][6] !== undefined){
							lvlColors.push(values.resultset[idx][6]);
						}
						if(values.resultset[idx][7] !== undefined){
							lvlColors.push(values.resultset[idx][7]);
						}
						gageConf.levelColors = lvlColors;
					}

					var extension = {};
					if(myself.extensionPoints != undefined && myself.extensionPoints[0] != undefined){
						for(var i = 0; i < myself.extensionPoints.length; i++){
							extension[myself.extensionPoints[i][0]] = typeof myself.extensionPoints[i][1] === 'function'?myself.extensionPoints[i][1]():myself.extensionPoints[i][1];
						}
					}

					gageConf = $.extend({}, gageConf, extension);

					if(Dashboards.debug!=1)Dashboards.log("Final gage properties: " + JSON.stringify(gageConf, function(key, val) { if (typeof val === 'function') {return val.toString();}return val;})||"<no properties>");

					new JustGage(gageConf);

					myself.gaugeChartObj[currCol] = gageConf;
					if(myself.expression!==undefined){
						$("#"+currCol).click(function(e){
							myself.expression(e, myself.gaugeChartObj[e.currentTarget.id]);
						});
					}
				}
			});
		}
	}
});<|endoftext|>


<commit_before>(function($) {

$.widget("ui.treeselect", {
		options: {
				datas: []
		},

		_create: function(){
				var self=this;
				this.element.addClass('ui-widget ui-helper-reset');
				this.container = $("

").
						appendTo(this.element);

				this.searchInput =
						$("
"+
								 "Rechercher: <input type='textfield' size='50'></input>"+
							"
").
						appendTo(this.container).
						find('input').keyup(function(event){
										self._onSearchInputChange($(this).val());
								}).end();

				this.itemsTree = ($("
")).
						appendTo(this.container);

				this.selectedItems =
						$("
"+
								 "
"+
										 "

").
						appendTo(this.container).
						find("ul");

				this._createDataTree();
				this._initialize();
		},

		_initialize: function(){
				this._initSelection();
				this._initAccordion();
				this._initSortable();
		},

		_destroy: function() {
				$.Widget.prototype.destroy.apply(this, arguments);
				this.container.remove(this.container.children());
		},

		_addCategoriesTo: function(categories, parent) {
				var self = this;

				if (categories == undefined) return;

				if (this.mkli == undefined)
						this.mkli = function(catOrItem, parent, type){
								return	$("
"+
														"<input type='checkbox' />" +
														"" +
																""+
																catOrItem.label+
														"" +
													"
").
										data("label", catOrItem.label).
										data("type", type).
										data("id", catOrItem.id).
										appendTo(parent).
										children('a').hover(
												function (event) {
														self._onMouseEntersLI($(event.target).parent());
												},
												function (event) {
														self._onMouseExitsLI($(event.target).parent());
												}).end();
						};

				var self = this;
				$.each(categories, function(index, cat) {
						var cat_li = self.mkli(cat, parent, 'category');

						if ((cat.categories.length + cat.items.length) == 0) {
								cat_li.addClass('ui-treeselect-empty-category');
								return;
						}

						var cat_ul = $("

").appendTo(cat_li);
						self._addCategoriesTo(cat.categories, cat_ul);

						$.each(cat.items, function(index, item){
								self.mkli(item, cat_ul, 'item').
										children('a');
						});
				});
		},

		_onMouseEntersLI: function(li) {
				var anchor = li.children('a');

				anchor.data('on_mouse_enter_classes', anchor[0].className);
				anchor.
						addClass("ui-state-hover").
						removeClass("ui-state-default").
						removeClass("ui-state-highlight").
						removeClass("ui-state-active");

				if (li.parents('.ui-treeselect-selected-items').length == 0) return;

				var hint =
						$('
').
						hide().
						appendTo(li);

				hint.delay(1000).fadeIn('fast');

				var sourceLI = this._findConnectedIn(li, this.itemsTree);

				this._getAnchorTreeFor(sourceLI).
						slice(0, -1).
						each(function(index, element){
								hint = $("
"+$(element).text()+"
").
										appendTo($("

")).
										appendTo(hint);
						});
		},

		_onMouseExitsLI: function(li) {
				var anchor = 	li.children('a');

				anchor.
						addClass(anchor.data('on_mouse_enter_classes')).
						removeData('on_mouse_enter_classes').
						removeClass("ui-state-hover");

				this.selectedItems.find('.hint').remove();
		},

		_createDataTree: function(){
				var self = this;
				$.each(this.options.datas, function(index, cat) {
						$("
"+cat.label+"
").
								appendTo(self.itemsTree);

						var ul = $("

").
								appendTo(self.itemsTree).
								append("

").
								children()[0];

						self._addCategoriesTo(cat.categories, ul);
				});
		},

		_initAccordion: function(){
				this.itemsTree.accordion();
		},

		_initSortable: function(){
				var self=this;
				this.selectedItems.
						addClass("sortable").
						sortable({
								cursor:'crosshair',
								opacity: 0.8,
								start: function(event, ui) {$(this).find('.hint').remove();}
						});

				this._adaptSelectedItemSize();
		},

		_adaptSelectedItemSize: function(){
				var inner = this.selectedItems.closest('.ui-treeselect-selected-items-inner');
				var outer = inner.parent();
				inner.height(this.itemsTree.height() - (outer.height() - inner.height()));
				inner.css('min-height', inner.height() + 'px');
		},

		_initSelection: function(){
				var self=this;

				this.itemsTree.find('li').each(
						function(index, li){
								$(li).data('sid', index);});

				this.itemsTree.change(
						function(event){
								self._onSelectionChange($(event.target).parent());
								event.stopPropagation();});

				this.itemsTree.find('li>ul').css("display","none");
				this.itemsTree.click(
						function(event){
								var $target = $(event.target);
								if ($target.is("a>*")) $target = $target.parent();
								if ($target.is("a")) {
										event.stopPropagation();
										event.preventDefault();
										$target.siblings('ul').find('ul').hide();
										$target.siblings('ul').toggle('fast', function(){
												self._turnHighlightOff();
										});}})
		},

		_findConnectedIn: function(li, items) {
				var sid = li.data('sid');
				return items.find('li[sid='+sid+']');
		},

		_deselect: function(li) {
				this._findConnectedIn(li, this.selectedItems).
						hide('fast', function(){
								$(this).remove()});

				li.children('input').removeAttr('checked');
				li.find("li input").removeAttr('disabled');
				li.children('a').removeClass('ui-state-active');
		},

		_setInactive: function(li) {
				li.children('a').removeClass('ui-state-active');

				parent = li.parent().parent();
				if (parent.length == 0) return;

				if (parent.find('li>input:checked').length==0) {
						this._setInactive(parent);
				}
		},

		_select: function(li) {
				var self = this;

				li.children('input').attr('checked', 'checked');

				var selectedLI = $("
"+
															"" +
															 $(li).data("label") +
														 "
").
						appendTo(self.selectedItems).
						data(li.data()).
						children('a').
						addClass('ui-state-default').
						addClass(li[0].className).
						hover(
								function (event) {
										self._onMouseEntersLI($(event.target).parent());
								},
								function (event) {
										self._onMouseExitsLI($(event.target).parent());
								}
						).end().
						click(
								function(event){
										event.preventDefault();
										if ($(event.target).is('a'))
												self._highlightSelected($(event.target).parent());
								});

				$("
").
						appendTo(selectedLI).
						click(function(event){
								self._deselect(
										self._findConnectedIn($(event.target).parent(),
																					self.itemsTree));
						});

				li.parents('li').andSelf().children('a').addClass('ui-state-active');

				this._disableChildren(li);
		},

		_disableChildren: function(li) {
				var self = this;
				li.find("li>input").each(
						function(index, checkbox) {
								self._deselect($(checkbox).parent());
								$(checkbox).
										attr('disabled', true).
										removeAttr('checked'); });
		},

		_onSelectionChange: function(li) {
				this._turnHighlightOff();
				if (li.children('input').is(':checked')) {
						this._select(li);
				}	else {
						this._deselect(li);
						this._setInactive(li);
				}

				this.selectedItems.sortable('refresh');
		},

		_turnHighlightOff: function() {
				this.container.find('.ui-state-highlight').
						removeClass("ui-state-highlight").
						filter('li a, h3').
						addClass("ui-state-default");
		},

		_hideAll: function() {
				this._turnHighlightOff();
				this.itemsTree.find('ul ul:visible').hide();
		},

		_getAnchorTreeFor: function(li) {
				var parents = li.parentsUntil('.ui-treeselect-items-tree, .ui-treeselect-selected-items');
				var litree = parents.andSelf().children('a');
				return litree.add(parents.last().prev());
		},

		_highlightItems: function(lis) {
				this._hideAll();
				lis.parents("ul").show();

				var self = this;
				lis.each(function(index, li) {
						self._getAnchorTreeFor($(li)).
								addClass("ui-state-highlight").
								removeClass("ui-state-default");
				});
		},

		_highlightSelected: function(li) {
				var itemToHighlight = this._findConnectedIn(li, this.itemsTree);

				this._highlightItems(itemToHighlight.add(li));

				itemToHighlight.
						parents(".ui-accordion-content").prev().click();
		},

		_onSearchInputChange: function(searchText) {
				if (searchText=="") {
						this._hideAll();
						return;
				}

				var re = new RegExp(searchText, 'i');
				var matches = this.itemsTree.find('li, h3').filter(function() {
						return re.test($(this).text());
				});
				this._highlightItems(matches);
		},

		_selectByIdAndType: function(ids, type) {
				var self = this;
				jQuery.each(ids, function(index, id) {
					self.itemsTree.find('li[id='+id+']').each(function(index, li) {
						if ($(li).data('type') == type)
							self._select($(li));
					});
				});
		},

		_getSelectedDataByType: function(type) {
				var datas = [];
				this.selectedItems.find('li').each(function(index,li){
					if ($(li).data('type') == type) {
						datas.push({"id": $(li).data('id'),
												"label": $(li).data('label')});
					}
				});
				return datas;
		},

		selectItems: function(ids) {
				this._selectByIdAndType(ids, 'item');
		},

		selectCategories: function(ids) {
				this._selectByIdAndType(ids, 'category');
		},

		readSelection: function(callback) {
				callback(
						this._getSelectedDataByType('item'),
						this._getSelectedDataByType('category'));
		},

		toggleVisibility: function(visible) {
				if (visible) {
						var self = this;
						this.element.show('fast',
															function() {
																	self.itemsTree.children('div').height(200);
																	self._adaptSelectedItemSize();});
				} else {
						this.element.hide('fast');
				}
		}
})})(jQuery);<commit_msg>correction du sélecteur d'articles avec jquery 1.7<commit_after>(function($) {

$.widget("ui.treeselect", {
		options: {
				datas: []
		},

		_create: function(){
				var self=this;
				this.element.addClass('ui-widget ui-helper-reset');
				this.container = $("

").
						appendTo(this.element);

				this.searchInput =
						$("
"+
								 "Rechercher: <input type='textfield' size='50'></input>"+
							"
").
						appendTo(this.container).
						find('input').keyup(function(event){
										self._onSearchInputChange($(this).val());
								}).end();

				this.itemsTree = ($("
")).
						appendTo(this.container);

				this.selectedItems =
						$("
"+
								 "
"+
										 "

").
						appendTo(this.container).
						find("ul");

				this._createDataTree();
				this._initialize();
		},

		_initialize: function(){
				this._initSelection();
				this._initAccordion();
				this._initSortable();
		},

		_destroy: function() {
				$.Widget.prototype.destroy.apply(this, arguments);
				this.container.remove(this.container.children());
		},

		_addCategoriesTo: function(categories, parent) {
				var self = this;

				if (categories == undefined) return;

				if (this.mkli == undefined)
						this.mkli = function(catOrItem, parent, type){
								return	$("
"+
														"<input type='checkbox' />" +
														"" +
																""+
																catOrItem.label+
														"" +
													"
").
										data("label", catOrItem.label).
										data("type", type).
										data("elid", catOrItem.id).
										appendTo(parent).
										children('a').hover(
												function (event) {
														self._onMouseEntersLI($(event.target).parent());
												},
												function (event) {
														self._onMouseExitsLI($(event.target).parent());
												}).end();
						};

				var self = this;
				$.each(categories, function(index, cat) {
						var cat_li = self.mkli(cat, parent, 'category');

						if ((cat.categories.length + cat.items.length) == 0) {
								cat_li.addClass('ui-treeselect-empty-category');
								return;
						}

						var cat_ul = $("

").appendTo(cat_li);
						self._addCategoriesTo(cat.categories, cat_ul);

						$.each(cat.items, function(index, item){
								self.mkli(item, cat_ul, 'item').
										children('a');
						});
				});
		},

		_onMouseEntersLI: function(li) {
				var anchor = li.children('a');

				anchor.data('on_mouse_enter_classes', anchor[0].className);
				anchor.
						addClass("ui-state-hover").
						removeClass("ui-state-default").
						removeClass("ui-state-highlight").
						removeClass("ui-state-active");

				if (li.parents('.ui-treeselect-selected-items').length == 0) return;

				var hint =
						$('
').
						hide().
						appendTo(li);

				hint.delay(1000).fadeIn('fast');

				var sourceLI = this._findConnectedIn(li, this.itemsTree);

				this._getAnchorTreeFor(sourceLI).
						slice(0, -1).
						each(function(index, element){
								hint = $("
"+$(element).text()+"
").
										appendTo($("

")).
										appendTo(hint);
						});
		},

		_onMouseExitsLI: function(li) {
				var anchor = 	li.children('a');

				anchor.
						addClass(anchor.data('on_mouse_enter_classes')).
						removeData('on_mouse_enter_classes').
						removeClass("ui-state-hover");

				this.selectedItems.find('.hint').remove();
		},

		_createDataTree: function(){
				var self = this;
				$.each(this.options.datas, function(index, cat) {
						$("
"+cat.label+"
").
								appendTo(self.itemsTree);

						var ul = $("

").
								appendTo(self.itemsTree).
								append("

").
								children()[0];

						self._addCategoriesTo(cat.categories, ul);
				});
		},

		_initAccordion: function(){
				this.itemsTree.accordion();
		},

		_initSortable: function(){
				var self=this;
				this.selectedItems.
						addClass("sortable").
						sortable({
								cursor:'crosshair',
								opacity: 0.8,
								start: function(event, ui) {$(this).find('.hint').remove();}
						});

				this._adaptSelectedItemSize();
		},

		_adaptSelectedItemSize: function(){
				var inner = this.selectedItems.closest('.ui-treeselect-selected-items-inner');
				var outer = inner.parent();
				inner.height(this.itemsTree.height() - (outer.height() - inner.height()));
				inner.css('min-height', inner.height() + 'px');
		},

		_initSelection: function(){
				var self=this;

				this.itemsTree.find('li').each(
						function(index, li){
								$(li).data('sid', index);});

				this.itemsTree.change(
						function(event){
								self._onSelectionChange($(event.target).parent());
								event.stopPropagation();});

				this.itemsTree.find('li>ul').css("display","none");
				this.itemsTree.click(
						function(event){
								var $target = $(event.target);
								if ($target.is("a>*")) $target = $target.parent();
								if ($target.is("a")) {
										event.stopPropagation();
										event.preventDefault();
										$target.siblings('ul').find('ul').hide();
										$target.siblings('ul').toggle('fast', function(){
												self._turnHighlightOff();
										});}})
		},

		_findConnectedIn: function(li, items) {
				var sid = li.data('sid');
			  return items.find('li').filter(function(index) {
					return $(this).data('sid') == sid;
				});
		},

		_deselect: function(li) {
				this._findConnectedIn(li, this.selectedItems).
						hide('fast', function(){
								$(this).remove()});

				li.children('input').removeAttr('checked');
				li.find("li input").removeAttr('disabled');
				li.children('a').removeClass('ui-state-active');
		},

		_setInactive: function(li) {
				li.children('a').removeClass('ui-state-active');

				parent = li.parent().parent();
				if (parent.length == 0) return;

				if (parent.find('li>input:checked').length==0) {
						this._setInactive(parent);
				}
		},

		_select: function(li) {
				var self = this;

				li.children('input').attr('checked', 'checked');

				var selectedLI = $("
"+
															"" +
															 $(li).data("label") +
														 "
").
						appendTo(self.selectedItems).
						data(li.data()).
						children('a').
						addClass('ui-state-default').
						addClass(li[0].className).
						hover(
								function (event) {
										self._onMouseEntersLI($(event.target).parent());
								},
								function (event) {
										self._onMouseExitsLI($(event.target).parent());
								}
						).end().
						click(
								function(event){
										event.preventDefault();
										if ($(event.target).is('a'))
												self._highlightSelected($(event.target).parent());
								});

				$("
").
						appendTo(selectedLI).
						click(function(event){
								self._deselect(
										self._findConnectedIn($(event.target).parent(),
																					self.itemsTree));
						});

				li.parents('li').andSelf().children('a').addClass('ui-state-active');

				this._disableChildren(li);
		},

		_disableChildren: function(li) {
				var self = this;
				li.find("li>input").each(
						function(index, checkbox) {
								self._deselect($(checkbox).parent());
								$(checkbox).
										attr('disabled', true).
										removeAttr('checked'); });
		},

		_onSelectionChange: function(li) {
				this._turnHighlightOff();
				if (li.children('input').is(':checked')) {
						this._select(li);
				}	else {
						this._deselect(li);
						this._setInactive(li);
				}

				this.selectedItems.sortable('refresh');
		},

		_turnHighlightOff: function() {
				this.container.find('.ui-state-highlight').
						removeClass("ui-state-highlight").
						filter('li a, h3').
						addClass("ui-state-default");
		},

		_hideAll: function() {
				this._turnHighlightOff();
				this.itemsTree.find('ul ul:visible').hide();
		},

		_getAnchorTreeFor: function(li) {
				var parents = li.parentsUntil('.ui-treeselect-items-tree, .ui-treeselect-selected-items');
				var litree = parents.andSelf().children('a');
				return litree.add(parents.last().prev());
		},

		_highlightItems: function(lis) {
				this._hideAll();
				lis.parents("ul").show();

				var self = this;
				lis.each(function(index, li) {
						self._getAnchorTreeFor($(li)).
								addClass("ui-state-highlight").
								removeClass("ui-state-default");
				});
		},

		_highlightSelected: function(li) {
				var itemToHighlight = this._findConnectedIn(li, this.itemsTree);

				this._highlightItems(itemToHighlight.add(li));

				itemToHighlight.
						parents(".ui-accordion-content").prev().click();
		},

		_onSearchInputChange: function(searchText) {
				if (searchText=="") {
						this._hideAll();
						return;
				}

				var re = new RegExp(searchText, 'i');
				var matches = this.itemsTree.find('li, h3').filter(function() {
						return re.test($(this).text());
				});
				this._highlightItems(matches);
		},

		_selectByIdAndType: function(ids, type) {
				var self = this;
				jQuery.each(ids, function(index, id) {
					self.itemsTree.find('li').each(function(index, li) {
						var listitem = $(li);
						if ((listitem.data('elid') == id) && (listitem.data('type') == type))
							self._select($(li));
					});
				});
		},

		_getSelectedDataByType: function(type) {
				var datas = [];
				this.selectedItems.find('li').each(function(index,li){
					if ($(li).data('type') == type) {
						datas.push({"id": $(li).data('elid'),
												"label": $(li).data('label')});
					}
				});
				return datas;
		},

		selectItems: function(ids) {
				this._selectByIdAndType(ids, 'item');
		},

		selectCategories: function(ids) {
				this._selectByIdAndType(ids, 'category');
		},

		readSelection: function(callback) {
				callback(
						this._getSelectedDataByType('item'),
						this._getSelectedDataByType('category'));
		},

		toggleVisibility: function(visible) {
				if (visible) {
						var self = this;
						this.element.show('fast',
															function() {
																	self.itemsTree.children('div').height(200);
																	self._adaptSelectedItemSize();});
				} else {
						this.element.hide('fast');
				}
		}
})})(jQuery);<|endoftext|>