<commit_before>var togeojson = require('@mapbox/togeojson');
var DOMParser = require('xmldom').DOMParser;
var meta = require('@turf/meta');
var turf = require('@turf/turf');
var datapoints = [];
var _ = {
  omit: require('lodash/omit')
};

module.exports = function gpxToGeoJSON(gpx) {
  gpx = new DOMParser().parseFromString(gpx);
  var geojson = togeojson.gpx(gpx);
  meta.coordEach(geojson, function (coord) {
    datapoints.push({
      coord: coord
    });
  });

  meta.propEach(geojson, function (prop) {
    Object.keys(prop).forEach(function (key) {
      if (Array.isArray(prop[key])) {
        prop[key].forEach(function (value, index) {
          if(datapoints[index]) {
            datapoints[index][key] = value;
          }
        })
      }
    });
  });
  var length = datapoints.length;
  var features = [];
  var feature = datapoints.map(function (point, index) {
    if (index < length - 1) {
      var next_point = datapoints[index + 1];
      var props = _.omit(point, ['coord']);
      if (point.coord.length === 3) {
        props.elevation = point.coord[2];
      }
      var units = 'kilometers';
      var linestring = turf.lineString([point.coord, next_point.coord]);
      var distance = turf.lineDistance(linestring, units);
      var cut_distance = 0.0001;
      if(distance > cut_distance) {
        var lineslice = turf.lineSliceAlong(linestring, 0, (distance - cut_distance), units);
        lineslice.properties = props;
        features.push(lineslice);
      }
    }
  });
  return turf.featureCollection(features);
}<commit_msg>use Array.map properly. and change cut distance to 1 yard<commit_after>var togeojson = require('@mapbox/togeojson');
var DOMParser = require('xmldom').DOMParser;
var meta = require('@turf/meta');
var turf = require('@turf/turf');
var datapoints = [];
var _ = {
  omit: require('lodash/omit'),
  compact: require('lodash/compact')
};

module.exports = function gpxToGeoJSON(gpx) {
  gpx = new DOMParser().parseFromString(gpx);
  var geojson = togeojson.gpx(gpx);
  meta.coordEach(geojson, function (coord) {
    datapoints.push({
      coord: coord
    });
  });

  meta.propEach(geojson, function (prop) {
    Object.keys(prop).forEach(function (key) {
      if (Array.isArray(prop[key])) {
        prop[key].forEach(function (value, index) {
          if(datapoints[index]) {
            datapoints[index][key] = value;
          }
        })
      }
    });
  });
  var length = datapoints.length;
  var features = datapoints.map(function (point, index) {
    if (index < length - 1) {
      var next_point = datapoints[index + 1];
      var props = _.omit(point, ['coord']);
      if (point.coord.length === 3) {
        props.elevation = point.coord[2];
      }
      var units = 'kilometers';
      var linestring = turf.lineString([point.coord, next_point.coord]);
      var distance = turf.lineDistance(linestring, units);
      var cut_distance = 0.0009144;
      if(distance > cut_distance) {
        var lineslice = turf.lineSliceAlong(linestring, 0, (distance - cut_distance), units);
        lineslice.properties = props;
        return lineslice;
      }
      return null;
    }
  });
  return turf.featureCollection(_.compact(features));
}<|endoftext|>


<commit_before>/**
 * Appcelerator Common Library for Node.js
 * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * Please see the LICENSE file for information about licensing.
 *
 * Portions derived from wrench under the MIT license.
 * Copyright (c) 2010 Ryan McGrath
 * https://github.com/ryanmcgrath/wrench-js
 */

var fs = require('fs'),
	path = require('path'),
	wrench = require('wrench'),
	tildeRegExp = /^(~)(\/.*)?$/,
	winEnvVarRegExp = /(%([^%]*)%)/g;

exports.home = function () {
	return process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME'];
};

exports.exists = function (p) {
	// existsSync was moved from path to fs in node 0.8.0
	return (fs.existsSync || path.existsSync)(arguments.length > 1 ? path.join.apply(null, arguments) : p);
};

exports.resolvePath = function () {
	var p = path.join.apply(null, arguments);
	return path.resolve(p.replace(tildeRegExp, function (s, m, n) {
		return exports.home() + (n || '/');
	}).replace(winEnvVarRegExp, function (s, m, n) {
		return process.platform == 'win32' && process.env[n] || m;
	}));
};

exports.touch = function (file) {
	if (exports.exists(file)) {
		fs.utimesSync(file, Date.now(), Date.now());
	} else {
		fs.writeFileSync(file, '');
	}
};

exports.isDirWritable = function (dir) {
	var result = false,
		tmpFile = path.join(dir, 'tmp' + Math.round(Math.random() * 1e12));
	if (exports.exists(dir)) {
		try {
			exports.touch(tmpFile);
			result = exports.exists(tmpFile);
			fs.unlink(tmpFile);
		} catch (e) {}
	}
	return result;
};

// Copies a file synchronously. If the destination is an existing directory, it uses the source's filename.
// If the destination is a existing file, it uses the destination file's name. If the destination does NOT
// exist, it assumes the dest is a path to a file.
exports.copyFileSync = function (src, dest, opts) {
	var destFilename = path.basename(src);
	if (!exports.exists(dest) || !fs.lstatSync(dest).isDirectory()) {
		destFilename = path.basename(dest);
		dest = path.dirname(dest);
	}
	wrench.mkdirSyncRecursive(dest);
	dest = path.join(dest, destFilename);
	opts && opts.logger && opts.logger(__('Copying %s => %s', src.cyan, dest.cyan));
	fs.writeFileSync(dest, fs.readFileSync(src));
};

// copyDirSyncRecursive() is the same as the one from wrench, except this one supports a
// logger option and ignore lists.
exports.copyDirSyncRecursive = function(sourceDir, newDirLocation, opts) {
	opts = opts || {};
	opts.logger && opts.logger(__('Copying %s => %s', sourceDir.cyan, newDirLocation.cyan));

	if (!opts.preserve) {
		try {
			fs.statSync(newDirLocation).isDirectory() && exports.rmdirSyncRecursive(newDirLocation);
		} catch(e) {}
	}

	//  Create the directory where all our junk is moving to; read the mode of the source directory and mirror it
	var checkDir = fs.statSync(sourceDir);
	try {
		fs.mkdirSync(newDirLocation, checkDir.mode);
	} catch (e) {
		// if the directory already exists, that's okay
		if (e.code !== 'EEXIST') {
			throw e;
		}
	}

	var files = fs.readdirSync(sourceDir),
		rootIgnore = opts.rootIgnore && [].concat(opts.rootIgnore);

	delete opts.rootIgnore;

	for (var i = 0; i < files.length; i++) {
		if (rootIgnore && rootIgnore.indexOf(files[i]) != -1) continue;

		var currFile = fs.lstatSync(sourceDir + '/' + files[i]);

		if (currFile.isDirectory()) {
			// recursion this thing right on back.
			if (opts.ignoreDirs && opts.ignoreDirs.indexOf(files[i]) != -1) continue;
			exports.copyDirSyncRecursive(sourceDir + '/' + files[i], newDirLocation + '/' + files[i], opts);
		} else {
			if (opts.ignoreFiles && opts.ignoreFiles.indexOf(files[i]) != -1) continue;
			if (currFile.isSymbolicLink()) {
				var symlinkFull = fs.readlinkSync(sourceDir + '/' + files[i]);
				fs.symlinkSync(symlinkFull, newDirLocation + '/' + files[i]);
			} else {
				// At this point, we've hit a file actually worth copying... so copy it on over.
				var contents = fs.readFileSync(sourceDir + '/' + files[i]);
				fs.writeFileSync(newDirLocation + '/' + files[i], opts.callback ? opts.callback(sourceDir + '/' + files[i], newDirLocation + '/' + files[i], contents.toString(), opts.logger) : contents);
			}
		}
	}
};
<commit_msg>Added async capabilities to the exists() function. Added callback based visitDirs function.<commit_after>/**
 * Appcelerator Common Library for Node.js
 * Copyright (c) 2012 by Appcelerator, Inc. All Rights Reserved.
 * Please see the LICENSE file for information about licensing.
 *
 * Portions derived from wrench under the MIT license.
 * Copyright (c) 2010 Ryan McGrath
 * https://github.com/ryanmcgrath/wrench-js
 */

var fs = require('fs'),
	path = require('path'),
	wrench = require('wrench'),
	tildeRegExp = /^(~)(\/.*)?$/,
	winEnvVarRegExp = /(%([^%]*)%)/g;

exports.home = function () {
	return process.env[process.platform == 'win32' ? 'USERPROFILE' : 'HOME'];
};

exports.exists = function (p) {
	// existsSync was moved from path to fs in node 0.8.0
	var len = arguments.length,
		cb = len && arguments[len-1];
	if (cb && Object.prototype.toString.call(cb) == '[object Function]') {
		// async
		if (arguments.length > 2) {
			(fs.exists || path.exists)(path.join.apply(null, Array.prototype.slice.call(arguments, 0, len-1)), cb);
		} else {
			(fs.exists || path.exists)(p, cb);
		}
	} else {
		// sync
		return (fs.existsSync || path.existsSync)(len > 1 ? path.join.apply(null, arguments) : p);
	}
};

exports.resolvePath = function () {
	var p = path.join.apply(null, arguments);
	return path.resolve(p.replace(tildeRegExp, function (s, m, n) {
		return exports.home() + (n || '/');
	}).replace(winEnvVarRegExp, function (s, m, n) {
		return process.platform == 'win32' && process.env[n] || m;
	}));
};

// list all directories in a given directory and call the callback function for each specific directory
exports.visitDirs = function (dir, visitor, finished) {
	var visited = 0;
	fs.readdir(dir, function (err, files) {
		if (!err) {
			files.forEach(function (file) {
				var full = path.join(dir, file);
				fs.lstat(full, function (err, stats) {
					visited++;
					if (!err && stats.isDirectory()) {
						visitor(file, full);
						if (visited == files.length) {
							finished();
						}
					}
				});
			});
		}
	});
};

exports.visitDirsSync = function (dir, visitor) {
	fs.readdirSync(dir).filter(function (file) {
		return fs.lstatSync(path.join(dir, file)).isDirectory();
	}).forEach(function (subdir) {
		visitor(subdir, path.join(dir, subdir));
	});
};

exports.touch = function (file) {
	if (exports.exists(file)) {
		fs.utimesSync(file, Date.now(), Date.now());
	} else {
		fs.writeFileSync(file, '');
	}
};

exports.isDirWritable = function (dir) {
	var result = false,
		tmpFile = path.join(dir, 'tmp' + Math.round(Math.random() * 1e12));
	if (exports.exists(dir)) {
		try {
			exports.touch(tmpFile);
			result = exports.exists(tmpFile);
			fs.unlink(tmpFile);
		} catch (e) {}
	}
	return result;
};

// Copies a file synchronously. If the destination is an existing directory, it uses the source's filename.
// If the destination is a existing file, it uses the destination file's name. If the destination does NOT
// exist, it assumes the dest is a path to a file.
exports.copyFileSync = function (src, dest, opts) {
	var destFilename = path.basename(src);
	if (!exports.exists(dest) || !fs.lstatSync(dest).isDirectory()) {
		destFilename = path.basename(dest);
		dest = path.dirname(dest);
	}
	wrench.mkdirSyncRecursive(dest);
	dest = path.join(dest, destFilename);
	opts && opts.logger && opts.logger(__('Copying %s => %s', src.cyan, dest.cyan));
	fs.writeFileSync(dest, fs.readFileSync(src));
};

// copyDirSyncRecursive() is the same as the one from wrench, except this one supports a
// logger option and ignore lists.
exports.copyDirSyncRecursive = function(sourceDir, newDirLocation, opts) {
	opts = opts || {};
	opts.logger && opts.logger(__('Copying %s => %s', sourceDir.cyan, newDirLocation.cyan));

	if (!opts.preserve) {
		try {
			fs.statSync(newDirLocation).isDirectory() && exports.rmdirSyncRecursive(newDirLocation);
		} catch(e) {}
	}

	//  Create the directory where all our junk is moving to; read the mode of the source directory and mirror it
	var checkDir = fs.statSync(sourceDir);
	try {
		fs.mkdirSync(newDirLocation, checkDir.mode);
	} catch (e) {
		// if the directory already exists, that's okay
		if (e.code !== 'EEXIST') {
			throw e;
		}
	}

	var files = fs.readdirSync(sourceDir),
		rootIgnore = opts.rootIgnore && [].concat(opts.rootIgnore);

	delete opts.rootIgnore;

	for (var i = 0; i < files.length; i++) {
		if (rootIgnore && rootIgnore.indexOf(files[i]) != -1) continue;

		var currFile = fs.lstatSync(sourceDir + '/' + files[i]);

		if (currFile.isDirectory()) {
			// recursion this thing right on back.
			if (opts.ignoreDirs && opts.ignoreDirs.indexOf(files[i]) != -1) continue;
			exports.copyDirSyncRecursive(sourceDir + '/' + files[i], newDirLocation + '/' + files[i], opts);
		} else {
			if (opts.ignoreFiles && opts.ignoreFiles.indexOf(files[i]) != -1) continue;
			if (currFile.isSymbolicLink()) {
				var symlinkFull = fs.readlinkSync(sourceDir + '/' + files[i]);
				fs.symlinkSync(symlinkFull, newDirLocation + '/' + files[i]);
			} else {
				// At this point, we've hit a file actually worth copying... so copy it on over.
				var contents = fs.readFileSync(sourceDir + '/' + files[i]);
				fs.writeFileSync(newDirLocation + '/' + files[i], opts.callback ? opts.callback(sourceDir + '/' + files[i], newDirLocation + '/' + files[i], contents.toString(), opts.logger) : contents);
			}
		}
	}
};
<|endoftext|>


<commit_before>"use strict";

var Freya = Freya || {};

Freya.get_popup = function (url, $button) {

    // Ability to load popup via ajax url
    $.get(url).done(function (data, textStatus, jqXHR) {
        if (data) {
            var $popup = $(data.data_html);
            $('body').append($popup);
            window.rebind($popup);
            $popup.modal('show');
            $popup.on('hidden.bs.modal', function (event) {
                $popup.remove();
            });
            if (data.flash_html) {
                $alerts.append(data.flash_html);
            } else if (data.flash_html === '') {
                $alerts.html('');
            }
        }
    })
    .always(function () {
        if ($button !== undefined ) {
            $button.prop('disabled', false);
        }
    });
};

$(function () {

    var $alerts = $alerts || $('#alerts');

    var done_handler = function (data, textStatus, jqXHR, $initiator) {

        if (data) {
            if (data.redirect_url) {
                if (data.redirect_url == document.URL) {
                    location.reload();
                } else {
                    window.location.href = data.redirect_url;
                }
            }

            // new wrapper can be the same as current, or be insede, or be outside
            if (data.data_html || data.data_html === '') {
                var wrapper, $wrapper;
                var $newData = $(data.data_html);
                if ($initiator) {
                    if ($initiator.data('wrapper')) {
                        $wrapper = $initiator.closest($initiator.data('wrapper'));
                        if ($wrapper.length) {
                            if ($initiator.data('wrapper') == '.modal-content') {
                                $newData = $newData.find('.modal-content');
                            }
                        } else {
                            $wrapper = $($initiator.data("wrapper"));
                        }
                    } else if ($initiator.is('form')) {
                        $wrapper = $initiator.closest('form');
                    } else if ($initiator.is('button')) {
                        $wrapper = $initiator.closest('.model-item');
                    }
                } else if (data.settings && data.settings['wrapper']) {
                    $wrapper = $(data.settings['wrapper']);
                }
                if ($wrapper.length) {
                    $wrapper = $newData.replaceAll($wrapper);
                    window.rebind($wrapper, data.settings);
                }
            } else if (data.settings) {
                window.rebind($('body'), data.settings);
            }

            if (data.flash_html) {
                $alerts.html(data.flash_html);
            }

        } else {
            console.log('Data from ajax request is empty')
        }
    };

    // API for BUTTON that updates content on page (using GET method)
    $(document.body).on('click', 'button[data-api="ajax.get"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');
        var confirm = $button.attr('data-confirm');

        //To prevent multisending
        $button.prop('disabled', true);

        function handle() {
            $.ajax({
                type: 'get',
                url: url,
                data: {'value': $button.val(), 'next': document.URL}
            })
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $button);
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });

    // API for FORM that updates content on page by changing any field
    $(document.body).on('change', 'form[data-api="ajax.autoreload"] :input', function (event) {
        event.preventDefault();
        var $form = $(this).closest('form');
        var $submit = $form.find('input[type="submit"]');

        // To prevent multisending
        $submit.prop('disabled', true);

        // Update URL if form.method == GET
        if ($form.attr('method') == 'GET') {
            var url = $form.attr('action');
            var path = url.indexOf("?") >=0 ? url + '&' + $form.serialize() : url + '?' + $form.serialize();
            path += "&" + $submit.attr("name") + "=" + $submit.val();
            window.history.pushState({}, $(document).find("title").text(), path);
        }

        var formData = $form.serializeArray();
        formData.push({ name: $submit.attr("name"), value: $submit.val() });

        function handle() {
            $.ajax({
                type: $form.attr('method'),
                url: $form.data('api-action') || $form.attr('action'),
                data: formData,
            })
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $form);
            })
            .always(function () {
              $submit.prop('disabled', false);
            });
        }

        handle();
    });

    // API for BUTTON that updates model on page (card usual)
    $(document.body).on('click', 'button[data-api="ajax.update"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');
        var confirm = $button.attr('data-confirm');

        //To prevent multisending
        if (!confirm) {
            $button.prop('disabled', true);
        }

        function handle() {
            if (LocalStorage.get('conf.csrfToken')) {
                var setting = { beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", LocalStorage.get('conf.csrfToken'))
                }}
            }
            $.ajax($.extend(setting, {
                type: 'post',
                url: url,
                data: {'value': $button.val(), 'next': document.URL}
            }))
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $button);
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });

    // API for FORM that works by ajax
    $(document.body).on('click', 'form[data-api="ajax.update"] input[type="submit"]', function (event) {
        event.preventDefault();
        var $form = $(this).closest('form[data-api="ajax.update"]');
        var formData = $form.serializeArray();

        // To prevent multisending
        $(this).prop('disabled', true);

        formData.push({ name: this.name, value: this.value });
        formData.push({ name: 'next', value: document.URL });
        $.ajax({
            type: 'post',
            url: $form.attr('action'),
            data: formData
        })
        .done(function (data, textStatus, jqXHR) {
            done_handler(data, textStatus, jqXHR, $form);
        })
        .always(function () {
            $(this).prop('disabled', false);
        });
    });

    // POPUP - GET
    $(document.body).on('click', 'button[data-api="ajax.popup"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');

        // To prevent multisending
        $button.prop('disabled', true);

        Freya.get_popup(url, $button);
    });

    // POPUP - FORM
    $(document.body).on('click', '.modal[data-api="ajax.popup"] form [type="submit"]', function (event) {
        event.preventDefault();

        //To prevent multisending
        var $button = $(this);
        $button.prop('disabled', true);

        var $form = $button.closest('form');
        var $popup = $form.closest('.modal[data-api="ajax.popup"]');
        var confirm = Boolean(Number($button.attr('confirm')));

        var url = $form.attr('action');
        var formData = $form.serializeArray();
        formData.push({ name: this.name, value: this.value });
        formData.push({ name: 'next', value: document.URL });
        $.post(url, formData).done(function (data, textStatus, jqXHR) {
            if (data) {
                if (data.redirect_url) {
                    if (data.redirect_url == document.URL) {
                        location.reload();
                    } else {
                        window.location.href = data.redirect_url;
                    }
                }
                if (data.settings && data.settings['closePopup']) {
                    $popup.modal('hide');
                    done_handler(data, textStatus, jqXHR, null);
                } else {
                    if (data.data_html) {
                        // To make update quicker and to not reinit popup
                        $popup.find('.modal-body').replaceWith($(data.data_html).find('.modal-body'));
                        window.rebind($popup);
                    }
                    if (data.flash_html) {
                        $alerts.append(data.flash_html);
                    } else if (data.flash_html === '') {
                        $alerts.html('');
                    }
                }
            }
        })
        .always(function () {
          $button.prop('disabled', false);
        });
    });
});
<commit_msg>Add ability to open ajax result in popup<commit_after>"use strict";

var Freya = Freya || {};

Freya.get_popup = function (url, $button) {

    // Ability to load popup via ajax url
    $.get(url).done(function (data, textStatus, jqXHR) {
        if (data) {
            var $popup = $(data.data_html);
            $('body').append($popup);
            window.rebind($popup);
            $popup.modal('show');
            $popup.on('hidden.bs.modal', function (event) {
                $popup.remove();
            });
            if (data.flash_html) {
                $alerts.append(data.flash_html);
            } else if (data.flash_html === '') {
                $alerts.html('');
            }
        }
    })
    .always(function () {
        if ($button !== undefined ) {
            $button.prop('disabled', false);
        }
    });
};

$(function () {

    var $alerts = $alerts || $('#alerts');

    var done_handler = function (data, textStatus, jqXHR, $initiator) {

        if (data) {
            if (data.redirect_url) {
                if (data.redirect_url == document.URL) {
                    location.reload();
                } else {
                    window.location.href = data.redirect_url;
                }
            }

            // new wrapper can be the same as current, or be insede, or be outside
            if (data.data_html || data.data_html === '') {
                var wrapper, $wrapper;
                var $newData = $(data.data_html);
                if (data.settings && data.settings['openPopup']) {
                    var $popup = $newData;
                    $('body').append($popup);
                    window.rebind($popup);
                    $popup.modal('show');
                    $popup.on('hidden.bs.modal', function (event) {
                        $popup.remove();
                    });
                } else {
                    if ($initiator) {
                        if ($initiator.data('wrapper')) {
                            $wrapper = $initiator.closest($initiator.data('wrapper'));
                            if ($wrapper.length) {
                                if ($initiator.data('wrapper') == '.modal-content') {
                                    $newData = $newData.find('.modal-content');
                                }
                            } else {
                                $wrapper = $($initiator.data("wrapper"));
                            }
                        } else if ($initiator.is('form')) {
                            $wrapper = $initiator.closest('form');
                        } else if ($initiator.is('button')) {
                            $wrapper = $initiator.closest('.model-item');
                        }
                    } else if (data.settings && data.settings['wrapper']) {
                        $wrapper = $(data.settings['wrapper']);
                    }
                }
                if ($wrapper && $wrapper.length) {
                    $wrapper = $newData.replaceAll($wrapper);
                    window.rebind($wrapper, data.settings);
                }
            } else if (data.settings) {
                window.rebind($('body'), data.settings);
            }

            if (data.flash_html) {
                $alerts.html(data.flash_html);
            }

        } else {
            console.log('Data from ajax request is empty')
        }
    };

    // API for BUTTON that updates content on page (using GET method)
    $(document.body).on('click', 'button[data-api="ajax.get"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');
        var confirm = $button.attr('data-confirm');

        //To prevent multisending
        $button.prop('disabled', true);

        function handle() {
            $.ajax({
                type: 'get',
                url: url,
                data: {'value': $button.val(), 'next': document.URL}
            })
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $button);
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });

    // API for FORM that updates content on page by changing any field
    $(document.body).on('change', 'form[data-api="ajax.autoreload"] :input', function (event) {
        event.preventDefault();
        var $form = $(this).closest('form');
        var $submit = $form.find('input[type="submit"]');

        // To prevent multisending
        $submit.prop('disabled', true);

        // Update URL if form.method == GET
        if ($form.attr('method') == 'GET') {
            var url = $form.attr('action');
            var path = url.indexOf("?") >=0 ? url + '&' + $form.serialize() : url + '?' + $form.serialize();
            path += "&" + $submit.attr("name") + "=" + $submit.val();
            window.history.pushState({}, $(document).find("title").text(), path);
        }

        var formData = $form.serializeArray();
        formData.push({ name: $submit.attr("name"), value: $submit.val() });

        function handle() {
            $.ajax({
                type: $form.attr('method'),
                url: $form.data('api-action') || $form.attr('action'),
                data: formData,
            })
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $form);
            })
            .always(function () {
              $submit.prop('disabled', false);
            });
        }

        handle();
    });

    // API for BUTTON that updates model on page (card usual)
    $(document.body).on('click', 'button[data-api="ajax.update"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');
        var confirm = $button.attr('data-confirm');

        //To prevent multisending
        if (!confirm) {
            $button.prop('disabled', true);
        }

        function handle() {
            if (LocalStorage.get('conf.csrfToken')) {
                var setting = { beforeSend: function (xhr) {
                    xhr.setRequestHeader("X-CSRFToken", LocalStorage.get('conf.csrfToken'))
                }}
            }
            $.ajax($.extend(setting, {
                type: 'post',
                url: url,
                data: {'value': $button.val(), 'next': document.URL}
            }))
            .done(function (data, textStatus, jqXHR) {
                done_handler(data, textStatus, jqXHR, $button);
            })
            .always(function () {
              $button.prop('disabled', false);
            });
        }

        if (confirm) {
            bootbox.confirm(confirm, function (result) {
                if (result) {
                    handle();
                }
            });
        } else {
            handle();
        }
    });

    // API for FORM that works by ajax
    $(document.body).on('click', 'form[data-api="ajax.update"] input[type="submit"]', function (event) {
        event.preventDefault();
        var $form = $(this).closest('form[data-api="ajax.update"]');
        var formData = $form.serializeArray();

        var $submitBtn = $(this);

        // To prevent multisending
        $submitBtn.prop('disabled', true);

        formData.push({ name: this.name, value: this.value });
        formData.push({ name: 'next', value: document.URL });
        $.ajax({
            type: 'post',
            url: $form.attr('action'),
            data: formData
        })
        .done(function (data, textStatus, jqXHR) {
            done_handler(data, textStatus, jqXHR, $form);
        })
        .always(function () {
            $submitBtn.prop('disabled', false);
        });
    });

    // POPUP - GET
    $(document.body).on('click', 'button[data-api="ajax.popup"]', function (event) {
        event.preventDefault();
        var $button = $(this);
        var url = $button.attr('action');

        // To prevent multisending
        $button.prop('disabled', true);

        Freya.get_popup(url, $button);
    });

    // POPUP - FORM
    $(document.body).on('click', '.modal[data-api="ajax.popup"] form [type="submit"]', function (event) {
        event.preventDefault();

        //To prevent multisending
        var $button = $(this);
        $button.prop('disabled', true);

        var $form = $button.closest('form');
        var $popup = $form.closest('.modal[data-api="ajax.popup"]');
        var confirm = Boolean(Number($button.attr('confirm')));

        var url = $form.attr('action');
        var formData = $form.serializeArray();
        formData.push({ name: this.name, value: this.value });
        formData.push({ name: 'next', value: document.URL });
        $.post(url, formData).done(function (data, textStatus, jqXHR) {
            if (data) {
                if (data.redirect_url) {
                    if (data.redirect_url == document.URL) {
                        location.reload();
                    } else {
                        window.location.href = data.redirect_url;
                    }
                }
                if (data.settings && data.settings['closePopup']) {
                    $popup.modal('hide');
                    done_handler(data, textStatus, jqXHR, null);
                } else {
                    if (data.data_html) {
                        // To make update quicker and to not reinit popup
                        $popup.find('.modal-body').replaceWith($(data.data_html).find('.modal-body'));
                        window.rebind($popup);
                    }
                    if (data.flash_html) {
                        $alerts.append(data.flash_html);
                    } else if (data.flash_html === '') {
                        $alerts.html('');
                    }
                }
            }
        })
        .always(function () {
          $button.prop('disabled', false);
        });
    });
});
<|endoftext|>


<commit_before>var app = angular.module("quicklist", []);

app.factory("StorageService",function(){
  return{
    set: function(key,value){
        localStorage[key] = JSON.stringify(value);
    },
    get: function(key){
      if(localStorage[key])
        return JSON.parse(localStorage[key]);
      else
        throw "invalid key " + key;
    },
    remove: function(key){
      if(localStorage[key])
        delete localStorage[key];
      else
        throw "invalid key " + key;
    }
  };
});

app.factory("TodoListService",function(StorageService){
  return{
    save: function(data){
        list = [];

        for (index in data) {
          item = data[index];

          if (item.type === "text") {
            list.push ({
               text: item.text,
               done: item.done,
               type: item.type
            });

          }
          else if (item.type === 'location') {
              list.push ({
                longitude: item.longitude,
                latitude:  item.latitude,
                type:      item.type
              });
          }

          StorageService.set("TodoList", list);
    },
    load: function(){
        return StorageService.get("TodoList");
    }
  };
});

app.controller("TodoController",function($scope,TodoListService, GeolocalizationService) {
    try{
      $scope.todos = TodoListService.load();
    }
    catch(error){
      $scope.todos = [{text:'Fire',done:true}];
    }
    $scope.addTodo = function() {
      $scope.todos.push({text:$scope.text, done:false, type:"text"});
      $scope.text = '';
      TodoListService.save($scope.todos);
    };

    $scope.geolocalize = function () {
        GeolocalizationService.getPosition (function (position){
            //console.log (position);
            //alert('Lat: ' + position.coords.latitude + ' Long: ' + position.coords.longitude);
            //url = "https://www.google.it/maps?t=m&ll=" + position.coords.latitude + "," + position.coords.longitude + "&z=20&output=classic";

            text = 'Lat: ' + position.coords.latitude + ' Long: ' + position.coords.longitude;

            $scope.todos.push({text: text, done: false, type:'location'});
            $scope.$apply();

            TodoListService.save($scope.todos);
        },
        function ()  {
          alert("Error!");
        });
    };

    $scope.archive = function() {
      var oldTodos = $scope.todos;
      $scope.todos = [];
      angular.forEach(oldTodos, function(todo) {
        if (!todo.done) $scope.todos.push(todo);
      });
      TodoListService.save($scope.todos);
    };

    $scope.deleteTodo = function($index) {
      console.log($index);
      $scope.todos.splice($index,1);
      TodoListService.save($scope.todos);
    };

});
<commit_msg>shfjkfds<commit_after>var app = angular.module("quicklist", []);

app.factory("StorageService",function(){
  return{
    set: function(key,value){
        localStorage[key] = JSON.stringify(value);
    },
    get: function(key){
      if(localStorage[key])
        return JSON.parse(localStorage[key]);
      else
        throw "invalid key " + key;
    },
    remove: function(key){
      if(localStorage[key])
        delete localStorage[key];
      else
        throw "invalid key " + key;
    }
  };
});

app.factory("TodoListService",function(StorageService){
  return{
    save: function(data){
        list = [];

        for (index in data) {
          item = data[index];

          if (item.type === "text") {
            list.push ({
               text: item.text,
               done: item.done,
               type: item.type
            });

          }
          else if (item.type === 'location') {
              list.push ({
                longitude: item.longitude,
                latitude:  item.latitude,
                type:      item.type
              });
          }

          StorageService.set("TodoList", list);
    },
    load: function(){
        return StorageService.get("TodoList");
    }
  };
});

app.controller("TodoController",function($scope,TodoListService, GeolocalizationService) {
    try{
      $scope.todos = TodoListService.load();
    }
    catch(error){
      $scope.todos = [{text:'Fire',done:true}];
    }
    $scope.addTodo = function() {
      $scope.todos.push({text:$scope.text, done:false, type:"text"});
      $scope.text = '';
      TodoListService.save($scope.todos);
    };

    $scope.geolocalize = function () {
        GeolocalizationService.getPosition (function (position){
            //console.log (position);
            //alert('Lat: ' + position.coords.latitude + ' Long: ' + position.coords.longitude);
            //url = "https://www.google.it/maps?t=m&ll=" + position.coords.latitude + "," + position.coords.longitude + "&z=20&output=classic";

            //text = 'Lat: ' + position.coords.latitude + ' Long: ' + position.coords.longitude;

            $scope.todos.push({
              longitude: position.coords.longitude,
              latitude: position.coords.latitude,
              type:'location'
            });

            $scope.$apply();

            TodoListService.save($scope.todos);
        },
        function ()  {
          alert("Error!");
        });
    };

    $scope.archive = function() {
      var oldTodos = $scope.todos;
      $scope.todos = [];
      angular.forEach(oldTodos, function(todo) {
        if (!todo.done) $scope.todos.push(todo);
      });
      TodoListService.save($scope.todos);
    };

    $scope.deleteTodo = function($index) {
      console.log($index);
      $scope.todos.splice($index,1);
      TodoListService.save($scope.todos);
    };

});
<|endoftext|>


<commit_before>requirejs.config({
	shim: {
		'facebook': {
			export: 'FB'
		},
		'backbone': {
			deps: ["underscore", "jquery"],
			exports: "Backbone"
		},
		'underscore': {
			exports: "_"
		},
		'bootstrap': {
			deps: ["jquery"]
		},
		'jquery-ui': {
			deps: ["jquery"]
		}
	},
	"paths": {
		"jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min",
		"jquery-ui": "//code.jquery.com/ui/1.10.3/jquery-ui",
		"facebook": "//connect.facebook.net/en_US/all",
		"underscore": "//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min",
		"backbone": "//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min",
		"json": "//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min",
		"text": "//cdnjs.cloudflare.com/ajax/libs/require-text/2.0.10/text.min",
		'bootstrap': '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min',

		'models': 'app/models/modelIndex',
		'model_want': 'app/models/want',
		'model_wants': 'app/models/wants',
		'model_search_item': 'app/models/searchItem',
		'model_search_results': 'app/models/searchResults',

		'views': 'app/views/viewIndex',
		'view_common': 'app/views/common',
		'view_main': 'app/views/main',
		'view_search': 'app/views/search',

		'utils': 'app/utils'
	}
});

requirejs(["jquery", "underscore", "backbone", "views", "utils", 'bootstrap'], function($, _, Backbone, Views, Utils) {

	// Create a loading indicator. Inspired by
	// http://tbranyen.com/post/how-to-indicate-backbone-fetch-progress
	_.each(["Model", "Collection"], function(name) {
		// Cache Backbone constructor.
		var ctor = Backbone[name];
		// Cache original fetch and set.
		var fetch = ctor.prototype.fetch;

		// Override the fetch method to emit a fetch event.
		ctor.prototype.fetch = function() {
			// Trigger the fetch event on the instance.
			this.trigger("fetch", this);

			// Pass through to original fetch.
			var result = fetch.apply(this, arguments);
			var that = this;
			result.success(function() {
				that.trigger("fetched", that);
			});
			return result;
		};
	});

	var App = _.extend({
		init: function() {
			FB.init({
				appId: '509825915758193',
				channelUrl: '//http://crowdbuy.sapuan.org/channel.html',
				oauth: true
			});
			FB.login(function() {}, {
				scope: 'read_friendlists, user_about_me'
			});

			$('#loginbutton,#feedbutton').removeAttr('disabled');

			FB.getLoginStatus((function(that) {
				return function(response) {
					if (response.status === 'connected') {
						// Handle authentication here.
						Utils.logIn();

						FB.api('/me', function(response) {
							var welcomeString = that._randomWelcome();
							that.userId = response.id;
							$('#welcome').html(welcomeString + response.first_name + '!');

							if (that.view) {
								that.view.userId = response.id;
							}

							that._continueInit();
						});

					} else {
						alert("Whoa, something went wrong! Try refreshing this page.");
					}

				};
			})(this));
		},

		loadHome: function() {
			this.changeView(Views.Main);
		},

		changeView: function(newView) {
			if (typeof this.view !== 'undefined') {
				this.stopListening(this.view);
			}
			this.view = Utils.loadView(newView, this.userId);
			this.listenTo(this.view, 'changeView', this.changeView);
			this.listenTo(this.view, 'goHome', this.loadHome);
		},

		_randomWelcome: function() {
			var welcomeMessages = ["Welcome, ", "Hey ", "Hello ", "Hi "];
			var rand = Math.floor(Math.random() * 4);
			return welcomeMessages[rand];
		},

		_continueInit: function() {
			this.loadHome();

			this.SearchPane = new Views.SearchForm({
				el: '#search-bar',
				id: 'search',
				userId: this.userId
			});

			this.listenTo(this.SearchPane, 'changeView', this.changeView);
			this.listenTo(this.SearchPane, 'goHome', this.loadHome);
			this.listenTo(this.view, 'changeView', this.changeView);
		}

	}, Backbone.Events);
	App.init();

});<commit_msg>Attempt to fix jQuery UI dependency quirks.<commit_after>requirejs.config({
	shim: {
		'facebook': {
			export: 'FB'
		},
		'backbone': {
			deps: ["underscore", "jquery"],
			exports: "Backbone"
		},
		'underscore': {
			exports: "_"
		},
		'bootstrap': {
			deps: ["jquery"]
		},
		'jquery-ui': {
			deps: ["jquery"],
			exports: '$'
		}
	},
	"paths": {
		"jquery": "//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min",
		"jquery-ui": "//code.jquery.com/ui/1.10.3/jquery-ui",
		"facebook": "//connect.facebook.net/en_US/all",
		"underscore": "//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min",
		"backbone": "//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min",
		"json": "//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.min",
		"text": "//cdnjs.cloudflare.com/ajax/libs/require-text/2.0.10/text.min",
		'bootstrap': '//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.0/js/bootstrap.min',

		'models': 'app/models/modelIndex',
		'model_want': 'app/models/want',
		'model_wants': 'app/models/wants',
		'model_search_item': 'app/models/searchItem',
		'model_search_results': 'app/models/searchResults',

		'views': 'app/views/viewIndex',
		'view_common': 'app/views/common',
		'view_main': 'app/views/main',
		'view_search': 'app/views/search',

		'utils': 'app/utils'
	}
});

requirejs(["jquery", "underscore", "backbone", "views", "utils", 'bootstrap'], function($, _, Backbone, Views, Utils) {

	// Create a loading indicator. Inspired by
	// http://tbranyen.com/post/how-to-indicate-backbone-fetch-progress
	_.each(["Model", "Collection"], function(name) {
		// Cache Backbone constructor.
		var ctor = Backbone[name];
		// Cache original fetch and set.
		var fetch = ctor.prototype.fetch;

		// Override the fetch method to emit a fetch event.
		ctor.prototype.fetch = function() {
			// Trigger the fetch event on the instance.
			this.trigger("fetch", this);

			// Pass through to original fetch.
			var result = fetch.apply(this, arguments);
			var that = this;
			result.success(function() {
				that.trigger("fetched", that);
			});
			return result;
		};
	});

	var App = _.extend({
		init: function() {
			FB.init({
				appId: '509825915758193',
				channelUrl: '//http://crowdbuy.sapuan.org/channel.html',
				oauth: true
			});
			FB.login(function() {}, {
				scope: 'read_friendlists, user_about_me'
			});

			$('#loginbutton,#feedbutton').removeAttr('disabled');

			FB.getLoginStatus((function(that) {
				return function(response) {
					if (response.status === 'connected') {
						// Handle authentication here.
						Utils.logIn();

						FB.api('/me', function(response) {
							var welcomeString = that._randomWelcome();
							that.userId = response.id;
							$('#welcome').html(welcomeString + response.first_name + '!');

							if (that.view) {
								that.view.userId = response.id;
							}

							that._continueInit();
						});

					} else {
						alert("Whoa, something went wrong! Try refreshing this page.");
					}

				};
			})(this));
		},

		loadHome: function() {
			this.changeView(Views.Main);
		},

		changeView: function(newView) {
			if (typeof this.view !== 'undefined') {
				this.stopListening(this.view);
			}
			this.view = Utils.loadView(newView, this.userId);
			this.listenTo(this.view, 'changeView', this.changeView);
			this.listenTo(this.view, 'goHome', this.loadHome);
		},

		_randomWelcome: function() {
			var welcomeMessages = ["Welcome, ", "Hey ", "Hello ", "Hi "];
			var rand = Math.floor(Math.random() * 4);
			return welcomeMessages[rand];
		},

		_continueInit: function() {
			this.loadHome();

			this.SearchPane = new Views.SearchForm({
				el: '#search-bar',
				id: 'search',
				userId: this.userId
			});

			this.listenTo(this.SearchPane, 'changeView', this.changeView);
			this.listenTo(this.SearchPane, 'goHome', this.loadHome);
			this.listenTo(this.view, 'changeView', this.changeView);
		}

	}, Backbone.Events);
	App.init();

});<|endoftext|>


<commit_before>(function($)
{
  var router = new $.mobile.Router( [
   {"#page-authorize": {handler: "pageAuthorize",
         events: "s", // do when we show the page
         argsre: true
       } },

        {"#home": {handler: "home",
          events: "s", // do when we show the page
          argsre: true
        } },

        {"#listing": {handler: "listing",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#registering-ruleset": {handler: "registeringRuleset",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#confirming-deletion": {handler: "confirmingDeletion",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#updating-url": {handler: "updatingUrl",
          events: "s", // do when we show the page
          argsre: true
        } }
        ],
        {
          pageAuthorize: function(type, match, ui, page) {
            console.log("manage fuse: authorize page");
            $.mobile.loading("hide");
          },

          home: function(type, match, ui, page) {
            console.log("home Handler");
          },

          listing: function(type, match, ui, page) {
            console.log("listing Handler");

            //get the ruleset here using CloudOS??
            //var rulesets_list = Devtools.getRulesets();
           // var json_text = Devtools.getRulesets();
           // var ruleset_obj = JSON.parse(json_text);

           // console.log(ruleset_obj);
          var obj_json = "'" + Devtools.getRulesets() + "'";
          //var obj_json = '[{"rid":"b506607x0.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/HelloWorld.krl"},{"rid_index":0,"last_modified":1418237853,"rid":"b506607x0.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/HelloWorld.krl","prefix":"b506607"},{"rid":"b506607x1.dev","uri":"w.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl"},{"rid_index":1,"last_modified":1418234018,"rid":"b506607x1.prod","uri":"w.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl","prefix":"b506607"},{"last_modified":1422397298,"rid":"b506607x10.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl"},{"rid_index":10,"last_modified":1423525230,"rid":"b506607x10.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl","prefix":"b506607"},{"rid":"b506607x11.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl"},{"rid_index":11,"last_modified":1418237853,"rid":"b506607x11.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl","prefix":"b506607"},{"last_modified":1418234156,"rid":"b506607x12.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlog.krl"},{"rid_index":12,"rid":"b506607x12.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlog.krl","prefix":"b506607"},{"last_modified":1418238023,"rid":"b506607x13.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlogData.krl"},{"rid_index":13,"rid":"b506607x13.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlogData.krl","prefix":"b506607"},{"last_modified":1423689382,"rid":"b506607x14.dev","uri":"https://raw.githubusercontent.com/kre/devtools/gh-pages/ruleSets/devtools.krl"},{"rid_index":14,"last_modified":1423525738,"rid":"b506607x14.prod","uri":"https://raw.githubusercontent.com/kre/devtools/gh-pages/ruleSets/devtools.krl","prefix":"b506607"},{"last_modified":1412788749,"rid":"b506607x2.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl"},{"rid_index":2,"last_modified":1418234018,"rid":"b506607x2.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl","prefix":"b506607"},{"rid":"b506607x3.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter7Ruleset.krl"},{"rid_index":3,"last_modified":1418237852,"rid":"b506607x3.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter7Ruleset.krl","prefix":"b506607"},{"rid":"b506607x4.dev","uri":"https://raw.github.com/bobsmeuncle/Practice-with-KRL/master/ch7book_example.krl"},{"rid_index":4,"last_modified":1418234018,"rid":"b506607x4.prod","uri":"https://raw.github.com/bobsmeuncle/Practice-with-KRL/master/ch7book_example.krl","prefix":"b506607"},{"rid":"b506607x5.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/ch8RottenTomatoes"},{"rid_index":5,"last_modified":1418234018,"rid":"b506607x5.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/ch8RottenTomatoes","prefix":"b506607"},{"last_modified":1421862706,"rid":"b506607x6.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter9.krl"},{"rid_index":6,"last_modified":1421736146,"rid":"b506607x6.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter9.krl","prefix":"b506607"},{"rid":"b506607x7.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/setA.krl"},{"rid_index":7,"last_modified":1418237852,"rid":"b506607x7.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/setA.krl","prefix":"b506607"},{"rid":"b506607x8.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/steB.krl"},{"rid_index":8,"last_modified":1418237852,"rid":"b506607x8.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/steB.krl","prefix":"b506607"},{"last_modified":1421862706,"rid":"b506607x9.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/pythonCode/buttonpresssed.krl"},{"rid_index":9,"last_modified":1421862708,"rid":"b506607x9.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/pythonCode/buttonpresssed.krl","prefix":"b506607"}]';
          var obj = JSON.parse(obj_json);
         // document.getElementById("List-Rulesets").innerHTML = obj;

            //$("#List-Rulesets").html("
"+ruleset_obj+"
");
            //$('#List-Rulesets').listview('refresh');

            //console.log(obj.rid);
            //console.log(ruleset_obj.rid);
            var len = obj.length;
            var txt = "";
            if(len > 0){
                for(var i=0;i<len;i++){
                    txt += "
"+obj[i].rid+"	"+obj[i].uri+"
";

                  }
                if(txt !== ""){
                        $("#ruleset-list").append(txt);
                  }
            }

            /*var frm = "#ruleset-form";
            $(frm)[0].reset();
            var owner_eci = CloudOS.defaultECI; //from pageUpdateProfile

            var rulesetJSON = Devtools.showRulesets()

              $("#RID", frm).val(ruleset_obj.rid);
              $("#source-URL", frm).val(ruleset_obj.uri);*/

           // $("#List-Rulesets").html(
             // obj.name + "
" +
             // obj.street + "
" +
              //obj.phone;);

          },
          registeringRuleset: function(type, match, ui, page) {
            console.log("registering Ruleset Handler");
          },
          confirmingDeletion: function(type, match, ui, page) {
            console.log("confirming Deletion Handler");
          },
          updatingUrl: function(type, match, ui, page) {
            console.log("updating Url Handler");
          }
        },
      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route (" + type + ", " + ui + ", " + page + ")");
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });

function plant_authorize_button()
{
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);

      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

    function onPageLoad() {// Document.Ready
    	console.log("document ready");
      CloudOS.retrieveSession();

  // only put static stuff here...
  plant_authorize_button();

  $('.logout').off("tap").on("tap", function(event)
  {
            CloudOS.removeSession(true); // true for hard reset (log out of login server too)
            $.mobile.changePage('#page-authorize', {
              transition: 'slide'
            }); // this will go to the authorization page.

          });

  try {
    var authd = CloudOS.authenticatedSession();
    if(authd) {
      console.log("Authorized");
      document.location.hash = "#home";
    } else {
      console.log("Asking for authorization");
      document.location.hash = "#page-authorize";
    }
  } catch (exception) {

  } finally {
    $.mobile.initializePage();
    $.mobile.loading("hide");
  }

}

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
    $(document).bind("mobileinit", onMobileInit);
    $(document).ready(onPageLoad);
  })(jQuery);
<commit_msg>seeing if  devtools.getRulesets is array or obj<commit_after>(function($)
{
  var router = new $.mobile.Router( [
   {"#page-authorize": {handler: "pageAuthorize",
         events: "s", // do when we show the page
         argsre: true
       } },

        {"#home": {handler: "home",
          events: "s", // do when we show the page
          argsre: true
        } },

        {"#listing": {handler: "listing",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#registering-ruleset": {handler: "registeringRuleset",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#confirming-deletion": {handler: "confirmingDeletion",
          events: "s", // do when we show the page
          argsre: true
        } },
        {"#updating-url": {handler: "updatingUrl",
          events: "s", // do when we show the page
          argsre: true
        } }
        ],
        {
          pageAuthorize: function(type, match, ui, page) {
            console.log("manage fuse: authorize page");
            $.mobile.loading("hide");
          },

          home: function(type, match, ui, page) {
            console.log("home Handler");
          },

          listing: function(type, match, ui, page) {
            console.log("listing Handler");

            //var rulesets_list = Devtools.getRulesets();
           // var json_text = Devtools.getRulesets();
           // var ruleset_obj = JSON.parse(json_text);

           // console.log(ruleset_obj);
          var obj = Devtools.getRulesets();
          console.log(obj);
          //var obj_json = '[{"rid":"b506607x0.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/HelloWorld.krl"},{"rid_index":0,"last_modified":1418237853,"rid":"b506607x0.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/HelloWorld.krl","prefix":"b506607"},{"rid":"b506607x1.dev","uri":"w.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl"},{"rid_index":1,"last_modified":1418234018,"rid":"b506607x1.prod","uri":"w.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl","prefix":"b506607"},{"last_modified":1422397298,"rid":"b506607x10.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl"},{"rid_index":10,"last_modified":1423525230,"rid":"b506607x10.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl","prefix":"b506607"},{"rid":"b506607x11.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl"},{"rid_index":11,"last_modified":1418237853,"rid":"b506607x11.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/StockChecker.krl","prefix":"b506607"},{"last_modified":1418234156,"rid":"b506607x12.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlog.krl"},{"rid_index":12,"rid":"b506607x12.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlog.krl","prefix":"b506607"},{"last_modified":1418238023,"rid":"b506607x13.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlogData.krl"},{"rid_index":13,"rid":"b506607x13.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/smsBlogData.krl","prefix":"b506607"},{"last_modified":1423689382,"rid":"b506607x14.dev","uri":"https://raw.githubusercontent.com/kre/devtools/gh-pages/ruleSets/devtools.krl"},{"rid_index":14,"last_modified":1423525738,"rid":"b506607x14.prod","uri":"https://raw.githubusercontent.com/kre/devtools/gh-pages/ruleSets/devtools.krl","prefix":"b506607"},{"last_modified":1412788749,"rid":"b506607x2.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl"},{"rid_index":2,"last_modified":1418234018,"rid":"b506607x2.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/RuleExercise1.krl","prefix":"b506607"},{"rid":"b506607x3.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter7Ruleset.krl"},{"rid_index":3,"last_modified":1418237852,"rid":"b506607x3.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter7Ruleset.krl","prefix":"b506607"},{"rid":"b506607x4.dev","uri":"https://raw.github.com/bobsmeuncle/Practice-with-KRL/master/ch7book_example.krl"},{"rid_index":4,"last_modified":1418234018,"rid":"b506607x4.prod","uri":"https://raw.github.com/bobsmeuncle/Practice-with-KRL/master/ch7book_example.krl","prefix":"b506607"},{"rid":"b506607x5.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/ch8RottenTomatoes"},{"rid_index":5,"last_modified":1418234018,"rid":"b506607x5.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/ch8RottenTomatoes","prefix":"b506607"},{"last_modified":1421862706,"rid":"b506607x6.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter9.krl"},{"rid_index":6,"last_modified":1421736146,"rid":"b506607x6.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/chapter9.krl","prefix":"b506607"},{"rid":"b506607x7.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/setA.krl"},{"rid_index":7,"last_modified":1418237852,"rid":"b506607x7.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/setA.krl","prefix":"b506607"},{"rid":"b506607x8.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/steB.krl"},{"rid_index":8,"last_modified":1418237852,"rid":"b506607x8.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/steB.krl","prefix":"b506607"},{"last_modified":1421862706,"rid":"b506607x9.dev","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/pythonCode/buttonpresssed.krl"},{"rid_index":9,"last_modified":1421862708,"rid":"b506607x9.prod","uri":"https://raw.githubusercontent.com/bobsmeuncle/Practice-with-KRL/master/pythonCode/buttonpresssed.krl","prefix":"b506607"}]';
          // var obj = JSON.parse(obj_json);
         // document.getElementById("List-Rulesets").innerHTML = obj;

            //$("#List-Rulesets").html("
"+ruleset_obj+"
");
            //$('#List-Rulesets').listview('refresh');

            //console.log(obj.rid);
            //console.log(ruleset_obj.rid);
            var len = obj.length;
            var txt = "";
            if(len > 0){
                for(var i=0;i<len;i++){
                    txt += "
"+obj[i].rid+"	"+obj[i].uri+"
";

                  }
                if(txt !== ""){
                        $("#ruleset-list").append(txt);
                  }
            }

            /*var frm = "#ruleset-form";
            $(frm)[0].reset();
            var owner_eci = CloudOS.defaultECI; //from pageUpdateProfile

            var rulesetJSON = Devtools.showRulesets();

              $("#RID", frm).val(ruleset_obj.rid);
              $("#source-URL", frm).val(ruleset_obj.uri);*/

           // $("#List-Rulesets").html(
             // obj.name + "
" +
             // obj.street + "
" +
              //obj.phone;);

          },
          registeringRuleset: function(type, match, ui, page) {
            console.log("registering Ruleset Handler");
          },
          confirmingDeletion: function(type, match, ui, page) {
            console.log("confirming Deletion Handler");
          },
          updatingUrl: function(type, match, ui, page) {
            console.log("updating Url Handler");
          }
        },
      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route (" + type + ", " + ui + ", " + page + ")");
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });

function plant_authorize_button()
{
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);

      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

    function onPageLoad() {// Document.Ready
    	console.log("document ready");
      CloudOS.retrieveSession();

  // only put static stuff here...
  plant_authorize_button();

  $('.logout').off("tap").on("tap", function(event)
  {
            CloudOS.removeSession(true); // true for hard reset (log out of login server too)
            $.mobile.changePage('#page-authorize', {
              transition: 'slide'
            }); // this will go to the authorization page.

          });

  try {
    var authd = CloudOS.authenticatedSession();
    if(authd) {
      console.log("Authorized");
      document.location.hash = "#home";
    } else {
      console.log("Asking for authorization");
      document.location.hash = "#page-authorize";
    }
  } catch (exception) {

  } finally {
    $.mobile.initializePage();
    $.mobile.loading("hide");
  }

}

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
    $(document).bind("mobileinit", onMobileInit);
    $(document).ready(onPageLoad);
  })(jQuery);
<|endoftext|>


<commit_before>/**
 * Main application file for: minnpost-hennepin-county-parcels
 *
 * This pulls in all the parts
 * and creates the main object for the application.
 */

// Create main application
define('minnpost-hennepin-county-parcels', [
  'jquery', 'underscore', 'leafletUTFGrid', 'mpConfig', 'mpFormatters', 'mpMaps', 'helpers',
  'text!templates/application.underscore',
  'text!templates/map-tooltip.underscore'
], function(
  $, _, LUTF, mpConfig, mpFormatters, mpMaps, helpers, tApplication, tTooltip
  ) {

  // Constructor for app
  var App = function(options) {
    this.options = _.extend(this.defaultOptions, options);
    this.el = this.options.el;
    this.$el = $(this.el);
    this.$ = function(selector) { return this.$el.find(selector); };
    this.$content = this.$el.find('.content-container');
    this.loadApp();
  };

  // Extend with custom methods
  _.extend(App.prototype, {
    // Start function
    start: function() {
      var thisApp = this;

      // Create main application view
      this.$el.html(_.template(tApplication, {
        legend: {
          '#F1F1F1': '$0 or no data.',
          '#543005': '$0 - $100k',
          '#8c510a': '$100k - $250k',
          '#bf812d': '$250k - $500',
          '#dfc27d': '$500 - $1M',
          '#c7eae5': '$1M - $2M',
          '#80cdc1': '$2M - $5M',
          '#35978f': '$5M - $20M',
          '#01665e': '$20M - $100M',
          '#003c30': 'above $100M'
        }
      }));

      // Make tooltip template
      this.tooltipTemplate = _.template(tTooltip);

      // Get tilejson data
      $.ajax({
        url: this.options.tilestream_base + this.options.tilestream_map + '.json?callback=?',
        dataType: 'jsonp',
        jsonpCallback: 'mpCacheBuster',
        cache: true,
        success: function(data) {
          console.log(data);
          thisApp.tilejson = data;
          thisApp.makeMap();
          thisApp.handleEvents();
        }
      });
    },

    // Put together map
    makeMap: function() {
      var thisApp = this;

      // Mapbox.js doesn't seem to play nicely with cross domain requests
      // to our custom tilestream server (though it looks like the appropriate
      // headers are there).  So, we use a different library for the UTF grid

      // Map
      this.map = new L.map('h-county-parcels', {
        minZoom: this.tilejson.minzoom,
        maxZoom: this.tilejson.maxzoom,
        scrollWheelZoom: false,
        trackResize: true
      }).setView([this.tilejson.center[1], this.tilejson.center[0]], this.tilejson.center[2]);
      this.map.removeControl(this.map.attributionControl);

      // Add tooltip control
      this.tooltip = new mpMaps.TooltipControl();
      this.map.addControl(this.tooltip);

      // Add main map
      L.tileLayer(this.options.tilestream_base + this.options.tilestream_map +
        '/{z}/{x}/{y}.png', {
      }).addTo(this.map);

      // Add main map grid
      this.grid = new L.UtfGrid(this.options.tilestream_base +
        this.options.tilestream_map + '/{z}/{x}/{y}.grid.json?callback={cb}', {
        useJsonP: true
      });
      this.grid.on('mouseover', function(e) {
        e.data = thisApp.parseParcelData(e.data);
        thisApp.tooltip.update(thisApp.tooltipTemplate({
          format: mpFormatters,
          data: e.data
        }));
      });
      this.grid.on('mouseout', function(e) {
        thisApp.tooltip.hide();
      });
      this.map.addLayer(this.grid);

      // Add street overlay, limit view to when zoomed further in
      L.tileLayer(this.options.mapbox_base + 'minnpost.map-dotjndlk/{z}/{x}/{y}.png', {
        zIndex: 100
      }).addTo(this.map);

      // Add terrain underlay
      L.tileLayer(this.options.mapbox_base + 'minnpost.map-vhjzpwel/{z}/{x}/{y}.png', {
        zIndex: -100
      }).addTo(this.map);

      // This way doesn't work with cross domain stuff, though its simpler
      /*
      // Override urls for Mapbox
      L.mapbox.config.HTTP_URLS = [tilestream_base];

      // Make base map
      this.map = L.mapbox.map('h-county-parcels', 'hennepin-parcels', {
        minZoom: 10,
        maxZoom: 16
      });
      // Remove mapbox control
      this.map.removeControl(this.map.infoControl);

      // Add street overlay
      L.tileLayer(mapbox_base + 'minnpost.map-dotjndlk/{z}/{x}/{y}.png', {
        zIndex: 100,
        minZoom: 12
      }).addTo(this.map);

      // Add terrain underlay
      L.tileLayer(mapbox_base + 'minnpost.map-vhjzpwel/{z}/{x}/{y}.png', {
        zIndex: -100
      }).addTo(this.map);
      */

      // For whatever reason, the map may not load complete, probably
      // due to the face that the DOM element for it is not
      // completely loaded
      _.delay(function() {
        thisApp.map.invalidateSize();
      }, 750);
    },

    // Handle some events
    handleEvents: function() {
      var thisApp = this;
      var places = {
        'harriet': {
          loc: [44.92236863873383, -93.30546547367703],
          zoom: 14
        },
        'ids': {
          loc: [44.97611437647188, -93.27250648930203],
          zoom: 15
        }
      };

      this.$el.find('.location-link').on('click', function(e) {
        e.preventDefault();
        var place = $(this).data('location');
        if (_.isObject(places[place])) {
          thisApp.map.setView(places[place].loc, places[place].zoom);
        }
      });

    },

    // Make the data a tad better
    parseParcelData: function(data) {
      data.BUILD_YR = (data.BUILD_YR == '0000' || data.BUILD_YR < 1) ? null : data.BUILD_YR;
      return data;
    },

    // Default options
    defaultOptions: {
      projectName: 'minnpost-hennepin-county-parcels',
      remoteProxy: null,
      el: '.minnpost-hennepin-county-parcels-container',
      // We our using a temporary Tilestream server, so we override
      // what Mapbox usually expects
      tilestream_base: '//ec2-54-82-59-19.compute-1.amazonaws.com:9003/v2/',
      tilestream_map: 'hennepin-parcels',
      mapbox_base: '//{s}.tiles.mapbox.com/v3/',
      availablePaths: {
        local: {
          css: ['.tmp/css/main.css'],
          images: 'images/',
          data: 'data/'
        },
        build: {
          css: [
            '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css',
            'dist/minnpost-hennepin-county-parcels.libs.min.css',
            'dist/minnpost-hennepin-county-parcels.latest.min.css'
          ],
          ie: [
            'dist/minnpost-hennepin-county-parcels.libs.min.ie.css',
            'dist/minnpost-hennepin-county-parcels.latest.min.ie.css'
          ],
          images: 'dist/images/',
          data: 'dist/data/'
        },
        deploy: {
          css: [
            '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css',  'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/minnpost-hennepin-county-parcels.libs.min.css',
            'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/minnpost-hennepin-county-parcels.latest.min.css'
          ],
          ie: [  'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/minnpost-hennepin-county-parcels.libs.min.ie.css',
            'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/minnpost-hennepin-county-parcels.latest.min.ie.css'
          ],
          images: 'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/images/',
          data: 'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/data/'
        }
      }
    },

    // Load up app
    loadApp: function() {
      this.determinePaths();
      this.getLocalAssests(function(map) {
        this.renderAssests(map);
        this.start();
      });
    },

    // Determine paths.  A bit hacky.
    determinePaths: function() {
      var query;
      this.options.deployment = 'deploy';

      if (window.location.host.indexOf('localhost') !== -1) {
        this.options.deployment = 'local';

        // Check if a query string forces something
        query = helpers.parseQueryString();
        if (_.isObject(query) && _.isString(query.mpDeployment)) {
          this.options.deployment = query.mpDeployment;
        }
      }

      this.options.paths = this.options.availablePaths[this.options.deployment];
    },

    // Get local assests, if needed
    getLocalAssests: function(callback) {
      var thisApp = this;

      // If local read in the bower map
      if (this.options.deployment === 'local') {
        $.getJSON('bower.json', function(data) {
          callback.apply(thisApp, [data.dependencyMap]);
        });
      }
      else {
        callback.apply(this, []);
      }
    },

    // Rendering tasks
    renderAssests: function(map) {
      var isIE = (helpers.isMSIE() && helpers.isMSIE() <= 8);

      // Add CSS from bower map
      if (_.isObject(map)) {
        _.each(map, function(c, ci) {
          if (c.css) {
            _.each(c.css, function(s, si) {
              s = (s.match(/^(http|\/\/)/)) ? s : 'bower_components/' + s + '.css';
              $('head').append('<link rel="stylesheet" href="' + s + '" type="text/css" />');
            });
          }
          if (c.ie && isIE) {
            _.each(c.ie, function(s, si) {
              s = (s.match(/^(http|\/\/)/)) ? s : 'bower_components/' + s + '.css';
              $('head').append('<link rel="stylesheet" href="' + s + '" type="text/css" />');
            });
          }
        });
      }

      // Get main CSS
      _.each(this.options.paths.css, function(c, ci) {
        $('head').append('<link rel="stylesheet" href="' + c + '" type="text/css" />');
      });
      if (isIE) {
        _.each(this.options.paths.ie, function(c, ci) {
          $('head').append('<link rel="stylesheet" href="' + c + '" type="text/css" />');
        });
      }

      // Add a processed class
      this.$el.addClass('processed');
    }
  });

  return App;
});

/**
 * Run application
 */
require(['jquery', 'minnpost-hennepin-county-parcels'], function($, App) {
  $(document).ready(function() {
    var app = new App();
  });
});
<commit_msg>Removing console statement.<commit_after>/**
 * Main application file for: minnpost-hennepin-county-parcels
 *
 * This pulls in all the parts
 * and creates the main object for the application.
 */

// Create main application
define('minnpost-hennepin-county-parcels', [
  'jquery', 'underscore', 'leafletUTFGrid', 'mpConfig', 'mpFormatters', 'mpMaps', 'helpers',
  'text!templates/application.underscore',
  'text!templates/map-tooltip.underscore'
], function(
  $, _, LUTF, mpConfig, mpFormatters, mpMaps, helpers, tApplication, tTooltip
  ) {

  // Constructor for app
  var App = function(options) {
    this.options = _.extend(this.defaultOptions, options);
    this.el = this.options.el;
    this.$el = $(this.el);
    this.$ = function(selector) { return this.$el.find(selector); };
    this.$content = this.$el.find('.content-container');
    this.loadApp();
  };

  // Extend with custom methods
  _.extend(App.prototype, {
    // Start function
    start: function() {
      var thisApp = this;

      // Create main application view
      this.$el.html(_.template(tApplication, {
        legend: {
          '#F1F1F1': '$0 or no data.',
          '#543005': '$0 - $100k',
          '#8c510a': '$100k - $250k',
          '#bf812d': '$250k - $500',
          '#dfc27d': '$500 - $1M',
          '#c7eae5': '$1M - $2M',
          '#80cdc1': '$2M - $5M',
          '#35978f': '$5M - $20M',
          '#01665e': '$20M - $100M',
          '#003c30': 'above $100M'
        }
      }));

      // Make tooltip template
      this.tooltipTemplate = _.template(tTooltip);

      // Get tilejson data
      $.ajax({
        url: this.options.tilestream_base + this.options.tilestream_map + '.json?callback=?',
        dataType: 'jsonp',
        jsonpCallback: 'mpCacheBuster',
        cache: true,
        success: function(data) {
          thisApp.tilejson = data;
          thisApp.makeMap();
          thisApp.handleEvents();
        }
      });
    },

    // Put together map
    makeMap: function() {
      var thisApp = this;

      // Mapbox.js doesn't seem to play nicely with cross domain requests
      // to our custom tilestream server (though it looks like the appropriate
      // headers are there).  So, we use a different library for the UTF grid

      // Map
      this.map = new L.map('h-county-parcels', {
        minZoom: this.tilejson.minzoom,
        maxZoom: this.tilejson.maxzoom,
        scrollWheelZoom: false,
        trackResize: true
      }).setView([this.tilejson.center[1], this.tilejson.center[0]], this.tilejson.center[2]);
      this.map.removeControl(this.map.attributionControl);

      // Add tooltip control
      this.tooltip = new mpMaps.TooltipControl();
      this.map.addControl(this.tooltip);

      // Add main map
      L.tileLayer(this.options.tilestream_base + this.options.tilestream_map +
        '/{z}/{x}/{y}.png', {
      }).addTo(this.map);

      // Add main map grid
      this.grid = new L.UtfGrid(this.options.tilestream_base +
        this.options.tilestream_map + '/{z}/{x}/{y}.grid.json?callback={cb}', {
        useJsonP: true
      });
      this.grid.on('mouseover', function(e) {
        e.data = thisApp.parseParcelData(e.data);
        thisApp.tooltip.update(thisApp.tooltipTemplate({
          format: mpFormatters,
          data: e.data
        }));
      });
      this.grid.on('mouseout', function(e) {
        thisApp.tooltip.hide();
      });
      this.map.addLayer(this.grid);

      // Add street overlay, limit view to when zoomed further in
      L.tileLayer(this.options.mapbox_base + 'minnpost.map-dotjndlk/{z}/{x}/{y}.png', {
        zIndex: 100
      }).addTo(this.map);

      // Add terrain underlay
      L.tileLayer(this.options.mapbox_base + 'minnpost.map-vhjzpwel/{z}/{x}/{y}.png', {
        zIndex: -100
      }).addTo(this.map);

      // This way doesn't work with cross domain stuff, though its simpler
      /*
      // Override urls for Mapbox
      L.mapbox.config.HTTP_URLS = [tilestream_base];

      // Make base map
      this.map = L.mapbox.map('h-county-parcels', 'hennepin-parcels', {
        minZoom: 10,
        maxZoom: 16
      });
      // Remove mapbox control
      this.map.removeControl(this.map.infoControl);

      // Add street overlay
      L.tileLayer(mapbox_base + 'minnpost.map-dotjndlk/{z}/{x}/{y}.png', {
        zIndex: 100,
        minZoom: 12
      }).addTo(this.map);

      // Add terrain underlay
      L.tileLayer(mapbox_base + 'minnpost.map-vhjzpwel/{z}/{x}/{y}.png', {
        zIndex: -100
      }).addTo(this.map);
      */

      // For whatever reason, the map may not load complete, probably
      // due to the face that the DOM element for it is not
      // completely loaded
      _.delay(function() {
        thisApp.map.invalidateSize();
      }, 750);
    },

    // Handle some events
    handleEvents: function() {
      var thisApp = this;
      var places = {
        'harriet': {
          loc: [44.92236863873383, -93.30546547367703],
          zoom: 14
        },
        'ids': {
          loc: [44.97611437647188, -93.27250648930203],
          zoom: 15
        }
      };

      this.$el.find('.location-link').on('click', function(e) {
        e.preventDefault();
        var place = $(this).data('location');
        if (_.isObject(places[place])) {
          thisApp.map.setView(places[place].loc, places[place].zoom);
        }
      });

    },

    // Make the data a tad better
    parseParcelData: function(data) {
      data.BUILD_YR = (data.BUILD_YR == '0000' || data.BUILD_YR < 1) ? null : data.BUILD_YR;
      return data;
    },

    // Default options
    defaultOptions: {
      projectName: 'minnpost-hennepin-county-parcels',
      remoteProxy: null,
      el: '.minnpost-hennepin-county-parcels-container',
      // We our using a temporary Tilestream server, so we override
      // what Mapbox usually expects
      tilestream_base: '//ec2-54-82-59-19.compute-1.amazonaws.com:9003/v2/',
      tilestream_map: 'hennepin-parcels',
      mapbox_base: '//{s}.tiles.mapbox.com/v3/',
      availablePaths: {
        local: {
          css: ['.tmp/css/main.css'],
          images: 'images/',
          data: 'data/'
        },
        build: {
          css: [
            '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css',
            'dist/minnpost-hennepin-county-parcels.libs.min.css',
            'dist/minnpost-hennepin-county-parcels.latest.min.css'
          ],
          ie: [
            'dist/minnpost-hennepin-county-parcels.libs.min.ie.css',
            'dist/minnpost-hennepin-county-parcels.latest.min.ie.css'
          ],
          images: 'dist/images/',
          data: 'dist/data/'
        },
        deploy: {
          css: [
            '//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css',  'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/minnpost-hennepin-county-parcels.libs.min.css',
            'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/minnpost-hennepin-county-parcels.latest.min.css'
          ],
          ie: [  'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/minnpost-hennepin-county-parcels.libs.min.ie.css',
            'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/minnpost-hennepin-county-parcels.latest.min.ie.css'
          ],
          images: 'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/images/',
          data: 'https://s3.amazonaws.com/data.minnpost/projects/minnpost-hennepin-county-parcels/data/'
        }
      }
    },

    // Load up app
    loadApp: function() {
      this.determinePaths();
      this.getLocalAssests(function(map) {
        this.renderAssests(map);
        this.start();
      });
    },

    // Determine paths.  A bit hacky.
    determinePaths: function() {
      var query;
      this.options.deployment = 'deploy';

      if (window.location.host.indexOf('localhost') !== -1) {
        this.options.deployment = 'local';

        // Check if a query string forces something
        query = helpers.parseQueryString();
        if (_.isObject(query) && _.isString(query.mpDeployment)) {
          this.options.deployment = query.mpDeployment;
        }
      }

      this.options.paths = this.options.availablePaths[this.options.deployment];
    },

    // Get local assests, if needed
    getLocalAssests: function(callback) {
      var thisApp = this;

      // If local read in the bower map
      if (this.options.deployment === 'local') {
        $.getJSON('bower.json', function(data) {
          callback.apply(thisApp, [data.dependencyMap]);
        });
      }
      else {
        callback.apply(this, []);
      }
    },

    // Rendering tasks
    renderAssests: function(map) {
      var isIE = (helpers.isMSIE() && helpers.isMSIE() <= 8);

      // Add CSS from bower map
      if (_.isObject(map)) {
        _.each(map, function(c, ci) {
          if (c.css) {
            _.each(c.css, function(s, si) {
              s = (s.match(/^(http|\/\/)/)) ? s : 'bower_components/' + s + '.css';
              $('head').append('<link rel="stylesheet" href="' + s + '" type="text/css" />');
            });
          }
          if (c.ie && isIE) {
            _.each(c.ie, function(s, si) {
              s = (s.match(/^(http|\/\/)/)) ? s : 'bower_components/' + s + '.css';
              $('head').append('<link rel="stylesheet" href="' + s + '" type="text/css" />');
            });
          }
        });
      }

      // Get main CSS
      _.each(this.options.paths.css, function(c, ci) {
        $('head').append('<link rel="stylesheet" href="' + c + '" type="text/css" />');
      });
      if (isIE) {
        _.each(this.options.paths.ie, function(c, ci) {
          $('head').append('<link rel="stylesheet" href="' + c + '" type="text/css" />');
        });
      }

      // Add a processed class
      this.$el.addClass('processed');
    }
  });

  return App;
});

/**
 * Run application
 */
require(['jquery', 'minnpost-hennepin-county-parcels'], function($, App) {
  $(document).ready(function() {
    var app = new App();
  });
});
<|endoftext|>