<commit_before>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/
var config            = require('./config'),
    cordova           = require('./cordova'),
    cordova_util      = require('./util'),
    ConfigParser      = require('./ConfigParser'),
    util              = require('util'),
    fs                = require('fs'),
    os                = require('os'),
    path              = require('path'),
    hooker            = require('./hooker'),
    events            = require('./events'),
    lazy_load         = require('./lazy_load'),
    CordovaError      = require('../CordovaError'),
    Q                 = require('q'),
    platforms         = require('./platforms'),
    superspawn        = require('./superspawn'),
    semver            = require('semver'),
    shell             = require('shelljs');

function getVersionFromScript(script, defaultValue) {
    var versionPromise = Q(defaultValue);
    if (fs.existsSync(script)) {
        versionPromise = superspawn.spawn(script);
    } else {
        /* if you are here, it's probably because you're in Jasmine: fix your existsSync stub */
        versionPromise = Q(defaultValue);
    }
    return versionPromise;
}

function add(hooks, projectRoot, targets, opts) {
    var xml = cordova_util.projectConfig(projectRoot);
    var cfg = new ConfigParser(xml);
    if (!targets || !targets.length) {
        return Q.reject(new CordovaError('No platform specified. Please specify a platform to add. See `'+cordova_util.binname+' platform list`.'));
    }
    var config_json = config.read(projectRoot);
    var platformsDir = path.join(projectRoot, 'platforms');

    // The "platforms" dir is safe to delete, it's almost equivalent to
    // cordova platfrom rm <list of all platforms>
    if ( !fs.existsSync(platformsDir)) {
        shell.mkdir('-p', platformsDir);
    }

    return hooks.fire('before_platform_add', opts)
    .then(function() {
        return targets.reduce(function(soFar, t) {
            return soFar.then(function() {
                return lazy_load.based_on_config(projectRoot, t, opts)
                .then(function(libDir) {
                    var template = config_json.lib && config_json.lib[t] && config_json.lib[t].template || null;
                    var copts = null;
                    if ('spawnoutput' in opts) {
                        copts = opts.spawnoutput;
                    }
                    return call_into_create(t, projectRoot, cfg, libDir, template, copts);
                }, function(err) {
                    throw new CordovaError('Unable to fetch platform ' + t + ': ' + err);
                });
            });
        }, Q());
    })
    .then(function() {
        return hooks.fire('after_platform_add', opts);
    });
};

function remove(hooks, projectRoot, targets, opts) {
    if (!targets || !targets.length) {
        return Q.reject(new CordovaError('No platform[s] specified. Please specify platform[s] to remove. See `'+cordova_util.binname+' platform list`.'));
    }
    return hooks.fire('before_platform_rm', opts)
    .then(function() {
        targets.forEach(function(target) {
            shell.rm('-rf', path.join(projectRoot, 'platforms', target));
            var plugins_json = path.join(projectRoot, 'plugins', target + '.json');
            if (fs.existsSync(plugins_json)) shell.rm(plugins_json);
        });
    }).then(function() {
        return hooks.fire('after_platform_rm', opts);
    });
}

function update(hooks, projectRoot, targets, opts) {
    // Shell out to the update script provided by the named platform.
    if (!targets || !targets.length) {
        return Q.reject(new CordovaError('No platform specified. Please specify a platform to update. See `'+cordova_util.binname+' platform list`.'));
    } else if (targets.length > 1) {
        return Q.reject(new CordovaError('Platform update can only be executed on one platform at a time.'));
    } else {
        var plat = targets[0];
        var platformPath = path.join(projectRoot, 'platforms', plat);
        var installed_platforms = cordova_util.listPlatforms(projectRoot);
        if (installed_platforms.indexOf(plat) < 0) {
            return Q.reject(new CordovaError('Platform "' + plat + '" is not installed. See `'+cordova_util.binname+' platform list`.'));
        }

        function copyCordovaJs() {
            var parser = new platforms[plat].parser(platformPath);
            var platform_www = path.join(platformPath, 'platform_www');
            shell.mkdir('-p', platform_www);
            shell.cp('-f', path.join(parser.www_dir(), 'cordova.js'), path.join(platform_www, 'cordova.js'));
        }

        // First, lazy_load the latest version.
        return hooks.fire('before_platform_update', opts)
        .then(function() {
            return lazy_load.based_on_config(projectRoot, plat, opts);
        }).then(function(libDir) {
            // Call the platform's update script.
            var script = path.join(libDir, 'bin', 'update');
            return superspawn.spawn(script, [platformPath], { stdio: 'inherit' })
            .then(function() {
                // Copy the new cordova.js from www -> platform_www.
                copyCordovaJs();
                // Leave it to the update script to log out "updated to v FOO".
            });
        });
    }
}

function check(hooks, projectRoot) {
    var platformsText = [],
        platforms_on_fs = cordova_util.listPlatforms(projectRoot),
        scratch = path.join(os.tmpdir(), "cordova-platform-check-"+Date.now()),
        listeners = events._events;
        events._events = {};
    var result = Q.defer();
    cordova.raw.create(scratch)
    .then(function () {
        var h = new hooker(scratch);
        // Acquire the version number of each platform we have installed, and output that too.
        Q.all(platforms_on_fs.map(function(p) {
            var d = Q.defer();
            add(h, scratch, [p], {spawnoutput: {stdio: 'ignore'}})
            .then(function() {
                var d_avail = Q.defer(),
                    d_cur = Q.defer();
                getVersionFromScript(path.join(scratch, 'platforms', p, 'cordova', 'version'), null)
                .then(function(avail) {
                    if (!avail) {
                        /* Platform version script was silent, we can't work with this */
                        d_avail.resolve('');
                    } else {
                        d_avail.resolve(avail);
                    }
                })
                .catch(function () {
                    /* Platform version script failed, we can't work with this */
                    d_avail.resolve('');
                });
                getVersionFromScript(path.join(projectRoot, 'platforms', p, 'cordova', 'version'), null)
                .catch(function () {
                    d_cur.resolve('broken');
                }).then(function(v) {
                    d_cur.resolve(v || '');
                });
                Q.all([d_avail.promise, d_cur.promise]).spread(function (avail, v) {
                    var m;
                    if (avail && (!v || v == 'broken' || semver.gt(avail, v))) {
                        m = p + ' @ ' + (v || 'unknown') + ' could be updated to: ' + avail;
                        platformsText.push(m);
                    }
                    d.resolve(m);
                })
                .catch(function () {
                    return '?';
                })
                .done();
            })
            .catch(function () {
                /* If a platform doesn't install, then we can't realistically suggest updating */
                d.resolve();
            });
            return d.promise;
        })).then(function() {
            var results = '';
            events._events = listeners;
            shell.rm('-rf', scratch);
            if (platformsText) {
                results = platformsText.filter(function (p) {return !!p}).sort().join('\n');
            }
            if (!results) {
                results = 'All platforms are up-to-date.';
            }
            events.emit('results', results);
            result.resolve();
        })
        .done();
    }).catch(function (){
        events._events = listeners;
        shell.rm('-rf', scratch);
    })
    .done();
    return result.promise;
}

function list(hooks, projectRoot) {
    var platforms_on_fs = cordova_util.listPlatforms(projectRoot);
    return hooks.fire('before_platform_ls')
    .then(function() {
        // Acquire the version number of each platform we have installed, and output that too.
        return Q.all(platforms_on_fs.map(function(p) {
            return getVersionFromScript(path.join(projectRoot, 'platforms', p, 'cordova', 'version'), null)
            .then(function(v) {
                if (!v) return p;
                return p + ' ' + v;
            }, function(v) {
                return p + ' broken';
            });
        }));
    }).then(function(platformsText) {
        var results = 'Installed platforms: ' + platformsText.sort().join(', ') + '\n';
        var available = Object.getOwnPropertyNames(platforms).filter(function(p) {
            var platform = platforms[p] || {},
                hostos = platform.hostos || null;
            if (!hostos)
                return true;
            if (hostos.indexOf('*') >= 0)
                return true;
            if (hostos.indexOf(process.platform) >= 0)
                return true;
            return false;
        });

        available = available.filter(function(p) {
            return platforms_on_fs.indexOf(p) < 0; // Only those not already installed.
        });
        results += 'Available platforms: ' + available.sort().join(', ');

        events.emit('results', results);
    }).then(function() {
        return hooks.fire('after_platform_ls');
    });
}

// Returns a promise.
module.exports = function platform(command, targets, opts) {
    var projectRoot = cordova_util.cdProjectRoot();

    var hooks = new hooker(projectRoot);

    if (arguments.length === 0) command = 'ls';
    if (targets) {
        if (!(targets instanceof Array)) targets = [targets];
        var err;
        targets.forEach(function(t) {
            if (!(t in platforms)) {
                err = new CordovaError('Platform "' + t + '" not recognized as a core cordova platform. See `'+cordova_util.binname+' platform list`.');
            }
        });
        if (err) return Q.reject(err);
    } else {
        if (command == 'add' || command == 'rm') {
            return Q.reject(new CordovaError('You need to qualify `add` or `remove` with one or more platforms!'));
        }
    }

    opts = opts || {};
    opts.platforms = targets;

    switch(command) {
        case 'add':
            return add(hooks, projectRoot, targets, opts);
        case 'rm':
        case 'remove':
            return remove(hooks, projectRoot, targets, opts);
        case 'update':
        case 'up':
            return update(hooks, projectRoot, targets, opts);
        case 'check':
            return check(hooks, projectRoot);
        case 'ls':
        case 'list':
        default:
            return list(hooks, projectRoot);
    }
};

/**
 * Check Platform Support.
 *
 *   - {String} `name` of the platform to test.
 *   - Returns a promise, which shows any errors.
 *
 */

function supports(project_root, name) {
    // required parameters
    if (!name) return Q.reject(new CordovaError('requires a platform name parameter'));

    // check if platform exists
    var platform = platforms[name];
    if (!platform) {
        return Q.reject(new CordovaError(util.format('"%s" platform does not exist', name)));
    }

    // look up platform meta-data parser
    var platformParser = platforms[name].parser;
    if (!platformParser) {
        return Q.reject(new Error(util.format('"%s" platform parser does not exist', name)));
    }

    // check for platform support
    return platformParser.check_requirements(project_root);
};

// Expose the platform parsers on top of this command
for (var p in platforms) {
    module.exports[p] = platforms[p];
}
function createOverrides(projectRoot, target) {
    shell.mkdir('-p', path.join(cordova_util.appDir(projectRoot), 'merges', target));
};

// Returns a promise.
function call_into_create(target, projectRoot, cfg, libDir, template_dir, opts) {
    var output = path.join(projectRoot, 'platforms', target);

    // Check if output directory already exists.
    if (fs.existsSync(output)) {
        return Q.reject(new CordovaError('Platform ' + target + ' already added'));
    } else {
        // Make sure we have minimum requirements to work with specified platform
        events.emit('verbose', 'Checking if platform "' + target + '" passes minimum requirements...');
        /* XXX this is calling the public symbol so that Jasmine Spy can attack it */
        return module.exports.supports(projectRoot, target)
        .then(function() {
            events.emit('log', 'Creating ' + target + ' project...');
            var bin = path.join(libDir, 'bin', 'create');
            var args = [];
            if (target == 'android') {
                var platformVersion = fs.readFileSync(path.join(libDir, 'VERSION'), 'UTF-8').trim();
                if (semver.gt(platformVersion, '3.3.0')) {
                    args.push('--cli');
                }
            } else if (target == 'ios') {
                var platformVersion = fs.readFileSync(path.join(libDir, 'CordovaLib', 'VERSION'), 'UTF-8').trim();
                args.push('--arc');
                if (semver.gt(platformVersion, '3.3.0')) {
                    args.push('--cli');
                }
            }

            var pkg = cfg.packageName().replace(/[^\w.]/g,'_');
            var name = cfg.name();
            args.push(output, pkg, name);
            if (template_dir) {
                args.push(template_dir);
            }
            return superspawn.spawn(bin, args, opts || { stdio: 'inherit' })
            .then(function() {
                return require('./cordova').raw.prepare(target);
            })
            .then(function() {
                createOverrides(projectRoot, target);
                // Install all currently installed plugins into this new platform.
                var plugins_dir = path.join(projectRoot, 'plugins');
                var plugins = cordova_util.findPlugins(plugins_dir);
                var parser = new platforms[target].parser(output);
                if (!plugins) return Q();

                var plugman = require('../plugman/plugman');
                // Install them serially.
                return plugins.reduce(function(soFar, plugin) {
                    return soFar.then(function() {
                        events.emit('verbose', 'Installing plugin "' + plugin + '" following successful platform add of ' + target);
                        return plugman.raw.install(target, output, path.basename(plugin), plugins_dir);
                    });
                }, Q());
            });
        });
    }
}

module.exports.add = add;
module.exports.remove = remove;
module.exports.update = update;
module.exports.check = check;
module.exports.list = list;
module.exports.supports = supports;
<commit_msg>Style changes in cordova/platform.js<commit_after>/**
    Licensed to the Apache Software Foundation (ASF) under one
    or more contributor license agreements.  See the NOTICE file
    distributed with this work for additional information
    regarding copyright ownership.  The ASF licenses this file
    to you under the Apache License, Version 2.0 (the
    "License"); you may not use this file except in compliance
    with the License.  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing,
    software distributed under the License is distributed on an
    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    KIND, either express or implied.  See the License for the
    specific language governing permissions and limitations
    under the License.
*/

/* jshint node:true, laxcomma:true, strict:false, trailing:true, unused:vars */

var config            = require('./config'),
    cordova           = require('./cordova'),
    cordova_util      = require('./util'),
    ConfigParser      = require('./ConfigParser'),
    util              = require('util'),
    fs                = require('fs'),
    os                = require('os'),
    path              = require('path'),
    hooker            = require('./hooker'),
    events            = require('./events'),
    lazy_load         = require('./lazy_load'),
    CordovaError      = require('../CordovaError'),
    Q                 = require('q'),
    platforms         = require('./platforms'),
    superspawn        = require('./superspawn'),
    semver            = require('semver'),
    shell             = require('shelljs');

// Expose the platform parsers on top of this command
for (var p in platforms) {
    module.exports[p] = platforms[p];
}

function getVersionFromScript(script, defaultValue) {
    var versionPromise = Q(defaultValue);
    if (fs.existsSync(script)) {
        versionPromise = superspawn.spawn(script);
    } else {
        /* if you are here, it's probably because you're in Jasmine: fix your existsSync stub */
        versionPromise = Q(defaultValue);
    }
    return versionPromise;
}

function add(hooks, projectRoot, targets, opts) {
    var xml = cordova_util.projectConfig(projectRoot);
    var cfg = new ConfigParser(xml);
    if (!targets || !targets.length) {
        return Q.reject(new CordovaError('No platform specified. Please specify a platform to add. See `'+cordova_util.binname+' platform list`.'));
    }
    var config_json = config.read(projectRoot);
    var platformsDir = path.join(projectRoot, 'platforms');

    // The "platforms" dir is safe to delete, it's almost equivalent to
    // cordova platfrom rm <list of all platforms>
    if ( !fs.existsSync(platformsDir)) {
        shell.mkdir('-p', platformsDir);
    }

    return hooks.fire('before_platform_add', opts)
    .then(function() {
        return targets.reduce(function(soFar, t) {
            return soFar.then(function() {
                return lazy_load.based_on_config(projectRoot, t, opts)
                .then(function(libDir) {
                    var template = config_json.lib && config_json.lib[t] && config_json.lib[t].template || null;
                    var copts = null;
                    if ('spawnoutput' in opts) {
                        copts = opts.spawnoutput;
                    }
                    return call_into_create(t, projectRoot, cfg, libDir, template, copts);
                }, function(err) {
                    throw new CordovaError('Unable to fetch platform ' + t + ': ' + err);
                });
            });
        }, Q());
    })
    .then(function() {
        return hooks.fire('after_platform_add', opts);
    });
}

function remove(hooks, projectRoot, targets, opts) {
    if (!targets || !targets.length) {
        return Q.reject(new CordovaError('No platform[s] specified. Please specify platform[s] to remove. See `'+cordova_util.binname+' platform list`.'));
    }
    return hooks.fire('before_platform_rm', opts)
    .then(function() {
        targets.forEach(function(target) {
            shell.rm('-rf', path.join(projectRoot, 'platforms', target));
            var plugins_json = path.join(projectRoot, 'plugins', target + '.json');
            if (fs.existsSync(plugins_json)) shell.rm(plugins_json);
        });
    }).then(function() {
        return hooks.fire('after_platform_rm', opts);
    });
}

function update(hooks, projectRoot, targets, opts) {
    // Shell out to the update script provided by the named platform.
    var msg;
    if ( !targets || !targets.length ) {
        msg = 'No platform specified. Please specify a platform to update. See `' +
              cordova_util.binname + ' platform list`.';
        return Q.reject(new CordovaError(msg));
    } else if (targets.length > 1) {
        msg = 'Platform update can only be executed on one platform at a time.';
        return Q.reject(new CordovaError(msg));
    }
    var plat = targets[0];
    var platformPath = path.join(projectRoot, 'platforms', plat);
    var installed_platforms = cordova_util.listPlatforms(projectRoot);
    if (installed_platforms.indexOf(plat) < 0) {
        msg = 'Platform "' + plat + '" is not installed. See `' +
              cordova_util.binname + ' platform list`.';
        return Q.reject(new CordovaError(msg));
    }

    // First, lazy_load the latest version.
    return hooks.fire('before_platform_update', opts)
    .then(function() {
        return lazy_load.based_on_config(projectRoot, plat, opts);
    })
    .then(function(libDir) {
        // Call the platform's update script.
        var script = path.join(libDir, 'bin', 'update');
        return superspawn.spawn(script, [platformPath], { stdio: 'inherit' });
    })
    .then(function() {
         // Copy the new cordova.js from www -> platform_www.
        var parser = new platforms[plat].parser(platformPath);
        var platform_www = path.join(platformPath, 'platform_www');
        shell.mkdir('-p', platform_www);
        shell.cp('-f', path.join(parser.www_dir(), 'cordova.js'), path.join(platform_www, 'cordova.js'));
        // Leave it to the update script to log out "updated to v FOO".
    });
}

function check(hooks, projectRoot) {
    var platformsText = [],
        platforms_on_fs = cordova_util.listPlatforms(projectRoot),
        scratch = path.join(os.tmpdir(), 'cordova-platform-check-' + Date.now()),
        listeners = events._events;
        events._events = {};
    var result = Q.defer();
    cordova.raw.create(scratch)
    .then(function () {
        var h = new hooker(scratch);
        // Acquire the version number of each platform we have installed, and output that too.
        Q.all(platforms_on_fs.map(function(p) {
            var d = Q.defer();
            add(h, scratch, [p], {spawnoutput: {stdio: 'ignore'}})
            .then(function() {
                var d_avail = Q.defer(),
                    d_cur = Q.defer();
                getVersionFromScript(path.join(scratch, 'platforms', p, 'cordova', 'version'), null)
                .then(function(avail) {
                    if (!avail) {
                        /* Platform version script was silent, we can't work with this */
                        d_avail.resolve('');
                    } else {
                        d_avail.resolve(avail);
                    }
                })
                .catch(function () {
                    /* Platform version script failed, we can't work with this */
                    d_avail.resolve('');
                });
                getVersionFromScript(path.join(projectRoot, 'platforms', p, 'cordova', 'version'), null)
                .catch(function () {
                    d_cur.resolve('broken');
                }).then(function(v) {
                    d_cur.resolve(v || '');
                });
                Q.all([d_avail.promise, d_cur.promise]).spread(function (avail, v) {
                    var m;
                    if (avail && (!v || v == 'broken' || semver.gt(avail, v))) {
                        m = p + ' @ ' + (v || 'unknown') + ' could be updated to: ' + avail;
                        platformsText.push(m);
                    }
                    d.resolve(m);
                })
                .catch(function () {
                    return '?';
                })
                .done();
            })
            .catch(function () {
                /* If a platform doesn't install, then we can't realistically suggest updating */
                d.resolve();
            });
            return d.promise;
        })).then(function() {
            var results = '';
            events._events = listeners;
            shell.rm('-rf', scratch);
            if (platformsText) {
                results = platformsText.filter(function (p) { return !!p; }).sort().join('\n');
            }
            if (!results) {
                results = 'All platforms are up-to-date.';
            }
            events.emit('results', results);
            result.resolve();
        })
        .done();
    }).catch(function (){
        events._events = listeners;
        shell.rm('-rf', scratch);
    })
    .done();
    return result.promise;
}

function list(hooks, projectRoot) {
    var platforms_on_fs = cordova_util.listPlatforms(projectRoot);
    return hooks.fire('before_platform_ls')
    .then(function() {
        // Acquire the version number of each platform we have installed, and output that too.
        return Q.all(platforms_on_fs.map(function(p) {
            return getVersionFromScript(path.join(projectRoot, 'platforms', p, 'cordova', 'version'), null)
            .then(function(v) {
                if (!v) return p;
                return p + ' ' + v;
            }, function(v) {
                return p + ' broken';
            });
        }));
    }).then(function(platformsText) {
        var results = 'Installed platforms: ' + platformsText.sort().join(', ') + '\n';
        var available = Object.getOwnPropertyNames(platforms).filter(function(p) {
            var platform = platforms[p] || {},
                hostos = platform.hostos || null;
            if (!hostos)
                return true;
            if (hostos.indexOf('*') >= 0)
                return true;
            if (hostos.indexOf(process.platform) >= 0)
                return true;
            return false;
        });

        available = available.filter(function(p) {
            return platforms_on_fs.indexOf(p) < 0; // Only those not already installed.
        });
        results += 'Available platforms: ' + available.sort().join(', ');

        events.emit('results', results);
    }).then(function() {
        return hooks.fire('after_platform_ls');
    });
}

// Returns a promise.
module.exports = platform;
function platform(command, targets, opts) {
    var projectRoot = cordova_util.cdProjectRoot();

    var hooks = new hooker(projectRoot);

    if (arguments.length === 0) command = 'ls';
    if (targets) {
        if (!(targets instanceof Array)) targets = [targets];
        var err;
        targets.forEach(function(t) {
            if (!(t in platforms)) {
                err = new CordovaError('Platform "' + t + '" not recognized as a core cordova platform. See `'+cordova_util.binname+' platform list`.');
            }
        });
        if (err) return Q.reject(err);
    } else if (command == 'add' || command == 'rm') {
        return Q.reject(new CordovaError('You need to qualify `add` or `remove` with one or more platforms!'));
    }

    opts = opts || {};
    opts.platforms = targets;

    switch(command) {
        case 'add':
            return add(hooks, projectRoot, targets, opts);
        case 'rm':
        case 'remove':
            return remove(hooks, projectRoot, targets, opts);
        case 'update':
        case 'up':
            return update(hooks, projectRoot, targets, opts);
        case 'check':
            return check(hooks, projectRoot);
        default:
            return list(hooks, projectRoot);
    }
}

/**
 * Check Platform Support.
 *
 *   - {String} `name` of the platform to test.
 *   - Returns a promise, which shows any errors.
 *
 */

function supports(project_root, name) {
    // required parameters
    if (!name) return Q.reject(new CordovaError('requires a platform name parameter'));

    // check if platform exists
    var platform = platforms[name];
    if (!platform) {
        return Q.reject(new CordovaError(util.format('"%s" platform does not exist', name)));
    }

    // look up platform meta-data parser
    var platformParser = platforms[name].parser;
    if (!platformParser) {
        return Q.reject(new Error(util.format('"%s" platform parser does not exist', name)));
    }

    // check for platform support
    return platformParser.check_requirements(project_root);
}

function createOverrides(projectRoot, target) {
    shell.mkdir('-p', path.join(cordova_util.appDir(projectRoot), 'merges', target));
}

// Returns a promise.
function call_into_create(target, projectRoot, cfg, libDir, template_dir, opts) {
    var output = path.join(projectRoot, 'platforms', target);

    // Check if output directory already exists.
    if (fs.existsSync(output)) {
        return Q.reject(new CordovaError('Platform ' + target + ' already added'));
    } else {
        // Make sure we have minimum requirements to work with specified platform
        events.emit('verbose', 'Checking if platform "' + target + '" passes minimum requirements...');
        /* XXX this is calling the public symbol so that Jasmine Spy can attack it */
        return module.exports.supports(projectRoot, target)
        .then(function() {
            events.emit('log', 'Creating ' + target + ' project...');
            var bin = path.join(libDir, 'bin', 'create');
            var args = [];
            var platformVersion;
            if (target == 'android') {
                platformVersion = fs.readFileSync(path.join(libDir, 'VERSION'), 'UTF-8').trim();
                if (semver.gt(platformVersion, '3.3.0')) {
                    args.push('--cli');
                }
            } else if (target == 'ios') {
                platformVersion = fs.readFileSync(path.join(libDir, 'CordovaLib', 'VERSION'), 'UTF-8').trim();
                args.push('--arc');
                if (semver.gt(platformVersion, '3.3.0')) {
                    args.push('--cli');
                }
            }

            var pkg = cfg.packageName().replace(/[^\w.]/g,'_');
            var name = cfg.name();
            args.push(output, pkg, name);
            if (template_dir) {
                args.push(template_dir);
            }
            return superspawn.spawn(bin, args, opts || { stdio: 'inherit' })
            .then(function() {
                return require('./cordova').raw.prepare(target);
            })
            .then(function() {
                createOverrides(projectRoot, target);
                // Install all currently installed plugins into this new platform.
                var plugins_dir = path.join(projectRoot, 'plugins');
                var plugins = cordova_util.findPlugins(plugins_dir);
                if (!plugins) return Q();

                var plugman = require('../plugman/plugman');
                // Install them serially.
                return plugins.reduce(function(soFar, plugin) {
                    return soFar.then(function() {
                        events.emit('verbose', 'Installing plugin "' + plugin + '" following successful platform add of ' + target);
                        return plugman.raw.install(target, output, path.basename(plugin), plugins_dir);
                    });
                }, Q());
            });
        });
    }
}

module.exports.add = add;
module.exports.remove = remove;
module.exports.update = update;
module.exports.check = check;
module.exports.list = list;
module.exports.supports = supports;
<|endoftext|>


<commit_before>var YAML = require('json2yaml')

var Importer = require('../importers/index')

function Exporter() {
  this.data = null
  this.project = null
}

Exporter.prototype.loadSLData = function (rawData) {
  var importer = Importer.factory({
    name: 'StopLight',
    className: 'StopLight'
  })
  importer.loadData(rawData)
  this.project = importer.import()
}

Exporter.prototype.loadProject = function (project) {
  this.project = project
}

Exporter.prototype._export = function () {
  throw new Error('_export method not implemented')
}

Exporter.prototype.export = function (format) {
  this._export()
  return this.getData(format)
}

Exporter.prototype.getData = function(format) {
  switch (format) {
    case 'yaml':
      return YAML.stringify(this.data)
    default:
      return JSON.stringify(this.data, null, 2)
  }
}

module.exports = Exporter
<commit_msg>- small fix.<commit_after>var YAML = require('json2yaml')

var Importer = require('../importers/index')

function Exporter() {
  this.data = null
  this.project = null
}

Exporter.prototype.loadSLData = function (rawData) {
  var importer = Importer.factory({
    name: 'StopLight',
    className: 'StopLight'
  })
  importer.loadData(rawData)
  this.project = importer.import()
}

Exporter.prototype.loadProject = function (project) {
  this.project = project
}

Exporter.prototype._export = function () {
  throw new Error('_export method not implemented')
}

Exporter.prototype.export = function (format) {
  this._export()
  return this.getData(format)
}

Exporter.prototype.getData = function(format) {
  switch (format) {
    case 'yaml':
      return YAML.stringify(this.data)
    default:
      return this.data
  }
}

module.exports = Exporter
<|endoftext|>


<commit_before>var YAML = require('js-yaml'),
    Importer = require('../importers/index');

function Exporter() {
  this.data = null;
  this.project = null;
}
Exporter.prototype = {
  get Data(){
    return this.data;
  }
};

Exporter.prototype.loadSLData = function (rawData, cb) {
  var importer = Importer.factory({
    name: 'StopLight',
    className: 'StopLight'
  });
  var me = this;
  importer.loadData(rawData)
  .then(function(){
    me.project = importer.import();
    cb();
  })
  .catch(function(err){
    cb(err);
  });
};

Exporter.prototype.loadProject = function (project) {
  this.project = project;
};

Exporter.prototype._export = function () {
  throw new Error('_export method not implemented');
};

Exporter.prototype.export = function (format) {
  var me = this;
  return new Promise(function(resolve, reject){
    try {
      me._export();

      var formattedData, exportedData = me._getData(format);
			resolve(exportedData);
      // if (typeof exportedData === 'object') {
      //   formattedData = JSON.stringify(exportedData);
      // } else {
      //   formattedData = exportedData;
      // }
			//
      // var importer = Importer.factory({
      //   name: 'AUTO',
      //   className: 'Auto'
      // });
      // importer.loadData(formattedData)
      //     .then(function(){
      //       try {
      //         importer.import();
      //         resolve(exportedData);
      //       } catch(err) {
      //         resolve(exportedData, err);
      //       }
      //     })
      //     .catch(function(err){
      //       resolve(exportedData, err);
      //     });
    } catch(err) {
      reject(err, null);
    }
  });
};

Exporter.prototype._getData = function(format) {
  switch (format) {
    case 'yaml':
      return YAML.dump(JSON.parse(JSON.stringify(this.Data)), {lineWidth: -1});
    default:
      return this.Data;
  }
};

Exporter.prototype._mapEndpoint = function () {
  throw new Error('_mapEndpoint method not implemented');
};

Exporter.prototype._mapSchema = function () {
  throw new Error('_mapSchema method not implemented');
};
Exporter.prototype._mapQueryString = function () {
  throw new Error('_mapQueryString method not implemented');
};
Exporter.prototype._mapURIParams = function () {
  throw new Error('_mapURIParams method not implemented');
};
Exporter.prototype._mapRequestBody = function () {
  throw new Error('_mapRequestBody method not implemented');
};
Exporter.prototype._mapResponseBody = function () {
  throw new Error('_mapResponseBody method not implemented');
};
Exporter.prototype._mapRequestHeaders = function () {
  throw new Error('_mapRequestHeaders method not implemented');
};

module.exports = Exporter;
<commit_msg>minor changes<commit_after>var YAML = require('js-yaml'),
    Importer = require('../importers/index');

function Exporter() {
  this.data = null;
  this.project = null;
}
Exporter.prototype = {
  get Data(){
    return this.data;
  }
};

Exporter.prototype.loadSLData = function (rawData, cb) {
  var importer = Importer.factory({
    name: 'StopLight',
    className: 'StopLight'
  });
  var me = this;
  importer.loadData(rawData)
  .then(function(){
    me.project = importer.import();
    cb();
  })
  .catch(function(err){
    cb(err);
  });
};

Exporter.prototype.loadProject = function (project) {
  this.project = project;
};

Exporter.prototype._export = function () {
  throw new Error('_export method not implemented');
};

Exporter.prototype.export = function (format) {
  var me = this;
  return new Promise(function(resolve, reject){
    try {
      me._export();

      var formattedData, exportedData = me._getData(format);
      if (typeof exportedData === 'object') {
        formattedData = JSON.stringify(exportedData);
      } else {
        formattedData = exportedData;
      }

      var importer = Importer.factory({
        name: 'AUTO',
        className: 'Auto'
      });
      importer.loadData(formattedData)
          .then(function(){
            try {
              importer.import();
              resolve(exportedData);
            } catch(err) {
              resolve(exportedData, err);
            }
          })
          .catch(function(err){
            resolve(exportedData, err);
          });
    } catch(err) {
      reject(err, null);
    }
  });
};

Exporter.prototype._getData = function(format) {
  switch (format) {
    case 'yaml':
      return YAML.dump(JSON.parse(JSON.stringify(this.Data)), {lineWidth: -1});
    default:
      return this.Data;
  }
};

Exporter.prototype._mapEndpoint = function () {
  throw new Error('_mapEndpoint method not implemented');
};

Exporter.prototype._mapSchema = function () {
  throw new Error('_mapSchema method not implemented');
};
Exporter.prototype._mapQueryString = function () {
  throw new Error('_mapQueryString method not implemented');
};
Exporter.prototype._mapURIParams = function () {
  throw new Error('_mapURIParams method not implemented');
};
Exporter.prototype._mapRequestBody = function () {
  throw new Error('_mapRequestBody method not implemented');
};
Exporter.prototype._mapResponseBody = function () {
  throw new Error('_mapResponseBody method not implemented');
};
Exporter.prototype._mapRequestHeaders = function () {
  throw new Error('_mapRequestHeaders method not implemented');
};

module.exports = Exporter;
<|endoftext|>


<commit_before>(function(window){

  if (typeof console === 'undefined') {
    /**
     * @see http://getfirebug.com/console.html
     */
    window.console = {};
  }

  console._output = console.log || window.opera && opera.postError || function dump (message) {
    console.history = console.history || [];
    return console.history.push(message);
  };

  /**
   * Limit of objects dimensions
   * console.dimensions_limit = 1
   * console.log({a:{b:1}}) ==> { 'a': {?} }
   * console.dimensions_limit = 2
   * console.log({a:{b:1}}) ==> { 'a': { 'b': 1 } }
   */
  console.dimensions_limit = 1;

  /**
   * source_of({x:2, y:8, z:[4,3]}) ==> '{ x: 2, y: 8, z: [4, 3] }'
   */
  console._source_of = function source_of () {

    /**
     * source_of_one_arg({x:2, y:8}) === "{'x':2, 'y':8}"
     * @param {Object} arg
     * @param {Number} limit dimension of objects
     * @return {String} string representation of input
     */
    function source_of_one_arg (arg, limit) {
      if (arg === null) {
        return 'null';
      } else if (typeof arg === 'undefined') {
        return 'undefined';
      }
      var result = '';
      if (arg && arg.nodeType == 1) {
        // Is element?
        result = '<'+ arg.tagName;
        for (var i=0, ii=arg.attributes.length; i<ii; i++) {
          if (arg.attributes[i].specified) {
            result +=' '+ arg.attributes[i].name +'="'+ arg.attributes[i].value +'"';
          }
        }
        if (arg.childNodes && arg.childNodes.length === 0) {
          result += '/';
        }
        return result + '>';
      }
      var kind = Object.prototype.toString.call(arg).replace('[object ', '').replace(']','');
      if (kind === 'String') {
        return '"'+ arg +'"';
      } else if (kind === 'Array' || kind === 'HTMLCollection' || kind === 'NodeList') {
        // Is array-like object?
        result = '[';
        var arr_list = [];
        for (var j=0, jj=arg.length; j<jj; j++) {
          arr_list[j] = source_of_one_arg(arg[j], limit);
        }
        return result + arr_list.join(', ') +']';
      } else if (kind === 'RegExp') {
        return "/"+ arg.source +"/";
      } else if (kind === 'Date') {
        return arg;
      } else if (typeof arg === 'object') {
        if (!limit) return '{?}';
        result = '{';
        var arr_obj = [];
        for (var key in arg) {
          try {
            var value = arg === arg[key] ? 'this' : source_of_one_arg(arg[key], limit-1);
            arr_obj.push( '"'+ key +'": '+ value);
          } catch (e) {}
        }
        return result + arr_obj.join(', ') +'}';
      } else {
        return arg;
      }
    }

    var result = [];
    for (var i=0; i<arguments.length; i++) {
      result.push( source_of_one_arg(arguments[i], console.dimensions_limit) );
    }
    return result.join(', ');

  };

  var browser_suck_at_logging = /*@cc_on 1 || @*/ window.opera;

  var log_methods = ['log', 'info', 'warn', 'error', 'debug', 'dir', 'dirxml'];

  for (var i=0; i<log_methods.length; i++) {
    var _log = console[log_methods[i]];
    if (browser_suck_at_logging || !console[log_methods[i]]) {
      console[log_methods[i]] = function () {
        return (_log || console._output)( console._source_of.apply(this, arguments) );
      };
    }
  }

  /**
   * Simplified version of http://eriwen.com/javascript/js-stack-trace/
   */
  console.trace = console.trace || function trace() {
    try {
      i.dont.exist++;
    } catch(e) {
      var stack = e.stack || e.stacktrace;
      if (stack) {
        try {
          stack = stack.split('\n').slice(2).join('\n');
        } catch (err) {}
        console._output(stack);
      }
    }
  };

  /**
   * console.assert(false, "I'm gonna fail")
   * @param {Boolean} is_ok
   * @param {String} message optional
   */
  console.assert = console.assert || function assert (is_ok, message) {
    if (!is_ok) console._output( 'ASSERT FAIL: '+ message );
  };

  /**
   * @param {String} name optional
   */
  console.group = console.group || function group (name) {
    console._output('\n-------- '+ name +' --------');
  };

  console.groupCollapsed = console.groupCollapsed || console.group;

  /**
   * Print 3 line breaks
   */
  console.groupEnd = console.groupEnd || function groupEnd () {
    console._output('\n\n\n');
  };

  /**
   * @param {String} title optional
   */
  console.count = console.count || function count (title) {
    var title = title || '';
    count.counters = count.counters || {};
    if (count.counters[title]) {
      count.counters[title]++;
    } else {
      count.counters[title] = 1;
    }
    console._output(title +' '+ count.counters[title]);
  };

  /**
   * @param {String} title optional
   */
  console.profile = console.profile || function profile (title) {
    return 'Not implemented';
  };
  console.profileEnd = console.profileEnd || function profileEnd () {
    return 'Not implemented';
  };

  console._timers = {};

  /**
   * @param {String} name such as "my damn slow parser"
   */
  console.time = console.time || function time (name) {
    var start = (new Date).getTime();
    console._timers[name] = {'start': start};
  };

  /**
   * @param {String} name such as "my damn slow parser"
   */
  console.timeEnd = console.timeEnd || function timeEnd (name) {
    var end = (new Date).getTime();
    console.info(name +': '+ (end - console._timers[name].start) +'ms');
    console._timers[name].end = end;
  };

  if (typeof require === 'function' && typeof exports !== 'undefined') {
    exports.console = window.console;
    console._output = require('system').print;
  }

})(this);<commit_msg>Unnecessary `var` removed<commit_after>(function(window){

  if (typeof console === 'undefined') {
    /**
     * @see http://getfirebug.com/console.html
     */
    window.console = {};
  }

  console._output = console.log || window.opera && opera.postError || function dump (message) {
    console.history = console.history || [];
    return console.history.push(message);
  };

  /**
   * Limit of objects dimensions
   * console.dimensions_limit = 1
   * console.log({a:{b:1}}) ==> { 'a': {?} }
   * console.dimensions_limit = 2
   * console.log({a:{b:1}}) ==> { 'a': { 'b': 1 } }
   */
  console.dimensions_limit = 1;

  /**
   * source_of({x:2, y:8, z:[4,3]}) ==> '{ x: 2, y: 8, z: [4, 3] }'
   */
  console._source_of = function source_of () {

    /**
     * source_of_one_arg({x:2, y:8}) === "{'x':2, 'y':8}"
     * @param {Object} arg
     * @param {Number} limit dimension of objects
     * @return {String} string representation of input
     */
    function source_of_one_arg (arg, limit) {
      if (arg === null) {
        return 'null';
      } else if (typeof arg === 'undefined') {
        return 'undefined';
      }
      var result = '';
      if (arg && arg.nodeType == 1) {
        // Is element?
        result = '<'+ arg.tagName;
        for (var i=0, ii=arg.attributes.length; i<ii; i++) {
          if (arg.attributes[i].specified) {
            result +=' '+ arg.attributes[i].name +'="'+ arg.attributes[i].value +'"';
          }
        }
        if (arg.childNodes && arg.childNodes.length === 0) {
          result += '/';
        }
        return result + '>';
      }
      var kind = Object.prototype.toString.call(arg).replace('[object ', '').replace(']','');
      if (kind === 'String') {
        return '"'+ arg +'"';
      } else if (kind === 'Array' || kind === 'HTMLCollection' || kind === 'NodeList') {
        // Is array-like object?
        result = '[';
        var arr_list = [];
        for (var j=0, jj=arg.length; j<jj; j++) {
          arr_list[j] = source_of_one_arg(arg[j], limit);
        }
        return result + arr_list.join(', ') +']';
      } else if (kind === 'RegExp') {
        return "/"+ arg.source +"/";
      } else if (kind === 'Date') {
        return arg;
      } else if (typeof arg === 'object') {
        if (!limit) return '{?}';
        result = '{';
        var arr_obj = [];
        for (var key in arg) {
          try {
            var value = arg === arg[key] ? 'this' : source_of_one_arg(arg[key], limit-1);
            arr_obj.push( '"'+ key +'": '+ value);
          } catch (e) {}
        }
        return result + arr_obj.join(', ') +'}';
      } else {
        return arg;
      }
    }

    var result = [];
    for (var i=0; i<arguments.length; i++) {
      result.push( source_of_one_arg(arguments[i], console.dimensions_limit) );
    }
    return result.join(', ');

  };

  var browser_suck_at_logging = /*@cc_on 1 || @*/ window.opera;

  var log_methods = ['log', 'info', 'warn', 'error', 'debug', 'dir', 'dirxml'];

  for (var i=0; i<log_methods.length; i++) {
    var _log = console[log_methods[i]];
    if (browser_suck_at_logging || !console[log_methods[i]]) {
      console[log_methods[i]] = function () {
        return (_log || console._output)( console._source_of.apply(this, arguments) );
      };
    }
  }

  /**
   * Simplified version of http://eriwen.com/javascript/js-stack-trace/
   */
  console.trace = console.trace || function trace() {
    try {
      i.dont.exist++;
    } catch(e) {
      var stack = e.stack || e.stacktrace;
      if (stack) {
        try {
          stack = stack.split('\n').slice(2).join('\n');
        } catch (err) {}
        console._output(stack);
      }
    }
  };

  /**
   * console.assert(false, "I'm gonna fail")
   * @param {Boolean} is_ok
   * @param {String} message optional
   */
  console.assert = console.assert || function assert (is_ok, message) {
    if (!is_ok) console._output( 'ASSERT FAIL: '+ message );
  };

  /**
   * @param {String} name optional
   */
  console.group = console.group || function group (name) {
    console._output('\n-------- '+ name +' --------');
  };

  console.groupCollapsed = console.groupCollapsed || console.group;

  /**
   * Print 3 line breaks
   */
  console.groupEnd = console.groupEnd || function groupEnd () {
    console._output('\n\n\n');
  };

  /**
   * @param {String} title optional
   */
  console.count = console.count || function count (title) {
    title = title || '';
    count.counters = count.counters || {};
    if (count.counters[title]) {
      count.counters[title]++;
    } else {
      count.counters[title] = 1;
    }
    console._output(title +' '+ count.counters[title]);
  };

  /**
   * @param {String} title optional
   */
  console.profile = console.profile || function profile (title) {
    return 'Not implemented';
  };
  console.profileEnd = console.profileEnd || function profileEnd () {
    return 'Not implemented';
  };

  console._timers = {};

  /**
   * @param {String} name such as "my damn slow parser"
   */
  console.time = console.time || function time (name) {
    var start = (new Date).getTime();
    console._timers[name] = {'start': start};
  };

  /**
   * @param {String} name such as "my damn slow parser"
   */
  console.timeEnd = console.timeEnd || function timeEnd (name) {
    var end = (new Date).getTime();
    console.info(name +': '+ (end - console._timers[name].start) +'ms');
    console._timers[name].end = end;
  };

  if (typeof require === 'function' && typeof exports !== 'undefined') {
    exports.console = window.console;
    console._output = require('system').print;
  }

})(this);<|endoftext|>


<commit_before>var spawn = require( 'child_process' ).spawn
  , exec = require( 'child_process' ).exec
  , os = require( 'os' )
  , path = require( 'path' )
  , types
  ;

// textutil -convert txt -stdout foo.doc
function extractText( filePath, options, cb ) {
  var result = ''
    , escapedPath = filePath.replace( /\s/g, '\\ ' )
    , error = null
    , textutil = spawn( 'textutil', ['-convert', 'txt', '-stdout', escapedPath] )
    ;

  textutil.stdout.on( 'data', function( buffer ) {
    result += buffer.toString();
  });

  textutil.stderr.on( 'error', function( buffer ) {
    if ( !error ) {
      error = '';
    }
    error += buffer.toString();
  });

  textutil.on( 'close', function( /* code */ ) {
    if ( error ) {
      error = new Error( 'textutil read of file named [[ ' +
        path.basename( filePath ) + ' ]] failed: ' + error );
      cb( error, null );
      return;
    }
    cb( null, result.trim() );
  });
}

function testForBinary( options, cb ) {
  // just osx extractor, so don't bother checking on osx
  if ( os.platform() !== 'darwin' ) {
    cb( true );
    return;
  }

  exec( 'textutil ' + __filename,
    function( error /* , stdout, stderr */ ) {
      var msg;
      if ( error !== null ) {
        msg = 'INFO: \'textutil\' does not appear to be installed, ' +
         'so textract will be unable to extract DOCs.';
      }
      cb( error === null, msg );
    }
  );
}

if ( os.platform() === 'darwin' ) {
  types = ['application/msword', 'application/rtf', 'text/rtf'];
  // types = [];
} else {
  types = [];
}

module.exports = {
  types: types,
  extract: extractText,
  test: testForBinary
};
<commit_msg>fixes #109, osx isn't interested in an escaped file path<commit_after>var spawn = require( 'child_process' ).spawn
  , exec = require( 'child_process' ).exec
  , os = require( 'os' )
  , path = require( 'path' )
  , types
  ;

// textutil -convert txt -stdout foo.doc
function extractText( filePath, options, cb ) {
  var result = ''
    , error = null
    , textutil = spawn( 'textutil', ['-convert', 'txt', '-stdout', filePath] )
    ;

  textutil.stdout.on( 'data', function( buffer ) {
    result += buffer.toString();
  });

  textutil.stderr.on( 'error', function( buffer ) {
    if ( !error ) {
      error = '';
    }
    error += buffer.toString();
  });

  textutil.on( 'close', function( /* code */ ) {
    if ( error ) {
      error = new Error( 'textutil read of file named [[ ' +
        path.basename( filePath ) + ' ]] failed: ' + error );
      cb( error, null );
      return;
    }
    cb( null, result.trim() );
  });
}

function testForBinary( options, cb ) {
  // just osx extractor, so don't bother checking on osx
  if ( os.platform() !== 'darwin' ) {
    cb( true );
    return;
  }

  exec( 'textutil ' + __filename,
    function( error /* , stdout, stderr */ ) {
      var msg;
      if ( error !== null ) {
        msg = 'INFO: \'textutil\' does not appear to be installed, ' +
         'so textract will be unable to extract DOCs.';
      }
      cb( error === null, msg );
    }
  );
}

if ( os.platform() === 'darwin' ) {
  types = ['application/msword', 'application/rtf', 'text/rtf'];
  // types = [];
} else {
  types = [];
}

module.exports = {
  types: types,
  extract: extractText,
  test: testForBinary
};
<|endoftext|>


<commit_before>(function() {
    'use strict';

    var app = angular.module('mainApp', [
        'ngRoute'
    ]);

    app.config(['$routeProvider', function($routeProvider) {
        $routeProvider
            .when("/", {templateUrl: "partials/main.html"});
    }]);

    app.controller('NotesController', function() {
       this.posts = note_posts;
    });

    var note_posts = [
        {
            href: "/notes/2016-03-24-awk.html",
            date: "24 Mar 2016",
            title: "Awk",
        },
        {
            href: "/notes/2016-01-14-installing_spamassassin.html",
            date: "14 Jan 2016",
            title: "Installing Spamassassin",
        },
        {
            href: "/notes/2016-01-14-installing_postfix_greylisting.html",
            date: "14 Jan 2016",
            title: "Installing Postfix Greylisting",
        },
        {
            href: "/notes/2016-01-14-installing_postfix.html",
            date: "14 Jan 2016",
            title: "Installing Postfix on System",
        },
        {
            href: "/notes/2016-01-14-installing_nfs_server.html",
            date: "14 Jan 2016",
            title: "Installing NFS Server",
        },
        {
            href: "/notes/2016-01-14-installing_courier.html",
            date: "14 Jan 2016",
            title: "Installing Courier",
        },
        {
            href: "/notes/2016-01-14-installing_automount_ldap.html",
            date: "14 Jan 2016",
            title: "Installing Automount on System (using LDAP)",
        },
        {
            href: "/notes/2016-01-14-configuring_spf.html",
            date: "14 Jan 2016",
            title: "Configuring SPF",
        },
        {
            href: "/notes/2015-10-20-expect_ssh_login.html",
            date: "20 Oct 2015",
            title: "Expecting ssh login",
        },
        {
            href: "/notes/2015-10-02-static_wlan0.html",
            date: "02 Oct 2015",
            title: "Configure static wlan0 in /etc/network/interfaces",
        },
        {
            href: "/notes/2015-10-02-static_eth0.html",
            date: "02 Oct 2015",
            title: "Configure static eth0 in /etc/network/interfaces",
        },
        {
            href: "/notes/2015-10-02-postfix_disable_ipv6.html",
            date: "02 Oct 2015",
            title: "Postfix Address Family Not Supported",
        },
        {
            href: "/notes/2015-09-30-install_ldap.html",
            date: "30 Sep 2015",
            title: "Install and configure LDAP on server",
        },
        {
            href: "/notes/2015-09-30-attach_ldap.html",
            date: "30 Sep 2015",
            title: "Attach to LDAP on server",
        },
        {
            href: "/notes/2015-09-26-install-quagga-rip.html",
            date: "26 Sep 2015",
            title: "Configure Quagga with RIP",
        },
        {
            href: "/notes/2015-09-26-install-dns.html",
            date: "26 Sep 2015",
            title: "Install and Configure DNS",
        },
        {
            href: "/notes/2015-04-27-smb.conf.html",
            date: "27 Apr 2015",
            title: "smb.conf",
        },
        {
            href: "/notes/2015-04-15-usb-hid.html",
            date: "15 Apr 2015",
            title: "USBHID on Linux",
        },
        {
            href: "/notes/2015-03-24-chromium.html",
            date: "24 Mar 2015",
            title: "Cannot click and drag in Chrome/Chromium when running inside a virtualbox",
        },
        {
            href: "/notes/2015-03-21-teamspeak3-server.html",
            date: "21 Mar 2015",
            title: "Setup Teamspeak3 Server",
        },
        {
            href: "/notes/2015-03-19-git.html",
            date: "19 Mar 2015",
            title: "Generic Git Stuff",
        },
        {
            href: "/notes/2014-11-04-makepkg.html",
            date: "04 Nov 2014",
            title: "Archlinux Makepkg / Installing from AUR",
        },
        {
            href: "/notes/2014-10-28-mongodb.html",
            date: "28 Oct 2014",
            title: "Generic Mongodb Usage",
        },
        {
            href: "/notes/2014-10-28-crazykamo.html",
            date: "28 Oct 2014",
            title: "Crazykamo.js",
        },
        {
            href: "/notes/2014-10-27-building-debian-files.html",
            date: "27 Oct 2014",
            title: "Building Debian files",
        },
        {
            href: "/notes/2014-10-27-LaTeX.html",
            date: "27 Oct 2014",
            title: "LaTeX Template",
        },
        {
            href: "/notes/2014-10-27-BSD-ports.html",
            date: "27 Oct 2014",
            title: "BSD Ports",
        },
        {
            href: "/notes/2014-09-17-android-studio.html",
            date: "17 Sep 2014",
            title: "Android Studio Installation",
        },
        {
            href: "/notes/2014-09-17-android-studio-fix-questionmark.html",
            date: "17 Sep 2014",
            title: "Android Studio Questionmark Instead of Phone Name",
        },
        {
            href: "/notes/2014-09-11-sendmail.html",
            date: "11 Sep 2014",
            title: "Testing Sendmail",
        },
        {
            href: "/notes/2014-09-11-sendmail-starttls.html",
            date: "11 Sep 2014",
            title: "Sendmail @ FreeBSD - Activating SMTP AUTH (PLAIN) through STARTLS",
        },
        {
            href: "/notes/2014-09-05-fix-ubuntu-x11.html",
            date: "05 Sep 2014",
            title: "Fix Ubuntu X11",
        },
        {
            href: "/notes/2014-08-29-syscalls.html",
            date: "29 Aug 2014",
            title: "Syscalls",
        },
        {
            href: "/notes/2014-08-29-mysql.html",
            date: "29 Aug 2014",
            title: "Generic MYSQL Usage",
        },
        {
            href: "/notes/2014-08-28-ssh_config.html",
            date: "28 Aug 2014",
            title: ".ssh/config",
        },
        {
            href: "/notes/2014-08-28-ssh.html",
            date: "28 Aug 2014",
            title: "SSH Agent",
        },
        {
            href: "/notes/2014-08-28-cli.html",
            date: "28 Aug 2014",
            title: "Command Line Interface",
        },
        {
            href: "/notes/2014-08-28-c.html",
            date: "28 Aug 2014",
            title: "C Programming",
        },
        {
            href: "/notes/2014-08-28-bash.html",
            date: "28 Aug 2014",
            title: "Bash",
        },
        {
            href: "/notes/2014-01-07-hterm-crosh.html",
            date: "07 Jan 2014",
            title: "Crosh / HTerm",
        },
        {
            href: "/notes/2013-12-30-postfix.html",
            date: "30 Dec 2013",
            title: "Old OpenBSD Postfix main.cf",
        },
        {
            href: "/notes/2013-10-29-pae-error-on-boot.html",
            date: "29 Oct 2013",
            title: "PAE Error on boot",
        },
        {
            href: "/notes/2013-04-11-installing-spotify-on-linux.html",
            date: "11 Apr 2013",
            title: "Installing Spotify on Linux",
        },
    ];
})();<commit_msg>Troubleshooting routes<commit_after>(function() {
    'use strict';

    var app = angular.module('mainApp', [
        'ngRoute',
    ]);

    app.config(['$routeProvider', function($routeProvider) {
        $routeProvider
            .when("/", {templateUrl: "partials/main.html",
controller: NotesController
});
    }]);

    app.controller('NotesController', function() {
       this.posts = note_posts;
    });

    var note_posts = [
        {
            href: "/notes/2016-03-24-awk.html",
            date: "24 Mar 2016",
            title: "Awk",
        },
        {
            href: "/notes/2016-01-14-installing_spamassassin.html",
            date: "14 Jan 2016",
            title: "Installing Spamassassin",
        },
        {
            href: "/notes/2016-01-14-installing_postfix_greylisting.html",
            date: "14 Jan 2016",
            title: "Installing Postfix Greylisting",
        },
        {
            href: "/notes/2016-01-14-installing_postfix.html",
            date: "14 Jan 2016",
            title: "Installing Postfix on System",
        },
        {
            href: "/notes/2016-01-14-installing_nfs_server.html",
            date: "14 Jan 2016",
            title: "Installing NFS Server",
        },
        {
            href: "/notes/2016-01-14-installing_courier.html",
            date: "14 Jan 2016",
            title: "Installing Courier",
        },
        {
            href: "/notes/2016-01-14-installing_automount_ldap.html",
            date: "14 Jan 2016",
            title: "Installing Automount on System (using LDAP)",
        },
        {
            href: "/notes/2016-01-14-configuring_spf.html",
            date: "14 Jan 2016",
            title: "Configuring SPF",
        },
        {
            href: "/notes/2015-10-20-expect_ssh_login.html",
            date: "20 Oct 2015",
            title: "Expecting ssh login",
        },
        {
            href: "/notes/2015-10-02-static_wlan0.html",
            date: "02 Oct 2015",
            title: "Configure static wlan0 in /etc/network/interfaces",
        },
        {
            href: "/notes/2015-10-02-static_eth0.html",
            date: "02 Oct 2015",
            title: "Configure static eth0 in /etc/network/interfaces",
        },
        {
            href: "/notes/2015-10-02-postfix_disable_ipv6.html",
            date: "02 Oct 2015",
            title: "Postfix Address Family Not Supported",
        },
        {
            href: "/notes/2015-09-30-install_ldap.html",
            date: "30 Sep 2015",
            title: "Install and configure LDAP on server",
        },
        {
            href: "/notes/2015-09-30-attach_ldap.html",
            date: "30 Sep 2015",
            title: "Attach to LDAP on server",
        },
        {
            href: "/notes/2015-09-26-install-quagga-rip.html",
            date: "26 Sep 2015",
            title: "Configure Quagga with RIP",
        },
        {
            href: "/notes/2015-09-26-install-dns.html",
            date: "26 Sep 2015",
            title: "Install and Configure DNS",
        },
        {
            href: "/notes/2015-04-27-smb.conf.html",
            date: "27 Apr 2015",
            title: "smb.conf",
        },
        {
            href: "/notes/2015-04-15-usb-hid.html",
            date: "15 Apr 2015",
            title: "USBHID on Linux",
        },
        {
            href: "/notes/2015-03-24-chromium.html",
            date: "24 Mar 2015",
            title: "Cannot click and drag in Chrome/Chromium when running inside a virtualbox",
        },
        {
            href: "/notes/2015-03-21-teamspeak3-server.html",
            date: "21 Mar 2015",
            title: "Setup Teamspeak3 Server",
        },
        {
            href: "/notes/2015-03-19-git.html",
            date: "19 Mar 2015",
            title: "Generic Git Stuff",
        },
        {
            href: "/notes/2014-11-04-makepkg.html",
            date: "04 Nov 2014",
            title: "Archlinux Makepkg / Installing from AUR",
        },
        {
            href: "/notes/2014-10-28-mongodb.html",
            date: "28 Oct 2014",
            title: "Generic Mongodb Usage",
        },
        {
            href: "/notes/2014-10-28-crazykamo.html",
            date: "28 Oct 2014",
            title: "Crazykamo.js",
        },
        {
            href: "/notes/2014-10-27-building-debian-files.html",
            date: "27 Oct 2014",
            title: "Building Debian files",
        },
        {
            href: "/notes/2014-10-27-LaTeX.html",
            date: "27 Oct 2014",
            title: "LaTeX Template",
        },
        {
            href: "/notes/2014-10-27-BSD-ports.html",
            date: "27 Oct 2014",
            title: "BSD Ports",
        },
        {
            href: "/notes/2014-09-17-android-studio.html",
            date: "17 Sep 2014",
            title: "Android Studio Installation",
        },
        {
            href: "/notes/2014-09-17-android-studio-fix-questionmark.html",
            date: "17 Sep 2014",
            title: "Android Studio Questionmark Instead of Phone Name",
        },
        {
            href: "/notes/2014-09-11-sendmail.html",
            date: "11 Sep 2014",
            title: "Testing Sendmail",
        },
        {
            href: "/notes/2014-09-11-sendmail-starttls.html",
            date: "11 Sep 2014",
            title: "Sendmail @ FreeBSD - Activating SMTP AUTH (PLAIN) through STARTLS",
        },
        {
            href: "/notes/2014-09-05-fix-ubuntu-x11.html",
            date: "05 Sep 2014",
            title: "Fix Ubuntu X11",
        },
        {
            href: "/notes/2014-08-29-syscalls.html",
            date: "29 Aug 2014",
            title: "Syscalls",
        },
        {
            href: "/notes/2014-08-29-mysql.html",
            date: "29 Aug 2014",
            title: "Generic MYSQL Usage",
        },
        {
            href: "/notes/2014-08-28-ssh_config.html",
            date: "28 Aug 2014",
            title: ".ssh/config",
        },
        {
            href: "/notes/2014-08-28-ssh.html",
            date: "28 Aug 2014",
            title: "SSH Agent",
        },
        {
            href: "/notes/2014-08-28-cli.html",
            date: "28 Aug 2014",
            title: "Command Line Interface",
        },
        {
            href: "/notes/2014-08-28-c.html",
            date: "28 Aug 2014",
            title: "C Programming",
        },
        {
            href: "/notes/2014-08-28-bash.html",
            date: "28 Aug 2014",
            title: "Bash",
        },
        {
            href: "/notes/2014-01-07-hterm-crosh.html",
            date: "07 Jan 2014",
            title: "Crosh / HTerm",
        },
        {
            href: "/notes/2013-12-30-postfix.html",
            date: "30 Dec 2013",
            title: "Old OpenBSD Postfix main.cf",
        },
        {
            href: "/notes/2013-10-29-pae-error-on-boot.html",
            date: "29 Oct 2013",
            title: "PAE Error on boot",
        },
        {
            href: "/notes/2013-04-11-installing-spotify-on-linux.html",
            date: "11 Apr 2013",
            title: "Installing Spotify on Linux",
        },
    ];
})();<|endoftext|>


<commit_before>(function () {
	//Detailwindow en zijn elementen
	var DetailWindow = {
		window: Titanium.UI.createWindow({
			top: 			0,
			height: 		'100%',
			width: 			'100%',
			backgroundColor: VwApp.Config.ViewBackgroundColor,
			contentHeight: 	'auto'
		}),

		// Een container waar we alles in stoppen
		Container: Titanium.UI.createScrollView({
			height:			'100%',
			width:			'100%',
			layout:			'vertical'
		}),

		//wanneer er een foto beschikbaar is deze weergeven in een imageview
		Imagebridge : 	Ti.UI.createImageView({
			image:				'',
			height: 			'auto',
			width: 				'80%',
			top: 				'2%',
			bottom:				'5%'
		}),

		// Wanneer er geen foto beschikbaar is komt er een tekst te staan
		NoImagebridge : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			bottom: 		'5%',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		//Type van de data
		TypeData : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		13,
			top:			'2%',
			color:			VwApp.Config.TextColor
		}),

		//Hieronder staan de eigenschappen van de data
		Type : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Hoogte : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Breedte : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Bron : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Adres : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Postcode : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Stad : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Oppervlakte : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Code : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		//de button om de brug op de kaart te tonen
		Toonkaart : Titanium.UI.createButton({
			top: 			60,
			image:			VwApp.Config.ShowOnMap,
			position: 		'center'
		})
	};

	// variabelen voor de lat en de lon
	var Lat = "";
	var Lon = "";

	/**
	 *	Een functie die de meegegeven data zal omzetten naar
	 * 		de nieuwe informatie voor de detailView
	 *
	 *	@param {Object} [data]
	 * 		De meegegeven informatie over een annotatie
	 */
	function ChangeValue(data) {
		// wanneer er geen data is gevonden, niks doen.
		if (!data) {
			return;
		}
		// title
		if (data.title) {
			DetailWindow.window.setTitle(data.title);
		} else {
			DetailWindow.window.setTitle("-");
		}

		//het type data bovenaan zetten
		if (data.TYPE == 'jachthavens') {
			DetailWindow.TypeData.setText(Config.JachthavenDetail);
		}

		if (data.TYPE == 'bruggen') {
			DetailWindow.TypeData.setText(Config.BrugDetail);
		}
		if (data.TYPE == 'ligplaatsen') {
			DetailWindow.TypeData.setText(Config.LigplaatsenDetail);
		}

		DetailWindow.Container.add(DetailWindow.NoImagebridge);
		//afbeelding
		if (data.TYPE == 'ligplaatsen' || data.TYPE == 'bruggen') {
			//kijken of er een foto beschikbaar is en of het laten zien van foto's aangevinkt is in de settings.
			if (data.PICTURE && Titanium.App.Properties.getBool('laadData', true)) {
				//foto tonen
				if (data.TYPE == 'bruggen') {
					DetailWindow.Imagebridge.setImage(ChangeBridgeLink(data.PICTURE));
				}

				if (data.TYPE == 'ligplaatsen') {
						DetailWindow.Imagebridge.setImage(ChangeMoorageLink(data.PICTURE));
				}

				DetailWindow.Imagebridge.setHeight('auto');
				DetailWindow.NoImagebridge.setText("");
			} else {
				// geen foto beschikbaar

				// wanneer foto's laden ingeschakeld is en er is geen foto beschikbaar toon de tekst dat er geen foto beschikbaar is
				if (Titanium.App.Properties.getBool('laadData', true)) {
						DetailWindow.Imagebridge.setHeight('0%');  //image hoogte is 0%, dus niet zichtbaar
						DetailWindow.NoImagebridge.setText(VwApp.Config.NoPictureDetail);
				}
				// als het laden van foto's uitgeschakeld is geef hierover een melding
				else {
					// image hoogte is 0%, dus niet zichtbaar
					DetailWindow.Imagebridge.setHeight('0%');
					DetailWindow.NoImagebridge.setText(VwApp.Config.PictureOffDetail);
				}
			}

			DetailWindow.Container.add(DetailWindow.Imagebridge);
			DetailWindow.Container.add(DetailWindow.NoImagebridge);
		}

		// adres, geldt alleen voor bepaalde types
		if (data.TYPE == 'jachthavens' || data.TYPE == 'bruggen') {
			if (data.ADRESS) {
				DetailWindow.Adres.setText(VwApp.Config.AdressDetail + data.ADRESS);
			} else {
				DetailWindow.Adres.setText(VwApp.Config.AdressDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Adres);
		}

		if (data.TYPE == 'bruggen') {
			// hoogte
			if (data.HEIGHT || data.HEIGHT == 0) {
				DetailWindow.Hoogte.setText(VwApp.Config.HeigthDetail + data.HEIGHT + VwApp.Config.UnitDetail);
			} else {
				DetailWindow.Hoogte.setText(VwApp.Config.HeigthDetail + "-");
			}

			// breedte
			if (data.WIDTH || data.WIDTH == 0) {
				DetailWindow.Breedte.setText(VwApp.Config.WidthDetail + data.WIDTH + VwApp.Config.UnitDetail);
			} else {
				DetailWindow.Breedte.setText(VwApp.Config.WidthDetail +"-");
			}

			// type
			if (data.BRIDGETYPE) {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + data.BRIDGETYPE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + "-");
			}

			// bron
			if (data.SOURCE) {
				DetailWindow.Type.setText(VwApp.Config.BronDetail + data.SOURCE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.BronDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Type);
			DetailWindow.Container.add(DetailWindow.Hoogte);
			DetailWindow.Container.add(DetailWindow.Breedte);
			DetailWindow.Container.add(DetailWindow.Bron);
		}

		if (data.TYPE == 'jachthavens') {
			// postcode
			if(data.ZIPCODE) {
				DetailWindow.Postcode.setText(VwApp.Config.ZipcodeDetail + data.ZIPCODE);
			} else {
				DetailWindow.Postcode.setText(VwApp.Config.ZipcodeDetail + "-");
			}

			// stad
			if (data.CITY) {
				DetailWindow.Stad.setText(VwApp.Config.CityDetail + data.CITY);
			} else {
				DetailWindow.Stad.setText(VwApp.Config.CityDetail + "-");
			}

			// oppervlakte
			if (data.SIZE) {
				DetailWindow.Oppervlakte.setText(VwApp.Config.SizeDetail + data.SIZE + VwApp.Config.SquareUnitDetail);
			} else {
				DetailWindow.Oppervlakte.setText(VwApp.Config.SizeDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Stad);
			DetailWindow.Container.add(DetailWindow.Postcode);
			DetailWindow.Container.add(DetailWindow.Oppervlakte);
		}

		if (data.TYPE == 'ligplaatsen') {
			if (data.MOORAGETYPE) {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + data.MOORAGETYPE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + "-");
			}

			if (data.CODE) {
				DetailWindow.Code.setText(VwApp.Config.CodeDetail + data.CODE);
			} else {
				DetailWindow.Code.setText(VwApp.Config.CodeDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Type);
			DetailWindow.Container.add(DetailWindow.Code);
		}

		if (data.LON && data.LAT) {
		    Lat = data.LAT;
		  	Lon = data.LON;
		} else {
			Lat = "";
		  	Lon = "";
		}

		// toonkaart hier pas toevoegen, anders komt deze bovenaan te staan
		DetailWindow.Container.add(DetailWindow.Toonkaart);
	}

	/**
	 * De onnodige info van de link afhalen zodat deze in te laden is als image, toe te passen op de bruglinks
 	 *
 	 * @param {string} [link]
 	 * 		Een link naar een afbeelding
	 */
	function ChangeBridgeLink(link) {
		// inladen van de oude link
		var oldlink = link;

		// link die ontstaat uit de oude link
		var newlink = "";

		//integer om het aantal '/' te tellen
		var slash = 0;

		// de oude link doorlopen, karakter voor karakter
		for (var i = 0; i < oldlink.length; i++) {
			// wanneer en een ',' voorkomt, stoppen met het maken van de nieuwe link
			if (oldlink[i] == ',')
				return newlink;

			// het aantal '/' tellen
			if (oldlink[i] == '/') {
				newlink = newlink + oldlink[i];
				slash++;
			}
			// bij de 6de slash
			if (slash == 6) {
				slash++;

				// alles er tussenuithalen tot er een '=' komt
				while (oldlink[i] != '=') {
					i++
				}
			}
			// else de nieuwe link maken
			if (oldlink[i] != ',' && oldlink[i] != '/' && oldlink[i] != '=' && oldlink[i] != undefined) {
				newlink = newlink + oldlink[i];
			}

		}
	}

	/**
	 * Een functie die de link naar een marrekrite aanlegplaats
	 * 		klaarmaakt voor gebruik
	 *
 	 * @param {Object} [oldlink]
 	 * 		De link naar de afbeelding zoals deze voorkomt in de annotaties data
 	 *
	 */
	function ChangeMoorageLink(oldlink) {

		// link die ontstaat uit de oude link
		var newlink = "";

		// integer om het aantal '/' te tellen
		var slash = 0;

		// de oude link doorlopen, karakter voor karakter
		for (var i = 0; i < oldlink.length; i++) {
			if (oldlink[i] == '/') {
				slash++
			}

			// bij de 7de slash
			if (slash == 7) {
				// stukje toevoegen aan de nieuwe link
				newlink = newlink + "/foto_marrekrite/";
				// de laatste 5 karakters plakken aan de nieuwe link
				for (var n = oldlink.length - 5; n < oldlink.length; n++) {
					newlink = newlink + oldlink[n];
				}
				// fotonummer toevoegen aan de link, in dit geval altijd 1
				newlink = newlink + "_1.jpg";
				return newlink;
			}
			// newlink maken uit de oude link
			newlink = newlink + oldlink[i];
		}

	}

	// wanneer er geklikt wordt op de button setlocation op map en open de map, mits lat en lon aanwezig
	DetailWindow.Toonkaart.addEventListener('click', function() {
		if (Lat != "") {
			VwApp.Map.setLocation(Lat, Lon, VwApp.Config.DefaultUserLocZoom);
			VwApp.UI.TabBar.tabGroup.setActiveTab(VwApp.UI.TabBar.mapTab);
			VwApp.UI.DetailWindow.window.close();
		}
	});

	// toevoegen aan scrollview
	DetailWindow.window.add(DetailWindow.Container);

	VwApp.UI.DetailWindow = DetailWindow;
	VwApp.UI.changeDetailView = ChangeValue;
})();
<commit_msg>Nog een spatie :D<commit_after>(function () {
	//Detailwindow en zijn elementen
	var DetailWindow = {
		window: Titanium.UI.createWindow({
			top: 			0,
			height: 		'100%',
			width: 			'100%',
			backgroundColor: VwApp.Config.ViewBackgroundColor,
			contentHeight: 	'auto'
		}),

		// Een container waar we alles in stoppen
		Container: Titanium.UI.createScrollView({
			height:			'100%',
			width:			'100%',
			layout:			'vertical'
		}),

		//wanneer er een foto beschikbaar is deze weergeven in een imageview
		Imagebridge : 	Ti.UI.createImageView({
			image:				'',
			height: 			'auto',
			width: 				'80%',
			top: 				'2%',
			bottom:				'5%'
		}),

		// Wanneer er geen foto beschikbaar is komt er een tekst te staan
		NoImagebridge : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			bottom: 		'5%',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		//Type van de data
		TypeData : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		13,
			top:			'2%',
			color:			VwApp.Config.TextColor
		}),

		//Hieronder staan de eigenschappen van de data
		Type : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Hoogte : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Breedte : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Bron : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Adres : Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Postcode : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Stad : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Oppervlakte : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		Code : 	Titanium.UI.createLabel({
			text : 			"",
			textAlign : 	"left",
			left: 			'3 %',
			width : 		'auto',
			heigth : 		'auto',
			color:			VwApp.Config.TextColor
		}),

		//de button om de brug op de kaart te tonen
		Toonkaart : Titanium.UI.createButton({
			top: 			60,
			image:			VwApp.Config.ShowOnMap,
			position: 		'center'
		})
	};

	// variabelen voor de lat en de lon
	var Lat = "";
	var Lon = "";

	/**
	 *	Een functie die de meegegeven data zal omzetten naar
	 * 		de nieuwe informatie voor de detailView
	 *
	 *	@param {Object} [data]
	 * 		De meegegeven informatie over een annotatie
	 */
	function ChangeValue(data) {
		// wanneer er geen data is gevonden, niks doen.
		if (!data) {
			return;
		}
		// title
		if (data.title) {
			DetailWindow.window.setTitle(data.title);
		} else {
			DetailWindow.window.setTitle("-");
		}

		// het type data bovenaan zetten
		if (data.TYPE == 'jachthavens') {
			DetailWindow.TypeData.setText(Config.JachthavenDetail);
		}

		if (data.TYPE == 'bruggen') {
			DetailWindow.TypeData.setText(Config.BrugDetail);
		}
		if (data.TYPE == 'ligplaatsen') {
			DetailWindow.TypeData.setText(Config.LigplaatsenDetail);
		}

		DetailWindow.Container.add(DetailWindow.NoImagebridge);
		// afbeelding
		if (data.TYPE == 'ligplaatsen' || data.TYPE == 'bruggen') {
			// kijken of er een foto beschikbaar is en of het laten zien van foto's aangevinkt is in de settings.
			if (data.PICTURE && Titanium.App.Properties.getBool('laadData', true)) {
				// foto tonen
				if (data.TYPE == 'bruggen') {
					DetailWindow.Imagebridge.setImage(ChangeBridgeLink(data.PICTURE));
				}

				if (data.TYPE == 'ligplaatsen') {
						DetailWindow.Imagebridge.setImage(ChangeMoorageLink(data.PICTURE));
				}

				DetailWindow.Imagebridge.setHeight('auto');
				DetailWindow.NoImagebridge.setText("");
			} else {
				// geen foto beschikbaar

				// wanneer foto's laden ingeschakeld is en er is geen foto beschikbaar toon de tekst dat er geen foto beschikbaar is
				if (Titanium.App.Properties.getBool('laadData', true)) {
						DetailWindow.Imagebridge.setHeight('0%');  //image hoogte is 0%, dus niet zichtbaar
						DetailWindow.NoImagebridge.setText(VwApp.Config.NoPictureDetail);
				}
				// als het laden van foto's uitgeschakeld is geef hierover een melding
				else {
					// image hoogte is 0%, dus niet zichtbaar
					DetailWindow.Imagebridge.setHeight('0%');
					DetailWindow.NoImagebridge.setText(VwApp.Config.PictureOffDetail);
				}
			}

			DetailWindow.Container.add(DetailWindow.Imagebridge);
			DetailWindow.Container.add(DetailWindow.NoImagebridge);
		}

		// adres, geldt alleen voor bepaalde types
		if (data.TYPE == 'jachthavens' || data.TYPE == 'bruggen') {
			if (data.ADRESS) {
				DetailWindow.Adres.setText(VwApp.Config.AdressDetail + data.ADRESS);
			} else {
				DetailWindow.Adres.setText(VwApp.Config.AdressDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Adres);
		}

		if (data.TYPE == 'bruggen') {
			// hoogte
			if (data.HEIGHT || data.HEIGHT == 0) {
				DetailWindow.Hoogte.setText(VwApp.Config.HeigthDetail + data.HEIGHT + VwApp.Config.UnitDetail);
			} else {
				DetailWindow.Hoogte.setText(VwApp.Config.HeigthDetail + "-");
			}

			// breedte
			if (data.WIDTH || data.WIDTH == 0) {
				DetailWindow.Breedte.setText(VwApp.Config.WidthDetail + data.WIDTH + VwApp.Config.UnitDetail);
			} else {
				DetailWindow.Breedte.setText(VwApp.Config.WidthDetail +"-");
			}

			// type
			if (data.BRIDGETYPE) {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + data.BRIDGETYPE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + "-");
			}

			// bron
			if (data.SOURCE) {
				DetailWindow.Type.setText(VwApp.Config.BronDetail + data.SOURCE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.BronDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Type);
			DetailWindow.Container.add(DetailWindow.Hoogte);
			DetailWindow.Container.add(DetailWindow.Breedte);
			DetailWindow.Container.add(DetailWindow.Bron);
		}

		if (data.TYPE == 'jachthavens') {
			// postcode
			if(data.ZIPCODE) {
				DetailWindow.Postcode.setText(VwApp.Config.ZipcodeDetail + data.ZIPCODE);
			} else {
				DetailWindow.Postcode.setText(VwApp.Config.ZipcodeDetail + "-");
			}

			// stad
			if (data.CITY) {
				DetailWindow.Stad.setText(VwApp.Config.CityDetail + data.CITY);
			} else {
				DetailWindow.Stad.setText(VwApp.Config.CityDetail + "-");
			}

			// oppervlakte
			if (data.SIZE) {
				DetailWindow.Oppervlakte.setText(VwApp.Config.SizeDetail + data.SIZE + VwApp.Config.SquareUnitDetail);
			} else {
				DetailWindow.Oppervlakte.setText(VwApp.Config.SizeDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Stad);
			DetailWindow.Container.add(DetailWindow.Postcode);
			DetailWindow.Container.add(DetailWindow.Oppervlakte);
		}

		if (data.TYPE == 'ligplaatsen') {
			if (data.MOORAGETYPE) {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + data.MOORAGETYPE);
			} else {
				DetailWindow.Type.setText(VwApp.Config.TypeDetail + "-");
			}

			if (data.CODE) {
				DetailWindow.Code.setText(VwApp.Config.CodeDetail + data.CODE);
			} else {
				DetailWindow.Code.setText(VwApp.Config.CodeDetail + "-");
			}

			DetailWindow.Container.add(DetailWindow.Type);
			DetailWindow.Container.add(DetailWindow.Code);
		}

		if (data.LON && data.LAT) {
		    Lat = data.LAT;
		  	Lon = data.LON;
		} else {
			Lat = "";
		  	Lon = "";
		}

		// toonkaart hier pas toevoegen, anders komt deze bovenaan te staan
		DetailWindow.Container.add(DetailWindow.Toonkaart);
	}

	/**
	 * De onnodige info van de link afhalen zodat deze in te laden is als image, toe te passen op de bruglinks
 	 *
 	 * @param {string} [link]
 	 * 		Een link naar een afbeelding
	 */
	function ChangeBridgeLink(link) {
		// inladen van de oude link
		var oldlink = link;

		// link die ontstaat uit de oude link
		var newlink = "";

		//integer om het aantal '/' te tellen
		var slash = 0;

		// de oude link doorlopen, karakter voor karakter
		for (var i = 0; i < oldlink.length; i++) {
			// wanneer en een ',' voorkomt, stoppen met het maken van de nieuwe link
			if (oldlink[i] == ',')
				return newlink;

			// het aantal '/' tellen
			if (oldlink[i] == '/') {
				newlink = newlink + oldlink[i];
				slash++;
			}
			// bij de 6de slash
			if (slash == 6) {
				slash++;

				// alles er tussenuithalen tot er een '=' komt
				while (oldlink[i] != '=') {
					i++
				}
			}
			// else de nieuwe link maken
			if (oldlink[i] != ',' && oldlink[i] != '/' && oldlink[i] != '=' && oldlink[i] != undefined) {
				newlink = newlink + oldlink[i];
			}

		}
	}

	/**
	 * Een functie die de link naar een marrekrite aanlegplaats
	 * 		klaarmaakt voor gebruik
	 *
 	 * @param {Object} [oldlink]
 	 * 		De link naar de afbeelding zoals deze voorkomt in de annotaties data
 	 *
	 */
	function ChangeMoorageLink(oldlink) {

		// link die ontstaat uit de oude link
		var newlink = "";

		// integer om het aantal '/' te tellen
		var slash = 0;

		// de oude link doorlopen, karakter voor karakter
		for (var i = 0; i < oldlink.length; i++) {
			if (oldlink[i] == '/') {
				slash++
			}

			// bij de 7de slash
			if (slash == 7) {
				// stukje toevoegen aan de nieuwe link
				newlink = newlink + "/foto_marrekrite/";
				// de laatste 5 karakters plakken aan de nieuwe link
				for (var n = oldlink.length - 5; n < oldlink.length; n++) {
					newlink = newlink + oldlink[n];
				}
				// fotonummer toevoegen aan de link, in dit geval altijd 1
				newlink = newlink + "_1.jpg";
				return newlink;
			}
			// newlink maken uit de oude link
			newlink = newlink + oldlink[i];
		}

	}

	// wanneer er geklikt wordt op de button setlocation op map en open de map, mits lat en lon aanwezig
	DetailWindow.Toonkaart.addEventListener('click', function() {
		if (Lat != "") {
			VwApp.Map.setLocation(Lat, Lon, VwApp.Config.DefaultUserLocZoom);
			VwApp.UI.TabBar.tabGroup.setActiveTab(VwApp.UI.TabBar.mapTab);
			VwApp.UI.DetailWindow.window.close();
		}
	});

	// toevoegen aan scrollview
	DetailWindow.window.add(DetailWindow.Container);

	VwApp.UI.DetailWindow = DetailWindow;
	VwApp.UI.changeDetailView = ChangeValue;
})();
<|endoftext|>