<commit_before>(function($, window, undefined){

	"use strict";

	var images, Images = function() {
		images = this;
		this.initalized();
	};
	Images.prototype = {
		initalized: function() {
			// 変数定義
			this.canvas = $('#canvas')[0];
			this.context = canvas.getContext('2d');
			this.originData = null;
			this.image = new Image();
			this.image.onload = $.proxy(this.onloadImage, this);
			this.reader = new FileReader();
			this.reader.onload = $.proxy(this.onloadReader, this);
			this.file = null;

			// jQueryイベント
			$(document)
				.on('change', '#file', $.proxy(this.changeFile, this))
				.on('click', '#canvas', $.proxy(this.getColorClick, this))
				.on('click', '#reset', $.proxy(this.renderOriginalImage, this))
				.on('click', '#brightness', $.proxy(this.renderGrayScale, this, 'brightness'))
				.on('click', '#saturation', $.proxy(this.renderGrayScale, this, 'saturation'))
				.on('click', '#average', $.proxy(this.renderGrayScale, this, 'average'));
		},
		// ---------------------------------------------------------------------------------------------
		// FileReader().onload
		// ---------------------------------------------------------------------------------------------
		onloadReader: function(file) {
			console.log('#### onloadReader ####');
			var dataUrl = file.target.result;
			this.image.src = dataUrl;
		},
		// ---------------------------------------------------------------------------------------------
		// Image().onload
		// ---------------------------------------------------------------------------------------------
		onloadImage: function() {
			console.log('#### onloadImage ####');
			// 画像のサイズを変更
			this.canvas.width = this.image.width;
			this.canvas.height = this.image.height;
			// 画像を描画
			this.context.drawImage(this.image, 0, 0);
			this.originData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
		},
		// ---------------------------------------------------------------------------------------------
		// [jq] 入力ファイルの変更
		// ---------------------------------------------------------------------------------------------
		changeFile: function(event) {
			console.log('#### changeFile ####');
			// ファイルを読み込み
			this.file = event.target.files[0];
			console.log(this.file);
			this.reader.readAsDataURL(this.file);
		},
		// ---------------------------------------------------------------------------------------------
		// ---------------------------------------------------------------------------------------------
		getColorClick: function(event) {
			var pos = $('#canvas').position();
			var x = event.pageX - pos.left;
			var y = event.pageY - pos.top;
			var color = this.getPixelColor(x, y);
			var luminance = this.getLuminance(color);
			console.log(color);
		},
		// ---------------------------------------------------------------------------------------------
		// 画素値の取得
		// ---------------------------------------------------------------------------------------------
		getPixelColor: function(x, y) {
			var pixel = this.context.getImageData(x, y, 1, 1);
			var color = { r: pixel.data[0], g: pixel.data[1], b: pixel.data[2] };
			return color;
		},
		// ---------------------------------------------------------------------------------------------
		// 輝度の取得
		// ---------------------------------------------------------------------------------------------
		getLuminance: function(color) {
			// NTSC加重平均
			var luminance = Math.floor(0.298912 * color.r + 0.586611 * color.g + 0.114478 * color.b);
			return luminance;
		},
		// ---------------------------------------------------------------------------------------------
		// 彩度の取得
		// ---------------------------------------------------------------------------------------------
		getSaturation: function(color) {
			var max = Math.max(color.r, color.g, color.b);
			var min = Math.min(color.r, color.g, color.b);
			var saturation = (max + min) / 2;
			return saturation;
		},
		// ---------------------------------------------------------------------------------------------
		// RGBの平均値
		// ---------------------------------------------------------------------------------------------
		getAverage: function(color) {
			var average = Math.floor((color.r + color.g + color.b) / 3)
			return average;
		},
		// ---------------------------------------------------------------------------------------------
		// 元の画像を表示
		// ---------------------------------------------------------------------------------------------
		renderOriginalImage: function() {
			if ( this.originData !== null ) {
				this.context.putImageData(this.originData, 0, 0);
			}
		},
		// ---------------------------------------------------------------------------------------------
		// グレースケール化
		// ---------------------------------------------------------------------------------------------
		renderGrayScale: function(mode) {
			// 新しく作る画像の準備
			var create = this.context.createImageData(this.canvas.width, this.canvas.height);
			// 今描画している画像のデータを取得
			// var origin = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
			// 元々の画像からデータを取得
			var origin = this.originData;
			var get = null;
			switch(mode) {
				// 輝度
				case 'brightness':
					get = this.getLuminance;
					break;
				// 彩度
				case 'saturation':
					get = this.getSaturation;
					break;
				// 単純平均法
				case 'average':
					get = this.getAverage;
					break;
				default:
					get = this.getLuminance;
					break;
			}
			for( var i = 0; i < origin.data.length/4; i++ ) {
				var p = i*4;
				// 画素値を取得
				var value = get({ r: origin.data[p], g: origin.data[p+1], b: origin.data[p+2] });
				// 冗長だが Uint8ClampedArray に対して push() は出来ないようだ
				create.data[p+0] = value;
				create.data[p+1] = value;
				create.data[p+2] = value;
				create.data[p+3] = 255;
			}
			// 作成した画像に置き換え
			this.context.putImageData(create, 0, 0);
		}
	};

	$(document).ready(function($) {
		new Images();
	});

})(jQuery, window, undefined);<commit_msg>閾値による2値化処理の関数を追加<commit_after>(function($, window, undefined){

	"use strict";

	var images, Images = function() {
		images = this;
		this.initalized();
	};
	Images.prototype = {
		initalized: function() {
			// 変数定義
			this.canvas = $('#canvas')[0];
			this.context = canvas.getContext('2d');
			this.originData = null;
			this.image = new Image();
			this.image.onload = $.proxy(this.onloadImage, this);
			this.reader = new FileReader();
			this.reader.onload = $.proxy(this.onloadReader, this);
			this.file = null;

			// jQueryイベント
			$(document)
				.on('change', '#file', $.proxy(this.changeFile, this))
				.on('click', '#canvas', $.proxy(this.getColorClick, this))
				.on('click', '#reset', $.proxy(this.renderOriginalImage, this))
				.on('click', '#brightness', $.proxy(this.renderGrayScale, this, 'brightness'))
				.on('click', '#saturation', $.proxy(this.renderGrayScale, this, 'saturation'))
				.on('click', '#average', $.proxy(this.renderGrayScale, this, 'average'));
		},
		// ---------------------------------------------------------------------------------------------
		// FileReader().onload
		// ---------------------------------------------------------------------------------------------
		onloadReader: function(file) {
			console.log('#### onloadReader ####');
			var dataUrl = file.target.result;
			this.image.src = dataUrl;
		},
		// ---------------------------------------------------------------------------------------------
		// Image().onload
		// ---------------------------------------------------------------------------------------------
		onloadImage: function() {
			console.log('#### onloadImage ####');
			// 画像のサイズを変更
			this.canvas.width = this.image.width;
			this.canvas.height = this.image.height;
			// 画像を描画
			this.context.drawImage(this.image, 0, 0);
			this.originData = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
		},
		// ---------------------------------------------------------------------------------------------
		// [jq] 入力ファイルの変更
		// ---------------------------------------------------------------------------------------------
		changeFile: function(event) {
			console.log('#### changeFile ####');
			// ファイルを読み込み
			this.file = event.target.files[0];
			console.log(this.file);
			this.reader.readAsDataURL(this.file);
		},
		// ---------------------------------------------------------------------------------------------
		// ---------------------------------------------------------------------------------------------
		getColorClick: function(event) {
			var pos = $('#canvas').position();
			var x = event.pageX - pos.left;
			var y = event.pageY - pos.top;
			var color = this.getPixelColor(x, y);
			var luminance = this.getLuminance(color);
			console.log(color);
		},
		// ---------------------------------------------------------------------------------------------
		// 画素値の取得
		// ---------------------------------------------------------------------------------------------
		getPixelColor: function(x, y) {
			var pixel = this.context.getImageData(x, y, 1, 1);
			var color = { r: pixel.data[0], g: pixel.data[1], b: pixel.data[2] };
			return color;
		},
		// ---------------------------------------------------------------------------------------------
		// 輝度の取得
		// ---------------------------------------------------------------------------------------------
		getLuminance: function(color) {
			// NTSC加重平均
			var luminance = Math.floor(0.298912 * color.r + 0.586611 * color.g + 0.114478 * color.b);
			return luminance;
		},
		// ---------------------------------------------------------------------------------------------
		// 彩度の取得
		// ---------------------------------------------------------------------------------------------
		getSaturation: function(color) {
			var max = Math.max(color.r, color.g, color.b);
			var min = Math.min(color.r, color.g, color.b);
			var saturation = (max + min) / 2;
			return saturation;
		},
		// ---------------------------------------------------------------------------------------------
		// RGBの平均値
		// ---------------------------------------------------------------------------------------------
		getAverage: function(color) {
			var average = Math.floor((color.r + color.g + color.b) / 3)
			return average;
		},
		// ---------------------------------------------------------------------------------------------
		// 元の画像を表示
		// ---------------------------------------------------------------------------------------------
		renderOriginalImage: function() {
			if ( this.originData !== null ) {
				this.context.putImageData(this.originData, 0, 0);
			}
		},
		// ---------------------------------------------------------------------------------------------
		// グレースケール化
		// ---------------------------------------------------------------------------------------------
		renderGrayScale: function(mode) {
			// 新しく作る画像の準備
			var create = this.context.createImageData(this.canvas.width, this.canvas.height);
			// 今描画している画像のデータを取得
			// var origin = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);
			// 元々の画像からデータを取得
			var origin = this.originData;
			var get = null;
			switch(mode) {
				// 輝度
				case 'brightness':
					get = this.getLuminance;
					break;
				// 彩度
				case 'saturation':
					get = this.getSaturation;
					break;
				// 単純平均法
				case 'average':
					get = this.getAverage;
					break;
				default:
					get = this.getLuminance;
					break;
			}
			for( var i = 0; i < origin.data.length/4; i++ ) {
				var p = i*4;
				// 画素値を取得
				var value = get({ r: origin.data[p], g: origin.data[p+1], b: origin.data[p+2] });
				// 冗長だが Uint8ClampedArray に対して push() は出来ないようだ
				create.data[p+0] = value;
				create.data[p+1] = value;
				create.data[p+2] = value;
				create.data[p+3] = 255;
			}
			// 作成した画像に置き換え
			this.context.putImageData(create, 0, 0);
		},
		// ---------------------------------------------------------------------------------------------
		// 閾値による2値化
		// ---------------------------------------------------------------------------------------------
		renderThresholdImage: function(value) {

			var create = this.context.createImageData(this.canvas.width, this.canvas.height);
			var origin = this.context.getImageData(0, 0, this.canvas.width, this.canvas.height);

			for( var i = 0; i < origin.data.length/4; i++ ) {
				var p = i*4;
				// 画素値を取得
				if ( ! (origin.data[p] === origin.data[p+1] && origin.data[p] === origin.data[p+2]) ) {
					console.error("Please input gray scale image.");
					return;
				}
				var pixel = origin.data[p];
				if ( pixel > value ) {
					create.data[p+0] = 255;
					create.data[p+1] = 255;
					create.data[p+2] = 255;
				}
				else {
					create.data[p+0] = 0;
					create.data[p+1] = 0;
					create.data[p+2] = 0;
				}
				create.data[p+3] = 255;
			}
			// 作成した画像に置き換え
			this.context.putImageData(create, 0, 0);
		}
	};

	$(document).ready(function($) {
		new Images();
	});

})(jQuery, window, undefined);<|endoftext|>


<commit_before>#!/usr/bin/env headstone
var async = require('async');
var keystone = require('keystone');
var fs = require('fs');
var path = require('path');

var Page = keystone.list('Page'),
  Media = keystone.list('Media');

function find(startPath,filter) {
  var res = [];
  if (!fs.existsSync(startPath)) {
    console.log('no dir ', startPath);
    return null;
  }

  var files=fs.readdirSync(startPath);
  for (var i=0;i<files.length;i++) {
    var filename=path.join(startPath,files[i]);
    if (filename.indexOf(filter)>=0) {
      res.push(filename);
    };
  };

  return res;
}

module.exports = function(done) {
  var pageFiles = find('../db/pages', '.json');
  var mediaFiles = find('../db/media', '.json');

  async.waterfall(
    mediaFiles.map((mediaFile) => (callback) => {
      var mediaData = JSON.parse(fs.readFileSync(mediaFile));

      Media.model.findOne({slug: mediaData.slug})
        .exec((findErr, media) => {
          if (findErr)
            return callback(findErr);

          if (media) {
            var time1 = new Date(media.updatedAt).getTime();
            var time2 = new Date(mediaData.updatedAt).getTime();

            if (mediaData.updatedAt && time1 === time2)
              return callback(null);
          }

          return Media.model.update(
            {slug: mediaData.slug},
            mediaData,
            {upsert: true},
            (err) => {
              console.log('Updated media "' + mediaData.slug + '"');
              return callback(err);
            }
          );
        });
    }),
    (err, result) => {
      async.waterfall(
        pageFiles.map((pageFile) => (callback) => {
          var pageData = JSON.parse(fs.readFileSync(pageFile));

          Page.model.findOne({slug: pageData.slug})
            .exec((findErr, page) => {
              if (findErr)
                return callback(findErr);

              if (page) {
                var time1 = new Date(page.updatedAt).getTime();
                var time2 = new Date(pageData.updatedAt).getTime();

                if (pageData.updatedAt && time1 === time2)
                  return callback(null);
              }

              if (pageData.contentType === 'HTML')
                pageData.html = fs.readFileSync('./db/pages/' + pageData.slug + '.html', 'utf8');
              else
                pageData.markdown = { md : fs.readFileSync('./db/pages/' + pageData.slug + '.md', 'utf8')};

              return Page.model.update(
                {slug: pageData.slug},
                pageData,
                {upsert: true},
                (updateErr) => {
                  console.log('Updated page "' + pageData.slug + '"');
                  return callback(updateErr);
                }
              );
            });
        }),
        done
      );
    }
  );
}
<commit_msg>Fix uncaught exception causing the import-pages.js script to never end.<commit_after>#!/usr/bin/env headstone
var async = require('async');
var keystone = require('keystone');
var fs = require('fs');
var path = require('path');

var Page = keystone.list('Page'),
  Media = keystone.list('Media');

function find(startPath,filter) {
  var res = [];
  if (!fs.existsSync(startPath)) {
    console.log('no dir ', startPath);
    return null;
  }

  var files=fs.readdirSync(startPath);
  for (var i=0;i<files.length;i++) {
    var filename=path.join(startPath,files[i]);
    if (filename.indexOf(filter)>=0) {
      res.push(filename);
    };
  };

  return res;
}

module.exports = function(done) {
  var pageFiles = find('../db/pages', '.json');
  var mediaFiles = find('../db/media', '.json');

  async.waterfall(
    mediaFiles.map((mediaFile) => (callback) => {
      var mediaData = JSON.parse(fs.readFileSync(mediaFile));

      Media.model.findOne({slug: mediaData.slug})
        .exec((findErr, media) => {
          if (findErr)
            return callback(findErr);

          if (media) {
            var time1 = new Date(media.updatedAt).getTime();
            var time2 = new Date(mediaData.updatedAt).getTime();

            if (mediaData.updatedAt && time1 === time2)
              return callback(null);
          }

          return Media.model.update(
            {slug: mediaData.slug},
            mediaData,
            {upsert: true},
            (err) => {
              console.log('Updated media "' + mediaData.slug + '"');
              return callback(err);
            }
          );
        });
    }),
    (err, result) => {
      async.waterfall(
        pageFiles.map((pageFile) => (callback) => {
          var pageData = JSON.parse(fs.readFileSync(pageFile));

          Page.model.findOne({slug: pageData.slug})
            .exec((findErr, page) => {
              if (findErr)
                return callback(findErr);

              if (page) {
                var time1 = new Date(page.updatedAt).getTime();
                var time2 = new Date(pageData.updatedAt).getTime();

                if (pageData.updatedAt && time1 === time2)
                  return callback(null);
              }

              if (pageData.contentType === 'HTML')
                pageData.html = fs.readFileSync('../db/pages/' + pageData.slug + '.html', 'utf8');
              else
                pageData.markdown = { md : fs.readFileSync('../db/pages/' + pageData.slug + '.md', 'utf8')};

              return Page.model.update(
                {slug: pageData.slug},
                pageData,
                {upsert: true},
                (updateErr) => {
                  console.log('Updated page "' + pageData.slug + '"');
                  return callback(updateErr);
                }
              );
            });
        }),
        done
      );
    }
  );
}
<|endoftext|>


<commit_before>/**************************************************************************************************
 * Module name: Patient
 * Author(s): Sean malone
 * Description: This module is used to query the database.
 *************************************************************************************************/
define(function(require) {
	/**********************************************************************************************
	 * Constructor
	 *********************************************************************************************/
	var patient = function() {};

	/**********************************************************************************************
	 * Get Methods
	 *
	 * These methods retrieve information from the database via SELECT queries
	 *********************************************************************************************/
	// Get All Patients
	patient.prototype.getPatients = function() {
		return this.query({
			mode: 'select',
			table: 'patient',
			fields: '*'
		});
	}

	// Get Personal Information for a Single Patient
	patient.prototype.getPatient = function(id) {
		return this.query({
			mode: 'select',
			table: 'patient',
			fields: '*',
			where: "WHERE id='" + id + "'"
		});
	}

	// Get All Insurances for a Single Patient
	patient.prototype.getInsurance = function(id) {
		return this.query({
			mode: 'select',
			table: 'insurance',
			fields: '*',
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Get Guarantor for a Single Patient
	patient.prototype.getGuarantor = function(id) {
		return this.query({
			mode: 'select',
			table: 'guarantor',
			fields: '*',
			where: "WHERE patient_id='" + id + "'"
		});
	}

	/**********************************************************************************************
	 * Add Methods
	 *
	 * These methods add information to the database via INSERT queries
	 *********************************************************************************************/
	// Add Personal Information for a Single Patient
	patient.prototype.addPatient = function(id, data) {
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'insert',
			table: 'patient',
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Add Insurance for a Single Patient
	patient.prototype.addInsurance = function(id, data) {
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'insert',
			table: 'insurance',
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Add Guarantor for a Single Patient
	patient.prototype.addGuarantor = function(id, data) {
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'insert',
			table: 'guarantor',
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	/**********************************************************************************************
	 * Update Methods
	 *
	 * These methods update information in the database via UPDATE queries
	 *********************************************************************************************/
	// Update Personal Information for a Single Patient
	patient.prototype.updatePatient = function(id, data) {
		var fields = Object.keys(data);
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'update',
			table: 'patient',
			fields: fields,
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Update Insurance for a Single Patient
	patient.prototype.updateInsurance = function(id, data) {
		var fields = Object.keys(data);
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'update',
			table: 'insurance',
			fields: fields,
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Update Guarantor for a Single Patient
	patient.prototype.updateGuarantor = function(id, data) {
		var fields = Object.keys(data);
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'update',
			table: 'guarantor',
			fields: fields,
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	/**********************************************************************************************
	 * remove Methods
	 *
	 * These methods remove information from the database via DELETE queries
	 *********************************************************************************************/
	// Delete Personal Information for a Single Patient
	patient.prototype.deletePatient = function(id) {
		return this.query({
			mode: 'delete',
			table: 'patient',
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Delete Insurance for a Single Patient
	patient.prototype.deleteInsurance = function(id) {
		return this.query({
			mode: 'delete',
			table: 'insurance',
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Delete Guarantor for a Single Patient
	patient.prototype.deleteGuarantor = function(id) {
		return this.query({
			mode: 'delete',
			table: 'guarantor',
			where: "WHERE patient_id='" + id + "'"
		});
	}
	/**********************************************************************************************
	 * Query
	 *
	 * This method is used by all other methods to execute the ajax call.
	 *********************************************************************************************/
	patient.prototype.query = function(data) {
		return $.getJSON('php/query.php',data);
	}

	/**************************************************************************************************
	 * Return class so it is usable.
	 *************************************************************************************************/
	return patient;
});<commit_msg>Update patient module.<commit_after>/**************************************************************************************************
 * Module name: Patient
 * Author(s): Sean malone
 * Description: This module is used to query the database.
 *************************************************************************************************/
define(function(require) {
	/**********************************************************************************************
	 * Constructor
	 *********************************************************************************************/
	var patient = function() {};

	/**********************************************************************************************
	 * Get Methods
	 *
	 * These methods retrieve information from the database via SELECT queries
	 *********************************************************************************************/
	// Get All Patients
	patient.prototype.getPatients = function() {
		return this.query({
			mode: 'select',
			table: 'patient',
			fields: '*'
		});
	}

	// Get Personal Information for a Single Patient
	patient.prototype.getPatient = function(id) {
		return this.query({
			mode: 'select',
			table: 'patient',
			fields: '*',
			where: "WHERE id='" + id + "'"
		});
	}

	// Get All Insurances for a Single Patient
	patient.prototype.getInsurance = function(id) {
		return this.query({
			mode: 'select',
			table: 'insurance',
			fields: '*',
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Get Guarantor for a Single Patient
	patient.prototype.getGuarantor = function(id) {
		return this.query({
			mode: 'select',
			table: 'guarantor',
			fields: '*',
			where: "WHERE patient_id='" + id + "'"
		});
	}

	/**********************************************************************************************
	 * Add Methods
	 *
	 * These methods add information to the database via INSERT queries
	 *********************************************************************************************/
	// Add Personal Information for a Single Patient
	patient.prototype.addPatient = function(id, data) {
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'insert',
			table: 'patient',
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Add Insurance for a Single Patient
	patient.prototype.addInsurance = function(id, data) {
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'insert',
			table: 'insurance',
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Add Guarantor for a Single Patient
	patient.prototype.addGuarantor = function(id, data) {
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'insert',
			table: 'guarantor',
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	/**********************************************************************************************
	 * Update Methods
	 *
	 * These methods update information in the database via UPDATE queries
	 *********************************************************************************************/
	// Update Personal Information for a Single Patient
	patient.prototype.updatePatient = function(id, data) {
		var fields = Object.keys(data);
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'update',
			table: 'patient',
			fields: fields,
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Update Insurance for a Single Patient
	patient.prototype.updateInsurance = function(id, data) {
		var fields = Object.keys(data);
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'update',
			table: 'insurance',
			fields: fields,
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Update Guarantor for a Single Patient
	patient.prototype.updateGuarantor = function(id, data) {
		var fields = Object.keys(data);
		var values = $.map(data, function(k,v) {
			return [k];
		});

		return this.query({
			mode: 'update',
			table: 'guarantor',
			fields: fields,
			values: values,
			where: "WHERE patient_id='" + id + "'"
		});
	}

	/**********************************************************************************************
	 * Remove Methods
	 *
	 * These methods remove information from the database via DELETE queries
	 *********************************************************************************************/
	// Delete Personal Information for a Single Patient
	patient.prototype.deletePatient = function(id) {
		return this.query({
			mode: 'delete',
			table: 'patient',
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Delete Insurance for a Single Patient
	patient.prototype.deleteInsurance = function(id) {
		return this.query({
			mode: 'delete',
			table: 'insurance',
			where: "WHERE patient_id='" + id + "'"
		});
	}

	// Delete Guarantor for a Single Patient
	patient.prototype.deleteGuarantor = function(id) {
		return this.query({
			mode: 'delete',
			table: 'guarantor',
			where: "WHERE patient_id='" + id + "'"
		});
	}
	/**********************************************************************************************
	 * Query
	 *
	 * This method is used by all other methods to execute the ajax call.
	 *********************************************************************************************/
	patient.prototype.query = function(data) {
		return $.getJSON('php/query.php',data);
	}

	/**************************************************************************************************
	 * Return class so it is usable.
	 *************************************************************************************************/
	return patient;
});<|endoftext|>


<commit_before>/* jshint -W003,-W004, -W038, -W117 */

(function () {

    'use strict';
    angular
            .module('newplayer')
            .directive('npLayer', NpLayer);

    /** @ngInject */
    function NpLayer($log/*,  $timeout*/) {
        $log.debug('NpLayer::Init\n');

        var directive = {
            restrict: 'E',
            scope: {
                manifestId: '@npId',
                manifestURL: '@npUrl',
                overrideURL: '@npOverrideUrl',
                overrideData: '@npOverrideData',
                language: '@npLang'
            },
            //compile: function (tElement, tAttrs, transclude, ConfigService)
            //{
            //  /** @ngInject */
            //  return function ($scope, $element, $attributes)
            //  {
            //    $log.info('ComponentDirective::compile!', $attributes);
            //    var vm = $scope.vm;
            //
            //
            //
            //    parseComponent( $scope, $element, $attributes );
            //  };
            //},
            controller: NpLayerController,
            controllerAs: 'vm',
            bindToController: true
        };

        return directive;
    }

    /** @ngInject */
    function NpLayerController($scope, $rootScope, $element, $attrs, $log, $compile,
            APIService, ComponentService, ConfigService, ManifestService) {
        var vm = this;
        vm.manifestData = null;
        vm.overrideData = null;

        // $rootScope.$on('npLangChanged', npLangChanged);
        // $rootScope.$on('npPageWantsChange', npPageChanged);
        //.on('npManifestChanged', npManifestChanged)

        ConfigService.setConfigData(vm);
        loadManifests();

        //function npManifestChanged(event, toManifest, toPage) {
        //
        //}
        function npLangChanged(event, toLang) {
            $log.info('npLangChanged', event, toLang);
            if (!!toLang) {
                ManifestService.setLang(toLang);
                parseComponent($scope, $element, $attrs, $compile);
            }
        }

        function npPageWantsChange(event, toPage) {
            $log.info('npPageWantsChange', event, toPage);
            if (!!toPage) {
                ManifestService.setPageId(toPage);
                //$element.empty();
                //parseComponent($scope, $element, $attrs, $compile);
            }
        }

        //$log.info('NpLayer ConfigService:', ConfigService);

        /*
         * ---------------- supporting functions INSIDE function to keep scope
         */

        function loadManifests() {
            var manifestURL = ConfigService.getManifestURL();
            APIService.getData(manifestURL).then(function (md) {
                vm.manifestData = md;

                var overrideURL = ConfigService.getOverrideURL();

                if (!!vm.language) {
                    ManifestService.setLang(lang);
                }

                if (!!overrideURL) {
                    $log.info('NpLayer: getting override data from:', overrideURL);
                    ConfigService.getOverrideData(overrideURL).then(function (od) {
                        vm.overrideData = od;
                        renderComponent(vm, $scope, $element, $attrs, $compile);
                    });

                } else {
                    $log.info('NpLayer: init manifest', vm.manifestData);
                    renderComponent(vm, $scope, $element, $attrs, $compile);
                }
            });
        }

        $rootScope.$on('npReplaceManifest', function (obj, newManifest) {
            $log.info('NpLayer:changeManifestTo | ', newManifest);
            ConfigService.setManifestURL(newManifest);
            loadManifests();
        });

        function renderComponent(vm, $scope, $element, $attrs, $compile) {
            $element.empty();
            ManifestService.initialize(vm.manifestData, vm.overrideData);
            parseComponent($scope, $element, $attrs, $compile);
        }

        function parseComponent($scope, $element, $attributes, $compile) {
            var cmp = ManifestService.getComponent($attributes.idx);
            var cmpIdx = cmp.idx || [0];

            $log.debug('NpLayer::parseComponent', cmp, cmpIdx, $attributes);
            if (!!cmp) {

                $log.debug('NpLayer::parseComponent then', cmp, cmpIdx);
                // reset scope!!!
                $scope.subCmp = false;
                $scope.component = cmp;
                $scope.components = null;

                $scope.cmpIdx = cmpIdx.toString();

                $element.attr('data-cmpType', cmp.type);
                $element.addClass('np-cmp-sub');

                if (!!cmp.data) {
                    // set known data values
                    var attrId = cmp.data.id;
                    if (!attrId) {
                        attrId = cmp.type + ':' + cmpIdx.toString();
                    }
                    // id must start with letter (according to HTML4 spec)
                    if (/^[^a-zA-Z]/.test(attrId)) {
                        attrId = 'np' + attrId;
                    }
                    // replace invalid id characters (according to HTML4 spec)
                    attrId = attrId.replace(/[^\w\-.:]/g, '_');
                    //$element.attr( 'id', attrId );
                    if (!cmp.data.id) {
                        cmp.data.id = attrId;
                    }
                    $element.attr('id', 'np_' + attrId);

                    var attrClass = cmp.data['class'];
                    if (angular.isString(attrClass)) {
                        attrClass = attrClass.replace(/[^\w\-.:]/g, '_');
                        $element.addClass('np_' + attrClass);
                    }

                    var attrPlugin = cmp.data.plugin;
                    if (angular.isString(attrPlugin)) {
                        attrPlugin = attrPlugin.replace(/[^\w\-.:]/g, '_');
                    }
                }
                if (!!cmp.components && cmp.components.length > 0) {
                    $log.debug('NpLayer::parseComponent - HAS SUBS:', cmp);
                    $scope.subCmp = true;
                    $scope.components = cmp.components;
                }

                var templateData = ComponentService.getTemplate(cmp);
                $log.debug('npComponent::parseComponent: template', templateData);

                // modify template before compiling!?
                var tmpTemplate = document.createElement('div');
                tmpTemplate.innerHTML = templateData;

                var ngWrapperEl, ngMainEl, ngSubEl;
                ngWrapperEl = angular.element(tmpTemplate.querySelectorAll('.np-cmp-wrapper'));
                ngMainEl = angular.element(tmpTemplate.querySelectorAll('.np-cmp-main'));
                ngSubEl = angular.element(tmpTemplate.querySelectorAll('.np-cmp-sub'));
                if (ngWrapperEl.length) {
                    ngWrapperEl.attr('id', attrId);
                    ngWrapperEl.addClass(attrPlugin);

                    // pass all "data-*" attributes into element
                    angular.forEach(cmp.data, function (val, key) {
                        if (angular.isString(key) && key.indexOf('data-') === 0) {
                            ngWrapperEl.attr(key, val);
                        }
                    });
                }
                if (ngMainEl.length) {
                    if (!ngWrapperEl.length) {
                        ngMainEl.attr('id', attrId);
                        ngMainEl.addClass(attrPlugin);

                        // pass all "data-*" attributes into element
                        angular.forEach(cmp.data, function (val, key) {
                            if (angular.isString(key) && key.indexOf('data-') === 0) {
                                ngMainEl.attr(key, val);
                            }
                        });
                    }
                    ngMainEl.addClass(attrClass);
                }

                var compiledTemplate = $compile(tmpTemplate.innerHTML);
                compiledTemplate($scope, function (clone) {
                    $element.append(clone);
                });

                //  }
                //);
            }
        }
    }

})();
<commit_msg>feat(manifest): 2way binding WIP<commit_after>/* jshint -W003,-W004, -W038, -W117 */

(function () {

    'use strict';
    angular
            .module('newplayer')
            .directive('npLayer', NpLayer);

    /** @ngInject */
    function NpLayer($log/*,  $timeout*/) {
        $log.debug('NpLayer::Init\n');

        var directive = {
            restrict: 'E',
            scope: {
                manifestId: '@npId',
                manifestURL: '@npUrl',
                overrideURL: '@npOverrideUrl',
                overrideData: '@npOverrideData',
                language: '@npLang',
                manifestData: '=?'
            },
            //compile: function (tElement, tAttrs, transclude, ConfigService)
            //{
            //  /** @ngInject */
            //  return function ($scope, $element, $attributes)
            //  {
            //    $log.info('ComponentDirective::compile!', $attributes);
            //    var vm = $scope.vm;
            //
            //
            //
            //    parseComponent( $scope, $element, $attributes );
            //  };
            //},
            controller: NpLayerController,
            controllerAs: 'vm',
            bindToController: true
        };

        return directive;
    }

    /** @ngInject */
    function NpLayerController($scope, $rootScope, $element, $attrs, $log, $compile,
            APIService, ComponentService, ConfigService, ManifestService) {
        var vm = this;
        vm.manifestData = null;
        vm.overrideData = null;

        // $rootScope.$on('npLangChanged', npLangChanged);
        // $rootScope.$on('npPageWantsChange', npPageChanged);
        //.on('npManifestChanged', npManifestChanged)

        ConfigService.setConfigData(vm);
        loadManifests();

        //function npManifestChanged(event, toManifest, toPage) {
        //
        //}
        function npLangChanged(event, toLang) {
            $log.info('npLangChanged', event, toLang);
            if (!!toLang) {
                ManifestService.setLang(toLang);
                parseComponent($scope, $element, $attrs, $compile);
            }
        }

        function npPageWantsChange(event, toPage) {
            $log.info('npPageWantsChange', event, toPage);
            if (!!toPage) {
                ManifestService.setPageId(toPage);
                //$element.empty();
                //parseComponent($scope, $element, $attrs, $compile);
            }
        }

        //$log.info('NpLayer ConfigService:', ConfigService);

        /*
         * ---------------- supporting functions INSIDE function to keep scope
         */

        function loadManifests() {
            var manifestURL = ConfigService.getManifestURL();
            APIService.getData(manifestURL).then(function (md) {
                vm.manifestData = md;

                var overrideURL = ConfigService.getOverrideURL();

                if (!!vm.language) {
                    ManifestService.setLang(lang);
                }

                if (!!overrideURL) {
                    $log.info('NpLayer: getting override data from:', overrideURL);
                    ConfigService.getOverrideData(overrideURL).then(function (od) {
                        vm.overrideData = od;
                        renderComponent(vm, $scope, $element, $attrs, $compile);
                    });

                } else {
                    $log.info('NpLayer: init manifest', vm.manifestData);
                    renderComponent(vm, $scope, $element, $attrs, $compile);
                }
            });
        }

        $rootScope.$on('npReplaceManifest', function (obj, newManifest) {
            $log.info('NpLayer:changeManifestTo | ', newManifest);
            ConfigService.setManifestURL(newManifest);
            loadManifests();
        });

        function renderComponent(vm, $scope, $element, $attrs, $compile) {
            $element.empty();
            ManifestService.initialize(vm.manifestData, vm.overrideData);
            parseComponent($scope, $element, $attrs, $compile);
        }

        function parseComponent($scope, $element, $attributes, $compile) {
            var cmp = ManifestService.getComponent($attributes.idx);
            var cmpIdx = cmp.idx || [0];

            $log.debug('NpLayer::parseComponent', cmp, cmpIdx, $attributes);
            if (!!cmp) {

                $log.debug('NpLayer::parseComponent then', cmp, cmpIdx);
                // reset scope!!!
                $scope.subCmp = false;
                $scope.component = cmp;
                $scope.components = null;

                $scope.cmpIdx = cmpIdx.toString();

                $element.attr('data-cmpType', cmp.type);
                $element.addClass('np-cmp-sub');

                if (!!cmp.data) {
                    // set known data values
                    var attrId = cmp.data.id;
                    if (!attrId) {
                        attrId = cmp.type + ':' + cmpIdx.toString();
                    }
                    // id must start with letter (according to HTML4 spec)
                    if (/^[^a-zA-Z]/.test(attrId)) {
                        attrId = 'np' + attrId;
                    }
                    // replace invalid id characters (according to HTML4 spec)
                    attrId = attrId.replace(/[^\w\-.:]/g, '_');
                    //$element.attr( 'id', attrId );
                    if (!cmp.data.id) {
                        cmp.data.id = attrId;
                    }
                    $element.attr('id', 'np_' + attrId);

                    var attrClass = cmp.data['class'];
                    if (angular.isString(attrClass)) {
                        attrClass = attrClass.replace(/[^\w\-.:]/g, '_');
                        $element.addClass('np_' + attrClass);
                    }

                    var attrPlugin = cmp.data.plugin;
                    if (angular.isString(attrPlugin)) {
                        attrPlugin = attrPlugin.replace(/[^\w\-.:]/g, '_');
                    }
                }
                if (!!cmp.components && cmp.components.length > 0) {
                    $log.debug('NpLayer::parseComponent - HAS SUBS:', cmp);
                    $scope.subCmp = true;
                    $scope.components = cmp.components;
                }

                var templateData = ComponentService.getTemplate(cmp);
                $log.debug('npComponent::parseComponent: template', templateData);

                // modify template before compiling!?
                var tmpTemplate = document.createElement('div');
                tmpTemplate.innerHTML = templateData;

                var ngWrapperEl, ngMainEl, ngSubEl;
                ngWrapperEl = angular.element(tmpTemplate.querySelectorAll('.np-cmp-wrapper'));
                ngMainEl = angular.element(tmpTemplate.querySelectorAll('.np-cmp-main'));
                ngSubEl = angular.element(tmpTemplate.querySelectorAll('.np-cmp-sub'));
                if (ngWrapperEl.length) {
                    ngWrapperEl.attr('id', attrId);
                    ngWrapperEl.addClass(attrPlugin);

                    // pass all "data-*" attributes into element
                    angular.forEach(cmp.data, function (val, key) {
                        if (angular.isString(key) && key.indexOf('data-') === 0) {
                            ngWrapperEl.attr(key, val);
                        }
                    });
                }
                if (ngMainEl.length) {
                    if (!ngWrapperEl.length) {
                        ngMainEl.attr('id', attrId);
                        ngMainEl.addClass(attrPlugin);

                        // pass all "data-*" attributes into element
                        angular.forEach(cmp.data, function (val, key) {
                            if (angular.isString(key) && key.indexOf('data-') === 0) {
                                ngMainEl.attr(key, val);
                            }
                        });
                    }
                    ngMainEl.addClass(attrClass);
                }

                var compiledTemplate = $compile(tmpTemplate.innerHTML);
                compiledTemplate($scope, function (clone) {
                    $element.append(clone);
                });

                //  }
                //);
            }
        }
    }

})();
<|endoftext|>


<commit_before>/**
 * UserService
 *
 * @description :: Server-side logic for managing your account
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */
var _user;
module.exports = {
  current: function(user,origin,request) {
    if(user) _user = user;
    if(request && origin && user && request.session){
      request.session.authenticated = true;
      request.session.origin = origin;
      request.session.user = user;
    }
  },
  me : function (req) {
    if(!req) return _user;
    sails.log.debug('+ Get user',req.session.user);
    return req.session.user || req.user;
  }
};
<commit_msg>USerService set token<commit_after>/**
 * UserService
 *
 * @description :: Server-side logic for managing your account
 * @help        :: See http://links.sailsjs.org/docs/controllers
 */
var _user;
module.exports = {
  current: function(user,origin,request) {
    if(user) _user = user;

    if(!require ('fbgraph').getAccessToken() && !_.isUndefined(request.session.user.token)){
      sails.log.debug('Set token of access');
      require ('fbgraph').setAccessToken(request.session.user.token);
    }

    if(request && origin && user && request.session){
      sails.log.debug('+ Get user',request.session.user);
      request.session.authenticated = true;
      request.session.origin = origin;
      request.session.user = user;
    }
  },
  me : function (req) {
    if(!req) return _user;

    sails.log.debug('+ Get user',req.session.user);
    if(!require ('fbgraph').getAccessToken() && !_.isUndefined(req.session.user.token)){
      sails.log.debug('Set token of access');
      require ('fbgraph').setAccessToken(req.session.user.token);
    }

    return req.session.user || req.user;
  }
};
<|endoftext|>


<commit_before>angular.module("checkoutModule")
/**
 *
 */
    .service("$checkoutService", [
        "$q",
        "$timeout",
        "$interval",
        "$checkoutApiService",
        "ONEPAGE_URL",
        "ACCORDION_URL",
        function ($q, $timeout, $interval, $checkoutApiService, ONEPAGE_URL, ACCORDION_URL) {
            // Variables
            var checkout, allowedShippingMethods, allowedPaymentMethods, defaultType, activeType;

            // Functions
            var init, getUrl, getType, setType, update, loadShippingMethods, loadPaymentMethods,
                saveBillingAddress, saveShippingAddress, saveShippingMethod, savePaymentMethod, discountApply, discountNeglect,
                getCheckout, getAllowedPaymentMethods, getAllowedShippingMethods, saveAdditionalInfo, getAllowedGuestCheckout,
                getMinimalCostShippingMethods;

            checkout = {};
            defaultType = "accordion";

            loadShippingMethods = function () {
                var defer = $q.defer();

                var splitMethodToRates = function (method) {
                    var i, rate;
                    for (i = 0; i < method.Rates.length; i += 1) {
                        rate = method.Rates[i];

                        var methodLabel = method.Name + " - " + rate.Name + " ($" + rate.Price + ")";
                        if (method.Name == 'Flat Rate') {
                            methodLabel = rate.Name + " ($" + rate.Price + ")";
                        }

                        allowedShippingMethods.push({
                            "Name": methodLabel,
                            "Price": rate.Price,
                            "Method": method.Code,
                            "Rate": rate.Code
                        });
                    }
                };

                $checkoutApiService.shippingMethods().$promise.then(function (response) {
                    var i, method;
                    allowedShippingMethods = [];
                    if (response.error === null) {
                        for (i = 0; i < response.result.length; i += 1) {
                            method = response.result[i] || [];
                            if (method.Rates instanceof Array && method.Rates.length > 0) {
                                splitMethodToRates(method);
                            }
                        }
                    }

                    defer.resolve(allowedShippingMethods);
                });

                return defer.promise;
            };

            loadPaymentMethods = function () {
                var defer = $q.defer();
                allowedPaymentMethods = [];
                $checkoutApiService.paymentMethods().$promise.then(function (response) {
                    allowedPaymentMethods = response.result || [];
                    defer.resolve(allowedPaymentMethods);
                });

                return defer.promise;
            };

            // TODO: I THINK THIS CAN BE DELETED
            init = function () {
                var defer, statuses;
                statuses = {
                    "isLoadedSM": false,
                    "isLoadedPM": false
                };
                defer = $q.defer();

                loadShippingMethods().then(function () {
                    statuses.isLoadedSM = true;
                });
                loadPaymentMethods().then(function () {
                    statuses.isLoadedPM = true;
                });

                var stop = $interval(function () {
                    var initAll = true;
                    for (var key in statuses) {
                        if (statuses.hasOwnProperty(key) && !statuses[key]) {
                            initAll = false;
                            break;
                        }
                    }
                    if (initAll) {
                        $interval.cancel(stop);
                        defer.resolve(checkout);
                    }
                }, 100);

                return defer.promise;
            };

            update = function () {
                var defer = $q.defer();

                $checkoutApiService.info().$promise.then(
                    function (response) {
                        checkout = response.result || [];
                        defer.resolve(checkout);
                    }
                );

                return defer.promise;
            };

            saveBillingAddress = function (address) {
                var defer = $q.defer();

                $checkoutApiService.setBillingAddress(address).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            saveShippingAddress = function (address) {
                var defer = $q.defer();

                $checkoutApiService.setShippingAddress(address).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            saveShippingMethod = function (method) {
                var defer = $q.defer();

                $checkoutApiService.setShippingMethod(method).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            savePaymentMethod = function (method) {
                var defer = $q.defer();

                $checkoutApiService.setPaymentMethod(method).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            saveAdditionalInfo = function (data) {
                var defer = $q.defer();

                $checkoutApiService.setInfo(data).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            discountApply = function (data) {
                var defer = $q.defer();

                $checkoutApiService.discountApply(data).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            discountNeglect = function (data) {
                var defer = $q.defer();

                $checkoutApiService.discountNeglect(data).$promise.then(
                    function (response) {
                        if (response.error === null) {
                            defer.resolve(response);
                        }
                    }
                );

                return defer.promise;
            };

            getUrl = function () {
                var url;

                if ("onepage" === activeType) {
                    url = ONEPAGE_URL;
                } else {
                    url = ACCORDION_URL;
                }

                return url;
            };

            setType = function (type) {
                var types = ["onepage", "accordion"];

                if (-1 !== types.indexOf(type)) {
                    activeType = type;
                } else {
                    activeType = defaultType;
                }

                return activeType;
            };

            getType = function () {
                return activeType;
            };

            getCheckout = function () {
                return checkout;
            };

            getAllowedPaymentMethods = function () {
                return allowedPaymentMethods || [];
            };

            getAllowedShippingMethods = function () {
                return allowedShippingMethods || [];
            };

            getAllowedGuestCheckout = function () {
                return angular.appConfigValue("general.checkout.guest_checkout");
            };

            getMinimalCostShippingMethods = function () {
                var result, currentMinPrice;

                for (var i = 0; i < allowedShippingMethods.length; i += 1) {
                    if (typeof currentMinPrice === "undefined") {
                        currentMinPrice = allowedShippingMethods[i].Price;
                        result = allowedShippingMethods[i];
                        result.index = i;
                        continue;
                    }
                    if (currentMinPrice > allowedShippingMethods[i].Price) {
                        currentMinPrice = allowedShippingMethods[i].Price;
                        result = allowedShippingMethods[i];
                        result.index = i;
                    }
                }

                return result;
            };

            return {
                "init": init,
                "update": update,
                "getUrl": getUrl,
                "getType": getType,
                "setType": setType,
                "getAllowedPaymentMethods": getAllowedPaymentMethods,
                "getAllowedShippingMethods": getAllowedShippingMethods,
                "loadShippingMethods": loadShippingMethods,
                "loadPaymentMethods": loadPaymentMethods,
                "getCheckout": getCheckout,
                "saveShippingAddress": saveShippingAddress,
                "saveBillingAddress": saveBillingAddress,
                "saveShippingMethod": saveShippingMethod,
                "savePaymentMethod": savePaymentMethod,
                "saveAdditionalInfo": saveAdditionalInfo,
                "discountNeglect": discountNeglect,
                "discountApply": discountApply,
                "getAllowedGuestCheckout": getAllowedGuestCheckout,
                "getMinimalCostShippingMethods": getMinimalCostShippingMethods
            };
        }
    ]
);<commit_msg>whitespace cleanup<commit_after>angular.module("checkoutModule")
/**
 *
 */
    .service("$checkoutService", [
        "$q",
        "$timeout",
        "$interval",
        "$checkoutApiService",
        "ONEPAGE_URL",
        "ACCORDION_URL",
        function ($q, $timeout, $interval, $checkoutApiService, ONEPAGE_URL, ACCORDION_URL) {
            // Variables
            var checkout, allowedShippingMethods, allowedPaymentMethods, defaultType, activeType;

            // Functions
            var init, getUrl, getType, setType, update, loadShippingMethods, loadPaymentMethods,
                saveBillingAddress, saveShippingAddress, saveShippingMethod, savePaymentMethod, discountApply, discountNeglect,
                getCheckout, getAllowedPaymentMethods, getAllowedShippingMethods, saveAdditionalInfo, getAllowedGuestCheckout,
                getMinimalCostShippingMethods;

            checkout = {};
            defaultType = "accordion";

            loadShippingMethods = function () {
                var defer = $q.defer();

                var splitMethodToRates = function (method) {
                    var i, rate;
                    for (i = 0; i < method.Rates.length; i += 1) {
                        rate = method.Rates[i];

                        var methodLabel = method.Name + " - " + rate.Name + " ($" + rate.Price + ")";
                        if (method.Name == 'Flat Rate') {
                            methodLabel = rate.Name + " ($" + rate.Price + ")";
                        }

                        allowedShippingMethods.push({
                            "Name": methodLabel,
                            "Price": rate.Price,
                            "Method": method.Code,
                            "Rate": rate.Code
                        });
                    }
                };

                $checkoutApiService.shippingMethods().$promise.then(function (response) {
                    var i, method;
                    allowedShippingMethods = [];
                    if (response.error === null) {
                        for (i = 0; i < response.result.length; i += 1) {
                            method = response.result[i] || [];
                            if (method.Rates instanceof Array && method.Rates.length > 0) {
                                splitMethodToRates(method);
                            }
                        }
                    }

                    defer.resolve(allowedShippingMethods);
                });

                return defer.promise;
            };

            loadPaymentMethods = function () {
                var defer = $q.defer();
                allowedPaymentMethods = [];
                $checkoutApiService.paymentMethods().$promise.then(function (response) {
                    allowedPaymentMethods = response.result || [];
                    defer.resolve(allowedPaymentMethods);
                });

                return defer.promise;
            };

            // TODO: I THINK THIS CAN BE DELETED
            init = function () {
                var defer, statuses;
                statuses = {
                    "isLoadedSM": false,
                    "isLoadedPM": false
                };
                defer = $q.defer();

                loadShippingMethods().then(function () {
                    statuses.isLoadedSM = true;
                });
                loadPaymentMethods().then(function () {
                    statuses.isLoadedPM = true;
                });

                var stop = $interval(function () {
                    var initAll = true;
                    for (var key in statuses) {
                        if (statuses.hasOwnProperty(key) && !statuses[key]) {
                            initAll = false;
                            break;
                        }
                    }
                    if (initAll) {
                        $interval.cancel(stop);
                        defer.resolve(checkout);
                    }
                }, 100);

                return defer.promise;
            };

            update = function () {
                var defer = $q.defer();

                $checkoutApiService.info().$promise.then(
                    function (response) {
                        checkout = response.result || [];
                        defer.resolve(checkout);
                    }
                );

                return defer.promise;
            };

            saveBillingAddress = function (address) {
                var defer = $q.defer();

                $checkoutApiService.setBillingAddress(address).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            saveShippingAddress = function (address) {
                var defer = $q.defer();

                $checkoutApiService.setShippingAddress(address).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            saveShippingMethod = function (method) {
                var defer = $q.defer();

                $checkoutApiService.setShippingMethod(method).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            savePaymentMethod = function (method) {
                var defer = $q.defer();

                $checkoutApiService.setPaymentMethod(method).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            saveAdditionalInfo = function (data) {
                var defer = $q.defer();

                $checkoutApiService.setInfo(data).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            discountApply = function (data) {
                var defer = $q.defer();

                $checkoutApiService.discountApply(data).$promise.then(
                    function (response) {
                        defer.resolve(response);
                    }
                );

                return defer.promise;
            };

            discountNeglect = function (data) {
                var defer = $q.defer();

                $checkoutApiService.discountNeglect(data).$promise.then(
                    function (response) {
                        if (response.error === null) {
                            defer.resolve(response);
                        }
                    }
                );

                return defer.promise;
            };

            getUrl = function () {
                var url;

                if ("onepage" === activeType) {
                    url = ONEPAGE_URL;
                } else {
                    url = ACCORDION_URL;
                }

                return url;
            };

            setType = function (type) {
                var types = ["onepage", "accordion"];

                if (-1 !== types.indexOf(type)) {
                    activeType = type;
                } else {
                    activeType = defaultType;
                }

                return activeType;
            };

            getType = function () {
                return activeType;
            };

            getCheckout = function () {
                return checkout;
            };

            getAllowedPaymentMethods = function () {
                return allowedPaymentMethods || [];
            };

            getAllowedShippingMethods = function () {
                return allowedShippingMethods || [];
            };

            getAllowedGuestCheckout = function () {
                return angular.appConfigValue("general.checkout.guest_checkout");
            };

            getMinimalCostShippingMethods = function () {
                var result, currentMinPrice;

                for (var i = 0; i < allowedShippingMethods.length; i += 1) {
                    if (typeof currentMinPrice === "undefined") {
                        currentMinPrice = allowedShippingMethods[i].Price;
                        result = allowedShippingMethods[i];
                        result.index = i;
                        continue;
                    }
                    if (currentMinPrice > allowedShippingMethods[i].Price) {
                        currentMinPrice = allowedShippingMethods[i].Price;
                        result = allowedShippingMethods[i];
                        result.index = i;
                    }
                }

                return result;
            };

            return {
                "init": init,
                "update": update,
                "getUrl": getUrl,
                "getType": getType,
                "setType": setType,
                "getAllowedPaymentMethods": getAllowedPaymentMethods,
                "getAllowedShippingMethods": getAllowedShippingMethods,
                "loadShippingMethods": loadShippingMethods,
                "loadPaymentMethods": loadPaymentMethods,
                "getCheckout": getCheckout,
                "saveShippingAddress": saveShippingAddress,
                "saveBillingAddress": saveBillingAddress,
                "saveShippingMethod": saveShippingMethod,
                "savePaymentMethod": savePaymentMethod,
                "saveAdditionalInfo": saveAdditionalInfo,
                "discountNeglect": discountNeglect,
                "discountApply": discountApply,
                "getAllowedGuestCheckout": getAllowedGuestCheckout,
                "getMinimalCostShippingMethods": getMinimalCostShippingMethods
            };
        }
    ]
);<|endoftext|>


<commit_before>/**
 * Placeholdem - Placeholder Caret Animation
 * v1.0.0 - MIT License
 * http://placeholdem.jackrugile.com - git://github.com/jackrugile/placeholdem.git
 * by Jack Rugile - @jackrugile
 */

function Placeholdem(e){"use strict";!function(){for(var e=0,n=["ms","moz","webkit","o"],a=0;a<n.length&&!window.requestAnimationFrame;++a)window.requestAnimationFrame=window[n[a]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[n[a]+"CancelAnimationFrame"]||window[n[a]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(n){var a=(new Date).getTime(),i=Math.max(0,16-(a-e)),l=window.setTimeout(function(){n(a+i)},i);return e=a+i,l}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})}();var n={};return n.init=function(){if(n.elems=[],e&&e.length)for(var a=0;a<e.length;a++)n.hasPlaceholder(e[a])&&n.elems.push(new n.PlaceholdemElem(e[a]));else e&&n.hasPlaceholder(e)&&n.elems.push(new n.PlaceholdemElem(e))},n.hasPlaceholder=function(e){return"function"==typeof e.hasAttribute&&e.hasAttribute("placeholder")},n.PlaceholdemElem=function(e){var n=this;n.init=function(){n.elem=e,n.placeholder=n.elem.getAttribute("placeholder"),n.elem.removeAttribute("placeholder"),n.rAF=null,n.animating=0,n.elem.value||(n.elem.value=n.placeholder),n.on(n.elem,"focus",n.onFocus),n.on(n.elem,"blur",n.onBlur),n.on(n.elem,"keydown",n.onKeydown)},n.on=function(e,n,a){e.addEventListener?e.addEventListener(n,a):e.attachEvent("on"+n,a)},n.onFocus=function(){(n.animating||n.elem.value===n.placeholder)&&(n.animating=1,window.cancelAnimationFrame(n.rAF),n.deletePlaceholder())},n.onBlur=function(){(n.animating||""===n.elem.value)&&(n.animating=1,window.cancelAnimationFrame(n.rAF),n.restorePlaceholder())},n.onKeydown=function(){n.animating&&(n.animating=0,window.cancelAnimationFrame(n.rAF),n.elem.value="")},n.deletePlaceholder=function(){n.elem.value.length>0?(n.elem.value=n.elem.value.slice(0,-1),n.rAF=window.requestAnimationFrame(n.deletePlaceholder)):n.animating=0},n.restorePlaceholder=function(){n.elem.value.length<n.placeholder.length?(n.elem.value+=n.placeholder[n.elem.value.length],n.rAF=window.requestAnimationFrame(n.restorePlaceholder)):n.animating=0},n.init()},n.init(),n}<commit_msg>update version number comment<commit_after>/**
 * Placeholdem - Placeholder Caret Animation
 * v1.0.1 - MIT License
 * http://placeholdem.jackrugile.com - git://github.com/jackrugile/placeholdem.git
 * by Jack Rugile - @jackrugile
 */

function Placeholdem(e){"use strict";!function(){for(var e=0,n=["ms","moz","webkit","o"],a=0;a<n.length&&!window.requestAnimationFrame;++a)window.requestAnimationFrame=window[n[a]+"RequestAnimationFrame"],window.cancelAnimationFrame=window[n[a]+"CancelAnimationFrame"]||window[n[a]+"CancelRequestAnimationFrame"];window.requestAnimationFrame||(window.requestAnimationFrame=function(n){var a=(new Date).getTime(),i=Math.max(0,16-(a-e)),l=window.setTimeout(function(){n(a+i)},i);return e=a+i,l}),window.cancelAnimationFrame||(window.cancelAnimationFrame=function(e){clearTimeout(e)})}();var n={};return n.init=function(){if(n.elems=[],e&&e.length)for(var a=0;a<e.length;a++)n.hasPlaceholder(e[a])&&n.elems.push(new n.PlaceholdemElem(e[a]));else e&&n.hasPlaceholder(e)&&n.elems.push(new n.PlaceholdemElem(e))},n.hasPlaceholder=function(e){return"function"==typeof e.hasAttribute&&e.hasAttribute("placeholder")},n.PlaceholdemElem=function(e){var n=this;n.init=function(){n.elem=e,n.placeholder=n.elem.getAttribute("placeholder"),n.elem.removeAttribute("placeholder"),n.rAF=null,n.animating=0,n.elem.value||(n.elem.value=n.placeholder),n.on(n.elem,"focus",n.onFocus),n.on(n.elem,"blur",n.onBlur),n.on(n.elem,"keydown",n.onKeydown)},n.on=function(e,n,a){e.addEventListener?e.addEventListener(n,a):e.attachEvent("on"+n,a)},n.onFocus=function(){(n.animating||n.elem.value===n.placeholder)&&(n.animating=1,window.cancelAnimationFrame(n.rAF),n.deletePlaceholder())},n.onBlur=function(){(n.animating||""===n.elem.value)&&(n.animating=1,window.cancelAnimationFrame(n.rAF),n.restorePlaceholder())},n.onKeydown=function(){n.animating&&(n.animating=0,window.cancelAnimationFrame(n.rAF),n.elem.value="")},n.deletePlaceholder=function(){n.elem.value.length>0?(n.elem.value=n.elem.value.slice(0,-1),n.rAF=window.requestAnimationFrame(n.deletePlaceholder)):n.animating=0},n.restorePlaceholder=function(){n.elem.value.length<n.placeholder.length?(n.elem.value+=n.placeholder[n.elem.value.length],n.rAF=window.requestAnimationFrame(n.restorePlaceholder)):n.animating=0},n.init()},n.init(),n}<|endoftext|>


<commit_before>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',

    'dojo/text!./templates/UserAdmin.html',

    'dojo/request',
    'dojo/dom-style',
    'dojo/dom-construct',
    'dojo/store/Memory',
    'dojo/topic',
    'dojo/string',
    'dojo/Deferred',

    'dijit/_WidgetBase',
    'dijit/_TemplatedMixin',
    'dijit/_WidgetsInTemplateMixin',

    'dgrid/OnDemandGrid',

    'jquery',
    'ijit/widgets/authentication/LoginRegister',
    'ijit/widgets/authentication/_UserAdminPendingUser',
    'ijit/widgets/authentication/_UserAdminUser'
], function(
    declare,
    lang,
    array,

    template,

    request,
    domStyle,
    domConstruct,
    Memory,
    topic,
    dojoString,
    Deferred,

    _WidgetBase,
    _TemplatedMixin,
    _WidgetsInTemplateMixin,

    Grid,

    jquery,
    LoginRegister,
    UserAdminPendingUser,
    UserAdminUser
) {
    var fieldNames = {
        id: 'userId',
        email: 'email',
        role: 'role',
        lastLogin: 'lastLogin',
        first: 'first',
        last: 'last',
        agency: 'agency',
        startDate: 'startDate',
        endDate: 'endDate'
    };
    var formatDate = function (value) {
        if (value > 0) {
            return new Date(parseInt(value, 10)).toLocaleString();
        } else {
            return '';
        }
    };

    // summary:
    //      Provides controls to allow admins to do things like acceept users, delete users and reset passwords.
    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
        widgetsInTemplate: true,
        templateString: template,
        baseClass: 'user-admin',

        urls: {
            base: '/permissionproxy/api',
            getallwaiting: '/admin/getallwaiting',
            getallapproved: '/admin/getallapproved',
            getroles: '/admin/getroles'
        },

        fieldNames: fieldNames,

        // dateFields: string[]
        //      list of date fields for csv export
        dateFields: [fieldNames.lastLogin, fieldNames.startDate, fieldNames.endDate],

        // roles: String[]
        //      as returned by GetRoles
        roles: null,

        // login: LoginRegister
        login: null,

        // grid: Grid
        //      the approved users grid
        grid: null,

        // params passed in via the constructor

        // appName: String
        //      The name of the associated application in the Raven DB
        appName: null,

        postCreate: function() {
            // summary:
            //      dom is ready
            console.log('ijit/widgets/authentication/UserAdmin:postCreate', arguments);

            var that = this;

            this.login = new LoginRegister({
                appName: this.appName,
                logoutDiv: this.logoutDiv,
                isAdminPage: true
            });

            this.login.on('sign-in-success', function() {
                that.getRoles();
            });

            this.own(
                topic.subscribe(UserAdminPendingUser.prototype.successTopic, function () {
                    that.getUsers(true);
                })
            );
        },
        getRoles: function() {
            // summary:
            //      gets roles for app
            console.log('ijit/widgets/authentication/UserAdmin:getRoles', arguments);

            var def = request(this.urls.base + this.urls.getroles, {
                query: {
                    application: this.appName
                },
                handleAs: 'json'
            });
            var that = this;
            def.then(function(response) {
                that.roles = response.result;
                that.getUsers();
            }, lang.hitch(this, 'onError'));
        },
        getUsers: function(approvedOnly) {
            // summary:
            //      calls getallwaiting & getallapproved
            console.log('ijit/widgets/authentication/UserAdmin:getUsers', arguments);

            var that = this;
            var makeRequest = function (url, callback) {
                request(that.urls.base + url, {
                    query: {
                        application: that.appName,
                        adminToken: that.login.user.adminToken
                    },
                    handleAs: 'json'
                }).then(lang.hitch(that, callback), lang.hitch(that, 'onError'));
            };

            if (!approvedOnly) {
                makeRequest(this.urls.getallwaiting, 'showWaitingUsers');
            }
            makeRequest(this.urls.getallapproved, 'showApprovedUsers');
        },
        showApprovedUsers: function (response) {
            // summary:
            //      builds the approved users grid
            // response: {}
            //      response object from getallapproved service
            console.log('ijit/widgets/authentication/UserAdmin:showApprovedUsers', arguments);

            var that = this;
            var getStore = function () {
                return new Memory({
                    data: response.result,
                    idProperty: that.fieldNames.email,
                    query: function (query, options){
                        query = query || {};
                        options = options || {};

                        // this block is to make the sorting of strings case-insensitive
                        // it overrides the default sort logic adding in the .toLowerCase stuff
                        if (options.sort) {
                            var sort = options.sort[0];
                            options.sort = function (a, b) {
                                a = dojoString.trim(a[sort.attribute]).toLowerCase();
                                b = dojoString.trim(b[sort.attribute]).toLowerCase();

                                /* jshint -W018 */
                                return !!sort.descending === (a > b) ? -1 : 1;
                                /* jshint +W018 */
                            };
                        }
                        return this.queryEngine(query, options)(this.data);
                    }
                });
            };

            if (!this.grid) {
                this.grid = new Grid({
                    store: getStore(),
                    columns: [
                        {
                            label: 'Edit',
                            field: this.fieldNames.id,
                            renderCell: function (object) {
                                return domConstruct.create('button', {
                                    value: object[that.fieldNames.email],
                                    innerHTML: '...',
                                    'class': 'btn btn-default btn-xs',
                                    onclick: function () {
                                        that.editUser(object);
                                    }
                                });
                            }
                        },
                        {label: 'Email', field: this.fieldNames.email},
                        {label: 'First Name', field: this.fieldNames.first},
                        {label: 'Last Name', field: this.fieldNames.last},
                        {label: 'Agency', field: this.fieldNames.agency},
                        {label: 'Role', field: this.fieldNames.role},
                        {
                            label: 'Last Login',
                            field: this.fieldNames.lastLogin,
                            formatter: formatDate
                        }
                    ]
                }, this.userGrid);
                this.grid.set('sort', 'email');
                this.grid.startup();
            } else {
                this.grid.set('store', getStore());
            }
        },
        editUser: function (item) {
            // summary:
            //      creates a new UserAdminUser widget
            // item: Object
            //      row item as returned from the grid
            console.log('ijit/widget/authentication/UserAdmin:editUser', arguments);

            // deferred makes custom approvals possible
            // check app/security/_UserAdminPendingUser in deq-enviro
            // for an example
            var def = new Deferred();
            var that = this;

            var userAdmin = new UserAdminUser(lang.mixin(item, {
                adminToken: this.login.user.adminToken,
                appName: this.appName,
                roles: this.roles
            }));
            userAdmin.startup();
            userAdmin.on('edit', function () {
                that.getUsers(true);
                def.resolve();
            });

            return def;
        },
        onError: function(response) {
            // summary:
            //      error callback for xhr
            // response: {}
            //      response object from server
            console.log('ijit/widgets/authentication/UserAdmin:onError', arguments);

            this.errMsgDiv.innerHTML = response.message;
            domStyle.set(this.errMsgDiv, 'display', 'block');
        },
        showWaitingUsers: function(response) {
            // summary:
            //      callback from getallwaiting
            //      builds user widgets
            // response: {}
            //      response object from server
            console.log('ijit/widgets/authentication/UserAdmin:showWaitingUsers', arguments);

            var users = response.result;

            if (users.length === 0) {
                domStyle.set(this.noUsersMsg, 'display', 'block');
            } else {
                array.forEach(users, function(u) {
                    new UserAdminPendingUser(lang.mixin(u, {
                        roles: this.roles,
                        adminToken: this.login.user.adminToken,
                        appName: this.appName,
                        userAdmin: this
                    }), domConstruct.create('div', {}, this.userContainer));
                }, this);
            }
        },
        destroyRecursive: function() {
            // summary:
            //      mostly for tear down during tests
            console.log('ijit/widgets/authentication/UserAdmin:destroyRecursive', arguments);

            this.login.destroyRecursive();
            this.inherited(arguments);
        },
        exportToCsv: function () {
            // summary:
            //      Exports the user list to a csv file for download
            console.log('ijit/widgets/authentication/UserAdmin:exportToCsv', arguments);

            var csvTxt;
            var that = this;

            var users = this.grid.store.data;
            var firstUser = users[0];

            // polyfill for IE < 9
            if (!Array.isArray) {
                Array.isArray = function (arg) {
                    return Object.prototype.toString.call(arg) === '[object Array]';
                };
            }

            var walkObject = function (obj, header) {
                var values = [];
                for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                        if (typeof obj[prop] !== 'object' || Array.isArray(obj[prop])) {
                            // skip admin token
                            if (prop === 'adminToken') {
                                continue;
                            }
                            var v = (header) ? prop : obj[prop];

                            if (array.indexOf(that.dateFields, prop) !== -1 && !header) {
                                v = formatDate(v);
                            }
                            values.push('"' + v + '"');
                        } else {
                            values = values.concat(walkObject(obj[prop], header));
                        }
                    }
                }
                return values;
            };

            csvTxt = walkObject(firstUser, true).join(',') + '\n';

            var data = array.map(users, function (u) {
                return walkObject(u, false);
            });
            csvTxt += data.join('\n');

            var uri = encodeURI('data:text/csv;charset=utf-8,' + csvTxt);

            if (this.downloadLink.download === '') {
                this.downloadLink.href = uri;
                this.downloadLink.download = 'users.csv';
                this.downloadLink.click();
            } else {
                var newWindow = window.open();
                newWindow.document.writeln(csvTxt);
            }

            return csvTxt;
        }
    });
});<commit_msg>fix(user-admin): handle hashes (#) in user data export to csv (#82)<commit_after>define([
    'dojo/_base/declare',
    'dojo/_base/lang',
    'dojo/_base/array',

    'dojo/text!./templates/UserAdmin.html',

    'dojo/request',
    'dojo/dom-style',
    'dojo/dom-construct',
    'dojo/store/Memory',
    'dojo/topic',
    'dojo/string',
    'dojo/Deferred',

    'dijit/_WidgetBase',
    'dijit/_TemplatedMixin',
    'dijit/_WidgetsInTemplateMixin',

    'dgrid/OnDemandGrid',

    'jquery',
    'ijit/widgets/authentication/LoginRegister',
    'ijit/widgets/authentication/_UserAdminPendingUser',
    'ijit/widgets/authentication/_UserAdminUser'
], function(
    declare,
    lang,
    array,

    template,

    request,
    domStyle,
    domConstruct,
    Memory,
    topic,
    dojoString,
    Deferred,

    _WidgetBase,
    _TemplatedMixin,
    _WidgetsInTemplateMixin,

    Grid,

    jquery,
    LoginRegister,
    UserAdminPendingUser,
    UserAdminUser
) {
    var fieldNames = {
        id: 'userId',
        email: 'email',
        role: 'role',
        lastLogin: 'lastLogin',
        first: 'first',
        last: 'last',
        agency: 'agency',
        startDate: 'startDate',
        endDate: 'endDate'
    };
    var formatDate = function (value) {
        if (value > 0) {
            return new Date(parseInt(value, 10)).toLocaleString();
        } else {
            return '';
        }
    };

    // summary:
    //      Provides controls to allow admins to do things like acceept users, delete users and reset passwords.
    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin], {
        widgetsInTemplate: true,
        templateString: template,
        baseClass: 'user-admin',

        urls: {
            base: '/permissionproxy/api',
            getallwaiting: '/admin/getallwaiting',
            getallapproved: '/admin/getallapproved',
            getroles: '/admin/getroles'
        },

        fieldNames: fieldNames,

        // dateFields: string[]
        //      list of date fields for csv export
        dateFields: [fieldNames.lastLogin, fieldNames.startDate, fieldNames.endDate],

        // roles: String[]
        //      as returned by GetRoles
        roles: null,

        // login: LoginRegister
        login: null,

        // grid: Grid
        //      the approved users grid
        grid: null,

        // params passed in via the constructor

        // appName: String
        //      The name of the associated application in the Raven DB
        appName: null,

        postCreate: function() {
            // summary:
            //      dom is ready
            console.log('ijit/widgets/authentication/UserAdmin:postCreate', arguments);

            var that = this;

            this.login = new LoginRegister({
                appName: this.appName,
                logoutDiv: this.logoutDiv,
                isAdminPage: true
            });

            this.login.on('sign-in-success', function() {
                that.getRoles();
            });

            this.own(
                topic.subscribe(UserAdminPendingUser.prototype.successTopic, function () {
                    that.getUsers(true);
                })
            );
        },
        getRoles: function() {
            // summary:
            //      gets roles for app
            console.log('ijit/widgets/authentication/UserAdmin:getRoles', arguments);

            var def = request(this.urls.base + this.urls.getroles, {
                query: {
                    application: this.appName
                },
                handleAs: 'json'
            });
            var that = this;
            def.then(function(response) {
                that.roles = response.result;
                that.getUsers();
            }, lang.hitch(this, 'onError'));
        },
        getUsers: function(approvedOnly) {
            // summary:
            //      calls getallwaiting & getallapproved
            console.log('ijit/widgets/authentication/UserAdmin:getUsers', arguments);

            var that = this;
            var makeRequest = function (url, callback) {
                request(that.urls.base + url, {
                    query: {
                        application: that.appName,
                        adminToken: that.login.user.adminToken
                    },
                    handleAs: 'json'
                }).then(lang.hitch(that, callback), lang.hitch(that, 'onError'));
            };

            if (!approvedOnly) {
                makeRequest(this.urls.getallwaiting, 'showWaitingUsers');
            }
            makeRequest(this.urls.getallapproved, 'showApprovedUsers');
        },
        showApprovedUsers: function (response) {
            // summary:
            //      builds the approved users grid
            // response: {}
            //      response object from getallapproved service
            console.log('ijit/widgets/authentication/UserAdmin:showApprovedUsers', arguments);

            var that = this;
            var getStore = function () {
                return new Memory({
                    data: response.result,
                    idProperty: that.fieldNames.email,
                    query: function (query, options){
                        query = query || {};
                        options = options || {};

                        // this block is to make the sorting of strings case-insensitive
                        // it overrides the default sort logic adding in the .toLowerCase stuff
                        if (options.sort) {
                            var sort = options.sort[0];
                            options.sort = function (a, b) {
                                a = dojoString.trim(a[sort.attribute]).toLowerCase();
                                b = dojoString.trim(b[sort.attribute]).toLowerCase();

                                /* jshint -W018 */
                                return !!sort.descending === (a > b) ? -1 : 1;
                                /* jshint +W018 */
                            };
                        }
                        return this.queryEngine(query, options)(this.data);
                    }
                });
            };

            if (!this.grid) {
                this.grid = new Grid({
                    store: getStore(),
                    columns: [
                        {
                            label: 'Edit',
                            field: this.fieldNames.id,
                            renderCell: function (object) {
                                return domConstruct.create('button', {
                                    value: object[that.fieldNames.email],
                                    innerHTML: '...',
                                    'class': 'btn btn-default btn-xs',
                                    onclick: function () {
                                        that.editUser(object);
                                    }
                                });
                            }
                        },
                        {label: 'Email', field: this.fieldNames.email},
                        {label: 'First Name', field: this.fieldNames.first},
                        {label: 'Last Name', field: this.fieldNames.last},
                        {label: 'Agency', field: this.fieldNames.agency},
                        {label: 'Role', field: this.fieldNames.role},
                        {
                            label: 'Last Login',
                            field: this.fieldNames.lastLogin,
                            formatter: formatDate
                        }
                    ]
                }, this.userGrid);
                this.grid.set('sort', 'email');
                this.grid.startup();
            } else {
                this.grid.set('store', getStore());
            }
        },
        editUser: function (item) {
            // summary:
            //      creates a new UserAdminUser widget
            // item: Object
            //      row item as returned from the grid
            console.log('ijit/widget/authentication/UserAdmin:editUser', arguments);

            // deferred makes custom approvals possible
            // check app/security/_UserAdminPendingUser in deq-enviro
            // for an example
            var def = new Deferred();
            var that = this;

            var userAdmin = new UserAdminUser(lang.mixin(item, {
                adminToken: this.login.user.adminToken,
                appName: this.appName,
                roles: this.roles
            }));
            userAdmin.startup();
            userAdmin.on('edit', function () {
                that.getUsers(true);
                def.resolve();
            });

            return def;
        },
        onError: function(response) {
            // summary:
            //      error callback for xhr
            // response: {}
            //      response object from server
            console.log('ijit/widgets/authentication/UserAdmin:onError', arguments);

            this.errMsgDiv.innerHTML = response.message;
            domStyle.set(this.errMsgDiv, 'display', 'block');
        },
        showWaitingUsers: function(response) {
            // summary:
            //      callback from getallwaiting
            //      builds user widgets
            // response: {}
            //      response object from server
            console.log('ijit/widgets/authentication/UserAdmin:showWaitingUsers', arguments);

            var users = response.result;

            if (users.length === 0) {
                domStyle.set(this.noUsersMsg, 'display', 'block');
            } else {
                array.forEach(users, function(u) {
                    new UserAdminPendingUser(lang.mixin(u, {
                        roles: this.roles,
                        adminToken: this.login.user.adminToken,
                        appName: this.appName,
                        userAdmin: this
                    }), domConstruct.create('div', {}, this.userContainer));
                }, this);
            }
        },
        destroyRecursive: function() {
            // summary:
            //      mostly for tear down during tests
            console.log('ijit/widgets/authentication/UserAdmin:destroyRecursive', arguments);

            this.login.destroyRecursive();
            this.inherited(arguments);
        },
        exportToCsv: function () {
            // summary:
            //      Exports the user list to a csv file for download
            console.log('ijit/widgets/authentication/UserAdmin:exportToCsv', arguments);

            var csvTxt;
            var that = this;

            var users = this.grid.store.data;
            var firstUser = users[0];

            // polyfill for IE < 9
            if (!Array.isArray) {
                Array.isArray = function (arg) {
                    return Object.prototype.toString.call(arg) === '[object Array]';
                };
            }

            var walkObject = function (obj, header) {
                var values = [];
                for (var prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                        if (typeof obj[prop] !== 'object' || Array.isArray(obj[prop])) {
                            // skip admin token
                            if (prop === 'adminToken') {
                                continue;
                            }
                            var v = (header) ? prop : obj[prop];

                            if (array.indexOf(that.dateFields, prop) !== -1 && !header) {
                                v = formatDate(v);
                            }
                            values.push('"' + v + '"');
                        } else {
                            values = values.concat(walkObject(obj[prop], header));
                        }
                    }
                }
                return values;
            };

            csvTxt = walkObject(firstUser, true).join(',') + '\n';

            var data = array.map(users, function (u) {
                return walkObject(u, false);
            });
            csvTxt += data.join('\n');

            var uri = encodeURI('data:text/csv;charset=utf-8,' + csvTxt);

            if (this.downloadLink.download === '') {
                // encodeURI does not touch hash marks but they mess up the csv if they are preserved
                this.downloadLink.href = uri.replace(/#/g, '%23');
                this.downloadLink.download = 'users.csv';
                this.downloadLink.click();
            } else {
                var newWindow = window.open();
                newWindow.document.writeln(csvTxt);
            }

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