<commit_before>/**
 *	@author bh-lay
 *	@github https://github.com/bh-lay/uploader
 *  @updata 2014-3-13 21:08
 *
 */
window.util = window.util || {};
/**
 * until.drag(handle_dom,dom,fn);
 */
(function uploaderClosure(exports){
	var staticID = 0;
	var upCnt_tpl = ['

'].join('');
	var up_tpl = ['
',
		'',
		'<form method="post" action="{action}" enctype="multipart/form-data" name="uploader" target="uploader{ID}">',
			//请选择图片
			'<input name="{fileinputname}" type="file" multiple="multiple" class="uploader_btn" title="\u8BF7\u9009\u62E9\u56FE\u7247"/>',
			'{data}',
		'</form>',
	'
'].join('');

	var input_tpl = '<input type="hidden" name="{name}" value="{value}" />';

	var up_css = [''].join('');

	//创建工作环境
	var global_cnt = $(upCnt_tpl);

	$('body').append(global_cnt);
	$('head').append(up_css);

	//iframe加载事件监听方法
	function iframe_load(iframe,load){
		if (iframe.attachEvent){
			iframe.attachEvent("onload", function(){
				load&&load.call(iframe.contentDocument);
			});
		}else{
			iframe.onload = function(){
				load&&load.call(iframe.contentDocument);
			};
		}
	}
	//创建新的html
	function buildDom(){
		var this_up = this;
		var data_html = '';
		var data = this.data;
		for(var i in data){
			data_html += input_tpl.replace(/{(\w*)}/g,function(result,key){
				if(key == 'name'){
					return i;
				}else if(key == 'value'){
					return data[i]
				}
			});
		}

		var html = up_tpl.replace(/{(\w*)}/g,function(result,key){
			if(key == 'ID'){
				return this_up.ID
			}else if(key == 'action'){
				return this_up.action
			}else if(key == 'fileinputname'){
				return this_up.fileinputname
			}else if(key == "data"){
				return data_html;
			}
		});
		return $(html);
	}
	//获取文件信息
	function getFilesFromInput(input){
		var returns = [];
		if(input.value.length > 0){
			if(input.files){
				for(var i=0,total=input.files.length;i<total;i++){
					returns.push({
						'name' : input.files[i]['name'],
						'size' : input.files[i]['size']
					})
				}
			}else{
				returns.push({
					'name' : input.value.split(/\\/).pop()
				});
			}
		}
		return returns;
	}
	//格式化JSON
	function parseJSON(input){
		//去除部分浏览器自动添加的标签
		input = input.replace(/<[^>]+>|<\/[^>]+>/g,'');
		var output = {};
		//尝试去解析
		try{
			output = eval('(' + input + ')');
		}catch(e){
			output = 'fail';
		}
		return output;
	}
	//构造新的单次上传模块
	function SingleUp(param){
		var this_up = this;
		this.ID = ++staticID;
		this.action = param.action;
		this.data = param['data'] || {};

		//状态 等待上传|上传中
		//    wait | uploading
		this.status = 'wait';
		this.responseParser = param['responseParser'] || null;
		this.fileinputname = param['fileinputname'] || 'photos';
		//事件集
		this.onHide = param.onHide || null;
		this.onMousedown = param.onMousedown || null;
		this.beforeUpload = param.beforeUpload || null;
		this.onStartUpload = param.onStartUpload || null;
		this.onFail = param.onFail || null;
		this.onSuccess = param.onSuccess || null;

		this.dom = buildDom.call(this);

		var position = param.position;

		this.dom.css({
			'top' : position.top,
			'left' : position.left,
			'width' : position.width,
			'height' : position.height
		});

		global_cnt.append(this.dom);

		/**
		 * 这个定时器是为了处理IE7异步创建iframe的BUG
		 * 如果你有好的办法，请  mail:bh_lay@126.com
		 */
		setTimeout(function(){
			this_up.init();
		},100);
	}
	//销毁自己
	SingleUp.prototype.destory = function(){
		this.onHide && this.onHide();
		if(this.status == 'wait'){
			this.dom.remove();
		}else{
			this.dom.hide();
		}
	};
	//处理response
	SingleUp.prototype.handleResponse = function(responseTXT){
		var ID = this.ID;
		this.status = 'wait';
		//是否已格式化数据方法
		if(this.responseParser){
			var jsonData = parseJSON(responseTXT);
			if(jsonData == 'fail'){
					//服务器数据异常！
				this.onFail && this.onFail(ID,'\u670D\u52A1\u5668\u6570\u636E\u5F02\u5E38\uFF01');
			}else{
				//数据交由开发者格式化
				var parserData = this.responseParser(jsonData);

				if(typeof(parserData) != 'object'){
					this.onFail && this.onFail(ID);
				}else{
					if(parserData['files'] && parserData['files']['length'] > 0){
						this.onSuccess && this.onSuccess(ID,parserData['files'],parserData['extra']);
					}else{
						this.onFail && this.onFail(ID,parserData['extra']);
					}
				}
			}
		}else{
			this.onFail && this.onFail(ID,'you need define method : responseParser! ');
		}
		//销毁单次上传模块
		this.destory();
	}
	//初始化单次上传模块
	SingleUp.prototype.init = function(){
		var this_up = this;

		var uploaderDom = this.dom;
		var iframe = this.dom.find('iframe')[0];
		var ID = this.ID;
		//事件处理
		uploaderDom.on('mouseleave',function(){
	//		setTimeout(function(){
				this_up.destory();
		//	},100);
		}).on('mousedown',function(){
			this_up.onMousedown && this_up.onMousedown();
		}).on('mousemove',function(e){
			var oW = uploaderDom.width();
			var oL = uploaderDom.offset().left;
			var mL = e.pageX;
			uploaderDom.find('.uploader_btn').css('right',oL+oW-mL-25);
		}).on('change','.uploader_btn',function(){
			var input = this;
			var can_start = true;
			//检测是否已选择文件
			var files = getFilesFromInput(input);
			if(files.length > 0){
				//触发上传前事件
				if(this_up.beforeUpload){
					can_start = this_up.beforeUpload(ID,files);
				}else{
					can_start = true;
				}
				if(can_start){
					uploaderDom.hide();
					//开始上传文件
					$(this).parents('form').submit();
					this_up.status = 'uploading';
					//触发上传事件
					this_up.onStartUpload && this_up.onStartUpload(ID,files);
				}else{
					//重置html
					input.outerHTML = input.outerHTML;
				}
			}
		});
		iframe_load(iframe,function(){
			var responseTXT = this.body.innerHTML;
			this_up.handleResponse(responseTXT);
		});
	};

	////

	function uploader(param){
		var this_up = this;
		//事件堆
		this.events = {};
		this.action = param['action'] || null;
		this.data = param['data'] || {};
		//绑定上传方法的DOM
		this.dom = param['dom'];
		this.fileinputname = param['fileinputname'] || 'photos';
		//是否可上传
		this.can_upload = true;
		this.responseParser = param['responseParser'] || null;

		//为按钮绑定悬停事件
		var delay;
		this.dom.mouseenter(function(){
			clearTimeout(delay);
			var btn = $(this);
			delay = setTimeout(function(){
				this_up.createSingleUp(btn);
			},100);
		}).mouseleave(function(){
			clearTimeout(delay);
		});
	}
	uploader.prototype = {
		'on' : function (eventName,callback){
			//事件堆无该事件，创建一个事件堆
			if(!this.events[eventName]){
				this.events[eventName] = [];
			}
			this.events[eventName].push(callback);
			return this;
		},
		'emit' : function (eventName,args){
			//事件堆无该事件，结束运行
			if(!this.events[eventName]){
				return
			}
			args = args || null;
			for(var i=0,total=this.events[eventName].length;i<total;i++){
				this.events[eventName][i].apply(this.event_global || this , args);
			}
		},
		'createSingleUp' : function(BTN){
			BTN.addClass('hover');
			var offset = BTN.offset();
			var this_up = this;
			var newUp = new SingleUp({
				'action' : this.action,
				'data' : this.data,
				'responseParser' : this.responseParser,
				'position' : {
					'top' : offset.top,
					'left' : offset.left,
					'width' : BTN.outerWidth(),
					'height' : BTN.outerHeight()
				},
				'beforeUpload' : function(ID,files){
					this_up.emit('beforeUpload',[ID,files]);
					if(this_up.can_upload){
						return true;
					}else{
						return false;
					}
				},
				'onStartUpload' : function(ID,files){
					this_up.emit('startUpload',[ID,files]);
				},
				'onSuccess' : function(ID,files,extra){
					this_up.emit('success',[ID,files,extra]);
				},
				'onFail' : function(ID,extra){
					this_up.emit('fail',[ID,extra]);
				},
				'onHide' : function(){
					BTN.removeClass('hover');
					BTN.removeClass('active');
				},
				'onMousedown' : function(){
					BTN.removeClass('hover')
					BTN.addClass('active');
				}
			});
		}
	};
	exports.uploader = uploader;
})(window.util);

//提供CommonJS规范的接口
window.define && define(function(require,exports,module){
	//对外接口
	return window.util.uploader;
});<commit_msg>调整鼠标交互<commit_after>/**
 *	@author bh-lay
 *	@github https://github.com/bh-lay/uploader
 *  @updata 2014-3-26 17:10
 *
 */
window.util = window.util || {};
/**
 * until.drag(handle_dom,dom,fn);
 */
(function uploaderClosure(exports){
	var staticID = 0;
	var upCnt_tpl = ['

'].join('');
	var up_tpl = ['
',
		'',
		'<form method="post" action="{action}" enctype="multipart/form-data" name="uploader" target="uploader{ID}">',
			//请选择图片
			'<input name="{fileinputname}" type="file" multiple="multiple" class="uploader_btn" title="\u8BF7\u9009\u62E9\u56FE\u7247"/>',
			'{data}',
		'</form>',
	'
'].join('');

	var input_tpl = '<input type="hidden" name="{name}" value="{value}" />';

	var up_css = [''].join('');

	//创建工作环境
	var global_cnt = $(upCnt_tpl);

	$('body').append(global_cnt);
	$('head').append(up_css);

	//iframe加载事件监听方法
	function iframe_load(iframe,load){
		if (iframe.attachEvent){
			iframe.attachEvent("onload", function(){
				load&&load.call(iframe.contentDocument);
			});
		}else{
			iframe.onload = function(){
				load&&load.call(iframe.contentDocument);
			};
		}
	}
	//创建新的html
	function buildDom(){
		var this_up = this;
		var data_html = '';
		var data = this.data;
		for(var i in data){
			data_html += input_tpl.replace(/{(\w*)}/g,function(result,key){
				if(key == 'name'){
					return i;
				}else if(key == 'value'){
					return data[i]
				}
			});
		}

		var html = up_tpl.replace(/{(\w*)}/g,function(result,key){
			if(key == 'ID'){
				return this_up.ID
			}else if(key == 'action'){
				return this_up.action
			}else if(key == 'fileinputname'){
				return this_up.fileinputname
			}else if(key == "data"){
				return data_html;
			}
		});
		return $(html);
	}
	//获取文件信息
	function getFilesFromInput(input){
		var returns = [];
		if(input.value.length > 0){
			if(input.files){
				for(var i=0,total=input.files.length;i<total;i++){
					returns.push({
						'name' : input.files[i]['name'],
						'size' : input.files[i]['size']
					})
				}
			}else{
				returns.push({
					'name' : input.value.split(/\\/).pop()
				});
			}
		}
		return returns;
	}
	//格式化JSON
	function parseJSON(input){
		//去除部分浏览器自动添加的标签
		input = input.replace(/<[^>]+>|<\/[^>]+>/g,'');
		var output = {};
		//尝试去解析
		try{
			output = eval('(' + input + ')');
		}catch(e){
			output = null;
		}
		return output;
	}
	//构造新的单次上传模块
	function SingleUp(param){
		var this_up = this;
		this.ID = ++staticID;
		this.action = param.action;
		this.data = param['data'] || {};

		//状态 等待上传|上传中
		//    wait | uploading
		this.status = 'wait';
		this.responseParser = param['responseParser'] || null;
		this.fileinputname = param['fileinputname'] || 'photos';
		//事件集
		this.onHide = param.onHide || null;
		this.onMousedown = param.onMousedown || null;
		this.beforeUpload = param.beforeUpload || null;
		this.onStartUpload = param.onStartUpload || null;
		this.onFail = param.onFail || null;
		this.onSuccess = param.onSuccess || null;

		this.dom = buildDom.call(this);

		var position = param.position;

		this.dom.css({
			'top' : position.top,
			'left' : position.left,
			'width' : position.width,
			'height' : position.height
		});

		global_cnt.append(this.dom);

		/**
		 * 这个定时器是为了处理IE7异步创建iframe的BUG
		 * 如果你有好的办法，请  mail:bh_lay@126.com
		 */
		setTimeout(function(){
			this_up.init();
		},100);
	}
	//销毁自己
	SingleUp.prototype.destory = function(){
			console.log('destory-2');
			console.log('---------------');
		this.onHide && this.onHide();
		if(this.status == 'wait'){
			this.dom.remove();
		}else{
			this.dom.hide();
		}
	};
	//处理response
	SingleUp.prototype.handleResponse = function(responseTXT){
		var ID = this.ID;
		this.status = 'wait';
		//是否已格式化数据方法
		if(this.responseParser){
			var jsonData = parseJSON(responseTXT);
			if(jsonData == null){
				//服务器数据异常！
				this.onFail && this.onFail(ID,'\u670D\u52A1\u5668\u6570\u636E\u5F02\u5E38\uFF01');
			}else{
				//数据交由开发者格式化
				var parserData = this.responseParser(jsonData);

				if(typeof(parserData) != 'object'){
					this.onFail && this.onFail(ID);
				}else{
					if(parserData['files'] && parserData['files']['length'] > 0){
						this.onSuccess && this.onSuccess(ID,parserData['files'],parserData['extra']);
					}else{
						this.onFail && this.onFail(ID,parserData['extra']);
					}
				}
			}
		}else{
			//需要定义responseParser
			this.onFail && this.onFail(ID,'you need define method : responseParser! ');
		}
		//销毁单次上传模块
		this.destory();
	}
	//初始化单次上传模块
	SingleUp.prototype.init = function(){
		var this_up = this;

		var uploaderDom = this.dom;
		var iframe = this.dom.find('iframe')[0];
		var ID = this.ID;
		//事件处理

		uploaderDom.on('mouseout',function(){
			this_up.destory();
		}).on('mousedown',function(){
			this_up.onMousedown && this_up.onMousedown();
		}).on('mousemove',function(e){
			var oW = uploaderDom.width();
			var oL = uploaderDom.offset().left;
			var mL = e.pageX;
			uploaderDom.find('.uploader_btn').css('right',oL+oW-mL-25);
		}).on('change','.uploader_btn',function(){
			var input = this;
			var can_start = true;
			//检测是否已选择文件
			var files = getFilesFromInput(input);
			if(files.length > 0){
				//触发上传前事件
				if(this_up.beforeUpload){
					can_start = this_up.beforeUpload(ID,files);
				}else{
					can_start = true;
				}
				if(can_start){
					uploaderDom.hide();
					//开始上传文件
					$(this).parents('form').submit();
					this_up.status = 'uploading';
					//触发上传事件
					this_up.onStartUpload && this_up.onStartUpload(ID,files);
				}else{
					//重置html
					input.outerHTML = input.outerHTML;
				}
			}
		});
		iframe_load(iframe,function(){
			var responseTXT = this.body.innerHTML;
			this_up.handleResponse(responseTXT);
		});
	};

	////

	function uploader(param){
		var this_up = this;
		//事件堆
		this.events = {};
		this.action = param['action'] || null;
		this.data = param['data'] || {};
		//绑定上传方法的DOM
		this.dom = param['dom'];
		this.fileinputname = param['fileinputname'] || 'photos';
		//是否可上传
		this.can_upload = true;
		this.responseParser = param['responseParser'] || null;

		//为按钮绑定悬停事件
		var delay;
		this.dom.mouseenter(function(){
	//		clearTimeout(delay);
			var btn = $(this);
	//		delay = setTimeout(function(){
				this_up.createSingleUp(btn);
	//		},80);
		}).mouseleave(function(){
	//		clearTimeout(delay);
		});
	}
	uploader.prototype = {
		'on' : function (eventName,callback){
			//事件堆无该事件，创建一个事件堆
			if(!this.events[eventName]){
				this.events[eventName] = [];
			}
			this.events[eventName].push(callback);
			return this;
		},
		'emit' : function (eventName,args){
			//事件堆无该事件，结束运行
			if(!this.events[eventName]){
				return
			}
			args = args || null;
			for(var i=0,total=this.events[eventName].length;i<total;i++){
				this.events[eventName][i].apply(this.event_global || this , args);
			}
		},
		'createSingleUp' : function(BTN){
			BTN.addClass('hover');
			var offset = BTN.offset();
			var this_up = this;
			var newUp = new SingleUp({
				'action' : this.action,
				'data' : this.data,
				'responseParser' : this.responseParser,
				'position' : {
					'top' : offset.top,
					'left' : offset.left,
					'width' : BTN.outerWidth(),
					'height' : BTN.outerHeight()
				},
				'beforeUpload' : function(ID,files){
					this_up.emit('beforeUpload',[ID,files]);
					if(this_up.can_upload){
						return true;
					}else{
						return false;
					}
				},
				'onStartUpload' : function(ID,files){
					this_up.emit('startUpload',[ID,files]);
				},
				'onSuccess' : function(ID,files,extra){
					this_up.emit('success',[ID,files,extra]);
				},
				'onFail' : function(ID,extra){
					this_up.emit('fail',[ID,extra]);
				},
				'onHide' : function(){
					BTN.removeClass('hover');
					BTN.removeClass('active');
				},
				'onMousedown' : function(){
					BTN.removeClass('hover')
					BTN.addClass('active');
				}
			});
		}
	};
	exports.uploader = uploader;
})(window.util);

//提供CommonJS规范的接口
window.define && define(function(require,exports,module){
	//对外接口
	return window.util.uploader;
});<|endoftext|>


<commit_before>/*
 OpenBeerMap main.js | noemie.lehuby(at)gmail.com | MIT Licensed
*/

/* Basemap Layers */
var attr_osm = 'Map data © OpenStreetMap contributors ',
      attr_overpass = 'POI via Overpass API';
var osm = new L.TileLayer('http://{s}.tile.stamen.com/toner-lite/{z}/{x}/{y}.png', {opacity: 0.7, attribution: [attr_overpass,attr_osm].join('| ')});

var map = new L.Map('map').addLayer(osm).setView(new L.LatLng(48.84702,2.37705), 17);

/*User Location*/
map.locate({setView: true})
        .on('locationfound', function(e){
        console.log("localisation utilisateur réussie");
            var marker = L.marker([e.latlng.lat, e.latlng.lng]).bindPopup('Vous êtes par ici  ');
            map.addLayer(marker);
				function onPopupClick(e) {
				document.l10n.localize(['locate_ok',], function(l10n) {
				  var node = document.querySelector('[data-l10n-id=locate_ok]');
				  if (node != null ) {node.textContent = l10n.entities.locate_ok.value;}
				  })
				}
				marker.on('click', onPopupClick);
        })
       .on('locationerror', function(e){
            //console.log(e);
            console.log("Échec de localisation de l'utilisateur");
});

/* Larger screens get expanded layer control */
if (document.body.clientWidth <= 767) {
  var isCollapsed = true;
} else {
  var isCollapsed = false;
}

/* Leaflet sidebar */
var sidebar = L.control.sidebar("sidebar", {
  closeButton: true,
  position: "left"
}).addTo(map);
//les fonctions liées à l'éditeur OSM sont dans OSM_js_editor.js

/*OverPassAPI overlay*/
	var tous = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];(node(BBOX)[amenity=bar];node(BBOX)[amenity=cafe];node(BBOX)[amenity=biergarten];node(BBOX)[microbrewery=yes];node(BBOX)[amenity=pub]);out;>;out;", "assets/img/beer1.png");

    var leffe = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[lL]effe'];out;", "assets/img/beer2.png");

    var chouffe = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[cC]houffe'];out;", "assets/img/beer4.png");

    var chimay = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[Cc]himay'];out;", "assets/img/beer1.png");

    var guinness = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[Gg]uinness'];out;", "assets/img/beer1.png");

	var brewdog = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[Bb]rewdog'];out;", "assets/img/beer1.png");

	var affligem = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[aA]ffligem'];out;", "assets/img/affligem.png");

    var karmeliet = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[tT]ripel_[kK]armeliet'];out;", "assets/img/beer3.png");
//les fonctions utilisées pour récupérer les données et les placer sont dans BeerLayer.js

    var baseMaps = {
        "OpenStreetMap": osm,
    };

    var overlayMaps = {
        " Boire": tous,
        "  Chouffe": chouffe,
        "  Tripel Karmeliet": karmeliet,
        "  Leffe": leffe,
        "  Chimay": chimay,
        "  Brewdog": brewdog,
        "  Guinness": guinness,
        "  Affligem": affligem
    };
    map.addLayer(tous);

//indication utilisateur en cas de dé-zoom
className : 'leaflet-control-minZoomIndecator'
map.zoomIndecator._container.innerHTML = "Zoom zoom zoom ! ";

L.control.layers(baseMaps, overlayMaps, {
  collapsed: isCollapsed
}).addTo(map);

//recherche
map.addControl( new L.Control.Search({
			url: 'http://nominatim.openstreetmap.org/search?format=json&q={s}',
			jsonpParam: 'json_callback',
			propertyName: 'display_name',
			propertyLoc: ['lat','lon'],
			markerLocation: true,
			autoType: false,
			autoCollapse: true,
			minLength: 2,
			zoom:16
		}) );

//supprimer la barre de progression quand tout le js est traité
$(document).one("ajaxStop", function () {$("#loading").hide(); });

<commit_msg>show amenity with brewery tag, even if it's not a cafe/bar/pub/etc<commit_after>/*
 OpenBeerMap main.js | noemie.lehuby(at)gmail.com | MIT Licensed
*/

/* Basemap Layers */
var attr_osm = 'Map data © OpenStreetMap contributors ',
      attr_overpass = 'POI via Overpass API';
var osm = new L.TileLayer('http://{s}.tile.stamen.com/toner-lite/{z}/{x}/{y}.png', {opacity: 0.7, attribution: [attr_overpass,attr_osm].join('| ')});

var map = new L.Map('map').addLayer(osm).setView(new L.LatLng(48.84702,2.37705), 17);

/*User Location*/
map.locate({setView: true})
        .on('locationfound', function(e){
        console.log("localisation utilisateur réussie");
            var marker = L.marker([e.latlng.lat, e.latlng.lng]).bindPopup('Vous êtes par ici  ');
            map.addLayer(marker);
				function onPopupClick(e) {
				document.l10n.localize(['locate_ok',], function(l10n) {
				  var node = document.querySelector('[data-l10n-id=locate_ok]');
				  if (node != null ) {node.textContent = l10n.entities.locate_ok.value;}
				  })
				}
				marker.on('click', onPopupClick);
        })
       .on('locationerror', function(e){
            //console.log(e);
            console.log("Échec de localisation de l'utilisateur");
});

/* Larger screens get expanded layer control */
if (document.body.clientWidth <= 767) {
  var isCollapsed = true;
} else {
  var isCollapsed = false;
}

/* Leaflet sidebar */
var sidebar = L.control.sidebar("sidebar", {
  closeButton: true,
  position: "left"
}).addTo(map);
//les fonctions liées à l'éditeur OSM sont dans OSM_js_editor.js

/*OverPassAPI overlay*/
	var tous = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];(node(BBOX)[amenity=bar];node(BBOX)[amenity=cafe];node(BBOX)[amenity=biergarten];node(BBOX)[microbrewery=yes];node(BBOX)['brewery'];node(BBOX)[amenity=pub]);out;>;out;", "assets/img/beer1.png");

    var leffe = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[lL]effe'];out;", "assets/img/beer2.png");

    var chouffe = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[cC]houffe'];out;", "assets/img/beer4.png");

    var chimay = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[Cc]himay'];out;", "assets/img/beer1.png");

    var guinness = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[Gg]uinness'];out;", "assets/img/beer1.png");

	var brewdog = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[Bb]rewdog'];out;", "assets/img/beer1.png");

	var affligem = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[aA]ffligem'];out;", "assets/img/affligem.png");

    var karmeliet = draw_beer("https://overpass-api.de/api/interpreter?data=[out:json];node(BBOX)['brewery'~'[tT]ripel_[kK]armeliet'];out;", "assets/img/beer3.png");
//les fonctions utilisées pour récupérer les données et les placer sont dans BeerLayer.js

    var baseMaps = {
        "OpenStreetMap": osm,
    };

    var overlayMaps = {
        " Boire": tous,
        "  Chouffe": chouffe,
        "  Tripel Karmeliet": karmeliet,
        "  Leffe": leffe,
        "  Chimay": chimay,
        "  Brewdog": brewdog,
        "  Guinness": guinness,
        "  Affligem": affligem
    };
    map.addLayer(tous);

//indication utilisateur en cas de dé-zoom
className : 'leaflet-control-minZoomIndecator'
map.zoomIndecator._container.innerHTML = "Zoom zoom zoom ! ";

L.control.layers(baseMaps, overlayMaps, {
  collapsed: isCollapsed
}).addTo(map);

//recherche
map.addControl( new L.Control.Search({
			url: 'http://nominatim.openstreetmap.org/search?format=json&q={s}',
			jsonpParam: 'json_callback',
			propertyName: 'display_name',
			propertyLoc: ['lat','lon'],
			markerLocation: true,
			autoType: false,
			autoCollapse: true,
			minLength: 2,
			zoom:16
		}) );

//supprimer la barre de progression quand tout le js est traité
$(document).one("ajaxStop", function () {$("#loading").hide(); });

<|endoftext|>


<commit_before>import R from 'ramda';
import api from './api-internal';
import * as util from 'js-util';
import schema, { PropTypes } from 'react-schema';
import AlignmentContainer from 'react-atoms/components/AlignmentContainer';
import log from '../shared/log';

const isBrowser = (typeof window !== 'undefined');
const PROP = Symbol('Prop');
const PROPS = {
  children: {
    key: 'componentChildren', // Stored on {current} as this.
  },
  width: {
    default: 'auto',
    type: PropTypes.numberOrString,
    resetOn: null,
  },
  height: {
    default: 'auto',
    type: PropTypes.numberOrString,
    resetOn: null,
  },
  cropMarks: {
    default: true,
    type: PropTypes.bool,
  },
  'cropMarks.size': {
    default: 25,
    type: PropTypes.number,
  },
  'cropMarks.offset': {
    default: 5,
    type: PropTypes.number,
  },
  margin: {
    default: 60,
    type: PropTypes.number,
  },
  align: {
    default: 'center top',
    type: AlignmentContainer.propTypes.align,
  },
  header: {
    type: PropTypes.string,
  },
  footer: {
    type: PropTypes.string,
  },
  hr: {
    default: true,
    type: PropTypes.bool,
  },
  backdrop: {
    default: 0,
    type: PropTypes.numberOrString,
  },
  scroll: {
    default: false,
    type: PropTypes.oneOf([true, false, 'x', 'y', 'x:y']),
  },
  context: {
    type: PropTypes.object,
  },
};

const getPropParent = (ns, obj) => (
  ns.length === 0
      ? obj
      : getPropParent(R.takeLast(ns.length - 1, ns), obj[ns[0]])
);

/**
 * The [this] context that is passed into the [describe/it]
 * BDD methods.
 */
export default class UIHContext {
  constructor() {
    // Determine whether this is the currently loaded suite.
    const isCurrent = () => {
      const currentSuite = api.current.get('suite');
      return (currentSuite && currentSuite.id === this.suite.id);
    };

    // Read|Write helper for data-property methods.
    this[PROP] = (key, value, options) => {
      options = options || PROPS[key] || {};
      key = options.key || key; // The property options may provide an alternative
                                // key to store as on the {current} map.

      // WRITE.
      if (value !== undefined) {
        // Perform type validation.
        const type = options.type;
        if (type) {
          const validation = schema.validate(type, value);
          if (!validation.isValid) {
            const msg = `Invalid '${ key }' value (${ value }). Should be ${ type.toString() }.`;
            throw new Error(msg);
          }
        }

        // Reset the value if required.
        if (options.resetOn !== undefined && value === options.resetOn) {
          value = options.default;
        }

        // Store the value.
        this[PROP].state[key] = value;
        if (isCurrent()) { api.setCurrent({ [key]: value }); }
        return this; // When writing the [this] context is returned.
                     // This allows for chaining of write operations.
      }
      // READ.
      let result = this[PROP].state[key];
      if (result === undefined) { result = options.default; }
      return result;
    };
    this[PROP].state = {};

    // Create property functions.
    Object.keys(PROPS).forEach(key => {
      if (this[key]) { throw new Error(`Property named '${ key }' already exists.`); }

      // Ensure nested property extensions are added to the hierarchy.
      // ie. functions as properites of parent functions, for example:
      //     - cropMarks
      //     - cropMarks.size
      const parts = key.split('.');
      const ns = R.take(parts.length - 1, parts);
      const propName = R.takeLast(1, parts).join('.');
      const parent = getPropParent(ns, this);

      // Store the propery.
      parent[propName] = (value) => this[PROP](key, value);
    });

    // Property extension methods.
    this.log.clear = () => api.clearLog();
  }

  /**
   * Converts to an object of all current values.
   */
  toValues() {
    const result = {};
    Object.keys(PROPS).forEach(key => {
      const propFunc = util.ns(this, key);
      if (R.is(Function, propFunc)) {
        result[key] = propFunc.call(this);
      } else {
        result[key] = this[PROP].state[key];
      }
    });
    return result;
  }

  /**
   * Resets the UI Harness.
   */
  reset(options) { api.reset(options); }

  /**
   * Cumulatively sets property values on the current component.
   * @param {object} value:  An object containing {prop:value} to add
   */
  props(value) {
    // WRITE.
    if (R.is(Object, value)) {
      // Cumulatively add given props to the existing
      // props on the component.
      const component = api.component();
      let props = component && component.props;
      if (props) {
        props = R.clone(props);
        R.keys(value).forEach(key => props[key] = value[key]);
        value = props;
      }
    }

    // READ.
    return this[PROP]('componentProps', value);
  }

  /**
   * Loads the given component.
   *
   * @param component:  The component Type
   *                    or created component element (eg: <MyComponent/>).
   *
   * @param props:      Optional. The component props
   *                    (if not passed in with a component element).
   *
   * @param children:   Optional. The component children
   *                    (if not passed in with a component element).
   *
   */
  load(component, props, children) {
    if (!component) {
      if (isBrowser) { log.warn('Cannot load: a component was not specified (undefined/null)'); }
    } else {
      api.loadComponent(component, props, children);
    }
    return this;
  }

  /**
   * Unloads the currently loaded component.
   */
  unload() {
    api.component(null);
    return this;
  }

  /**
   * Logs a value to the output.
   * @param {array} value: The value or values to append.
   */
   log(...value) {
     api.log(value);
     return this;
   }
}
<commit_msg>Move context to top - and give it a key name.<commit_after>import R from 'ramda';
import api from './api-internal';
import * as util from 'js-util';
import schema, { PropTypes } from 'react-schema';
import AlignmentContainer from 'react-atoms/components/AlignmentContainer';
import log from '../shared/log';

const isBrowser = (typeof window !== 'undefined');
const PROP = Symbol('Prop');
const PROPS = {
  children: {
    key: 'componentChildren', // Stored on {current} as this.
  },
  context: {
    type: PropTypes.object,
    key: 'componentContext',
  },
  width: {
    default: 'auto',
    type: PropTypes.numberOrString,
    resetOn: null,
  },
  height: {
    default: 'auto',
    type: PropTypes.numberOrString,
    resetOn: null,
  },
  cropMarks: {
    default: true,
    type: PropTypes.bool,
  },
  'cropMarks.size': {
    default: 25,
    type: PropTypes.number,
  },
  'cropMarks.offset': {
    default: 5,
    type: PropTypes.number,
  },
  margin: {
    default: 60,
    type: PropTypes.number,
  },
  align: {
    default: 'center top',
    type: AlignmentContainer.propTypes.align,
  },
  header: {
    type: PropTypes.string,
  },
  footer: {
    type: PropTypes.string,
  },
  hr: {
    default: true,
    type: PropTypes.bool,
  },
  backdrop: {
    default: 0,
    type: PropTypes.numberOrString,
  },
  scroll: {
    default: false,
    type: PropTypes.oneOf([true, false, 'x', 'y', 'x:y']),
  },
};

const getPropParent = (ns, obj) => (
  ns.length === 0
      ? obj
      : getPropParent(R.takeLast(ns.length - 1, ns), obj[ns[0]])
);

/**
 * The [this] context that is passed into the [describe/it]
 * BDD methods.
 */
export default class UIHContext {
  constructor() {
    // Determine whether this is the currently loaded suite.
    const isCurrent = () => {
      const currentSuite = api.current.get('suite');
      return (currentSuite && currentSuite.id === this.suite.id);
    };

    // Read|Write helper for data-property methods.
    this[PROP] = (key, value, options) => {
      options = options || PROPS[key] || {};
      key = options.key || key; // The property options may provide an alternative
                                // key to store as on the {current} map.

      // WRITE.
      if (value !== undefined) {
        // Perform type validation.
        const type = options.type;
        if (type) {
          const validation = schema.validate(type, value);
          if (!validation.isValid) {
            const msg = `Invalid '${ key }' value (${ value }). Should be ${ type.toString() }.`;
            throw new Error(msg);
          }
        }

        // Reset the value if required.
        if (options.resetOn !== undefined && value === options.resetOn) {
          value = options.default;
        }

        // Store the value.
        this[PROP].state[key] = value;
        if (isCurrent()) { api.setCurrent({ [key]: value }); }
        return this; // When writing the [this] context is returned.
                     // This allows for chaining of write operations.
      }
      // READ.
      let result = this[PROP].state[key];
      if (result === undefined) { result = options.default; }
      return result;
    };
    this[PROP].state = {};

    // Create property functions.
    Object.keys(PROPS).forEach(key => {
      if (this[key]) { throw new Error(`Property named '${ key }' already exists.`); }

      // Ensure nested property extensions are added to the hierarchy.
      // ie. functions as properites of parent functions, for example:
      //     - cropMarks
      //     - cropMarks.size
      const parts = key.split('.');
      const ns = R.take(parts.length - 1, parts);
      const propName = R.takeLast(1, parts).join('.');
      const parent = getPropParent(ns, this);

      // Store the propery.
      parent[propName] = (value) => this[PROP](key, value);
    });

    // Property extension methods.
    this.log.clear = () => api.clearLog();
  }

  /**
   * Converts to an object of all current values.
   */
  toValues() {
    const result = {};
    Object.keys(PROPS).forEach(key => {
      const propFunc = util.ns(this, key);
      if (R.is(Function, propFunc)) {
        result[key] = propFunc.call(this);
      } else {
        result[key] = this[PROP].state[key];
      }
    });
    return result;
  }

  /**
   * Resets the UI Harness.
   */
  reset(options) { api.reset(options); }

  /**
   * Cumulatively sets property values on the current component.
   * @param {object} value:  An object containing {prop:value} to add
   */
  props(value) {
    // WRITE.
    if (R.is(Object, value)) {
      // Cumulatively add given props to the existing
      // props on the component.
      const component = api.component();
      let props = component && component.props;
      if (props) {
        props = R.clone(props);
        R.keys(value).forEach(key => props[key] = value[key]);
        value = props;
      }
    }

    // READ.
    return this[PROP]('componentProps', value);
  }

  /**
   * Loads the given component.
   *
   * @param component:  The component Type
   *                    or created component element (eg: <MyComponent/>).
   *
   * @param props:      Optional. The component props
   *                    (if not passed in with a component element).
   *
   * @param children:   Optional. The component children
   *                    (if not passed in with a component element).
   *
   */
  load(component, props, children) {
    if (!component) {
      if (isBrowser) { log.warn('Cannot load: a component was not specified (undefined/null)'); }
    } else {
      api.loadComponent(component, props, children);
    }
    return this;
  }

  /**
   * Unloads the currently loaded component.
   */
  unload() {
    api.component(null);
    return this;
  }

  /**
   * Logs a value to the output.
   * @param {array} value: The value or values to append.
   */
   log(...value) {
     api.log(value);
     return this;
   }
}
<|endoftext|>


<commit_before>define(['js/data/Entity', 'sprd/entity/Offset', 'sprd/entity/Size', 'sprd/entity/PrintArea', 'sprd/model/PrintType', 'js/core/List' , "sprd/entity/Price", "sprd/type/Matrix2d", "sprd/util/ProductUtil", "sprd/entity/PrintTypeColor", "underscore", "js/core/Bus"], function (Entity, Offset, Size, PrintArea, PrintType, List, Price, Matrix2d, ProductUtil, PrintTypeColor, _, Bus) {

    return Entity.inherit('sprd.entity.Configuration', {

        schema: {
            offset: Offset,
            printArea: {
                type: PrintArea,
                isReference: true
            },
            printType: PrintType,
            printColors: [PrintTypeColor],

            content: Object,
            restrictions: Object,
            type: String
        },

        defaults: {
            printArea: null,
            printType: null,
            offset: Offset,
            scale: {
                x: 1,
                y: 1
            },
            rotation: 0,
            printColors: List,

            // bind this
            _size: "{size()}",
            _x: "{offset.x}",
            _y: "{offset.y}",

            _isDeletable: true,

            _printTypePrice: "{printType.price}"
        },

        inject: {
            bus: Bus
        },

        _commitChangedAttributes: function ($, options) {

            var delay = options && options.userInteraction ? 300 : 0,
                self = this,
                combinedAttributes = {};

            this.callBase();

            if (this._hasSome($, ["scale", "rotation", "printArea", "printColors", "printArea", "printType"])) {
                validate($);
                this.trigger('configurationChanged');
            } else if ($.hasOwnProperty("offset") && $.offset && !$.offset.isDeepEqual(this.$previousAttributes["offset"])) {
                    validate($);
                    this.trigger('configurationChanged');
            }

            function validate(attributes) {
                _.extend(combinedAttributes, attributes);
                self._debounceFunctionCall(performValidate, "validateTransform", delay, self);
            }

            function performValidate() {
                self._setError(self._validateTransform(combinedAttributes));
                combinedAttributes = {};
            }

        },

        _validateTransform: function ($) {

            var rotationChanged = this._hasSome($, ["rotation"]),
                sizeChanged = this._hasSome($, ["_size", "_x", "_y", "scale", "offset", "bound"]),
                printTypeChanged = this._hasSome($, ["printType"]),
                width, height,
                printType = $.printType || this.$.printType,
                scale = $.scale || this.$.scale,
                rotation = $.rotation || this.$.rotation,
                ret = {},
                printArea = this.$.printArea;

            if (sizeChanged || rotationChanged) {
                width = this.width(scale.x);
                height = this.height(scale.y);

                if (printArea) {

                    if (printArea.hasSoftBoundary()) {
                        ret.hardBoundary = false;
                    } else {
                        ret.hardBoundary = this._hasHardBoundaryError($.offset || this.$.offset, width, height, rotation, scale);
                    }
                }

            }

            if (sizeChanged || printTypeChanged) {
                width = width || this.width();
                height = height || this.height();
                _.extend(ret, this._validatePrintTypeSize(printType, width, height, scale));
            }

            if (ret.minBound && this.$context && this.$context.$contextModel && !printTypeChanged) {
                var printTypes = this.getPossiblePrintTypesForPrintArea(this.$.printArea, this.$context.$contextModel.get('appearance.id'));
                for (var i = 0; i < printTypes.length; i++) {
                    if (!printTypes[i].isPrintColorColorSpace()) {

                        this.$.bus && this.$.bus.trigger("Configuration.automaticallyPrintTypeChange", {
                            printType: printTypes[i]
                        });

                        this.set('printType', printTypes[i]);
                        ret.minBound = false;
                        break;
                    }

                }
            }

            return ret;

        },

        _validatePrintTypeSize: function (printType, width, height, scale) {
            if (!printType) {
                return {};
            }

            var printArea = this.$.printArea;
            if (printArea && printArea.hasSoftBoundary()) {
                // if we use softboundaries the size of the configuration is maximum the
                // size of the softboudary. As long as we haven't the size of the softboundary
                // we use the size of the print area
                width = Math.min(width, printArea.width());
                height = Math.min(height, printArea.height());
            }

            return {
                printTypeScaling: !printType.isScalable() && (scale.x != 1 || scale.y != 1),
                maxBound: width > printType.get("size.width") || height > printType.get("size.height"),
                minBound: false
            };

        },

        isPrintTypeAvailable: function (printType) {

            var ret = this._validatePrintTypeSize(printType, this.get('size.width'), this.get('size.height'), this.$.scale);

            return !ret.maxBound && !ret.minBound && !ret.printTypeScaling;
        }.onChange('_size.width', '_size.height', 'scale'),

        _hasHardBoundaryError: function (offset, width, height, rotation, scale) {

            var printArea = this.$.printArea;

            if (!(printArea && offset)) {
                return null;
            }

            var boundingBox = this._getBoundingBox(offset, width, height, rotation, scale, true);

            return !(boundingBox.x >= -0.1 && boundingBox.y >= -0.1 &&
                (boundingBox.x + boundingBox.width - 0.1) <= printArea.get("boundary.size.width") &&
                (boundingBox.y + boundingBox.height - 0.1) <= printArea.get("boundary.size.height"));

        },

        _getBoundingBox: function (offset, width, height, rotation, scale, onlyContent, xOffset) {

            offset = offset || this.$.offset;
            width = width || this.width();
            height = height || this.height();
            rotation = rotation || this.$.rotation;

            var x = offset.$.x,
                y = offset.$.y;

            if (!(rotation % 360)) {
                return {
                    x: x,
                    y: y,
                    height: height,
                    width: width
                };
            }

            var minX,
                maxX,
                minY,
                maxY,
                matrix = new Matrix2d().rotateDeg(rotation);

            xOffset = xOffset || 0;

            var halfW = width / 2,
                halfH = height / 2;

            var points = [
                [-halfW + xOffset, -halfH],
                [halfW + xOffset, -halfH],
                [halfW + xOffset, halfH],
                [-halfW + xOffset, halfH]
            ];

            var point = matrix.transformPoint(points[0]);
            minX = maxX = point[0];
            minY = maxY = point[1];

            for (var i = 1; i < points.length; i++) {
                point = matrix.transformPoint(points[i]);

                minX = Math.min(point[0], minX);
                maxX = Math.max(point[0], maxX);
                minY = Math.min(point[1], minY);
                maxY = Math.max(point[1], maxY);
            }

            return {
                x: minX + halfW + x - xOffset,
                y: minY + halfH + y,
                width: maxX - minX,
                height: maxY - minY
            };

        },

        size: function () {
            this.log("size() not implemented", "debug");
            return Size.empty;
        },

        height: function (scale) {

            if (!scale && scale !== 0) {
                scale = this.$.scale.y;
            }

            return Math.abs(this.size().$.height * scale);
        }.onChange("scale", "size()").on("sizeChanged"),

        width: function (scale) {

            if (!scale && scale !== 0) {
                scale = this.$.scale.x;
            }

            return Math.abs(this.size().$.width * scale);
        }.onChange("scale", "size()").on("sizeChanged"),

        isScalable: function () {
            return this.get("printType.isScalable()");
        }.onChange("printType"),

        isRotatable: function () {
            return true;
        },

        isRemovable: function () {
            return true;
        },

        price: function () {
            var printTypePrice = this.get('printType.price');
            if (printTypePrice) {
                return printTypePrice.clone();
            }
            return new Price();
        },

        /***
         *
         * @param {sprd.model.PrintType} printType
         * @return {sprd.entity.Size}
         */
        getSizeForPrintType: function (printType) {
            return Size.empty;
        },

        possiblePrintTypes: function (appearance) {
            var ret = [],
                printArea = this.$.printArea;

            if (printArea && appearance) {
                ret = ProductUtil.getPossiblePrintTypesForPrintAreas([printArea], appearance.$.id);
            }

            return ret;
        }.onChange("printArea"),

        isAllowedOnPrintArea: function (printArea) {
            return false;
        },

        getPossiblePrintTypesForPrintArea: function () {
            return [];
        },

        allowScale: function () {
            return true;
        },

        minimumScale: function () {
            return 0;
        },

        isReadyForCompose: function () {
            return true;
        }
    });
});
<commit_msg>DEV-65227 - Problem with scaling a flex design down and then up again * DD print type gets now switched back to Flex if design is big enough<commit_after>define(['js/data/Entity', 'sprd/entity/Offset', 'sprd/entity/Size', 'sprd/entity/PrintArea', 'sprd/model/PrintType', 'js/core/List' , "sprd/entity/Price", "sprd/type/Matrix2d", "sprd/util/ProductUtil", "sprd/entity/PrintTypeColor", "underscore", "js/core/Bus"], function (Entity, Offset, Size, PrintArea, PrintType, List, Price, Matrix2d, ProductUtil, PrintTypeColor, _, Bus) {

    return Entity.inherit('sprd.entity.Configuration', {

        schema: {
            offset: Offset,
            printArea: {
                type: PrintArea,
                isReference: true
            },
            printType: PrintType,
            printColors: [PrintTypeColor],

            content: Object,
            restrictions: Object,
            type: String
        },

        defaults: {
            printArea: null,
            printType: null,
            offset: Offset,
            scale: {
                x: 1,
                y: 1
            },
            rotation: 0,
            printColors: List,

            // bind this
            _size: "{size()}",
            _x: "{offset.x}",
            _y: "{offset.y}",

            _isDeletable: true,

            _printTypePrice: "{printType.price}"
        },

        inject: {
            bus: Bus
        },

        _commitChangedAttributes: function ($, options) {

            var delay = options && options.userInteraction ? 300 : 0,
                self = this,
                combinedAttributes = {};

            this.callBase();

            if (this._hasSome($, ["scale", "rotation", "printArea", "printColors", "printArea", "printType"])) {
                validate($);
                this.trigger('configurationChanged');
            } else if ($.hasOwnProperty("offset") && $.offset && !$.offset.isDeepEqual(this.$previousAttributes["offset"])) {
                validate($);
                this.trigger('configurationChanged');
            }

            function validate(attributes) {
                _.extend(combinedAttributes, attributes);
                self._debounceFunctionCall(performValidate, "validateTransform", delay, self);
            }

            function performValidate() {
                self._setError(self._validateTransform(combinedAttributes));
                combinedAttributes = {};
            }

        },

        _validateTransform: function ($) {

            var rotationChanged = this._hasSome($, ["rotation"]),
                sizeChanged = this._hasSome($, ["_size", "_x", "_y", "scale", "offset", "bound"]),
                printTypeChanged = this._hasSome($, ["printType"]),
                width, height,
                printType = $.printType || this.$.printType,
                scale = $.scale || this.$.scale,
                rotation = $.rotation || this.$.rotation,
                ret = {},
                printArea = this.$.printArea;

            if (sizeChanged || rotationChanged) {
                width = this.width(scale.x);
                height = this.height(scale.y);

                if (printArea) {

                    if (printArea.hasSoftBoundary()) {
                        ret.hardBoundary = false;
                    } else {
                        ret.hardBoundary = this._hasHardBoundaryError($.offset || this.$.offset, width, height, rotation, scale);
                    }
                }

            }

            if (sizeChanged || printTypeChanged) {
                width = width || this.width();
                height = height || this.height();
                _.extend(ret, this._validatePrintTypeSize(printType, width, height, scale));
            }

            // when configuration is too small for print type or it is a DD print type try to find another print type that fits better
            if (printType && (ret.minBound || !printType.isPrintColorColorSpace()) && this.$context && this.$context.$contextModel && !printTypeChanged) {
                var printTypes = this.getPossiblePrintTypesForPrintArea(this.$.printArea, this.$context.$contextModel.get('appearance.id'));
                var preferredPrintType = null,
                    val,
                    newPrintType;

                for (var i = 0; i < printTypes.length; i++) {
                    newPrintType = printTypes[i];
                    val = this._validatePrintTypeSize(newPrintType, width, height, scale);
                    if (!(val.printTypeScaling || val.maxBound || val.minBound)) {
                        if (newPrintType.isPrintColorColorSpace()) {
                            preferredPrintType = newPrintType;
                            break;
                        } else if (!preferredPrintType) {
                            preferredPrintType = newPrintType;
                        }
                    }
                }

                if (preferredPrintType && preferredPrintType !== printType) {
                    this.$.bus && this.$.bus.trigger("Configuration.automaticallyPrintTypeChange", {
                        printType: preferredPrintType
                    });

                    this.set('printType', preferredPrintType);
                    ret.minBound = false;
                }
            }

            return ret;

        },

        _validatePrintTypeSize: function (printType, width, height, scale) {
            if (!printType) {
                return {};
            }

            var printArea = this.$.printArea;
            if (printArea && printArea.hasSoftBoundary()) {
                // if we use softboundaries the size of the configuration is maximum the
                // size of the softboudary. As long as we haven't the size of the softboundary
                // we use the size of the print area
                width = Math.min(width, printArea.width());
                height = Math.min(height, printArea.height());
            }

            return {
                printTypeScaling: !printType.isScalable() && (scale.x != 1 || scale.y != 1),
                maxBound: width > printType.get("size.width") || height > printType.get("size.height"),
                minBound: false
            };

        },

        isPrintTypeAvailable: function (printType) {

            var ret = this._validatePrintTypeSize(printType, this.get('size.width'), this.get('size.height'), this.$.scale);

            return !ret.maxBound && !ret.minBound && !ret.printTypeScaling;
        }.onChange('_size.width', '_size.height', 'scale'),

        _hasHardBoundaryError: function (offset, width, height, rotation, scale) {

            var printArea = this.$.printArea;

            if (!(printArea && offset)) {
                return null;
            }

            var boundingBox = this._getBoundingBox(offset, width, height, rotation, scale, true);

            return !(boundingBox.x >= -0.1 && boundingBox.y >= -0.1 &&
                (boundingBox.x + boundingBox.width - 0.1) <= printArea.get("boundary.size.width") &&
                (boundingBox.y + boundingBox.height - 0.1) <= printArea.get("boundary.size.height"));

        },

        _getBoundingBox: function (offset, width, height, rotation, scale, onlyContent, xOffset) {

            offset = offset || this.$.offset;
            width = width || this.width();
            height = height || this.height();
            rotation = rotation || this.$.rotation;

            var x = offset.$.x,
                y = offset.$.y;

            if (!(rotation % 360)) {
                return {
                    x: x,
                    y: y,
                    height: height,
                    width: width
                };
            }

            var minX,
                maxX,
                minY,
                maxY,
                matrix = new Matrix2d().rotateDeg(rotation);

            xOffset = xOffset || 0;

            var halfW = width / 2,
                halfH = height / 2;

            var points = [
                [-halfW + xOffset, -halfH],
                [halfW + xOffset, -halfH],
                [halfW + xOffset, halfH],
                [-halfW + xOffset, halfH]
            ];

            var point = matrix.transformPoint(points[0]);
            minX = maxX = point[0];
            minY = maxY = point[1];

            for (var i = 1; i < points.length; i++) {
                point = matrix.transformPoint(points[i]);

                minX = Math.min(point[0], minX);
                maxX = Math.max(point[0], maxX);
                minY = Math.min(point[1], minY);
                maxY = Math.max(point[1], maxY);
            }

            return {
                x: minX + halfW + x - xOffset,
                y: minY + halfH + y,
                width: maxX - minX,
                height: maxY - minY
            };

        },

        size: function () {
            this.log("size() not implemented", "debug");
            return Size.empty;
        },

        height: function (scale) {

            if (!scale && scale !== 0) {
                scale = this.$.scale.y;
            }

            return Math.abs(this.size().$.height * scale);
        }.onChange("scale", "size()").on("sizeChanged"),

        width: function (scale) {

            if (!scale && scale !== 0) {
                scale = this.$.scale.x;
            }

            return Math.abs(this.size().$.width * scale);
        }.onChange("scale", "size()").on("sizeChanged"),

        isScalable: function () {
            return this.get("printType.isScalable()");
        }.onChange("printType"),

        isRotatable: function () {
            return true;
        },

        isRemovable: function () {
            return true;
        },

        price: function () {
            var printTypePrice = this.get('printType.price');
            if (printTypePrice) {
                return printTypePrice.clone();
            }
            return new Price();
        },

        /***
         *
         * @param {sprd.model.PrintType} printType
         * @return {sprd.entity.Size}
         */
        getSizeForPrintType: function (printType) {
            return Size.empty;
        },

        possiblePrintTypes: function (appearance) {
            var ret = [],
                printArea = this.$.printArea;

            if (printArea && appearance) {
                ret = ProductUtil.getPossiblePrintTypesForPrintAreas([printArea], appearance.$.id);
            }

            return ret;
        }.onChange("printArea"),

        isAllowedOnPrintArea: function (printArea) {
            return false;
        },

        getPossiblePrintTypesForPrintArea: function () {
            return [];
        },

        allowScale: function () {
            return true;
        },

        minimumScale: function () {
            return 0;
        },

        isReadyForCompose: function () {
            return true;
        }
    });
});
<|endoftext|>


<commit_before>// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE in the project root for license information.

(function ($) {

  /**
   * DatePicker Plugin
   */

  $.fn.DatePicker = function () {

    return this.each(function () {

      /** Set up variables and run the Pickadate plugin. */
      var $datePicker = $(this);
      var $dateField = $datePicker.find('.ms-TextField-field').pickadate({
        // Strings and translations.
        weekdaysShort: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],

        // Don't render the buttons
        today: '',
        clear: '',
        close: '',

        // Events
        onStart: function() {
          initCustomView($datePicker);
        },

        // Classes
        klass: {

          // The element states
          input: 'ms-DatePicker-input',
          active: 'ms-DatePicker-input--active',

          // The root picker and states
          picker: 'ms-DatePicker-picker',
          opened: 'ms-DatePicker-picker--opened',
          focused: 'ms-DatePicker-picker--focused',

          // The picker holder
          holder: 'ms-DatePicker-holder',

          // The picker frame, wrapper, and box
          frame: 'ms-DatePicker-frame',
          wrap: 'ms-DatePicker-wrap',
          box: 'ms-DatePicker-dayPicker',

          // The picker header
          header: 'ms-DatePicker-header',

          // Month & year labels
          month: 'ms-DatePicker-month',
          year: 'ms-DatePicker-year',

          // Table of dates
          table: 'ms-DatePicker-table',

          // Weekday labels
          weekdays: 'ms-DatePicker-weekday',

          // Day states
          day: 'ms-DatePicker-day',
          disabled: 'ms-DatePicker-day--disabled',
          selected: 'ms-DatePicker-day--selected',
          highlighted: 'ms-DatePicker-day--highlighted',
          now: 'ms-DatePicker-day--today',
          infocus: 'ms-DatePicker-day--infocus',
          outfocus: 'ms-DatePicker-day--outfocus',

        }
      });
      var $picker = $dateField.pickadate('picker');

      /** Respond to built-in picker events. */
      $picker.on({
        render: function() {
          updateCustomView($datePicker);
        },
        open: function() {
          scrollUp($datePicker);
        }
      });

    });
  };

  /**
   * After the Pickadate plugin starts, this function
   * adds additional controls to the picker view.
   */
  function initCustomView($datePicker) {

    /** Get some variables ready. */
    var $monthControls = $datePicker.find('.ms-DatePicker-monthComponents');
    var $goToday = $datePicker.find('.ms-DatePicker-goToday');
    var $dayPicker = $datePicker.find('.ms-DatePicker-dayPicker');
    var $monthPicker = $datePicker.find('.ms-DatePicker-monthPicker');
    var $yearPicker = $datePicker.find('.ms-DatePicker-yearPicker');
    var $pickerWrapper = $datePicker.find('.ms-DatePicker-wrap');
    var $picker = $datePicker.find('.ms-TextField-field').pickadate('picker');

    /** Move the month picker into position. */
    $monthControls.appendTo($pickerWrapper);
    $goToday.appendTo($pickerWrapper);
    $monthPicker.appendTo($pickerWrapper);
    $yearPicker.appendTo($pickerWrapper);

    /** Update the custom view. */
    updateCustomView($datePicker);

    /** Move back one month. */
    $monthControls.on('click', '.js-prevMonth', function(event) {
      event.preventDefault();
      var newMonth = $picker.get('highlight').month - 1;
      changeHighlightedDate($picker, null, newMonth, null);
    });

    /** Move ahead one month. */
    $monthControls.on('click', '.js-nextMonth', function(event) {
      event.preventDefault();
      var newMonth = $picker.get('highlight').month + 1;
      changeHighlightedDate($picker, null, newMonth, null);
    });

    /** Move back one year. */
    $monthPicker.on('click', '.js-prevYear', function(event) {
      event.preventDefault();
      var newYear = $picker.get('highlight').year - 1;
      changeHighlightedDate($picker, newYear, null, null);
    });

    /** Move ahead one year. */
    $monthPicker.on('click', '.js-nextYear', function(event) {
      event.preventDefault();
      var newYear = $picker.get('highlight').year + 1;
      changeHighlightedDate($picker, newYear, null, null);
    });

    /** Move back one decade. */
    $yearPicker.on('click', '.js-prevDecade', function(event) {
      event.preventDefault();
      var newYear = $picker.get('highlight').year - 10;
      changeHighlightedDate($picker, newYear, null, null);
    });

    /** Move ahead one decade. */
    $yearPicker.on('click', '.js-nextDecade', function(event) {
      event.preventDefault();
      var newYear = $picker.get('highlight').year + 10;
      changeHighlightedDate($picker, newYear, null, null);
    });

    /** Go to the current date, shown in the day picking view. */
    $goToday.click(function(event) {
      event.preventDefault();

      /** Select the current date, while keeping the picker open. */
      var now = new Date();
      $picker.set('select', [now.getFullYear(), now.getMonth(), now.getDate()]);

      /** Switch to the default (calendar) view. */
      $datePicker.removeClass('is-pickingMonths').removeClass('is-pickingYears');

    });

    /** Change the highlighted month. */
    $monthPicker.on('click', '.js-changeDate', function(event) {
      event.preventDefault();

      /** Get the requested date from the data attributes. */
      var newYear = $(this).attr('data-year');
      var newMonth = $(this).attr('data-month');
      var newDay = $(this).attr('data-day');

      /** Update the date. */
      changeHighlightedDate($picker, newYear, newMonth, newDay);

      /** If we've been in the "picking months" state on mobile, remove that state so we show the calendar again. */
      if ($datePicker.hasClass('is-pickingMonths')) {
        $datePicker.removeClass('is-pickingMonths');
      }
    });

    /** Change the highlighted year. */
    $yearPicker.on('click', '.js-changeDate', function(event) {
      event.preventDefault();

      /** Get the requested date from the data attributes. */
      var newYear = $(this).attr('data-year');
      var newMonth = $(this).attr('data-month');
      var newDay = $(this).attr('data-day');

      /** Update the date. */
      changeHighlightedDate($picker, newYear, newMonth, newDay);

      /** If we've been in the "picking years" state on mobile, remove that state so we show the calendar again. */
      if ($datePicker.hasClass('is-pickingYears')) {
        $datePicker.removeClass('is-pickingYears');
      }
    });

    /** Switch to the default state. */
    $monthPicker.on('click', '.js-showDayPicker', function(event) {
      $datePicker.removeClass('is-pickingMonths');
      $datePicker.removeClass('is-pickingYears');
    });

    /** Switch to the is-pickingMonths state. */
    $monthControls.on('click', '.js-showMonthPicker', function(event) {
      $datePicker.toggleClass('is-pickingMonths');
    });

    /** Switch to the is-pickingYears state. */
    $monthPicker.on('click', '.js-showYearPicker', function(event) {
      $datePicker.toggleClass('is-pickingYears');
    });

  }

  /** Change the highlighted date. */
  function changeHighlightedDate($picker, newYear, newMonth, newDay) {

    /** All variables are optional. If not provided, default to the current value. */
    if (newYear == null) {
      newYear = $picker.get('highlight').year;
    }
    if (newMonth == null) {
      newMonth = $picker.get('highlight').month;
    }
    if (newDay == null) {
      newDay = $picker.get('highlight').date;
    }

    /** Update it. */
    $picker.set('highlight', [newYear, newMonth, newDay]);

  }

  /** Whenever the picker renders, do our own rendering on the custom controls. */
  function updateCustomView($datePicker) {

    /** Get some variables ready. */
    var $monthPicker = $datePicker.find('.ms-DatePicker-monthPicker');
    var $yearPicker = $datePicker.find('.ms-DatePicker-yearPicker');
    var $pickerWrapper = $datePicker.find('.ms-DatePicker-wrap');
    var $picker = $datePicker.find('.ms-TextField-field').pickadate('picker');

    /** Set the correct year. */
    $monthPicker.find('.ms-DatePicker-currentYear').text($picker.get('view').year);

    /** Highlight the current month. */
    $monthPicker.find('.ms-DatePicker-monthOption').removeClass('is-highlighted')
    $monthPicker.find('.ms-DatePicker-monthOption[data-month="' + $picker.get('highlight').month + '"]').addClass('is-highlighted');

    /** Generate the grid of years for the year picker view. */

      // Start by removing any existing generated output. */
    $yearPicker.find('.ms-DatePicker-currentDecade').remove();
    $yearPicker.find('.ms-DatePicker-optionGrid').remove();

    // Generate the output by going through the years.
    var startingYear = $picker.get('highlight').year - 11;
    var decadeText = startingYear + " - " + (startingYear + 11);
    var output = '
' + decadeText + '
';
    output += '
';
    for (year = startingYear; year < (startingYear + 12); year++) {
      output += '' + year +'';
    }
    output += '
';

    // Output the title and grid of years generated above.
    $yearPicker.append(output);

    /** Highlight the current year. */
    $yearPicker.find('.ms-DatePicker-yearOption').removeClass('is-highlighted')
    $yearPicker.find('.ms-DatePicker-yearOption[data-year="' + $picker.get('highlight').year + '"]').addClass('is-highlighted');
  }

  /** Scroll the page up so that the field the date picker is attached to is at the top. */
  function scrollUp($datePicker) {
    $('html, body').animate({
      scrollTop: $datePicker.offset().top
    }, 367);
  }

})(jQuery);<commit_msg>made DatePicker configurable<commit_after>// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See LICENSE in the project root for license information.

(function ($) {

  /**
   * DatePicker Plugin
   */

  $.fn.DatePicker = function (options) {

    return this.each(function () {

      /** Set up variables and run the Pickadate plugin. */
      var $datePicker = $(this);
      var $dateField = $datePicker.find('.ms-TextField-field').pickadate($.extend({
        // Strings and translations.
        weekdaysShort: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],

        // Don't render the buttons
        today: '',
        clear: '',
        close: '',

        // Events
        onStart: function() {
          initCustomView($datePicker);
        },

        // Classes
        klass: {

          // The element states
          input: 'ms-DatePicker-input',
          active: 'ms-DatePicker-input--active',

          // The root picker and states
          picker: 'ms-DatePicker-picker',
          opened: 'ms-DatePicker-picker--opened',
          focused: 'ms-DatePicker-picker--focused',

          // The picker holder
          holder: 'ms-DatePicker-holder',

          // The picker frame, wrapper, and box
          frame: 'ms-DatePicker-frame',
          wrap: 'ms-DatePicker-wrap',
          box: 'ms-DatePicker-dayPicker',

          // The picker header
          header: 'ms-DatePicker-header',

          // Month & year labels
          month: 'ms-DatePicker-month',
          year: 'ms-DatePicker-year',

          // Table of dates
          table: 'ms-DatePicker-table',

          // Weekday labels
          weekdays: 'ms-DatePicker-weekday',

          // Day states
          day: 'ms-DatePicker-day',
          disabled: 'ms-DatePicker-day--disabled',
          selected: 'ms-DatePicker-day--selected',
          highlighted: 'ms-DatePicker-day--highlighted',
          now: 'ms-DatePicker-day--today',
          infocus: 'ms-DatePicker-day--infocus',
          outfocus: 'ms-DatePicker-day--outfocus',

        }
      },options));
      var $picker = $dateField.pickadate('picker');

      /** Respond to built-in picker events. */
      $picker.on({
        render: function() {
          updateCustomView($datePicker);
        },
        open: function() {
          scrollUp($datePicker);
        }
      });

    });
  };

  /**
   * After the Pickadate plugin starts, this function
   * adds additional controls to the picker view.
   */
  function initCustomView($datePicker) {

    /** Get some variables ready. */
    var $monthControls = $datePicker.find('.ms-DatePicker-monthComponents');
    var $goToday = $datePicker.find('.ms-DatePicker-goToday');
    var $dayPicker = $datePicker.find('.ms-DatePicker-dayPicker');
    var $monthPicker = $datePicker.find('.ms-DatePicker-monthPicker');
    var $yearPicker = $datePicker.find('.ms-DatePicker-yearPicker');
    var $pickerWrapper = $datePicker.find('.ms-DatePicker-wrap');
    var $picker = $datePicker.find('.ms-TextField-field').pickadate('picker');

    /** Move the month picker into position. */
    $monthControls.appendTo($pickerWrapper);
    $goToday.appendTo($pickerWrapper);
    $monthPicker.appendTo($pickerWrapper);
    $yearPicker.appendTo($pickerWrapper);

    /** Update the custom view. */
    updateCustomView($datePicker);

    /** Move back one month. */
    $monthControls.on('click', '.js-prevMonth', function(event) {
      event.preventDefault();
      var newMonth = $picker.get('highlight').month - 1;
      changeHighlightedDate($picker, null, newMonth, null);
    });

    /** Move ahead one month. */
    $monthControls.on('click', '.js-nextMonth', function(event) {
      event.preventDefault();
      var newMonth = $picker.get('highlight').month + 1;
      changeHighlightedDate($picker, null, newMonth, null);
    });

    /** Move back one year. */
    $monthPicker.on('click', '.js-prevYear', function(event) {
      event.preventDefault();
      var newYear = $picker.get('highlight').year - 1;
      changeHighlightedDate($picker, newYear, null, null);
    });

    /** Move ahead one year. */
    $monthPicker.on('click', '.js-nextYear', function(event) {
      event.preventDefault();
      var newYear = $picker.get('highlight').year + 1;
      changeHighlightedDate($picker, newYear, null, null);
    });

    /** Move back one decade. */
    $yearPicker.on('click', '.js-prevDecade', function(event) {
      event.preventDefault();
      var newYear = $picker.get('highlight').year - 10;
      changeHighlightedDate($picker, newYear, null, null);
    });

    /** Move ahead one decade. */
    $yearPicker.on('click', '.js-nextDecade', function(event) {
      event.preventDefault();
      var newYear = $picker.get('highlight').year + 10;
      changeHighlightedDate($picker, newYear, null, null);
    });

    /** Go to the current date, shown in the day picking view. */
    $goToday.click(function(event) {
      event.preventDefault();

      /** Select the current date, while keeping the picker open. */
      var now = new Date();
      $picker.set('select', [now.getFullYear(), now.getMonth(), now.getDate()]);

      /** Switch to the default (calendar) view. */
      $datePicker.removeClass('is-pickingMonths').removeClass('is-pickingYears');

    });

    /** Change the highlighted month. */
    $monthPicker.on('click', '.js-changeDate', function(event) {
      event.preventDefault();

      /** Get the requested date from the data attributes. */
      var newYear = $(this).attr('data-year');
      var newMonth = $(this).attr('data-month');
      var newDay = $(this).attr('data-day');

      /** Update the date. */
      changeHighlightedDate($picker, newYear, newMonth, newDay);

      /** If we've been in the "picking months" state on mobile, remove that state so we show the calendar again. */
      if ($datePicker.hasClass('is-pickingMonths')) {
        $datePicker.removeClass('is-pickingMonths');
      }
    });

    /** Change the highlighted year. */
    $yearPicker.on('click', '.js-changeDate', function(event) {
      event.preventDefault();

      /** Get the requested date from the data attributes. */
      var newYear = $(this).attr('data-year');
      var newMonth = $(this).attr('data-month');
      var newDay = $(this).attr('data-day');

      /** Update the date. */
      changeHighlightedDate($picker, newYear, newMonth, newDay);

      /** If we've been in the "picking years" state on mobile, remove that state so we show the calendar again. */
      if ($datePicker.hasClass('is-pickingYears')) {
        $datePicker.removeClass('is-pickingYears');
      }
    });

    /** Switch to the default state. */
    $monthPicker.on('click', '.js-showDayPicker', function(event) {
      $datePicker.removeClass('is-pickingMonths');
      $datePicker.removeClass('is-pickingYears');
    });

    /** Switch to the is-pickingMonths state. */
    $monthControls.on('click', '.js-showMonthPicker', function(event) {
      $datePicker.toggleClass('is-pickingMonths');
    });

    /** Switch to the is-pickingYears state. */
    $monthPicker.on('click', '.js-showYearPicker', function(event) {
      $datePicker.toggleClass('is-pickingYears');
    });

  }

  /** Change the highlighted date. */
  function changeHighlightedDate($picker, newYear, newMonth, newDay) {

    /** All variables are optional. If not provided, default to the current value. */
    if (newYear == null) {
      newYear = $picker.get('highlight').year;
    }
    if (newMonth == null) {
      newMonth = $picker.get('highlight').month;
    }
    if (newDay == null) {
      newDay = $picker.get('highlight').date;
    }

    /** Update it. */
    $picker.set('highlight', [newYear, newMonth, newDay]);

  }

  /** Whenever the picker renders, do our own rendering on the custom controls. */
  function updateCustomView($datePicker) {

    /** Get some variables ready. */
    var $monthPicker = $datePicker.find('.ms-DatePicker-monthPicker');
    var $yearPicker = $datePicker.find('.ms-DatePicker-yearPicker');
    var $pickerWrapper = $datePicker.find('.ms-DatePicker-wrap');
    var $picker = $datePicker.find('.ms-TextField-field').pickadate('picker');

    /** Set the correct year. */
    $monthPicker.find('.ms-DatePicker-currentYear').text($picker.get('view').year);

    /** Highlight the current month. */
    $monthPicker.find('.ms-DatePicker-monthOption').removeClass('is-highlighted')
    $monthPicker.find('.ms-DatePicker-monthOption[data-month="' + $picker.get('highlight').month + '"]').addClass('is-highlighted');

    /** Generate the grid of years for the year picker view. */

      // Start by removing any existing generated output. */
    $yearPicker.find('.ms-DatePicker-currentDecade').remove();
    $yearPicker.find('.ms-DatePicker-optionGrid').remove();

    // Generate the output by going through the years.
    var startingYear = $picker.get('highlight').year - 11;
    var decadeText = startingYear + " - " + (startingYear + 11);
    var output = '
' + decadeText + '
';
    output += '
';
    for (year = startingYear; year < (startingYear + 12); year++) {
      output += '' + year +'';
    }
    output += '
';

    // Output the title and grid of years generated above.
    $yearPicker.append(output);

    /** Highlight the current year. */
    $yearPicker.find('.ms-DatePicker-yearOption').removeClass('is-highlighted')
    $yearPicker.find('.ms-DatePicker-yearOption[data-year="' + $picker.get('highlight').year + '"]').addClass('is-highlighted');
  }

  /** Scroll the page up so that the field the date picker is attached to is at the top. */
  function scrollUp($datePicker) {
    $('html, body').animate({
      scrollTop: $datePicker.offset().top
    }, 367);
  }

})(jQuery);
<|endoftext|>


<commit_before><commit_msg>overwrite existing file<commit_after><|endoftext|>