<commit_before>var config = require('config');
var FeedbackModal = require('feedback-modal');
var FilterView = require('filter-view');
var HelpMeChoose = require('help-me-choose-view');
var LeafletTransitiveLayer = require('Leaflet.TransitiveLayer');
var LocationsView = require('locations-view');
var log = require('./client/log')('planner-page');
var showMapView = require('map-view');
var OptionsView = require('options-view');
var PlannerNav = require('planner-nav');
var querystring = require('querystring');
var scrollbarSize = require('scrollbar-size');
var scrolling = require('scrolling');
var session = require('session');
var textModal = require('text-modal');
//var transitive = require('transitive');
var ua = require('user-agent');
var view = require('view');
var showWelcomeWizard = require('welcome-flow');
var showPlannerWalkthrough = require('planner-walkthrough');
var geocode = require('geocode');

var FROM = config.geocode().start_address;
var TO = config.geocode().end_address;
var isMobile = window.innerWidth <= 480;
var center = config.geocode().center.split(',').map(parseFloat);

var View = view(require('./template.html'), function(view, model) {
  view.scrollable = view.find('.scrollable');
  view.panelFooter = view.find('.footer');

  if (scrollbarSize > 0) {
    if (ua.os.name === 'Windows' || ua.browser.name !== 'Chrome')
      view.scrollable.style.marginRight = -scrollbarSize + 'px';

    // Scrollbars are fun and implemented the same on every OS/Browser...right
    if (ua.os.name === 'Windows' && ua.browser.name === 'Chrome')
      view.scrollable.style.paddingRight = scrollbarSize + 'px';
  }
});

/**
 * Expose `render`
 */

module.exports = function(ctx, next) {
  log('render');

  var plan = ctx.plan;
  var query = querystring.parse(window.location.search);

  // Set up the views
  var views = {
    'filter-view': new FilterView(plan),
    'locations-view': new LocationsView(plan),
    'options-view': new OptionsView(plan),
    'planner-nav': new PlannerNav(session)
  };

  ctx.view = new View(views);
  ctx.view.on('rendered', function() {
    // Set plan to loading
    plan.loading(true);

    for (var key in views) {
      views[key].emit('rendered', views[key]);
    }

    // Show the map
    var map = showMapView(ctx.view.find('.MapView'));

    console.log("map ->", map);

    // Create the transitive layer
    //var transitiveLayer = new LeafletTransitiveLayer(transitive);

    // Set the transitive layer
    //map.addLayer(transitiveLayer);

    // Update map on plan change
    updateMapOnPlanChange(plan, map);

    //map.on('click', function (e) {
    //      var from = plan.from_ll();
    //      var to = plan.to_ll();
    //      if (!plan.coordinateIsValid(from)) {
    //        plan.journey({
    //      places: [
    //        {
    //          place_id: 'from',
    //          place_lat: e.latlng.lat,
    //          place_lon: e.latlng.lng,
    //          place_name: 'From'
    //        },
    //        {
    //          place_id: 'to',
    //          place_lat: (plan.to_ll() ? plan.to_ll().lat : 0),
    //          place_lon: (plan.to_ll() ? plan.to_ll().lng : 0),
    //          place_name: 'To'
    //        }
    //      ]
    //    });
    //    plan.setAddress('from', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
    //        plan.updateRoutes();
    //    });
    //      } else if (!plan.coordinateIsValid(to)) {
    //    plan.journey({
    //      places: [
    //        {
    //          place_id: 'from',
    //          place_lat: plan.from_ll().lat,
    //          place_lon: plan.from_ll().lng,
    //          place_name: 'From'
    //        },
    //        {
    //          place_id: 'to',
    //          place_lat: e.latlng.lat,
    //          place_lon: e.latlng.lng,
    //          place_name: 'To'
    //        }
    //      ]
    //    });
    //    plan.setAddress('to', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
    //        plan.updateRoutes();
    //    });
    //      }
    //});

    // Clear plan & cookies for now, plan will re-save automatically on save
      var from = plan.from_ll();
      var to = plan.to_ll();
      //plan.clearStore();

    // If it's a shared URL or welcome is complete skip the welcome screen
    console.log("query ->", query);
    if ((query.from && query.to)) {
      showQuery(query);
    } else {
      console.log("plan.coordinateIsValid(from)", plan.coordinateIsValid(from));
      console.log("plan.coordinateIsValid(to)", plan.coordinateIsValid(to));

      if (plan.coordinateIsValid(from) && plan.coordinateIsValid(to)) {
          plan.setAddresses(
            from.lng + ',' + from.lat, // from
            to.lng + ',' + to.lat, // to
            function (err, res) {
              plan.updateRoutes();
              console.log("aqui la data del plan 4 ->", plan.dataplan);
            }
          );
          plan.updateRoutes();
          console.log("aqui la data del plan 3 ->", plan.dataplan);
      } else {
          console.log(from);
          console.log(to);
          plan.loading(false);
      }
    }
  });

  plan.on('updating options', function() {
    ctx.view.panelFooter.classList.add('hidden');
  });

  plan.on('updating options complete', function(res) {
    if (res && !res.err) ctx.view.panelFooter.classList.remove('hidden');
  });

  next();
};

/**
 * Reverse Commute
 */

View.prototype.reverseCommute = function(e) {
  e.preventDefault();
  var plan = session.plan();
  plan.set({
    from: plan.to(),
    from_id: plan.to_id(),
    from_ll: plan.to_ll(),
    to: plan.from(),
    to_id: plan.from_id(),
    to_ll: plan.from_ll()
  });

  plan.updateRoutes();

  console.log("aqui la data del plan 5 ->", plan.dataplan);
};

/**
 * Scroll
 */

View.prototype.scroll = function(e) {
  e.preventDefault();
  this.scrollable.scrollTop += (this.scrollable.scrollHeight / 5);
};

/**
 * On submit
 */

View.prototype.onsubmit = function(e) {
  e.preventDefault();
};

/**
 * Help Me Choose
 */

View.prototype.helpMeChoose = function(e) {
  HelpMeChoose(session.plan().options()).show();
};

/**
 * Show feedback modal
 */
View.prototype.feedback = function(e) {
  e.preventDefault();
  FeedbackModal().show();
};

/**
 * Hide Side Panel
 */

View.prototype.hideSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(' + width + 'px, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding': '0'
  });

  setTimeout(function () {
    map.invalidateSize();
  }, 2100)
};

/**
 * Show Side Panel
 */

View.prototype.showSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(0, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding-right': '320px'
  });

  setTimeout(function () {
    var plan = session.plan();
    map.invalidateSize();

    plan = session.plan();
    plan.updateRoutes();
    //transitive.updateData(plan.journey());
  }, 2100)
};

/**
 * Show Journey
 */

function showQuery(query) {
  var plan = session.plan();
  // If no querystring, see if we have them in the plan already
  var from = query.from || plan.from() || FROM;
  var to = query.to || plan.to() || TO;
  var sameAddresses = from === plan.from() && to === plan.to();

  // Set plan from querystring
  if (query.modes) plan.setModes(query.modes);
  if (query.start_time !== undefined) plan.start_time(parseInt(query.start_time, 10));
  if (query.end_time !== undefined) plan.end_time(parseInt(query.end_time, 10));
  if (query.days !== undefined) plan.days(query.days);

  // If has valid coordinates, load
  if (plan.validCoordinates() && sameAddresses) {
    plan.journey({
      places: plan.generatePlaces()
    });
    plan.updateRoutes();

    console.log("aqui la data del plan 1 ->", plan.dataplan);
  } else {
      if (!plan.validCoordinates()) {
	  plan.loading(false);
	  return;
      } else {
    // Set addresses and update the routes
    plan.setAddresses(from, to, function(err) {
      if (err) {
        log.error('%e', err);
      } else {
        plan.journey({
          places: plan.generatePlaces()
        });
        plan.updateRoutes();

        console.log("aqui la data del plan 2 ->", plan.dataplan);
      }
    });
}
  }
}

/**
 * Update Map on plan change
 */

function updateMapOnPlanChange(plan, map) {
  // Register plan update events
    /*
    for (i in map._layers) {
        if (map._layers[i].options.format == undefined) {
            try {
                map.removeLayer(map._layers[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }
        }
    }
    */

    //map.removeLayer(polyline);
/*

  for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }
  */

  plan.on('change journey', function(journey) {

  var polyline_creadas = showMapView.getpolyline_creadas();
    //console.log("poliline credas ->", polyline_creadas);
    //console.log("llamamos sin evento ->", showMapView.polyline_creadas);

    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }

    showMapView.polyline_creadas = [];
    if (journey && !isMobile) {
      try {

        log('updating data');

        var datajourney = journey;
        if (!(plan.dataplan === undefined)) {
            var itineraries = plan.dataplan.itineraries;
            showMapView.marker_map([plan.dataplan.from.lat,plan.dataplan.from.lon],[plan.dataplan.to.lat,plan.dataplan.to.lon], map);
            for (i = 0; i < itineraries.length; i++) {
                for (ii=0; ii < itineraries[i].legs.length; ii++) {
                  showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                }
            }
          console.log("entre if ")
        }else{
            var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
            if(!(sesion_plan === null)) {
                var itineraries = sesion_plan.itineraries;

                showMapView.marker_map([sesion_plan.from.lat,sesion_plan.from.lon],[sesion_plan.to.lat,sesion_plan.to.lon], map);

                for (i = 0; i < itineraries.length; i++) {
                    for (ii=0; ii < itineraries[i].legs.length; ii++) {
                      showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                    }
                }
            }

        }
      } catch (e) {
        console.log("entre cath")
	    map.setView([center[1], center[0]], config.geocode().zoom);
      }

    }
  });
}
<commit_msg>adding html layer<commit_after>var config = require('config');
var FeedbackModal = require('feedback-modal');
var FilterView = require('filter-view');
var HelpMeChoose = require('help-me-choose-view');
var LeafletTransitiveLayer = require('Leaflet.TransitiveLayer');
var LocationsView = require('locations-view');
var log = require('./client/log')('planner-page');
var showMapView = require('map-view');
var OptionsView = require('options-view');
var PlannerNav = require('planner-nav');
var querystring = require('querystring');
var scrollbarSize = require('scrollbar-size');
var scrolling = require('scrolling');
var session = require('session');
var textModal = require('text-modal');
//var transitive = require('transitive');
var ua = require('user-agent');
var view = require('view');
var showWelcomeWizard = require('welcome-flow');
var showPlannerWalkthrough = require('planner-walkthrough');
var geocode = require('geocode');

var FROM = config.geocode().start_address;
var TO = config.geocode().end_address;
var isMobile = window.innerWidth <= 480;
var center = config.geocode().center.split(',').map(parseFloat);

var View = view(require('./template.html'), function(view, model) {
  view.scrollable = view.find('.scrollable');
  view.panelFooter = view.find('.footer');

  if (scrollbarSize > 0) {
    if (ua.os.name === 'Windows' || ua.browser.name !== 'Chrome')
      view.scrollable.style.marginRight = -scrollbarSize + 'px';

    // Scrollbars are fun and implemented the same on every OS/Browser...right
    if (ua.os.name === 'Windows' && ua.browser.name === 'Chrome')
      view.scrollable.style.paddingRight = scrollbarSize + 'px';
  }
});

/**
 * Expose `render`
 */

module.exports = function(ctx, next) {
  log('render');

  var plan = ctx.plan;
  var query = querystring.parse(window.location.search);

  // Set up the views
  var views = {
    'filter-view': new FilterView(plan),
    'locations-view': new LocationsView(plan),
    'options-view': new OptionsView(plan),
    'planner-nav': new PlannerNav(session)
  };

  ctx.view = new View(views);
  ctx.view.on('rendered', function() {
    // Set plan to loading
    plan.loading(true);

    for (var key in views) {
      views[key].emit('rendered', views[key]);
    }

    // Show the map
    var map = showMapView(ctx.view.find('.MapView'));

    console.log("map ->", map);

    // Create the transitive layer
    //var transitiveLayer = new LeafletTransitiveLayer(transitive);

    // Set the transitive layer
    //map.addLayer(transitiveLayer);

    // Update map on plan change
    updateMapOnPlanChange(plan, map);

    //map.on('click', function (e) {
    //      var from = plan.from_ll();
    //      var to = plan.to_ll();
    //      if (!plan.coordinateIsValid(from)) {
    //        plan.journey({
    //      places: [
    //        {
    //          place_id: 'from',
    //          place_lat: e.latlng.lat,
    //          place_lon: e.latlng.lng,
    //          place_name: 'From'
    //        },
    //        {
    //          place_id: 'to',
    //          place_lat: (plan.to_ll() ? plan.to_ll().lat : 0),
    //          place_lon: (plan.to_ll() ? plan.to_ll().lng : 0),
    //          place_name: 'To'
    //        }
    //      ]
    //    });
    //    plan.setAddress('from', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
    //        plan.updateRoutes();
    //    });
    //      } else if (!plan.coordinateIsValid(to)) {
    //    plan.journey({
    //      places: [
    //        {
    //          place_id: 'from',
    //          place_lat: plan.from_ll().lat,
    //          place_lon: plan.from_ll().lng,
    //          place_name: 'From'
    //        },
    //        {
    //          place_id: 'to',
    //          place_lat: e.latlng.lat,
    //          place_lon: e.latlng.lng,
    //          place_name: 'To'
    //        }
    //      ]
    //    });
    //    plan.setAddress('to', e.latlng.lng + ',' + e.latlng.lat, function (err, res) {
    //        plan.updateRoutes();
    //    });
    //      }
    //});

    // Clear plan & cookies for now, plan will re-save automatically on save
      var from = plan.from_ll();
      var to = plan.to_ll();
      //plan.clearStore();

    // If it's a shared URL or welcome is complete skip the welcome screen
    console.log("query ->", query);
    if ((query.from && query.to)) {
      showQuery(query);
    } else {
      console.log("plan.coordinateIsValid(from)", plan.coordinateIsValid(from));
      console.log("plan.coordinateIsValid(to)", plan.coordinateIsValid(to));

      if (plan.coordinateIsValid(from) && plan.coordinateIsValid(to)) {
          plan.setAddresses(
            from.lng + ',' + from.lat, // from
            to.lng + ',' + to.lat, // to
            function (err, res) {
              plan.updateRoutes();
              console.log("aqui la data del plan 4 ->", plan.dataplan);
            }
          );
          plan.updateRoutes();
          console.log("aqui la data del plan 3 ->", plan.dataplan);
      } else {
          console.log(from);
          console.log(to);
          plan.loading(false);
      }
    }
  });

  plan.on('updating options', function() {
    ctx.view.panelFooter.classList.add('hidden');
  });

  plan.on('updating options complete', function(res) {
    if (res && !res.err) ctx.view.panelFooter.classList.remove('hidden');
  });

  next();
};

/**
 * Reverse Commute
 */

View.prototype.reverseCommute = function(e) {
  e.preventDefault();
  var plan = session.plan();
  plan.set({
    from: plan.to(),
    from_id: plan.to_id(),
    from_ll: plan.to_ll(),
    to: plan.from(),
    to_id: plan.from_id(),
    to_ll: plan.from_ll()
  });

  plan.updateRoutes();

  console.log("aqui la data del plan 5 ->", plan.dataplan);
};

/**
 * Scroll
 */

View.prototype.scroll = function(e) {
  e.preventDefault();
  this.scrollable.scrollTop += (this.scrollable.scrollHeight / 5);
};

/**
 * On submit
 */

View.prototype.onsubmit = function(e) {
  e.preventDefault();
};

/**
 * Help Me Choose
 */

View.prototype.helpMeChoose = function(e) {
  HelpMeChoose(session.plan().options()).show();
};

/**
 * Show feedback modal
 */
View.prototype.feedback = function(e) {
  e.preventDefault();
  FeedbackModal().show();
};

/**
 * Hide Side Panel
 */

View.prototype.hideSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(' + width + 'px, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding': '0'
  });

  setTimeout(function () {
    map.invalidateSize();
  }, 2100)
};

/**
 * Show Side Panel
 */

View.prototype.showSidePanel = function (e) {
  var sidePanel = $('.SidePanel');
  var fullscreen = $('.fullscreen');
  var width = sidePanel.width();
  var map = showMapView.getMap();

  sidePanel.css({
    'transition': 'transform 2s',
    '-webkit-transition': '-webkit-transform 2s',
    'transform': 'translate3d(0, 0, 0)'
  });

  fullscreen.css({
    'transition': 'padding 2s',
    'padding-right': '320px'
  });

  setTimeout(function () {
    var plan = session.plan();
    map.invalidateSize();

    plan = session.plan();
    plan.updateRoutes();
    //transitive.updateData(plan.journey());
  }, 2100)
};

/**
 * Show Journey
 */

function showQuery(query) {
  var plan = session.plan();
  // If no querystring, see if we have them in the plan already
  var from = query.from || plan.from() || FROM;
  var to = query.to || plan.to() || TO;
  var sameAddresses = from === plan.from() && to === plan.to();

  // Set plan from querystring
  if (query.modes) plan.setModes(query.modes);
  if (query.start_time !== undefined) plan.start_time(parseInt(query.start_time, 10));
  if (query.end_time !== undefined) plan.end_time(parseInt(query.end_time, 10));
  if (query.days !== undefined) plan.days(query.days);

  // If has valid coordinates, load
  if (plan.validCoordinates() && sameAddresses) {
    plan.journey({
      places: plan.generatePlaces()
    });
    plan.updateRoutes();

    console.log("aqui la data del plan 1 ->", plan.dataplan);
  } else {
      if (!plan.validCoordinates()) {
	  plan.loading(false);
	  return;
      } else {
    // Set addresses and update the routes
    plan.setAddresses(from, to, function(err) {
      if (err) {
        log.error('%e', err);
      } else {
        plan.journey({
          places: plan.generatePlaces()
        });
        plan.updateRoutes();

        console.log("aqui la data del plan 2 ->", plan.dataplan);
      }
    });
}
  }
}

/**
 * Update Map on plan change
 */

function updateMapOnPlanChange(plan, map) {
  // Register plan update events
    /*
    for (i in map._layers) {
        if (map._layers[i].options.format == undefined) {
            try {
                map.removeLayer(map._layers[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }
        }
    }
    */

    //map.removeLayer(polyline);
/*

  for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }
  */

  plan.on('change journey', function(journey) {

  var polyline_creadas = showMapView.getpolyline_creadas();
    //console.log("poliline credas ->", polyline_creadas);
    //console.log("llamamos sin evento ->", showMapView.polyline_creadas);

    for (i in polyline_creadas) {
        try {
                map.removeLayer(polyline_creadas[i]);
            } catch (e) {
                console.log("problem with " + e + map._layers[i]);
            }

  }

    showMapView.polyline_creadas = [];
    if (journey && !isMobile) {
      try {

        log('updating data');

        var datajourney = journey;
        if (!(plan.dataplan === undefined)) {
            var itineraries = plan.dataplan.itineraries;
            showMapView.marker_map([plan.dataplan.from.lat,plan.dataplan.from.lon],[plan.dataplan.to.lat,plan.dataplan.to.lon], map);
            for (i = 0; i < itineraries.length; i++) {
                for (ii=0; ii < itineraries[i].legs.length; ii++) {
                  console.log("itineraries[i].legs[ii]", itineraries[i].legs[ii]);
                  showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                }
            }
          console.log("entre if ")
        }else{
            var sesion_plan = JSON.parse(localStorage.getItem('dataplan'));
            if(!(sesion_plan === null)) {
                var itineraries = sesion_plan.itineraries;

                showMapView.marker_map([sesion_plan.from.lat,sesion_plan.from.lon],[sesion_plan.to.lat,sesion_plan.to.lon], map);

                for (i = 0; i < itineraries.length; i++) {
                    for (ii=0; ii < itineraries[i].legs.length; ii++) {
                      showMapView.drawRouteAmigo(itineraries[i].legs[ii].legGeometry.points, itineraries[i].legs[ii].mode);
                    }
                }
            }

        }
      } catch (e) {
        console.log("entre cath")
	    map.setView([center[1], center[0]], config.geocode().zoom);
      }

    }
  });
}
<|endoftext|>


<commit_before>/**
 *	Copyright (C) 2016 3D Repo Ltd
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU Affero General Public License as
 *	published by the Free Software Foundation, either version 3 of the
 *	License, or (at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU Affero General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

(function () {
	"use strict";

	angular.module("3drepo")
		.directive("accountProjects", accountProjects);

	function accountProjects() {
		return {
			restrict: 'EA',
			templateUrl: 'accountProjects.html',
			scope: {
				account: "=",
				accounts: "=",
				onShowPage: "&",
				quota: "=",
				subscriptions: "="
			},
			controller: AccountProjectsCtrl,
			controllerAs: 'vm',
			bindToController: true
		};
	}

	AccountProjectsCtrl.$inject = ["$scope", "$location", "$element", "$timeout", "AccountService", "UtilsService", "RevisionsService", "serverConfig"];

	function AccountProjectsCtrl($scope, $location, $element, $timeout, AccountService, UtilsService, RevisionsService, serverConfig) {
		var vm = this,
			existingProjectToUpload,
			existingProjectFileUploader,
			newProjectFileUploader;

		/*
		 * Init
		 */
		vm.info = "Retrieving projects...";
		vm.showProgress = true;
		vm.projectTypes = ["Architectural", "Structural", "Mechanical", "GIS", "Other"];
		vm.units = serverConfig.units;

		// Setup file uploaders
		existingProjectFileUploader = $element[0].querySelector("#existingProjectFileUploader");
		existingProjectFileUploader.addEventListener(
			"change",
			function () {
				vm.projectToUpload = this.files[0];
				//vm.uploadedFile = {project: existingProjectToUpload, file: this.files[0]};
				$scope.$apply();
			},
			false
		);
		newProjectFileUploader = $element[0].querySelector("#newProjectFileUploader");
		newProjectFileUploader.addEventListener(
			"change",
			function () {
				vm.newProjectFileToUpload = this.files[0];

				$scope.$apply();
			},
			false
		);

		/*
		 * Added data to accounts and projects for UI
		 */
		$scope.$watch("vm.accounts", function () {
			var i, length;

			if (angular.isDefined(vm.accounts)) {
				//console.log('vm.accounts', vm.accounts);
				vm.showProgress = false;
				vm.projectsExist = (vm.accounts.length > 0);
				vm.info = vm.projectsExist ? "" : "There are currently no projects";
				// Accounts
				for (i = 0, length = vm.accounts.length; i < length; i+= 1) {
					vm.accounts[i].name = vm.accounts[i].account;
					vm.accounts[i].showProjects = true;
					vm.accounts[i].showProjectsIcon = "folder_open";
					// Always show user account
					// Don't show account if it doesn't have any projects - possible when user is a team member of a federation but not a member of a project in that federation!
					vm.accounts[i].showAccount = ((i === 0) || (vm.accounts[i].projects.length !== 0));
					// Only show add project menu for user account
					vm.accounts[i].canAddProject = vm.accounts[i].isAdmin;
				}
			}
		});

		/*
		 * Watch the new project type
		 */
		$scope.$watch("vm.newProjectData.type", function (newValue) {
			if (angular.isDefined(newValue)) {
				vm.showProjectTypeOtherInput = (newValue.toString() === "Other");
			}
		});

		/*
		 * Watch new project data
		 */

		$scope.$watch('{a : vm.newProjectData, b: vm.newProjectFileToUpload.name}', function (data){

			var newValue = vm.newProjectData;

			vm.showNewProjectErrorMessage = false;
			vm.newProjectErrorMessage = '';

			if (angular.isDefined(newValue)) {
				vm.newProjectButtonDisabled =
					(angular.isUndefined(newValue.name) || (angular.isDefined(newValue.name) && (newValue.name === "")));

				if (!vm.newProjectButtonDisabled && (newValue.type === "Other")) {
					vm.newProjectButtonDisabled =
						(angular.isUndefined(newValue.otherType) || (angular.isDefined(newValue.otherType) && (newValue.otherType === "")));
				}

				if(!newValue.unit){
					vm.newProjectButtonDisabled = true;
				}

			}

			if(vm.newProjectFileToUpload){
				var names = vm.newProjectFileToUpload.name.split('.');

				if(names.length === 1){
					vm.showNewProjectErrorMessage = true;
					vm.newProjectErrorMessage = 'Filename must have extension';
					vm.newProjectButtonDisabled = true;
				} else if(serverConfig.acceptedFormat.indexOf(names[names.length - 1]) === -1) {
					vm.showNewProjectErrorMessage = true;
					vm.newProjectErrorMessage = 'File format not supported';
					vm.newProjectButtonDisabled = true;
				}
			}

		}, true);

		/*
		 * Watch new database name
		 */
		$scope.$watch("vm.newDatabaseName", function (newValue) {
			if (angular.isDefined(newValue)) {
				vm.newDatabaseButtonDisabled =
					(angular.isUndefined(newValue) || (angular.isDefined(newValue) && (newValue.toString() === "")));
			}
		}, true);

		/**
		 * Toggle display of projects for an account
		 *
		 * @param {Number} index
		 */
		vm.toggleProjectsList = function (index) {
			vm.accounts[index].showProjects = !vm.accounts[index].showProjects;
			vm.accounts[index].showProjectsIcon = vm.accounts[index].showProjects ? "folder_open" : "folder";
		};

		/**
		 * Bring up dialog to add a new project
		 */
		vm.newProject = function (event, accountForProject) {
			vm.tag = null;
			vm.desc = null;
			vm.showNewProjectErrorMessage = false;
			vm.newProjectFileToUpload = null;
			vm.newProjectData = {
				account: accountForProject,
				type: vm.projectTypes[0]
			};
			vm.newProjectFileToUpload = null;
			UtilsService.showDialog("projectDialog.html", $scope, event, true);
		};

		/**
		 * Close the dialog
		 */
		vm.closeDialog = function() {
			UtilsService.closeDialog();
		};

		/**
		 * Save a new project
		 */
		vm.saveNewProject = function (event) {
			var project,
				promise,
				enterKey = 13,
				doSave = false;

			if (angular.isDefined(event)) {
				if (event.which === enterKey) {
					doSave = true;
				}
			}
			else {
				doSave = true;
			}

			if (doSave) {

				if(RevisionsService.isTagFormatInValid(vm.tag)){
					vm.showNewProjectErrorMessage = true;
					vm.newProjectErrorMessage = 'Invalid revision name';
					return;
				}

				promise = AccountService.newProject(vm.newProjectData);
				promise.then(function (response) {
					console.log(response);
					if (response.data.status === 400) {
						vm.showNewProjectErrorMessage = true;
						vm.newProjectErrorMessage = response.data.message;
					}
					else {
						vm.projectsExist = true;
						// Add project to list
						project = {
							project: response.data.project,
							permissions: response.data.permissions,
							canUpload: true,
							timestamp: null
						};
						updateAccountProjects(response.data.account, project);
						vm.closeDialog();
					}
				});
			}
		};

		/**
		 * Upload a file
		 *
		 * @param {Object} project
		 */
		vm.uploadFile = function (project) {
			console.log(project);
			existingProjectFileUploader.value = "";
			existingProjectToUpload = project;
			existingProjectFileUploader.click();
		};

		/**
		 * Upload a file
		 */
		vm.uploadFileForNewProject = function () {
			newProjectFileUploader.value = "";
			newProjectFileUploader.click();
		};

		/**
		 * Create a new database
		 */
		vm.newDatabase = function (event) {
			vm.newDatabaseName = "";
			vm.showPaymentWait = false;
			vm.newDatabaseToken = false;
			UtilsService.showDialog("databaseDialog.html", $scope, event, true);
		};

		/**
		 * Save a new database
		 */
		vm.saveNewDatabase = function () {
			var promise = AccountService.newDatabase(vm.account, vm.newDatabaseName);
			promise.then(function (response) {
				console.log(response);
				vm.newDatabaseToken = response.data.token;
				vm.paypalReturnUrl = $location.protocol() + "://" + $location.host() + "/" + vm.account;
			});
		};

		/**
		 * Show waiting before going to payment page
		 * $timeout required otherwise Submit does not work
		 */
		vm.setupPayment = function () {
			$timeout(function () {
				vm.showPaymentWait = true;
			});
		};

		/**
		 * Set up deleting of project
		 *
		 * @param {Object} event
		 * @param {Object} project
		 */
		vm.setupDeleteProject = function (event, project, account) {
			vm.projectToDelete = project;
			vm.deleteError = null;
			vm.deleteTitle = "Delete Project";
			vm.deleteWarning = "Your data will be lost permanently and will not be recoverable";
			vm.deleteName = vm.projectToDelete.name;
			vm.targetAccountToDeleteProject = account;
			UtilsService.showDialog("deleteDialog.html", $scope, event, true);
		};

		/**
		 * Delete project
		 */
		vm.delete = function () {
			var i, iLength, j, jLength,
				promise;
			promise = UtilsService.doDelete({}, vm.targetAccountToDeleteProject + "/" + vm.projectToDelete.name);
			promise.then(function (response) {
				if (response.status === 200) {
					// Remove project from list
					for (i = 0, iLength = vm.accounts.length; i < iLength; i += 1) {
						if (vm.accounts[i].name === response.data.account) {
							for (j = 0, jLength = vm.accounts[i].projects.length; j < jLength; j += 1) {
								if (vm.accounts[i].projects[j].name === response.data.project) {
									vm.accounts[i].projects.splice(j, 1);
									break;
								}
							}
						}
					}
					vm.closeDialog();
				}
				else {
					vm.deleteError = "Error deleting project";
				}
			});
		};

		/**
		 * Remove a collaborator
		 *
		 * @param collaborator
		 */
		vm.removeCollaborator = function (collaborator) {
			delete vm.collaborators[collaborator];
		};

		vm.showPage = function (page, callingPage) {
			vm.onShowPage({page: page, callingPage: callingPage});
		};

		/**
		 * Add a project to an existing or create newly created account
		 *
		 * @param account
		 * @param project
		 */
		function updateAccountProjects (account, project) {
			var i, length,
				accountToUpdate;

			for (i = 0, length = vm.accounts.length; i < length; i += 1) {
				if (vm.accounts[i].name === account) {
					accountToUpdate = vm.accounts[i];
					accountToUpdate.projects.push(project);
					break;
				}
			}
			if (angular.isUndefined(accountToUpdate)) {
				accountToUpdate = {
					name: account,
					projects: [project],
					showProjects: true,
					showProjectsIcon: "folder_open"
				};
				accountToUpdate.canUpload = (account === vm.account);
				vm.accounts.push(accountToUpdate);
			}

			console.log('vmaccounts', vm.accounts);
			// Save model to project
			if (vm.newProjectFileToUpload !== null) {
				$timeout(function () {
					vm.uploadedFile = {project: project, file: vm.newProjectFileToUpload, tag: vm.tag, desc: vm.desc, newProject: true};
				});
			}
		}
	}
}());
<commit_msg>ISSUE #311 fix save enable/disable logic and also the selected file label's visibility<commit_after>/**
 *	Copyright (C) 2016 3D Repo Ltd
 *
 *	This program is free software: you can redistribute it and/or modify
 *	it under the terms of the GNU Affero General Public License as
 *	published by the Free Software Foundation, either version 3 of the
 *	License, or (at your option) any later version.
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *	GNU Affero General Public License for more details.
 *
 *	You should have received a copy of the GNU Affero General Public License
 *	along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

(function () {
	"use strict";

	angular.module("3drepo")
		.directive("accountProjects", accountProjects);

	function accountProjects() {
		return {
			restrict: 'EA',
			templateUrl: 'accountProjects.html',
			scope: {
				account: "=",
				accounts: "=",
				onShowPage: "&",
				quota: "=",
				subscriptions: "="
			},
			controller: AccountProjectsCtrl,
			controllerAs: 'vm',
			bindToController: true
		};
	}

	AccountProjectsCtrl.$inject = ["$scope", "$location", "$element", "$timeout", "AccountService", "UtilsService", "RevisionsService", "serverConfig"];

	function AccountProjectsCtrl($scope, $location, $element, $timeout, AccountService, UtilsService, RevisionsService, serverConfig) {
		var vm = this,
			existingProjectToUpload,
			existingProjectFileUploader,
			newProjectFileUploader;

		/*
		 * Init
		 */
		vm.info = "Retrieving projects...";
		vm.showProgress = true;
		vm.projectTypes = ["Architectural", "Structural", "Mechanical", "GIS", "Other"];
		vm.units = serverConfig.units;

		// Setup file uploaders
		existingProjectFileUploader = $element[0].querySelector("#existingProjectFileUploader");
		existingProjectFileUploader.addEventListener(
			"change",
			function () {
				vm.projectToUpload = this.files[0];
				//vm.uploadedFile = {project: existingProjectToUpload, file: this.files[0]};
				$scope.$apply();
			},
			false
		);
		newProjectFileUploader = $element[0].querySelector("#newProjectFileUploader");
		newProjectFileUploader.addEventListener(
			"change",
			function () {
				vm.newProjectFileToUpload = this.files[0];

				$scope.$apply();
			},
			false
		);

		/*
		 * Added data to accounts and projects for UI
		 */
		$scope.$watch("vm.accounts", function () {
			var i, length;

			if (angular.isDefined(vm.accounts)) {
				//console.log('vm.accounts', vm.accounts);
				vm.showProgress = false;
				vm.projectsExist = (vm.accounts.length > 0);
				vm.info = vm.projectsExist ? "" : "There are currently no projects";
				// Accounts
				for (i = 0, length = vm.accounts.length; i < length; i+= 1) {
					vm.accounts[i].name = vm.accounts[i].account;
					vm.accounts[i].showProjects = true;
					vm.accounts[i].showProjectsIcon = "folder_open";
					// Always show user account
					// Don't show account if it doesn't have any projects - possible when user is a team member of a federation but not a member of a project in that federation!
					vm.accounts[i].showAccount = ((i === 0) || (vm.accounts[i].projects.length !== 0));
					// Only show add project menu for user account
					vm.accounts[i].canAddProject = vm.accounts[i].isAdmin;
				}
			}
		});

		/*
		 * Watch the new project type
		 */
		$scope.$watch("vm.newProjectData.type", function (newValue) {
			if (angular.isDefined(newValue)) {
				vm.showProjectTypeOtherInput = (newValue.toString() === "Other");
			}
		});

		/*
		 * Watch new project data
		 */

		$scope.$watch('{a : vm.newProjectData, b: vm.newProjectFileToUpload.name}', function (data){

			var newValue = vm.newProjectData;

			if (angular.isDefined(newValue)) {
				vm.newProjectButtonDisabled =
					(angular.isUndefined(newValue.name) || (angular.isDefined(newValue.name) && (newValue.name === "")));

				if (!vm.newProjectButtonDisabled && (newValue.type === "Other")) {
					vm.newProjectButtonDisabled =
						(angular.isUndefined(newValue.otherType) || (angular.isDefined(newValue.otherType) && (newValue.otherType === "")));
				}

				if(!newValue.unit){
					vm.newProjectButtonDisabled = true;
				}

			}

			if(vm.newProjectFileToUpload){
				var names = vm.newProjectFileToUpload.name.split('.');

				vm.showNewProjectErrorMessage = false;
				vm.newProjectErrorMessage = '';
				if(names.length === 1){
					vm.showNewProjectErrorMessage = true;
					vm.newProjectErrorMessage = 'Filename must have extension';
					vm.newProjectFileToUpload = null;
				} else if(serverConfig.acceptedFormat.indexOf(names[names.length - 1]) === -1) {
					vm.showNewProjectErrorMessage = true;
					vm.newProjectErrorMessage = 'File format not supported';
					vm.newProjectFileToUpload = null
				}
			}

		}, true);

		/*
		 * Watch new database name
		 */
		$scope.$watch("vm.newDatabaseName", function (newValue) {
			if (angular.isDefined(newValue)) {
				vm.newDatabaseButtonDisabled =
					(angular.isUndefined(newValue) || (angular.isDefined(newValue) && (newValue.toString() === "")));
			}
		}, true);

		/**
		 * Toggle display of projects for an account
		 *
		 * @param {Number} index
		 */
		vm.toggleProjectsList = function (index) {
			vm.accounts[index].showProjects = !vm.accounts[index].showProjects;
			vm.accounts[index].showProjectsIcon = vm.accounts[index].showProjects ? "folder_open" : "folder";
		};

		/**
		 * Bring up dialog to add a new project
		 */
		vm.newProject = function (event, accountForProject) {
			vm.tag = null;
			vm.desc = null;
			vm.showNewProjectErrorMessage = false;
			vm.newProjectFileToUpload = null;
			vm.newProjectData = {
				account: accountForProject,
				type: vm.projectTypes[0]
			};
			vm.newProjectFileToUpload = null;
			UtilsService.showDialog("projectDialog.html", $scope, event, true);
		};

		/**
		 * Close the dialog
		 */
		vm.closeDialog = function() {
			UtilsService.closeDialog();
		};

		/**
		 * Save a new project
		 */
		vm.saveNewProject = function (event) {
			var project,
				promise,
				enterKey = 13,
				doSave = false;

			if (angular.isDefined(event)) {
				if (event.which === enterKey) {
					doSave = true;
				}
			}
			else {
				doSave = true;
			}

			if (doSave) {

				if(RevisionsService.isTagFormatInValid(vm.tag)){
					vm.showNewProjectErrorMessage = true;
					vm.newProjectErrorMessage = 'Invalid revision name';
					return;
				}

				promise = AccountService.newProject(vm.newProjectData);
				promise.then(function (response) {
					console.log(response);
					if (response.data.status === 400) {
						vm.showNewProjectErrorMessage = true;
						vm.newProjectErrorMessage = response.data.message;
					}
					else {
						vm.projectsExist = true;
						// Add project to list
						project = {
							project: response.data.project,
							permissions: response.data.permissions,
							canUpload: true,
							timestamp: null
						};
						updateAccountProjects(response.data.account, project);
						vm.closeDialog();
					}
				});
			}
		};

		/**
		 * Upload a file
		 *
		 * @param {Object} project
		 */
		vm.uploadFile = function (project) {
			console.log(project);
			existingProjectFileUploader.value = "";
			existingProjectToUpload = project;
			existingProjectFileUploader.click();
		};

		/**
		 * Upload a file
		 */
		vm.uploadFileForNewProject = function () {
			newProjectFileUploader.value = "";
			newProjectFileUploader.click();
		};

		/**
		 * Create a new database
		 */
		vm.newDatabase = function (event) {
			vm.newDatabaseName = "";
			vm.showPaymentWait = false;
			vm.newDatabaseToken = false;
			UtilsService.showDialog("databaseDialog.html", $scope, event, true);
		};

		/**
		 * Save a new database
		 */
		vm.saveNewDatabase = function () {
			var promise = AccountService.newDatabase(vm.account, vm.newDatabaseName);
			promise.then(function (response) {
				console.log(response);
				vm.newDatabaseToken = response.data.token;
				vm.paypalReturnUrl = $location.protocol() + "://" + $location.host() + "/" + vm.account;
			});
		};

		/**
		 * Show waiting before going to payment page
		 * $timeout required otherwise Submit does not work
		 */
		vm.setupPayment = function () {
			$timeout(function () {
				vm.showPaymentWait = true;
			});
		};

		/**
		 * Set up deleting of project
		 *
		 * @param {Object} event
		 * @param {Object} project
		 */
		vm.setupDeleteProject = function (event, project, account) {
			vm.projectToDelete = project;
			vm.deleteError = null;
			vm.deleteTitle = "Delete Project";
			vm.deleteWarning = "Your data will be lost permanently and will not be recoverable";
			vm.deleteName = vm.projectToDelete.name;
			vm.targetAccountToDeleteProject = account;
			UtilsService.showDialog("deleteDialog.html", $scope, event, true);
		};

		/**
		 * Delete project
		 */
		vm.delete = function () {
			var i, iLength, j, jLength,
				promise;
			promise = UtilsService.doDelete({}, vm.targetAccountToDeleteProject + "/" + vm.projectToDelete.name);
			promise.then(function (response) {
				if (response.status === 200) {
					// Remove project from list
					for (i = 0, iLength = vm.accounts.length; i < iLength; i += 1) {
						if (vm.accounts[i].name === response.data.account) {
							for (j = 0, jLength = vm.accounts[i].projects.length; j < jLength; j += 1) {
								if (vm.accounts[i].projects[j].name === response.data.project) {
									vm.accounts[i].projects.splice(j, 1);
									break;
								}
							}
						}
					}
					vm.closeDialog();
				}
				else {
					vm.deleteError = "Error deleting project";
				}
			});
		};

		/**
		 * Remove a collaborator
		 *
		 * @param collaborator
		 */
		vm.removeCollaborator = function (collaborator) {
			delete vm.collaborators[collaborator];
		};

		vm.showPage = function (page, callingPage) {
			vm.onShowPage({page: page, callingPage: callingPage});
		};

		/**
		 * Add a project to an existing or create newly created account
		 *
		 * @param account
		 * @param project
		 */
		function updateAccountProjects (account, project) {
			var i, length,
				accountToUpdate;

			for (i = 0, length = vm.accounts.length; i < length; i += 1) {
				if (vm.accounts[i].name === account) {
					accountToUpdate = vm.accounts[i];
					accountToUpdate.projects.push(project);
					break;
				}
			}
			if (angular.isUndefined(accountToUpdate)) {
				accountToUpdate = {
					name: account,
					projects: [project],
					showProjects: true,
					showProjectsIcon: "folder_open"
				};
				accountToUpdate.canUpload = (account === vm.account);
				vm.accounts.push(accountToUpdate);
			}

			console.log('vmaccounts', vm.accounts);
			// Save model to project
			if (vm.newProjectFileToUpload !== null) {
				$timeout(function () {
					vm.uploadedFile = {project: project, file: vm.newProjectFileToUpload, tag: vm.tag, desc: vm.desc, newProject: true};
				});
			}
		}
	}
}());
<|endoftext|>


<commit_before>function BarcodePlugin(bot) {
	var self = this;
	self.name = "barcode";
	self.help = "Barcode plugin";
	self.depend = ["cmd"];

	self.chars = " ▗▝▐▖▄▞▟▘▚▀▜▌▙▛█";

	self.halflines = " ▐▌█";
	self.quiet = [0,0,0,0,0,0,0,0,0];
	self.start = [1,0,1];
	self.first = [
		[0,0,0,0,0,0], // 0
		[0,0,1,0,1,1], // 1
		[0,0,1,1,0,1], // 2
		[0,0,1,1,1,0], // 3
		[0,1,0,0,1,1], // 4
		[0,1,1,0,0,1], // 5
		[0,1,1,1,0,0], // 6
		[0,1,0,1,0,1], // 7
		[0,1,0,1,1,0], // 8
		[0,1,1,0,1,0]  // 9
	];
	self.leftL = [
		[0,0,0,1,1,0,1], // 0
		[0,0,1,1,0,0,1], // 1
		[0,0,1,0,0,1,1], // 2
		[0,1,1,1,1,0,1], // 3
		[0,1,0,0,0,1,1], // 4
		[0,1,1,0,0,0,1], // 5
		[0,1,0,1,1,1,1], // 6
		[0,1,1,1,0,1,1], // 7
		[0,1,1,0,1,1,1], // 8
		[0,0,0,1,0,1,1]  // 9
	];
	self.leftG = [
		[0,1,0,0,1,1,1], // 0
		[0,1,1,0,0,1,1], // 1
		[0,0,1,1,0,1,1], // 2
		[0,1,0,0,0,0,1], // 3
		[0,0,1,1,1,0,1], // 4
		[0,1,1,1,0,0,1], // 5
		[0,0,0,0,1,0,1], // 6
		[0,0,1,0,0,0,1], // 7
		[0,0,0,1,0,0,1], // 8
		[0,0,1,0,1,1,1]  // 9
	];
	self.middle = [0,1,0,1,0];
	self.right = [
		[1,1,1,0,0,1,0], // 1
		[1,1,0,0,1,1,0], // 0
		[1,1,0,1,1,0,0], // 2
		[1,0,0,0,0,1,0], // 3
		[1,0,1,1,1,0,0], // 4
		[1,0,0,1,1,1,0], // 5
		[1,0,1,0,0,0,0], // 6
		[1,0,0,0,1,0,0], // 7
		[1,0,0,1,0,0,0], // 8
		[1,1,1,0,1,0,0]  // 9
	];
	self.end = [1,0,1];
	self.code0 = "0".charCodeAt(0);

	self.mask = function(br, tr, bl, tl) {
		return self.chars.charAt(br | (tr << 1) | (bl << 2) | (tl << 3));
	};

	self.barmask = function(arr) {
		var str = "";
		for (var i = 0; i < arr.length; i += 2) {
			str += self.halflines[(arr[i] << 1) | (arr[i + 1] || 0)];
		}
		return str;
	};

	self.EAN13 = function(num) {
		var arr = [];

		arr = arr.concat(self.quiet);
		arr = arr.concat(self.start);
		var groups = self.first[num.charCodeAt(0) - self.code0];
		for (var i = 1; i < 7; i++) {
			arr = arr.concat((groups[i - 1] ?self.leftG : self.leftL)[num.charCodeAt(i) - self.code0]);
		}
		arr = arr.concat(self.middle);
		for (var i = 7; i < 13; i++) {
			arr = arr.concat(self.right[num.charCodeAt(i) - self.code0]);
		}
		arr = arr.concat(self.end);
		arr = arr.concat(self.quiet);

		return arr;
	};

	self.UPCA = function(num) {
		return self.EAN13("0" + num);
	}

	self.events = {
		"cmd#bmask": function(nick, to, args) {
			bot.say(to, nick + ": " + self.mask(args[1] & 1, args[2] & 1, args[3] & 1, args[4] & 1));
		},

		"cmd#b-upc": function(nick, to, args) {
			bot.say(to, "\x0301,00" + self.barmask(self.UPCA(args[1])));
		},

		"cmd#b-ean": function(nick, to, args) {
			bot.say(to, "\x0301,00" + self.barmask(self.EAN13(args[1])));
		}
	}
}

module.exports = BarcodePlugin;
<commit_msg>barcode: style fix<commit_after>function BarcodePlugin(bot) {
	var self = this;
	self.name = "barcode";
	self.help = "Barcode plugin";
	self.depend = ["cmd"];

	self.chars = " ▗▝▐▖▄▞▟▘▚▀▜▌▙▛█";

	self.halflines = " ▐▌█";
	self.quiet = [0,0,0,0,0,0,0,0,0];
	self.start = [1,0,1];
	self.first = [
		[0,0,0,0,0,0], // 0
		[0,0,1,0,1,1], // 1
		[0,0,1,1,0,1], // 2
		[0,0,1,1,1,0], // 3
		[0,1,0,0,1,1], // 4
		[0,1,1,0,0,1], // 5
		[0,1,1,1,0,0], // 6
		[0,1,0,1,0,1], // 7
		[0,1,0,1,1,0], // 8
		[0,1,1,0,1,0]  // 9
	];
	self.leftL = [
		[0,0,0,1,1,0,1], // 0
		[0,0,1,1,0,0,1], // 1
		[0,0,1,0,0,1,1], // 2
		[0,1,1,1,1,0,1], // 3
		[0,1,0,0,0,1,1], // 4
		[0,1,1,0,0,0,1], // 5
		[0,1,0,1,1,1,1], // 6
		[0,1,1,1,0,1,1], // 7
		[0,1,1,0,1,1,1], // 8
		[0,0,0,1,0,1,1]  // 9
	];
	self.leftG = [
		[0,1,0,0,1,1,1], // 0
		[0,1,1,0,0,1,1], // 1
		[0,0,1,1,0,1,1], // 2
		[0,1,0,0,0,0,1], // 3
		[0,0,1,1,1,0,1], // 4
		[0,1,1,1,0,0,1], // 5
		[0,0,0,0,1,0,1], // 6
		[0,0,1,0,0,0,1], // 7
		[0,0,0,1,0,0,1], // 8
		[0,0,1,0,1,1,1]  // 9
	];
	self.middle = [0,1,0,1,0];
	self.right = [
		[1,1,1,0,0,1,0], // 1
		[1,1,0,0,1,1,0], // 0
		[1,1,0,1,1,0,0], // 2
		[1,0,0,0,0,1,0], // 3
		[1,0,1,1,1,0,0], // 4
		[1,0,0,1,1,1,0], // 5
		[1,0,1,0,0,0,0], // 6
		[1,0,0,0,1,0,0], // 7
		[1,0,0,1,0,0,0], // 8
		[1,1,1,0,1,0,0]  // 9
	];
	self.end = [1,0,1];
	self.code0 = "0".charCodeAt(0);

	self.mask = function(br, tr, bl, tl) {
		return self.chars.charAt(br | (tr << 1) | (bl << 2) | (tl << 3));
	};

	self.barmask = function(arr) {
		var str = "";
		for (var i = 0; i < arr.length; i += 2) {
			str += self.halflines[(arr[i] << 1) | (arr[i + 1] || 0)];
		}
		return str;
	};

	self.EAN13 = function(num) {
		var arr = [];

		arr = arr.concat(self.quiet);
		arr = arr.concat(self.start);
		var groups = self.first[num.charCodeAt(0) - self.code0];
		for (var i = 1; i < 7; i++) {
			arr = arr.concat((groups[i - 1] ? self.leftG : self.leftL)[num.charCodeAt(i) - self.code0]);
		}
		arr = arr.concat(self.middle);
		for (var i = 7; i < 13; i++) {
			arr = arr.concat(self.right[num.charCodeAt(i) - self.code0]);
		}
		arr = arr.concat(self.end);
		arr = arr.concat(self.quiet);

		return arr;
	};

	self.UPCA = function(num) {
		return self.EAN13("0" + num);
	}

	self.events = {
		"cmd#bmask": function(nick, to, args) {
			bot.say(to, nick + ": " + self.mask(args[1] & 1, args[2] & 1, args[3] & 1, args[4] & 1));
		},

		"cmd#b-upc": function(nick, to, args) {
			bot.say(to, "\x0301,00" + self.barmask(self.UPCA(args[1])));
		},

		"cmd#b-ean": function(nick, to, args) {
			bot.say(to, "\x0301,00" + self.barmask(self.EAN13(args[1])));
		}
	}
}

module.exports = BarcodePlugin;
<|endoftext|>


<commit_before>'use strict';

define([
  'angular',
  'camunda-commons-ui/auth',
  'camunda-casemanager-ui/api',

  'text!camunda-casemanager-ui/user/login.html'
], function(
  angular,
  auth,
  api
) {

  /**
   * @module cam.casemanager.user
   */

  /**
   * @memberof cam.casemanager
   */

  var userModule = angular.module('cam.casemanager.user', [
    auth.name,
    api.name,
    'ui.bootstrap',
    'cam.form'
  ]);

  /**
   * Controller used for the /login route
   */
  userModule.controller('userLoginCtrl', [
    '$location',
    '$modal',
  function(
    $location,
    $modal
  ) {
    $modal.open({
      windowClass:  'user-login',
      template:     require('text!camunda-casemanager-ui/user/login.html')
    });
  }]);

  /**
   * controller to be used for the /logout route
   */
  userModule.controller('userLogoutCtrl', [
    '$rootScope',
    '$translate',
    'AuthenticationService',
    'Notifications',
  function(
    $rootScope,
    $translate,
    AuthenticationService,
    Notifications
  ) {
    AuthenticationService
      .logout()
      .then(function() {
        $translate('LOGGED_OUT').then(function(translated) {
          Notifications.add({
            status: translated
          });
        });
      });
  }]);

  userModule.controller('userLoginModalFormCtrl', [
    '$scope',
    '$rootScope',
    '$location',
    '$translate',
    'AuthenticationService',
    'Notifications',
  function(
    $scope,
    $rootScope,
    $location,
    $translate,
    AuthenticationService,
    Notifications
  ) {
    $scope.submitForm = function(htmlForm) {
      return htmlForm.$valid;
    };

    // /camunda/api/admin/auth/user/default/login/cockpit
    $scope.ok = function() {
      function success() {
        $translate('LOGGED_IN').then(function(translated) {
          Notifications.addMessage({
            duration: 5000,
            status: translated
          });
        });

        $scope.$parent.$parent.$close();
      }

      function error() {
        $translate('CREDENTIALS_ERROR').then(function(translated) {
          Notifications.addError({
            status: translated
          });
        });
      }

      AuthenticationService
        .login($scope.username, $scope.password)
        .then(success, error);
    };

    $scope.cancel = function() {
      $scope.$parent.$parent.$dismiss();
    };
  }]);

  return userModule;
});
<commit_msg>chore(case): remove dependency<commit_after>'use strict';

define([
  'angular',
  'camunda-commons-ui/auth',
  'camunda-casemanager-ui/api',

  'text!camunda-casemanager-ui/user/login.html'
], function(
  angular,
  auth,
  api
) {

  /**
   * @module cam.casemanager.user
   */

  /**
   * @memberof cam.casemanager
   */

  var userModule = angular.module('cam.casemanager.user', [
    auth.name,
    api.name,
    'ui.bootstrap'
  ]);

  /**
   * Controller used for the /login route
   */
  userModule.controller('userLoginCtrl', [
    '$location',
    '$modal',
  function(
    $location,
    $modal
  ) {
    $modal.open({
      windowClass:  'user-login',
      template:     require('text!camunda-casemanager-ui/user/login.html')
    });
  }]);

  /**
   * controller to be used for the /logout route
   */
  userModule.controller('userLogoutCtrl', [
    '$rootScope',
    '$translate',
    'AuthenticationService',
    'Notifications',
  function(
    $rootScope,
    $translate,
    AuthenticationService,
    Notifications
  ) {
    AuthenticationService
      .logout()
      .then(function() {
        $translate('LOGGED_OUT').then(function(translated) {
          Notifications.add({
            status: translated
          });
        });
      });
  }]);

  userModule.controller('userLoginModalFormCtrl', [
    '$scope',
    '$rootScope',
    '$location',
    '$translate',
    'AuthenticationService',
    'Notifications',
  function(
    $scope,
    $rootScope,
    $location,
    $translate,
    AuthenticationService,
    Notifications
  ) {
    $scope.submitForm = function(htmlForm) {
      return htmlForm.$valid;
    };

    // /camunda/api/admin/auth/user/default/login/cockpit
    $scope.ok = function() {
      function success() {
        $translate('LOGGED_IN').then(function(translated) {
          Notifications.addMessage({
            duration: 5000,
            status: translated
          });
        });

        $scope.$parent.$parent.$close();
      }

      function error() {
        $translate('CREDENTIALS_ERROR').then(function(translated) {
          Notifications.addError({
            status: translated
          });
        });
      }

      AuthenticationService
        .login($scope.username, $scope.password)
        .then(success, error);
    };

    $scope.cancel = function() {
      $scope.$parent.$parent.$dismiss();
    };
  }]);

  return userModule;
});
<|endoftext|>


<commit_before>define(['rules/rules.module'
       ],
function() {
    angular.module('rules').factory('references',
    [
    function() {
        function generateReference(query) {
            var bindings = {};

            angular.forEach(query.bindings, function(binding) {
                if (('id' in binding) && ('name' in binding))  {
                    bindings[binding.name] = binding.id;
            });

            var info = { rule: query.rule,
                         query: query.query,
                         bindings: bindings,
                         constraints: query.constraints
            };
            var url = ('#/rules/explain?inference=' +
                       encodeURIComponent(angular.toJson(info, false)));
            var reference = { P854: [{ datatype: 'url',
                                       datavalue: { type: 'string',
                                                    value: url,
                                                    __sqid_display_string_override__: '(explain inference)'
                                                  },
                                       snaktype: 'value',
                                       property: 'P854'
                                     }]
                            };

            return [{ snaks: reference,
                      'snaks-order': ['P854']
                    }];
        }

        return { generateReference: generateReference
               };
    }]);

    return {};
});
<commit_msg>Include qualifiers on reference generation<commit_after>define(['rules/rules.module'
       ],
function() {
    angular.module('rules').factory('references',
    ['ast',
    function(ast) {
        function generateReference(query) {
            var bindings = {};

            angular.forEach(query.bindings, function(binding) {
                if (('id' in binding) && ('name' in binding))  {
                    bindings[binding.name] = binding.id;
                }
            });

            angular.forEach(ast.variables(query.rule.head), function(variable) {
                var name = variable.name;
                bindings[name] = { id: query.bindings[name].id,
                                   type: query.bindings[name].type,
                                   qualifiers: query.bindings[name].qualifiers
                                 };
            });

            var info = { rule: query.rule,
                         query: query.query,
                         bindings: bindings,
                         constraints: query.constraints
            };
            var url = ('#/rules/explain?inference=' +
                       encodeURIComponent(angular.toJson(info, false)));
            var reference = { P854: [{ datatype: 'url',
                                       datavalue: { type: 'string',
                                                    value: url,
                                                    __sqid_display_string_override__: '(explain inference)'
                                                  },
                                       snaktype: 'value',
                                       property: 'P854'
                                     }]
                            };

            return [{ snaks: reference,
                      'snaks-order': ['P854']
                    }];
        }

        return { generateReference: generateReference
               };
    }]);

    return {};
});
<|endoftext|>


<commit_before>const {createVariableRule} = require('./lib/variable-rules')

module.exports = createVariableRule('primer/borders', {
  border: {
    expects: 'a border variable',
    props: 'border{,-top,-right,-bottom,-left}',
    values: ['$border', 'none', '0'],
    components: ['border-width', 'border-style', 'border-color'],
    replacements: {
      // because shorthand border properties ¯\_(ツ)_/¯
      '$border-width $border-style $border-gray': '$border',
      '$border-width $border-gray $border-style': '$border',
      '$border-style $border-width $border-gray': '$border',
      '$border-style $border-gray $border-width': '$border',
      '$border-gray $border-width $border-style': '$border',
      '$border-gray $border-style $border-width': '$border',
      '$border-width $border-style $border-color': '$border',
      '$border-width $border-color $border-style': '$border',
      '$border-style $border-width $border-color': '$border',
      '$border-style $border-color $border-width': '$border',
      '$border-color $border-width $border-style': '$border',
      '$border-color $border-style $border-width': '$border'
    }
  },
  'border color': {
    expects: 'a border color variable',
    props: 'border{,-top,-right,-bottom,-left}-color',
    values: [
      '$border-*',
      'transparent',
      'currentColor',
      // Match variables in any of the following formats: --color-text-*, --color-*-text-*, --color-*-text
      /var\(--color-(.+-)*border(-.+)*\)/
    ],
    replacements: {
      '$border-gray': '$border-color'
    }
  },
  'border style': {
    expects: 'a border style variable',
    props: 'border{,-top,-right,-bottom,-left}-style',
    values: ['$border-style', 'none']
  },
  'border width': {
    expects: 'a border width variable',
    props: 'border{,-top,-right,-bottom,-left}-width',
    values: ['$border-width*', '0']
  },
  'border radius': {
    expects: 'a border radius variable',
    props: 'border{,-{top,bottom}-{left,right}}-radius',
    values: ['$border-radius', '0', '50%', 'inherit'],
    replacements: {
      '100%': '50%'
    }
  }
})
<commit_msg>Update border regex comment<commit_after>const {createVariableRule} = require('./lib/variable-rules')

module.exports = createVariableRule('primer/borders', {
  border: {
    expects: 'a border variable',
    props: 'border{,-top,-right,-bottom,-left}',
    values: ['$border', 'none', '0'],
    components: ['border-width', 'border-style', 'border-color'],
    replacements: {
      // because shorthand border properties ¯\_(ツ)_/¯
      '$border-width $border-style $border-gray': '$border',
      '$border-width $border-gray $border-style': '$border',
      '$border-style $border-width $border-gray': '$border',
      '$border-style $border-gray $border-width': '$border',
      '$border-gray $border-width $border-style': '$border',
      '$border-gray $border-style $border-width': '$border',
      '$border-width $border-style $border-color': '$border',
      '$border-width $border-color $border-style': '$border',
      '$border-style $border-width $border-color': '$border',
      '$border-style $border-color $border-width': '$border',
      '$border-color $border-width $border-style': '$border',
      '$border-color $border-style $border-width': '$border'
    }
  },
  'border color': {
    expects: 'a border color variable',
    props: 'border{,-top,-right,-bottom,-left}-color',
    values: [
      '$border-*',
      'transparent',
      'currentColor',
      // Match variables in any of the following formats: --colorr-borde-*, --color-*-border-*, --color-*-border
      /var\(--color-(.+-)*border(-.+)*\)/
    ],
    replacements: {
      '$border-gray': '$border-color'
    }
  },
  'border style': {
    expects: 'a border style variable',
    props: 'border{,-top,-right,-bottom,-left}-style',
    values: ['$border-style', 'none']
  },
  'border width': {
    expects: 'a border width variable',
    props: 'border{,-top,-right,-bottom,-left}-width',
    values: ['$border-width*', '0']
  },
  'border radius': {
    expects: 'a border radius variable',
    props: 'border{,-{top,bottom}-{left,right}}-radius',
    values: ['$border-radius', '0', '50%', 'inherit'],
    replacements: {
      '100%': '50%'
    }
  }
})
<|endoftext|>


<commit_before>
import { h } from 'preact';
import { Button, Icon } from 'preact-mdl';

export default ({ icon, onClick }) => (
  <Button style={styles.container} onClick={onClick} fab colored>
    <Icon icon={icon}/>
  </Button>
);

const styles = {
  container: {
    position: 'fixed',
    right: 30,
    bottom: 30
  }
};
<commit_msg>Moved fab in front of the cards<commit_after>
import { h } from 'preact';
import { Button, Icon } from 'preact-mdl';

export default ({ icon, onClick }) => (
  <Button style={styles.container} onClick={onClick} fab colored>
    <Icon icon={icon}/>
  </Button>
);

const styles = {
  container: {
    position: 'fixed',
    right: 10,
    bottom: 10,
    zIndex: 2
  }
};
<|endoftext|>


<commit_before>OMAR.models.Map = Backbone.Model.extend({

});

OMAR.views.Map = Backbone.View.extend({
    el:"#map",
     initialize:function(params){
        this.setElement(this.el);
         if(params.theme)
         {
             this.theme = params.theme;
         }
         else
         {
             this.theme = null;
         }
     },
    reset:function()
    {
        if(this.map)
        {
            this.map.destroy();
            this.map = null;
        }
        if(this.el)
        {
            this.map = new OpenLayers.Map({
                div: this.el,
                theme:this.theme,
                layers: [
                    new OpenLayers.Layer.WMS( "OpenLayers WMS",
                        "http://vmap0.tiles.osgeo.org/wms/vmap0",
                        {layers: 'basic'} )
                ],
                controls: [
                    new OpenLayers.Control.Navigation({
                        dragPanOptions: {
                            enableKinetic: true
                        }
                    }),
                    new OpenLayers.Control.PanZoom(),
                    new OpenLayers.Control.Attribution()
                ],
                center: [0, 0],
                zoom: 3
            });

            this.map.addControl(new OpenLayers.Control.LayerSwitcher());

            this.map.events.register("moveend", this, this.setCenter);
            this.map.events.register("moveend", this, this.setExtent);
            this.map.events.register("mousemove", this, this.setMouse);

            this.map.zoomToMaxExtent();
        }
    },
    setCenter:function()
    {

        //alert("setCenter");
    },
    setExtent:function()
    {
        if(this.bboxModel)
        {
            this.bboxModel.off("change", this.bboxMapChanged, this);
            var extent = this.map.getExtent();
            this.bboxModel.set({"minx":extent.left, "miny":extent.bottom,
                                "maxx":extent.right, "maxy":extent.top});
            this.bboxModel.on("change", this.bboxMapChanged, this);
        }
    },
    setMouse:function(evt)
    {

    },
    setBboxModel:function(bboxModel)
    {
        if(this.bboxModel)
        {
            // may want to unregister change listener of old model
            this.bboxModel.off("change", this.bboxMapChanged,this);
        }
        this.bboxModel = bboxModel;
        if(this.bboxModel)
        {
            this.bboxModel.on("change", this.bboxMapChanged, this);
        }
    },

    bboxMapChanged:function()
    {
        alert(this.bboxModel.get("minx"));

    },
    render:function()
    {
       this.reset();
    }
});

<commit_msg>Added code for point model, grid layers, dd mouse over location, etc.<commit_after>OMAR.models.Map = Backbone.Model.extend({

});

OMAR.views.Map = Backbone.View.extend({
    el:"#map",
    initialize:function(params){
        this.setElement(this.el);
        if(params.theme)
        {
            this.theme = params.theme;
        }
        else
        {
            this.theme = null;
        }
    },
    reset:function()
    {
        if(this.map)
        {
            this.map.destroy();
            this.map = null;
        }
        if(this.el)
        {
            this.map = new OpenLayers.Map({
                div: this.el,
                theme:this.theme,
                layers: [
                    new OpenLayers.Layer.WMS( "OpenLayers WMS",
                        "http://vmap0.tiles.osgeo.org/wms/vmap0",
                        {layers: 'basic'} )
                ],
                controls: [
                    new OpenLayers.Control.Navigation({
                        dragPanOptions: {
                            enableKinetic: true
                        }
                    }),
                    new OpenLayers.Control.PanZoom(),
                    new OpenLayers.Control.Attribution(),
                    new OpenLayers.Control.Scale(),
                    new OpenLayers.Control.ScaleLine(),
                    new OpenLayers.Control.Graticule({
                        visible:false,
                        numPoints:2,
                        layerName:"DD Graticule",
                        labelled:true,
                        labelFormat:"dd",
                        lineSymbolizer:{strokeColor:"#4169E1", strokeOpacity:"0.7", strokeWidth:"1"},
                        labelSymbolizer:{fontColor:"#4169E1", fontOpacity:"0.7"}
                    }),
                    new OpenLayers.Control.Graticule({
                        visible:false,
                        numPoints:2,
                        layerName:"DMS Graticule",
                        labelled:true,
                        labelFormat:"dms",
                        lineSymbolizer:{strokeColor:"#4169E1", strokeOpacity:"0.7", strokeWidth:"1"},
                        labelSymbolizer:{fontColor:"#4169E1", fontOpacity:"0.7"}
                    })
                ],
                center: [0, 0],
                zoom: 3
            });

            this.map.addControl(new OpenLayers.Control.LayerSwitcher());

            this.map.events.register("moveend", this, this.setCenter);
            this.map.events.register("moveend", this, this.setExtent);
            this.map.events.register("mousemove", this, this.setMouse);

            this.map.zoomToMaxExtent();
        }
    },
    setCenter:function()
    {
        if(this.pointModel)
        {
            this.pointModel.off("change", this.pointModelChanged, this);
            var center = this.map.getCenter();
            this.pointModel.set({"lat":center.lat, "lon":center.lon});
            this.pointModel.on("change", this.pointModelChanged, this);
        }

    },
    setExtent:function()
    {
        if(this.bboxModel)
        {
            this.bboxModel.off("change", this.bboxMapChanged, this);
            var extent = this.map.getExtent();
            this.bboxModel.set({"minx":extent.left, "miny":extent.bottom,
                                "maxx":extent.right, "maxy":extent.top});
            this.bboxModel.on("change", this.bboxMapChanged, this);
        }
    },
    setMouse:function(evt)
    {
        var mouse = this.map.getLonLatFromViewPortPx(new OpenLayers.Pixel(evt.xy.x, evt.xy.y));

        var ddMouse = document.getElementById("ddMouse");
        if (mouse.lat < "90" && mouse.lat > "-90" && mouse.lon < "180" && mouse.lon > "-180")
        {
            ddMouse.innerHTML = "DD: " + mouse.lat + ", " + mouse.lon;
        }
        else
        {
            ddMouse.innerHTML = "DD: Outside of geographic extent.";
        }
    },

    setBboxModel:function(bboxModel)
    {
        if(this.bboxModel)
        {
            // may want to unregister change listener of old model
            this.bboxModel.off("change", this.bboxMapChanged,this);
        }
        this.bboxModel = bboxModel;
        if(this.bboxModel)
        {
            this.bboxModel.on("change", this.bboxMapChanged, this);
        }
    },

    bboxMapChanged:function()
    {
        alert(this.bboxModel.get("minx"));

    },
    render:function()
    {
       this.reset();
    }
});

<|endoftext|>


<commit_before>define('homeController', ['app', 'Uploader', 'UploadVideoCover', 'factories', 'less!homeStyle'], function(app, Uploader, UploadVideoCover){

  app

  .controller('home', function($scope, $http){
    $scope.tab = [];
    for (var i = 0; i < 6; ++i)
      $scope.tab[i] = {};
    $scope.changeTab = function(tabIndex){
      for (var i = 0; i < 6; ++i)
        $scope.tab[i].isActive = false;
      $scope.tab[tabIndex].isActive = true;
    }
    $scope.changeTab(4);

  })

  .controller('tab2', function($scope, $http){
  })

  .controller('tab4', ['$scope', '$http', 'collectionUrl', 'apiUrl', function($scope, $http, collectionUrl, apiUrl){
    $scope.videofiles = [];
	$scope.allvideofiles = [];
    $scope.changeVideoFiles = function() {
		for (var i=0; i<$scope.videofiles.length; i++) {
            /* state:
                  0: set up
                  1: uploading
                  2: uploaded
                  -1: failed
             */
			$scope.allvideofiles.push({
              file: $scope.videofiles[i],
              name: $scope.videofiles[i].name,
              state: 0,
                progress: {
                    checksum: 0,
                    upload: 0
                },
              upload: function() {
                  var ngfileobj = this;
                  ngfileobj.state = 1;
                  var uploadinst = new Uploader(ngfileobj.file,
                      function(obj){
                          ngfileobj.progress.checksum = obj.checksumprog;
                          ngfileobj.progress.upload = obj.uploadprog;
                      },
                      {
                          url: apiUrl + '/',
                          filename: ngfileobj.name
                      },
                      function(){
                          ngfileobj.state = 2;
                          $scope.$apply();
                      },
                      function(err){
                          console.log(err);
                          ngfileobj.state = -1;
                          $scope.$apply();
                      });
              }
            });
		}
		console.log($scope.allvideofiles);
	};

    $scope.videoCover = [];
    uploadVideoCover = new UploadVideoCover(document.getElementById('video-cover'), document.getElementById('video-cover-preview'));
    $http.get(collectionUrl + 'is_member_of')
    .success(function(res){
      console.log(res);
    })
  }]);

});
<commit_msg>upload<commit_after>define('homeController', ['app', 'Uploader', 'UploadVideoCover', 'factories', 'less!homeStyle'], function(app, Uploader, UploadVideoCover){

  app

  .controller('home', function($scope, $http){
    $scope.tab = [];
    for (var i = 0; i < 6; ++i)
      $scope.tab[i] = {};
    $scope.changeTab = function(tabIndex){
      for (var i = 0; i < 6; ++i)
        $scope.tab[i].isActive = false;
      $scope.tab[tabIndex].isActive = true;
    }
    $scope.changeTab(4);

  })

  .controller('tab2', function($scope, $http){
  })

  .controller('tab4', ['$scope', '$http', 'collectionUrl', 'apiUrl', function($scope, $http, collectionUrl, apiUrl){
    $scope.videofiles = [];
	$scope.allvideofiles = [];
    $scope.uploadQueue = [];
    $scope.uploadCounts = 0;
      $scope.uploadnext = function() {
          while ($scope.uploadCounts < 1) {
              if ($scope.uploadQueue.length != 0) {
                  $scope.uploadQueue[0].upload();
                  $scope.uploadQueue.splice(0,1);
              } else break;
          }
      };
    $scope.changeVideoFiles = function() {
		for (var i=0; i<$scope.videofiles.length; i++) {
            /* state:
                  0: set up
                  1: queued up
                  2: checksum
                  3: upload
                  4: succeeded
                  999: failed
             */
			$scope.allvideofiles.push({
              file: $scope.videofiles[i],
              name: $scope.videofiles[i].name,
              state: 0,
                progress: {
                    checksum: 0,
                    upload: 0
                },
                queue: function() {
                    this.state = 1;
                    $scope.uploadQueue.push(this);
                    $scope.uploadnext();
                },
              upload: function() {
                  $scope.uploadCounts++;
                  var ngfileobj = this;
                  ngfileobj.state = 2;
                  var uploadinst = new Uploader(ngfileobj.file,
                      function(obj){
                          ngfileobj.progress.checksum = obj.checksumprog;
                          ngfileobj.progress.upload = obj.uploadprog;
                          if (obj.checksumprog == 100) {
                              ngfileobj.state = 3;
                              $scope.$apply();
                          }
                      },
                      {
                          url: apiUrl + '/',
                          filename: ngfileobj.name,
                          collection: 'test'
                      },
                      function(){
                          ngfileobj.state = 4;
                          $scope.$apply();
                          $scope.uploadCounts--;
                          $scope.uploadnext();
                      },
                      function(err){
                          console.log(err);
                          ngfileobj.state = 999;
                          $scope.$apply();
                          $scope.uploadCounts--;
                          $scope.uploadnext();
                      });
              },
                remove: function() {
                    var index = 0;
                    for (; index < $scope.allvideofiles.length; index++) {
                        if ($scope.allvideofiles[index] === this) {
                            break;
                        }
                    }
                    console.log(index);
                    if (index < $scope.allvideofiles.length) {
                        $scope.allvideofiles.splice(index, 1);
                    }
                }
            });
		}
		console.log($scope.allvideofiles);
	};
    $scope.uploadall = function() {
      $scope.allvideofiles.map(function(f){f.queue();});
    };
    $scope.videoCover = [];
    uploadVideoCover = new UploadVideoCover(document.getElementById('video-cover'), document.getElementById('video-cover-preview'));
    $http.get(collectionUrl + 'is_member_of')
    .success(function(res){
      console.log(res);
    })
  }]);

});
<|endoftext|>