<commit_before>function insertAvaForm()
{
    $(".avaform-wrapper").append("
Request a Free AvaTax Sandbox Account<form>
First Name / Given Name<input type='text' class='form-control' id='firstName' placeholder=''>

Last Name / Family Name<input type='text' class='form-control' id='lastName' placeholder=''>

Email Address<input type='email' class='form-control' id='email' placeholder='user@example.org'>

Company<input type='text' class='form-control' id='company' placeholder='Company Name'>

Phone<input type='tel' class='form-control' id='phone' aria-describedby='emailHelp' placeholder='Phone Number'>
<button type='button' class='btn btn-primary' onclick='return submitShort();'>Submit</button></form>

");
}

function submitShort()
{
    return submitForm($('#firstName').val(), $('#lastName').val(), $('#email').val(), $('#company').val(), $('#phone').val(), $('#ava-form-info'), $('#ava-form-alert'));
}

function submitForm(fn, ln, e, c, p, outputElement, alertElement)
{
    alertElement.hide();
    var payload = {
        firstName: fn,
        lastName: ln,
        email: e,
        company: c,
        phone: p
    };
    $.ajax({
        url: 'https://sandbox-rest.avatax.com/api/v2/accounts/freetrials/request',
        data: JSON.stringify(payload),
        contentType: 'application/json',
        error: function(err) {
            var avataxerror = $.parseJSON(err.responseText);
            outputElement.html(avataxerror.error.message);
            alertElement.attr('class', 'alert alert-warning fade in');
            alertElement.show();
        },
        dataType: 'json',
        success: function(data) {
            outputElement.html('Success!  Your account credentials have been sent to ' + e + '.');
            alertElement.attr('class', 'alert alert-success fade in');
            alertElement.show();
        },
        type: 'POST'
    });
    return false;
}

// Populate forms on ready
$(
    function()
    {
        insertAvaForm();
    }
);<commit_msg>Update new-ava-form.js<commit_after>function insertAvaForm()
{
    $(".avaform-wrapper").append("
Request a Free AvaTax Sandbox Account<form>
First Name / Given Name<input type='text' class='form-control' id='firstName' placeholder=''>

Last Name / Family Name<input type='text' class='form-control' id='lastName' placeholder=''>

Email Address<input type='email' class='form-control' id='email' placeholder='user@example.org'>

Company<input type='text' class='form-control' id='company' placeholder='Company Name'>

Phone<input type='tel' class='form-control' id='phone' aria-describedby='emailHelp' placeholder='Phone Number'>
<button type='button' class='btn btn-primary' onclick='return submitShort();'>Submit</button>By clicking “Submit,” you agree to Avalara’s terms and conditions.</form>

");
}

function submitShort()
{
    return submitForm($('#firstName').val(), $('#lastName').val(), $('#email').val(), $('#company').val(), $('#phone').val(), $('#ava-form-info'), $('#ava-form-alert'));
}

function submitForm(fn, ln, e, c, p, outputElement, alertElement)
{
    alertElement.hide();
    var payload = {
        firstName: fn,
        lastName: ln,
        email: e,
        company: c,
        phone: p
    };
    $.ajax({
        url: 'https://sandbox-rest.avatax.com/api/v2/accounts/freetrials/request',
        data: JSON.stringify(payload),
        contentType: 'application/json',
        error: function(err) {
            var avataxerror = $.parseJSON(err.responseText);
            outputElement.html(avataxerror.error.message);
            alertElement.attr('class', 'alert alert-warning fade in');
            alertElement.show();
        },
        dataType: 'json',
        success: function(data) {
            outputElement.html('Success!  Your account credentials have been sent to ' + e + '.');
            alertElement.attr('class', 'alert alert-success fade in');
            alertElement.show();
        },
        type: 'POST'
    });
    return false;
}

// Populate forms on ready
$(
    function()
    {
        insertAvaForm();
    }
);
<|endoftext|>


<commit_before>import {
  relToAbsChromPos,
  scalesCenterAndK
} from './utils';

import {
  MOUSE_TOOL_MOVE,
  MOUSE_TOOL_SELECT
} from './configs';

export const api = function api(context) {
  const self = context;

  return {
    activateTool(tool) {
      switch (tool) {
        case 'select':
          self.setMouseTool(MOUSE_TOOL_SELECT);
          break;

        default:
          self.setMouseTool(MOUSE_TOOL_MOVE);
          break;
      }
    },

    goTo (
      viewUid,
      chrom1,
      start1,
      end1,
      chrom2,
      start2,
      end2,
      animate=false,
      animateTime=3000
    ) {
      // Set chromInfo if not available
      if (!self.chromInfo) {
        self.setChromInfo(
          self.state.views[viewUid].chromInfoPath,
          () => {
            self.api().goTo(
              viewUid,
              chrom1,
              start1,
              end1,
              chrom2,
              start2,
              end2,
              animate,
              animateTime
            );
          }
        );
        return;
      }

      const [start1Abs, end1Abs] = relToAbsChromPos(
        chrom1, start1, end1, self.chromInfo
      );

      const [start2Abs, end2Abs] = relToAbsChromPos(
        chrom2, start2, end2, self.chromInfo
      );

      let [centerX, centerY, k] = scalesCenterAndK(
        self.xScales[viewUid].copy().domain([start1Abs, end1Abs]),
        self.yScales[viewUid].copy().domain([start2Abs, end2Abs])
      );

      self.setCenters[viewUid](
        centerX, centerY, k, false, animate, animateTime
      );
    },

    off(event, listenerId, viewId) {
      switch (event) {
        case 'location':
          self.offLocationChange(viewId, listenerId);
          break;

        case 'rangeSelection':
          self.offRangeSelection(listenerId);
          break;

        case 'view':
          self.offViewChange(listenerId);
          break;

        default:
          // nothing
          break;
      }
    },

    on(event, callback, viewId, callbackId) {
      switch (event) {
        case 'location':
          self.onLocationChange(viewId, callback, callbackId);
          break;

        case 'rangeSelection':
          return self.onRangeSelection(callback);

        case 'view':
          return self.onViewChange(callback);

        default:
          // nothing
          break;
      }
    },

    refresh(force = false) {
      if (self.props.options.bounded) {
        self.fitPixiToParentContainer();
      }

      self.updateAfterResize();
      self.render();
      self.animate();

      if (force) {
        self.forceRefreshView();
      }
    }
  };
}

export default api;
<commit_msg>Add `get()` for immediate Promise-based retrieval of public props. Rename `view` event to `viewConfig`.<commit_after>import {
  relToAbsChromPos,
  scalesCenterAndK
} from './utils';

import {
  MOUSE_TOOL_MOVE,
  MOUSE_TOOL_SELECT
} from './configs';

export const api = function api(context) {
  const self = context;

  return {
    activateTool(tool) {
      switch (tool) {
        case 'select':
          self.setMouseTool(MOUSE_TOOL_SELECT);
          break;

        default:
          self.setMouseTool(MOUSE_TOOL_MOVE);
          break;
      }
    },

  /**
   * Get a property of HiGlass.
   *
   * @description
   * Returns the current value for any of the available listeners, e.g.,
   * `get(rangeSelection)` will return the current range selection without
   * requiring that a range selection event is fired.
   *
   * @param {string} prop - Name of the property.
   * @param {string} viewId - UUID of the view `prop` relates to.
   * @return {object} Promise resolving to the value.
   */
    get(prop, viewId) {
      switch (prop) {
        case 'location':
          if(typeof viewId === 'undefined') {
            return Promise.reject(
              'Please provide the view UUID sweetheart 😙'
            );
          }
          return self.getGenomeLocation(viewId);

        case 'rangeSelection':
          return Promise.resolve(self.rangeSelection);

        case 'viewConfig':
          return Promise.resolve(self.getViewsAsString());

        default:
          return Promise.reject(`Propert "${prop}" unknown`);
      }
    },

    goTo(
      viewUid,
      chrom1,
      start1,
      end1,
      chrom2,
      start2,
      end2,
      animate=false,
      animateTime=3000
    ) {
      // Set chromInfo if not available
      if (!self.chromInfo) {
        self.setChromInfo(
          self.state.views[viewUid].chromInfoPath,
          () => {
            self.api().goTo(
              viewUid,
              chrom1,
              start1,
              end1,
              chrom2,
              start2,
              end2,
              animate,
              animateTime
            );
          }
        );
        return;
      }

      const [start1Abs, end1Abs] = relToAbsChromPos(
        chrom1, start1, end1, self.chromInfo
      );

      const [start2Abs, end2Abs] = relToAbsChromPos(
        chrom2, start2, end2, self.chromInfo
      );

      let [centerX, centerY, k] = scalesCenterAndK(
        self.xScales[viewUid].copy().domain([start1Abs, end1Abs]),
        self.yScales[viewUid].copy().domain([start2Abs, end2Abs])
      );

      self.setCenters[viewUid](
        centerX, centerY, k, false, animate, animateTime
      );
    },

    off(event, listenerId, viewId) {
      switch (event) {
        case 'location':
          self.offLocationChange(viewId, listenerId);
          break;

        case 'rangeSelection':
          self.offRangeSelection(listenerId);
          break;

        case 'viewConfig':
          self.offViewChange(listenerId);
          break;

        default:
          // nothing
          break;
      }
    },

    on(event, callback, viewId, callbackId) {
      switch (event) {
        case 'location':
          self.onLocationChange(viewId, callback, callbackId);
          break;

        case 'rangeSelection':
          return self.onRangeSelection(callback);

        case 'viewConfig':
          return self.onViewChange(callback);

        default:
          // nothing
          break;
      }
    },

    refresh(force = false) {
      if (self.props.options.bounded) {
        self.fitPixiToParentContainer();
      }

      self.updateAfterResize();
      self.render();
      self.animate();

      if (force) {
        self.forceRefreshView();
      }
    }
  };
}

export default api;
<|endoftext|>


<commit_before>define(['settings'], function(settings)
{
	'use strict';
	var userData_ = {};
	var characters_ = {};

	// custom variables

	var meanings_ = {};
	var vocabulary_ = {};

	var meaningsList = "";
	var characterList = "";
	var vocabularyList = "";

	var resultsTest = "";
	var resultsTest2 = "";
	var resultsTest3 = "";

	// end custom variables

	return {
		load: function(onComplete) {
			var key = settings.api_key;
			if(document.getElementById('vocabOption').checked)
			{
				var url = 'https://www.wanikani.com/api/user/' + key + '/vocabulary?callback=define';
			}
			else if(document.getElementById('radicalOption').checked)
			{
				var url = 'https://www.wanikani.com/api/user/' + key + '/radicals?callback=define';
			}
			else
			{
				var url = 'https://www.wanikani.com/api/user/' + key + '/kanji?callback=define';
			}

			require([url], function(data) {
				if (data.error !== undefined) {
					var messageElem = document.getElementById('message');
					messageElem.innerHTML = "API Error: " + data.error.message;
					return;
				}
				userData_ = data.user_information;
				if(document.getElementById('kanjiOption').checked)
				{
					resultsTest = "";
					data.requested_information.forEach(function (character)
					{
						characters_[character.character] = character;
						characterList += character.character + " ";
						if(character.user_specific == null)
						{
							resultsTest += '' + character.character + ' ';
							//console.log("SRS unseen");
						}
						else
						{
							resultsTest += '' + character.character + ' ';
							//console.log("SRS " + character.user_specific.srs);
						}
					});
					//console.log(characterList);

					data.requested_information.forEach(function (meaning)
					{
						meanings_[meaning.meaning] = meaning;
						meaningsList += meaning.meaning + " ";
					});
				}
				else if(document.getElementById('radicalOption').checked)
				{
					resultsTest2 = "";
					data.requested_information.forEach(function (character)
					{
						characters_[character.character] = character;
						characterList += character.character + " ";
						if(character.character == null)
						{
							if(character.user_specific == null)
							{
								resultsTest2 += '' + '';
								//console.log("SRS unseen");
							}
							else
							{
								resultsTest2 += '' + '';
								//console.log("SRS " + character.user_specific.srs);
							}
						}
						else
						{
							if(character.user_specific == null)
							{
								resultsTest2 += '' + character.character + ' ';
								//console.log("SRS unseen");
							}
							else
							{
								resultsTest2 += '' + character.character + ' ';
								//console.log("SRS " + character.user_specific.srs);
							}
						}
					});
				}
				else
				{
					resultsTest3 = "";
					data.requested_information.general.forEach(function (character)
					{
						//vocabulary_[character.character] = character;
						//vocabularyList += character.character + " ";
						if(character.user_specific == null)
						{
							resultsTest3 += '' + character.character + ' ';
							//console.log("SRS unseen");
						}
						else
						{
							resultsTest3 += '' + character.character + ' ';
							//console.log("SRS " + character.user_specific.srs);
						}
					});
					//console.log(vocabularyList);

					data.requested_information.general.forEach(function (meaning)
					{
						meanings_[meaning.meaning] = meaning;
						meaningsList += meaning.meaning + " | ";
					});

				}
				//console.log(meaningsList);
				//console.log("Complete Dump " + JSON.stringify(data.requested_information));
				/*
				document.getElementById('meaningResults').value = meaningsList;
				document.getElementById('characterResults').value = characterList;
				document.getElementById('vocabResults').value = vocabularyList;
				*/
				document.getElementById('outputTestResults').innerHTML = resultsTest;
				document.getElementById('outputTestResults2').innerHTML = resultsTest2;
				document.getElementById('outputTestResults3').innerHTML = resultsTest3;
				onComplete();
			});
},
get userData() { return userData_; },
get characters() { return characters_; }
};
});
<commit_msg>update radical images<commit_after>define(['settings'], function(settings)
{
	'use strict';
	var userData_ = {};
	var characters_ = {};

	// custom variables

	var meanings_ = {};
	var vocabulary_ = {};

	var meaningsList = "";
	var characterList = "";
	var vocabularyList = "";

	var resultsTest = "";
	var resultsTest2 = "";
	var resultsTest3 = "";

	// end custom variables

	return {
		load: function(onComplete) {
			var key = settings.api_key;
			if(document.getElementById('vocabOption').checked)
			{
				var url = 'https://www.wanikani.com/api/user/' + key + '/vocabulary?callback=define';
			}
			else if(document.getElementById('radicalOption').checked)
			{
				var url = 'https://www.wanikani.com/api/user/' + key + '/radicals?callback=define';
			}
			else
			{
				var url = 'https://www.wanikani.com/api/user/' + key + '/kanji?callback=define';
			}

			require([url], function(data) {
				if (data.error !== undefined) {
					var messageElem = document.getElementById('message');
					messageElem.innerHTML = "API Error: " + data.error.message;
					return;
				}
				userData_ = data.user_information;
				if(document.getElementById('kanjiOption').checked)
				{
					resultsTest = "";
					data.requested_information.forEach(function (character)
					{
						characters_[character.character] = character;
						characterList += character.character + " ";
						if(character.user_specific == null)
						{
							resultsTest += '' + character.character + ' ';
							//console.log("SRS unseen");
						}
						else
						{
							resultsTest += '' + character.character + ' ';
							//console.log("SRS " + character.user_specific.srs);
						}
					});
					//console.log(characterList);

					data.requested_information.forEach(function (meaning)
					{
						meanings_[meaning.meaning] = meaning;
						meaningsList += meaning.meaning + " ";
					});
				}
				else if(document.getElementById('radicalOption').checked)
				{
					resultsTest2 = "";
					data.requested_information.forEach(function (character)
					{
						characters_[character.character] = character;
						characterList += character.character + " ";
						if(character.character == null)
						{
							if(character.user_specific == null)
							{
								resultsTest2 += '' + '';
								//console.log("SRS unseen");
							}
							else
							{
								resultsTest2 += '' + '';
								//console.log("SRS " + character.user_specific.srs);
							}
						}
						else
						{
							if(character.user_specific == null)
							{
								resultsTest2 += '' + character.character + ' ';
								//console.log("SRS unseen");
							}
							else
							{
								resultsTest2 += '' + character.character + ' ';
								//console.log("SRS " + character.user_specific.srs);
							}
						}
					});
				}
				else
				{
					resultsTest3 = "";
					data.requested_information.general.forEach(function (character)
					{
						//vocabulary_[character.character] = character;
						//vocabularyList += character.character + " ";
						if(character.user_specific == null)
						{
							resultsTest3 += '' + character.character + ' ';
							//console.log("SRS unseen");
						}
						else
						{
							resultsTest3 += '' + character.character + ' ';
							//console.log("SRS " + character.user_specific.srs);
						}
					});
					//console.log(vocabularyList);

					data.requested_information.general.forEach(function (meaning)
					{
						meanings_[meaning.meaning] = meaning;
						meaningsList += meaning.meaning + " | ";
					});

				}
				//console.log(meaningsList);
				//console.log("Complete Dump " + JSON.stringify(data.requested_information));
				/*
				document.getElementById('meaningResults').value = meaningsList;
				document.getElementById('characterResults').value = characterList;
				document.getElementById('vocabResults').value = vocabularyList;
				*/
				document.getElementById('outputTestResults').innerHTML = resultsTest;
				document.getElementById('outputTestResults2').innerHTML = resultsTest2;
				document.getElementById('outputTestResults3').innerHTML = resultsTest3;
				onComplete();
			});
},
get userData() { return userData_; },
get characters() { return characters_; }
};
});
<|endoftext|>


<commit_before>YUI.add('photosnearme', function (Y) {

Y.PhotosNearMe = Y.Base.create('photosNearMe', Y.App, [], {

    titleTemplate : Y.Handlebars.compile(Y.one('#title-template').getContent()),
    headerTemplate: Y.Handlebars.compile(Y.one('#header-template').getContent()),

    views: {
        grid: {
            type    : Y.GridView,
            preserve: true
        },

        lightbox: {
            type  : Y.LightboxView,
            parent: 'grid'
        }
    },

    initializer: function () {
        this.after('placeChange', this.render);
        this.after('placeChange', this.loadPhotos);

        this.on('gridView:more', this.loadMorePhotos);

        // Do initial dispatch.
        if (Y.config.win.navigator.standalone) {
            // iOS saved to home screen,
            // always route to / so geolocation lookup is preformed.
            this.handleLocate();
        } else {
            this.dispatch();
        }
    },

    render: function () {
        Y.PhotosNearMe.superclass.render.apply(this, arguments);

        var place     = this.get('place'),
            placeText = place.toString(),
            container = this.get('container'),
            doc       = Y.config.doc,
            content;

        // Update the title of the browser window.
        doc && (doc.title = this.titleTemplate({place: placeText}));

        content = this.headerTemplate({
            place: place.isNew() ? null : {
                id  : place.get('id'),
                text: placeText
            }
        });

        container.removeClass('loading').one('#header').setContent(content);
        Y.later(1, container, 'addClass', 'located');

        return this;
    },

    handleLocate: function () {
        var self = this;

        Y.Geo.getCurrentPosition(function (res) {
            if (!res.success) {
                // TODO: Show problem View: unable to locate you.
                return;
            }

            var place = new Y.Place(res.coords);
            place.load(function () {
                self.set('place', place);
                self.replace('/place/' + place.get('id') + '/');
            });
        });
    },

    handlePlace: function (req) {
        var placeId = req.params.id,
            place   = this.get('place'),
            photos  = this.get('photos'),
            self    = this;

        if (place.get('id') !== placeId) {
            place = new Y.Place({id: placeId});
            place.load(function () {
                self.set('place', place);
            });
        }

        this.showView('grid', {modelList: photos}, function (gridView) {
            gridView.reset();
        });
    },

    handlePhoto: function (req, res, next) {
        var params = req.params,
            photo  = this.get('photos').getById(params.id),
            self   = this;

        if (photo) {
            req.photo = photo;
            photo.loadImg(function () {
                next();
            });
        } else {
            photo = req.photo = new Y.Photo(params);
            photo.load(function () {
                if (self.get('place').isNew()) {
                    self.set('place', photo.get('place'));
                }

                photo.loadImg(function () {
                    next();
                });
            });
        }
    },

    showLightbox: function (req) {
        var photo      = req.photo,
            photos     = this.get('photos'),
            place      = this.get('place'),
            activeView = this.get('activeView');

        if (activeView instanceof this.views.lightbox.type) {
            activeView.set('model', photo);
        } else {
            this.showView('lightbox', {
                model    : photo,
                modelList: photos,
                place    : place
            });
        }
    },

    loadPhotos: function () {
        this.get('photos').load({place: this.get('place')});
    },

    loadMorePhotos: function () {
        var place     = this.get('place'),
            photos    = this.get('photos'),
            newPhotos = new Y.Photos;

        newPhotos.load({
            place: place,
            start: photos.size()
        }, function () {
            var allPhotos = photos.toArray().concat(newPhotos.toArray());
            photos.reset(allPhotos);
            // clean up temp ModelList
            newPhotos.destroy();
        });
    }

}, {

    ATTRS: {
        place : {value: new Y.Place},
        photos: {value: new Y.Photos},

        routes: {
            value: [
                {path: '/', callback: 'handleLocate'},

                {path: '/place/:id/', callback: 'handlePlace'},

                {path: '/photo/:id/', callback: 'handlePhoto'},
                {path: '/photo/:id/', callback: 'showLightbox'}
            ]
        }
    }

});

}, '0.3.2', {
    requires: [ 'app-base'
              , 'gallery-geo'
              , 'handlebars'
              , 'place'
              , 'photos'
              , 'grid-view'
              , 'lightbox-view'
              ]
});
<commit_msg>Make sure the Place is loaded before adding the `located` CSS class.<commit_after>YUI.add('photosnearme', function (Y) {

Y.PhotosNearMe = Y.Base.create('photosNearMe', Y.App, [], {

    titleTemplate : Y.Handlebars.compile(Y.one('#title-template').getContent()),
    headerTemplate: Y.Handlebars.compile(Y.one('#header-template').getContent()),

    views: {
        grid: {
            type    : Y.GridView,
            preserve: true
        },

        lightbox: {
            type  : Y.LightboxView,
            parent: 'grid'
        }
    },

    initializer: function () {
        this.after('placeChange', this.render);
        this.after('placeChange', this.loadPhotos);
        this.on('gridView:more', this.loadMorePhotos);

        // Do initial dispatch.
        if (Y.config.win.navigator.standalone) {
            // iOS saved to home screen,
            // always route to / so geolocation lookup is preformed.
            this.handleLocate();
        } else {
            this.dispatch();
        }
    },

    render: function () {
        Y.PhotosNearMe.superclass.render.apply(this, arguments);

        var place     = this.get('place'),
            placeText = place.toString(),
            container = this.get('container'),
            doc       = Y.config.doc,
            content;

        // Update the title of the browser window.
        doc && (doc.title = this.titleTemplate({place: placeText}));

        content = this.headerTemplate({
            place: place.isNew() ? null : {
                id  : place.get('id'),
                text: placeText
            }
        });

        container.removeClass('loading').one('#header').setContent(content);
        // Delay adding `located` class so the CSS transitions run.
        !place.isNew() && Y.later(1, container, 'addClass', 'located');

        return this;
    },

    handleLocate: function () {
        var self = this;

        Y.Geo.getCurrentPosition(function (res) {
            if (!res.success) {
                // TODO: Show problem View: unable to locate you.
                return;
            }

            var place = new Y.Place(res.coords);
            place.load(function () {
                self.set('place', place);
                self.replace('/place/' + place.get('id') + '/');
            });
        });
    },

    handlePlace: function (req) {
        var placeId = req.params.id,
            place   = this.get('place'),
            photos  = this.get('photos'),
            self    = this;

        if (place.get('id') !== placeId) {
            place = new Y.Place({id: placeId});
            place.load(function () {
                self.set('place', place);
            });
        }

        this.showView('grid', {modelList: photos}, function (gridView) {
            gridView.reset();
        });
    },

    handlePhoto: function (req, res, next) {
        var params = req.params,
            photo  = this.get('photos').getById(params.id),
            self   = this;

        if (photo) {
            req.photo = photo;
            photo.loadImg(function () {
                next();
            });
        } else {
            photo = req.photo = new Y.Photo(params);
            photo.load(function () {
                if (self.get('place').isNew()) {
                    self.set('place', photo.get('place'));
                }

                photo.loadImg(function () {
                    next();
                });
            });
        }
    },

    showLightbox: function (req) {
        var photo      = req.photo,
            photos     = this.get('photos'),
            place      = this.get('place'),
            activeView = this.get('activeView');

        if (activeView instanceof this.views.lightbox.type) {
            activeView.set('model', photo);
        } else {
            this.showView('lightbox', {
                model    : photo,
                modelList: photos,
                place    : place
            });
        }
    },

    loadPhotos: function () {
        this.get('photos').load({place: this.get('place')});
    },

    loadMorePhotos: function () {
        var place     = this.get('place'),
            photos    = this.get('photos'),
            newPhotos = new Y.Photos;

        newPhotos.load({
            place: place,
            start: photos.size()
        }, function () {
            var allPhotos = photos.toArray().concat(newPhotos.toArray());
            photos.reset(allPhotos);
            // clean up temp ModelList
            newPhotos.destroy();
        });
    }

}, {

    ATTRS: {
        place : {value: new Y.Place},
        photos: {value: new Y.Photos},

        routes: {
            value: [
                {path: '/', callback: 'handleLocate'},

                {path: '/place/:id/', callback: 'handlePlace'},

                {path: '/photo/:id/', callback: 'handlePhoto'},
                {path: '/photo/:id/', callback: 'showLightbox'}
            ]
        }
    }

});

}, '0.3.2', {
    requires: [ 'app-base'
              , 'gallery-geo'
              , 'handlebars'
              , 'place'
              , 'photos'
              , 'grid-view'
              , 'lightbox-view'
              ]
});
<|endoftext|>


<commit_before>(() => {
	Snakeskin.addDirective(
		'attr',

		{
			placement: 'template',
			notEmpty: true,
			text: true
		},

		function (command) {
			this.startInlineDir();
			if (this.isReady()) {
				let str = '',
					groups = this.splitAttrsGroup(command);

				for (let i = -1; ++i < groups.length;) {
					let el = groups[i];

					str += this.returnAttrDecl(
						el.attr,
						el.group,
						el.separator
					);
				}

				this.append(str);
			}
		}
	);

	var escapeEqRgxp = /===|==|([\\]+)=/g,
		escapeOrRgxp = /\|\||([\\]+)\|/g;

	var unEscapeEqRgxp = /__SNAKESKIN_EQ__(\d+)_(\d+)_/g,
		unEscapeOrRgxp = /__SNAKESKIN_OR__(\d+)_(\d+)_/g;

	function escapeEq(sstr, $1) {
		if ($1 && $1.length % 2 === 0) {
			return sstr;
		}

		return `__SNAKESKIN_EQ__${sstr.split('=').length}_${$1.length}_`;
	}

	function escapeOr(sstr, $1) {
		if ($1 && $1.length % 2 === 0) {
			return sstr;
		}

		return `__SNAKESKIN_OR__${sstr.split('|').length}_${$1.length}_`;
	}

	function unEscapeEq(sstr, $1, $2) {
		return new Array(Number($2)).join('\\') + new Array(Number($1)).join('=');
	}

	function unEscapeOr(sstr, $1, $2) {
		return new Array(Number($2)).join('\\') + new Array(Number($1)).join('|');
	}

	/**
	 * Вернуть строку декларации XML атрибутов
	 *
	 * @param {string} str - исходная строка
	 * @param {?string=} [opt_group] - название группы
	 * @param {?string=} [opt_separator='-'] - разделитель группы
	 * @param {?boolean=} [opt_classLink=false] - если true, то значения для атрибута class
	 *     будут сохраняться во временную переменную
	 *
	 * @return {string}
	 */
	DirObj.prototype.returnAttrDecl = function (str, opt_group, opt_separator, opt_classLink) {
		var rAttr = this.attr,
			rEscape = this.attrEscape;

		this.attr = true;
		this.attrEscape = true;

		opt_group = opt_group || '';
		opt_separator = opt_separator || '-';

		str = str
			.replace(escapeHTMLRgxp, escapeHTML)
			.replace(escapeOrRgxp, escapeOr);

		var parts = str.split('|'),
			res = '',
			ref = this.bemRef;

		var s = ADV_LEFT_BLOCK + LEFT_BLOCK,
			e = RIGHT_BLOCK;

		for (let i = -1; ++i < parts.length;) {
			parts[i] = parts[i]
				.replace(unEscapeOrRgxp, unEscapeOr)
				.replace(escapeEqRgxp, escapeEq);

			let arg = parts[i].split('='),
				empty = arg.length !== 2;

			if (empty) {
				arg[1] = this.doctype === 'xml' ?
					arg[0] : '';
			}

			arg[0] = arg[0].trim().replace(unEscapeEqRgxp, unEscapeEq);
			arg[1] = arg[1].trim().replace(unEscapeEqRgxp, unEscapeEq);

			res += /* cbws */`
				var __ATTR_STR__ = \'\',
					__ATTR_J__ = 0;
			`;

			if (opt_group) {
				arg[0] = opt_group + opt_separator + arg[0];

			} else {
				arg[0] = arg[0].charAt(0) === '-' ?
					`data-${arg[0].slice(1)}` : arg[0];
			}

			arg[0] = `'${this.pasteTplVarBlocks(arg[0])}'`;
			let vals = splitBySpace(arg[1]);

			for (let j = -1; ++j < vals.length;) {
				let val = vals[j].trim();

				if (parentLinkRgxp.test(val) && ref) {
					val = `${s}'${ref}'${FILTER}bem '${val.substring('&'.length)}'${e}`;
					val = this.pasteDangerBlocks(this.replaceTplVars(val));
				}

				val = `'${this.pasteTplVarBlocks(val)}'`;

				res += /* cbws */`
					if ((${val}) != null && (${val}) !== '') {
						__ATTR_STR__ += __ATTR_J__ ? ' ' + ${val} : ${val};
						__ATTR_J__++;
					}
				`;
			}

			res += `if ((${arg[0]}) != null && (${arg[0]}) != '' && (__ATTR_STR__ || ${empty})) {`;
			let tmp = /* cbws */`
				if (__NODE__) {
					__NODE__.setAttribute(${arg[0]}, __ATTR_STR__);

				} else {
					${this.wrap(`' ' + ${arg[0]} + (__ATTR_STR__ ? '="' + __ATTR_STR__ + '"' : '')`)}
				}
			`;

			if (opt_classLink) {
				res += /* cbws */`
					if (__ATTR_TMP__[(${arg[0]})] != null) {
						__ATTR_TMP__[(${arg[0]})] += __ATTR_STR__;

					} else {
						${tmp}
					}
				`;

			} else {
				res += tmp;
			}

			res += '}';
		}

		this.attr = rAttr;
		this.attrEscape = rEscape;

		return res;
	};

	/**
	 * Разбить строку декларации атрибута на группы
	 *
	 * @param {string} str - исходная строка
	 * @return {!Array}
	 */
	DirObj.prototype.splitAttrsGroup = function (str) {
		var rAttr = this.attr,
			rEscape = this.attrEscape;

		this.attr = true;
		this.attrEscape = true;

		str = this.replaceTplVars(str, false, true);
		var groups = [];

		var group = '',
			attr = '',
			sep = '';

		var pOpen = 0;
		var separator = {
			'-': true,
			':': true,
			'_': true
		};

		for (let i = -1; ++i < str.length;) {
			let el = str.charAt(i),
				next = str.charAt(i + 1);

			if (!pOpen) {
				if (separator[el] && next === '(') {
					pOpen++;
					i++;
					sep = el;
					continue;
				}

				if (el === '(') {
					pOpen++;
					sep = '';
					continue;
				}
			}

			if (pOpen) {
				if (el === '(') {
					pOpen++;

				} else if (el === ')') {
					pOpen--;

					if (!pOpen) {
						groups.push({
							group: Snakeskin.Filters.html(group, true).trim(),
							separator: sep,
							attr: attr.trim()
						});

						group = '';
						attr = '';
						sep = '';

						i++;
						continue;
					}
				}
			}

			if (!pOpen) {
				group += el;

			} else {
				attr += el;
			}
		}

		if (group && !attr) {
			groups.push({
				group: null,
				separator: null,
				attr: group.trim()
			});
		}

		this.attr = rAttr;
		this.attrEscape = rEscape;

		return groups;
	};
})();
<commit_msg>Исправление ошибки<commit_after>(() => {
	Snakeskin.addDirective(
		'attr',

		{
			placement: 'template',
			notEmpty: true,
			text: true
		},

		function (command) {
			this.startInlineDir();
			if (this.isReady()) {
				let str = '',
					groups = this.splitAttrsGroup(command);

				for (let i = -1; ++i < groups.length;) {
					let el = groups[i];

					str += this.returnAttrDecl(
						el.attr,
						el.group,
						el.separator
					);
				}

				this.append(str);
			}
		}
	);

	var escapeEqRgxp = /===|==|([\\]+)=/g,
		escapeOrRgxp = /\|\||([\\]+)\|/g;

	var unEscapeEqRgxp = /__SNAKESKIN_EQ__(\d+)_(\d+)_/g,
		unEscapeOrRgxp = /__SNAKESKIN_OR__(\d+)_(\d+)_/g;

	function escapeEq(sstr, $1) {
		if ($1 && $1.length % 2 === 0) {
			return sstr;
		}

		return `__SNAKESKIN_EQ__${sstr.split('=').length}_${$1.length}_`;
	}

	function escapeOr(sstr, $1) {
		if ($1 && $1.length % 2 === 0) {
			return sstr;
		}

		return `__SNAKESKIN_OR__${sstr.split('|').length}_${$1.length}_`;
	}

	function unEscapeEq(sstr, $1, $2) {
		return new Array(Number($2)).join('\\') + new Array(Number($1)).join('=');
	}

	function unEscapeOr(sstr, $1, $2) {
		return new Array(Number($2)).join('\\') + new Array(Number($1)).join('|');
	}

	/**
	 * Вернуть строку декларации XML атрибутов
	 *
	 * @param {string} str - исходная строка
	 * @param {?string=} [opt_group] - название группы
	 * @param {?string=} [opt_separator='-'] - разделитель группы
	 * @param {?boolean=} [opt_classLink=false] - если true, то значения для атрибута class
	 *     будут сохраняться во временную переменную
	 *
	 * @return {string}
	 */
	DirObj.prototype.returnAttrDecl = function (str, opt_group, opt_separator, opt_classLink) {
		var rAttr = this.attr,
			rEscape = this.attrEscape;

		this.attr = true;
		this.attrEscape = true;

		opt_group = opt_group || '';
		opt_separator = opt_separator || '-';

		str = str
			.replace(escapeHTMLRgxp, escapeHTML)
			.replace(escapeOrRgxp, escapeOr);

		var parts = str.split('|'),
			res = '',
			ref = this.bemRef;

		var s = ADV_LEFT_BLOCK + LEFT_BLOCK,
			e = RIGHT_BLOCK;

		for (let i = -1; ++i < parts.length;) {
			parts[i] = parts[i]
				.replace(unEscapeOrRgxp, unEscapeOr)
				.replace(escapeEqRgxp, escapeEq);

			let arg = parts[i].split('='),
				empty = arg.length !== 2;

			if (empty) {
				arg[1] = this.doctype === 'xml' ?
					arg[0] : '';
			}

			arg[0] = arg[0].trim().replace(unEscapeEqRgxp, unEscapeEq);
			arg[1] = arg[1].trim().replace(unEscapeEqRgxp, unEscapeEq);

			res += /* cbws */`
				var __ATTR_STR__ = \'\',
					__ATTR_J__ = 0;
			`;

			if (opt_group) {
				arg[0] = opt_group + opt_separator + arg[0];

			} else {
				arg[0] = arg[0].charAt(0) === '-' ?
					`data-${arg[0].slice(1)}` : arg[0];
			}

			arg[0] = `'${this.pasteTplVarBlocks(arg[0])}'`;
			let vals = splitBySpace(arg[1]);

			for (let j = -1; ++j < vals.length;) {
				let val = vals[j].trim();

				if (parentLinkRgxp.test(val) && ref) {
					val = `${s}'${ref}'${FILTER}bem '${val.substring('&'.length)}'${e}`;
					val = this.pasteDangerBlocks(this.replaceTplVars(val));
				}

				val = `'${this.pasteTplVarBlocks(val)}'`;

				res += /* cbws */`
					if ((${val}) != null && (${val}) !== '') {
						__ATTR_STR__ += __ATTR_J__ ? ' ' + ${val} : ${val};
						__ATTR_J__++;
					}
				`;
			}

			res += `if ((${arg[0]}) != null && (${arg[0]}) != '') {`;
			let tmp = /* cbws */`
				if (__NODE__) {
					__NODE__.setAttribute(${arg[0]}, ${empty} ? ${arg[0]} : __ATTR_STR__ );

				} else {
					${this.wrap(`' ' + ${arg[0]} + (${empty} && !__ATTR_STR__ ? '' : '="' + __ATTR_STR__ + '"')`)}
				}
			`;

			if (opt_classLink) {
				res += /* cbws */`
					if (__ATTR_TMP__[(${arg[0]})] != null) {
						__ATTR_TMP__[(${arg[0]})] += __ATTR_STR__;

					} else {
						${tmp}
					}
				`;

			} else {
				res += tmp;
			}

			res += '}';
		}

		this.attr = rAttr;
		this.attrEscape = rEscape;

		return res;
	};

	/**
	 * Разбить строку декларации атрибута на группы
	 *
	 * @param {string} str - исходная строка
	 * @return {!Array}
	 */
	DirObj.prototype.splitAttrsGroup = function (str) {
		var rAttr = this.attr,
			rEscape = this.attrEscape;

		this.attr = true;
		this.attrEscape = true;

		str = this.replaceTplVars(str, false, true);
		var groups = [];

		var group = '',
			attr = '',
			sep = '';

		var pOpen = 0;
		var separator = {
			'-': true,
			':': true,
			'_': true
		};

		for (let i = -1; ++i < str.length;) {
			let el = str.charAt(i),
				next = str.charAt(i + 1);

			if (!pOpen) {
				if (separator[el] && next === '(') {
					pOpen++;
					i++;
					sep = el;
					continue;
				}

				if (el === '(') {
					pOpen++;
					sep = '';
					continue;
				}
			}

			if (pOpen) {
				if (el === '(') {
					pOpen++;

				} else if (el === ')') {
					pOpen--;

					if (!pOpen) {
						groups.push({
							group: Snakeskin.Filters.html(group, true).trim(),
							separator: sep,
							attr: attr.trim()
						});

						group = '';
						attr = '';
						sep = '';

						i++;
						continue;
					}
				}
			}

			if (!pOpen) {
				group += el;

			} else {
				attr += el;
			}
		}

		if (group && !attr) {
			groups.push({
				group: null,
				separator: null,
				attr: group.trim()
			});
		}

		this.attr = rAttr;
		this.attrEscape = rEscape;

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


<commit_before>define(["jquery",
        "views/signupform",
        "views/signinform",
        "views/forgotpasswordform",
        "views/resetpasswordform",
        "views/errorreport",
        "views/selectdomain"
        ],

    function($,
        SignupForm,
        SigninForm,
        ForgotPasswordForm,
        ResetPasswordForm,
        ErrorReport,
        SelectDomain){

        return {
            run : function(){
                $(document).ready(function(){
                    var signupForm = $(".signup-form"),
                        signinForm = $(".login-form"),
                        forgotPasswordForm = $(".forgotpassword-form"),
                        resetPasswordForm = $(".resetpassword-form"),
                        errorContainer = $(".error-container"),
                        domainSelector = $(".select-domain");

                    if(signupForm.length !== 0){
                        (function(){
                            var form = SignupForm.get(signupForm),
                            errorReport = ErrorReport.get(errorContainer);

                            form.on("submitting", function(){
                                errorReport.hide();
                            });

                            form.on("success", function(d){
                                window.location.href = d.url;
                            });

                            form.on("invalid", function(field,message){
                                errorReport.show(message);
                            });
                        })();
                    }

                    if(signinForm.length !== 0){
                        (function(){
                            var form = SigninForm.get(signinForm),
                            errorReport = ErrorReport.get(errorContainer);

                            form.on("submitting", function(){
                                errorReport.hide();
                            });

                            form.on("success", function(){
                                alert("logged in");
                            });

                            form.on("invalid", function(field,message){
                                errorReport.show(message);
                            });
                        })();
                    }

                    if(forgotPasswordForm.length !== 0){
                        (function(){
                            var form = ForgotPasswordForm.get(forgotPasswordForm),
                            errorReport = ErrorReport.get(errorContainer);

                            form.on("submitting", function(){
                                errorReport.hide();
                            });

                            form.on("success", function(d){
                                form.showMessage(d.message);
                            });

                            form.on("invalid", function(field,message){
                                errorReport.show(message);
                            });

                        })();
                    }

                    if(resetPasswordForm.length !== 0){
                        (function(){

                            var form = ResetPasswordForm.get(resetPasswordForm),
                                errorReport = ErrorReport.get(errorContainer);

                            form.on("submitting", function(){
                                errorReport.hide();
                            });

                            form.on("success", function(d){
                                window.location.href = d.url;
                            });

                            form.on("invalid", function(field,message){
                                errorReport.show(message);
                            });

                            form.resolveUserEmail();

                        })();
                    }

                    if(domainSelector.length !== 0){
                        var selectdomain = new SelectDomain.get(domainSelector);
                    }

                });
            }
        };

    }
);
<commit_msg>integrate wait for tenant screen<commit_after>define(["jquery",
        "views/signupform",
        "views/signinform",
        "views/forgotpasswordform",
        "views/resetpasswordform",
        "views/errorreport",
        "views/selectdomain",
        "views/ideloader"
        ],

    function($,
        SignupForm,
        SigninForm,
        ForgotPasswordForm,
        ResetPasswordForm,
        ErrorReport,
        SelectDomain,
        IDELoader){

        return {
            run : function(){
                $(document).ready(function(){
                    var signupForm = $(".signup-form"),
                        signinForm = $(".login-form"),
                        forgotPasswordForm = $(".forgotpassword-form"),
                        resetPasswordForm = $(".resetpassword-form"),
                        errorContainer = $(".error-container"),
                        domainSelector = $(".select-domain"),
                        loader = $(".loader");

                    if(signupForm.length !== 0){
                        (function(){
                            var form = SignupForm.get(signupForm),
                            errorReport = ErrorReport.get(errorContainer);

                            form.on("submitting", function(){
                                errorReport.hide();
                            });

                            form.on("success", function(d){
                                window.location.href = d.url;
                            });

                            form.on("invalid", function(field,message){
                                errorReport.show(message);
                            });
                        })();
                    }

                    if(signinForm.length !== 0){
                        (function(){
                            var form = SigninForm.get(signinForm),
                            errorReport = ErrorReport.get(errorContainer);

                            form.on("submitting", function(){
                                errorReport.hide();
                            });

                            form.on("success", function(){
                                alert("logged in");
                            });

                            form.on("invalid", function(field,message){
                                errorReport.show(message);
                            });
                        })();
                    }

                    if(forgotPasswordForm.length !== 0){
                        (function(){
                            var form = ForgotPasswordForm.get(forgotPasswordForm),
                            errorReport = ErrorReport.get(errorContainer);

                            form.on("submitting", function(){
                                errorReport.hide();
                            });

                            form.on("success", function(d){
                                form.showMessage(d.message);
                            });

                            form.on("invalid", function(field,message){
                                errorReport.show(message);
                            });

                        })();
                    }

                    if(resetPasswordForm.length !== 0){
                        (function(){

                            var form = ResetPasswordForm.get(resetPasswordForm),
                                errorReport = ErrorReport.get(errorContainer);

                            form.on("submitting", function(){
                                errorReport.hide();
                            });

                            form.on("success", function(d){
                                window.location.href = d.url;
                            });

                            form.on("invalid", function(field,message){
                                errorReport.show(message);
                            });

                            form.resolveUserEmail();

                        })();
                    }

                    if(domainSelector.length !== 0){
                        var selectdomain = new SelectDomain.get(domainSelector);
                    }

                    if(loader.length !== 0){
                        new IDELoader.IDELoader().on("ready",function(d){
                            window.location.href = d.url;
                        });
                    }

                });
            }
        };

    }
);
<|endoftext|>


<commit_before>var fs = require('fs'),
    path = require('path'),
    util = require('util'),
    events = require('events'),
    async = require('async'),
    lstat = process.platform === 'win32' ? 'stat' : 'lstat',
    lstatSync = process.platform === 'win32' ? 'statSync' : 'lstatSync';

module.exports = DirectoryReader;

function DirectoryReader(dirs, excludeDirs) {
    var self = this;

    events.EventEmitter.call(self);
    self.dirStack = [];
    self.excludeDirs = excludeDirs || [];

    process.nextTick(function () {
        try {
            if (typeof self.excludeDirs === "string" || self.excludeDirs instanceof String) {
                self.excludeDirs = [ path.resolve(self.excludeDirs) ]
            }
            for (var i=0; i < self.excludeDirs.length; ++i) {
                self.excludeDirs[i] = path.resolve(self.excludeDirs[i]);
                var stat = fs.lstatSync(self.excludeDirs[i]);
                if (! stat.isDirectory()) {
                    throw new Error("Path " + self.excludeDirs[i] + " is not a directory");
                }
            }
        }
        catch (error) {
            self.emit("done", new Error(error.message));
            return;
        }

        if (typeof dirs === "string" || dirs instanceof String) {
            dirs = [ path.resolve(dirs ||'.') ]
        }
        async.eachSeries(dirs, function(dir, dirIterator) {
            self.currentFilePath = path.resolve(dir);

            if (! self._isExcludedDir()) {
                console.log("include dir", self.currentFilePath);
                self._pushDir(dirIterator, dirIterator);
            }
            else {
                console.log("exclude dir", self.currentFilePath);
                dirIterator();
            }
        },
        function complete(error) {
            if (error) {
                self.emit("done", error);
            }
            else {
                self.next();
            }
        });
    });
}
util.inherits(DirectoryReader, events.EventEmitter);

DirectoryReader.prototype._pushDir = function(nextCB, errorCB) {
    var self = this,
        dir = self.currentFilePath;

    fs.readdir(dir, function(error, list) {
        if (error) {
            if (errorCB) {
                errorCB(error);
            }
            else {
                self.emit("done", error);
            }
        }
        else {
            self.dirStack.push({dir: dir, list: list, iterator: 0});

            if (nextCB) {
                nextCB();
            }
        }
    });
    return self;
};

DirectoryReader.prototype._cwd = function() {
    var length = this.dirStack.length;
    if (length > 0) {
        return this.dirStack[length - 1]
    }
    return null;
};

DirectoryReader.prototype._isExcludedDir = function() {
    var excludeDirs = this.excludeDirs,
        dir = this.currentFilePath;

    for (var i=0; i<excludeDirs.length;++i) {
        if (dir.indexOf(excludeDirs[i]) === 0) {
            return true;
        }
    }
    return false;
};

DirectoryReader.prototype.next = function() {
    var self = this;

    if (self._cwd() === null) {
        self.emit("done");
    }
    else {
        var file = self._cwd().list[self._cwd().iterator++];

        if (! file) {
            self.dirStack.pop();
            if (self.dirStack.length === 0) {
                self.emit("done");
            }
            else {
                self.next();
            }
        }
        else {
            self.currentFilePath = self._cwd().dir + '/' + file;
            fs[lstat](self.currentFilePath, function(err, stat) {
                if (stat && stat.isDirectory()) {
                    if (! self._isExcludedDir()) {
                        self.emit("dir", file, stat, self.currentFilePath);
                    }
                    else {
                        console.log("exclude dir", self.currentFilePath);
                        self.next();
                    }
                }
                else {
                    self.emit("file", file, stat, self.currentFilePath);
                }
            });
        }
    }
};

DirectoryReader.prototype.list = function() {
    var self = this;

    self._pushDir(function () {
        self.next();
    });
};

<commit_msg>fixing exclude dirs<commit_after>var fs = require('fs'),
    path = require('path'),
    util = require('util'),
    events = require('events'),
    async = require('async'),
    lstat = process.platform === 'win32' ? 'stat' : 'lstat',
    lstatSync = process.platform === 'win32' ? 'statSync' : 'lstatSync';

module.exports = DirectoryReader;

function DirectoryReader(dirs, excludeDirs) {
    var self = this;

    events.EventEmitter.call(self);
    self.dirStack = [];
    self.excludeDirs = excludeDirs || [];

    process.nextTick(function () {
        try {
            if (typeof self.excludeDirs === "string" || self.excludeDirs instanceof String) {
                self.excludeDirs = [ path.resolve(self.excludeDirs) ]
            }
            for (var i=0; i < self.excludeDirs.length; ++i) {
                self.excludeDirs[i] = path.resolve(self.excludeDirs[i]);
                var stat = fs.lstatSync(self.excludeDirs[i]);
                if (! stat.isDirectory()) {
                    throw new Error("Path " + self.excludeDirs[i] + " is not a directory");
                }
            }
        }
        catch (error) {
            self.emit("done", new Error(error.message));
            return;
        }

        if (typeof dirs === "string" || dirs instanceof String) {
            dirs = [ path.resolve(dirs ||'.') ]
        }
        async.eachSeries(dirs, function(dir, dirIterator) {
            self.currentFilePath = path.resolve(dir);

            if (! self._isExcludedDir()) {
                console.log("include dir", self.currentFilePath);
                self._pushDir(dirIterator, dirIterator);
            }
            else {
                console.log("exclude dir", self.currentFilePath);
                dirIterator();
            }
        },
        function complete(error) {
            if (error) {
                self.emit("done", error);
            }
            else {
                self.next();
            }
        });
    });
}
util.inherits(DirectoryReader, events.EventEmitter);

DirectoryReader.prototype._pushDir = function(nextCB, errorCB) {
    var self = this,
        dir = self.currentFilePath;

    fs.readdir(dir, function(error, list) {
        if (error) {
            if (errorCB) {
                errorCB(error);
            }
            else {
                self.emit("done", error);
            }
        }
        else {
            self.dirStack.push({dir: dir, list: list, iterator: 0});

            if (nextCB) {
                nextCB();
            }
        }
    });
    return self;
};

DirectoryReader.prototype._cwd = function() {
    var length = this.dirStack.length;
    if (length > 0) {
        return this.dirStack[length - 1]
    }
    return null;
};

DirectoryReader.prototype._isExcludedDir = function() {
    var excludeDirs = this.excludeDirs,
        dir = path.resolve(this.currentFilePath);

    for (var i=0; i<excludeDirs.length;++i) {
        if (dir.indexOf(excludeDirs[i]) === 0) {
            return true;
        }
    }
    return false;
};

DirectoryReader.prototype.next = function() {
    var self = this;

    if (self._cwd() === null) {
        self.emit("done");
    }
    else {
        var file = self._cwd().list[self._cwd().iterator++];

        if (! file) {
            self.dirStack.pop();
            if (self.dirStack.length === 0) {
                self.emit("done");
            }
            else {
                self.next();
            }
        }
        else {
            self.currentFilePath = self._cwd().dir + '/' + file;
            fs[lstat](self.currentFilePath, function(err, stat) {
                if (stat && stat.isDirectory()) {
                    if (! self._isExcludedDir()) {
                        self.emit("dir", file, stat, self.currentFilePath);
                    }
                    else {
                        console.log("exclude dir", self.currentFilePath);
                        self.next();
                    }
                }
                else {
                    self.emit("file", file, stat, self.currentFilePath);
                }
            });
        }
    }
};

DirectoryReader.prototype.list = function() {
    var self = this;

    self._pushDir(function () {
        self.next();
    });
};

<|endoftext|>


<commit_before>require('./facets.scss');

import $ from 'jquery';
require('jquery-ui');
require('jquery.fancytree/src/jquery.fancytree');
import * as _ from 'underscore';
const workzoneFacets = services => {
    const { configService, localeService, appEvents } = services;

    /*
     selectedFacetValues[]
     key : facet.name
     value : {
     'value' : facet.value,
     'mode' : "AND"|"EXCEPT"
     }
     */

    const ORDER_BY_BCT = "ORDER_BY_BCT";
    const ORDER_ALPHA_ASC = "ORDER_ALPHA_ASC";
    const ORDER_BY_HITS = "ORDER_BY_HITS";

    let selectedFacetValues = [];
    let facetStatus = $.parseJSON(sessionStorage.getItem('facetStatus')) || [];
    let hiddenFacetsList = [];

    /*var getSelectedFacets = function() {
     return selectedFacetValues;
     };*/

    var resetSelectedFacets = function () {
        selectedFacetValues = [];
        return selectedFacetValues;
    };

    var loadFacets = function (data) {
        hiddenFacetsList = data.hiddenFacetsList;

        function sortIteration(i) {
            switch(data.facetValueOrder) {
                case ORDER_ALPHA_ASC:
                    return i.value.toString().toLowerCase();
                    break;
                case ORDER_BY_HITS:
                    return i.count*-1;
                    break;
            }
        }

        // Convert facets data to fancytree source format
        var treeSource = _.map(data.facets, function (facet) {
            // Values
            var values = _.map(_.sortBy(facet.values, sortIteration), function (value) {
                return {
                    title: value.value + ' (' + value.count + ')',
                    query: value.query,
                    label: value.value,
                    tooltip: value.value + ' (' + value.count + ')'
                };
            });
            // Facet
            return {
                name: facet.name,
                title: facet.label,
                folder: true,
                children: values,
                expanded: !_.some(facetStatus, function(o) { return _.has(o, facet.name)})
            };
        });

        treeSource.sort(
            _sortFacets('title', true, function (a) {
                return a.toUpperCase();
            })
        );

        if(data.facetOrder == ORDER_BY_BCT) {
            treeSource = _sortByPredefinedFacets(treeSource, 'name', ['base_aggregate', 'collection_aggregate', 'doctype_aggregate']);
        }

        if(data.filterFacet == true) {
            treeSource = _shouldFilterSingleContent(treeSource);
        }

        if (hiddenFacetsList.length > 0) {
            treeSource = _shouldMaskNodes(treeSource, hiddenFacetsList);
        }

        treeSource = _parseColors(treeSource);

        return _getFacetsTree().reload(treeSource)
            .done(function () {
                _.each($('#proposals').find('.fancytree-expanded'), function (element) {
                    $(element).find('.fancytree-title, .fancytree-expander').css('line-height', $(element)[0].offsetHeight + 'px');
                    $(element).find('.mask-facets-btn, .fancytree-expander').css('height', $(element)[0].offsetHeight + 'px');
                });
            });
    };

    function _parseColors(source) {
        _.forEach(source, function (facet) {
            if (!_.isUndefined(facet.children) && (facet.children.length > 0)) {
                _.forEach(facet.children, function (child) {
                    var title = child.title;
                    child.title = _formatColorText(title);
                });
            }
        });
        return source;
    }

    function _formatColorText(string, textLimit = 0) {
        //get color code from text if exist
        var regexp = /^(.*)\[#([0-9a-fA-F]{6})].*$/;

        var match = string.match(regexp);
        if (match && match[2] != null) {
            var colorCode = '#' + match[2];
            // //add color circle and re move color code from text;
            var textWithoutColorCode = string.replace('[' + colorCode + ']', '');
            if (textLimit > 0 && textWithoutColorCode.length > textLimit) {
                textWithoutColorCode = textWithoutColorCode.substring(0, textLimit) + '…';
            }
            return '' + ' ' + textWithoutColorCode;
        } else {
            if (textLimit > 0 && string.length > textLimit) {
                string = string.substring(0, textLimit) + '…';
            }
            return string;
        }
    }

    // from stackoverflow
    // http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects/979325#979325
    function _sortFacets(field, reverse, primer) {
        var key = function (x) {
            return primer ? primer(x[field]) : x[field];
        };

        return function (a, b) {
            let A = key(a);
            let B = key(b);
            return (A  B ? 1 : 0) * [-1, 1][+!!reverse];
        };
    }

    function _shouldMaskNodes(source, facetsList) {
        let filteredSource = source.slice();
        _.each(facetsList, function (facetsValue, index) {
            for (let i = filteredSource.length - 1; i > -1; --i) {
                let facet = filteredSource[i];
                if (facet['name'] !== undefined) {
                    if (facet['name'] === facetsValue.name) {
                        filteredSource.splice(i, 1);
                    }
                }
            }
        });
        return filteredSource;
    }

    function _shouldFilterSingleContent(source) {
        var filteredSource = [];
        _.forEach(source, function (facet) {
            //close expansion for facet containing selected values
            // if (!_.isUndefined(selectedFacetValues[facet.title])) {
            //     facet.expanded = false;
            // }
            if (
                !_.isUndefined(facet.children) &&
                (facet.children.length > 1 ||
                !_.isUndefined(selectedFacetValues[facet.title]))
            ) {
                filteredSource.push(facet);
            }
        });
        return filteredSource;
    }

    function _sortByPredefinedFacets(source, field, predefinedFieldOrder) {
        let filteredSource = source.slice();
        let ordered = [];

        _.each(predefinedFieldOrder, function (fieldValue, index) {
            for (let i = filteredSource.length - 1; i > -1; --i) {
                let facet = filteredSource[i];
                if (facet[field] !== undefined) {
                    if (facet[field] === fieldValue) {
                        ordered.push(facet);
                        // remove from filtered
                        filteredSource.splice(i, 1);
                    }
                }
            }
        });

        const olen = filteredSource.length;
        // fill predefined facets with non predefined facets
        for (let i = 0; i < olen; i++) {
            ordered.push(filteredSource[i]);
        }
        return ordered;
    }

    function _getFacetsTree() {
        var $facetsTree = $('#proposals');
        if (!$facetsTree.data('ui-fancytree')) {
            $facetsTree.fancytree({
                // activate and expand
                clickFolderMode: 3,
                icons: false,
                source: [],
                activate: function (event, data) {
                    var query = data.node.data.query;
                    var eventType = event.originalEvent;
                    //if user did not click, then no need to perform any query
                    if(eventType == null) {
                        return;
                    }
                    if (query) {
                        var facet = data.node.parent;
                        var facetData = {
                            value: data.node.data,
                            mode: event.altKey ? "EXCEPT" : "AND"
                        };

                        if (selectedFacetValues[facet.title] == null) {
                            selectedFacetValues[facet.title] = [];
                        }
                        selectedFacetValues[facet.title].push(facetData);
                        _facetCombinedSearch();
                    }
                },
                collapse: function (event, data) {
                    var dict = {};
                    dict[data.node.data.name] = "collapse";
                    if(_.findWhere(facetStatus, dict) !== undefined ) {
                        facetStatus = _.without(facetStatus, _.findWhere(facetStatus, dict))
                    }
                    facetStatus.push(dict);
                    sessionStorage.setItem('facetStatus', JSON.stringify(facetStatus));
                },
                expand: function (event, data) {
                    var dict = {};
                    dict[data.node.data.name] = "collapse";
                    if (_.findWhere(facetStatus, dict) !== undefined) {
                        facetStatus = _.without(facetStatus, _.findWhere(facetStatus, dict))
                    }
                    sessionStorage.setItem('facetStatus', JSON.stringify(facetStatus));
                },
                renderNode: function (event, data) {
                    var facetFilter = "";
                    var node = data.node;
                    var $nodeSpan = $(node.span);

                    // check if span of node already rendered
                    if (!$nodeSpan.data('rendered')) {
                        var deleteButton = $('

');
                        $nodeSpan.append(deleteButton);
                        deleteButton.hide();

                        $nodeSpan.hover(function () {
                            deleteButton.show();
                        }, function () {
                            deleteButton.hide();
                        });

                        deleteButton.click(function () {
                            var nodeObj = {name: node.data.name, title: node.title};
                            hiddenFacetsList.push(nodeObj);
                            node.remove();
                            appEvents.emit('search.saveHiddenFacetsList', hiddenFacetsList);
                            appEvents.emit('search.reloadHiddenFacetList', hiddenFacetsList);
                        });

                        // span rendered
                        $nodeSpan.data('rendered', true);

                        if (data.node.folder && !_.isUndefined(selectedFacetValues[data.node.title])) {
                            if ($(".fancytree-folder", data.node.li).find('.dataNode').length == 0) {
                                var dataNode = document.createElement('div');
                                dataNode.setAttribute("class", "dataNode");
                                $(".fancytree-folder", data.node.li).append(
                                    dataNode
                                );
                            } else {
                                //remove existing facets
                                $(".dataNode", data.node.li).empty();
                            }

                            _.each(selectedFacetValues[data.node.title], function (facetValue) {

                                facetFilter = facetValue.value.label;

                                var s_label = document.createElement("SPAN");
                                s_label.setAttribute("class", "facetFilter-label");
                                s_label.setAttribute("title", facetFilter);

                                var length = 15;
                                var facetFilterString = _formatColorText(facetFilter, length);

                                _.each($.parseHTML(facetFilterString), function (elem) {
                                    s_label.appendChild(elem);
                                });

                                var buttonsSpan = document.createElement("SPAN");
                                buttonsSpan.setAttribute("class", "buttons-span");

                                var s_inverse = document.createElement("A");
                                s_inverse.setAttribute("class", "facetFilter-inverse");

                                var s_closer = document.createElement("A");
                                s_closer.setAttribute("class", "facetFilter-closer");

                                var s_gradient = document.createElement("SPAN");
                                s_gradient.setAttribute("class", "facetFilter-gradient");
                                s_gradient.appendChild(document.createTextNode("\u00A0"));

                                s_label.appendChild(s_gradient);

                                var s_facet = document.createElement("SPAN");
                                s_facet.setAttribute("class", "facetFilter" + '_' + facetValue.mode);
                                s_facet.appendChild(s_label);
                                s_facet.appendChild(buttonsSpan);
                                buttonsSpan.appendChild(s_inverse);
                                buttonsSpan.appendChild(s_closer);

                                $(s_closer).on('click',
                                    function (event) {
                                        event.stopPropagation();
                                        var $facet = $(this).parent().parent();
                                        var facetTitle = $facet.data("facetTitle");
                                        var facetFilter = $facet.data("facetFilter");
                                        var mode = $facet.hasClass("facetFilter_EXCEPT") ? "EXCEPT" : "AND";
                                        selectedFacetValues[facetTitle] = _.reject(selectedFacetValues[facetTitle], function (obj) {
                                            return (obj.value.label == facetFilter && obj.mode == mode);
                                        });
                                        //delete selectedFacetValues[facetTitle];
                                        _facetCombinedSearch();
                                        return false;
                                    }
                                );

                                $(s_inverse).on('click',
                                    function (event) {
                                        event.stopPropagation();
                                        var $facet = $(this).parent().parent();
                                        var facetTitle = $facet.data("facetTitle");
                                        var facetFilter = $facet.data("facetFilter");
                                        var mode = $facet.hasClass("facetFilter_EXCEPT") ? "EXCEPT" : "AND";
                                        var found = _.find(selectedFacetValues[facetTitle], function (obj) {
                                            return (obj.value.label == facetFilter && obj.mode == mode);
                                        });
                                        if (found) {
                                            var newMode = mode == "EXCEPT" ? "AND" : "EXCEPT";
                                            found.mode = newMode;
                                            //replace class attr
                                            $facet.filter('.' + "facetFilter" + '_' + mode).removeClass("facetFilter" + '_' + mode).addClass("facetFilter" + '_' + newMode).end();
                                            _facetCombinedSearch();
                                        }
                                        return false;
                                    }
                                );

                                var newNode = document.createElement('div');
                                newNode.setAttribute("class", "newNode");
                                s_facet = $(newNode.appendChild(s_facet));
                                s_facet.data("facetTitle", data.node.title);
                                s_facet.data("facetFilter", facetFilter);

                                s_facet.hover(function () {
                                    $(buttonsSpan).show();
                                }, function () {
                                    $(buttonsSpan).hide();
                                });

                                $(".fancytree-folder .dataNode", data.node.li).append(
                                    newNode
                                );
                            });
                        }
                    }
                }
            });
        }
        return $facetsTree.fancytree('getTree');
    }

    function _facetCombinedSearch() {
        var q = $('#EDIT_query').val();
        var q_facet_and = "";
        var q_facet_except = "";
        _.each(_.values(selectedFacetValues), function (facet) {
            _.each(facet, function (facetValue) {
                switch (facetValue.mode) {
                    case "AND":
                        q_facet_and += (q_facet_and ? " AND " : "") + '(' + facetValue.value.query + ')';
                        break;
                    case "EXCEPT":
                        q_facet_except += (q_facet_except ? " OR " : "") + '(' + facetValue.value.query + ')';
                        break;
                }
            });
        });
        if(!q && !q_facet_and && q_facet_except) {
            // too bad : an except with no query.
            q = "created_on>1900/01/01";    // fake "all"
        }
        if(q_facet_and != "") {
            if (q) {
                q = '(' + q + ') AND '
            }
            q += q_facet_and;
        }
        if(q_facet_except != "") {
            q = '(' + q + ') EXCEPT (' + q_facet_except + ')';
        }

        appEvents.emit('search.doCheckFilters');
        appEvents.emit('search.doNewSearch', q);
        // searchModule.newSearch(q);
    }

    appEvents.listenAll({
        'facets.doLoadFacets': loadFacets,
        'facets.doResetSelectedFacets': resetSelectedFacets,
    });

    return {
        loadFacets,
        resetSelectedFacets
    };
};

export default workzoneFacets;
<commit_msg>fix error in integer value<commit_after>require('./facets.scss');

import $ from 'jquery';
require('jquery-ui');
require('jquery.fancytree/src/jquery.fancytree');
import * as _ from 'underscore';
const workzoneFacets = services => {
    const { configService, localeService, appEvents } = services;

    /*
     selectedFacetValues[]
     key : facet.name
     value : {
     'value' : facet.value,
     'mode' : "AND"|"EXCEPT"
     }
     */

    const ORDER_BY_BCT = "ORDER_BY_BCT";
    const ORDER_ALPHA_ASC = "ORDER_ALPHA_ASC";
    const ORDER_BY_HITS = "ORDER_BY_HITS";

    let selectedFacetValues = [];
    let facetStatus = $.parseJSON(sessionStorage.getItem('facetStatus')) || [];
    let hiddenFacetsList = [];

    /*var getSelectedFacets = function() {
     return selectedFacetValues;
     };*/

    var resetSelectedFacets = function () {
        selectedFacetValues = [];
        return selectedFacetValues;
    };

    var loadFacets = function (data) {
        hiddenFacetsList = data.hiddenFacetsList;

        function sortIteration(i) {
            switch(data.facetValueOrder) {
                case ORDER_ALPHA_ASC:
                    return i.value.toString().toLowerCase();
                    break;
                case ORDER_BY_HITS:
                    return i.count*-1;
                    break;
            }
        }

        // Convert facets data to fancytree source format
        var treeSource = _.map(data.facets, function (facet) {
            // Values
            var values = _.map(_.sortBy(facet.values, sortIteration), function (value) {
                return {
                    title: value.value + ' (' + value.count + ')',
                    query: value.query,
                    label: value.value,
                    tooltip: value.value + ' (' + value.count + ')'
                };
            });
            // Facet
            return {
                name: facet.name,
                title: facet.label,
                folder: true,
                children: values,
                expanded: !_.some(facetStatus, function(o) { return _.has(o, facet.name)})
            };
        });

        treeSource.sort(
            _sortFacets('title', true, function (a) {
                return a.toUpperCase();
            })
        );

        if(data.facetOrder == ORDER_BY_BCT) {
            treeSource = _sortByPredefinedFacets(treeSource, 'name', ['base_aggregate', 'collection_aggregate', 'doctype_aggregate']);
        }

        if(data.filterFacet == true) {
            treeSource = _shouldFilterSingleContent(treeSource);
        }

        if (hiddenFacetsList.length > 0) {
            treeSource = _shouldMaskNodes(treeSource, hiddenFacetsList);
        }

        treeSource = _parseColors(treeSource);

        return _getFacetsTree().reload(treeSource)
            .done(function () {
                _.each($('#proposals').find('.fancytree-expanded'), function (element) {
                    $(element).find('.fancytree-title, .fancytree-expander').css('line-height', $(element)[0].offsetHeight + 'px');
                    $(element).find('.mask-facets-btn, .fancytree-expander').css('height', $(element)[0].offsetHeight + 'px');
                });
            });
    };

    function _parseColors(source) {
        _.forEach(source, function (facet) {
            if (!_.isUndefined(facet.children) && (facet.children.length > 0)) {
                _.forEach(facet.children, function (child) {
                    var title = child.title;
                    child.title = _formatColorText(title.toString());
                });
            }
        });
        return source;
    }

    function _formatColorText(string, textLimit = 0) {
        //get color code from text if exist
        var regexp = /^(.*)\[#([0-9a-fA-F]{6})].*$/;

        var match = string.match(regexp);
        if (match && match[2] != null) {
            var colorCode = '#' + match[2];
            // //add color circle and re move color code from text;
            var textWithoutColorCode = string.replace('[' + colorCode + ']', '');
            if (textLimit > 0 && textWithoutColorCode.length > textLimit) {
                textWithoutColorCode = textWithoutColorCode.substring(0, textLimit) + '…';
            }
            return '' + ' ' + textWithoutColorCode;
        } else {
            if (textLimit > 0 && string.length > textLimit) {
                string = string.substring(0, textLimit) + '…';
            }
            return string;
        }
    }

    // from stackoverflow
    // http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects/979325#979325
    function _sortFacets(field, reverse, primer) {
        var key = function (x) {
            return primer ? primer(x[field]) : x[field];
        };

        return function (a, b) {
            let A = key(a);
            let B = key(b);
            return (A  B ? 1 : 0) * [-1, 1][+!!reverse];
        };
    }

    function _shouldMaskNodes(source, facetsList) {
        let filteredSource = source.slice();
        _.each(facetsList, function (facetsValue, index) {
            for (let i = filteredSource.length - 1; i > -1; --i) {
                let facet = filteredSource[i];
                if (facet['name'] !== undefined) {
                    if (facet['name'] === facetsValue.name) {
                        filteredSource.splice(i, 1);
                    }
                }
            }
        });
        return filteredSource;
    }

    function _shouldFilterSingleContent(source) {
        var filteredSource = [];
        _.forEach(source, function (facet) {
            //close expansion for facet containing selected values
            // if (!_.isUndefined(selectedFacetValues[facet.title])) {
            //     facet.expanded = false;
            // }
            if (
                !_.isUndefined(facet.children) &&
                (facet.children.length > 1 ||
                !_.isUndefined(selectedFacetValues[facet.title]))
            ) {
                filteredSource.push(facet);
            }
        });
        return filteredSource;
    }

    function _sortByPredefinedFacets(source, field, predefinedFieldOrder) {
        let filteredSource = source.slice();
        let ordered = [];

        _.each(predefinedFieldOrder, function (fieldValue, index) {
            for (let i = filteredSource.length - 1; i > -1; --i) {
                let facet = filteredSource[i];
                if (facet[field] !== undefined) {
                    if (facet[field] === fieldValue) {
                        ordered.push(facet);
                        // remove from filtered
                        filteredSource.splice(i, 1);
                    }
                }
            }
        });

        const olen = filteredSource.length;
        // fill predefined facets with non predefined facets
        for (let i = 0; i < olen; i++) {
            ordered.push(filteredSource[i]);
        }
        return ordered;
    }

    function _getFacetsTree() {
        var $facetsTree = $('#proposals');
        if (!$facetsTree.data('ui-fancytree')) {
            $facetsTree.fancytree({
                // activate and expand
                clickFolderMode: 3,
                icons: false,
                source: [],
                activate: function (event, data) {
                    var query = data.node.data.query;
                    var eventType = event.originalEvent;
                    //if user did not click, then no need to perform any query
                    if(eventType == null) {
                        return;
                    }
                    if (query) {
                        var facet = data.node.parent;
                        var facetData = {
                            value: data.node.data,
                            mode: event.altKey ? "EXCEPT" : "AND"
                        };

                        if (selectedFacetValues[facet.title] == null) {
                            selectedFacetValues[facet.title] = [];
                        }
                        selectedFacetValues[facet.title].push(facetData);
                        _facetCombinedSearch();
                    }
                },
                collapse: function (event, data) {
                    var dict = {};
                    dict[data.node.data.name] = "collapse";
                    if(_.findWhere(facetStatus, dict) !== undefined ) {
                        facetStatus = _.without(facetStatus, _.findWhere(facetStatus, dict))
                    }
                    facetStatus.push(dict);
                    sessionStorage.setItem('facetStatus', JSON.stringify(facetStatus));
                },
                expand: function (event, data) {
                    var dict = {};
                    dict[data.node.data.name] = "collapse";
                    if (_.findWhere(facetStatus, dict) !== undefined) {
                        facetStatus = _.without(facetStatus, _.findWhere(facetStatus, dict))
                    }
                    sessionStorage.setItem('facetStatus', JSON.stringify(facetStatus));
                },
                renderNode: function (event, data) {
                    var facetFilter = "";
                    var node = data.node;
                    var $nodeSpan = $(node.span);

                    // check if span of node already rendered
                    if (!$nodeSpan.data('rendered')) {
                        var deleteButton = $('

');
                        $nodeSpan.append(deleteButton);
                        deleteButton.hide();

                        $nodeSpan.hover(function () {
                            deleteButton.show();
                        }, function () {
                            deleteButton.hide();
                        });

                        deleteButton.click(function () {
                            var nodeObj = {name: node.data.name, title: node.title};
                            hiddenFacetsList.push(nodeObj);
                            node.remove();
                            appEvents.emit('search.saveHiddenFacetsList', hiddenFacetsList);
                            appEvents.emit('search.reloadHiddenFacetList', hiddenFacetsList);
                        });

                        // span rendered
                        $nodeSpan.data('rendered', true);

                        if (data.node.folder && !_.isUndefined(selectedFacetValues[data.node.title])) {
                            if ($(".fancytree-folder", data.node.li).find('.dataNode').length == 0) {
                                var dataNode = document.createElement('div');
                                dataNode.setAttribute("class", "dataNode");
                                $(".fancytree-folder", data.node.li).append(
                                    dataNode
                                );
                            } else {
                                //remove existing facets
                                $(".dataNode", data.node.li).empty();
                            }

                            _.each(selectedFacetValues[data.node.title], function (facetValue) {

                                facetFilter = facetValue.value.label;

                                var s_label = document.createElement("SPAN");
                                s_label.setAttribute("class", "facetFilter-label");
                                s_label.setAttribute("title", facetFilter);

                                var length = 15;
                                var facetFilterString = _formatColorText(facetFilter.toString(), length);

                                _.each($.parseHTML(facetFilterString), function (elem) {
                                    s_label.appendChild(elem);
                                });

                                var buttonsSpan = document.createElement("SPAN");
                                buttonsSpan.setAttribute("class", "buttons-span");

                                var s_inverse = document.createElement("A");
                                s_inverse.setAttribute("class", "facetFilter-inverse");

                                var s_closer = document.createElement("A");
                                s_closer.setAttribute("class", "facetFilter-closer");

                                var s_gradient = document.createElement("SPAN");
                                s_gradient.setAttribute("class", "facetFilter-gradient");
                                s_gradient.appendChild(document.createTextNode("\u00A0"));

                                s_label.appendChild(s_gradient);

                                var s_facet = document.createElement("SPAN");
                                s_facet.setAttribute("class", "facetFilter" + '_' + facetValue.mode);
                                s_facet.appendChild(s_label);
                                s_facet.appendChild(buttonsSpan);
                                buttonsSpan.appendChild(s_inverse);
                                buttonsSpan.appendChild(s_closer);

                                $(s_closer).on('click',
                                    function (event) {
                                        event.stopPropagation();
                                        var $facet = $(this).parent().parent();
                                        var facetTitle = $facet.data("facetTitle");
                                        var facetFilter = $facet.data("facetFilter");
                                        var mode = $facet.hasClass("facetFilter_EXCEPT") ? "EXCEPT" : "AND";
                                        selectedFacetValues[facetTitle] = _.reject(selectedFacetValues[facetTitle], function (obj) {
                                            return (obj.value.label == facetFilter && obj.mode == mode);
                                        });
                                        //delete selectedFacetValues[facetTitle];
                                        _facetCombinedSearch();
                                        return false;
                                    }
                                );

                                $(s_inverse).on('click',
                                    function (event) {
                                        event.stopPropagation();
                                        var $facet = $(this).parent().parent();
                                        var facetTitle = $facet.data("facetTitle");
                                        var facetFilter = $facet.data("facetFilter");
                                        var mode = $facet.hasClass("facetFilter_EXCEPT") ? "EXCEPT" : "AND";
                                        var found = _.find(selectedFacetValues[facetTitle], function (obj) {
                                            return (obj.value.label == facetFilter && obj.mode == mode);
                                        });
                                        if (found) {
                                            var newMode = mode == "EXCEPT" ? "AND" : "EXCEPT";
                                            found.mode = newMode;
                                            //replace class attr
                                            $facet.filter('.' + "facetFilter" + '_' + mode).removeClass("facetFilter" + '_' + mode).addClass("facetFilter" + '_' + newMode).end();
                                            _facetCombinedSearch();
                                        }
                                        return false;
                                    }
                                );

                                var newNode = document.createElement('div');
                                newNode.setAttribute("class", "newNode");
                                s_facet = $(newNode.appendChild(s_facet));
                                s_facet.data("facetTitle", data.node.title);
                                s_facet.data("facetFilter", facetFilter);

                                s_facet.hover(function () {
                                    $(buttonsSpan).show();
                                }, function () {
                                    $(buttonsSpan).hide();
                                });

                                $(".fancytree-folder .dataNode", data.node.li).append(
                                    newNode
                                );
                            });
                        }
                    }
                }
            });
        }
        return $facetsTree.fancytree('getTree');
    }

    function _facetCombinedSearch() {
        var q = $('#EDIT_query').val();
        var q_facet_and = "";
        var q_facet_except = "";
        _.each(_.values(selectedFacetValues), function (facet) {
            _.each(facet, function (facetValue) {
                switch (facetValue.mode) {
                    case "AND":
                        q_facet_and += (q_facet_and ? " AND " : "") + '(' + facetValue.value.query + ')';
                        break;
                    case "EXCEPT":
                        q_facet_except += (q_facet_except ? " OR " : "") + '(' + facetValue.value.query + ')';
                        break;
                }
            });
        });
        if(!q && !q_facet_and && q_facet_except) {
            // too bad : an except with no query.
            q = "created_on>1900/01/01";    // fake "all"
        }
        if(q_facet_and != "") {
            if (q) {
                q = '(' + q + ') AND '
            }
            q += q_facet_and;
        }
        if(q_facet_except != "") {
            q = '(' + q + ') EXCEPT (' + q_facet_except + ')';
        }

        appEvents.emit('search.doCheckFilters');
        appEvents.emit('search.doNewSearch', q);
        // searchModule.newSearch(q);
    }

    appEvents.listenAll({
        'facets.doLoadFacets': loadFacets,
        'facets.doResetSelectedFacets': resetSelectedFacets,
    });

    return {
        loadFacets,
        resetSelectedFacets
    };
};

export default workzoneFacets;
<|endoftext|>