<commit_before>
function map(start, end) {
  let mapProp= {
    center: new google.maps.LatLng(end.lat, end.lng),
    zoom: 15,
    disableDefaultUI: true,
    styles: [ { "featureType": "administrative", "elementType": "labels", "stylers": [ { "visibility": "on" } ] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [ { "color": "#212121" } ] }, { "featureType": "administrative", "elementType": "labels.text.stroke", "stylers": [ { "color": "#f5f5f5" } ] }, { "featureType": "administrative", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape", "elementType": "all", "stylers": [ { "color": "#f2f2f2" } ] }, { "featureType": "landscape.man_made", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#e0e0e0" } ] }, { "featureType": "landscape.man_made", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape.natural", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#eeeeee" } ] }, { "featureType": "landscape.natural", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape.natural.landcover", "elementType": "geometry", "stylers": [ { "color": "#ff0000" } ] }, { "featureType": "poi", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.attraction", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" }, { "visibility": "on" } ] }, { "featureType": "poi.attraction", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.business", "elementType": "all", "stylers": [ { "visibility": "on" }, { "color": "#bdbdbd" } ] }, { "featureType": "poi.business", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.government", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" }, { "visibility": "on" } ] }, { "featureType": "poi.government", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.medical", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" }, { "visibility": "on" } ] }, { "featureType": "poi.medical", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#81c781" } ] }, { "featureType": "poi.park", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.place_of_worship", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" }, { "visibility": "on" } ] }, { "featureType": "poi.place_of_worship", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.school", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#bdbdbd" } ] }, { "featureType": "poi.school", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.sports_complex", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" } ] }, { "featureType": "poi.sports_complex", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road", "elementType": "all", "stylers": [ { "saturation": -100 }, { "lightness": 45 } ] }, { "featureType": "road", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#f5f5f5" } ] }, { "featureType": "road", "elementType": "labels", "stylers": [ { "visibility": "on" } ] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [ { "color": "#212121" } ] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [ { "color": "#f5f5f5" } ] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road.highway", "elementType": "all", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "road.arterial", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "water", "elementType": "all", "stylers": [ { "color": "#46bcec" }, { "visibility": "on" } ] }, { "featureType": "water", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#00bcd4" } ] } ]
  };
  let drawMap = new google.maps.Map(document.getElementById("Map"), mapProp);

  let directionsService = new google.maps.DirectionsService;
  directionsService.route({
    origin: start.lat + ',' + start.lng,
    destination: end.lat + ',' + end.lng,
    travelMode: 'WALKING',
    language: 'fa-IR'
  }, function(response, status) {
    if (status === 'OK') {
      $('.description-title strong').text(response.routes[0].legs[0].distance.text)
      $('.description-title small').text(response.routes[0].legs[0].duration.text)
    } else {
      console.log('Directions request failed due to ' + status);
      $('.description-title p').hide()
    }
  });

}

$(function() {

  map(
    {
      // start
      lat: 35.746368,
      lng: 51.380923
    },
    {
      // end
      lat: 35.7442482,
      lng: 51.3757476
    }
  );

  $('.owl-carousel').owlCarousel({
    rtl: true,
    loop: true,
    margin: 12,
    items: 2,
    center: true
  })

  $('a.image-bg').featherlight({
    targetAttr: 'data-featherlight',
    closeIcon: '',
    closeOnClick: 'anywhere'
  });

  var is_open = false;
  $('.description-detail-more').on('click', function() {
    if (is_open) {
      $(this).siblings('.description-detail-inner').addClass('mini').css({
        'height': ''
      })
      $(this).children().html('نمایش بیشتر')
      $('html, body').animate({
        scrollTop: $('.description-title').offset().top - 62
      }, 200);
      is_open = false
    } else {
      $(this).siblings('.description-detail-inner').removeClass('mini').css({
        'height': $(this).siblings('.description-detail-inner').find('.description-detail-inner-wrapper').outerHeight()
      })
      $(this).children().text('نمایش کمتر')
      is_open = true
    }
  })
});
<commit_msg>Added marker to Map<commit_after>
function map(start, end) {
  let map = new google.maps.Map(document.getElementById("Map"), {
    center: new google.maps.LatLng(end.lat, end.lng),
    zoom: 14,
    disableDefaultUI: true,
    styles: [ { "featureType": "administrative", "elementType": "labels", "stylers": [ { "visibility": "on" } ] }, { "featureType": "administrative", "elementType": "labels.text.fill", "stylers": [ { "color": "#212121" } ] }, { "featureType": "administrative", "elementType": "labels.text.stroke", "stylers": [ { "color": "#f5f5f5" } ] }, { "featureType": "administrative", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape", "elementType": "all", "stylers": [ { "color": "#f2f2f2" } ] }, { "featureType": "landscape.man_made", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#e0e0e0" } ] }, { "featureType": "landscape.man_made", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape.natural", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#eeeeee" } ] }, { "featureType": "landscape.natural", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "landscape.natural.landcover", "elementType": "geometry", "stylers": [ { "color": "#ff0000" } ] }, { "featureType": "poi", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.attraction", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" }, { "visibility": "on" } ] }, { "featureType": "poi.attraction", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.business", "elementType": "all", "stylers": [ { "visibility": "on" }, { "color": "#bdbdbd" } ] }, { "featureType": "poi.business", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.government", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" }, { "visibility": "on" } ] }, { "featureType": "poi.government", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.medical", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" }, { "visibility": "on" } ] }, { "featureType": "poi.medical", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.park", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#81c781" } ] }, { "featureType": "poi.park", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.place_of_worship", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" }, { "visibility": "on" } ] }, { "featureType": "poi.place_of_worship", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.school", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#bdbdbd" } ] }, { "featureType": "poi.school", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "poi.sports_complex", "elementType": "geometry", "stylers": [ { "color": "#bdbdbd" } ] }, { "featureType": "poi.sports_complex", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road", "elementType": "all", "stylers": [ { "saturation": -100 }, { "lightness": 45 } ] }, { "featureType": "road", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#f5f5f5" } ] }, { "featureType": "road", "elementType": "labels", "stylers": [ { "visibility": "on" } ] }, { "featureType": "road", "elementType": "labels.text.fill", "stylers": [ { "color": "#212121" } ] }, { "featureType": "road", "elementType": "labels.text.stroke", "stylers": [ { "color": "#f5f5f5" } ] }, { "featureType": "road", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "road.highway", "elementType": "all", "stylers": [ { "visibility": "simplified" } ] }, { "featureType": "road.arterial", "elementType": "labels.icon", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit", "elementType": "all", "stylers": [ { "visibility": "off" } ] }, { "featureType": "water", "elementType": "all", "stylers": [ { "color": "#46bcec" }, { "visibility": "on" } ] }, { "featureType": "water", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "color": "#00bcd4" } ] } ]
  });

  let mapMarker = new google.maps.Marker({
      position: new google.maps.LatLng(end.lat, end.lng),
      map: map
    });

  let directionsService = new google.maps.DirectionsService;
  directionsService.route({
    origin: start.lat + ',' + start.lng,
    destination: end.lat + ',' + end.lng,
    travelMode: 'WALKING',
    language: 'fa-IR'
  }, function(response, status) {
    if (status === 'OK') {
      $('.description-title strong').text(response.routes[0].legs[0].distance.text)
      $('.description-title small').text(response.routes[0].legs[0].duration.text)
    } else {
      console.log('Directions request failed due to ' + status);
      $('.description-title p').hide()
    }
  });

}

$(function() {

  map(
    {
      // start
      lat: 35.746368,
      lng: 51.380923
    },
    {
      // end
      lat: 35.7442482,
      lng: 51.3757476
    }
  );

  $('.owl-carousel').owlCarousel({
    rtl: true,
    loop: true,
    margin: 12,
    items: 2,
    center: true
  })

  $('a.image-bg').featherlight({
    targetAttr: 'data-featherlight',
    closeIcon: '',
    closeOnClick: 'anywhere'
  });

  var is_open = false;
  $('.description-detail-more').on('click', function() {
    if (is_open) {
      $(this).siblings('.description-detail-inner').addClass('mini').css({
        'height': ''
      })
      $(this).children().html('نمایش بیشتر')
      $('html, body').animate({
        scrollTop: $('.description-title').offset().top - 62
      }, 200);
      is_open = false
    } else {
      $(this).siblings('.description-detail-inner').removeClass('mini').css({
        'height': $(this).siblings('.description-detail-inner').find('.description-detail-inner-wrapper').outerHeight()
      })
      $(this).children().text('نمایش کمتر')
      is_open = true
    }
  })
});
<|endoftext|>


<commit_before>sap.ui.define([
	'jquery.sap.global',
	'sap/ui/core/Fragment',
	'sap/ui/core/mvc/Controller',
	'sap/ui/model/json/JSONModel',
	'sap/m/MessageToast'
], function (jQuery, Fragment, Controller, JSONModel, MessageToast) {
	"use strict";

	var CController = Controller.extend("sap.m.sample.QuickView.QuickView", {

		// create JSON model instance
		oCompanyModel: new JSONModel(),
		oEmployeeModel: new JSONModel(),
		oGenericModel: new JSONModel(),
		oGenericDataNoHeader: new JSONModel(),
		onInit: function () {
			// JSON sample data
			var mCompanyData = {
				pages: [
					{
						pageId: "companyPageId",
						header: "Company info",
						title: "Adventure Company",
						titleUrl: "http://sap.com",
						icon: "sap-icon://building",
						description: "John Doe",
						groups: [
							{
								heading: "Contact Details",
								elements: [
									{
										label: "Phone",
										value: "+001 6101 34869-0",
										elementType: sap.m.QuickViewGroupElementType.phone
									},
									{
										label: "Address",
										value: "550 Larkin Street, 4F, Mountain View, CA, 94102 San Francisco USA",
										elementType: sap.m.QuickViewGroupElementType.text
									}
								]
							},
							{
								heading: "Main Contact",
								elements: [
									{
										label: "Name",
										value: "John Doe",
										elementType: sap.m.QuickViewGroupElementType.pageLink,
										pageLinkId: "companyEmployeePageId"
									},
									{
										label: "Mobile",
										value: "+001 6101 34869-0",
										elementType: sap.m.QuickViewGroupElementType.mobile
									},
									{
										label: "Phone",
										value: "+001 6101 34869-0",
										elementType: sap.m.QuickViewGroupElementType.phone
									},
									{
										label: "Email",
										value: "main.contact@company.com",
										emailSubject : 'Subject',
										elementType: sap.m.QuickViewGroupElementType.email
									}
								]
							}
						]
					},
					{
						pageId: "companyEmployeePageId",
						header: "Employee Info",
						title: "John Doe",
						icon: "sap-icon://person-placeholder",
						description: "Department Manager",
						groups: [
							{
								heading: "Company",
								elements: [
									{
										label: "Name",
										value: "Adventure Company",
										url: "http://sap.com",
										elementType: sap.m.QuickViewGroupElementType.link
									},
									{
										label: "Address",
										value: "Sofia, Boris III, 136A"
									},
									{
										label: "Slogan",
										value: "Innovation through technology"
									}
								]
							},
							{
								heading: "Other",
								elements: [
									{
										label: "Email",
										value: "john.doe@sap.com",
										emailSubject : 'Subject',
										elementType: sap.m.QuickViewGroupElementType.email
									},
									{
										label: "Phone",
										value: "+359 888 888 888",
										elementType: sap.m.QuickViewGroupElementType.phone
									}
								]
							}
						]
					}
				]
			};

			var mEmployeeData = {
				pages: [
					{
						pageId: "employeePageId",
						header: "Employee Info",
						icon: "test-resources/sap/ui/demokit/explored/img/johnDoe.png",
						title: "Michael Muller",
						description: "Account Manager",
						groups: [
							{
								heading: "Contact Details",
								elements: [
									{
										label: "Mobile",
										value: "+001 6101 34869-0",
										elementType: sap.m.QuickViewGroupElementType.mobile
									},
									{
										label: "Phone",
										value: "+001 6101 34869-1",
										elementType: sap.m.QuickViewGroupElementType.phone
									},
									{
										label: "Email",
										value: "main.contact@company.com",
										emailSubject : 'Subject',
										elementType: sap.m.QuickViewGroupElementType.email
									}
								]
							},
							{
								heading: "Company",
								elements: [
									{
										label: "Name",
										value: "Adventure Company",
										url: "http://sap.com",
										elementType: sap.m.QuickViewGroupElementType.link
									},
									{
										label: "Address",
										value: "Main Street 4572, Los Angeles USA"
									}
								]
							}
						]
					}
				]
			};

			var mGenericData = {
				pages: [
					{
						pageId: "genericPageId",
						header: "Process",
						title: "Inventarisation",
						titleUrl: "http://de.wikipedia.org/wiki/Inventarisation",
						icon: "sap-icon://camera",
						groups: [
							{
								elements: [
									{
										label: "Start Date",
										value: "01/01/2015"
									},
									{
										label: "End Date",
										value: "31/12/2015"
									},
									{
										label: "Occurrence",
										value: "Weekly"
									}
								]
							}
						]
					}
				]
			};

			var mGenericDataNoHeader = {
				pages: [
					{
						pageId: "genericPageId",
						title: "Inventarisation",
						titleUrl: "http://de.wikipedia.org/wiki/Inventarisation",
						icon: "sap-icon://camera",
						groups: [
							{
								elements: [
									{
										label: "Start Date",
										value: "01/01/2015"
									},
									{
										label: "End Date",
										value: "31/12/2015"
									},
									{
										label: "Occurrence",
										value: "Weekly"
									}
								]
							}
						]
					}
				]
			};

			// set the data for the model
			this.oCompanyModel.setData(mCompanyData);
			this.oEmployeeModel.setData(mEmployeeData);
			this.oGenericModel.setData(mGenericData);
			this.oGenericDataNoHeader.setData(mGenericDataNoHeader);
		},

		onAfterRendering: function () {
			var oButton = this.getView().byId('showQuickView');
			oButton.$().attr('aria-haspopup', true);

			oButton = this.getView().byId('employeeQuickView');
			oButton.$().attr('aria-haspopup', true);

			oButton = this.getView().byId('genericQuickView');
			oButton.$().attr('aria-haspopup', true);
		},

		openQuickView: function (oEvent, oModel) {
			this.createPopover();

			this._oQuickView.setModel(oModel);

			// delay because addDependent will do a async rerendering and the actionSheet will immediately close without it.
			var oButton = oEvent.getSource();
			jQuery.sap.delayedCall(0, this, function () {
				this._oQuickView.openBy(oButton);
			});
		},

		handleCompanyQuickViewPress: function (oEvent) {
			this.openQuickView(oEvent, this.oCompanyModel);
		},

		handleEmployeeQuickViewPress: function (oEvent) {
			this.openQuickView(oEvent, this.oEmployeeModel);
		},

		handleGenericQuickViewPress: function (oEvent) {
			this.openQuickView(oEvent, this.oGenericModel);
		},

		handleGenericNoHeaderQuickViewPress: function (oEvent) {
			this.openQuickView(oEvent, this.oGenericDataNoHeader);
		},

		createPopover: function() {
			if (!this._oQuickView) {
				this._oQuickView = sap.ui.xmlfragment("sap.m.sample.QuickView.QuickView", this);
				this.getView().addDependent(this._oQuickView);
			}
		},

		onNavigate: function (oEvent) {
			var oNavOrigin = oEvent.getParameter("navOrigin");
			if (oNavOrigin) {
				MessageToast.show('Link "' + oNavOrigin.getText() + '" was clicked');
			} else {
				MessageToast.show('Back button was clicked');
			}
		},

		onExit: function () {
			if (this._oQuickView) {
				this._oQuickView.destroy();
			}
		}
	});

	return CController;

});
<commit_msg>[INTERNAL][FIX] sap.m.QuickView: Samples are now working correctly<commit_after>sap.ui.define([
	'jquery.sap.global',
	'sap/ui/core/Fragment',
	'sap/ui/core/mvc/Controller',
	'sap/ui/model/json/JSONModel',
	'sap/m/MessageToast'
], function (jQuery, Fragment, Controller, JSONModel, MessageToast) {
	"use strict";

	var CController = Controller.extend("sap.m.sample.QuickView.QuickView", {

		// create JSON model instance
		oCompanyModel: new JSONModel(),
		oEmployeeModel: new JSONModel(),
		oGenericModel: new JSONModel(),
		oGenericDataNoHeader: new JSONModel(),
		onInit: function () {
			// JSON sample data
			var mCompanyData = {
				pages: [
					{
						pageId: "companyPageId",
						header: "Company info",
						title: "Adventure Company",
						titleUrl: "http://sap.com",
						icon: "sap-icon://building",
						description: "John Doe",
						groups: [
							{
								heading: "Contact Details",
								elements: [
									{
										label: "Phone",
										value: "+001 6101 34869-0",
										elementType: sap.m.QuickViewGroupElementType.phone
									},
									{
										label: "Address",
										value: "550 Larkin Street, 4F, Mountain View, CA, 94102 San Francisco USA",
										elementType: sap.m.QuickViewGroupElementType.text
									}
								]
							},
							{
								heading: "Main Contact",
								elements: [
									{
										label: "Name",
										value: "John Doe",
										elementType: sap.m.QuickViewGroupElementType.pageLink,
										pageLinkId: "companyEmployeePageId"
									},
									{
										label: "Mobile",
										value: "+001 6101 34869-0",
										elementType: sap.m.QuickViewGroupElementType.mobile
									},
									{
										label: "Phone",
										value: "+001 6101 34869-0",
										elementType: sap.m.QuickViewGroupElementType.phone
									},
									{
										label: "Email",
										value: "main.contact@company.com",
										emailSubject : 'Subject',
										elementType: sap.m.QuickViewGroupElementType.email
									}
								]
							}
						]
					},
					{
						pageId: "companyEmployeePageId",
						header: "Employee Info",
						title: "John Doe",
						icon: "sap-icon://person-placeholder",
						description: "Department Manager",
						groups: [
							{
								heading: "Company",
								elements: [
									{
										label: "Name",
										value: "Adventure Company",
										url: "http://sap.com",
										elementType: sap.m.QuickViewGroupElementType.link
									},
									{
										label: "Address",
										value: "Sofia, Boris III, 136A"
									},
									{
										label: "Slogan",
										value: "Innovation through technology"
									}
								]
							},
							{
								heading: "Other",
								elements: [
									{
										label: "Email",
										value: "john.doe@sap.com",
										emailSubject : 'Subject',
										elementType: sap.m.QuickViewGroupElementType.email
									},
									{
										label: "Phone",
										value: "+359 888 888 888",
										elementType: sap.m.QuickViewGroupElementType.phone
									}
								]
							}
						]
					}
				]
			};

			var mEmployeeData = {
				pages: [
					{
						pageId: "employeePageId",
						header: "Employee Info",
						icon: "test-resources/sap/ui/demokit/explored/img/johnDoe.png",
						title: "Michael Muller",
						description: "Account Manager",
						groups: [
							{
								heading: "Contact Details",
								elements: [
									{
										label: "Mobile",
										value: "+001 6101 34869-0",
										elementType: sap.m.QuickViewGroupElementType.mobile
									},
									{
										label: "Phone",
										value: "+001 6101 34869-1",
										elementType: sap.m.QuickViewGroupElementType.phone
									},
									{
										label: "Email",
										value: "main.contact@company.com",
										emailSubject : 'Subject',
										elementType: sap.m.QuickViewGroupElementType.email
									}
								]
							},
							{
								heading: "Company",
								elements: [
									{
										label: "Name",
										value: "Adventure Company",
										url: "http://sap.com",
										elementType: sap.m.QuickViewGroupElementType.link
									},
									{
										label: "Address",
										value: "Main Street 4572, Los Angeles USA"
									}
								]
							}
						]
					}
				]
			};

			var mGenericData = {
				pages: [
					{
						pageId: "genericPageId",
						header: "Process",
						title: "Inventarisation",
						titleUrl: "http://de.wikipedia.org/wiki/Inventarisation",
						icon: "sap-icon://camera",
						groups: [
							{
								elements: [
									{
										label: "Start Date",
										value: "01/01/2015"
									},
									{
										label: "End Date",
										value: "31/12/2015"
									},
									{
										label: "Occurrence",
										value: "Weekly"
									}
								]
							}
						]
					}
				]
			};

			var mGenericDataNoHeader = {
				pages: [
					{
						pageId: "genericPageId",
						title: "Inventarisation",
						titleUrl: "http://de.wikipedia.org/wiki/Inventarisation",
						icon: "sap-icon://camera",
						groups: [
							{
								elements: [
									{
										label: "Start Date",
										value: "01/01/2015"
									},
									{
										label: "End Date",
										value: "31/12/2015"
									},
									{
										label: "Occurrence",
										value: "Weekly"
									}
								]
							}
						]
					}
				]
			};

			// set the data for the model
			this.oCompanyModel.setData(mCompanyData);
			this.oEmployeeModel.setData(mEmployeeData);
			this.oGenericModel.setData(mGenericData);
			this.oGenericDataNoHeader.setData(mGenericDataNoHeader);
		},

		onAfterRendering: function () {
			var oButton = this.getView().byId('showQuickView');
			oButton.$().attr('aria-haspopup', true);

			oButton = this.getView().byId('employeeQuickView');
			oButton.$().attr('aria-haspopup', true);

			oButton = this.getView().byId('genericQuickView');
			oButton.$().attr('aria-haspopup', true);
		},

		openQuickView: function (oEvent, oModel) {
			this.createPopover();

			this._oQuickView.setModel(oModel);

			// delay because addDependent will do a async rerendering and the actionSheet will immediately close without it.
			var oButton = oEvent.getSource();
			jQuery.sap.delayedCall(0, this, function () {
				this._oQuickView.openBy(oButton);
			});
		},

		handleCompanyQuickViewPress: function (oEvent) {
			this.openQuickView(oEvent, this.oCompanyModel);
		},

		handleEmployeeQuickViewPress: function (oEvent) {
			this.openQuickView(oEvent, this.oEmployeeModel);
		},

		handleGenericQuickViewPress: function (oEvent) {
			this.openQuickView(oEvent, this.oGenericModel);
		},

		handleGenericNoHeaderQuickViewPress: function (oEvent) {
			this.openQuickView(oEvent, this.oGenericDataNoHeader);
		},

		createPopover: function() {
			if (this._oQuickView) {
				this._oQuickView.destroy();
			}

			this._oQuickView = sap.ui.xmlfragment("sap.m.sample.QuickView.QuickView", this);
			this.getView().addDependent(this._oQuickView);
		},

		onNavigate: function (oEvent) {
			var oNavOrigin = oEvent.getParameter("navOrigin");
			if (oNavOrigin) {
				MessageToast.show('Link "' + oNavOrigin.getText() + '" was clicked');
			} else {
				MessageToast.show('Back button was clicked');
			}
		},

		onExit: function () {
			if (this._oQuickView) {
				this._oQuickView.destroy();
			}
		}
	});

	return CController;

});
<|endoftext|>


<commit_before>window.UserSearchView = Backbone.View.extend({
  tagName: "div",
  className: "user-block",

  events: {
    "click div.avatar-container": "clickHandler"
  },

  initialize: function() {
    this.useTemplate("users", "_user_search");
  },

  render: function() {
    $(this.el).html( Mustache.to_html(this.tmpl, this.model.toJSON()) );

    return this;
  },

  clickHandler: function(e) {
    document.location.href = this.model.url();
  }
});
<commit_msg>Bind click on list-block<commit_after>window.UserSearchView = Backbone.View.extend({
  tagName: "div",
  className: "user-block",

  events: {
    "click div.list-block": "clickHandler"
  },

  initialize: function() {
    this.useTemplate("users", "_user_search");
  },

  render: function() {
    $(this.el).html( Mustache.to_html(this.tmpl, this.model.toJSON()) );

    return this;
  },

  clickHandler: function(e) {
    document.location.href = this.model.url();
  }
});
<|endoftext|>


<commit_before>/*globals $ */

function listImages(collection, item) {
	// TODO: Check for an initialized datatable & if it exists, destroy it
	//Clear away any existing contents of the table in the DOM
	$('tbody#page-images').empty();
	// Hide the item selector div and display a modal dialogue while the appropriate page image links are retrieved
	$('#itemSelector').hide();
	$('#loading_modal').ajaxStart(function(){
		$(this).modal('show');
	});

	// Check to see if a partial manifest already exists
	var checkServer = $.ajax({
		type: "HEAD",
		url: "/metadata/manifests/" + item + ".xml"
	});
	// If a partial manifest exists, GET it and construct a table with the data returned
	checkServer.done(function() {
		var manifestPromise = $.ajax({
			type: "GET",
			url: "/metadata/manifests/" + item + ".xml",
			dataType: "xml"
		});
		// Create table rows with info retrieved from the server: filename | link to page image | label
		manifestPromise.done(function(xml) {
			// Set the name of the item as the title for the table
			$('#imageTable > h2').append(item);
			// Parse the XML returned by AJAX and build html strings with the data. Add them to the table
			$(xml).find("item").each(function(){
				var tdString = '
'+$(this).children("filename").text()+'		'+$(this).children("label").text()+'
';
				$('#page-images').prepend(tdString);
			});
		});
		// Initialize jquery datatable from DOM table to add pagination, sorting, editing functionality
		manifestPromise.done(function() {
			// dataTable() takes an object with initialization parameters. See dataTable API
			var editableTable = $('#imageDataTable').dataTable({
				"bDestroy":true,
				"bStateSave": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": false
			});
			// Make the rows editable (this adds another dependency)
			$('td.editable', editableTable.fnGetNodes()).editable(function(value, settings) {
				var aPos = editableTable.fnGetPosition(this);
				editableTable.fnUpdate(value, aPos[0], aPos[1]);
			},
			{
				onblur : "submit"
			});
		});
		// Add an event handler to reset to item selection state
		$('#prev-to-manifest button').one('click', function() {
			// Hide the table, deactivate save, tear down data tables functionality & empty the table
			$('#imageTable').hide();
			$('#jsSave').off();
			$('#imageDataTable').dataTable().fnDestroy();
			$('tbody#page-images').empty();
			$('#imageTable > h2').empty();
			// Run getItems again to get the item list
			getItems($('#select-repo option:selected').attr('value'));
		});

		// When everything is constructed, add save handler, show the div with the table and clear the modal dialogue
		manifestPromise.done(function() {
			$('#jsSave').on("click", function(){
				saveManifest();
			});
			$('#imageTable').show();
			$('#loading_modal').ajaxStop(function(){
				$(this).modal('hide');
			});
		});
	}); // End of manifest exists block

	// If no manifest exists, GET the listing from the sga.mith.org/images directory & build the table from that
	checkServer.fail(function() {
		var remoteDirPromise = $.ajax({
			type: "GET",
			url: "/metadata/xq/image_getter.xquery?coll-id="+collection+"&item="+item,
			dataType: "xml"
		});
		remoteDirPromise.done(function(xml){
			$('#imageTable > h2').append(item);
			$(xml).find("a").each(function(){
				var tdString = '
'+$(this).text()+'
';
				$('#page-images').prepend(tdString);
			});
		});
		remoteDirPromise.done(function() {
			// dataTable() takes an object with initialization parameters. See dataTable API
			var editableTable = $('#imageDataTable').dataTable({
				"bDestroy":true,
				"bStateSave": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": false
			});
			// Make the rows editable (this adds another dependency)
			$('td.editable', editableTable.fnGetNodes()).editable(function(value, settings) {
				var aPos = editableTable.fnGetPosition(this);
				editableTable.fnUpdate(value, aPos[0], aPos[1]);
			},
			{
				onblur : "submit"
			});
		});
		// Add an event handler to reset to item selection state
		$('#prev-to-manifest button').one('click', function() {
			// Hide the table, deactivate save, tear down data tables functionality & empty the table
			$('#imageTable').hide();
			$('#jsSave').off();
			$('#imageDataTable').dataTable().fnDestroy();
			$('tbody#page-images').empty();
			$('#imageTable > h2').empty();
			// Run getItems again to get the item list
			getItems($('#select-repo option:selected').attr('value'));
		});

		// When everything is constructed, add save handler, show the div with the table and clear the modal dialogue
		remoteDirPromise.done(function() {
			$('#jsSave').on("click", function(){
				saveManifest();
			});
			$('#imageTable').show();
			$('#loading_modal').ajaxStop(function(){
				$(this).modal('hide');
			});
		});

	}); // End of manifest does not exist block
}

function getItems(param) {
	"use strict";
	$('#ajax-loader').ajaxStart(function () {
    	$(this).show();
    	// Make sure the list of items is empty
    	if ($('#ajax-file-manifest').children().length !== 0) {
    		$('#ajax-file-manifest').empty();
    	}
    });
	var getItemPromise = $.ajax({
		type: 'GET',
		url: '/metadata/xq/dir_parser.xquery?coll-id=' + param,
		dataType: 'xml',
		timeout: 30000
	});
	getItemPromise.done(function(xml) {
        if($(xml).find('error').length !== 0) {
            var errorMsg = '
×'+$(xml).find('error').text()+' Please make sure the correct holdings information has been selected. [HTTP status code '+$(xml).find('error').attr('http-status-code')+']
';
           $('.container').prepend(errorMsg);
           $(".alert").alert();
           // $('#next-to-manifest button').on("click", function() {
           //          window.getItems($('#institution-code .xforms-value').text());
           //      });
        }
        else {
        var arr = [];
        $(xml).find("a").each(function () {
            arr.push($(this).attr("href"));
        });
        arr.shift();
        var all_items = $.map(arr, function(n){
            return n.split("-")[1];
        });
        var i,
            len = all_items.length,
            out = [],
            obj = {};
        for (i=0;i < len; i++){
            obj[all_items[i]] = 0;
        }
        for (i in obj){
            out.push(i);
        }
        $.map(out, function(val){
            return $('#ajax-file-manifest').prepend('
'+ val + '
' );
        });
    }
    });
	// Create an event listener on each li in the newly-created list of items
	getItemPromise.done(function () {
		$('.sga-item').on('click', 'a', function() {
			listImages($('#select-repo option:selected').attr('value'), $(this).parent().attr('id'));
			});
	});
	// Clean-up and show the list of items returned
	getItemPromise.done(function() {
		// Don't show an empty list
		if ($('#ajax-file-manifest').children().length !== 0) {
			// Disable the library selector --- don't want to change collections now that we have items
			$('#itemSelector').show();
			$('#select-repo select').attr('disabled', 'disabled');
			/* Unload the event listener on the image manifest button
			Don't want to fetch items again unless the load action fails */
			$('#next-to-manifest button').off();
		} else {
			// Need some error catching here
		}
		$('#ajax-loader').ajaxStop(function() {
			$(this).hide()
			});
	});
}

function setImageEventListener() {
	"use strict";
// Add event listener for image manifest section
    $('#next-to-manifest button').on("click", function () {
    window.getItems($('#select-repo option:selected').attr('value'));
});
}

function saveManifest() {
    var xmlString = '<?xml version="1.0" encoding="UTF-8"?><items>';
    var data = $('#imageDataTable').dataTable().fnGetData();
    $.each(data, function(index, value){
        xmlString += '<item id="'+ $('#imageTable > h2').text()+'"><filename>'+value[0]+'</filename>'+value[2]+'</item>';
    });
    xmlString += '</items>';
    var savePromise = $.ajax({
        type: "PUT",
        url: "/metadata/manifests/"+$('#itemID').text()+".xml",
        contentType: "application/xml",
        data: xmlString
    });
    savePromise.done(function(){
         var saveMsg = '
×Saved!
';
         $('#msgPlaceHolder').append(saveMsg);
         $(".alert").alert();
         window.setTimeout(function() { $(".alert-success").alert('close'); }, 2000);
    });
}

$(document).ready(
    function () {
        "use strict";

        // Do some basic re-styling of the page---for aesthetic reasons only
        $("div.container").css("margin-top", "40px");
        $("textarea.xforms-value").addClass('input-xlarge').css('height', '150px');

        // Add classes to use Twitter bootstrap
        $("button").addClass('btn');
        $(".navbar button").addClass("btn-inverse");
        // Emphasize certain buttons
        $("#img-to-finish button").addClass("btn-large btn-success");
        $("#next-to-manifest button").addClass("btn-primary btn-large");
        $("#surrogate-to-finish button").addClass("btn-large btn-success");
        $('.xforms-submit button').addClass('btn btn-primary btn-large');

        // Substitute attractive Twitter bootstrap + FontAwesome tooltips for ugly XSLTForms ones
        $(".xforms-required-icon").replaceWith('');
        $(".xforms-alert-icon").replaceWith('');
        // Tweak the display of the new icons
        $(".icon-large").css("display", "inline");
        // Activate the tooltip function on links
        $("a").popover();

        // Add placeholder text to the form
        $("#main-title input").attr("placeholder", "e.g., Frankenstein Notebook A");
        $("#creation-date input").attr("placeholder", "e.g., 1815");
        $("#item-label textarea").attr("placeholder", "Fragment of manuscript of Frankenstein (1818) (Draft Notebook A) containing parts of chapters 3-14 (plus further chapters unidentified)");
        $("#lib-collection input").attr("placeholder", "The Abinger Papers, 1780-1937");
        $("#lib-idno input").attr("placeholder", "MS. Abinger c. 56 ");
        $("#physical-extent input").attr("placeholder", "163 leaves");
        $("#physical-support textarea").attr("placeholder", "Paper with watermark: anchor in a circle with star on top, countermark B-B with trefoil similar to Moschin, Anchor N 1680, 1570-1585.");
        $("#foliation-orig textarea").attr("placeholder", "Folio numbers were added in brown ink ca. 1720-1730 in the upper right corner of all recto-pages.");
        $('#physical-condition textarea').attr("placeholder", "The manuscript shows signs of damage from water and mould on its outermost leaves.");
        $("#manu-hands textarea").attr("placeholder", "The manuscript is written in two contemporary hands. Hand I writes ff. 1r-22v and hand II ff. 23 and 24.");
        $("#metadata-creator input").attr("placeholder", "Liz Denlinger");
        $("#surrogate1 textarea").attr("placeholder", "Shelley, Mary W, and Charles E. Robinson. The Frankenstein Notebooks. New York: Garland Pub, 1996. Print.");
        $("#who input").attr("placeholder", "Charles Carter");
        $("#revision textarea").attr("placeholder", "Added more detailed information about hands");

        // Hide elements that will be used later for AJAX functionality
        $('#itemSelector').hide();
        $('#imageTable').hide();
        $('#ajax-loader').hide();

        $(".fancybox").fancybox();
        setImageEventListener();
    }
);

$(window).load(function() {
// If not a blank form (loading existing data), disable the repository selector
        if(location.pathname.search(/edit/) !== -1) {
            $('#select-repo select').attr('disabled', 'disabled');
        }
});<commit_msg>Adding placeholder text for info source<commit_after>/*globals $ */

function listImages(collection, item) {
	// TODO: Check for an initialized datatable & if it exists, destroy it
	//Clear away any existing contents of the table in the DOM
	$('tbody#page-images').empty();
	// Hide the item selector div and display a modal dialogue while the appropriate page image links are retrieved
	$('#itemSelector').hide();
	$('#loading_modal').ajaxStart(function(){
		$(this).modal('show');
	});

	// Check to see if a partial manifest already exists
	var checkServer = $.ajax({
		type: "HEAD",
		url: "/metadata/manifests/" + item + ".xml"
	});
	// If a partial manifest exists, GET it and construct a table with the data returned
	checkServer.done(function() {
		var manifestPromise = $.ajax({
			type: "GET",
			url: "/metadata/manifests/" + item + ".xml",
			dataType: "xml"
		});
		// Create table rows with info retrieved from the server: filename | link to page image | label
		manifestPromise.done(function(xml) {
			// Set the name of the item as the title for the table
			$('#imageTable > h2').append(item);
			// Parse the XML returned by AJAX and build html strings with the data. Add them to the table
			$(xml).find("item").each(function(){
				var tdString = '
'+$(this).children("filename").text()+'		'+$(this).children("label").text()+'
';
				$('#page-images').prepend(tdString);
			});
		});
		// Initialize jquery datatable from DOM table to add pagination, sorting, editing functionality
		manifestPromise.done(function() {
			// dataTable() takes an object with initialization parameters. See dataTable API
			var editableTable = $('#imageDataTable').dataTable({
				"bDestroy":true,
				"bStateSave": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": false
			});
			// Make the rows editable (this adds another dependency)
			$('td.editable', editableTable.fnGetNodes()).editable(function(value, settings) {
				var aPos = editableTable.fnGetPosition(this);
				editableTable.fnUpdate(value, aPos[0], aPos[1]);
			},
			{
				onblur : "submit"
			});
		});
		// Add an event handler to reset to item selection state
		$('#prev-to-manifest button').one('click', function() {
			// Hide the table, deactivate save, tear down data tables functionality & empty the table
			$('#imageTable').hide();
			$('#jsSave').off();
			$('#imageDataTable').dataTable().fnDestroy();
			$('tbody#page-images').empty();
			$('#imageTable > h2').empty();
			// Run getItems again to get the item list
			getItems($('#select-repo option:selected').attr('value'));
		});

		// When everything is constructed, add save handler, show the div with the table and clear the modal dialogue
		manifestPromise.done(function() {
			$('#jsSave').on("click", function(){
				saveManifest();
			});
			$('#imageTable').show();
			$('#loading_modal').ajaxStop(function(){
				$(this).modal('hide');
			});
		});
	}); // End of manifest exists block

	// If no manifest exists, GET the listing from the sga.mith.org/images directory & build the table from that
	checkServer.fail(function() {
		var remoteDirPromise = $.ajax({
			type: "GET",
			url: "/metadata/xq/image_getter.xquery?coll-id="+collection+"&item="+item,
			dataType: "xml"
		});
		remoteDirPromise.done(function(xml){
			$('#imageTable > h2').append(item);
			$(xml).find("a").each(function(){
				var tdString = '
'+$(this).text()+'
';
				$('#page-images').prepend(tdString);
			});
		});
		remoteDirPromise.done(function() {
			// dataTable() takes an object with initialization parameters. See dataTable API
			var editableTable = $('#imageDataTable').dataTable({
				"bDestroy":true,
				"bStateSave": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": false
			});
			// Make the rows editable (this adds another dependency)
			$('td.editable', editableTable.fnGetNodes()).editable(function(value, settings) {
				var aPos = editableTable.fnGetPosition(this);
				editableTable.fnUpdate(value, aPos[0], aPos[1]);
			},
			{
				onblur : "submit"
			});
		});
		// Add an event handler to reset to item selection state
		$('#prev-to-manifest button').one('click', function() {
			// Hide the table, deactivate save, tear down data tables functionality & empty the table
			$('#imageTable').hide();
			$('#jsSave').off();
			$('#imageDataTable').dataTable().fnDestroy();
			$('tbody#page-images').empty();
			$('#imageTable > h2').empty();
			// Run getItems again to get the item list
			getItems($('#select-repo option:selected').attr('value'));
		});

		// When everything is constructed, add save handler, show the div with the table and clear the modal dialogue
		remoteDirPromise.done(function() {
			$('#jsSave').on("click", function(){
				saveManifest();
			});
			$('#imageTable').show();
			$('#loading_modal').ajaxStop(function(){
				$(this).modal('hide');
			});
		});

	}); // End of manifest does not exist block
}

function getItems(param) {
	"use strict";
	$('#ajax-loader').ajaxStart(function () {
    	$(this).show();
    	// Make sure the list of items is empty
    	if ($('#ajax-file-manifest').children().length !== 0) {
    		$('#ajax-file-manifest').empty();
    	}
    });
	var getItemPromise = $.ajax({
		type: 'GET',
		url: '/metadata/xq/dir_parser.xquery?coll-id=' + param,
		dataType: 'xml',
		timeout: 30000
	});
	getItemPromise.done(function(xml) {
        if($(xml).find('error').length !== 0) {
            var errorMsg = '
×'+$(xml).find('error').text()+' Please make sure the correct holdings information has been selected. [HTTP status code '+$(xml).find('error').attr('http-status-code')+']
';
           $('.container').prepend(errorMsg);
           $(".alert").alert();
           // $('#next-to-manifest button').on("click", function() {
           //          window.getItems($('#institution-code .xforms-value').text());
           //      });
        }
        else {
        var arr = [];
        $(xml).find("a").each(function () {
            arr.push($(this).attr("href"));
        });
        arr.shift();
        var all_items = $.map(arr, function(n){
            return n.split("-")[1];
        });
        var i,
            len = all_items.length,
            out = [],
            obj = {};
        for (i=0;i < len; i++){
            obj[all_items[i]] = 0;
        }
        for (i in obj){
            out.push(i);
        }
        $.map(out, function(val){
            return $('#ajax-file-manifest').prepend('
'+ val + '
' );
        });
    }
    });
	// Create an event listener on each li in the newly-created list of items
	getItemPromise.done(function () {
		$('.sga-item').on('click', 'a', function() {
			listImages($('#select-repo option:selected').attr('value'), $(this).parent().attr('id'));
			});
	});
	// Clean-up and show the list of items returned
	getItemPromise.done(function() {
		// Don't show an empty list
		if ($('#ajax-file-manifest').children().length !== 0) {
			// Disable the library selector --- don't want to change collections now that we have items
			$('#itemSelector').show();
			$('#select-repo select').attr('disabled', 'disabled');
			/* Unload the event listener on the image manifest button
			Don't want to fetch items again unless the load action fails */
			$('#next-to-manifest button').off();
		} else {
			// Need some error catching here
		}
		$('#ajax-loader').ajaxStop(function() {
			$(this).hide()
			});
	});
}

function setImageEventListener() {
	"use strict";
// Add event listener for image manifest section
    $('#next-to-manifest button').on("click", function () {
    window.getItems($('#select-repo option:selected').attr('value'));
});
}

function saveManifest() {
    var xmlString = '<?xml version="1.0" encoding="UTF-8"?><items>';
    var data = $('#imageDataTable').dataTable().fnGetData();
    $.each(data, function(index, value){
        xmlString += '<item id="'+ $('#imageTable > h2').text()+'"><filename>'+value[0]+'</filename>'+value[2]+'</item>';
    });
    xmlString += '</items>';
    var savePromise = $.ajax({
        type: "PUT",
        url: "/metadata/manifests/"+$('#itemID').text()+".xml",
        contentType: "application/xml",
        data: xmlString
    });
    savePromise.done(function(){
         var saveMsg = '
×Saved!
';
         $('#msgPlaceHolder').append(saveMsg);
         $(".alert").alert();
         window.setTimeout(function() { $(".alert-success").alert('close'); }, 2000);
    });
}

$(document).ready(
    function () {
        "use strict";

        // Do some basic re-styling of the page---for aesthetic reasons only
        $("div.container").css("margin-top", "40px");
        $("textarea.xforms-value").addClass('input-xlarge').css('height', '150px');

        // Add classes to use Twitter bootstrap
        $("button").addClass('btn');
        $(".navbar button").addClass("btn-inverse");
        // Emphasize certain buttons
        $("#img-to-finish button").addClass("btn-large btn-success");
        $("#next-to-manifest button").addClass("btn-primary btn-large");
        $("#surrogate-to-finish button").addClass("btn-large btn-success");
        $('.xforms-submit button').addClass('btn btn-primary btn-large');

        // Substitute attractive Twitter bootstrap + FontAwesome tooltips for ugly XSLTForms ones
        $(".xforms-required-icon").replaceWith('');
        $(".xforms-alert-icon").replaceWith('');
        // Tweak the display of the new icons
        $(".icon-large").css("display", "inline");
        // Activate the tooltip function on links
        $("a").popover();

        // Add placeholder text to the form
        $("#main-title input").attr("placeholder", "e.g., Frankenstein Notebook A");
        $("#creation-date input").attr("placeholder", "e.g., 1815");
        $("#item-label textarea").attr("placeholder", "Fragment of manuscript of Frankenstein (1818) (Draft Notebook A) containing parts of chapters 3-14 (plus further chapters unidentified)");
        $("#lib-collection input").attr("placeholder", "The Abinger Papers, 1780-1937");
        $("#lib-idno input").attr("placeholder", "MS. Abinger c. 56 ");
        $("#physical-extent input").attr("placeholder", "163 leaves");
        $("#physical-support textarea").attr("placeholder", "Paper with watermark: anchor in a circle with star on top, countermark B-B with trefoil similar to Moschin, Anchor N 1680, 1570-1585.");
        $("#foliation-orig textarea").attr("placeholder", "Folio numbers were added in brown ink ca. 1720-1730 in the upper right corner of all recto-pages.");
        $('#physical-condition textarea').attr("placeholder", "The manuscript shows signs of damage from water and mould on its outermost leaves.");
        $("#manu-hands textarea").attr("placeholder", "The manuscript is written in two contemporary hands. Hand I writes ff. 1r-22v and hand II ff. 23 and 24.");
        $("#metadata-creator input").attr("placeholder", "Liz Denlinger");
        $("#source textarea").attr("placeholder", "Oxford, Bodleian Library, Finding aid for MS. Abinger c. 56");
        $("#surrogate1 textarea").attr("placeholder", "Shelley, Mary W, and Charles E. Robinson. The Frankenstein Notebooks. New York: Garland Pub, 1996. Print.");
        $("#who input").attr("placeholder", "Charles Carter");
        $("#revision textarea").attr("placeholder", "Added more detailed information about hands");

        // Hide elements that will be used later for AJAX functionality
        $('#itemSelector').hide();
        $('#imageTable').hide();
        $('#ajax-loader').hide();

        $(".fancybox").fancybox();
        setImageEventListener();
    }
);

$(window).load(function() {
// If not a blank form (loading existing data), disable the repository selector
        if(location.pathname.search(/edit/) !== -1) {
            $('#select-repo select').attr('disabled', 'disabled');
        }
});<|endoftext|>


<commit_before>function getSizeAndPos(winKey) {
  // Convert percentages to pixel values
  const properties = {};
  ['width', 'height', 'left', 'top'].forEach(pKey => {
    const value = localStorage[`ttw_${winKey}-${pKey}`];
    const screenDimension = pKey === 'width' || pKey === 'left'
      ? screen.availWidth
      : screen.availHeight;
    properties[pKey] = Math.round(value * screenDimension);
  });

  return properties;
}

function getOriginId(id) {
  return `ttw_pop_origin_${id}`;
}

function isFullscreen(orig) {
  return localStorage.ttw_copy_fullscreen === 'true' && orig.state === 'fullscreen';
}

function getCloneVals(orig) {
  const pos = localStorage.ttw_clone_position;
  const vals = { fullscreen: isFullscreen(orig) };
  // this covers the case of clone-position-same
  ['width', 'height', 'left', 'top'].forEach(k => vals[k] = orig[k]);

  if (pos === 'clone-position-horizontal') {
    const right = orig.left + orig.width;
    const hgap = screen.availWidth - right;
    const positionOnRight = orig.left < hgap;

    vals.width = Math.min(orig.width, positionOnRight ? hgap : orig.left);
    vals.left = positionOnRight ? right : orig.left - Math.min(orig.width, orig.left);
  }
  else if (pos === 'clone-position-vertical') {
    const bottom = orig.top + orig.height;
    const vgap = screen.availHeight - bottom;
    const positionBelow = orig.top < vgap;

    vals.top = positionBelow ? bottom : orig.top - Math.min(orig.height, orig.top);
    vals.height = Math.min(orig.height, positionBelow ? vgap : orig.top);
  }

  return vals;
}

function getNewVals(orig) {
  const vals = getSizeAndPos('new');
  vals.fullscreen = isFullscreen(orig);
  return vals;
}

function moveTabOut(windowType) {
  chrome.windows.getCurrent({},  currentWindow => {
    const resizeOriginal = localStorage.ttw_resize_original === 'true';
    const copyFullscreen = localStorage.ttw_copy_fullscreen === 'true';
    const originalIsFullscreen = currentWindow.state === 'fullscreen';

    // resize original window
    if (resizeOriginal && !(copyFullscreen && originalIsFullscreen)) {
      const vals = getSizeAndPos('original');
      chrome.windows.update(currentWindow.id, {
        width: vals.width,
        height: vals.height,
        left: vals.left,
        top: vals.top
      });
    }

    // move out new window
    chrome.tabs.query({
      currentWindow: true,
      active: true
    }, tabs => {
      const tab = tabs[0];

      // If we are cloning the origin window, use the origin window values
      const vals = localStorage.ttw_clone_original === 'true'
        ? getCloneVals(currentWindow)
        : getNewVals(currentWindow);

      const createData = {
        tabId: tab.id,
        type: windowType,
        focused: localStorage.ttw_focus === 'new',
        incognito: tab.incognito
      };

      if (vals.fullscreen) {
        createData.state = vals.fullscreen ? 'fullscreen' : 'normal';
      }
      else {
        ['width', 'height', 'left', 'top'].forEach(key => createData[key] = vals[key]);
      }

      // Move it to a new window
      chrome.windows.create(createData, newWindow => {
        // save parent id in case we want to pop_in
        sessionStorage[getOriginId(tab.id)] = currentWindow.id;

        if (localStorage.ttw_focus === "original") {
          chrome.windows.update(currentWindow.id, { focused: true });
        }
      });
    });

  });
}

function tabToWindow(windowType) {
  // Check there are more than 1 tabs in current window
  chrome.tabs.query({
    currentWindow: true
  }, tabs => {
    if (tabs.length <= 1) { return; }
    moveTabOut(windowType);
  });
}

function windowToTab() {
  chrome.tabs.query({
    currentWindow: true,
    active:      true
  }, tabs => {
    const tab = tabs[0];

    const popped_key = getOriginId(tab.id);
    if (!sessionStorage.hasOwnProperty(popped_key)) { return; }

    const origin_window_id = parseInt(sessionStorage[popped_key]);

    // check original window still exists
    chrome.windows.get(origin_window_id, {}, originWindow => {
      if (chrome.runtime.lastError) { return; }

      // move the current tab
      chrome.tabs.move(tab.id, {
        windowId: origin_window_id,
        index:    -1
      }, () => {
        sessionStorage.removeItem(popped_key);
        chrome.tabs.update(tab.id, {
          active: true
        });
      });
    });
  });
}

chrome.commands.onCommand.addListener(command => {
  const lookup = {
    'tab-to-window-normal': () => tabToWindow('normal'),
    'tab-to-window-popup':  () => tabToWindow('popup'),
    'window-to-tab':        windowToTab
  };

  if (lookup.hasOwnProperty(command)) {
    lookup[command]();
  }
});
<commit_msg>breaking fullscreen<commit_after>function getSizeAndPos(winKey) {
  // Convert percentages to pixel values
  const properties = {};
  ['width', 'height', 'left', 'top'].forEach(pKey => {
    const value = localStorage[`ttw_${winKey}-${pKey}`];
    const screenDimension = pKey === 'width' || pKey === 'left'
      ? screen.availWidth
      : screen.availHeight;
    properties[pKey] = Math.round(value * screenDimension);
  });

  return properties;
}

function getOriginId(id) {
  return `ttw_pop_origin_${id}`;
}

function moveTabOut(windowType) {
  chrome.windows.getCurrent({},  curWin => {
    const resizeOriginal = localStorage.ttw_resize_original === 'true';
    const copyFullscreen = localStorage.ttw_copy_fullscreen === 'true';
    const originalIsFullscreen = curWin.state === 'fullscreen';

    // resize original window
    if (resizeOriginal && !(copyFullscreen && originalIsFullscreen)) {
      const vals = getSizeAndPos('original');
      chrome.windows.update(curWin.id, {
        width: vals.width,
        height: vals.height,
        left: vals.left,
        top: vals.top
      });
    }

    // create new window
    chrome.tabs.query({
      currentWindow: true,
      active: true
    }, tabs => {
      const tab = tabs[0];
      const fullscreen = localStorage.ttw_copy_fullscreen === 'true' &&
                         curWin.state === 'fullscreen';
      const createData = {
        tabId: tab.id,
        type: windowType,
        focused: localStorage.ttw_focus === 'new',
        focused: true,
        incognito: tab.incognito
      };

      createData.state = fullscreen ? 'fullscreen' : 'normal';
      if (!fullscreen) {
        // cloning
        if (localStorage.ttw_clone_original === 'true' && !fullscreen) {
          // copying all values covers the case of clone-position-same
          ['width', 'height', 'left', 'top'].forEach(k => createData[k] = curWin[k]);

          const pos = localStorage.ttw_clone_position;
          if (pos === 'clone-position-horizontal') {
            const right = curWin.left + curWin.width;
            const hgap = screen.availWidth - right;
            const positionOnRight = curWin.left < hgap;

            createData.width = Math.min(curWin.width, positionOnRight ? hgap : curWin.left);
            createData.left = positionOnRight
              ? right
              : curWin.left - Math.min(curWin.width, curWin.left);
          }
          else if (pos === 'clone-position-vertical') {
            const bottom = curWin.top + curWin.height;
            const vgap = screen.availHeight - bottom;
            const positionBelow = curWin.top < vgap;

            createData.top = positionBelow
              ? bottom
              : curWin.top - Math.min(curWin.height, curWin.top);
            createData.height = Math.min(curWin.height, positionBelow ? vgap : curWin.top);
          }
        }
        else {
          const vals = getSizeAndPos('new');
          Object.keys(vals).forEach(k => createData[k] = vals[k]);
        }
      }

      console.log("createData:", createData);
      // Move it to a new window
      chrome.windows.create(createData, newWindow => {
        // save parent id in case we want to pop_in
        sessionStorage[getOriginId(tab.id)] = curWin.id;

        // focus on original if needed
        if (localStorage.ttw_focus === "original") {
          chrome.windows.update(curWin.id, { focused: true });
        }
      });
    });

  });
}

function tabToWindow(windowType) {
  // Check there are more than 1 tabs in current window
  chrome.tabs.query({
    currentWindow: true
  }, tabs => {
    if (tabs.length <= 1) { return; }
    moveTabOut(windowType);
  });
}

function windowToTab() {
  chrome.tabs.query({
    currentWindow: true,
    active:      true
  }, tabs => {
    const tab = tabs[0];

    const popped_key = getOriginId(tab.id);
    if (!sessionStorage.hasOwnProperty(popped_key)) { return; }

    const origin_window_id = parseInt(sessionStorage[popped_key]);

    // check original window still exists
    chrome.windows.get(origin_window_id, {}, originWindow => {
      if (chrome.runtime.lastError) { return; }

      // move the current tab
      chrome.tabs.move(tab.id, {
        windowId: origin_window_id,
        index:    -1
      }, () => {
        sessionStorage.removeItem(popped_key);
        chrome.tabs.update(tab.id, {
          active: true
        });
      });
    });
  });
}

chrome.commands.onCommand.addListener(command => {
  const lookup = {
    'tab-to-window-normal': () => tabToWindow('normal'),
    'tab-to-window-popup':  () => tabToWindow('popup'),
    'window-to-tab':        windowToTab
  };

  if (lookup.hasOwnProperty(command)) {
    lookup[command]();
  }
});
<|endoftext|>


<commit_before>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action, set } from "@ember/object";

/**
Shows a button with an optional confirm dialog.
The component has two modes:

1. show a `<button/>` tag and handle clicks via callback:
   `<OxiButton @button={{myDef1}} @onClick={{sendData}}/>`
2. show a `<a href/>` tag and simply open the given URL:
   `<OxiButton @button={{myDef2}}/>`

@module oxi-button
@param { hash } button - Hash containing the button definition.
    Mode 1:
    ```json
        {
            label: "Move",
            className: "green",
            tooltip: "This should move it"
            disabled: false,
            confirm: {
                label: "Really sure?",
                description: "Think about it one more time."
            },
        }
    ```
    Mode 2:
    ```json
        {
            label: "Learn",
            className: "blue",
            tooltip: "Just fyi"
            href: "https://www.openxpki.org",
            target: "_blank",
        }
    ```

*/
export default class OxiButtonComponent extends Component {
    tagName = "span";

    @tracked showConfirmDialog = false;

    @action
    click() {
        if (this.args.button.confirm) {
            set(this.args.button, "loading", true);
            this.showConfirmDialog = true;
        } else {
            this.executeAction();
        }
    }

    @action
    executeAction() {
        this.resetConfirmState();
        this.args.onClick(this.args.button);
    }

    @action
    resetConfirmState() {
        set(this.args.button, "loading", false);
        this.showConfirmDialog = false;
    }
}
<commit_msg>JS: update jsdoc in oxi-button<commit_after>import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action, set } from "@ember/object";

/**
Shows a button with an optional confirm dialog.

The component has two modes:

1. show a `<a href/>` tag and simply open the given URL:
   ```html
   <OxiButton @button={{myDef2}} class="btn btn-default"/>
   ```
2. show a `<button/>` tag and handle clicks via callback:
   ```html
   <OxiButton @button={{myDef1}} @onClick={{sendData}} class="btn btn-default"/>
   ```

@module oxi-button
@param { hash } button - Hash containing the button definition.
Mode 1 `<a href>`:
```javascript
{
    className: "btn-info",
    label: "Learn",                     // mandatory
    tooltip: "Just fyi",
    href: "https://www.openxpki.org",   // mandatory
    target: "_blank",
}
```
Mode 2 `<button>`:
```javascript
{
    className: "btn-info",
    label: "Move",                      // mandatory
    tooltip: "This should move it",
    disabled: false,
    confirm: {
        label: "Really sure?",          // mandatory if "confirm" exists
        description: "Think!",          // mandatory if "confirm" exists
        confirm_label: ""
        cancel_label: ""
    },
}
```
@param { callback } onClick - Action handler to be called.
The `button` hash will be passed on to the handler as single parameter.
*/
export default class OxiButtonComponent extends Component {
    tagName = "span";

    @tracked showConfirmDialog = false;

    @action
    click() {
        if (this.args.button.confirm) {
            set(this.args.button, "loading", true);
            this.showConfirmDialog = true;
        } else {
            this.executeAction();
        }
    }

    @action
    executeAction() {
        this.resetConfirmState();
        this.args.onClick(this.args.button);
    }

    @action
    resetConfirmState() {
        set(this.args.button, "loading", false);
        this.showConfirmDialog = false;
    }
}
<|endoftext|>


<commit_before>//This file is intended to be used only on forms pages with forms

// this action works for the create forms in Action, Deployment and Calibration pages.
// It hides fields from the action forms depending on the type of action being created.
function setOtherActions() {
    var mainForm = $('form');
    var actionTypeElem;

    if (mainForm.hasClass('Generic')) {
        $('.Generic .calibration').not('option').parents('tr').hide();
        $('.Generic .maintenance').not('option').parents('tr').hide();
        actionTypeElem = $('.Generic [name="actiontypecv"]');
        actionTypeElem.children('[value="Equipment deployment"]').remove();
        actionTypeElem.children('[value="Instrument calibration"]').remove();

    } else if (mainForm.hasClass('InstrumentCalibration')) {
        /* Careful when deleting parents of calibration etc tr */
        $('.InstrumentCalibration .maintenance').not('option').parents('tr').remove();
        actionTypeElem = $('.InstrumentCalibration [name="actiontypecv"]');
        actionTypeElem.select2('val', 'Instrument calibration');
        actionTypeElem.parents('tr').hide();

    } else if (mainForm.hasClass('EquipmentDeployment')) {
        $('.EquipmentDeployment .calibration').not('option').parents('tr').hide();
        $('.EquipmentDeployment .maintenance').not('option').parents('tr').hide();
        actionTypeElem = $('.EquipmentDeployment [name="actiontypecv"]');
        actionTypeElem.select2('val', 'Equipment deployment');
        actionTypeElem.parents('tr').hide();
    }
}

function initDTPicker() {
    /* http://tarruda.github.io/bootstrap-datetimepicker/ */
    var dateElements = [];
    // Push elements to get calendar widget
    dateElements.push($('#id_equipmentpurchasedate'));
    dateElements.push($("[name='begindatetime']"));
    dateElements.push($("[name='enddatetime']"));
    dateElements.push($("[name='referencematerialpurchasedate']"));
    dateElements.push($("[name='referencematerialexpirationdate']"));

    dateElements.forEach(function (element) {
        element.wrap("
</div");
        element.after(
            $("")
        );

    });

    var currentDateTimePicker = $('.datetimepicker');
    currentDateTimePicker.datetimepicker({
        format: 'YYYY-MM-DD HH:mm',
        sideBySide: true
    });
}

function setDateTimePicker() {
    initDTPicker();

    //When begindatetime changes, set maxDate on enddatetime
    var tBodies = $('tbody');
    tBodies.each(function () {
        beginDateTimeChanged(this, true);
    });

}

function setDTPickerClose(beginDTElem) {
    //Function to set up begindatetime fields to close automatically when date is picked and open next enddatetime field.
    beginDTElem.parent('.datetimepicker').on('dp.hide', function () {
        var beginDTObj = $(this).data('DateTimePicker');
        if (beginDTObj.collapse) {
            beginDTObj.hide();
            var endDTObj = $(this).parents('tbody').find('[name="enddatetime"]').parents('.datetimepicker').data('DateTimePicker');
            endDTObj.show();
            endDTObj.date(beginDTObj.date())
        }
    })
}

function setFormFields(currentForm) {
    currentForm.find('input').addClass('form-control');
    currentForm.find("[type='checkbox']").removeClass('form-control');
    currentForm.find('textarea').addClass('form-control');
    currentForm.find('select').addClass('select-two');

    currentForm.find(".select-two").select2();
    currentForm.find('.select2-container').css('width', '100%');
}

function handleActionTypeChange(formType, currentForm) {
    var formClasses = {
        'Field activity': 'notypeclass',
        'Equipment deployment': 'deployment',
        'Instrument calibration': 'calibration',
        'Equipment maintenance': 'maintenance'
    };

    var formClass = formClasses[formType] || 'notypeclass';

    for (var key in formClasses) {
        if (formClasses.hasOwnProperty(key) && key !== formType) {
            $(currentForm).find('.' + formClasses[key]).not('option').parents('tr').hide();
            $(currentForm).find('option.' + formClasses[key]).attr('disabled', 'disabled');
        }
    }

    $(currentForm).find('.' + formClass).not('option').parents('tr:hidden').show();
    $(currentForm).find('option.' + formClass).removeAttr('disabled');

    //reset select2 to hide disabled options
    var methodSelect = $(currentForm).find('[name="methodid"]');
    methodSelect.select2();
    $('.select2-container').css('width', '100%');

    var equipmentUsedElem = $(currentForm).find('[name="equipmentused"]');

    //Set EquipmentUsed required
    if (formType !== 'Generic')
        equipmentUsedElem.parents('tr').addClass('form-required');
    else
        equipmentUsedElem.parents('tr').removeClass('form-required');

    //Filter equipmentUsed
    filterEquipmentBySite($('form').find('.select-two[name="samplingfeatureid"]').val(), equipmentUsedElem);

    if (formType == 'Instrument deployment') {
        var addResultButton = $("

	+ Add Result

");
        addResultButton.insertAfter(currentForm);
        addResultForm(addResultButton, true);
    } else {
        $(currentForm).nextUntil('tbody.add-result-btn', '.results-set').remove();
        $(currentForm).next('tbody.add-result-btn').remove();
    }
}

function addResultForm(that, firstResult) {
    var removeButton = $('
	- Remove Result
');
    var fields = $('#results-form').children().clone();

    if (firstResult) {
        var resultsRow = $('
Results
');
        var btnForm = $(that);
        fields.prepend(resultsRow);

    } else {
        var btnForm = $(that).parents('tbody.add-result-btn');
        fields.prepend(removeButton);
    }

    fields.find(".select-two").select2();
    fields.insertBefore(btnForm);
}

function removeResultForm(that) {
    $(that).parents('tbody').remove();
}

function filterEquipmentBySite(selected, equipmentUsedSelectElems) {
    if (selected == "")
        return;

    var equipmentBySiteUrl = $('#equipment-by-site-api').val();

    $.ajax({
        url: equipmentBySiteUrl, /*needs to be changed depending on application name. ie in development it's ODM2Sensor, in sandbox it's equipment*/
        type: "POST",
        data: {
            site_selected: selected,
            csrfmiddlewaretoken: $('form').find('[name="csrfmiddlewaretoken"]').val()
        },

        success: function (json) {
            handle_equ_used_filter_response(json, equipmentUsedSelectElems)
        },

        error: function (xhr, errmsg, err) {
            console.log(errmsg);
            console.log(xhr.status + ": " + xhr.responseText)
        }
    });
}

function filterEquipmentByAction(selected, equipmentUsedSelectElems) {
    if(selected == "") {
        return;
    }

    var equipmentByActionUrl = $('#equipment-by-action-api').val();

    $.ajax({
        url: equipmentByActionUrl,
        type: "POST",
        data :{
            action_id: selected,
            csrfmiddlewaretoken: $('form').find('[name="csrfmiddlewaretoken"]').val()
        },

        success: function (json) {
            handle_equ_used_filter_response(json, equipmentUsedSelectElems)
        },

        error: function (xhr, errmsg, err) {
            console.log(errmsg);
            console.log(xhr.status+": "+xhr.responseText)
        }
    });
}

function showAllEquipment(equipmentUsedSelectElems) {
    equipmentUsedSelectElems.empty();
    equipmentUsedSelectElems.append($('#all-equipment-select').children().clone());
}

// get site visit dates from get_site_visit_dates, and restrict begindate and enddate
function filterActionDatesByVisit(siteVisitId) {
    if (siteVisitId == '') {
        return;
    }

    var apiUrl = $('#site-visit-dates').val();
    var form = $('form');
    var token = form.find('[name="csrfmiddlewaretoken"]').val();
    $.ajax({
        url: apiUrl,
        type: 'POST',
        data: { site_visit: siteVisitId, csrfmiddlewaretoken: token },
        success: function(data) {

            // get datetimepicker stuff and restrict by the dates received.
            var minDatetime = moment(data.begin_date);
            var maxDatetime = moment(data.end_date);

            var beginDateTimeObj = form.find('[name="begindatetime"]').parents('.datetimepicker').data('DateTimePicker');
            var endDateTimeObj = form.find('[name="enddatetime"]').parents('.datetimepicker').data('DateTimePicker');

            beginDateTimeObj.maxDate(false);
            beginDateTimeObj.minDate(false);
            endDateTimeObj.maxDate(false);
            endDateTimeObj.minDate(false);

            beginDateTimeObj.maxDate(maxDatetime);
            beginDateTimeObj.minDate(minDatetime);
            endDateTimeObj.maxDate(maxDatetime);
            endDateTimeObj.minDate(minDatetime);

            beginDateTimeObj.date(minDatetime);
            endDateTimeObj.date(maxDatetime);

            beginDateTimeObj.date(minDatetime);
            endDateTimeObj.date(maxDatetime);
        },
        error: function(xhr, errmsg) {
            console.log(errmsg);
            console.log(xhr.status+": "+xhr.responseText)
        }
    });
}

function handle_equ_used_filter_response(json, equipmentUsedSelectElems) {
    var currentValue;
    json = JSON.parse(json);
    equipmentUsedSelectElems.each(function () {
        currentValue = $(this).parents('tbody').find('[name="actiontypecv"]').val();
        var currentEquipmentSelect = $(this);
        if (currentValue !== "Equipment deployment") {
            var options = [];
            currentEquipmentSelect.empty();
            json.forEach(function(object) {
                var equipment = object.fields;
                var equipmentElement = ['<option value=', object.pk, '>',
                    equipment.equipmentcode, ': ', equipment.equipmentserialnumber,
                    ' (', equipment.equipmenttypecv, ', ', equipment.equipmentmodelid, ')',
                    '</option>'
                ];
                options.push(equipmentElement.join(''));
            });
            currentEquipmentSelect.append(options.join(''));
        } else {
            var defaultElements = $('#action-form').find('[name="equipmentused"]').children();
            if (defaultElements.length > 0) {
                currentEquipmentSelect.empty();
                currentEquipmentSelect.append($(defaultElements).clone());
            }
        }

        // Clear value of equipment selected. An equipment can't be deployed at two locations.
        //$(currentEquipmentSelect).select2("val", "");
    });
}

function onEquipmentModelChange(event) {
    var modelForm = $('#model-form');
    var modelFields = $('tbody.model-fields');
    var modelSelect = $('#id_equipmentmodelid');

    if (modelSelect.find(':selected').val() == 'new') {
        cleanFields(modelFields);
        modelFields.insertAfter(modelSelect.parents('tbody'));
    } else {
        modelForm.append(modelFields);
    }
}

function cleanFields(fields) {
    fields.find('textarea, input').val('');
    fields.find('input[type="checkbox"]').prop('checked', false);
    fields.find('select').val(undefined).trigger('change');
    fields.find('select').prop('checked', false);
}

$(document).ready(function () {
    setDateTimePicker();
    setDTPickerClose($('[name="begindatetime"]'));
    setFormFields($('tbody'));
    setOtherActions();

    var currentForm = $('form');
    var allForms = $('tbody').has('[name="actiontypecv"]');
    var filterEquipmentCheck = $('#id_equipment_by_site');
    var siteVisitSelect = currentForm.find('[name="actionid"]');

    var equipmentSelect = $('#all-equipment-select');
    equipmentSelect.append($('#id_equipmentused').children().clone());

    if (currentForm.attr('action').indexOf('create-equipment')) { // if current form is the create new equipment form
        var modelSelect = $('#id_equipmentmodelid');
        $('<option value="new">New Equipment Model</option>').insertAfter(modelSelect.children().first());
        modelSelect.on('change', onEquipmentModelChange);
    }

    allForms.each(function (index) {
        var actionType = $(this).find('.select-two[name="actiontypecv"]');
        handleActionTypeChange(actionType.val(), this);
        actionType.change(function () {
            var selected = $(this).val();
            var currentActionForm = $(this).parents('tbody');
            handleActionTypeChange(selected, currentActionForm);
        });
    });

    siteVisitSelect.change(function (eventData, handler) {
        var formActionType = currentForm.find('[name="actiontypecv"]').val();

        if (formActionType != "Equipment deployment" && formActionType != "Instrument deployment" && !filterEquipmentCheck.prop('checked')) {
            filterEquipmentByAction($(this).val(), currentForm.find('[name="equipmentused"]'));
        } else {
            showAllEquipment(currentForm.find('[name="equipmentused"]'));
        }

        if (currentForm.hasClass('EquipmentDeployment') || currentForm.hasClass('InstrumentCalibration') || currentForm.hasClass('Generic')) {
            var siteVisit = eventData.target.options[eventData.target.selectedIndex].value;
            filterActionDatesByVisit(siteVisit);
        }
    });

    filterEquipmentCheck.change(function(eventData) {
        siteVisitSelect.trigger('change');
    });

    $('#results-form').find('.select-two').select2('destroy');
    $('#results-form').find(".select2-container").remove();

});

<commit_msg>#146 Made all equipment show for the equipment used field when the action type is Instrument Deployment<commit_after>//This file is intended to be used only on forms pages with forms

// this action works for the create forms in Action, Deployment and Calibration pages.
// It hides fields from the action forms depending on the type of action being created.
function setOtherActions() {
    var mainForm = $('form');
    var actionTypeElem;

    if (mainForm.hasClass('Generic')) {
        $('.Generic .calibration').not('option').parents('tr').hide();
        $('.Generic .maintenance').not('option').parents('tr').hide();
        actionTypeElem = $('.Generic [name="actiontypecv"]');
        actionTypeElem.children('[value="Equipment deployment"]').remove();
        actionTypeElem.children('[value="Instrument deployment"]').remove();
        actionTypeElem.children('[value="Instrument calibration"]').remove();

    } else if (mainForm.hasClass('InstrumentCalibration')) {
        /* Careful when deleting parents of calibration etc tr */
        $('.InstrumentCalibration .maintenance').not('option').parents('tr').remove();
        actionTypeElem = $('.InstrumentCalibration [name="actiontypecv"]');
        actionTypeElem.select2('val', 'Instrument calibration');
        actionTypeElem.parents('tr').hide();

    } else if (mainForm.hasClass('EquipmentDeployment')) {
        $('.EquipmentDeployment .calibration').not('option').parents('tr').hide();
        $('.EquipmentDeployment .maintenance').not('option').parents('tr').hide();
        actionTypeElem = $('.EquipmentDeployment [name="actiontypecv"]');
        // TODO: ASK AMBER IS IT EQUIPMENT OR INSTRUMENT DEPLOYMENT?
        actionTypeElem.select2('val', 'Instrument deployment');
        actionTypeElem.parents('tr').hide();
    }
}

function initDTPicker() {
    /* http://tarruda.github.io/bootstrap-datetimepicker/ */
    var dateElements = [];
    // Push elements to get calendar widget
    dateElements.push($('#id_equipmentpurchasedate'));
    dateElements.push($("[name='begindatetime']"));
    dateElements.push($("[name='enddatetime']"));
    dateElements.push($("[name='referencematerialpurchasedate']"));
    dateElements.push($("[name='referencematerialexpirationdate']"));

    dateElements.forEach(function (element) {
        element.wrap("
</div");
        element.after(
            $("")
        );

    });

    var currentDateTimePicker = $('.datetimepicker');
    currentDateTimePicker.datetimepicker({
        format: 'YYYY-MM-DD HH:mm',
        sideBySide: true
    });
}

function setDateTimePicker() {
    initDTPicker();

    //When begindatetime changes, set maxDate on enddatetime
    var tBodies = $('tbody');
    tBodies.each(function () {
        beginDateTimeChanged(this, true);
    });

}

function setDTPickerClose(beginDTElem) {
    //Function to set up begindatetime fields to close automatically when date is picked and open next enddatetime field.
    beginDTElem.parent('.datetimepicker').on('dp.hide', function () {
        var beginDTObj = $(this).data('DateTimePicker');
        if (beginDTObj.collapse) {
            beginDTObj.hide();
            var endDTObj = $(this).parents('tbody').find('[name="enddatetime"]').parents('.datetimepicker').data('DateTimePicker');
            endDTObj.show();
            endDTObj.date(beginDTObj.date())
        }
    })
}

function setFormFields(currentForm) {
    currentForm.find('input').addClass('form-control');
    currentForm.find("[type='checkbox']").removeClass('form-control');
    currentForm.find('textarea').addClass('form-control');
    currentForm.find('select').addClass('select-two');

    currentForm.find(".select-two").select2();
    currentForm.find('.select2-container').css('width', '100%');
}

function handleActionTypeChange(formType, currentForm) {
    var formClasses = {
        'Field activity': 'notypeclass',
        'Equipment deployment': 'deployment',
        'Instrument calibration': 'calibration',
        'Equipment maintenance': 'maintenance'
    };

    var formClass = formClasses[formType] || 'notypeclass';

    for (var key in formClasses) {
        if (formClasses.hasOwnProperty(key) && key !== formType) {
            $(currentForm).find('.' + formClasses[key]).not('option').parents('tr').hide();
            $(currentForm).find('option.' + formClasses[key]).attr('disabled', 'disabled');
        }
    }

    $(currentForm).find('.' + formClass).not('option').parents('tr:hidden').show();
    $(currentForm).find('option.' + formClass).removeAttr('disabled');

    //reset select2 to hide disabled options
    var methodSelect = $(currentForm).find('[name="methodid"]');
    methodSelect.select2();
    $('.select2-container').css('width', '100%');

    var equipmentUsedElem = $(currentForm).find('[name="equipmentused"]');

    //Set EquipmentUsed required
    if (formType !== 'Generic')
        equipmentUsedElem.parents('tr').addClass('form-required');
    else
        equipmentUsedElem.parents('tr').removeClass('form-required');

    //Filter equipmentUsed
    filterEquipmentBySite($('form').find('.select-two[name="samplingfeatureid"]').val(), equipmentUsedElem);

    if (formType == 'Instrument deployment') {
        var addResultButton = $("

	+ Add Result

");
        addResultButton.insertAfter(currentForm);
        addResultForm(addResultButton, true);
    } else {
        $(currentForm).nextUntil('tbody.add-result-btn', '.results-set').remove();
        $(currentForm).next('tbody.add-result-btn').remove();
    }
}

function addResultForm(that, firstResult) {
    var removeButton = $('
	- Remove Result
');
    var fields = $('#results-form').children().clone();

    if (firstResult) {
        var resultsRow = $('
Results
');
        var btnForm = $(that);
        fields.prepend(resultsRow);

    } else {
        var btnForm = $(that).parents('tbody.add-result-btn');
        fields.prepend(removeButton);
    }

    fields.find(".select-two").select2();
    fields.insertBefore(btnForm);
}

function removeResultForm(that) {
    $(that).parents('tbody').remove();
}

function filterEquipmentBySite(selected, equipmentUsedSelectElems) {
    if (selected == "")
        return;

    var equipmentBySiteUrl = $('#equipment-by-site-api').val();

    $.ajax({
        url: equipmentBySiteUrl, /*needs to be changed depending on application name. ie in development it's ODM2Sensor, in sandbox it's equipment*/
        type: "POST",
        data: {
            site_selected: selected,
            csrfmiddlewaretoken: $('form').find('[name="csrfmiddlewaretoken"]').val()
        },

        success: function (json) {
            handle_equ_used_filter_response(json, equipmentUsedSelectElems)
        },

        error: function (xhr, errmsg, err) {
            console.log(errmsg);
            console.log(xhr.status + ": " + xhr.responseText)
        }
    });
}

function filterEquipmentByAction(selected, equipmentUsedSelectElems) {
    if(selected == "") {
        return;
    }

    var equipmentByActionUrl = $('#equipment-by-action-api').val();

    $.ajax({
        url: equipmentByActionUrl,
        type: "POST",
        data :{
            action_id: selected,
            csrfmiddlewaretoken: $('form').find('[name="csrfmiddlewaretoken"]').val()
        },

        success: function (json) {
            handle_equ_used_filter_response(json, equipmentUsedSelectElems)
        },

        error: function (xhr, errmsg, err) {
            console.log(errmsg);
            console.log(xhr.status+": "+xhr.responseText)
        }
    });
}

function showAllEquipment(equipmentUsedSelectElems) {
    equipmentUsedSelectElems.empty();
    equipmentUsedSelectElems.append($('#all-equipment-select').children().clone());
}

// get site visit dates from get_site_visit_dates, and restrict begindate and enddate
function filterActionDatesByVisit(siteVisitId) {
    if (siteVisitId == '') {
        return;
    }

    var apiUrl = $('#site-visit-dates').val();
    var form = $('form');
    var token = form.find('[name="csrfmiddlewaretoken"]').val();
    $.ajax({
        url: apiUrl,
        type: 'POST',
        data: { site_visit: siteVisitId, csrfmiddlewaretoken: token },
        success: function(data) {

            // get datetimepicker stuff and restrict by the dates received.
            var minDatetime = moment(data.begin_date);
            var maxDatetime = moment(data.end_date);

            var beginDateTimeObj = form.find('[name="begindatetime"]').parents('.datetimepicker').data('DateTimePicker');
            var endDateTimeObj = form.find('[name="enddatetime"]').parents('.datetimepicker').data('DateTimePicker');

            beginDateTimeObj.maxDate(false);
            beginDateTimeObj.minDate(false);
            endDateTimeObj.maxDate(false);
            endDateTimeObj.minDate(false);

            beginDateTimeObj.maxDate(maxDatetime);
            beginDateTimeObj.minDate(minDatetime);
            endDateTimeObj.maxDate(maxDatetime);
            endDateTimeObj.minDate(minDatetime);

            beginDateTimeObj.date(minDatetime);
            endDateTimeObj.date(maxDatetime);

            beginDateTimeObj.date(minDatetime);
            endDateTimeObj.date(maxDatetime);
        },
        error: function(xhr, errmsg) {
            console.log(errmsg);
            console.log(xhr.status+": "+xhr.responseText)
        }
    });
}

function handle_equ_used_filter_response(json, equipmentUsedSelectElems) {
    var currentValue;
    json = JSON.parse(json);
    equipmentUsedSelectElems.each(function () {
        currentValue = $(this).parents('tbody').find('[name="actiontypecv"]').val();
        var currentEquipmentSelect = $(this);
        if (currentValue !== "Equipment deployment" && currentValue !== "Instrument deployment") {
            var options = [];
            currentEquipmentSelect.empty();
            json.forEach(function(object) {
                var equipment = object.fields;
                var equipmentElement = ['<option value=', object.pk, '>',
                    equipment.equipmentcode, ': ', equipment.equipmentserialnumber,
                    ' (', equipment.equipmenttypecv, ', ', equipment.equipmentmodelid, ')',
                    '</option>'
                ];
                options.push(equipmentElement.join(''));
            });
            currentEquipmentSelect.append(options.join(''));
        } else {
            var defaultElements = $('#action-form').find('[name="equipmentused"]').children();
            if (defaultElements.length > 0) {
                currentEquipmentSelect.empty();
                currentEquipmentSelect.append($(defaultElements).clone());
            }
        }

        // Clear value of equipment selected. An equipment can't be deployed at two locations.
        //$(currentEquipmentSelect).select2("val", "");
    });
}

function onEquipmentModelChange(event) {
    var modelForm = $('#model-form');
    var modelFields = $('tbody.model-fields');
    var modelSelect = $('#id_equipmentmodelid');

    if (modelSelect.find(':selected').val() == 'new') {
        cleanFields(modelFields);
        modelFields.insertAfter(modelSelect.parents('tbody'));
    } else {
        modelForm.append(modelFields);
    }
}

function cleanFields(fields) {
    fields.find('textarea, input').val('');
    fields.find('input[type="checkbox"]').prop('checked', false);
    fields.find('select').val(undefined).trigger('change');
    fields.find('select').prop('checked', false);
}

$(document).ready(function () {
    setDateTimePicker();
    setDTPickerClose($('[name="begindatetime"]'));
    setFormFields($('tbody'));
    setOtherActions();

    var currentForm = $('form');
    var allForms = $('tbody').has('[name="actiontypecv"]');
    var filterEquipmentCheck = $('#id_equipment_by_site');
    var siteVisitSelect = currentForm.find('[name="actionid"]');

    var equipmentSelect = $('#all-equipment-select');
    equipmentSelect.append($('#id_equipmentused').children().clone());

    if (currentForm.attr('action').indexOf('create-equipment')) { // if current form is the create new equipment form
        var modelSelect = $('#id_equipmentmodelid');
        $('<option value="new">New Equipment Model</option>').insertAfter(modelSelect.children().first());
        modelSelect.on('change', onEquipmentModelChange);
    }

    allForms.each(function (index) {
        var actionType = $(this).find('.select-two[name="actiontypecv"]');
        handleActionTypeChange(actionType.val(), this);
        actionType.change(function () {
            var selected = $(this).val();
            var currentActionForm = $(this).parents('tbody');
            handleActionTypeChange(selected, currentActionForm);
        });
    });

    siteVisitSelect.change(function (eventData, handler) {
        var formActionType = currentForm.find('[name="actiontypecv"]').val();

        if (formActionType != "Equipment deployment" && formActionType != "Instrument deployment" && !filterEquipmentCheck.prop('checked')) {
            filterEquipmentByAction($(this).val(), currentForm.find('[name="equipmentused"]'));
        } else {
            showAllEquipment(currentForm.find('[name="equipmentused"]'));
        }

        if (currentForm.hasClass('EquipmentDeployment') || currentForm.hasClass('InstrumentCalibration') || currentForm.hasClass('Generic')) {
            var siteVisit = eventData.target.options[eventData.target.selectedIndex].value;
            filterActionDatesByVisit(siteVisit);
        }
    });

    filterEquipmentCheck.change(function(eventData) {
        siteVisitSelect.trigger('change');
    });

    $('#results-form').find('.select-two').select2('destroy');
    $('#results-form').find(".select2-container").remove();

});

<|endoftext|>