<commit_before>'use strict';

angular.module('farmbuild.nutrientCalculator.examples.concentratesPurchased', ['farmbuild.nutrientCalculator'])

	.run(function($rootScope){
		$rootScope.appVersion = farmbuild.examples.nutrientcalculator.version;
	})

	.filter('dryWet', function() {
		return function(input) {
			return input ? 'Dry' : 'Wet';
		}
	})

	.controller('ConcentratesPurchasedCtrl', function ($scope, $rootScope, nutrientCalculator, concentratesPurchased) {

		$rootScope.decimalPrecision = farmbuild.examples.nutrientcalculator.decimalPrecision;
		$scope.concentrates = [];
		$scope.noResult = false;
		$scope.concentrateTypes = concentratesPurchased.types.toArray();
    $scope.newConcentrate = createNew();

    function createNew() {
      return {isDry:true};
    }

		$scope.calculate = function (concentrates) {
      if(!concentratesPurchased.validateAll(concentrates)) {
        $scope.noResult = true;
        return;
      }
			$scope.result = concentratesPurchased.calculate(concentrates);
			$scope.noResult = !$scope.result;
      saveInSessionStorage($scope.result);

		};

		$scope.addConcentrate = function (type, weight, isDry) {
      if(!concentratesPurchased.validate(type, weight, isDry)) {
        $scope.noResult = true;
        return;
      }

			isDry = (isDry === 'true');
			$scope.concentrates = concentratesPurchased.add(type, weight, isDry).concentrates();
			$scope.result = '';
			$scope.newConcentrate = createNew();
			$scope.noResult = !$scope.concentrates;
		};

		$scope.removeConcentrate = function (index) {
			$scope.result = '';
			$scope.concentrates = concentratesPurchased.removeAt(index);
		};

		$scope.addConcentrateType = function (type) {
      if(!concentratesPurchased.types.validate(type)) {
        $scope.noResult = true;
        return;
      }
			$scope.concentrateTypes = concentratesPurchased.types.add(type.name, type.metabolisableEnergyInMJPerKg, type.dryMatterPercentage,
																									type.sulphurPercentage, type.potassiumPercentage,
																									type.phosphorusPercentage, type.nitrogenPercentage);
			$scope.result = '';
			$scope.type = {};
			$scope.noResult = !$scope.concentrates;
		};

		$scope.removeConcentrateType = function (index) {
			$scope.result = '';
			$scope.concentrateTypes = concentratesPurchased.types.removeAt(index);
		};

    function saveInSessionStorage(result) {
      nutrientCalculator.session.saveSection('concentratesPurchased', result);
    };

    if(nutrientCalculator.session.isLoadFlagSet(location)){
      var concentratesPurchasedData = nutrientCalculator.session.loadSection('concentratesPurchased');

      concentratesPurchased.load(concentratesPurchasedData.concentrates);
      $scope.calculate(concentratesPurchasedData.concentrates);
      $scope.concentrates =  concentratesPurchasedData.concentrates;
    }

	});<commit_msg>remove and then call concentrates<commit_after>'use strict';

angular.module('farmbuild.nutrientCalculator.examples.concentratesPurchased', ['farmbuild.nutrientCalculator'])

	.run(function($rootScope){
		$rootScope.appVersion = farmbuild.examples.nutrientcalculator.version;
	})

	.filter('dryWet', function() {
		return function(input) {
			return input ? 'Dry' : 'Wet';
		}
	})

	.controller('ConcentratesPurchasedCtrl', function ($scope, $rootScope, nutrientCalculator, concentratesPurchased) {

		$rootScope.decimalPrecision = farmbuild.examples.nutrientcalculator.decimalPrecision;
		$scope.concentrates = [];
		$scope.noResult = false;
		$scope.concentrateTypes = concentratesPurchased.types.toArray();
    $scope.newConcentrate = createNew();

    function createNew() {
      return {isDry:true};
    }

		$scope.calculate = function (concentrates) {
      if(!concentratesPurchased.validateAll(concentrates)) {
        $scope.noResult = true;
        return;
      }
			$scope.result = concentratesPurchased.calculate(concentrates);
			$scope.noResult = !$scope.result;
      saveInSessionStorage($scope.result);

		};

		$scope.addConcentrate = function (type, weight, isDry) {
      if(!concentratesPurchased.validate(type, weight, isDry)) {
        $scope.noResult = true;
        return;
      }

			isDry = (isDry === 'true');
			$scope.concentrates = concentratesPurchased.add(type, weight, isDry).concentrates();
			$scope.result = '';
			$scope.newConcentrate = createNew();
			$scope.noResult = !$scope.concentrates;
		};

		$scope.removeConcentrate = function (index) {
			$scope.result = '';
			$scope.concentrates = concentratesPurchased.removeAt(index).concentrates();
		};

		$scope.addConcentrateType = function (type) {
      if(!concentratesPurchased.types.validate(type)) {
        $scope.noResult = true;
        return;
      }
			$scope.concentrateTypes = concentratesPurchased.types.add(type.name, type.metabolisableEnergyInMJPerKg, type.dryMatterPercentage,
																									type.sulphurPercentage, type.potassiumPercentage,
																									type.phosphorusPercentage, type.nitrogenPercentage);
			$scope.result = '';
			$scope.type = {};
			$scope.noResult = !$scope.concentrates;
		};

		$scope.removeConcentrateType = function (index) {
			$scope.result = '';
			$scope.concentrateTypes = concentratesPurchased.types.removeAt(index);
		};

    function saveInSessionStorage(result) {
      nutrientCalculator.session.saveSection('concentratesPurchased', result);
    };

    if(nutrientCalculator.session.isLoadFlagSet(location)){
      var concentratesPurchasedData = nutrientCalculator.session.loadSection('concentratesPurchased');

      concentratesPurchased.load(concentratesPurchasedData.concentrates);
      $scope.calculate(concentratesPurchasedData.concentrates);
      $scope.concentrates =  concentratesPurchasedData.concentrates;
    }

	});<|endoftext|>


<commit_before>import React from "react";

import { connect } from "react-redux";

import { Overlay as OverlayFrame, Close } from "sajari-react/ui/Overlay";
import { setActive } from "sajari-react/ui/actions/Overlay";
import AutocompleteInput from "sajari-react/pipeline/AutocompleteInput";
import {
  Response,
  Summary,
  Results,
  Paginator
} from "sajari-react/pipeline/Response";
import Tabs from "sajari-react/pipeline/Tabs";
import Analytics from "sajari-react/pipeline/analytics";

import { State } from "sajari-react/pipeline/state";

import "./styles.css";

const _state = State.default();

const SearchInterface = ({ config }) => (

    <SearchBox config={config} />
    <Close />
    <SearchResponse config={config} />

);

class SearchBox extends React.Component {
  componentDidMount() {
    _state.setProject(this.props.config.project);
    _state.setCollection(this.props.config.collection);
    _state.setPipeline(this.props.config.pipeline);

    if (this.props.config.values) {
      _state.setValues(this.props.config.values, !!this.props.config.values.q);
    }

    if (!this.props.config.disableGA) {
      new Analytics("default");
    }
  }

  render() {
    const { searchBoxPlaceHolder } = this.props.config;
    return <AutocompleteInput placeHolder={searchBoxPlaceHolder} />;
  }
}

const SearchResponse = ({ config }) => {
  let tabs = null;
  if (config.tabFilters) {
    tabs = (
      <Tabs
        defaultTab={config.tabFilters.defaultTab}
        tabs={config.tabFilters.tabs}
      />
    );
  }

  return (
    <Response>
      {tabs}

      <Results showImages={config.showImages} />
      <Paginator />
    </Response>
  );
};

class overlay extends React.Component {
  componentDidMount() {
    document.addEventListener("keydown", e => {
      // Check for escape key
      if (e.keyCode === 27) {
        this.props.closeOverlay();
      }
    });
  }

  render() {
    return (
      <OverlayFrame>
        <SearchInterface config={this.props.config} />
      </OverlayFrame>
    );
  }
}

const Overlay = connect(null, dispatch => ({
  closeOverlay: () => dispatch(setActive(false))
}))(overlay);

export default Overlay;
<commit_msg>site-search-overlay: remove unneeded div in response<commit_after>import React from "react";

import { connect } from "react-redux";

import { Overlay as OverlayFrame, Close } from "sajari-react/ui/Overlay";
import { setActive } from "sajari-react/ui/actions/Overlay";
import AutocompleteInput from "sajari-react/pipeline/AutocompleteInput";
import {
  Response,
  Summary,
  Results,
  Paginator
} from "sajari-react/pipeline/Response";
import Tabs from "sajari-react/pipeline/Tabs";
import Analytics from "sajari-react/pipeline/analytics";

import { State } from "sajari-react/pipeline/state";

import "./styles.css";

const _state = State.default();

class SearchBox extends React.Component {
  componentDidMount() {
    _state.setProject(this.props.config.project);
    _state.setCollection(this.props.config.collection);
    _state.setPipeline(this.props.config.pipeline);

    if (this.props.config.values) {
      _state.setValues(this.props.config.values, !!this.props.config.values.q);
    }

    if (!this.props.config.disableGA) {
      new Analytics("default");
    }
  }

  render() {
    const { searchBoxPlaceHolder } = this.props.config;
    return <AutocompleteInput placeHolder={searchBoxPlaceHolder} />;
  }
}

const SearchResponse = ({ config }) => {
  let tabs = null;
  if (config.tabFilters) {
    tabs = (
      <Tabs
        defaultTab={config.tabFilters.defaultTab}
        tabs={config.tabFilters.tabs}
      />
    );
  }

  return (
    <Response>
      {tabs}

      <Results showImages={config.showImages} />
      <Paginator />
    </Response>
  );
};

class overlay extends React.Component {
  componentDidMount() {
    document.addEventListener("keydown", e => {
      // Check for escape key
      if (e.keyCode === 27) {
        this.props.closeOverlay();
      }
    });
  }

  render() {
    const { config, closeOverlay } = this.props;
    return (
      <OverlayFrame>

        <SearchBox config={config} />
        <Close />
        <SearchResponse config={config} />
      </OverlayFrame>
    );
  }
}

const Overlay = connect(null, dispatch => ({
  closeOverlay: () => dispatch(setActive(false))
}))(overlay);

export default Overlay;
<|endoftext|>


<commit_before>function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  //insert elements, even before Polymer is loaded

  //first element of the original document
  // var firstElement = document.body.children[0];
  var firstElement = document.querySelector('primo-explore');

  //as a back up insert header if it's not defined already
  var alerts = document.createElement('uqlibrary-alerts');
  // document.body.insertBefore(alerts, firstElement.childNodes[0]);
  // firstElement.appendChild(alerts);

  // insert header after body-tag
  var header = document.createElement('uq-minimal-header');
  // document.body.insertBefore(header, firstElement.childNodes[0]);
  // firstElement.appendChild(header);

  // while new PrimoUI has infinite scrolling, do not include footer

  // // insert sub footer before body-tag
  // var subFooter = document.createElement('uql-connect-footer');
  // document.body.appendChild(subFooter);
  //
  // // insert footer before body-tag
  // var footer = document.createElement('uq-minimal-footer');
  // document.body.appendChild(footer);

  var app = angular.module('viewCustom', ['angularLoad']);
  app.component('prmExploreMainBefore', {
    template: '<uqlibrary-alerts></uqlibrary-alerts><uq-minimal-header></uq-minimal-header>'

  });

  window.addEventListener('WebComponentsReady', function() {
    // when polymer is ready - configure elements
    header.showLoginButton = false;
  });
}

ready(loadReusableComponents);<commit_msg>adding header with angular<commit_after>function ready(fn) {
  if (document.readyState != 'loading'){
    fn();
  } else {
    document.addEventListener('DOMContentLoaded', fn);
  }
}

function loadReusableComponents() {
  //insert elements, even before Polymer is loaded

  //first element of the original document
  // var firstElement = document.body.children[0];
  var firstElement = document.querySelector('primo-explore');

  //as a back up insert header if it's not defined already
  var alerts = document.createElement('uqlibrary-alerts');
  // document.body.insertBefore(alerts, firstElement.childNodes[0]);
  // firstElement.appendChild(alerts);

  // insert header after body-tag
  var header = document.createElement('uq-minimal-header');
  // document.body.insertBefore(header, firstElement.childNodes[0]);
  // firstElement.appendChild(header);

  // while new PrimoUI has infinite scrolling, do not include footer

  // // insert sub footer before body-tag
  // var subFooter = document.createElement('uql-connect-footer');
  // document.body.appendChild(subFooter);
  //
  // // insert footer before body-tag
  // var footer = document.createElement('uq-minimal-footer');
  // document.body.appendChild(footer);

  var app = angular.module('viewCustom', ['angularLoad']);
  app.component('prmExploreMainBefore', {
    template: '<uqlibrary-alerts></uqlibrary-alerts><uq-minimal-header></uq-minimal-header>'

  });

  app.component('prmSearchBarAfter', {
    template: '<uq-minimal-header></uq-minimal-header>'

  });

  window.addEventListener('WebComponentsReady', function() {
    // when polymer is ready - configure elements
    header.showLoginButton = false;
  });
}

ready(loadReusableComponents);<|endoftext|>


<commit_before>'use strict'

module.exports = {
  development: {
    client: 'sqlite3',
    connection: {
      //filename: ':memory:'
      //dont put the filename here, we need to dynamically set it in appSettings.js and pagesdb.js
    },
    //debug: (process.env.NODE_ENV === 'development'),
    /****
     * https://github.com/tgriesser/knex/pull/1043
     */
    useNullAsDefault: false
  },
  production: {
    client: 'sqlite3',
    connection: {
      //filename: ':memory:'
      //dont put the filename here, we need to dynamically set it in appSettings.js and pagesdb.js
    },
    //debug: (process.env.NODE_ENV === 'development'),
    useNullAsDefault: false
  },
  testing: {
    // client: 'pg',
    // connection: process.env.DATABASE_URL
  }
}<commit_msg>Cleaned up knexconfig<commit_after>'use strict'

module.exports = {
  development: {
    client: 'sqlite3',
    connection: {
      //dont put the filename here, we need to dynamically set it in appSettings.js and pagesdb.js
    },
    /****
     * https://github.com/tgriesser/knex/pull/1043
     */
    useNullAsDefault: false
  },
  production: {
    client: 'sqlite3',
    connection: {
    },
    useNullAsDefault: false
  }
}<|endoftext|>


<commit_before>Collection={
	artists:[],
	albums:[],
	songs:[],
	artistsById:{},
	albumsById:{},
	loaded:false,
	loading:false,
	loadedListeners:[],
	load:function(ready){
		if(ready){
			Collection.loadedListeners.push(ready);
		}
		if(!Collection.loading){
			Collection.loading=true;
			$.ajax({
				url: OC.linkTo('media','ajax/api.php')+'?action=get_collection',
				dataType: 'json',
				success: function(data){
					//normalize the data
					for(var i=0;i<data.artists.length;i++){
						var artist=data.artists[i];
						var artistData={name:artist.artist_name,songs:[],albums:[]};
						Collection.artistsById[artist.artist_id]=artistData;
						Collection.artists.push(artistData);
					}
					for(var i=0;i<data.albums.length;i++){
						var album=data.albums[i];
						if(Collection.artistsById[album.album_artist]){
							var artistName=Collection.artistsById[album.album_artist].name;
						}else{
							var artistName='unknown';
						}
						var albumData={name:album.album_name,artist:artistName,songs:[]};
						Collection.albumsById[album.album_id]=albumData;
						Collection.albums.push(albumData);
						if(Collection.artistsById[album.album_artist]){
							Collection.artistsById[album.album_artist].albums.push(albumData);
						}
					}
					for(var i=0;i<data.songs.length;i++){
						var song=data.songs[i];
						if(Collection.artistsById[song.song_artist] && Collection.albumsById[song.song_album]){
							var songData={
								name:song.song_name,
								artist:Collection.artistsById[song.song_artist].name,
								album:Collection.albumsById[song.song_album].name,
								lastPlayed:song.song_lastplayed,
								length:song.song_length,
								path:song.song_path,
								playCount:song.song_playcount,
							};
							Collection.songs.push(songData);
							Collection.artistsById[song.song_artist].songs.push(songData);
							Collection.albumsById[song.song_album].songs.push(songData);
						}
					}

					Collection.artists.sort(function(a,b){
						if(!a.name){
							return -1;
						}
						return a.name.localeCompare(b.name);
					});

					Collection.loaded=true;
					Collection.loading=false;
					for(var i=0;i<Collection.loadedListeners.length;i++){
						Collection.loadedListeners[i]();
					}
					if(data.songs.length==0){
						$('#scan input.start').val(t('media','Scan Collection'));
						$('#scan input.start').click();
					}

				}
			});
		}
	},
	display:function(){
		if(Collection.parent){
			Collection.parent.show();
		}
		if(!Collection.loaded){
			Collection.load(Collection.display)
		}else{
			if(Collection.parent){
				Collection.parent.find('tr:not(.template)').remove();
				var template=Collection.parent.find('tr.template');
				var lastArtist='';
				var lastAlbum='';
				$.each(Collection.artists,function(i,artist){
					if(artist.name && artist.songs.length>0){
						var tr=template.clone().removeClass('template');
						if(artist.songs.length>1){
							tr.find('td.title a').text(artist.songs.length+' '+t('media','songs'));
							tr.find('td.album a').text(artist.albums.length+' '+t('media','albums'));
						}else{
							tr.find('td.title a').text(artist.songs[0].name);
							tr.find('td.album a').text(artist.albums[0].name);
						}
						tr.find('td.artist a').text(artist.name);
						tr.data('artistData',artist);
						tr.find('td.artist a').click(function(event){
							event.preventDefault();
							PlayList.add(artist);
							PlayList.play(0);
							Collection.parent.find('tr').removeClass('active');
							$('tr[data-artist="'+artist.name+'"]').addClass('active');
						});
						if(artist.songs.length>1){
							var expander=$('>');
							expander.data('expanded',false);
							expander.click(function(event){
								var tr=$(this).parent().parent();
								if(expander.data('expanded')){
									Collection.hideArtist(tr.data('artist'));
								}else{
									Collection.showArtist(tr.data('artist'));
								}
							});
						}
						tr.find('td.artist').addClass('buttons');
						Collection.addButtons(tr,artist);
						tr.children('td.artist').append(expander);
						tr.attr('data-artist',artist.name);
						Collection.parent.find('tbody').append(tr);
					}
				});
			}
		}
	},
	showArtist:function(artist){
		var tr=Collection.parent.find('tr[data-artist="'+artist+'"]');
		var lastRow=tr;
		var artist=tr.data('artistData');
		var first=true;
		$.each(artist.albums,function(j,album){
			$.each(album.songs,function(i,song){
				if(first){
					newRow=tr;
				}else{
					var newRow=tr.clone();
					newRow.find('td.artist').text('');
					newRow.find('.expander').remove();
				}
				newRow.find('td.album .expander').remove();
				if(i==0){
					newRow.find('td.album a').text(album.name);
					newRow.find('td.album a').click(function(event){
						event.preventDefault();
						PlayList.add(album);
						PlayList.play(0);
						Collection.parent.find('tr').removeClass('active');
						$('tr[data-album="'+album.name+'"]').addClass('active');
					});
					if(album.songs.length>1){
						var expander=$('v ');
						expander.data('expanded',true);
						expander.click(function(event){
							var tr=$(this).parent().parent();
							if(expander.data('expanded')) {
								Collection.hideAlbum(tr.data('artist'),tr.data('album'));
							} else {
								Collection.showAlbum(tr.data('artist'),tr.data('album'));
							}
						});
						newRow.children('td.album').append(expander);
					}
					Collection.addButtons(newRow,album);
				} else {
					newRow.find('td.album a').text('');
					Collection.addButtons(newRow,song);
				}
				newRow.find('td.title a').text(song.name);
				newRow.find('td.title a').click(function(event){
					event.preventDefault();
					PlayList.add(song);
					PlayList.play(0);
					Collection.parent.find('tr').removeClass('active');
					$('tr[data-title="'+song.name+'"]').addClass('active');
				});
				newRow.attr('data-album',album.name);
				newRow.attr('data-title',song.name);
				newRow.attr('data-artist',artist.name);
				newRow.data('albumData',album);
				if(!first){
					lastRow.after(newRow);
				}
				first=false;
				lastRow=newRow;
			});
		});
		tr.removeClass('collapsed');
		tr.find('td.artist a.expander').data('expanded',true);
		tr.find('td.artist a.expander').addClass('expanded');
		tr.find('td.artist a.expander').text('v');
	},
	hideArtist:function(artist){
		var tr=Collection.parent.find('tr[data-artist="'+artist+'"]');
		var artist=tr.first().data('artistData');
		tr.first().find('td.album a').first().text(artist.albums.length+' '+t('media','albums'));
		tr.first().find('td.album a.expander').remove();
		tr.first().find('td.title a').text(artist.songs.length+' '+t('media','songs'));
		tr.first().find('td.album a').unbind('click');
		tr.first().find('td.title a').unbind('click');
		tr.each(function(i,row){
			if(i>0){
				$(row).remove();
			}
		});
		tr.find('td.artist a.expander').data('expanded',false);
		tr.find('td.artist a.expander').removeClass('expanded');
		tr.find('td.artist a.expander').text('>');
		Collection.addButtons(tr,artist);
	},
	showAlbum:function(artist,album){
		var tr = Collection.parent.find('tr[data-artist="'+artist+'"][data-album="'+album+'"]');
		var lastRow=tr;
		var albumData=tr.data('albumData');
		tr.find('td.album a.expander').data('expanded',true);
		tr.find('td.album a.expander').addClass('expanded');
		tr.find('td.album a.expander').text('v');
		$.each(albumData.songs,function(i,song){
			if(i>0){
				var newRow=tr.clone();
				newRow.find('a.expander').remove();
				newRow.find('td.album a').text('');
				newRow.find('td.artist a').text('');
			}else{
				var newRow=tr;
			}
			newRow.find('td.title a').text(song.name);
			if(i>0){
				lastRow.after(newRow);
			}
			lastRow=newRow;
		});
	},
	hideAlbum:function(artist,album){
		var tr = Collection.parent.find('tr[data-artist="'+artist+'"][data-album="'+album+'"]');
		var albumData=tr.data('albumData');
		tr.first().find('td.title a').text(albumData.songs.length+' '+t('media','songs'));
		tr.find('td.album a.expander').data('expanded',false);
		tr.find('td.album a.expander').removeClass('expanded');
		tr.find('td.album a.expander').text('> ');
		tr.each(function(i,row){
			if(i>0){
				$(row).remove();
			}
		});
	},
	parent:null,
	hide:function(){
		if(Collection.parent){
			Collection.parent.hide();
		}
	},
	registerPlay:function(item){
		if(item){
			var song=Collection.findSong(item.artist,item.album,item.name);
			song.song_playcount++;
		}
	},
	addButtons:function(parent,data){
		buttons = parent.find('.buttons');
		if(buttons.find('.add').length<=0) {
			buttons.prepend('');
		}
		buttons.find('.add').unbind('click');
		buttons.find('.add').click(function(event){
			event.preventDefault();
			PlayList.add(data,true);
			PlayList.render();
		});
	},
	find:function(artistName,albumName,songName){
		if(songName){
			return Collection.findSong(artistName,albumName,songName);
		}else if(albumName){
			return Collection.findAlbum(artistName,albumName);
		}else{
			return Collection.findArtist(artistName);
		}
	},
	findArtist:function(name){
		for(var i=0;i<Collection.artists.length;i++){
			if(Collection.artists[i].name==name){
				return Collection.artists[i];
			}
		}
	},
	findAlbum:function(artistName,albumName){
		var artist=Collection.findArtist(artistName);
		if(artist){
			for(var i=0;i<artist.albums.length;i++){
				if(artist.albums[i].name==albumName){
					return artist.albums[i];
				}
			}
		}
	},
	findSong:function(artistName,albumName,songName){
		var album=Collection.findAlbum(artistName,albumName);
		if(album){
			for(var i=0;i<album.songs.length;i++){
				if(album.songs[i].name==songName){
					return album.songs[i];
				}
			}
		}
	},
	addSong:function(song){
		var artist=false
		var album=false;
		for(var i=0;i<Collection.artists.length;i++){
			if(Collection.artists[i].artist_id==song.song_artist){
				artist=Collection.artists[i];
				for(var j=0;j<artist.albums.length;j++){
					if(artist.albums[j].album_id==song.song_album){
						album=artist.albums[j];
						break;
					}
				}
				break;
			}
		}
		if(!artist){
			artist={artist_id:song.song_artist,artist_name:song.artist,albums:[]};
			Collection.artists.push(artist);
			if(!Collection.parent || Collection.parent.is(":visible")){
				Collection.display();
			}

		}
		if(!album){
			album={album_id:song.song_album,album_name:song.album,album_artist:song.song_artist,songs:[]};
			artist.albums.push(album)
		}
		album.songs.push(song)
	}
}

$(document).ready(function(){
	Collection.parent=$('#collection');
	Collection.load();
	Collection.parent.hide();
	$('#scan input.start').click(function(){
		$('#scan input.start').hide();
		$('#scan input.stop').show();
		$('#scan input.stop').click(function(){
			Scanner.toggle();
		});
		Scanner.scanCollection();
	});
});
<commit_msg>fix event handler after re-expanding an artist in collection view<commit_after>Collection={
	artists:[],
	albums:[],
	songs:[],
	artistsById:{},
	albumsById:{},
	loaded:false,
	loading:false,
	loadedListeners:[],
	load:function(ready){
		if(ready){
			Collection.loadedListeners.push(ready);
		}
		if(!Collection.loading){
			Collection.loading=true;
			$.ajax({
				url: OC.linkTo('media','ajax/api.php')+'?action=get_collection',
				dataType: 'json',
				success: function(data){
					//normalize the data
					for(var i=0;i<data.artists.length;i++){
						var artist=data.artists[i];
						var artistData={name:artist.artist_name,songs:[],albums:[]};
						Collection.artistsById[artist.artist_id]=artistData;
						Collection.artists.push(artistData);
					}
					for(var i=0;i<data.albums.length;i++){
						var album=data.albums[i];
						if(Collection.artistsById[album.album_artist]){
							var artistName=Collection.artistsById[album.album_artist].name;
						}else{
							var artistName='unknown';
						}
						var albumData={name:album.album_name,artist:artistName,songs:[]};
						Collection.albumsById[album.album_id]=albumData;
						Collection.albums.push(albumData);
						if(Collection.artistsById[album.album_artist]){
							Collection.artistsById[album.album_artist].albums.push(albumData);
						}
					}
					for(var i=0;i<data.songs.length;i++){
						var song=data.songs[i];
						if(Collection.artistsById[song.song_artist] && Collection.albumsById[song.song_album]){
							var songData={
								name:song.song_name,
								artist:Collection.artistsById[song.song_artist].name,
								album:Collection.albumsById[song.song_album].name,
								lastPlayed:song.song_lastplayed,
								length:song.song_length,
								path:song.song_path,
								playCount:song.song_playcount,
							};
							Collection.songs.push(songData);
							Collection.artistsById[song.song_artist].songs.push(songData);
							Collection.albumsById[song.song_album].songs.push(songData);
						}
					}

					Collection.artists.sort(function(a,b){
						if(!a.name){
							return -1;
						}
						return a.name.localeCompare(b.name);
					});

					Collection.loaded=true;
					Collection.loading=false;
					for(var i=0;i<Collection.loadedListeners.length;i++){
						Collection.loadedListeners[i]();
					}
					if(data.songs.length==0){
						$('#scan input.start').val(t('media','Scan Collection'));
						$('#scan input.start').click();
					}

				}
			});
		}
	},
	display:function(){
		if(Collection.parent){
			Collection.parent.show();
		}
		if(!Collection.loaded){
			Collection.load(Collection.display)
		}else{
			if(Collection.parent){
				Collection.parent.find('tr:not(.template)').remove();
				var template=Collection.parent.find('tr.template');
				var lastArtist='';
				var lastAlbum='';
				$.each(Collection.artists,function(i,artist){
					if(artist.name && artist.songs.length>0){
						var tr=template.clone().removeClass('template');
						if(artist.songs.length>1){
							tr.find('td.title a').text(artist.songs.length+' '+t('media','songs'));
							tr.find('td.album a').text(artist.albums.length+' '+t('media','albums'));
						}else{
							tr.find('td.title a').text(artist.songs[0].name);
							tr.find('td.album a').text(artist.albums[0].name);
						}
						tr.find('td.artist a').text(artist.name);
						tr.data('artistData',artist);
						tr.find('td.artist a').click(function(event){
							event.preventDefault();
							PlayList.add(artist);
							PlayList.play(0);
							Collection.parent.find('tr').removeClass('active');
							$('tr[data-artist="'+artist.name+'"]').addClass('active');
						});
						if(artist.songs.length>1){
							var expander=$('>');
							expander.data('expanded',false);
							expander.click(function(event){
								var tr=$(this).parent().parent();
								if(expander.data('expanded')){
									Collection.hideArtist(tr.data('artist'));
								}else{
									Collection.showArtist(tr.data('artist'));
								}
							});
						}
						tr.find('td.artist').addClass('buttons');
						Collection.addButtons(tr,artist);
						tr.children('td.artist').append(expander);
						tr.attr('data-artist',artist.name);
						Collection.parent.find('tbody').append(tr);
					}
				});
			}
		}
	},
	showArtist:function(artist){
		var tr=Collection.parent.find('tr[data-artist="'+artist+'"]');
		var lastRow=tr;
		var artist=tr.data('artistData');
		var first=true;
		$.each(artist.albums,function(j,album){
			$.each(album.songs,function(i,song){
				if(first){
					newRow=tr;
				}else{
					var newRow=tr.clone();
					newRow.find('td.artist').text('');
					newRow.find('.expander').remove();
				}
				newRow.find('td.album .expander').remove();
				if(i==0){
					newRow.find('td.album a').text(album.name);
					newRow.find('td.album a').click(function(event){
						event.preventDefault();
						PlayList.add(album);
						PlayList.play(0);
						Collection.parent.find('tr').removeClass('active');
						$('tr[data-album="'+album.name+'"]').addClass('active');
					});
					if(album.songs.length>1){
						var expander=$('v ');
						expander.data('expanded',true);
						expander.click(function(event){
							var tr=$(this).parent().parent();
							if(expander.data('expanded')) {
								Collection.hideAlbum(tr.data('artist'),tr.data('album'));
							} else {
								Collection.showAlbum(tr.data('artist'),tr.data('album'));
							}
						});
						newRow.children('td.album').append(expander);
					}
					Collection.addButtons(newRow,album);
				} else {
					newRow.find('td.album a').text('');
					Collection.addButtons(newRow,song);
				}
				newRow.find('td.title a').text(song.name);
				newRow.find('td.title a').click(function(event){
					event.preventDefault();
					PlayList.add(song);
					PlayList.play(0);
					Collection.parent.find('tr').removeClass('active');
					$('tr[data-title="'+song.name+'"]').addClass('active');
				});
				newRow.attr('data-album',album.name);
				newRow.attr('data-title',song.name);
				newRow.attr('data-artist',artist.name);
				newRow.data('albumData',album);
				if(!first){
					lastRow.after(newRow);
				}
				first=false;
				lastRow=newRow;
			});
		});
		tr.removeClass('collapsed');
		tr.find('td.artist a.expander').data('expanded',true);
		tr.find('td.artist a.expander').addClass('expanded');
		tr.find('td.artist a.expander').text('v');
	},
	hideArtist:function(artist){
		var tr=Collection.parent.find('tr[data-artist="'+artist+'"]');
		var artist=tr.first().data('artistData');
		tr.first().find('td.album a').first().text(artist.albums.length+' '+t('media','albums'));
		tr.first().find('td.album a.expander').remove();
		tr.first().find('td.title a').text(artist.songs.length+' '+t('media','songs'));
		tr.first().find('td.album a').unbind('click');
		tr.first().find('td.title a').unbind('click');
		tr.each(function(i,row){
			if(i>0){
				$(row).remove();
			}
		});
		tr.find('td.artist a.expander').data('expanded',false);
		tr.find('td.artist a.expander').removeClass('expanded');
		tr.find('td.artist a.expander').text('>');
		Collection.addButtons(tr,artist);
	},
	showAlbum:function(artist,album){
		var tr = Collection.parent.find('tr[data-artist="'+artist+'"][data-album="'+album+'"]');
		var lastRow=tr;
		var albumData=tr.data('albumData');
		tr.find('td.album a.expander').data('expanded',true);
		tr.find('td.album a.expander').addClass('expanded');
		tr.find('td.album a.expander').text('v');
		$.each(albumData.songs,function(i,song){
			if(i>0){
				var newRow=tr.clone();
				newRow.find('a.expander').remove();
				newRow.find('td.album a').text('');
				newRow.find('td.artist a').text('');
			}else{
				var newRow=tr;
			}
			newRow.find('td.title a').text(song.name);
			newRow.find('td.title a').click(function(event){
				event.preventDefault();
				PlayList.add(song);
				PlayList.play(0);
				Collection.parent.find('tr').removeClass('active');
				$('tr[data-title="'+song.name+'"]').addClass('active');
			});
			if(i>0){
				lastRow.after(newRow);
			}
			lastRow=newRow;
		});
	},
	hideAlbum:function(artist,album){
		var tr = Collection.parent.find('tr[data-artist="'+artist+'"][data-album="'+album+'"]');
		var albumData=tr.data('albumData');
		tr.first().find('td.title a').text(albumData.songs.length+' '+t('media','songs'));
		tr.find('td.album a.expander').data('expanded',false);
		tr.find('td.album a.expander').removeClass('expanded');
		tr.find('td.album a.expander').text('> ');
		tr.each(function(i,row){
			if(i>0){
				$(row).remove();
			}
		});
	},
	parent:null,
	hide:function(){
		if(Collection.parent){
			Collection.parent.hide();
		}
	},
	registerPlay:function(item){
		if(item){
			var song=Collection.findSong(item.artist,item.album,item.name);
			song.song_playcount++;
		}
	},
	addButtons:function(parent,data){
		buttons = parent.find('.buttons');
		if(buttons.find('.add').length<=0) {
			buttons.prepend('');
		}
		buttons.find('.add').unbind('click');
		buttons.find('.add').click(function(event){
			event.preventDefault();
			PlayList.add(data,true);
			PlayList.render();
		});
	},
	find:function(artistName,albumName,songName){
		if(songName){
			return Collection.findSong(artistName,albumName,songName);
		}else if(albumName){
			return Collection.findAlbum(artistName,albumName);
		}else{
			return Collection.findArtist(artistName);
		}
	},
	findArtist:function(name){
		for(var i=0;i<Collection.artists.length;i++){
			if(Collection.artists[i].name==name){
				return Collection.artists[i];
			}
		}
	},
	findAlbum:function(artistName,albumName){
		var artist=Collection.findArtist(artistName);
		if(artist){
			for(var i=0;i<artist.albums.length;i++){
				if(artist.albums[i].name==albumName){
					return artist.albums[i];
				}
			}
		}
	},
	findSong:function(artistName,albumName,songName){
		var album=Collection.findAlbum(artistName,albumName);
		if(album){
			for(var i=0;i<album.songs.length;i++){
				if(album.songs[i].name==songName){
					return album.songs[i];
				}
			}
		}
	},
	addSong:function(song){
		var artist=false
		var album=false;
		for(var i=0;i<Collection.artists.length;i++){
			if(Collection.artists[i].artist_id==song.song_artist){
				artist=Collection.artists[i];
				for(var j=0;j<artist.albums.length;j++){
					if(artist.albums[j].album_id==song.song_album){
						album=artist.albums[j];
						break;
					}
				}
				break;
			}
		}
		if(!artist){
			artist={artist_id:song.song_artist,artist_name:song.artist,albums:[]};
			Collection.artists.push(artist);
			if(!Collection.parent || Collection.parent.is(":visible")){
				Collection.display();
			}

		}
		if(!album){
			album={album_id:song.song_album,album_name:song.album,album_artist:song.song_artist,songs:[]};
			artist.albums.push(album)
		}
		album.songs.push(song)
	}
}

$(document).ready(function(){
	Collection.parent=$('#collection');
	Collection.load();
	Collection.parent.hide();
	$('#scan input.start').click(function(){
		$('#scan input.start').hide();
		$('#scan input.stop').show();
		$('#scan input.stop').click(function(){
			Scanner.toggle();
		});
		Scanner.scanCollection();
	});
});
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var BROWSERS = []; // for debugging

/** QuickBug Top-Level Object. **/
FOAModel({
  name: 'QBug',
  label: 'Quick Bug',

  properties: [
    {
      name: 'baseURL',
      defaultValue: 'https://code.google.com/p/'
    },
    {
      name: 'user',
      type: 'QUser',
      postSet: function(oldValue, newValue) {
        oldValue && oldValue.removePropertyListener('email', this.onUserUpdate);
        newValue.addPropertyListener('email', this.onUserUpdate);
        this.onUserUpdate();
      }
    },
    {
      name: 'userFuture',
      factory: function() { return afuture(); }
    },
    {
      name: 'persistentContext',
      factory: function() {
        return PersistentContext.create({
          dao: IDBDAO.create({ model: Binding }),
          context: this
        });
      }
    },
    {
      name: 'ProjectNetworkDAO',
      factory: function() {
        var dao = this.X.RestDAO.create({
          url: 'https://www.googleapis.com/projecthosting/v2/projects/',
          model: Project
        });

        dao.buildFindURL = function(key) {
          return this.url + key;
        };

        dao.jsonToObj = function(json) {
          if ( json.members ) {
            for ( var i = 0; i < json.members.length; i++ ) {
              json.members[i] = QIssuePerson.create(json.members[i]);
            }
          }

          if ( json.issuesConfig ) {
            if ( json.issuesConfig.statuses ) {
              for ( i = 0; i < json.issuesConfig.statuses.length; i++ ) {
                json.issuesConfig.statuses[i] =
                  QIssueStatus.create(json.issuesConfig.statuses[i]);
              }
            }

            if ( json.issuesConfig.labels ) {
              for ( i = 0; i < json.issuesConfig.labels.length; i++ ) {
                json.issuesConfig.labels[i] =
                  QIssueLabel.create(json.issuesConfig.labels[i]);
              }
            }
          }
          return this.model.create(json);
        };

          /*
        dao.jsonToObj = function(json) {
          if ( json.author ) json.author = json.author.name;

          return this.model.create(json);
        };
        */

        return dao;
      },
      transient: true
    },

    {
      // Cache of QProject objects
      name: 'projects_',
      factory: function() { return {}; },
      transient: true
    },
    {
      name: 'defaultProjectName',
      defaultValue: 'chromium'
    },
    {
      name: 'authAgent2'
    }
  ],

  methods: {
    init: function(args) {
      this.SUPER(args);
      var self = this;

      this.initOAuth(args && args.authClientId, args && args.authClientSecret);

      this.persistentContext.bindObject('user', QUser)(function(user) {
        self.userFuture.set(user);
        self.refreshUser();
      });
    },

    initOAuth: function(opt_clientId, opt_clientSecret) {
      var jsonpFuture = afuture();
      this.X.ajsonp = function() {
        var args = arguments;
        return function(ret) {
          jsonpFuture.get(function(f) {
            f.apply(undefined, args)(ret);
          });
        };
      };

      this.persistentContext.bindObject('authAgent2', EasyOAuth2, {
        clientId: opt_clientId || '18229540903-ajaqivrvb8vu3c1viaq4drg3847vt9nq.apps.googleusercontent.com',
        clientSecret: opt_clientSecret || 'mbxy7-eZlosojSZgHTRT15o9',
        scopes: [
          "https://www.googleapis.com/auth/userinfo.email",
          "https://www.googleapis.com/auth/projecthosting"
        ]
      })(function(oauth2) {
        jsonpFuture.set((function() {
          var factory = self.X.OAuthXhrFactory.create({
            authAgent: oauth2,
            responseType: "json"
          });

          return function(url, params, opt_method, opt_payload) {
            return function(ret) {
              var xhr = factory.make();
              xhr.responseType = "json";
              return xhr.asend(ret,
                               opt_method ? opt_method : "GET",
                               url + (params ? '?' + params.join('&') : ''),
                               opt_payload);
            };
          };
        })());
      });
    },

    refreshUser: function() {
      var self = this;
      this.userFuture.get(function(user) {
        self.X.ajsonp("https://www.googleapis.com/oauth2/v1/userinfo", ["alt=json"])(
          function(response) {
            if ( response ) {
              user.email = response.email;
            }
          });

        self.X.ajsonp("https://www.googleapis.com/projecthosting/v2/users/me")(
          function(response) {
            response && user.copyFrom(response);
          });
      });
    },

    findProject: function(projectName, sink) {
      if ( this.projects_[projectName] ) {
        sink.put(this.projects_[projectName]);
        return;
      }

      var self = this;

      this.ProjectNetworkDAO.find(projectName, {
        __proto__: sink,
        put: function(project) {
          var p = self.X.QProject.create({qbug: self, project: project});

          self.projects_[projectName] = p;

          sink.put(p);
        },
        error: function() {
          sink.error && sink.error();
        }
      });
    },

    getDefaultProject: function(sink) {
      this.findProject(this.defaultProjectName, sink);
    },

    launchBrowser: function(opt_projectName, opt_url) {
      var self = this;
      this.userFuture.get(function(user) {
        self.findProject(opt_projectName || user.defaultProject, {
          put: function(p) {
            console.log('launch: ', p);
            p.launchBrowser(opt_url);
          },
          error: function() {
            metricsSrv.sendException('Failed to find default project.');
            console.warn("Couldn't find default project, default to ", self.defaultProjectName);
            if ( opt_projectName === self.defaultProjectName) {
              // TODO: Some sort of error view that we couldn't find the project.
              console.error("Couldn't find a project, you're probably offline.");
              metricsSrv.sendException('Failed to find project.', true);
              return;
            }
            self.launchBrowser(self.defaultProjectName);
          },
        });
      });
    }
  },

  listeners: [
    {
      name: 'onUserUpdate',
      code: function() { QueryParser.ME = this.user.email; }
    }
  ]
});
<commit_msg>Create projects in their own sub-context.<commit_after>/**
 * @license
 * Copyright 2014 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var BROWSERS = []; // for debugging

/** QuickBug Top-Level Object. **/
FOAModel({
  name: 'QBug',
  label: 'Quick Bug',

  properties: [
    {
      name: 'baseURL',
      defaultValue: 'https://code.google.com/p/'
    },
    {
      name: 'user',
      type: 'QUser',
      postSet: function(oldValue, newValue) {
        oldValue && oldValue.removePropertyListener('email', this.onUserUpdate);
        newValue.addPropertyListener('email', this.onUserUpdate);
        this.onUserUpdate();
      }
    },
    {
      name: 'userFuture',
      factory: function() { return afuture(); }
    },
    {
      name: 'persistentContext',
      factory: function() {
        return PersistentContext.create({
          dao: IDBDAO.create({ model: Binding }),
          context: this
        });
      }
    },
    {
      name: 'ProjectNetworkDAO',
      factory: function() {
        var dao = this.X.RestDAO.create({
          url: 'https://www.googleapis.com/projecthosting/v2/projects/',
          model: Project
        });

        dao.buildFindURL = function(key) {
          return this.url + key;
        };

        dao.jsonToObj = function(json) {
          if ( json.members ) {
            for ( var i = 0; i < json.members.length; i++ ) {
              json.members[i] = QIssuePerson.create(json.members[i]);
            }
          }

          if ( json.issuesConfig ) {
            if ( json.issuesConfig.statuses ) {
              for ( i = 0; i < json.issuesConfig.statuses.length; i++ ) {
                json.issuesConfig.statuses[i] =
                  QIssueStatus.create(json.issuesConfig.statuses[i]);
              }
            }

            if ( json.issuesConfig.labels ) {
              for ( i = 0; i < json.issuesConfig.labels.length; i++ ) {
                json.issuesConfig.labels[i] =
                  QIssueLabel.create(json.issuesConfig.labels[i]);
              }
            }
          }
          return this.model.create(json);
        };

          /*
        dao.jsonToObj = function(json) {
          if ( json.author ) json.author = json.author.name;

          return this.model.create(json);
        };
        */

        return dao;
      },
      transient: true
    },

    {
      // Cache of QProject objects
      name: 'projects_',
      factory: function() { return {}; },
      transient: true
    },
    {
      name: 'defaultProjectName',
      defaultValue: 'chromium'
    },
    {
      name: 'authAgent2'
    }
  ],

  methods: {
    init: function(args) {
      this.SUPER(args);
      var self = this;

      this.initOAuth(args && args.authClientId, args && args.authClientSecret);

      this.persistentContext.bindObject('user', QUser)(function(user) {
        self.userFuture.set(user);
        self.refreshUser();
      });
    },

    initOAuth: function(opt_clientId, opt_clientSecret) {
      var jsonpFuture = afuture();
      this.X.ajsonp = function() {
        var args = arguments;
        return function(ret) {
          jsonpFuture.get(function(f) {
            f.apply(undefined, args)(ret);
          });
        };
      };

      this.persistentContext.bindObject('authAgent2', EasyOAuth2, {
        clientId: opt_clientId || '18229540903-ajaqivrvb8vu3c1viaq4drg3847vt9nq.apps.googleusercontent.com',
        clientSecret: opt_clientSecret || 'mbxy7-eZlosojSZgHTRT15o9',
        scopes: [
          "https://www.googleapis.com/auth/userinfo.email",
          "https://www.googleapis.com/auth/projecthosting"
        ]
      })(function(oauth2) {
        jsonpFuture.set((function() {
          var factory = self.X.OAuthXhrFactory.create({
            authAgent: oauth2,
            responseType: "json"
          });

          return function(url, params, opt_method, opt_payload) {
            return function(ret) {
              var xhr = factory.make();
              xhr.responseType = "json";
              return xhr.asend(ret,
                               opt_method ? opt_method : "GET",
                               url + (params ? '?' + params.join('&') : ''),
                               opt_payload);
            };
          };
        })());
      });
    },

    refreshUser: function() {
      var self = this;
      this.userFuture.get(function(user) {
        self.X.ajsonp("https://www.googleapis.com/oauth2/v1/userinfo", ["alt=json"])(
          function(response) {
            if ( response ) {
              user.email = response.email;
            }
          });

        self.X.ajsonp("https://www.googleapis.com/projecthosting/v2/users/me")(
          function(response) {
            response && user.copyFrom(response);
          });
      });
    },

    findProject: function(projectName, sink) {
      if ( this.projects_[projectName] ) {
        sink.put(this.projects_[projectName]);
        return;
      }

      var self = this;

      this.ProjectNetworkDAO.find(projectName, {
        __proto__: sink,
        put: function(project) {
          var p = self.X.sub().QProject.create({qbug: self, project: project});

          self.projects_[projectName] = p;

          sink.put(p);
        },
        error: function() {
          sink.error && sink.error();
        }
      });
    },

    getDefaultProject: function(sink) {
      this.findProject(this.defaultProjectName, sink);
    },

    launchBrowser: function(opt_projectName, opt_url) {
      var self = this;
      this.userFuture.get(function(user) {
        self.findProject(opt_projectName || user.defaultProject, {
          put: function(p) {
            console.log('launch: ', p);
            p.launchBrowser(opt_url);
          },
          error: function() {
            metricsSrv.sendException('Failed to find default project.');
            console.warn("Couldn't find default project, default to ", self.defaultProjectName);
            if ( opt_projectName === self.defaultProjectName) {
              // TODO: Some sort of error view that we couldn't find the project.
              console.error("Couldn't find a project, you're probably offline.");
              metricsSrv.sendException('Failed to find project.', true);
              return;
            }
            self.launchBrowser(self.defaultProjectName);
          },
        });
      });
    }
  },

  listeners: [
    {
      name: 'onUserUpdate',
      code: function() { QueryParser.ME = this.user.email; }
    }
  ]
});
<|endoftext|>


<commit_before>import Ember from 'ember';

export default Ember.Route.extend({
  titleToken: 'Add a student',

  model() {
    return this.store.createRecord('student');
  },

  resetController(controller, isExiting) {
    if (isExiting) {
      controller.set('didValidate', false);
      controller.set('errorMessage', false);
    }
  }
});
<commit_msg>Handle useless student records upon leaving the form route.<commit_after>import Ember from 'ember';

export default Ember.Route.extend({
  titleToken: 'Add a student',

  model() {
    return this.store.createRecord('student');
  },

  actions: {
    willTransition() {
      // Clean out any unsaved students from the store.
      const model = this.modelFor(this.routeName);
      model.rollbackAttributes();
    }
  },

  resetController(controller, isExiting) {
    if (isExiting) {
      controller.set('didValidate', false);
      controller.set('errorMessage', false);
    }
  }
});
<|endoftext|>


<commit_before>var results           = [];
var paginationResults;

var previousResults = document.getElementById("previousResults");
var nextResults     = document.getElementById("nextResults");

var draggableMarker;

previousResults.addEventListener('click', function() {
    paginationResults -= 1;
    renderResults();
})
nextResults.addEventListener('click', function() {
    paginationResults += 1;
    renderResults();
})

function renderResults() {
    var $proposal = $('#proposal');
    var $proposalMessage = $('#proposal-message');

    var $searchStreet = $('#input-search');
    var $searchMunicipality = $('#input-ward');

    $proposal.empty();
    var features = [];

    var iconIdx = 0;
    for(var i=paginationResults*5, length=results.length; i<length && features.length<5; i++) {
        var address = results[i].address;
        var pos = results[i].point;

        var newAddress = new AddressResult(pos.x, pos.y, address, iconIdx++);
        $proposal.append(newAddress.render());

        // Create feature on vectore layer
        var feature = new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.Point(pos.x, pos.y),
                { 'additionalInfo' :
                    {
                        'streetName'   : address.street.name,
                        'number'       : address.number,
                        'postCode'     : address.street.postCode,
                        'municipality' : address.street.municipality
                    }
                },
                {
                    externalGraphic: newAddress.iconSrc(),
                    graphicWidth: 25,
                    graphicHeight: 32,
                    graphicYOffset: -32
                }
            );
        features.push(feature);

        // Define message if needed
        if ($searchMunicipality.val()) {
            $proposalMessage.html("Cette rue n'est pas répertoriée dans cette commune");
        } else if ($searchStreet.val().toLowerCase() == address.street.name.toLowerCase()) {
            $proposalMessage.html("Cette rue existe dans plusieurs communes, merci de préciser");
        }
    }

    // Mask/display pagination buttons
    if (paginationResults == 0) {
        previousResults.hidden = true;
    } else {
        previousResults.hidden = false;
    }

    if (results.length >= paginationResults * 5 + 6) {
        nextResults.hidden = false;
    } else {
        nextResults.hidden = true;
    }

    // Add features to layer
    cleanMap();
    fms.currentMap.homepageMarkersLayer.addFeatures(features);

    // Zoom to markers
    var markersBound = fms.currentMap.homepageMarkersLayer.getDataExtent();
    fms.currentMap.map.zoomToExtent(markersBound);

    // Show/hide proposal and message
    $proposalContainer = $('#proposal-container');
    $proposalContainer.slideDown();

    if ($proposalMessage.html()) {
        map.classList.add("map-big-message");
        $proposalMessage.slideDown();
    } else {
        map.classList.remove("map-big-message");
        map.classList.add("map-big");
        $proposalMessage.slideUp();
    }

}
function AddressResult(x, y, address, idx)
{
    var self = this;

    this.x = x;
    this.y = y;
    this.el = document.createElement('li');

    this.address = address;

    this.render = function() {
        this.el.innerHTML = '
' + this.address.street.name +
                            '
' +
                            '' + this.address.street.postCode + ' ' + this.address.street.municipality + '' +
                            '
';
        this.el.addEventListener('click', this.onclick);
        return  this.el;
    };

    this.iconSrc = function() {
        return "/static/images/marker/marker-" + idx + ".png";
    },

    this.onclick = function(event) {
        additionalInfo = {
            'streetName'   : self.address.street.name,
            'number'       : self.address.number,
            'postCode'     : self.address.street.postCode,
            'municipality' : self.address.street.municipality
        }

        initDragMarker(self.x, self.y, additionalInfo);
    }
}

function getAddressFromPoint(lang, x, y) {
    var self = this;
    $.ajax({
        url: 'http://service.gis.irisnet.be/urbis/Rest/Localize/getaddressfromxy',
        type:'POST',
        dataType:'jsonp',
        data: {
            json: ['{',
                '"language": "' + lang + '",',
                '"point":{x:' + x + ',y:' + y + '}',
                '}'].join('\n')
        },
        success:function(response)
        {
            cleanMap();

            var street = response.result.address.street.name;
            var number = response.result.address.number;
            var postCode = response.result.address.street.postCode;
            var municipality = zipcodes[postCode].commune;

            var x = response.result.point.x;
            var y = response.result.point.y;

            //var popupContent = "
" + street + ", " + number;
            // Convert the point and url for google street view
            var pointStreetView = UtilGeolocation.convertCoordinatesToWGS84(x, y);
            var streetBiewLink = 'https://maps.google.be/maps?q=' + pointStreetView.y +','+ pointStreetView.x +'&layer=c&z=17&iwloc=A&sll='+ pointStreetView.y + ',' + pointStreetView.x + '&cbp=13,240.6,0,0,0&cbll=' + pointStreetView.y + ',' + pointStreetView.x;
            var popupContent = "
Déplacez-moi à l'adresse exacte
";
            popupContent += "
" + street + ", " + number;
            popupContent += "
" + postCode + " " + municipality + "
";

            if (NEXT_PAGE_URL) {
                popupContent += "C'est ici !";
            }
            popupContent += '
Street View
';

            var popup = new OpenLayers.Popup(
                "popup",
                new OpenLayers.LonLat(draggableMarker.components[0].x, draggableMarker.components[0].y),
                new OpenLayers.Size(200,150),
                popupContent,
                true
            );
            popup.panMapIfOutOfView = true;

            fms.currentMap.map.addPopup(popup);
        },
        error:function(response)
        {
            // Error
            //~ var msg = 'Error: ' + response.status;
            //~ if(response.status == 'error') {
                //~ msg = 'Unable to locate this address';
            //~ }
        }
    });
}

function initDragMarker(x, y, additionalInfo) {
        cleanMap();

        // Remove message info
        var $map = $('#map');
        map.classList.remove("map-big-message");
        map.classList.add("map-big");

        var $proposalMessage = $('#proposal-message');
        $proposalMessage.slideUp();

        draggableMarker = fms.currentMap.addDraggableMarker(x, y);
        fms.currentMap.centerOnDraggableMarker();
        fms.currentMap.map.zoomTo(6);

        var popupContent = "
Déplacez-moi à l'adresse exacte
";

        if (additionalInfo) {
            popupContent += "
" + additionalInfo.streetName + ", " + additionalInfo.number;
            popupContent += "
" + additionalInfo.postCode + " " + additionalInfo.municipality + "
";

            if (additionalInfo.number) {
                popupContent += "C'est ici !";
                popupContent += '
Street View
';
            }
        }

        var popup = new OpenLayers.Popup(
            "popup",
            new OpenLayers.LonLat(x, y),
            new OpenLayers.Size(200,150),
            popupContent,
            true
        );
        popup.panMapIfOutOfView = true;

        fms.currentMap.map.addPopup(popup);
}

function cleanMap() {
    // Remove all popups
    while(fms.currentMap.map.popups.length) {
         fms.currentMap.map.removePopup(fms.currentMap.map.popups[0]);
    }

    // Remove all features
    if (fms.currentMap.markersLayer) {
        fms.currentMap.markersLayer.destroyFeatures();
    }
    if (fms.currentMap.homepageMarkersLayer) {
        fms.currentMap.homepageMarkersLayer.destroyFeatures();
    }

    // Hide results
    $proposalContainer = $('#proposal-container');
    $proposalContainer.slideUp();
}

$(function(){

    var $searchStreet = $('#input-search');
    var $searchStreetNumber = $('#input-streetnumber');
    var $searchMunicipality = $('#input-ward');
    var $searchAddressForm = $('#search-address-form');
    var $searchTicketForm = $('#search-ticket-form');
    var $searchButton = $('#widget-search-button');
    var $searchTicketButton = $('#widget-search-ticket-button');
    var $proposal = $('#proposal');
    var $proposalContainer = $('#proposal-container');
    var $proposalMessage = $('#proposal-message');

    var $map = $('#map');
    $map.bind('markermoved',function(evt,point) {
        getAddressFromPoint(LANGUAGE_CODE, point.x, point.y);
    });

    $searchTicketForm.submit(function(event){
        event.preventDefault();
        var searchValue = $('#input-ticket-search').val();

        if (searchValue && searchValue.length > 0) {
            //Get current language
            var currentLng = 'en';
            if (window.location.href.indexOf('/nl/') != -1) {
                currentLng = 'nl';
            } else if (window.location.href.indexOf('/fr/') != -1) {
                currentLng = 'fr'
            }
            if (window.location.href.indexOf('pro') != -1) {
                window.location = "/"+currentLng+"/pro/report/search?report_id="+searchValue;
            } else {
                window.location = "/"+currentLng+"/report/search?report_id="+searchValue;
            }
        }
    });

    $searchAddressForm.submit(function(event){
        event.preventDefault();

        paginationResults = 0;

        var searchValue = $searchStreet.val();
        $proposalContainer.slideUp();

        if (!$searchStreet.val()) {
            $searchTicketForm.show();
            return;
        }

        var btnLocalizeviamap = document.getElementById('btn-localizeviamap');
        if (btnLocalizeviamap) {
            btnLocalizeviamap.parentNode.removeChild(btnLocalizeviamap);
        }

        $searchStreet.addClass('loading');
        $searchButton.prop('disabled',true);
        $.ajax({
            url: URBIS_URL + 'service/urbis/Rest/Localize/getaddressesfields',
            dataType:'jsonp',
            data:{
                json:'{"language": "' + LANGUAGE_CODE + '",' +
                '"address": {' +
                    '"street": {' +
                        '"name": "' + $searchStreet.val().replace("\"","\\\"") + '",' +
                        '"postcode": "' + $searchMunicipality.val().replace("\"","\\\"") + '"' +
                    '},"number": "' + $searchStreetNumber.val() + '"' +
                '}}'
            }
        }).success(function(response){
            if(response.status == 'success' && response.result.length > 0)
            {
                var map = document.getElementById('map');
                var mapViewPort = document.getElementById('OpenLayers.Map_4_OpenLayers_ViewPort');

                cleanMap();

                $searchStreet.removeClass('loading');
                $searchButton.prop('disabled',false);
                $proposalMessage.empty();

                // Urbis response 1 result
                if(response.result.length == 1) {
                    var pos    = response.result[0].point;
                    var address = response.result[0].address;

                    additionalInfo = {
                        'streetName'   : address.street.name,
                        'number'       : address.number,
                        'postCode'     : address.street.postCode,
                        'municipality' : address.street.municipality
                    }

                    initDragMarker(pos.x, pos.y, additionalInfo);

                    map.classList.remove("map-big-message");
                    map.classList.add("map-big");
                }
                // Urbis response many results
                else {
                    features = [];

                    results = response.result;
                    document.getElementById('numberResults').innerHTML = results.length;

                    if (!fms.currentMap.homepageMarkersLayer) {
                        // Create vector layer
                        fms.currentMap.homepageMarkersLayer = new OpenLayers.Layer.Vector("Overlay");

                        // Add layer to map
                        fms.currentMap.map.addLayer(fms.currentMap.homepageMarkersLayer);

                        // Function to bind selector to initDragMarker
                        function bindClick(feature) {
                            var x = feature.geometry.x;
                            var y = feature.geometry.y;

                            initDragMarker(x, y, feature.attributes.additionalInfo);
                        }

                        // Add the selector control to the vectorLayer
                        var clickCtrl = new OpenLayers.Control.SelectFeature(fms.currentMap.homepageMarkersLayer, { onSelect: bindClick });
                        fms.currentMap.map.addControl(clickCtrl);
                        clickCtrl.activate();
                    }

                    renderResults();

                }
            }
            else
            {
                $searchTicketForm.show();
                $searchStreet.removeClass('loading');
                $searchButton.prop('disabled',false);
                if(response.status == "noresult" || response.status == "success")
                {
                    $proposalMessage.html('No corresponding address has been found').slideDown();
                }
                else
                {
                    $proposalMessage.html('' + response.status + '').slideDown();
                }
            }
        }).error(function(xhr,msg,error){
            $searchStreet.removeClass('loading');
            $searchButton.prop('disabled',false);

            $proposalMessage.html('Unexpected error.').slideDown();
        });
    });

    $searchAddressForm.submit();
});

(function() {

    var streetKeywords = document.getElementById('input-search');
    var postalCode = document.getElementById('input-ward');
    var searchBtn = document.getElementById('widget-search-button')

    function enableSearch() {
        var enableSearchBtn = false;

        if (streetKeywords.value) {
            enableSearchBtn = true;
        }

        searchBtn.disabled = !enableSearchBtn;
    }

    function municipalityChange() {
        enableSearch();

        if ( !(streetKeywords.value) && (postalCode.value) ) {
            alert('middle of municipality : ' + postalCode.value);
        }
    }
    // Enable search button if one of fields contain a value
    streetKeywords.addEventListener('keyup', enableSearch);
    streetKeywords.addEventListener('change', enableSearch);
    postalCode.addEventListener('change', municipalityChange);

})(document);

// Localize report with map
(function() {

    var btnLocalizeviamap = document.getElementById('btn-localizeviamap');

    btnLocalizeviamap.addEventListener("click", function() {
        // Hard code center of map (~same value than fms.currentMap.map.getCenter() but as x,y and not lat,lon)
        initDragMarker(148894,170714);
        fms.currentMap.map.zoomTo(2);

        btnLocalizeviamap.parentNode.removeChild(btnLocalizeviamap);
    });

})(document);
<commit_msg>fix unit tests + add reject report unit test<commit_after>var results           = [];
var paginationResults;

var previousResults = document.getElementById("previousResults");
var nextResults     = document.getElementById("nextResults");

var draggableMarker;

previousResults.addEventListener('click', function() {
    paginationResults -= 1;
    renderResults();
})
nextResults.addEventListener('click', function() {
    paginationResults += 1;
    renderResults();
})

function renderResults() {
    var $proposal = $('#proposal');
    var $proposalMessage = $('#proposal-message');

    var $searchStreet = $('#input-search');
    var $searchMunicipality = $('#input-ward');

    $proposal.empty();
    var features = [];

    var iconIdx = 0;
    for(var i=paginationResults*5, length=results.length; i<length && features.length<5; i++) {
        var address = results[i].address;
        var pos = results[i].point;

        var newAddress = new AddressResult(pos.x, pos.y, address, iconIdx++);
        $proposal.append(newAddress.render());

        // Create feature on vectore layer
        var feature = new OpenLayers.Feature.Vector(
                new OpenLayers.Geometry.Point(pos.x, pos.y),
                { 'additionalInfo' :
                    {
                        'streetName'   : address.street.name,
                        'number'       : address.number,
                        'postCode'     : address.street.postCode,
                        'municipality' : address.street.municipality
                    }
                },
                {
                    externalGraphic: newAddress.iconSrc(),
                    graphicWidth: 25,
                    graphicHeight: 32,
                    graphicYOffset: -32
                }
            );
        features.push(feature);

        // Define message if needed
        if ($searchMunicipality.val()) {
            $proposalMessage.html("Cette rue n'est pas répertoriée dans cette commune");
        } else if ($searchStreet.val().toLowerCase() == address.street.name.toLowerCase()) {
            $proposalMessage.html("Cette rue existe dans plusieurs communes, merci de préciser");
        }
    }

    // Mask/display pagination buttons
    if (paginationResults == 0) {
        previousResults.hidden = true;
    } else {
        previousResults.hidden = false;
    }

    if (results.length >= paginationResults * 5 + 6) {
        nextResults.hidden = false;
    } else {
        nextResults.hidden = true;
    }

    // Add features to layer
    cleanMap();
    fms.currentMap.homepageMarkersLayer.addFeatures(features);

    // Zoom to markers
    var markersBound = fms.currentMap.homepageMarkersLayer.getDataExtent();
    fms.currentMap.map.zoomToExtent(markersBound);

    // Show/hide proposal and message
    $proposalContainer = $('#proposal-container');
    $proposalContainer.slideDown();

    if ($proposalMessage.html()) {
        map.classList.add("map-big-message");
        $proposalMessage.slideDown();
    } else {
        map.classList.remove("map-big-message");
        map.classList.add("map-big");
        $proposalMessage.slideUp();
    }

}
function AddressResult(x, y, address, idx)
{
    var self = this;

    this.x = x;
    this.y = y;
    this.el = document.createElement('li');

    this.address = address;

    this.render = function() {
        this.el.innerHTML = '
' + this.address.street.name +
                            '
' +
                            '' + this.address.street.postCode + ' ' + this.address.street.municipality + '' +
                            '
';
        this.el.addEventListener('click', this.onclick);
        return  this.el;
    };

    this.iconSrc = function() {
        return "/static/images/marker/marker-" + idx + ".png";
    },

    this.onclick = function(event) {
        additionalInfo = {
            'streetName'   : self.address.street.name,
            'number'       : self.address.number,
            'postCode'     : self.address.street.postCode,
            'municipality' : self.address.street.municipality
        }

        initDragMarker(self.x, self.y, additionalInfo);
    }
}

function getAddressFromPoint(lang, x, y) {
    var self = this;
    $.ajax({
        url: 'http://service.gis.irisnet.be/urbis/Rest/Localize/getaddressfromxy',
        type:'POST',
        dataType:'jsonp',
        data: {
            json: ['{',
                '"language": "' + lang + '",',
                '"point":{x:' + x + ',y:' + y + '}',
                '}'].join('\n')
        },
        success:function(response)
        {
            //Fix problem with postcode 1041
            if (response.result.address.street.postCode === "1041") {
                response.result.address.street.postCode = "1040";
            }

            cleanMap();

            var street = response.result.address.street.name;
            var number = response.result.address.number;
            var postCode = response.result.address.street.postCode;
            var municipality = zipcodes[postCode].commune;

            var x = response.result.point.x;
            var y = response.result.point.y;

            //var popupContent = "
" + street + ", " + number;
            // Convert the point and url for google street view
            var pointStreetView = UtilGeolocation.convertCoordinatesToWGS84(x, y);
            var streetBiewLink = 'https://maps.google.be/maps?q=' + pointStreetView.y +','+ pointStreetView.x +'&layer=c&z=17&iwloc=A&sll='+ pointStreetView.y + ',' + pointStreetView.x + '&cbp=13,240.6,0,0,0&cbll=' + pointStreetView.y + ',' + pointStreetView.x;
            var popupContent = "
Déplacez-moi à l'adresse exacte
";
            popupContent += "
" + street + ", " + number;
            popupContent += "
" + postCode + " " + municipality + "
";

            if (NEXT_PAGE_URL) {
                popupContent += "C'est ici !";
            }
            popupContent += '
Street View
';

            var popup = new OpenLayers.Popup(
                "popup",
                new OpenLayers.LonLat(draggableMarker.components[0].x, draggableMarker.components[0].y),
                new OpenLayers.Size(200,150),
                popupContent,
                true
            );
            popup.panMapIfOutOfView = true;

            fms.currentMap.map.addPopup(popup);
        },
        error:function(response)
        {
            // Error
            //~ var msg = 'Error: ' + response.status;
            //~ if(response.status == 'error') {
                //~ msg = 'Unable to locate this address';
            //~ }
        }
    });
}

function initDragMarker(x, y, additionalInfo) {
        cleanMap();

        // Remove message info
        var $map = $('#map');
        map.classList.remove("map-big-message");
        map.classList.add("map-big");

        var $proposalMessage = $('#proposal-message');
        $proposalMessage.slideUp();

        draggableMarker = fms.currentMap.addDraggableMarker(x, y);
        fms.currentMap.centerOnDraggableMarker();
        fms.currentMap.map.zoomTo(6);

        var popupContent = "
Déplacez-moi à l'adresse exacte
";

        if (additionalInfo) {
            popupContent += "
" + additionalInfo.streetName + ", " + additionalInfo.number;
            popupContent += "
" + additionalInfo.postCode + " " + additionalInfo.municipality + "
";

            if (additionalInfo.number) {
                popupContent += "C'est ici !";
                popupContent += '
Street View
';
            }
        }

        var popup = new OpenLayers.Popup(
            "popup",
            new OpenLayers.LonLat(x, y),
            new OpenLayers.Size(200,150),
            popupContent,
            true
        );
        popup.panMapIfOutOfView = true;

        fms.currentMap.map.addPopup(popup);
}

function cleanMap() {
    // Remove all popups
    while(fms.currentMap.map.popups.length) {
         fms.currentMap.map.removePopup(fms.currentMap.map.popups[0]);
    }

    // Remove all features
    if (fms.currentMap.markersLayer) {
        fms.currentMap.markersLayer.destroyFeatures();
    }
    if (fms.currentMap.homepageMarkersLayer) {
        fms.currentMap.homepageMarkersLayer.destroyFeatures();
    }

    // Hide results
    $proposalContainer = $('#proposal-container');
    $proposalContainer.slideUp();
}

$(function(){

    var $searchStreet = $('#input-search');
    var $searchStreetNumber = $('#input-streetnumber');
    var $searchMunicipality = $('#input-ward');
    var $searchAddressForm = $('#search-address-form');
    var $searchTicketForm = $('#search-ticket-form');
    var $searchButton = $('#widget-search-button');
    var $searchTicketButton = $('#widget-search-ticket-button');
    var $proposal = $('#proposal');
    var $proposalContainer = $('#proposal-container');
    var $proposalMessage = $('#proposal-message');

    var $map = $('#map');
    $map.bind('markermoved',function(evt,point) {
        getAddressFromPoint(LANGUAGE_CODE, point.x, point.y);
    });

    $searchTicketForm.submit(function(event){
        event.preventDefault();
        var searchValue = $('#input-ticket-search').val();

        if (searchValue && searchValue.length > 0) {
            //Get current language
            var currentLng = 'en';
            if (window.location.href.indexOf('/nl/') != -1) {
                currentLng = 'nl';
            } else if (window.location.href.indexOf('/fr/') != -1) {
                currentLng = 'fr'
            }
            if (window.location.href.indexOf('pro') != -1) {
                window.location = "/"+currentLng+"/pro/report/search?report_id="+searchValue;
            } else {
                window.location = "/"+currentLng+"/report/search?report_id="+searchValue;
            }
        }
    });

    $searchAddressForm.submit(function(event){
        event.preventDefault();

        paginationResults = 0;

        var searchValue = $searchStreet.val();
        $proposalContainer.slideUp();

        if (!$searchStreet.val()) {
            $searchTicketForm.show();
            return;
        }

        var btnLocalizeviamap = document.getElementById('btn-localizeviamap');
        if (btnLocalizeviamap) {
            btnLocalizeviamap.parentNode.removeChild(btnLocalizeviamap);
        }

        $searchStreet.addClass('loading');
        $searchButton.prop('disabled',true);
        $.ajax({
            url: URBIS_URL + 'service/urbis/Rest/Localize/getaddressesfields',
            dataType:'jsonp',
            data:{
                json:'{"language": "' + LANGUAGE_CODE + '",' +
                '"address": {' +
                    '"street": {' +
                        '"name": "' + $searchStreet.val().replace("\"","\\\"") + '",' +
                        '"postcode": "' + $searchMunicipality.val().replace("\"","\\\"") + '"' +
                    '},"number": "' + $searchStreetNumber.val() + '"' +
                '}}'
            }
        }).success(function(response){
            if(response.status == 'success' && response.result.length > 0)
            {
                var map = document.getElementById('map');
                var mapViewPort = document.getElementById('OpenLayers.Map_4_OpenLayers_ViewPort');

                cleanMap();

                $searchStreet.removeClass('loading');
                $searchButton.prop('disabled',false);
                $proposalMessage.empty();

                // Urbis response 1 result
                if(response.result.length == 1) {
                    var pos    = response.result[0].point;
                    var address = response.result[0].address;

                    additionalInfo = {
                        'streetName'   : address.street.name,
                        'number'       : address.number,
                        'postCode'     : address.street.postCode,
                        'municipality' : address.street.municipality
                    }

                    initDragMarker(pos.x, pos.y, additionalInfo);

                    map.classList.remove("map-big-message");
                    map.classList.add("map-big");
                }
                // Urbis response many results
                else {
                    features = [];

                    results = response.result;
                    document.getElementById('numberResults').innerHTML = results.length;

                    if (!fms.currentMap.homepageMarkersLayer) {
                        // Create vector layer
                        fms.currentMap.homepageMarkersLayer = new OpenLayers.Layer.Vector("Overlay");

                        // Add layer to map
                        fms.currentMap.map.addLayer(fms.currentMap.homepageMarkersLayer);

                        // Function to bind selector to initDragMarker
                        function bindClick(feature) {
                            var x = feature.geometry.x;
                            var y = feature.geometry.y;

                            initDragMarker(x, y, feature.attributes.additionalInfo);
                        }

                        // Add the selector control to the vectorLayer
                        var clickCtrl = new OpenLayers.Control.SelectFeature(fms.currentMap.homepageMarkersLayer, { onSelect: bindClick });
                        fms.currentMap.map.addControl(clickCtrl);
                        clickCtrl.activate();
                    }

                    renderResults();

                }
            }
            else
            {
                $searchTicketForm.show();
                $searchStreet.removeClass('loading');
                $searchButton.prop('disabled',false);
                if(response.status == "noresult" || response.status == "success")
                {
                    $proposalMessage.html('No corresponding address has been found').slideDown();
                }
                else
                {
                    $proposalMessage.html('' + response.status + '').slideDown();
                }
            }
        }).error(function(xhr,msg,error){
            $searchStreet.removeClass('loading');
            $searchButton.prop('disabled',false);

            $proposalMessage.html('Unexpected error.').slideDown();
        });
    });

    $searchAddressForm.submit();
});

(function() {

    var streetKeywords = document.getElementById('input-search');
    var postalCode = document.getElementById('input-ward');
    var searchBtn = document.getElementById('widget-search-button')

    function enableSearch() {
        var enableSearchBtn = false;

        if (streetKeywords.value) {
            enableSearchBtn = true;
        }

        searchBtn.disabled = !enableSearchBtn;
    }

    function municipalityChange() {
        enableSearch();

        if ( !(streetKeywords.value) && (postalCode.value) ) {
            alert('middle of municipality : ' + postalCode.value);
        }
    }
    // Enable search button if one of fields contain a value
    streetKeywords.addEventListener('keyup', enableSearch);
    streetKeywords.addEventListener('change', enableSearch);
    postalCode.addEventListener('change', municipalityChange);

})(document);

// Localize report with map
(function() {

    var btnLocalizeviamap = document.getElementById('btn-localizeviamap');

    btnLocalizeviamap.addEventListener("click", function() {
        // Hard code center of map (~same value than fms.currentMap.map.getCenter() but as x,y and not lat,lon)
        initDragMarker(148894,170714);
        fms.currentMap.map.zoomTo(2);

        btnLocalizeviamap.parentNode.removeChild(btnLocalizeviamap);
    });

})(document);
<|endoftext|>