<commit_before>(function(exports) {

	var states = {UNFULFILLED: 0, FULFILLED: 1, FAILED: 2};

	function Promise() {
		this._state = states.UNFULFILLED;
		this._value = null;
		this._handlers = [];
	}

	Promise.defer = typeof process != 'undefined' ? process.nextTick : function(fn) {
		setTimeout(fn, 0);
	};

	Promise.prototype.fulfill = function(value) {
		var self = this;
		if (this._state) return;
		this._value = value;
		this._state = states.FULFILLED;
		Promise.defer(function() { self._runHandlers(); });
		return;
	};

	Promise.prototype.fail = function(error) {
		var self = this;
		if (this._state) return;
		this._value = error;
		this._state = states.FAILED;
		Promise.defer(function() { self._runHandlers(); });
		return;
	};

	Promise.prototype.then = function(fulfilledHandler, failedHandler) {
		var self = this;
		var promise = new Promise();
		this._handlers.push({
			fulfilled: fulfilledHandler,
			failed: failedHandler,
			promise: promise
		});
		if (this._state !== states.UNFULFILLED)
			Promise.defer(function() { self._runHandlers(); });
		return promise;
	};

	Promise.prototype.join = function(promise) {
		this.then(function(value) {
			promise.fulfill(value);
		}, function(error) {
			promise.fail(error);
		});
		return this;
	};

	Promise.prototype._runHandlers = function() {
		var value = this._value;
		if (this._state == states.UNFULFILLED) return;
		var fulfilled = this._state === states.FULFILLED;
		var handlers = this._handlers.splice(0);
		for (var i = 0, l = handlers.length; i < l; i++) {
			var handler = handlers[i];
			var callback = handler[fulfilled ? 'fulfilled' : 'failed'];
			var promise = handler.promise;
			if (!callback) {
				if (fulfilled) promise.fulfill(value);
				else promise.fail(value);
				continue;
			}
			try {
				var returnValue = callback(value);
			} catch (e) {
				promise.fail(e);
				continue;
			}
			if (returnValue instanceof Promise) {
				returnValue.join(promise);
			} else {
				if (!fulfilled && returnValue === undefined) {
					promise.fail(returnValue);
				} else {
					promise.fulfill(returnValue);
				}
			}
		}
	};

	exports.Promise = Promise;

})(typeof exports != 'undefined' ? exports : this);
<commit_msg>Explicitly compare the state rather than rely on the fact that states.UNFULFILLED is an integer.<commit_after>(function(exports) {

	var states = {UNFULFILLED: 0, FULFILLED: 1, FAILED: 2};

	function Promise() {
		this._state = states.UNFULFILLED;
		this._value = null;
		this._handlers = [];
	}

	Promise.defer = typeof process != 'undefined' ? process.nextTick : function(fn) {
		setTimeout(fn, 0);
	};

	Promise.prototype.fulfill = function(value) {
		var self = this;
		if (this._state !== states.UNFULFILLED) return;
		this._value = value;
		this._state = states.FULFILLED;
		Promise.defer(function() { self._runHandlers(); });
		return;
	};

	Promise.prototype.fail = function(error) {
		var self = this;
		if (this._state !== states.UNFULFILLED) return;
		this._value = error;
		this._state = states.FAILED;
		Promise.defer(function() { self._runHandlers(); });
		return;
	};

	Promise.prototype.then = function(fulfilledHandler, failedHandler) {
		var self = this;
		var promise = new Promise();
		this._handlers.push({
			fulfilled: fulfilledHandler,
			failed: failedHandler,
			promise: promise
		});
		if (this._state !== states.UNFULFILLED)
			Promise.defer(function() { self._runHandlers(); });
		return promise;
	};

	Promise.prototype.join = function(promise) {
		this.then(function(value) {
			promise.fulfill(value);
		}, function(error) {
			promise.fail(error);
		});
		return this;
	};

	Promise.prototype._runHandlers = function() {
		var value = this._value;
		if (this._state == states.UNFULFILLED) return;
		var fulfilled = this._state === states.FULFILLED;
		var handlers = this._handlers.splice(0);
		for (var i = 0, l = handlers.length; i < l; i++) {
			var handler = handlers[i];
			var callback = handler[fulfilled ? 'fulfilled' : 'failed'];
			var promise = handler.promise;
			if (!callback) {
				if (fulfilled) promise.fulfill(value);
				else promise.fail(value);
				continue;
			}
			try {
				var returnValue = callback(value);
			} catch (e) {
				promise.fail(e);
				continue;
			}
			if (returnValue instanceof Promise) {
				returnValue.join(promise);
			} else {
				if (!fulfilled && returnValue === undefined) {
					promise.fail(returnValue);
				} else {
					promise.fulfill(returnValue);
				}
			}
		}
	};

	exports.Promise = Promise;

})(typeof exports != 'undefined' ? exports : this);
<|endoftext|>


<commit_before>var cookieName = 'mapData';
var interactiveLayerId = 'label-amenity';
var defaultType = defaultType || 'map';

var mapTypes = {
  map: 'm',
  orto: 'o',
  hybrid: 'h'
};
var mapData = {
  type: defaultType,
  zoom: 7,
  lat: 55.19114,
  lng: 23.87100,
  bearing: 0,
  pitch: 0
};

var showAttributes = [
  'name',
  'official_name',
  'opening_hours',
  'website',
  'image'
];

var label = {
  official_name: 'Oficialus pavadinimas'
};

var icons = {
  opening_hours: "glyphicon glyphicon-time",
  website: 'glyphicon glyphicon-globe'
};

var attributeType = {
  name: 'bold',
  website: 'link',
  image: 'image'
};

if (!mapboxgl.supported()) {
  alert('Jūsų naršyklė nepalaiko Mapbox GL. Prašome atsinaujinti naršyklę.');
} else {
  if (hashData = getMapDataFromHashUrl()) {
    $.extend(mapData, hashData);
  }

  if (!hashData && (cookieData = readCookie(cookieName))) {
    $.extend(mapData, cookieData);
  }

  $("button[data-style='" + mapData.type + "']").addClass('active');
  $('#layers').removeClass('hidden');

  changeHashUrl();

  var map = new mapboxgl.Map({
    container: 'map',
    style: 'styles/' + mapData.type + '.json',
    zoom: mapData.zoom,
    minZoom: 7,
    maxZoom: 18,
    center: [mapData.lng, mapData.lat],
    hash: false,
    maxBounds: [20.880, 53.888, 26.862, 56.453],
    bearing: mapData.bearing,
    pitch: mapData.pitch
  })
    .addControl(new mapboxgl.NavigationControl(), 'top-left')
    .addControl(new mapboxgl.GeolocateControl({
      positionOptions: {
        enableHighAccuracy: true
      },
      trackUserLocation: true
    }), 'top-left')
    .on('sourcedata', function () {
      if (map.isStyleLoaded()) {
        poiInteractive();
      }
    })
    .on('moveend', function () {
      setMapData();
      changeHashUrl();
    });
}

$('#layers button').on('click', function (e) {
  if ($(this).hasClass('active')) {
    return false;
  }
  $('#layers button').removeClass('active');
  $(this).addClass('active');

  var selectLayer = $(e.target).data('style');
  map.setStyle('styles/' + selectLayer + '.json');

  mapData.type = selectLayer;
  changeHashUrl(mapData);
});

function changeHashUrl() {
  var formatHash = [];
  for (var key in mapData) {
    var value = mapData[key];
    if (key === 'type') {
      value = mapTypes[mapData.type]
    }
    formatHash.push(value);
  }
  window.location.hash = '#' + formatHash.join('/');
  storeCookie(cookieName, mapData);
}

function getMapDataFromHashUrl() {
  var hash = window.location.hash;
  if (hash.length > 0) {
    hash = hash.replace('#', '');

    // Add support old hash format: #l=55.23777,23.871,8,L
    var result = hash.match(new RegExp('l=([^]+)'));
    if (result) {
      var mapQueries = result[1].split(',');
      return {
        lat: parseFloat(mapQueries[0]),
        lng: parseFloat(mapQueries[1]),
        zoom: parseInt(mapQueries[2])
      };
    }

    var mapQueries = hash.split('/');

    // Add support old hash format: #8/55.23777/23.871
    if (mapQueries.length === 3) {
      return {
        zoom: parseFloat(mapQueries[0]),
        lat: parseFloat(mapQueries[1]),
        lng: parseFloat(mapQueries[2])
      }
    }

    if (mapQueries.length < 6) {
      return null;
    }

    var type = defaultType;
    for (var key in mapTypes) {
      if (mapTypes[key] === mapQueries[0]) {
        type = key;
        break;
      }
    }

    return {
      type: type,
      zoom: parseFloat(mapQueries[1]),
      lat: parseFloat(mapQueries[2]),
      lng: parseFloat(mapQueries[3]),
      bearing: parseInt(mapQueries[4]),
      pitch: parseInt(mapQueries[5])
    };
  }
  return null;
}

function setMapData() {
  mapData.zoom = Number(map.getZoom().toFixed(2));
  mapData.lat = Number(map.getCenter().lat.toFixed(5));
  mapData.lng = Number(map.getCenter().lng.toFixed(5));
  mapData.bearing = parseInt(map.getBearing());
  mapData.pitch = parseInt(map.getPitch());
}

function storeCookie(name, value) {
  var date = new Date();
  date.setDate(date.getDate() + 365);
  var expires = "expires=" + date.toUTCString();
  document.cookie = name + '=' + JSON.stringify(value) + ';domain=.' + window.location.host.toString() + ';path=/;' + expires;
}

function readCookie(name) {
  var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
  if (result) {
    return JSON.parse(result[1]);
  }
  return null;
}

function poiInteractive() {
  map.off('mouseenter', interactiveLayerId, addMousePointerCursor);
  map.off('mouseleave', interactiveLayerId, removeMousePointerCursor);
  map.off('click', interactiveLayerId, poiOnClick);

  if (map.getLayer(interactiveLayerId)) {
    map.on('mouseenter', interactiveLayerId, addMousePointerCursor);
    map.on('mouseleave', interactiveLayerId, removeMousePointerCursor);
    map.on('click', interactiveLayerId, poiOnClick);
  }
}

function addMousePointerCursor() {
  map.getCanvas().style.cursor = 'pointer';
}

function removeMousePointerCursor() {
  map.getCanvas().style.cursor = '';
}

function poiOnClick(e) {
  var poi = e.features[0];
  var html = getHtml(poi).join('
');

  if (html.length) {
    new mapboxgl.Popup()
      .setLngLat(poi.geometry.coordinates)
      .setHTML(html)
      .addTo(map);
  }
}

function getHtml(poi) {
  return showAttributes
    .filter(function (prop_name) {
      return poi.properties[prop_name];
    })
    .map(function (prop_name) {
      var formatedValue = getFomatedValue(prop_name, poi.properties[prop_name]);

      if (icons[prop_name]) {
        return ' ' + formatedValue;
      }

      if (label[prop_name]) {
        return '' + label[prop_name] + ': ' + formatedValue;
      }

      return formatedValue;
    });
}

function getFomatedValue(attribute, value) {
  switch (attributeType[attribute]) {
    case 'bold':
      return '' + value + '';
    case 'link':
      return '' + value + '';
    case 'image':
      return '';
  }

  return value;
}<commit_msg>add new map types<commit_after>var cookieName = 'mapData';
var interactiveLayerId = 'label-amenity';
var defaultType = defaultType || 'map';

var mapTypes = {
  map: 'm',
  orto: 'o',
  hybrid: 'h',
  bicycle: 'b',
  bicycle_hybrid: 'bh'
};
var mapData = {
  type: defaultType,
  zoom: 7,
  lat: 55.19114,
  lng: 23.87100,
  bearing: 0,
  pitch: 0
};

var showAttributes = [
  'name',
  'official_name',
  'opening_hours',
  'website',
  'image'
];

var label = {
  official_name: 'Oficialus pavadinimas'
};

var icons = {
  opening_hours: "glyphicon glyphicon-time",
  website: 'glyphicon glyphicon-globe'
};

var attributeType = {
  name: 'bold',
  website: 'link',
  image: 'image'
};

if (!mapboxgl.supported()) {
  alert('Jūsų naršyklė nepalaiko Mapbox GL. Prašome atsinaujinti naršyklę.');
} else {
  if (hashData = getMapDataFromHashUrl()) {
    $.extend(mapData, hashData);
  }

  if (!hashData && (cookieData = readCookie(cookieName))) {
    $.extend(mapData, cookieData);
  }

  $("button[data-style='" + mapData.type + "']").addClass('active');
  $('#layers').removeClass('hidden');

  changeHashUrl();

  var map = new mapboxgl.Map({
    container: 'map',
    style: 'styles/' + mapData.type + '.json',
    zoom: mapData.zoom,
    minZoom: 7,
    maxZoom: 18,
    center: [mapData.lng, mapData.lat],
    hash: false,
    maxBounds: [20.880, 53.888, 26.862, 56.453],
    bearing: mapData.bearing,
    pitch: mapData.pitch
  })
    .addControl(new mapboxgl.NavigationControl(), 'top-left')
    .addControl(new mapboxgl.GeolocateControl({
      positionOptions: {
        enableHighAccuracy: true
      },
      trackUserLocation: true
    }), 'top-left')
    .on('sourcedata', function () {
      if (map.isStyleLoaded()) {
        poiInteractive();
      }
    })
    .on('moveend', function () {
      setMapData();
      changeHashUrl();
    });
}

$('#layers button').on('click', function (e) {
  if ($(this).hasClass('active')) {
    return false;
  }
  $('#layers button').removeClass('active');
  $(this).addClass('active');

  var selectLayer = $(e.target).data('style');
  map.setStyle('styles/' + selectLayer + '.json');

  mapData.type = selectLayer;
  changeHashUrl(mapData);
});

function changeHashUrl() {
  var formatHash = [];
  for (var key in mapData) {
    var value = mapData[key];
    if (key === 'type') {
      value = mapTypes[mapData.type]
    }
    formatHash.push(value);
  }
  window.location.hash = '#' + formatHash.join('/');
  storeCookie(cookieName, mapData);
}

function getMapDataFromHashUrl() {
  var hash = window.location.hash;
  if (hash.length > 0) {
    hash = hash.replace('#', '');

    // Add support old hash format: #l=55.23777,23.871,8,L
    var result = hash.match(new RegExp('l=([^]+)'));
    if (result) {
      var mapQueries = result[1].split(',');
      return {
        lat: parseFloat(mapQueries[0]),
        lng: parseFloat(mapQueries[1]),
        zoom: parseInt(mapQueries[2])
      };
    }

    var mapQueries = hash.split('/');

    // Add support old hash format: #8/55.23777/23.871
    if (mapQueries.length === 3) {
      return {
        zoom: parseFloat(mapQueries[0]),
        lat: parseFloat(mapQueries[1]),
        lng: parseFloat(mapQueries[2])
      }
    }

    if (mapQueries.length < 6) {
      return null;
    }

    var type = defaultType;
    for (var key in mapTypes) {
      if (mapTypes[key] === mapQueries[0]) {
        type = key;
        break;
      }
    }

    return {
      type: type,
      zoom: parseFloat(mapQueries[1]),
      lat: parseFloat(mapQueries[2]),
      lng: parseFloat(mapQueries[3]),
      bearing: parseInt(mapQueries[4]),
      pitch: parseInt(mapQueries[5])
    };
  }
  return null;
}

function setMapData() {
  mapData.zoom = Number(map.getZoom().toFixed(2));
  mapData.lat = Number(map.getCenter().lat.toFixed(5));
  mapData.lng = Number(map.getCenter().lng.toFixed(5));
  mapData.bearing = parseInt(map.getBearing());
  mapData.pitch = parseInt(map.getPitch());
}

function storeCookie(name, value) {
  var date = new Date();
  date.setDate(date.getDate() + 365);
  var expires = "expires=" + date.toUTCString();
  document.cookie = name + '=' + JSON.stringify(value) + ';domain=.' + window.location.host.toString() + ';path=/;' + expires;
}

function readCookie(name) {
  var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
  if (result) {
    return JSON.parse(result[1]);
  }
  return null;
}

function poiInteractive() {
  map.off('mouseenter', interactiveLayerId, addMousePointerCursor);
  map.off('mouseleave', interactiveLayerId, removeMousePointerCursor);
  map.off('click', interactiveLayerId, poiOnClick);

  if (map.getLayer(interactiveLayerId)) {
    map.on('mouseenter', interactiveLayerId, addMousePointerCursor);
    map.on('mouseleave', interactiveLayerId, removeMousePointerCursor);
    map.on('click', interactiveLayerId, poiOnClick);
  }
}

function addMousePointerCursor() {
  map.getCanvas().style.cursor = 'pointer';
}

function removeMousePointerCursor() {
  map.getCanvas().style.cursor = '';
}

function poiOnClick(e) {
  var poi = e.features[0];
  var html = getHtml(poi).join('
');

  if (html.length) {
    new mapboxgl.Popup()
      .setLngLat(poi.geometry.coordinates)
      .setHTML(html)
      .addTo(map);
  }
}

function getHtml(poi) {
  return showAttributes
    .filter(function (prop_name) {
      return poi.properties[prop_name];
    })
    .map(function (prop_name) {
      var formatedValue = getFomatedValue(prop_name, poi.properties[prop_name]);

      if (icons[prop_name]) {
        return ' ' + formatedValue;
      }

      if (label[prop_name]) {
        return '' + label[prop_name] + ': ' + formatedValue;
      }

      return formatedValue;
    });
}

function getFomatedValue(attribute, value) {
  switch (attributeType[attribute]) {
    case 'bold':
      return '' + value + '';
    case 'link':
      return '' + value + '';
    case 'image':
      return '';
  }

  return value;
}<|endoftext|>


<commit_before>function sync() {
  setTimeout(deferred,1000)
  console.log('sync');
}
function deferred() {
  console.log('deferred');
}
 sync()
 deferred()
<commit_msg>getting data from spotify<commit_after>fetch('https://api.spotify.com/v1/search?query=psytrance&offset=0&limit=20&type=artist')
.then(response =>response.json())
.then(data=> {
  const uris = data.artists.items.map(item=> {
    return item.uri
  }).slice(0,5)
  console.log(uris)
  document.write(uris)
})
<|endoftext|>


<commit_before>var interactiveLayerId = 'label-amenity';
var defaultType = defaultType || 'map';
var cookieName = defaultType + 'Data';

var mapTypes = mapTypes || {
  map: 'm',
  orto: 'o',
  hybrid: 'h'
};
var mapData = {
  type: defaultType,
  zoom: 7,
  lat: 55.19114,
  lng: 23.87100,
  bearing: 0,
  pitch: 0
};

var showAttributes = [
  'name',
  'official_name',
  'alt_name',
  'street',
  'opening_hours',
  'email',
  'phone',
  'website',
  'heritage',
  'wikipedia',
  'height',
  'fee',
  'image',
  'style_lager'
];

var label = {
  official_name: 'Oficialus pavadinimas',
  alt_name: 'Kiti pavadinimai',
  street: 'Adresas',
  email: 'E-paštas',
  phone: 'Telefono nr.',
  fee: 'Mokestis'
};

var icons = {
  opening_hours: "fa fa-clock-o",
  email: 'fa fa-envelope-o',
  phone: 'fa fa-phone',
  website: 'fa fa-globe',
  heritage: 'fa fa-globe',
  wikipedia: 'fa fa-wikipedia-w',
  height: 'fa fa-arrows-v',
  style_lager: 'fa fa-beer'
};

var attributeType = {
  name: 'bold',
  website: 'link',
  image: 'image',
  street: 'address',
  heritage: 'kvr_link',
  wikipedia: 'wikipedia',
  height: 'height',
  fee: 'fee',
  style_lager: 'beer_styles'
};
var legendData = legendData || {};
var legendTechUrl = legendTechUrl || null;

if (!mapboxgl.supported()) {
  alert('Jūsų naršyklė nepalaiko Mapbox GL. Prašome atsinaujinti naršyklę.');
} else {
  if (hashData = getMapDataFromHashUrl()) {
    $.extend(mapData, hashData);
  }

  if (!hashData && (cookieData = readCookie(cookieName))) {
    $.extend(mapData, cookieData);
  }

  $("button[data-style='" + mapData.type + "']").addClass('active');
  $('#layers').removeClass('hidden');

  changeHashUrl();

  var map = new mapboxgl.Map({
    container: 'map',
    style: 'styles/' + mapData.type + '.json',
    zoom: mapData.zoom,
    minZoom: 7,
    maxZoom: 18,
    center: [mapData.lng, mapData.lat],
    hash: false,
    maxBounds: [20.880, 53.888, 26.862, 56.453],
    bearing: mapData.bearing,
    pitch: mapData.pitch
  })
    .addControl(new mapboxgl.NavigationControl(), 'top-left')
    .addControl(new mapboxgl.GeolocateControl({
      positionOptions: {
        enableHighAccuracy: true
      },
      trackUserLocation: true
    }), 'top-left')
    .on('sourcedata', function () {
      if (map.isStyleLoaded()) {
        poiInteractive();
      }
    })
    .on('moveend', function () {
      setMapData();
      changeHashUrl();
    })
    .on('load', function() {
      showLegend();
    });
}

$('#layers button').on('click', function (e) {
  if ($(this).hasClass('active')) {
    return false;
  }
  $('#layers button').removeClass('active');
  $(this).addClass('active');

  var selectLayer = $(e.target).data('style');
  map.setStyle('styles/' + selectLayer + '.json');

  mapData.type = selectLayer;
  changeHashUrl(mapData);
});

function changeHashUrl() {
  var formatHash = [];
  for (var key in mapData) {
    var value = mapData[key];
    if (key === 'type') {
      value = mapTypes[mapData.type]
    }
    formatHash.push(value);
  }
  window.location.hash = '#' + formatHash.join('/');
  storeCookie(cookieName, mapData);
}

function getMapDataFromHashUrl() {
  var hash = window.location.hash;
  if (hash.length > 0) {
    hash = hash.replace('#', '');

    // Add support old hash format: #l=55.23777,23.871,8,L
    var result = hash.match(new RegExp('l=([^]+)'));
    if (result) {
      var mapQueries = result[1].split(',');
      return {
        lat: parseFloat(mapQueries[0]),
        lng: parseFloat(mapQueries[1]),
        zoom: parseInt(mapQueries[2])
      };
    }

    var mapQueries = hash.split('/');

    // Add support old hash format: #8/55.23777/23.871
    if (mapQueries.length === 3) {
      return {
        zoom: parseFloat(mapQueries[0]),
        lat: parseFloat(mapQueries[1]),
        lng: parseFloat(mapQueries[2])
      }
    }

    if (mapQueries.length < 6) {
      return null;
    }

    var type = defaultType;
    for (var key in mapTypes) {
      if (mapTypes[key] === mapQueries[0]) {
        type = key;
        break;
      }
    }

    return {
      type: type,
      zoom: parseFloat(mapQueries[1]),
      lat: parseFloat(mapQueries[2]),
      lng: parseFloat(mapQueries[3]),
      bearing: parseInt(mapQueries[4]),
      pitch: parseInt(mapQueries[5])
    };
  }
  return null;
}

function setMapData() {
  mapData.zoom = Number(map.getZoom().toFixed(2));
  mapData.lat = Number(map.getCenter().lat.toFixed(5));
  mapData.lng = Number(map.getCenter().lng.toFixed(5));
  mapData.bearing = parseInt(map.getBearing());
  mapData.pitch = parseInt(map.getPitch());
}

function storeCookie(name, value) {
  var date = new Date();
  date.setDate(date.getDate() + 365);
  var expires = "expires=" + date.toUTCString();
  document.cookie = name + '=' + JSON.stringify(value) + ';domain=.' + window.location.host.toString() + ';path=/;' + expires;
}

function readCookie(name) {
  var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
  if (result) {
    return JSON.parse(result[1]);
  }
  return null;
}

function poiInteractive() {
  map.off('mouseenter', interactiveLayerId, addMousePointerCursor);
  map.off('mouseleave', interactiveLayerId, removeMousePointerCursor);
  map.off('click', interactiveLayerId, poiOnClick);

  if (map.getLayer(interactiveLayerId)) {
    map.on('mouseenter', interactiveLayerId, addMousePointerCursor);
    map.on('mouseleave', interactiveLayerId, removeMousePointerCursor);
    map.on('click', interactiveLayerId, poiOnClick);
  }
}

function addMousePointerCursor() {
  map.getCanvas().style.cursor = 'pointer';
}

function removeMousePointerCursor() {
  map.getCanvas().style.cursor = '';
}

function poiOnClick(e) {
  var poi = e.features[0];
  var html = getHtml(poi).join('
');

  if (html.length) {
    new mapboxgl.Popup()
      .setLngLat(poi.geometry.coordinates)
      .setHTML(html)
      .addTo(map);
  }
}

function getHtml(poi) {
  return showAttributes
    .filter(function (prop_name) {
      return poi.properties[prop_name];
    })
    .map(function (prop_name) {
      var formatedValue = getFomatedValue(prop_name, poi.properties);

      if (icons[prop_name]) {
        return ' ' + formatedValue;
      }

      if (label[prop_name]) {
        return '' + label[prop_name] + ': ' + formatedValue;
      }

      return formatedValue;
    });
}

function getFomatedValue(attribute, properties) {
  var value = properties[attribute];
  switch (attributeType[attribute]) {
    case 'bold':
      return '' + value + '';
    case 'height':
      return value + ' m.';
    case 'fee':
      return value === 'yes' ? 'Yra' : 'Nėra';
    case 'link':
      return '' + value + '';
    case 'kvr_link':
      return 'Kultūros vertybių registras';
    case 'image':
      return '';
    case 'address':
      return [properties['city'], properties['street'], properties['housenumber']].join(' ');
    case 'wikipedia':
      var splitValue = value.split(':');
      return '' + splitValue[1] + '';
    case 'beer_styles':
      var styles = '';
      if (properties['style_lager'] == 'y') {
        styles += 'lageris';
      }
      if (properties['style_ale'] == 'y') {
        if (styles.length > 0) {
          styles += ', ';
        }
        styles += 'elis';
      }
      if (properties['style_stout'] == 'y') {
        if (styles.length > 0) {
          styles += ', ';
        }
        styles += 'stautas';
      }
      if (properties['style_ipa'] == 'y') {
        if (styles.length > 0) {
          styles += ', ';
        }
        styles += 'IPA';
      }
      return 'Stiliai: ' + styles;
  }

  return value;
}

function showLegend() {
  if (Object.keys(legendData).length === 0) {
    return;
  }

  var legendBlock = document.createElement('div');;
  legendBlock.id = 'legend';
  legendBlock.classList.add('map-overlay');

  var legendHeader = document.createElement('strong');
  legendHeader.classList.add('legend-header');
  legendHeader.innerHTML = 'Sutartiniai ženklai';
  legendHeader.addEventListener('click', function (e) {
    e.stopPropagation();
    legendBlock.classList.toggle('active');
  });
  legendBlock.addEventListener('click', function(e) {
    e.stopPropagation();
    legendBlock.classList.add('active');
  });
  document.body.addEventListener('click', function() {
    if (legendBlock.classList.contains('active')) {
      legendBlock.classList.remove('active');
    }
  });

  legendBlock.appendChild(legendHeader);

  var ul = document.createElement('ul');
  ul.classList.add('legend-items');

  for (var key in legendData) {
    if (!legendData.hasOwnProperty(key)) {
      continue;
    }

    var legend = legendData[key];

    if (!legend.type) {
      continue;
    }

    var legendSymbolIcon = document.createElement('span');
    legendSymbolIcon.classList.add('label-' + legend.type, key);

    var legendSymbol = document.createElement('span');
    legendSymbol.classList.add('label-item');
    legendSymbol.appendChild(legendSymbolIcon);

    var legendItem = document.createElement('li');
    legendItem.appendChild(legendSymbol);
    legendItem.insertAdjacentHTML('beforeend', legend.label);

    ul.appendChild(legendItem);
  }
  legendBlock.appendChild(ul);

  if (legendTechUrl) {
    var legendUrl = document.createElement('a');
    legendUrl.classList.add('legend-doc');
    legendUrl.setAttribute('href', legendTechUrl);
    legendUrl.setAttribute('target', '_blank');
    legendUrl.innerHTML = 'Techninė informaciją';
    legendBlock.appendChild(legendUrl);
  }

  document.body.appendChild(legendBlock);
}<commit_msg>Supaprastintas Craft žemėlapio javascript<commit_after>var interactiveLayerId = 'label-amenity';
var defaultType = defaultType || 'map';
var cookieName = defaultType + 'Data';

var mapTypes = mapTypes || {
  map: 'm',
  orto: 'o',
  hybrid: 'h'
};
var mapData = {
  type: defaultType,
  zoom: 7,
  lat: 55.19114,
  lng: 23.87100,
  bearing: 0,
  pitch: 0
};

var showAttributes = [
  'name',
  'official_name',
  'alt_name',
  'street',
  'opening_hours',
  'email',
  'phone',
  'website',
  'heritage',
  'wikipedia',
  'height',
  'fee',
  'image',
  'style_lager'
];

var label = {
  official_name: 'Oficialus pavadinimas',
  alt_name: 'Kiti pavadinimai',
  street: 'Adresas',
  email: 'E-paštas',
  phone: 'Telefono nr.',
  fee: 'Mokestis'
};

var icons = {
  opening_hours: "fa fa-clock-o",
  email: 'fa fa-envelope-o',
  phone: 'fa fa-phone',
  website: 'fa fa-globe',
  heritage: 'fa fa-globe',
  wikipedia: 'fa fa-wikipedia-w',
  height: 'fa fa-arrows-v',
  style_lager: 'fa fa-beer'
};

var attributeType = {
  name: 'bold',
  website: 'link',
  image: 'image',
  street: 'address',
  heritage: 'kvr_link',
  wikipedia: 'wikipedia',
  height: 'height',
  fee: 'fee',
  style_lager: 'beer_styles'
};
var legendData = legendData || {};
var legendTechUrl = legendTechUrl || null;

if (!mapboxgl.supported()) {
  alert('Jūsų naršyklė nepalaiko Mapbox GL. Prašome atsinaujinti naršyklę.');
} else {
  if (hashData = getMapDataFromHashUrl()) {
    $.extend(mapData, hashData);
  }

  if (!hashData && (cookieData = readCookie(cookieName))) {
    $.extend(mapData, cookieData);
  }

  $("button[data-style='" + mapData.type + "']").addClass('active');
  $('#layers').removeClass('hidden');

  changeHashUrl();

  var map = new mapboxgl.Map({
    container: 'map',
    style: 'styles/' + mapData.type + '.json',
    zoom: mapData.zoom,
    minZoom: 7,
    maxZoom: 18,
    center: [mapData.lng, mapData.lat],
    hash: false,
    maxBounds: [20.880, 53.888, 26.862, 56.453],
    bearing: mapData.bearing,
    pitch: mapData.pitch
  })
    .addControl(new mapboxgl.NavigationControl(), 'top-left')
    .addControl(new mapboxgl.GeolocateControl({
      positionOptions: {
        enableHighAccuracy: true
      },
      trackUserLocation: true
    }), 'top-left')
    .on('sourcedata', function () {
      if (map.isStyleLoaded()) {
        poiInteractive();
      }
    })
    .on('moveend', function () {
      setMapData();
      changeHashUrl();
    })
    .on('load', function() {
      showLegend();
    });
}

$('#layers button').on('click', function (e) {
  if ($(this).hasClass('active')) {
    return false;
  }
  $('#layers button').removeClass('active');
  $(this).addClass('active');

  var selectLayer = $(e.target).data('style');
  map.setStyle('styles/' + selectLayer + '.json');

  mapData.type = selectLayer;
  changeHashUrl(mapData);
});

function changeHashUrl() {
  var formatHash = [];
  for (var key in mapData) {
    var value = mapData[key];
    if (key === 'type') {
      value = mapTypes[mapData.type]
    }
    formatHash.push(value);
  }
  window.location.hash = '#' + formatHash.join('/');
  storeCookie(cookieName, mapData);
}

function getMapDataFromHashUrl() {
  var hash = window.location.hash;
  if (hash.length > 0) {
    hash = hash.replace('#', '');

    // Add support old hash format: #l=55.23777,23.871,8,L
    var result = hash.match(new RegExp('l=([^]+)'));
    if (result) {
      var mapQueries = result[1].split(',');
      return {
        lat: parseFloat(mapQueries[0]),
        lng: parseFloat(mapQueries[1]),
        zoom: parseInt(mapQueries[2])
      };
    }

    var mapQueries = hash.split('/');

    // Add support old hash format: #8/55.23777/23.871
    if (mapQueries.length === 3) {
      return {
        zoom: parseFloat(mapQueries[0]),
        lat: parseFloat(mapQueries[1]),
        lng: parseFloat(mapQueries[2])
      }
    }

    if (mapQueries.length < 6) {
      return null;
    }

    var type = defaultType;
    for (var key in mapTypes) {
      if (mapTypes[key] === mapQueries[0]) {
        type = key;
        break;
      }
    }

    return {
      type: type,
      zoom: parseFloat(mapQueries[1]),
      lat: parseFloat(mapQueries[2]),
      lng: parseFloat(mapQueries[3]),
      bearing: parseInt(mapQueries[4]),
      pitch: parseInt(mapQueries[5])
    };
  }
  return null;
}

function setMapData() {
  mapData.zoom = Number(map.getZoom().toFixed(2));
  mapData.lat = Number(map.getCenter().lat.toFixed(5));
  mapData.lng = Number(map.getCenter().lng.toFixed(5));
  mapData.bearing = parseInt(map.getBearing());
  mapData.pitch = parseInt(map.getPitch());
}

function storeCookie(name, value) {
  var date = new Date();
  date.setDate(date.getDate() + 365);
  var expires = "expires=" + date.toUTCString();
  document.cookie = name + '=' + JSON.stringify(value) + ';domain=.' + window.location.host.toString() + ';path=/;' + expires;
}

function readCookie(name) {
  var result = document.cookie.match(new RegExp(name + '=([^;]+)'));
  if (result) {
    return JSON.parse(result[1]);
  }
  return null;
}

function poiInteractive() {
  map.off('mouseenter', interactiveLayerId, addMousePointerCursor);
  map.off('mouseleave', interactiveLayerId, removeMousePointerCursor);
  map.off('click', interactiveLayerId, poiOnClick);

  if (map.getLayer(interactiveLayerId)) {
    map.on('mouseenter', interactiveLayerId, addMousePointerCursor);
    map.on('mouseleave', interactiveLayerId, removeMousePointerCursor);
    map.on('click', interactiveLayerId, poiOnClick);
  }
}

function addMousePointerCursor() {
  map.getCanvas().style.cursor = 'pointer';
}

function removeMousePointerCursor() {
  map.getCanvas().style.cursor = '';
}

function poiOnClick(e) {
  var poi = e.features[0];
  var html = getHtml(poi).join('
');

  if (html.length) {
    new mapboxgl.Popup()
      .setLngLat(poi.geometry.coordinates)
      .setHTML(html)
      .addTo(map);
  }
}

function getHtml(poi) {
  return showAttributes
    .filter(function (prop_name) {
      return poi.properties[prop_name];
    })
    .map(function (prop_name) {
      var formatedValue = getFomatedValue(prop_name, poi.properties);

      if (icons[prop_name]) {
        return ' ' + formatedValue;
      }

      if (label[prop_name]) {
        return '' + label[prop_name] + ': ' + formatedValue;
      }

      return formatedValue;
    });
}

function getFomatedValue(attribute, properties) {
  var value = properties[attribute];
  switch (attributeType[attribute]) {
    case 'bold':
      return '' + value + '';
    case 'height':
      return value + ' m.';
    case 'fee':
      return value === 'yes' ? 'Yra' : 'Nėra';
    case 'link':
      return '' + value + '';
    case 'kvr_link':
      return 'Kultūros vertybių registras';
    case 'image':
      return '';
    case 'address':
      return [properties['city'], properties['street'], properties['housenumber']].join(' ');
    case 'wikipedia':
      var splitValue = value.split(':');
      return '' + splitValue[1] + '';
    case 'beer_styles':
      var styles = [];
      if (properties['style_lager'] == 'y') {
        styles.push('lageris');
      }
      if (properties['style_ale'] == 'y') {
        styles.push('elis');
      }
      if (properties['style_stout'] == 'y') {
        styles.push('stautas');
      }
      if (properties['style_ipa'] == 'y') {
        styles.push('IPA');
      }
      return 'Stiliai: ' + styles.join(', ');
  }

  return value;
}

function showLegend() {
  if (Object.keys(legendData).length === 0) {
    return;
  }

  var legendBlock = document.createElement('div');;
  legendBlock.id = 'legend';
  legendBlock.classList.add('map-overlay');

  var legendHeader = document.createElement('strong');
  legendHeader.classList.add('legend-header');
  legendHeader.innerHTML = 'Sutartiniai ženklai';
  legendHeader.addEventListener('click', function (e) {
    e.stopPropagation();
    legendBlock.classList.toggle('active');
  });
  legendBlock.addEventListener('click', function(e) {
    e.stopPropagation();
    legendBlock.classList.add('active');
  });
  document.body.addEventListener('click', function() {
    if (legendBlock.classList.contains('active')) {
      legendBlock.classList.remove('active');
    }
  });

  legendBlock.appendChild(legendHeader);

  var ul = document.createElement('ul');
  ul.classList.add('legend-items');

  for (var key in legendData) {
    if (!legendData.hasOwnProperty(key)) {
      continue;
    }

    var legend = legendData[key];

    if (!legend.type) {
      continue;
    }

    var legendSymbolIcon = document.createElement('span');
    legendSymbolIcon.classList.add('label-' + legend.type, key);

    var legendSymbol = document.createElement('span');
    legendSymbol.classList.add('label-item');
    legendSymbol.appendChild(legendSymbolIcon);

    var legendItem = document.createElement('li');
    legendItem.appendChild(legendSymbol);
    legendItem.insertAdjacentHTML('beforeend', legend.label);

    ul.appendChild(legendItem);
  }
  legendBlock.appendChild(ul);

  if (legendTechUrl) {
    var legendUrl = document.createElement('a');
    legendUrl.classList.add('legend-doc');
    legendUrl.setAttribute('href', legendTechUrl);
    legendUrl.setAttribute('target', '_blank');
    legendUrl.innerHTML = 'Techninė informaciją';
    legendBlock.appendChild(legendUrl);
  }

  document.body.appendChild(legendBlock);
}<|endoftext|>


<commit_before>import $events from 'wee-events';
import { _doc, _win } from 'core/variables';
import { $copy, $extend, $isObject } from 'core/types';
import { $exec } from 'core/core';
import { $each, $parseHTML, $setRef } from 'core/dom';
import { $serializeForm } from 'dom/index';
import { supportsPushState } from './push-state';
import $fetch from 'wee-fetch';
import $ from 'wee-dom';
import { warn } from './warn';

let defaults = {
	bind: {
		click: 'a',
		submit: 'form'
	},
	context: 'document',
	fetch: $fetch.create(),
	partials: 'title,main',
	request: {
		method: 'get',
		responseType: 'text',
		headers: {
			'X-PJAX': 'true'
		}
	},
	replace: null
};
let settings = $copy(defaults);
let response = null;
let paused = false;

/**
 * Determine if path is valid for history navigation
 *
 * @param {HTMLElement} el
 * @param {string} [currentPath]
 * @returns {boolean}
 * @private
 */
function _isValid(el, currentPath) {
	// Link has no destination URL
	if (! el.href) { return false; }

	// Link opens a new browser window
	if (el.target === '_blank') { return false; }

	// Link is not absolute URL
	if (! /https?:/.test(el.href)) { return false; }

	// Link is a download
	if (el.hasAttribute('download')) { return false; }

	// Link is supposed to be ignored
	if (el.hasAttribute('data-static')) { return false; }

	// Link is external URL
	if (el.host && el.host !== location.host) { return false; }

	// Link is current page, but with a hash added
	if (el.hash && el.pathname === currentPath) { return false; }

	if (! currentPath) { return true; }

	// TODO: Remove whitelisting logic
	let exts = settings.extensions;
	let segs = currentPath.split('.');
	let ext;

	if (segs.length > 1) {
		ext = segs.pop().split(/#|\?/)[0];
	}

	// No file extension in URL or extension is whitelisted
	return ! ext || (exts && exts.indexOf(ext) > -1);
}

/**
 * Return current path
 *
 * @private
 * @param {object} [loc]
 * @returns {string}
 */
function _path(loc) {
	loc = loc || location;
	return loc.pathname + loc.search + loc.hash;
}

/**
 * Reset references and variables for a given selector
 *
 * @private
 * @param sel
 */
function _reset(sel) {
	response = null;
	$setRef(sel);
	// TODO: Uncomment when $setVar is added
	// $setVar(sel);

	pjax.bind(sel);
}

const pjax = {
	// Empty callback - will be defined by router.pjax
	onTrigger() {},

	/**
	 * Bind element events and form submit events to callback
	 *
	 * @param {($|HTMLElement|string)} [context=document]
	 */
	bind(context) {
		const events = settings.bind;
		context = context || settings.context;

		if (supportsPushState) {
			const keys = Object.keys(events);
			let i = 0;

			// Iterate through events to be bound
			for (; i < keys.length; i++) {
				const event = keys[i];
				const sel = events[event];

				$each(sel, el => {
					const evts = event.split(' ').map(val => {
							return val + '.pjax';
						}).join(' ');

					// Retrieve data-url off of element
					// Used if element is not  tag
					const loc = el.getAttribute('data-url');
					let destination = el;

					// Create  tag for validation of URL
					if (loc) {
						let attrs = el.attributes;
						let j = 0;
						let attr;

						destination = _doc.createElement('a');

						// Clone attributes from bound element to new a tag
						for (; j < attrs.length; j++) {
							attr = attrs[j];
							destination.setAttribute(attr.name, attr.value);
						}

						// Set URL
						destination.href = loc;
					}

					// Ensure the path exists and is local
					if (! evts || ! _isValid(destination)) {
						warn('PJAX: no events provided or invalid destination URL ' + destination.href);
						return;
					}

					// TODO: Make this reset optional so we can use 'bind' dynamically
					// Remove existing pjax events
					$events.off(el, '.pjax');

					// Bind designated events
					$events.on(el, evts, (e, el) => {
						if (paused) {
							warn('pjax has been paused - will not trigger navigation');
							return;
						}

						// Don't navigate with control keys
						if (e.metaKey || e.ctrlKey || e.shiftKey) { return; }

						// Don't navigate when preventDefault already called
						if (e.defaultPrevented) { return; }

						// Don't navigate on right click
						if (e.button !== undefined && e.button !== 0) { return; }

						let path = _path(destination);

						e.preventDefault();

						this.onTrigger(path);
					});
				}, {
					context: context
				});
			}
		}
	},

	go(to, from, next) {
		if (paused) {
			warn('pjax has been paused - will not request partials');
			return next();
		}

		let request = settings.request;

		// Navigate to external URL or if history isn't supported
		let a = _doc.createElement('a');
		a.href = to.url;

		if (! supportsPushState || ! _isValid(a, from.fullPath)) {
			// Will trigger full page reload
			_win.location = to.fullPath;
			return false;
		}

		request.url = to.fullPath;

		settings.fetch(request)
			.then(res => {
				response = res;
				next();
			})
			.catch(error => {
				next(error);
			});
	},

	/**
	 * Apply configuration
	 *
	 * @param {Object} options
	 */
	init(options) {
		if (supportsPushState) {
			settings = $extend(settings, options);

			// https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
			if ('scrollRestoration' in _win.history) {
				_win.history.scrollRestoration = 'manual';
			}

			// Bind all designated elements to trigger navigation
			this.bind();

			return true;
		}

		return false;
	},

	/**
	 * Inform if pjax is currently paused
	 *
	 * @returns {boolean}
	 */
	isPaused() {
		return paused;
	},

	/**
	 * Pause previously bound pjax from triggering
	 */
	pause() {
		paused = true;
	},

	/**
	 * Replace target partials on DOM
	 */
	replace() {
		if (paused) {
			warn('pjax has been paused - will not replace partials');
			return;
		}

		let html = response.data;

		if (settings.replace) {
			$exec(settings.replace, {
				args: [html, settings]
			});
		}

		html = $parseHTML('' + html + '').firstChild;

		// Make partial replacements from response
		// TODO: Change string format to array
		$each(settings.partials.split(','), sel => {
			$each(sel, function(el) {
				const target = $(sel)[0];

				if (target) {
					const parent = target.parentNode;

					settings.action === 'append' ?
						parent.appendChild(el) :
						parent.replaceChild(el, target);

					_reset(parent);
				}
			}, {
				context: html
			});
		});
	},

	/**
	 * Reset module back to default settings
	 */
	reset() {
		settings = $copy(defaults);
	},

	/**
	 * Resume pjax to normal operating status
	 */
	resume() {
		paused = false;
	}
};

export default pjax;<commit_msg>Prevent binding internal page links in pjax<commit_after>import $events from 'wee-events';
import { _doc, _win } from 'core/variables';
import { $copy, $extend, $isObject } from 'core/types';
import { $exec } from 'core/core';
import { $each, $parseHTML, $setRef } from 'core/dom';
import { $serializeForm } from 'dom/index';
import { supportsPushState } from './push-state';
import $fetch from 'wee-fetch';
import $ from 'wee-dom';
import { warn } from './warn';
import { parseLocation } from './location';

let defaults = {
	bind: {
		click: 'a',
		submit: 'form'
	},
	context: 'document',
	fetch: $fetch.create(),
	partials: 'title,main',
	request: {
		method: 'get',
		responseType: 'text',
		headers: {
			'X-PJAX': 'true'
		}
	},
	replace: null
};
let settings = $copy(defaults);
let response = null;
let paused = false;

/**
 * Determine if path is valid for history navigation
 *
 * @param {HTMLElement} el
 * @param {string} [currentPath]
 * @returns {boolean}
 * @private
 */
function _isValid(el, currentPath) {
	// Link has no destination URL
	if (! el.href) { return false; }

	// Link opens a new browser window
	if (el.target === '_blank') { return false; }

	// Link is not absolute URL
	if (! /https?:/.test(el.href)) { return false; }

	// Link is a download
	if (el.hasAttribute('download')) { return false; }

	// Link is supposed to be ignored
	if (el.hasAttribute('data-static')) { return false; }

	// Link is external URL
	if (el.host && el.host !== location.host) { return false; }

	// Link is current page, but with a hash added
	if (el.hash && el.pathname === currentPath) { return false; }

	return true;
}

/**
 * Return current path
 *
 * @private
 * @param {object} [loc]
 * @returns {string}
 */
function _path(loc) {
	loc = loc || location;
	return loc.pathname + loc.search + loc.hash;
}

/**
 * Reset references and variables for a given selector
 *
 * @private
 * @param sel
 */
function _reset(sel) {
	response = null;
	$setRef(sel);
	// TODO: Uncomment when $setVar is added
	// $setVar(sel);

	pjax.bind(sel);
}

const pjax = {
	// Empty callback - will be defined by router.pjax
	onTrigger() {},

	/**
	 * Bind element events and form submit events to callback
	 *
	 * @param {($|HTMLElement|string)} [context=document]
	 */
	bind(context) {
		const current = parseLocation();
		const events = settings.bind;
		context = context || settings.context;

		if (supportsPushState) {
			const keys = Object.keys(events);
			let i = 0;

			// Iterate through events to be bound
			for (; i < keys.length; i++) {
				const event = keys[i];
				const sel = events[event];

				$each(sel, el => {
					const evts = event.split(' ').map(val => {
							return val + '.pjax';
						}).join(' ');

					// Retrieve data-url off of element
					// Used if element is not  tag
					const loc = el.getAttribute('data-url');
					let destination = el;

					// Create  tag for validation of URL
					if (loc) {
						let attrs = el.attributes;
						let j = 0;
						let attr;

						destination = _doc.createElement('a');

						// Clone attributes from bound element to new a tag
						for (; j < attrs.length; j++) {
							attr = attrs[j];
							destination.setAttribute(attr.name, attr.value);
						}

						// Set URL
						destination.href = loc;
					}

					// Ensure the path exists and is local
					if (! evts || ! _isValid(destination, current.path)) {
						// TODO: Make this print as verbose only
						// warn('PJAX: no events provided or invalid destination URL ' + destination.href);
						return;
					}

					// TODO: Make this reset optional so we can use 'bind' dynamically
					// Remove existing pjax events
					$events.off(el, '.pjax');

					// Bind designated events
					$events.on(el, evts, e => {
						if (paused) {
							warn('pjax has been paused - will not trigger navigation');
							return;
						}

						// Don't navigate with control keys
						if (e.metaKey || e.ctrlKey || e.shiftKey) { return; }

						// Don't navigate when preventDefault already called
						if (e.defaultPrevented) { return; }

						// Don't navigate on right click
						if (e.button !== undefined && e.button !== 0) { return; }

						let path = _path(destination);

						e.preventDefault();

						this.onTrigger(path);
					});
				}, {
					context: context
				});
			}
		}
	},

	go(to, from, next) {
		if (paused) {
			warn('pjax has been paused - will not request partials');
			return next();
		}

		let request = settings.request;

		// Navigate to external URL or if history isn't supported
		let a = _doc.createElement('a');
		a.href = to.url;

		if (! supportsPushState || ! _isValid(a, from.fullPath)) {
			// Will trigger full page reload
			_win.location = to.fullPath;
			return false;
		}

		request.url = to.fullPath;

		settings.fetch(request)
			.then(res => {
				response = res;
				next();
			})
			.catch(error => {
				next(error);
			});
	},

	/**
	 * Apply configuration
	 *
	 * @param {Object} options
	 */
	init(options) {
		if (supportsPushState) {
			settings = $extend(settings, options);

			// https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
			if ('scrollRestoration' in _win.history) {
				_win.history.scrollRestoration = 'manual';
			}

			// Bind all designated elements to trigger navigation
			this.bind();

			return true;
		}

		return false;
	},

	/**
	 * Inform if pjax is currently paused
	 *
	 * @returns {boolean}
	 */
	isPaused() {
		return paused;
	},

	/**
	 * Pause previously bound pjax from triggering
	 */
	pause() {
		paused = true;
	},

	/**
	 * Replace target partials on DOM
	 */
	replace() {
		if (paused) {
			warn('pjax has been paused - will not replace partials');
			return;
		}

		let html = response.data;

		if (settings.replace) {
			$exec(settings.replace, {
				args: [html, settings]
			});
		}

		html = $parseHTML('' + html + '').firstChild;

		// Make partial replacements from response
		// TODO: Change string format to array
		$each(settings.partials.split(','), sel => {
			$each(sel, function(el) {
				const target = $(sel)[0];

				if (target) {
					const parent = target.parentNode;

					settings.action === 'append' ?
						parent.appendChild(el) :
						parent.replaceChild(el, target);

					_reset(parent);
				}
			}, {
				context: html
			});
		});
	},

	/**
	 * Reset module back to default settings
	 */
	reset() {
		settings = $copy(defaults);
	},

	/**
	 * Resume pjax to normal operating status
	 */
	resume() {
		paused = false;
	}
};

export default pjax;<|endoftext|>


<commit_before>/*  This work is licensed under Creative Commons GNU LGPL License.

  License: http://creativecommons.org/licenses/LGPL/2.1/
   Version: 0.9
  Author:  Stefan Goessner/2006
  Web:     http://goessner.net/
*/
function json2xml(o, tab) {
   var toXml = function(v, name, ind) {
      var xml = "";
      if (v instanceof Array) {
         for (var i=0, n=v.length; i<n; i++)
            xml += ind + toXml(v[i], name, ind+"\t") + "\n";
      }
      else if (typeof(v) == "object") {
         console.log('object');
         var hasChild = false;
         xml += ind + "<" + name;
         for (var m in v) {
            if (m.charAt(0) == "@")
               xml += " " + m.substr(1) + "=\"" + v[m].toString() + "\"";
            else
               hasChild = true;
         }
         xml += hasChild ? ">" : "/>";
         if (hasChild) {
            for (var m in v) {
               if (m == "#text")
                  xml += v[m];
               else if (m == "#cdata")
                  xml += "<![CDATA[" + v[m] + "]]>";
               else if (m.charAt(0) != "@")
                  xml += toXml(v[m], m, ind+"\t");
            }
            xml += (xml.charAt(xml.length-1)=="\n"?ind:"") + "</" + name + ">";
         }
      }
      else {
         xml += ind + "<" + name + ">" + v.toString() +  "</" + name + ">";
      }
      return xml;
   }, xml="";
   for (var m in o)
      xml += toXml(o[m], m, "");
   return tab ? xml.replace(/\t/g, tab) : xml.replace(/\t|\n/g, "");
}

exports.XML_ = new (function XML() {
  this.stringify = function(o) {
    return json2xml(o);
  };
})();

exports.XML = new (function () {
  var INDENT_LEVEL = 4;

  var tagFromType = function (item, prev) {
        var ret
          , type
          , types;
        if (item instanceof Array) {
          ret = 'array';
        }
        else {
          types = ['string', 'number', 'boolean', 'object'];
          for (var i = 0, ii = types.length; i < ii; i++) {
            type = types[i];
            if (typeof item == type) {
              ret = type;
            }
          }
        }
        if (prev && ret != prev) {
          return 'record'
        }
        else {
          return ret;
        }
      }

    , obj2xml = function (o, name, level) {
        var pack
          , item
          , n
          , currentIndent = (new Array(level * INDENT_LEVEL)).join(' ')
          , nextIndent = (new Array((level + 1) * INDENT_LEVEL)).join(' ')
          , xml = '';
        switch (typeof o) {
          case 'string':
          case 'number':
          case 'boolean':
            xml = o;
            break;
          case 'object':
            if (o instanceof Array) {
              pack = [];
              for (var i = 0, ii = o.length; i < ii; i++) {
                item = o[i];
                if (!name) {
                  n = tagFromType(item, n);
                }
                pack.push(obj2xml(item, '', level + 1));
              }
              if (name) {
                n = name;
              }
              if (level == 0) {
                xml += currentIndent + '<' + n + 's type="array">\n'
              }
              xml += nextIndent + '<' + n + '>' +
                  pack.join('</' + n + '>\n' + nextIndent +
                      '<' + n + '>') + '</' + n + '>\n';
              if (level == 0) {
                xml += currentIndent + '</' + n + 's>';
              }
            }
            else {
              n = name || 'object';
              if (level == 0) {
                xml = currentIndent + '<' + n + '>\n';
              }
              for (var p in o) {
                item = o[p];

                xml += nextIndent;

                if (p == '#cdata') {
                  xml += '<![CDATA[' + item + ']]>\n';
                }
                else {
                  xml += '<' + p;
                  if (item instanceof Array) {
                    xml += ' type="array">\n'
                  }
                  else if (typeof item == 'object') {
                    xml += '>\n';
                  }
                  else {
                    xml += '>'
                  }
                  xml += obj2xml(item, p, level + 1);
                  if (item instanceof Array || typeof item == 'object') {
                    xml += nextIndent;
                  }
                  xml += '</' + p + '>\n';
                }
              }
              if (level == 0) {
                xml += currentIndent + '</' + n + '>\n';
              }
            }
            break;
          default:
            // No default
        }
        return xml;
      };

  this.stringify = function (o) {
    var xml = '';
    xml += '<?xml version="1.0" encoding="UTF-8"?>\n';
    xml += obj2xml(o, '', 0);
    return xml;
  };

})();
<commit_msg>Replaced XML serialization lib.<commit_after>
exports.XML = new (function () {
  var whitespace = true
    , indentLevel = 4;

  var tagFromType = function (item, prev) {
        var ret
          , type
          , types;
        if (item instanceof Array) {
          ret = 'array';
        }
        else {
          types = ['string', 'number', 'boolean', 'object'];
          for (var i = 0, ii = types.length; i < ii; i++) {
            type = types[i];
            if (typeof item == type) {
              ret = type;
            }
          }
        }
        if (prev && ret != prev) {
          return 'record'
        }
        else {
          return ret;
        }
      }

    , obj2xml = function (o, name, level) {
        var pack
          , item
          , n
          , currentIndent = (new Array(level * indentLevel)).join(' ')
          , nextIndent = (new Array((level + 1) * indentLevel)).join(' ')
          , xml = '';
        switch (typeof o) {
          case 'string':
          case 'number':
          case 'boolean':
            xml = o.toString();
            break;
          case 'object':
            // Arrays
            if (o instanceof Array) {

              // Pack the processed version of each item into an array that
              // can be turned into a tag-list with a `join` method below
              // As the list gets iterated, if all items are the same type,
              // that's the tag-name for the individual tags. If the items are
              // a mixed, the tag-name is 'record'
              pack = [];
              for (var i = 0, ii = o.length; i < ii; i++) {
                item = o[i];
                if (!name) {
                  // Pass any previous tag-name, so it's possible to know if
                  // all items are the same type, or it's mixed types
                  n = tagFromType(item, n);
                }
                pack.push(obj2xml(item, '', level + 1));
              }

              // If this thing is attached to a named property on an object,
              // use the name for the containing tag-name
              if (name) {
                n = name;
              }

              // If this is a top-level item, wrap in a top-level containing tag
              if (level == 0) {
                xml += currentIndent + '<' + n + 's type="array">\n'
              }
              xml += nextIndent + '<' + n + '>' +
                  pack.join('</' + n + '>\n' + nextIndent +
                      '<' + n + '>') + '</' + n + '>\n';

              // If this is a top-level item, close the top-level containing tag
              if (level == 0) {
                xml += currentIndent + '</' + n + 's>';
              }
            }
            // Generic objects
            else {
              n = name || 'object';

              // If this is a top-level item, wrap in a top-level containing tag
              if (level == 0) {
                xml = currentIndent + '<' + n + '>\n';
              }
              for (var p in o) {
                item = o[p];

                xml += nextIndent;

                if (p == '#cdata') {
                  xml += '<![CDATA[' + item + ']]>\n';
                }
                else {
                  xml += '<' + p;
                  // Complex values, going to have items with multiple tags
                  // inside
                  if (typeof item == 'object') {
                    if (item instanceof Array) {
                      xml += ' type="array">\n'
                    }
                    else {
                      xml += '>\n';
                    }
                  }
                  // Scalars, just a value and closing tag
                  else {
                    xml += '>'
                  }
                  xml += obj2xml(item, p, level + 1);

                  // Objects and Arrays, need indentation before closing tag
                  if (typeof item == 'object') {
                    xml += nextIndent;
                  }
                  xml += '</' + p + '>\n';
                }
              }
              // If this is a top-level item, close the top-level containing tag
              if (level == 0) {
                xml += currentIndent + '</' + n + '>\n';
              }
            }
            break;
          default:
            // No default
        }
        return xml;
      };

  this.setNoWhitespace = function () {
    indentLevel = 0;
    whitespace = false;
  };

  this.setIndentLevel = function (level) {
    indentLevel = level;
  };

  this.stringify = function (o) {
    var xml = '';
    xml += '<?xml version="1.0" encoding="UTF-8"?>\n';
    xml += obj2xml(o, '', 0);
    if (!whitespace) {
      xml = xml.replace(/>\n/g, '>');
    }
    return xml;
  };

})();
<|endoftext|>


<commit_before>const fs = require('fs');
const requestp = require('request-promise-native');
const readline = require('readline-sync');
const { spawn } = require('child_process');
const { google } = require('googleapis');

if (require.main === module) {
    const argv = process.argv.slice(2);
    const releaseTag = argv.shift();

    let pkgPath = 'out/beta/machete-beta.zip';
    let appIds = ["ekcgmjhleflmfemjpeomblomcbhfnfcj"];
    if (releaseTag == 'release') {
        pkgPath = 'out/release/machete-release.zip';
        appIds = ["linbfabhpielmegmeckbhfadhnnjoack"];
    }

    (async function() {
        try {
            console.log(`Publishing ${pkgPath} to apps ${appIds}`);

            const client = await authClient();

            for (const appId of appIds) {
                console.log('Requesting access token...');
                const token = await accessToken(client);

                console.log(`Uploading to ${appId}...`);
                const uploadResult = await uploadPackage(appId, token, pkgPath);
                console.log('Upload result:', uploadResult);

                console.log(`Publishing ${appId}...`);
                const publishResult = await publishPackage(appId, token);
                console.log('Publish result:', publishResult);
            }

            console.log('Pushing and tagging current changes in git');
            await gitTag(releaseTag);
            await gitPush(releaseTag);

            process.exit(0);
        }
        catch (ex) {
            console.error(ex);
            process.exit(1);
        }
    }());
}

function asyncSpawn(cmd, args) {
    return new Promise((resolve, reject) => {
        console.log(cmd, args.join(' '));
        const child = spawn(cmd, args, { stdio: 'inherit' });
        child.on('close', code => {
            if (code == 0)
                return resolve();
            return reject('Error code: ' + code);
        });
    });
}

function gitTag(releaseTag) {
    const manifest = require('./manifest.json');
    return asyncSpawn('git', ['tag', '-f', `${releaseTag}-${manifest.version}`]);
}

async function gitPush(releaseTag) {
    await asyncSpawn('git', ['push', 'origin']);
    await asyncSpawn('git', ['push', 'origin', '--tags']);

    if (releaseTag == 'release') {
        await asyncSpawn('git', ['push', 'github']);
        await asyncSpawn('git', ['push', 'github', '--tags']);
    }
}

function readAsync(fname) {
    return new Promise((resolve, reject) => fs.readFile(fname, 'utf8', (err, data) => (err && reject(err)) || resolve(data)));
}

async function authClient() {
    const data = await readAsync('../uploader-keys.json');
    const codes = JSON.parse(data);
    const oauthClient = new google.auth.OAuth2(codes.client_id, codes.client_secret, 'urn:ietf:wg:oauth:2.0:oob');
    oauthClient.on('tokens', async tokens => {
        console.log('Storing new tokens');
        await new Promise((resolve, reject) => fs.writeFile('../uploader-tokens', JSON.stringify(tokens), err => (err && reject(err)) || resolve()));
    });
    return oauthClient;
}

async function accessToken(oauthClient) {
    try {
        const tokens = JSON.parse(await readAsync('../uploader-tokens'));
        await oauthClient.setCredentials(tokens);
        console.log('Using cached tokens');
        return tokens.access_token;
    }
    catch (ex) {
        console.warn(`Couldn't find cached tokens`);
    }

    const url = oauthClient.generateAuthUrl({ access_type: 'offline', scope: ['https://www.googleapis.com/auth/chromewebstore'] });

    console.log('Please visit the following URL to authorize this upload:');
    console.log(`  ${url}`);
    const accessCode = readline.question('Enter the authorization code here: ');
    const { tokens } = await oauthClient.getToken(accessCode);
    return tokens.access_token;
}

async function uploadPackage(appId, token, pkgPath) {
    const pkgBuffer = await new Promise((resolve, reject) => fs.readFile(pkgPath, (err, data) => (err && reject(err)) || resolve(data)));
    const response = await requestp({
        uri: 'https://www.googleapis.com/upload/chromewebstore/v1.1/items/' + appId,
        method: 'PUT',
        headers: { 'Authorization': 'Bearer ' + token, 'x-goog-api-version': 2 },
        body: pkgBuffer
    });

    const status = JSON.parse(response);
    if (status.uploadState != 'SUCCESS')
        throw new Error(JSON.stringify(status));

    return status;
}

async function publishPackage(appId, token) {
    const response = await requestp({
        uri: `https://www.googleapis.com/chromewebstore/v1.1/items/${appId}/publish`,
        method: 'POST',
        headers: { 'Authorization': 'Bearer ' + token, 'x-goog-api-version': 2 },
    });

    const status = JSON.parse(response);
    if (status.status[0] != 'OK')
        throw new Error(status.statusDetail.join('. '));
    return status;
}
<commit_msg>modified publish.js to actually not require explicit auth all the time<commit_after>const fs = require('fs');
const requestp = require('request-promise-native');
const readline = require('readline-sync');
const { spawn } = require('child_process');
const { google } = require('googleapis');

if (require.main === module) {
    const argv = process.argv.slice(2);
    const releaseTag = argv.shift();

    let pkgPath = 'out/beta/machete-beta.zip';
    let appIds = ["ekcgmjhleflmfemjpeomblomcbhfnfcj"];
    if (releaseTag == 'release') {
        pkgPath = 'out/release/machete-release.zip';
        appIds = ["linbfabhpielmegmeckbhfadhnnjoack"];
    }

    (async function() {
        try {
            console.log(`Publishing ${pkgPath} to apps ${appIds}`);

            const client = await authClient();

            for (const appId of appIds) {
                console.log('Requesting access token...');
                const header = await authorizationHeader(client);

                console.log(`Uploading to ${appId}...`);
                const uploadResult = await uploadPackage(appId, header, pkgPath);
                console.log('Upload result:', uploadResult);

                console.log(`Publishing ${appId}...`);
                const publishResult = await publishPackage(appId, token);
                console.log('Publish result:', publishResult);
            }

            console.log('Pushing and tagging current changes in git');
            await gitTag(releaseTag);
            await gitPush(releaseTag);

            process.exit(0);
        }
        catch (ex) {
            console.error(ex);
            process.exit(1);
        }
    }());
}

function asyncSpawn(cmd, args) {
    return new Promise((resolve, reject) => {
        console.log(cmd, args.join(' '));
        const child = spawn(cmd, args, { stdio: 'inherit' });
        child.on('close', code => {
            if (code == 0)
                return resolve();
            return reject('Error code: ' + code);
        });
    });
}

function gitTag(releaseTag) {
    const manifest = require('./manifest.json');
    return asyncSpawn('git', ['tag', '-f', `${releaseTag}-${manifest.version}`]);
}

async function gitPush(releaseTag) {
    await asyncSpawn('git', ['push', 'origin']);
    await asyncSpawn('git', ['push', 'origin', '--tags']);

    if (releaseTag == 'release') {
        await asyncSpawn('git', ['push', 'github']);
        await asyncSpawn('git', ['push', 'github', '--tags']);
    }
}

function readAsync(fname) {
    return new Promise((resolve, reject) => fs.readFile(fname, 'utf8', (err, data) => (err && reject(err)) || resolve(data)));
}

async function authClient() {
    const data = await readAsync('../uploader-keys.json');
    const codes = JSON.parse(data);
    const oauthClient = new google.auth.OAuth2(codes.client_id, codes.client_secret, 'urn:ietf:wg:oauth:2.0:oob');
    oauthClient.on('tokens', async tokens => {
        console.log('Storing new tokens in ./new-tokens, please save these in ../uploader-tokens');
        await new Promise((resolve, reject) => fs.writeFile('new-tokens', JSON.stringify(tokens), err => (err && reject(err)) || resolve()));
    });
    return oauthClient;
}

async function authorizationHeader(oauthClient) {
    try {
        const cached = JSON.parse(await readAsync('../uploader-tokens'));
        await oauthClient.setCredentials(cached);
        return oauthClient.getRequestHeaders();
    }
    catch (ex) {
        console.log(ex);
        console.warn(`Couldn't generate headers from cached tokens`);
    }

    const url = oauthClient.generateAuthUrl({ access_type: 'offline', scope: ['https://www.googleapis.com/auth/chromewebstore'] });

    console.log('Please visit the following URL to authorize this upload:');
    console.log(`  ${url}`);
    const accessCode = readline.question('Enter the authorization code here: ');
    const { tokens } = await oauthClient.getToken(accessCode);
    return oauthClient.getRequestHeaders();
}

async function uploadPackage(appId, headers, pkgPath) {
    const pkgBuffer = await new Promise((resolve, reject) => fs.readFile(pkgPath, (err, data) => (err && reject(err)) || resolve(data)));
    const response = await requestp({
        uri: 'https://www.googleapis.com/upload/chromewebstore/v1.1/items/' + appId,
        method: 'PUT',
        headers,
        body: pkgBuffer
    });

    const status = JSON.parse(response);
    if (status.uploadState != 'SUCCESS')
        throw new Error(JSON.stringify(status));

    return status;
}

async function publishPackage(appId, token) {
    const response = await requestp({
        uri: `https://www.googleapis.com/chromewebstore/v1.1/items/${appId}/publish`,
        method: 'POST',
        headers: { 'Authorization': 'Bearer ' + token, 'x-goog-api-version': 2 },
    });

    const status = JSON.parse(response);
    if (status.status[0] != 'OK')
        throw new Error(status.statusDetail.join('. '));
    return status;
}
<|endoftext|>


<commit_before>define(function (require) {
  "use strict";

  var React = require('react'),
      Router = require('react-router'),
      stores = require('stores'),
      actions = require('actions'),
      ImageRequestActions = require('actions/ImageRequestActions');

  return React.createClass({

    mixins: [Router.State],

    getInitialState: function(){
      return{
        response: ""
      }
    },

    handleResponseChange: function (event) {
      var response = event.target.value;
      if (response) this.setState({response: response});
    },

    approve: function(){
      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId);
      ImageRequestActions.update({
        request: request,
        response: this.state.response,
        action: "approve"
      });
    },

    deny: function(){
      ImageRequestActions.update({
        request: this.getParams().imageRequestId,
        response: this.state.response,
        action: "deny"
      });
    },

    resubmit: function(){
      ImageRequestActions.update({
        request: this.getParams().imageRequestId,
        response: this.state.response,
        action: "resubmit"
      });
    },

    render: function () {
      var requestId = (this.getParams().imageRequestId);

      var request = stores.ImageRequestStore.get(requestId);

      if(!request){
        return

      }

      // This is done to ensure boolean values are displayed as strings

      var allowImaging = "false";
      var forked = "false";

      if(request.get('new_version_forked')){
        forked = "true";
      }

      if(request.get('new_version_allow_imaging')){
        allowImaging = "true";
      }

      var instance = request.get('instance');

      return(

Image Request #{request.get('id')}

Installed software: {request.get('installed_software')}

Instance:

ID: {instance.id}

Name: {instance.name}

iPlant sys files: {request.get('iplant_sys_files')}

New application description: {request.get('new_application_description')}

New application name: {request.get('new_application_name')}

New machine owner: {request.get('new_machine_owner').username}

New provider: {request.get('new_machine_provider').name}

Allow imaging: {allowImaging}

Forked: {forked}

New version licenses: {request.get('new_version_licenses')}

New version memory min: {request.get('new_version_memory_min')}

New version storage min: {request.get('new_version_storage_min')}

New version name: {request.get('new_version_name')}

New version scripts: {request.get('new_version_scripts')}

New version tags: {request.get('new_version_tags')}

Status: {request.get('status')}

          <textarea type="text" form="admin" value={this.state.value} cols="60" rows="8"
                      onChange={this.handleResponseChange}/>
          <button onClick={this.approve} type="button" className="btn btn-default btn-sm">Approve</button>
          <button onClick={this.deny} type="button" className="btn btn-default btn-sm">Deny</button>
          <button onClick={this.resubmit} type="button" className="btn btn-default btn-sm">Re-Submit</button>

      );
    }
  });
});

<commit_msg>changed 'action' key to 'newStatus'<commit_after>define(function (require) {
  "use strict";

  var React = require('react'),
      Router = require('react-router'),
      stores = require('stores'),
      actions = require('actions'),
      ImageRequestActions = require('actions/ImageRequestActions');

  return React.createClass({

    mixins: [Router.State],

    getInitialState: function(){
      return{
        response: ""
      }
    },

    handleResponseChange: function (event) {
      var response = event.target.value;
      if (response) this.setState({response: response});
    },

    approve: function(){

      // request is guaranteed to exist in our store, since we needed it to render this component
      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId);
      ImageRequestActions.update({
        request: request,
        response: this.state.response,
        newStatus: "approved"
      });

    },

    deny: function(){

      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId);
      ImageRequestActions.update({
        request: this.getParams().imageRequestId,
        response: this.state.response,
        newStatus: "deny"
      });

    },

    resubmit: function(){

      var request = stores.ImageRequestStore.get(this.getParams().imageRequestId);
      ImageRequestActions.update({
        request: this.getParams().imageRequestId,
        response: this.state.response,
        newStatus: "resubmit"
      });

    },

    render: function () {
      var requestId = (this.getParams().imageRequestId);

      var request = stores.ImageRequestStore.get(requestId);

      if(!request){
        return

      }

      // This is done to ensure boolean values are displayed as strings

      var allowImaging = "false";
      var forked = "false";

      if(request.get('new_version_forked')){
        forked = "true";
      }

      if(request.get('new_version_allow_imaging')){
        allowImaging = "true";
      }

      var instance = request.get('instance');

      return(

Image Request #{request.get('id')}

Installed software: {request.get('installed_software')}

Instance:

ID: {instance.id}

Name: {instance.name}

iPlant sys files: {request.get('iplant_sys_files')}

New application description: {request.get('new_application_description')}

New application name: {request.get('new_application_name')}

New machine owner: {request.get('new_machine_owner').username}

New provider: {request.get('new_machine_provider').name}

Allow imaging: {allowImaging}

Forked: {forked}

New version licenses: {request.get('new_version_licenses')}

New version memory min: {request.get('new_version_memory_min')}

New version storage min: {request.get('new_version_storage_min')}

New version name: {request.get('new_version_name')}

New version scripts: {request.get('new_version_scripts')}

New version tags: {request.get('new_version_tags')}

Status: {request.get('status')}

          <textarea type="text" form="admin" value={this.state.value} cols="60" rows="8"
                      onChange={this.handleResponseChange}/>
          <button onClick={this.approve} type="button" className="btn btn-default btn-sm">Approve</button>
          <button onClick={this.deny} type="button" className="btn btn-default btn-sm">Deny</button>
          <button onClick={this.resubmit} type="button" className="btn btn-default btn-sm">Re-Submit</button>

      );
    }
  });
});

<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2014 by Animatron.
 * All rights are reserved.
 */

/* Variables we get from template:
   playerDomain — a URL to player domain host, e.g. player.animatron.com
   amazonDomain — a URL to snapshot storage host, e.g. http://snapshots.animatron.com/<snapshot-id>
   width — width of the animation
   height — height of the animation
   playerVersion — player version, default 'latest'
   filename — filename of snapshot, used as amazonDomain + filename
   autostart — (boolean) autostart of movie on player load
   loop — (boolean) loop animation instead of stoping at the end
   animation — JSON object of animatron movie (currently not used)
   hasInteractivity — (boolean) if there's some interactivity in the project, it should be autostarted (overrides `autostart`) and handle events
*/
(function($global, $window, $document) {
    var inIFrame = ($window.self !== $window.top);

    var autostart = $global['autostart'] || false,
        loop = $global['loop'] || false,
        hasInteractivity = $global['hasInteractivity'] || false;

    var utils = {
        isInt: function(n) {
            n = Number(n);
            return !isNaN(n) && Math.floor(n) === n;
        },
        serializeToQueryString: function(obj) {
            var str = [];
            for(var p in obj) {
                if (obj.hasOwnProperty(p)) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
            }
            return str.join("&");
        },
        parseQueryString: function() {
            var queryString = location.search.substring(1);
            if (!queryString) {
                return {};
            }
            var queries = queryString.split("&"),
                params = {}, temp, i, l;
            for ( i = 0, l = queries.length; i < l; i++ ) {
                temp = queries[i].split('=');
                params[temp[0]] = temp[1];
            }
            return params;
        },
        getRequiredRect: function () {
            if (inIFrame) {
                return utils.getIframeSize();
            } else {
                return {w: width, h: height};
            }
        },
        getIframeSize: function () {
            var size = {w:0, h:0};
            if (typeof $window.innerWidth == 'number') {
                size.w = $window.innerWidth;
                size.h = $window.innerHeight;
            } else {
                size.w = $document.documentElement.clientWidth;
                size.h = $document.documentElement.clientHeight;
            }
            return size;
        },
        forcedJS: function (path, then) {
            var scriptElm = $document.createElement('script');
            scriptElm.type = 'text/javascript';
            scriptElm.async = 'async';
            scriptElm.src = path;
            scriptElm.onload = scriptElm.onreadystatechange = (function () {
                var success = false;
                return function () {
                    if (this.readyState === 'loading') {
                        return;
                    }
                    if (!success && (!this.readyState ||
                        (this.readyState === 'complete' || this.readyState === 'loaded')
                    )) {
                        success = true;
                        then();
                    } else if (!success && $window.console) {
                        console.error('Request failed: ' + this.readyState);
                    }
                };
            })();
            var headElm = $document.head || $document.getElementsByTagName('head')[0];
            headElm.appendChild(scriptElm);
        }
    };

    var TARGET_ID = 'target',
    WRAPPER_CLASS = 'anm-wrapper',
    PLAYER_VERSION_ID = playerVersion || 'latest';

    // options to apply just _after_ the snapshot was completely loaded are stored in the url (width and height in `params`)
    // initialization options are stored in `initOptions`
    var params = utils.parseQueryString(),
        initOptions = {};

    var rect = utils.getRequiredRect(),
        targetWidth, targetHeight;

    //floating-point w&h parameters mean percentage sizing
    if (params.w && !utils.isInt(params.w)) {
        targetWidth = params.w = Math.round(params.w * rect.w);
    } else {
        targetWidth = params.w = params.w || rect.w;
    }
    if (params.h && !utils.isInt(params.h)) {
        targetHeight = params.h = Math.round(params.h * rect.h);
    } else {
        targetHeight = params.h = params.h || rect.h;
    }
    if (autostart || hasInteractivity) {
        initOptions.autoPlay = true;
    }
    if (loop) {
        initOptions.repeat = true;
    }
    if (hasInteractivity) {
        initOptions.controlsEnabled = false;
        initOptions.handleEvents = true;
    }

    if (params.v) {
        PLAYER_VERSION_ID = params.v;
    }

    var snapshotUrl = amazonDomain + '/' + filename + '?' +
        utils.serializeToQueryString(params);
    var thumbnailUrl = amazonDomain + '/' + filename + '.png';

    initOptions.thumbnail = thumbnailUrl;

    var start = function () {
        try {
            if (!inIFrame) {
                $document.body.className ='no-iframe';
            } else {
                $document.body.style.overflow = 'hidden';
            }
            var target = $document.getElementById(TARGET_ID);
            target.style.width  = targetWidth + 'px';
            target.style.height = targetHeight + 'px';
            target.style.marginLeft = -Math.floor(targetWidth / 2) + 'px';
            target.style.marginTop  = -Math.floor(targetHeight / 2) + 'px';
            target.style.position = 'absolute';
            target.style.left = '50%';
            target.style.top = '50%';

            utils.forcedJS('//' + playerDomain + '/' + PLAYER_VERSION_ID + '/bundle/animatron.min.js',
                function () {
                    var player = anm.Player.forSnapshot(TARGET_ID, snapshotUrl, anm.importers.create('animatron'), $window.actions, initOptions);
                    if (anm.interop && anm.interop.playerjs) {
                        anm.interop.playerjs.setPlayer(player);
                    }
            });
        } catch (e) {
            if($window.console) console.error(e);
        }
    };

    $window.start = start;

})(this, window, document);
<commit_msg>fix thumbnail URL in publish.js<commit_after>/*
 * Copyright (c) 2011-2014 by Animatron.
 * All rights are reserved.
 */

/* Variables we get from template:
   playerDomain — a URL to player domain host, e.g. player.animatron.com
   amazonDomain — a URL to snapshot storage host, e.g. http://snapshots.animatron.com/<snapshot-id>
   width — width of the animation
   height — height of the animation
   playerVersion — player version, default 'latest'
   filename — filename of snapshot, used as amazonDomain + filename
   autostart — (boolean) autostart of movie on player load
   loop — (boolean) loop animation instead of stoping at the end
   animation — JSON object of animatron movie (currently not used)
   hasInteractivity — (boolean) if there's some interactivity in the project, it should be autostarted (overrides `autostart`) and handle events
*/
(function($global, $window, $document) {
    var inIFrame = ($window.self !== $window.top);

    var autostart = $global['autostart'] || false,
        loop = $global['loop'] || false,
        hasInteractivity = $global['hasInteractivity'] || false;

    var utils = {
        isInt: function(n) {
            n = Number(n);
            return !isNaN(n) && Math.floor(n) === n;
        },
        serializeToQueryString: function(obj) {
            var str = [];
            for(var p in obj) {
                if (obj.hasOwnProperty(p)) {
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                }
            }
            return str.join("&");
        },
        parseQueryString: function() {
            var queryString = location.search.substring(1);
            if (!queryString) {
                return {};
            }
            var queries = queryString.split("&"),
                params = {}, temp, i, l;
            for ( i = 0, l = queries.length; i < l; i++ ) {
                temp = queries[i].split('=');
                params[temp[0]] = temp[1];
            }
            return params;
        },
        getRequiredRect: function () {
            if (inIFrame) {
                return utils.getIframeSize();
            } else {
                return {w: width, h: height};
            }
        },
        getIframeSize: function () {
            var size = {w:0, h:0};
            if (typeof $window.innerWidth == 'number') {
                size.w = $window.innerWidth;
                size.h = $window.innerHeight;
            } else {
                size.w = $document.documentElement.clientWidth;
                size.h = $document.documentElement.clientHeight;
            }
            return size;
        },
        forcedJS: function (path, then) {
            var scriptElm = $document.createElement('script');
            scriptElm.type = 'text/javascript';
            scriptElm.async = 'async';
            scriptElm.src = path;
            scriptElm.onload = scriptElm.onreadystatechange = (function () {
                var success = false;
                return function () {
                    if (this.readyState === 'loading') {
                        return;
                    }
                    if (!success && (!this.readyState ||
                        (this.readyState === 'complete' || this.readyState === 'loaded')
                    )) {
                        success = true;
                        then();
                    } else if (!success && $window.console) {
                        console.error('Request failed: ' + this.readyState);
                    }
                };
            })();
            var headElm = $document.head || $document.getElementsByTagName('head')[0];
            headElm.appendChild(scriptElm);
        }
    };

    var TARGET_ID = 'target',
    WRAPPER_CLASS = 'anm-wrapper',
    PLAYER_VERSION_ID = playerVersion || 'latest';

    // options to apply just _after_ the snapshot was completely loaded are stored in the url (width and height in `params`)
    // initialization options are stored in `initOptions`
    var params = utils.parseQueryString(),
        initOptions = {};

    var rect = utils.getRequiredRect(),
        targetWidth, targetHeight;

    //floating-point w&h parameters mean percentage sizing
    if (params.w && !utils.isInt(params.w)) {
        targetWidth = params.w = Math.round(params.w * rect.w);
    } else {
        targetWidth = params.w = params.w || rect.w;
    }
    if (params.h && !utils.isInt(params.h)) {
        targetHeight = params.h = Math.round(params.h * rect.h);
    } else {
        targetHeight = params.h = params.h || rect.h;
    }
    if (autostart || hasInteractivity) {
        initOptions.autoPlay = true;
    }
    if (loop) {
        initOptions.repeat = true;
    }
    if (hasInteractivity) {
        initOptions.controlsEnabled = false;
        initOptions.handleEvents = true;
    }

    if (params.v) {
        PLAYER_VERSION_ID = params.v;
    }

    var snapshotUrl = amazonDomain + '/' + filename + '?' +
        utils.serializeToQueryString(params);
    var thumbnailUrl = amazonDomain + '/' + filename.slice(0, filename.indexOf('.')) + '.jpg';

    initOptions.thumbnail = thumbnailUrl;

    var start = function () {
        try {
            if (!inIFrame) {
                $document.body.className ='no-iframe';
            } else {
                $document.body.style.overflow = 'hidden';
            }
            var target = $document.getElementById(TARGET_ID);
            target.style.width  = targetWidth + 'px';
            target.style.height = targetHeight + 'px';
            target.style.marginLeft = -Math.floor(targetWidth / 2) + 'px';
            target.style.marginTop  = -Math.floor(targetHeight / 2) + 'px';
            target.style.position = 'absolute';
            target.style.left = '50%';
            target.style.top = '50%';

            utils.forcedJS('//' + playerDomain + '/' + PLAYER_VERSION_ID + '/bundle/animatron.min.js',
                function () {
                    var player = anm.Player.forSnapshot(TARGET_ID, snapshotUrl, anm.importers.create('animatron'), $window.actions, initOptions);
                    if (anm.interop && anm.interop.playerjs) {
                        anm.interop.playerjs.setPlayer(player);
                    }
            });
        } catch (e) {
            if($window.console) console.error(e);
        }
    };

    $window.start = start;

})(this, window, document);
<|endoftext|>