<commit_before>define(['browser', 'jquery', 'sidebar', 'viewer'], function(Browser, $, Sidebar, Viewer) {

var App = {
	start: function() {
		var app = this;

		console.log('Starting application');

		app.sidebar = new Sidebar();
		app.browser = new Browser();
		app.viewer = new Viewer();

		app.setUiMode('main');

		console.log('Application started');

		window.addEventListener('hashchange', function() {
			app.dispatchHash();
		});

		app.dispatchHash();
	},

	getUiMode: function() {
		var mode = null;

		$.each(document.body.className.split(' '), function(idx, val) {
			if (val.indexOf('ui-mode-') === 0) {
				mode = val.slice('ui-mode-'.length);
				return;
			}
		});

		return mode;
	},

	setUiMode: function(mode) {
		var $body = $(document.body);
		var modeName = 'ui-mode-' + mode;
		var currentMode = this.getUiMode();

		if (currentMode) {
			if (currentMode === mode) {
				return;
			}

			$body.removeClass('ui-mode-' + currentMode);
		}

		$body.addClass(modeName);
	},

	hashRoutes: {
		'browse': 'browseAlbum',
		'view': 'viewPicture'
	},

	dispatchHash: function() {
		var hash = document.location.hash;

		if (hash === '') {
			this.browseAlbum(null);
			return;
		}

		hash = hash.slice(1); // remove the leading #

		for (x in this.hashRoutes) {
			var prefix = x + ':';

			if (hash.indexOf(prefix) !== 0) {
				continue;
			}

			var f = this[this.hashRoutes[x]];

			if (f === undefined) {
				console.log('Undefined route function: ' + this.hashRoutes[x]);
				return;
			}

			f.call(this, hash.slice(prefix.length));
		}
	},

	sortPicturesByDate: function(pictures) {
		// For each picture, parse the EXIF date (if any)
		$.each(pictures, function(idx, pic) {
			if (!pic.metadata) {
				return;
			}

			var exifDate = pic.metadata['Exif.Photo.DateTimeOriginal'];

			if (!exifDate) {
				return;
			}

			// Format of the date is 2013:11:13 11:14:12

			if (exifDate.length != 19) {
				console.log('Cannot parse EXIF date ' + exifDate + ': invalid length');
				return;
			}

			var yearStr = exifDate.slice(0, 4);
			var monthStr = exifDate.slice(5, 7);
			var dayStr = exifDate.slice(8, 10);
			var hourStr = exifDate.slice(11, 13);
			var minuteStr = exifDate.slice(14, 16);
			var secondStr = exifDate.slice(17, 19);

			date = new Date(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);

			if (isNaN(date.getTime())) {
				console.log('Cannot parse EXIF date ' + exifDate);
				return;
			}

			pic.date = date;
		});

		pictures.sort(function (a, b) {
			// If we have no date at all, fallback on filename lexical sort
			if (!a.date && !b.date) {
				return (a.path === b.path ? 0 : (a.path < b.path ? -1 : 1));
			}

			if (a.date && !b.date) {
				return -1;
			}

			if (!a.date && b.date) {
				return 1;
			}

			var ta = a.date.getTime();
			var tb = b.date.getTime();

			return (ta === tb ? 0 : (ta < tb ? -1 : 1));
		});
	},

	loadAlbum: function(name, cb) {
		var app = this;

		if (this.album && this.album.name === name) {
			cb(this.album);
		}

		$.getJSON('/albums/' + name, function(data) {
			app.sortPicturesByDate(data.pictures);

			app.album = data;

			cb(data);
		});
	},

	browseAlbum: function(album) {
		var app = this;

		app.setUiMode('main');

		if (album) {
			app.loadAlbum(album, function(data) {
				app.browser.browse(data);
			});
		}
	},

	viewPicture: function(path) {
		var app = this;

		this.setUiMode('viewer');

		var idx = path.lastIndexOf('/');
		var album = path.slice(0, idx);
		var filename = path.slice(1+idx);

		app.loadAlbum(album, function(data) {
			app.viewer.view(data, filename);
		});
	}
};

return App;

}); // define
<commit_msg>ui: Don't reload album from network if we have a cached version<commit_after>define(['browser', 'jquery', 'sidebar', 'viewer'], function(Browser, $, Sidebar, Viewer) {

var App = {
	start: function() {
		var app = this;

		console.log('Starting application');

		app.sidebar = new Sidebar();
		app.browser = new Browser();
		app.viewer = new Viewer();

		app.setUiMode('main');

		console.log('Application started');

		window.addEventListener('hashchange', function() {
			app.dispatchHash();
		});

		app.dispatchHash();
	},

	getUiMode: function() {
		var mode = null;

		$.each(document.body.className.split(' '), function(idx, val) {
			if (val.indexOf('ui-mode-') === 0) {
				mode = val.slice('ui-mode-'.length);
				return;
			}
		});

		return mode;
	},

	setUiMode: function(mode) {
		var $body = $(document.body);
		var modeName = 'ui-mode-' + mode;
		var currentMode = this.getUiMode();

		if (currentMode) {
			if (currentMode === mode) {
				return;
			}

			$body.removeClass('ui-mode-' + currentMode);
		}

		$body.addClass(modeName);
	},

	hashRoutes: {
		'browse': 'browseAlbum',
		'view': 'viewPicture'
	},

	dispatchHash: function() {
		var hash = document.location.hash;

		if (hash === '') {
			this.browseAlbum(null);
			return;
		}

		hash = hash.slice(1); // remove the leading #

		for (x in this.hashRoutes) {
			var prefix = x + ':';

			if (hash.indexOf(prefix) !== 0) {
				continue;
			}

			var f = this[this.hashRoutes[x]];

			if (f === undefined) {
				console.log('Undefined route function: ' + this.hashRoutes[x]);
				return;
			}

			f.call(this, hash.slice(prefix.length));
		}
	},

	sortPicturesByDate: function(pictures) {
		// For each picture, parse the EXIF date (if any)
		$.each(pictures, function(idx, pic) {
			if (!pic.metadata) {
				return;
			}

			var exifDate = pic.metadata['Exif.Photo.DateTimeOriginal'];

			if (!exifDate) {
				return;
			}

			// Format of the date is 2013:11:13 11:14:12

			if (exifDate.length != 19) {
				console.log('Cannot parse EXIF date ' + exifDate + ': invalid length');
				return;
			}

			var yearStr = exifDate.slice(0, 4);
			var monthStr = exifDate.slice(5, 7);
			var dayStr = exifDate.slice(8, 10);
			var hourStr = exifDate.slice(11, 13);
			var minuteStr = exifDate.slice(14, 16);
			var secondStr = exifDate.slice(17, 19);

			date = new Date(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr);

			if (isNaN(date.getTime())) {
				console.log('Cannot parse EXIF date ' + exifDate);
				return;
			}

			pic.date = date;
		});

		pictures.sort(function (a, b) {
			// If we have no date at all, fallback on filename lexical sort
			if (!a.date && !b.date) {
				return (a.path === b.path ? 0 : (a.path < b.path ? -1 : 1));
			}

			if (a.date && !b.date) {
				return -1;
			}

			if (!a.date && b.date) {
				return 1;
			}

			var ta = a.date.getTime();
			var tb = b.date.getTime();

			return (ta === tb ? 0 : (ta < tb ? -1 : 1));
		});
	},

	loadAlbum: function(name, cb) {
		var app = this;

		if (this.album && this.album.name === name) {
			cb(this.album);
			return;
		}

		$.getJSON('/albums/' + name, function(data) {
			app.sortPicturesByDate(data.pictures);

			app.album = data;

			cb(data);
		});
	},

	browseAlbum: function(album) {
		var app = this;

		app.setUiMode('main');

		if (album) {
			app.loadAlbum(album, function(data) {
				app.browser.browse(data);
			});
		}
	},

	viewPicture: function(path) {
		var app = this;

		this.setUiMode('viewer');

		var idx = path.lastIndexOf('/');
		var album = path.slice(0, idx);
		var filename = path.slice(1+idx);

		app.loadAlbum(album, function(data) {
			app.viewer.view(data, filename);
		});
	}
};

return App;

}); // define
<|endoftext|>


<commit_before>// Copyright (c) 2019, Compiler Explorer Team
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

const
    BaseCompiler = require('../base-compiler'),
    fs = require('fs-extra'),
    path = require('path'),
    logger = require('../logger').logger;

class CleanCompiler extends BaseCompiler {
    optionsForFilter(filters, outputFilename) {
        if (filters.binary) {
			return [];
        } else {
            return ['-S'];
        }
    }

    getOutputFilename(dirPath, outputFilebase) {
        return path.join(dirPath, "Clean System Files/example.s");
    }

    runCompiler(compiler, options, inputFilename, execOptions) {
        const tmpDir = path.dirname(inputFilename);
		const moduleName = path.basename(inputFilename, '.icl');
		const compilerPath = path.dirname(compiler);
        execOptions = this.getDefaultExecOptions();
        execOptions.customCwd = tmpDir;
		execOptions.env.CLEANLIB = path.join(compilerPath, "../exe");
		execOptions.env.CLEANPATH = path.join(compilerPath, "../StdEnv");
        options.pop();
        options.push(moduleName);
        return super.runCompiler(compiler, options, moduleName, execOptions).then(result => {
            if (fs.existsSync(this.getOutputFilename(tmpDir))) {
                result.code = 0;
            }
            return result;
        });
    }
}

module.exports = CleanCompiler;
<commit_msg>extra libpaths<commit_after>// Copyright (c) 2019, Compiler Explorer Team
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

const
    BaseCompiler = require('../base-compiler'),
    fs = require('fs-extra'),
    path = require('path'),
    logger = require('../logger').logger;

class CleanCompiler extends BaseCompiler {
    optionsForFilter(filters, outputFilename) {
        if (filters.binary) {
			return [];
        } else {
            return ['-S'];
        }
    }

    getOutputFilename(dirPath, outputFilebase) {
        return path.join(dirPath, "Clean System Files/example.s");
    }

    runCompiler(compiler, options, inputFilename, execOptions) {
        const tmpDir = path.dirname(inputFilename);
		const moduleName = path.basename(inputFilename, '.icl');
		const compilerPath = path.dirname(compiler);
        execOptions = this.getDefaultExecOptions();
        execOptions.customCwd = tmpDir;
		execOptions.env.CLEANLIB = path.join(compilerPath, "../exe");
		execOptions.env.CLEANPATH = [
			path.join(compilerPath, "../ArgEnv"),
			path.join(compilerPath, "../Directory"),
			path.join(compilerPath, "../Dynamics"),
			path.join(compilerPath, "../Gast"),
			path.join(compilerPath, "../Generics"),
			path.join(compilerPath, "../GraphCopy"),
			path.join(compilerPath, "../iTasks"),
			path.join(compilerPath, "../ObjectIO"),
			path.join(compilerPath, "../Platform"),
			path.join(compilerPath, "../Sapl"),
			path.join(compilerPath, "../StdEnv"),
			path.join(compilerPath, "../StdLib"),
			path.join(compilerPath, "../TCPIP")
		].join(":");
        options.pop();
        options.push(moduleName);
        return super.runCompiler(compiler, options, moduleName, execOptions).then(result => {
            if (fs.existsSync(this.getOutputFilename(tmpDir))) {
                result.code = 0;
            }
            return result;
        });
    }
}

module.exports = CleanCompiler;
<|endoftext|>


<commit_before>function useAccelerated() {
    if(Platform.isAndroid()) {
        return Platform.version > 2;
    }
    if(Platform.isWebOS()) {
        return Platform.version >= 3;
    }
    if(Platform.isWebWorks()) {
        return true;
    }
    return false;
}

prefs = {
    set: function(prop, setting)
    {
        setting = JSON.stringify(setting);
        localStorage.setItem(prop, setting);
        enyo.setCookie(prop, setting, { "Max-Age": 31536000 });
    },
    get: function(prop)
    {
        var x = localStorage && localStorage.getItem(prop);
        if(x) {
            try {
                x = JSON.parse(x);
            } catch(err) {
                // do nothing
            }
        }
        return x || (document && document.cookie && enyo.getCookie(prop));
    },
    del: function(prop)
    {
        localStorage.removeItem(prop);
        enyo.setCookie(prop, undefined, { "Max-Age": 0 } );
    },
    def: function(prop, setting)
    {
        var x = prefs.get(prop);
        enyo.log("def", prop, x, setting);
        if( (!isNaN(x) && isNaN(setting)) || x === undefined)
            prefs.set(prop, setting);
    }
};

function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    if(hours > 0)
        return (hours < 10 ? "0" : "") + hours+":" + (minutes < 10 ? "0" : "") + minutes+":"+(seconds < 10 ? "0" : "") + seconds;
    return (minutes < 10 ? "0" : "") + minutes+":" + (seconds < 10 ? "0" : "") + seconds;
}

function useInternalWebView()
{
    return false;
    //return isLargeScreen() && window.PalmSystem;
}

function stripHtml(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}

function formatPhoneNumber(phonenum) {
    var regexObj = /^(?:\+?1[-. ]?)?(?:\(?([0-9]{3})\)?[-. ]?)?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (regexObj.test(phonenum)) {
        var parts = phonenum.match(regexObj);
        var phone = "";
        if (parts[1]) { phone += "+1 (" + parts[1] + ") "; }
        phone += parts[2] + "-" + parts[3];
        return phone;
    }
    else {
        //invalid phone number
        return phonenum;
    }
}

function ParseMessages(html)
{
    var ret = [ ];
    var tmp = document.createElement("DIV");

    html = html.replace(/src=\"/g, 'src="https://www.google.com');
    tmp.innerHTML = html;

    SMSMessageBlocks = tmp.getElementsByClassName("gc-message-sms-row");
    for(var x = 0; x < SMSMessageBlocks.length; x++)
    {
        ret[x] = [ ];
        ret[x].SentBy = enyo.string.trim(SMSMessageBlocks[x].getElementsByClassName("gc-message-sms-from")[0].textContent);
        ret[x].SentTime = SMSMessageBlocks[x].getElementsByClassName("gc-message-sms-time")[0].textContent;
        // non-webOS and webOS 1/2 have broken runTextIndexer
        if(typeof Platform !== "undefined" && Platform.isWebOS() && Platform.platformVersion >= 3)
            ret[x].SentMessage = enyo.string.runTextIndexer(SMSMessageBlocks[x].getElementsByClassName("gc-message-sms-text")[0].textContent, { emoticon: false });
        else
            ret[x].SentMessage = SMSMessageBlocks[x].getElementsByClassName("gc-message-sms-text")[0].textContent;
    }
    // TODO: rewrite the voicemail search now that we know wtf field names we need?
    var vmt = tmp.getElementsByClassName("gc-edited-trans-text");
    if(vmt.length > 0) {
        VMTranscripts = tmp.getElementsByClassName("gc-message-tbl");
        if(VMTranscripts.length > 0) {
            for(x = 0; x < VMTranscripts.length; x++)
            {
                ret[x] = [ ];
                ret[x].SentBy = enyo.string.trim(VMTranscripts[x].getElementsByClassName("gc-message-name")[0].textContent);
                ret[x].SentTime = VMTranscripts[x].getElementsByClassName("gc-message-time")[0].textContent;
                vmt = VMTranscripts[x].getElementsByClassName("gc-edited-trans-text");
                ret[x].VoicemailTranscript = enyo.string.runTextIndexer(vmt[0].textContent, { emoticon: false });
            }
        }
    }
    var missedCallCheck = tmp.getElementsByClassName("gc-message-icon-0");
    ret.isMissedCall = (missedCallCheck.length > 0);
    var blockedCallerCheck = tmp.getElementsByClassName("gc-message-blocked");
    ret.isBlockedCaller = (blockedCallerCheck.length > 0);
    ret.html = html;
    ret.Portrait = tmp.getElementsByTagName("img")[0]; //ret.Portrait.getElementsByTagName("img");
    ret.Location = tmp.getElementsByClassName("gc-message-location");
    if(ret.Location.length > 0)
    {
        ret.Location = ret.Location[0].textContent;
    } else {
        ret.Location = "";
    }
    delete tmp.innerHtml;
    return ret;
}

function ParsePrimaryData(html)
{
    enyo.log("Parsing Primary Data");
    html = enyo.string.trim(html);
    var i = html.indexOf("var _gcData = {") + 14;
    var j = html.indexOf("};", i) + 1;
    tmp = html.substring(i,j);
    tmp = tmp.replace("<!-- TODO(pmoor): remove this as soon as the 9/12 release is cut -->", "");
    tmp = tmp.replace(/\'/g, '"');
    //enyo.log("tmp = " + tmp);
    try {
        var primarydata = JSON.parse(tmp);
    } catch(err) {
        //enyo.application.mainApp.$.ErrorPopup.openAtCenter();
        enyo.application.mainApp.$.rightPane.selectViewByName("errorView");
        enyo.application.debuglog("ERROR: " + err);
        enyo.application.debuglog("tmp="+tmp);
        enyo.application.debuglog("html="+html);
        //enyo.application.mainApp.$.errorView.$.ErrorBox.content += "ERROR: " + err + " tmp="+tmp + " html="+html;
        //enyo.application.mainApp.$.errorView.render();
        return;
    }

    var index = 0;
    var counter = 0;
    var tempcontacts = new Array();
    for(var id in primarydata.contacts)
    {
        counter++;
        if(primarydata.contacts.hasOwnProperty(id) && primarydata.contacts[id].displayNumber)
        {
            tempcontacts[index] = primarydata.contacts[id];
            //primarydata.contacts[index] = primarydata.contacts[id];
            index++;
        }
    }
    primarydata.contacts = tempcontacts;
    primarydata.contacts.sort( function(i1, i2) { return i1.name.localeCompare(i2.name); });
    enyo.log("ParsePrimaryData: " + index + "/" + counter + " contacts with displayNumber set");
    enyo.log("RankedContacts: " + primarydata.rankedContacts.length);
    index = 0;
    /*for(id in primarydata.phones)
    {
        if(primarydata.phones.hasOwnProperty(id))
        {
            primarydata.phones[index] = primarydata.phones[id];
            index++;
        }
    }*/

    return primarydata;
}

function pluralize(str, count)
{
    return (count != 1) ? str + "s" : str;
}<commit_msg>temp disable all accelerated scrolling on webos .. ?<commit_after>function useAccelerated() {
    if(Platform.isAndroid()) {
        return Platform.version > 2;
    }
    if(Platform.isWebOS()) {
        //return Platform.version >= 3;
        return false;
    }
    if(Platform.isWebWorks()) {
        return true;
    }
    return false;
}

prefs = {
    set: function(prop, setting)
    {
        setting = JSON.stringify(setting);
        localStorage.setItem(prop, setting);
        enyo.setCookie(prop, setting, { "Max-Age": 31536000 });
    },
    get: function(prop)
    {
        var x = localStorage && localStorage.getItem(prop);
        if(x) {
            try {
                x = JSON.parse(x);
            } catch(err) {
                // do nothing
            }
        }
        return x || (document && document.cookie && enyo.getCookie(prop));
    },
    del: function(prop)
    {
        localStorage.removeItem(prop);
        enyo.setCookie(prop, undefined, { "Max-Age": 0 } );
    },
    def: function(prop, setting)
    {
        var x = prefs.get(prop);
        enyo.log("def", prop, x, setting);
        if( (!isNaN(x) && isNaN(setting)) || x === undefined)
            prefs.set(prop, setting);
    }
};

function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    if(hours > 0)
        return (hours < 10 ? "0" : "") + hours+":" + (minutes < 10 ? "0" : "") + minutes+":"+(seconds < 10 ? "0" : "") + seconds;
    return (minutes < 10 ? "0" : "") + minutes+":" + (seconds < 10 ? "0" : "") + seconds;
}

function useInternalWebView()
{
    return false;
    //return isLargeScreen() && window.PalmSystem;
}

function stripHtml(html)
{
   var tmp = document.createElement("DIV");
   tmp.innerHTML = html;
   return tmp.textContent||tmp.innerText;
}

function formatPhoneNumber(phonenum) {
    var regexObj = /^(?:\+?1[-. ]?)?(?:\(?([0-9]{3})\)?[-. ]?)?([0-9]{3})[-. ]?([0-9]{4})$/;
    if (regexObj.test(phonenum)) {
        var parts = phonenum.match(regexObj);
        var phone = "";
        if (parts[1]) { phone += "+1 (" + parts[1] + ") "; }
        phone += parts[2] + "-" + parts[3];
        return phone;
    }
    else {
        //invalid phone number
        return phonenum;
    }
}

function ParseMessages(html)
{
    var ret = [ ];
    var tmp = document.createElement("DIV");

    html = html.replace(/src=\"/g, 'src="https://www.google.com');
    tmp.innerHTML = html;

    SMSMessageBlocks = tmp.getElementsByClassName("gc-message-sms-row");
    for(var x = 0; x < SMSMessageBlocks.length; x++)
    {
        ret[x] = [ ];
        ret[x].SentBy = enyo.string.trim(SMSMessageBlocks[x].getElementsByClassName("gc-message-sms-from")[0].textContent);
        ret[x].SentTime = SMSMessageBlocks[x].getElementsByClassName("gc-message-sms-time")[0].textContent;
        // non-webOS and webOS 1/2 have broken runTextIndexer
        if(typeof Platform !== "undefined" && Platform.isWebOS() && Platform.platformVersion >= 3)
            ret[x].SentMessage = enyo.string.runTextIndexer(SMSMessageBlocks[x].getElementsByClassName("gc-message-sms-text")[0].textContent, { emoticon: false });
        else
            ret[x].SentMessage = SMSMessageBlocks[x].getElementsByClassName("gc-message-sms-text")[0].textContent;
    }
    // TODO: rewrite the voicemail search now that we know wtf field names we need?
    var vmt = tmp.getElementsByClassName("gc-edited-trans-text");
    if(vmt.length > 0) {
        VMTranscripts = tmp.getElementsByClassName("gc-message-tbl");
        if(VMTranscripts.length > 0) {
            for(x = 0; x < VMTranscripts.length; x++)
            {
                ret[x] = [ ];
                ret[x].SentBy = enyo.string.trim(VMTranscripts[x].getElementsByClassName("gc-message-name")[0].textContent);
                ret[x].SentTime = VMTranscripts[x].getElementsByClassName("gc-message-time")[0].textContent;
                vmt = VMTranscripts[x].getElementsByClassName("gc-edited-trans-text");
                ret[x].VoicemailTranscript = enyo.string.runTextIndexer(vmt[0].textContent, { emoticon: false });
            }
        }
    }
    var missedCallCheck = tmp.getElementsByClassName("gc-message-icon-0");
    ret.isMissedCall = (missedCallCheck.length > 0);
    var blockedCallerCheck = tmp.getElementsByClassName("gc-message-blocked");
    ret.isBlockedCaller = (blockedCallerCheck.length > 0);
    ret.html = html;
    ret.Portrait = tmp.getElementsByTagName("img")[0]; //ret.Portrait.getElementsByTagName("img");
    ret.Location = tmp.getElementsByClassName("gc-message-location");
    if(ret.Location.length > 0)
    {
        ret.Location = ret.Location[0].textContent;
    } else {
        ret.Location = "";
    }
    delete tmp.innerHtml;
    return ret;
}

function ParsePrimaryData(html)
{
    enyo.log("Parsing Primary Data");
    html = enyo.string.trim(html);
    var i = html.indexOf("var _gcData = {") + 14;
    var j = html.indexOf("};", i) + 1;
    tmp = html.substring(i,j);
    tmp = tmp.replace("<!-- TODO(pmoor): remove this as soon as the 9/12 release is cut -->", "");
    tmp = tmp.replace(/\'/g, '"');
    //enyo.log("tmp = " + tmp);
    try {
        var primarydata = JSON.parse(tmp);
    } catch(err) {
        //enyo.application.mainApp.$.ErrorPopup.openAtCenter();
        enyo.application.mainApp.$.rightPane.selectViewByName("errorView");
        enyo.application.debuglog("ERROR: " + err);
        enyo.application.debuglog("tmp="+tmp);
        enyo.application.debuglog("html="+html);
        //enyo.application.mainApp.$.errorView.$.ErrorBox.content += "ERROR: " + err + " tmp="+tmp + " html="+html;
        //enyo.application.mainApp.$.errorView.render();
        return;
    }

    var index = 0;
    var counter = 0;
    var tempcontacts = new Array();
    for(var id in primarydata.contacts)
    {
        counter++;
        if(primarydata.contacts.hasOwnProperty(id) && primarydata.contacts[id].displayNumber)
        {
            tempcontacts[index] = primarydata.contacts[id];
            //primarydata.contacts[index] = primarydata.contacts[id];
            index++;
        }
    }
    primarydata.contacts = tempcontacts;
    primarydata.contacts.sort( function(i1, i2) { return i1.name.localeCompare(i2.name); });
    enyo.log("ParsePrimaryData: " + index + "/" + counter + " contacts with displayNumber set");
    enyo.log("RankedContacts: " + primarydata.rankedContacts.length);
    index = 0;
    /*for(id in primarydata.phones)
    {
        if(primarydata.phones.hasOwnProperty(id))
        {
            primarydata.phones[index] = primarydata.phones[id];
            index++;
        }
    }*/

    return primarydata;
}

function pluralize(str, count)
{
    return (count != 1) ? str + "s" : str;
}<|endoftext|>


<commit_before>import React from 'react';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Paper from 'material-ui/Paper';
import PeopleOutlineIcon from 'material-ui/svg-icons/social/people-outline';
import PeopleIcon from 'material-ui/svg-icons/social/people';
import EventIcon from 'material-ui/svg-icons/action/event';
import PlaceIcon from 'material-ui/svg-icons/maps/place';
import DirectionIcon from 'material-ui/svg-icons/maps/directions';
import IconButton from 'material-ui/IconButton';
import Avatar from 'material-ui/Avatar';
import math from 'mathjs';

const getEtherIcon = () =>(
  <Avatar src="https://15254b2dcaab7f5478ab-24461f391e20b7336331d5789078af53.ssl.cf1.rackcdn.com/ethereum.vanillaforums.com/favicon_85d47ba50743e3c3.ico" size={26} backgroundColor="white" />
)

const styles = {
  paperLeft:{
    flex: 2,
    height: '100%',
    textAlign: 'left',
    padding: 10
  },
  list:{
    float:'right', color: 'grey', merginHight:1
  },
  innerDiv:{
    paddingTop:1, paddingBottom:1, paddingRight:1
  }
};

class ConferenceDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      etherscan_url:null
    };
  }

  componentDidMount(){
    // Initialize
    this.props.getDetail(model =>{
      this.setState(model);
    })
    this.props.eventEmitter.on('network', network => {
      this.setState({
        etherscan_url: network.etherscan_url
      });
    })

    // If the app failed to get detail from contract (meaning either connecting
    // to wrong network or the contract id does not match to the one deployed),
    // it will show instruction page.
    setTimeout(function(){
      if(typeof(this.state.name) == 'undefined'){
        this.props.eventEmitter.emit('instruction');
      }
    }.bind(this), 1500)

    // Listen to watcher event.
    this.props.eventEmitter.on('change', model => {
      this.setState(model);
    });
    this.serverRequest = $.get('https://www.cryptocompare.com/api/data/price?fsym=ETH&tsyms=GBP', function (result) {
      this.setState({
        rate: result.Data[0].Price
      });
    }.bind(this));
  }

  toEther(value){
    if(value){
      return math.round(this.props.web3.fromWei(value, "ether").toNumber(), 3).toString();
    }
  }

  toNumber(value){
    if(value) return value.toNumber();
  }

  getNameContent(name, contractAddress){
    if(name){
      if (this.state.etherscan_url) {
        return (

            {name} (<a target='_blank' href={ `${this.state.etherscan_url}/address/${contractAddress}` }>{contractAddress.slice(0,5)}...)

        )
      }else{
        return (

            {name} ({contractAddress.slice(0,5)}...)

        )
      }
    }else{
      return (

          The contract {contractAddress.slice(0,10)}... not available

      )
    }
  }

  getDateContent(name){
    if(name){
      var d = new Date();
      var curr_date = d.getDate();
      var curr_month = d.getMonth() + 1; //Months are zero based
      var curr_year = d.getFullYear();
      var date = `${curr_date}-${curr_month}-${curr_year}`

      return (
        {name}
      )
    }else{
      return (
        No info available
      )
    }
  }

  getDepositContent(deposit, rate){
    if(deposit){
      return (
        {this.toEther(deposit)} (£{rate})
      )
    }else{
      return (
        No info available
      )
    }
  }

  render() {
    let attendancyStatus;
    if (this.state.ended) {
      attendancyStatus =
Attended{this.toNumber(this.state.attended)}

    }else{
      attendancyStatus =
Going (spots left){this.toNumber(this.state.registered)}({this.toNumber(this.state.limitOfParticipants) - this.toNumber(this.state.registered)})

    }

    return (
      <Paper zDepth={1} style={styles.paperLeft}>

Event Info

        <List>
          <ListItem innerDivStyle={styles.innerDiv} insetChildren={true} disabled={true}
            primaryText={

Name{this.getNameContent(this.state.name, this.props.contract.address)}

            }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={<EventIcon />} disabled={true}
            primaryText={

Date{this.getDateContent(this.state.date)}

            }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={<PlaceIcon />} disabled={true}
            primaryText={

Location

                  {this.state.location_text}

            }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={<DirectionIcon />} disabled={true}
            primaryText={

Description

                  { this.state.description_text }

            }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={getEtherIcon()} disabled={true}
            primaryText={

Deposit{this.getDepositContent(this.state.deposit, this.state.rate)}

            }
          />
        <Divider />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={getEtherIcon()} disabled={true}
          primaryText={

Pot{this.toEther(this.state.totalBalance)}

          }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={<PeopleIcon />} disabled={true}
          primaryText={attendancyStatus}
          />
        </List>
      </Paper>
    );
  }
}

export default ConferenceDetail;
<commit_msg>Add dangerouslySetInnterHTML<commit_after>import React from 'react';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Paper from 'material-ui/Paper';
import PeopleOutlineIcon from 'material-ui/svg-icons/social/people-outline';
import PeopleIcon from 'material-ui/svg-icons/social/people';
import EventIcon from 'material-ui/svg-icons/action/event';
import PlaceIcon from 'material-ui/svg-icons/maps/place';
import DirectionIcon from 'material-ui/svg-icons/maps/directions';
import IconButton from 'material-ui/IconButton';
import Avatar from 'material-ui/Avatar';
import math from 'mathjs';

const getEtherIcon = () =>(
  <Avatar src="https://15254b2dcaab7f5478ab-24461f391e20b7336331d5789078af53.ssl.cf1.rackcdn.com/ethereum.vanillaforums.com/favicon_85d47ba50743e3c3.ico" size={26} backgroundColor="white" />
)

const styles = {
  paperLeft:{
    flex: 2,
    height: '100%',
    textAlign: 'left',
    padding: 10
  },
  list:{
    float:'right', color: 'grey', merginHight:1
  },
  innerDiv:{
    paddingTop:1, paddingBottom:1, paddingRight:1
  }
};

class ConferenceDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      etherscan_url:null
    };
  }

  componentDidMount(){
    // Initialize
    this.props.getDetail(model =>{
      this.setState(model);
    })
    this.props.eventEmitter.on('network', network => {
      this.setState({
        etherscan_url: network.etherscan_url
      });
    })

    // If the app failed to get detail from contract (meaning either connecting
    // to wrong network or the contract id does not match to the one deployed),
    // it will show instruction page.
    setTimeout(function(){
      if(typeof(this.state.name) == 'undefined'){
        this.props.eventEmitter.emit('instruction');
      }
    }.bind(this), 1500)

    // Listen to watcher event.
    this.props.eventEmitter.on('change', model => {
      this.setState(model);
    });
    this.serverRequest = $.get('https://www.cryptocompare.com/api/data/price?fsym=ETH&tsyms=GBP', function (result) {
      this.setState({
        rate: result.Data[0].Price
      });
    }.bind(this));
  }

  toEther(value){
    if(value){
      return math.round(this.props.web3.fromWei(value, "ether").toNumber(), 3).toString();
    }
  }

  toNumber(value){
    if(value) return value.toNumber();
  }

  getNameContent(name, contractAddress){
    if(name){
      if (this.state.etherscan_url) {
        return (

            {name} (<a target='_blank' href={ `${this.state.etherscan_url}/address/${contractAddress}` }>{contractAddress.slice(0,5)}...)

        )
      }else{
        return (

            {name} ({contractAddress.slice(0,5)}...)

        )
      }
    }else{
      return (

          The contract {contractAddress.slice(0,10)}... not available

      )
    }
  }

  getDateContent(name){
    if(name){
      var d = new Date();
      var curr_date = d.getDate();
      var curr_month = d.getMonth() + 1; //Months are zero based
      var curr_year = d.getFullYear();
      var date = `${curr_date}-${curr_month}-${curr_year}`

      return (
        {name}
      )
    }else{
      return (
        No info available
      )
    }
  }

  getDepositContent(deposit, rate){
    if(deposit){
      return (
        {this.toEther(deposit)} (£{rate})
      )
    }else{
      return (
        No info available
      )
    }
  }

  render() {
    let attendancyStatus;
    if (this.state.ended) {
      attendancyStatus =
Attended{this.toNumber(this.state.attended)}

    }else{
      attendancyStatus =
Going (spots left){this.toNumber(this.state.registered)}({this.toNumber(this.state.limitOfParticipants) - this.toNumber(this.state.registered)})

    }

    return (
      <Paper zDepth={1} style={styles.paperLeft}>

Event Info

        <List>
          <ListItem innerDivStyle={styles.innerDiv} insetChildren={true} disabled={true}
            primaryText={

Name{this.getNameContent(this.state.name, this.props.contract.address)}

            }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={<EventIcon />} disabled={true}
            primaryText={

Date{this.getDateContent(this.state.date)}

            }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={<PlaceIcon />} disabled={true}
            primaryText={

Location

                  {this.state.location_text}

            }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={<DirectionIcon />} disabled={true}
            primaryText={

Description

            }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={getEtherIcon()} disabled={true}
            primaryText={

Deposit{this.getDepositContent(this.state.deposit, this.state.rate)}

            }
          />
        <Divider />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={getEtherIcon()} disabled={true}
          primaryText={

Pot{this.toEther(this.state.totalBalance)}

          }
          />
          <ListItem innerDivStyle={styles.innerDiv} leftIcon={<PeopleIcon />} disabled={true}
          primaryText={attendancyStatus}
          />
        </List>
      </Paper>
    );
  }
}

export default ConferenceDetail;
<|endoftext|>


<commit_before>const {ipcRenderer, remote} = require("electron");

//get the 'section' DOM element that will hold all dynamically created <webview> tags
let webviewsContainer = document.querySelector("#webviewsContainer");
let promises = remote.require("./promises.js");

//add new <webview> tag in the main window
let createWebview = (opts = {}) => {
    let webview = document.createElement("webview");
    // set all css rules to hide the webview
    if (!opts.show) {
        webview.style.visibility = "hidden";
        webview.style.display = "inline-flex";
        webview.style.position = "absolute";
        webview.style.width = "0";
        webview.style.height = "0";
    }

    // add to main view
    webviewsContainer.appendChild(webview);

    return webview;
}

let removeWebview = (webview) => {
    webviewsContainer.removeChild(webview);
}

let load = (args, cb) => {

    //create and add new instance of webview
    let webview = createWebview({show: false});

    //make webview navigate to desired URL
    webview.setAttribute("src", args.url);

    webview.addEventListener("did-finish-load", function(event){
        //remove the event so it gets called just once
        event.target.removeEventListener(event.type, arguments.callee);

        // execute this line of javascript, which will fetch the whole html of the document,
        // and then it will send it to the specified callback
        const fetchHTML = function(){
            return webview.executeJavaScript("document.documentElement.outerHTML", false, function(html){
                removeWebview(webview);
                cb(html);
            });
        };

        // if "wait" configuration option has been set other than 0, then wait for this many milliseconds
        // before fetching the html of the page
        if(args.wait){
            setTimeout(fetchHTML, args.wait);
        }else{
            fetchHTML();
        }

    });

}

ipcRenderer.on("load", function(event, args, promiseID) {
    load(args, (html)=>{
        promises.get(promiseID).resolve(html);
        promises.remove(promiseID);
    });
});
<commit_msg>fix webview rendering issue caused by setting visibility: hidden<commit_after>const {ipcRenderer, remote} = require("electron");

//get the 'section' DOM element that will hold all dynamically created <webview> tags
let webviewsContainer = document.querySelector("#webviewsContainer");
let promises = remote.require("./promises.js");

//add new <webview> tag in the main window
let createWebview = (opts = {}) => {
    let webview = document.createElement("webview");
    // set all css rules to hide the webview
    if (!opts.show) {
        webview.style.display = "inline-flex";
        webview.style.position = "absolute";
        webview.style.width = "0";
        webview.style.height = "0";
    }

    // add to main view
    webviewsContainer.appendChild(webview);

    return webview;
}

let removeWebview = (webview) => {
    webviewsContainer.removeChild(webview);
}

let load = (args, cb) => {

    //create and add new instance of webview
    let webview = createWebview({show: false});

    //make webview navigate to desired URL
    webview.setAttribute("src", args.url);

    webview.addEventListener("did-finish-load", function(event){
        //remove the event so it gets called just once
        event.target.removeEventListener(event.type, arguments.callee);

        // execute this line of javascript, which will fetch the whole html of the document,
        // and then it will send it to the specified callback
        const fetchHTML = function(){
            return webview.executeJavaScript("document.documentElement.outerHTML", false, function(html){
                removeWebview(webview);
                cb(html);
            });
        };

        // if "wait" configuration option has been set other than 0, then wait for this many milliseconds
        // before fetching the html of the page
        if(args.wait){
            setTimeout(fetchHTML, args.wait);
        }else{
            fetchHTML();
        }

    });

}

ipcRenderer.on("load", function(event, args, promiseID) {
    load(args, (html)=>{
        promises.get(promiseID).resolve(html);
        promises.remove(promiseID);
    });
});
<|endoftext|>


<commit_before>/*
* File:        jquery.dataTables.columnFilter.js
* Version:     0.9.0
* Author:      Jovan Popovic
*
* Copyright 2011 Jovan Popovic, all rights reserved.
*
* This source file is free software, under either the GPL v2 license or a
* BSD style license, as supplied with this software.
*
* This source file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE.
*
* Parameters:
* @sPlaceHolder                 String      Place where inline filtering function should be place ("tfoot", "thead"). Default is "tfoot"
* @sRangeSeparator              String      Separatot that will be used when range values are sent to the server-side. Default value is "~".
* @iFilteringDelay              int         TODO: Delay that will be set between the filtering requests. Default is 250.
* @sRangeFormat                 string      Default format of the From ... to ... range inputs. Default is From {from} to {to}
* @aoColumns                    Array       Array of the filter settings that will be applied on the columns

http://www.datatables.net/plug-ins/filtering

*/
(function ($) {

    var asInitVals, i, label, th;

    var sTableId = "table";
    var sRangeFormat = "From {from} to {to}";
    //Array of the functions that will override sSearch_ parameters
    var afnSearch_ = new Array();
    var aiCustomSearch_Indexes = new Array();

    var oFunctionTimeout = null;

    function fnCreateInput(regex, smart, bIsNumber) {
        var sCSSClass = "text_filter";
        if (bIsNumber)
            sCSSClass = "number_filter";
        var input = $('<input type="text" class="search_init ' + sCSSClass + '" value="' + label + '"/>');
        th.html(input);
        if (bIsNumber)
            th.wrapInner('');
        else
            th.wrapInner('');
        asInitVals[i] = label;
        var index = i;

        if (bIsNumber && !oTable.fnSettings().oFeatures.bServerSide) {
            input.keyup(function () {
                /* Filter on the column all numbers that starts with the entered value */
                oTable.fnFilter('^' + this.value, index, true, false);
            });
        } else {
            input.keyup(function () {
                /* Filter on the column (the index) of this element */
                oTable.fnFilter(this.value, index, regex, smart);
            });
        }

        input.focus(function () {
            if ($(this).hasClass("search_init")) {
                $(this).removeClass("search_init");
                this.value = "";
            }
        });
        input.blur(function () {
            if (this.value == "") {
                $(this).addClass("search_init");
                this.value = asInitVals[index];
            }
        });
    }

    function fnCreateRangeInput() {

        th.html(_fnRangeLabelPart(0));
        var sFromId = sTableId + 'range_from_' + i;
        var from = $('<input type="text" class="number_range_filter" id="' + sFromId + '" rel="' + i + '"/>');
        th.append(from);
        th.append(_fnRangeLabelPart(1));
        var sToId = sTableId + 'range_to_' + i;
        var to = $('<input type="text" class="number_range_filter" id="' + sToId + '" rel="' + i + '"/>');
        th.append(to);
        th.append(_fnRangeLabelPart(2));
        th.wrapInner('');
        var index = i;
        aiCustomSearch_Indexes.push(i);

        //------------start range filtering function

        /* 	Custom filtering function which will filter data in column four between two values
        *	Author: 	Allan Jardine, Modified by Jovan Popovic
        */
        $.fn.dataTableExt.afnFiltering.push(
	        function (oSettings, aData, iDataIndex) {
	            var iMin = document.getElementById(sFromId).value * 1;
	            var iMax = document.getElementById(sToId).value * 1;
	            var iValue = aData[index] == "-" ? 0 : aData[index] * 1;
	            if (iMin == "" && iMax == "") {
	                return true;
	            }
	            else if (iMin == "" && iValue < iMax) {
	                return true;
	            }
	            else if (iMin < iValue && "" == iMax) {
	                return true;
	            }
	            else if (iMin < iValue && iValue < iMax) {
	                return true;
	            }
	            return false;
	        }
        );
        //------------end range filtering function

        $('#' + sFromId + ',#' + sToId, th).keyup(function () {

            var iMin = document.getElementById(sFromId).value * 1;
            var iMax = document.getElementById(sToId).value * 1;
            if (iMin != 0 && iMax != 0 && iMin > iMax)
                return;

            oTable.fnDraw();

        });

    }

    function fnCreateDateRangeInput() {

        th.html(_fnRangeLabelPart(0));
        var sFromId = sTableId + 'range_from_' + i;
        var from = $('<input type="text" class="date_range_filter" id="' + sFromId + '" rel="' + i + '"/>');
        from.datepicker();
        th.append(from);
        th.append(_fnRangeLabelPart(1));
        var sToId = sTableId + 'range_to_' + i;
        var to = $('<input type="text" class="date_range_filter" id="' + sToId + '" rel="' + i + '"/>');
        th.append(to);
        th.append(_fnRangeLabelPart(2));
        th.wrapInner('');
        to.datepicker();
        var index = i;
        aiCustomSearch_Indexes.push(i);

        //------------start date range filtering function

        $.fn.dataTableExt.afnFiltering.push(
	        function (oSettings, aData, iDataIndex) {
	            var dStartDate = from.datepicker("getDate");

	            var dEndDate = to.datepicker("getDate");

	            var dCellDate = $.datepicker.parseDate($.datepicker.regional[""].dateFormat, aData[index]);

	            if (dCellDate == null)
	                return false;

	            if (dStartDate == null && dEndDate == null) {
	                return true;
	            }
	            else if (dStartDate == null && dCellDate < dEndDate) {
	                return true;
	            }
	            else if (dStartDate < dCellDate && dEndDate == null) {
	                return true;
	            }
	            else if (dStartDate < dCellDate && dCellDate < dEndDate) {
	                return true;
	            }
	            return false;
	        }
        );
        //------------end date range filtering function

        $('#' + sFromId + ',#' + sToId, th).change(function () {
            oTable.fnDraw();
        });

    }

    function fnCreateSelect(aData) {
        var index = i;
        var r = '<select class="search_init select_filter"><option value="" class="search_init">' + label + '</option>', j, iLen = aData.length;

        for (j = 0; j < iLen; j++) {
            r += '<option value="' + aData[j] + '">' + aData[j] + '</option>';
        }
        var select = $(r + '</select>');
        th.html(select);
        th.wrapInner('');
        select.change(function () {
            //var val = $(this).val();
            if ($(this).val() != "") {
                $(this).removeClass("search_init");
            } else {
                $(this).addClass("search_init");
            }
            oTable.fnFilter($(this).val(), index);
        });
    }

    function _fnRangeLabelPart(iPlace){
        switch(iPlace){
        case 0:
            return sRangeFormat.substring(0, sRangeFormat.indexOf("{from}"));
        case 1:
            return sRangeFormat.substring(sRangeFormat.indexOf("{from}") + 6, sRangeFormat.indexOf("{to}"));
        default:
            return sRangeFormat.substring(sRangeFormat.indexOf("{to}") + 4);
	}
    }

    $.fn.columnFilter = function (options) {

        oTable = this;

        var defaults = {
            sPlaceHolder: "foot",
            sRangeSeparator: "~",
            iFilteringDelay: 500,
            aoColumns: null,
            sRangeFormat: "From {from} to {to}"

        };

        properties = $.extend(defaults, options);

        return this.each(function () {

            asInitVals = new Array();
            var sFilterRow = "tfoot tr";
            if (properties.sPlaceHolder == "head:after") {
                sFilterRow = "thead tr:last";
            } else if (properties.sPlaceHolder == "head:before") {
                var tr = $("thead tr:last").detach();
                tr.prependTo("thead");
                sFilterRow = "thead tr:first";
            }

            $(sFilterRow + " th", oTable).each(function (index) {
                i = index;
                var aoColumn = { type: "text",
                    bRegex: false,
                    bSmart: true
                };
                if (properties.aoColumns != null) {
                    if (properties.aoColumns.length < i || properties.aoColumns[i] == null)
                        return;
                    aoColumn = properties.aoColumns[i];
                }
                label = $(this).text(); //"Search by " + $(this).text();
                th = $($(this)[0]);
                if (aoColumn != null) {
                    if (aoColumn.sRangeFormat != null)
                        sRangeFormat = aoColumn.sRangeFormat;
                    else
                        sRangeFormat = properties.sRangeFormat
                    switch (aoColumn.type) {
                        case "number":
                            fnCreateInput(true, false, true);
                            break;
                        case "text":
                            bRegex = (aoColumn.bRegex == null ? false : aoColumn.bRegex);
                            bSmart = (aoColumn.bSmart == null ? false : aoColumn.bSmart);
                            fnCreateInput(bRegex, bSmart, false);
                            break;
                        case "select":
                            fnCreateSelect(aoColumn.values);
                            break;
                        case "number-range":
                            fnCreateRangeInput();
                            break;
                        case "date-range":
                            fnCreateDateRangeInput();

                            break;
                        default:
                            break;

                    }
                }
            });

            for (j = 0; j < aiCustomSearch_Indexes.length; j++) {
                var index = aiCustomSearch_Indexes[j];
                var fnSearch_ = function () {
                    return $("#range_from_" + index).val() + properties.sRangeSeparator + $("#range_to_" + index).val()
                }
                afnSearch_.push(fnSearch_);
            }

            if (oTable.fnSettings().oFeatures.bServerSide) {

                var fnServerDataOriginal = oTable.fnSettings().fnServerData;

                oTable.fnSettings().fnServerData = function (sSource, aoData, fnCallback) {

                    for (j = 0; j < aiCustomSearch_Indexes.length; j++) {
                        var index = aiCustomSearch_Indexes[j];

                        for (k = 0; k < aoData.length; k++) {
                            if (aoData[k].name == "sSearch_" + index)
                                aoData[k].value = afnSearch_[j]();
                        }
                    }
                    aoData.push({ "name": "sRangeSeparator", "value": properties.sRangeSeparator });

                    if (fnServerDataOriginal != null) {
                        fnServerDataOriginal(sSource, aoData, fnCallback);
                    }
                    else {
                        $.getJSON(sSource, aoData, function (json) {
                            fnCallback(json)
                        });
                    }

                    /*
                    if (fnServerDataOriginal != null) {
                    if (properties.iDelay != 0) {
                    if (oFunctionTimeout != null)
                    window.clearTimeout(oFunctionTimeout);
                    oFunctionTimeout = window.setTimeout(function () {
                    fnServerDataOriginal(sSource, aoData, fnCallback);
                    }, properties.iDelay);
                    } else {
                    fnServerDataOriginal(sSource, aoData, fnCallback);
                    }
                    }
                    else
                    $.getJSON(sSource, aoData, function (json) {
                    fnCallback(json)
                    });
                    */
                };

            }

        });

    };

})(jQuery);
<commit_msg>Delete jquery.dataTables.columnFilter.js<commit_after><|endoftext|>


<commit_before>function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var x = 0;

            for (var key in gamesData.games) {
                if (!gamesData.games.hasOwnProperty(key)) {
                    continue;
                }
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    $("#index").addClass("hidden");
    $("#creategame").removeClass("hidden");
}

function hideCreateGame() {
    "use strict";
    $("#creategame").addClass("hidden");
    $("#index").removeClass("hidden");
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game!
";

            gameToHtml += '

Add Player
<form id="AddPlayerForm">Name: <input type="text" id="newPlayer"> <input type="button" onclick="addPlayer(\'' + id + '\')" value="Submit"></form>'

            var nicknames = getNicknames();

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        gameData.votes[i].target = gameData.votes[i].target.toLowerCase();
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equafls one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                                if (key.toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name                                     // (if it's in the nicknames list)
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        for (var j = 0; j < players.length; j++) {
                            if (players[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name                                     // (if it's in the players list)
                                gameData.votes[i].target = players[j];
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = targets.length - 1; i >= 0; i--) {
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                        break;
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay = gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase()) {
                                if(voters.hasOwnProperty(targets[j]) || activeVoters.hasOwnProperty(targets[j])){
                                    continue;
                                }
                                // add a new key (property) to the object for every vote target during the current day
                                voters[targets[j]] = [];
                                activeVoters[targets[j]] = [];
                            }
                        }
                    }
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            var remainingVoters = activeVoters[targets[j]].slice(0);
                            for (var z = remainingVoters.length - 1; z >= 0; z--) {
                                if (remainingVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, remove every previous vote from the active votes
                                    remainingVoters.splice(z, 1);
                                }
                            }
                            var markedVoters = voters[targets[j]].slice(0);
                            for (var z = markedVoters.length - 1; z >= 0; z--) {
                                if (markedVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, mark every previous vote with the mark "!" (unvoted) in the general votes
                                    markedVoters[z] = "!" + markedVoters[z];
                                }
                            }
                            activeVoters[targets[j]] = remainingVoters;
                            voters[targets[j]] = markedVoters;
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[i].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    var activesList = activeVoters[targets[i]];
                    for (var j = 0; j < activesList.length; j++) {
                        for (var z = nonvoters.length - 1; z >= 0; z--) {
                            if (activesList[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    var mainVotersList = voters[targets[i]].slice(0);
                    for (var j = 0; j < mainVotersList.length; j++) {
                            if (mainVotersList[j].indexOf("!") != -1) {
                                var nameWithoutMark = mainVotersList[j].substring(1);
                                mainVotersList[j] = "<s>" + nameWithoutMark + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + mainVotersList.join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]].slice(0);
                    for (var j = 0; j < votersList.length; j++) {
                            if (votersList[j].indexOf("!") != -1) {
                                var nameWithoutMark = votersList[j].substring(1);
                                votersList[j] = "[s]" + nameWithoutMark + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + votersList.join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    $("#index").addClass("hidden");
    $("#gameview").removeClass("hidden");
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
    window.location.reload();
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    $("#gameview").addClass("hidden");
    $("#index").removeClass("hidden");
    window.location.hash = "";
}

function addPlayer(gameid) {
	"use strict";
	if (document.getElementById("newPlayer").value) {
		var player = {"game": gameid, "name": document.getElementById("newPlayer").value}
		$.post("/add-player", player);
		window.location.reload();
	}
}
requestData();<commit_msg>fixed the styling of the ad player button<commit_after>function requestData() {
    "use strict";
    var req = new XMLHttpRequest();
    req.open("GET", "/games", true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamesjson = req.responseText;
            var gamesData = JSON.parse(gamesjson);
            var gamesToHtml = "";
            var x = 0;

            for (var key in gamesData.games) {
                if (!gamesData.games.hasOwnProperty(key)) {
                    continue;
                }
                gamesToHtml += "
";
                var gameurl = "/#" + gamesData.games[x].id;
                var threadurl = gamesData.games[x].url;
                gamesToHtml +=  '' + gamesData.games[x].name + "	";
                gamesToHtml += '' + threadurl + "	";
                gamesToHtml += "" + '<button type="button" onclick="deleteGame(\'' + gamesData.games[x].id + '\');return false;" class="pure-button">Delete</button>' + "	";
                gamesToHtml += "
";
                x++;
            }

            document.getElementById("games").innerHTML = gamesToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    locationHashChanged();
}

function locationHashChanged() {
    "use strict";
    if (window.location.hash != "") {
        var id = "" + window.location.hash;
        id = id.slice(1, id.length);
        showGame(id);
    }
}

function showCreateGame() {
    "use strict";
    $("#index").addClass("hidden");
    $("#creategame").removeClass("hidden");
}

function hideCreateGame() {
    "use strict";
    $("#creategame").addClass("hidden");
    $("#index").removeClass("hidden");
    window.location.hash = "";
}

function showGame(id) {
    "use strict";
    var req = new XMLHttpRequest();
    var url = "/game/" + id;
    req.open("GET", url, true);
    req.setRequestHeader("accept", "application/json");

    req.onload = function() {
        if (req.status >= 200 && req.status < 400){
            var gamejson = req.responseText;
            var gameData = JSON.parse(gamejson);
            var gameToHtml = "";

            document.getElementById("gameheader").innerHTML = gameData.game.name;

            gameToHtml += '' + gameData.game.url + "

";

            var hosts = [];

            for (var i = 0; i < gameData.hosts.length; i++) {
                hosts.push(gameData.hosts[i]);
            }

            gameToHtml += "Hosts
" + hosts.join(', ');

            var players = [];

            for (var i = 0; i < gameData.players.length; i++) {
                players.push(gameData.players[i].name);
            }

            var playerLinks = [];

            for (var i = 0; i < gameData.players.length; i++) {
                playerLinks.push('' + gameData.players[i].name + '');
            }

            gameToHtml += "

Players
" + playerLinks.join(', ');

            gameToHtml += "
Click on a player to permanently remove him from the game!
";

            gameToHtml += '
Add Player
<form id="AddPlayerForm">Name: <input type="text" id="newPlayer"> <input type="button" class="pure-button" onclick="addPlayer(\'' + id + '\')" value="Submit"></form>'

            var nicknames = getNicknames();

            var currentDay = 0;

            if (gameData.votes.length > 0) {
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                var targets = [];

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        gameData.votes[i].target = gameData.votes[i].target.toLowerCase();
                        for (var key in nicknames) {
                            if (!nicknames.hasOwnProperty(key)) {
                                continue;
                            }
                            var nicknameslist = nicknames[key];
                            for (var j = 0; j < nicknameslist.length; j++) {
                                if (nicknameslist[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equafls one of the nicknames, then change the vote to target the "real" name
                                    gameData.votes[i].target = key;
                                }
                                if (key.toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                    // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name                                     // (if it's in the nicknames list)
                                    gameData.votes[i].target = key;
                                }
                            }
                        }
                        for (var j = 0; j < players.length; j++) {
                            if (players[j].toLowerCase() == gameData.votes[i].target.toLowerCase()) {
                                // if a vote target equals a name with the wrong capitalization, then change the vote to target the "real" name                                     // (if it's in the players list)
                                gameData.votes[i].target = players[j];
                            }
                        }
                        if (targets.indexOf(gameData.votes[i].target) == -1) {
                            // push every new unique vote target to the targets array
                            targets.push(gameData.votes[i].target);
                        }
                      }
                }

                for (var i = targets.length - 1; i >= 0; i--) {
                    if (targets[i] == "") {
                        // remove the null (unvote) target from the list of vote targets
                        targets.splice(i, 1);
                        break;
                    }
                }

                var voters = {}; // "voters" is a JavaScript object with targets as keys and their voters as values
                var activeVoters = {}; // "activeVoters" is a JavaScript object with targets as keys and ACTIVE (not unvoted) voters as values
                var nonvoters = players; // players who aren't voting for anyone at the current time

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay = gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase()) {
                                if(voters.hasOwnProperty(targets[j]) || activeVoters.hasOwnProperty(targets[j])){
                                    continue;
                                }
                                // add a new key (property) to the object for every vote target during the current day
                                voters[targets[j]] = [];
                                activeVoters[targets[j]] = [];
                            }
                        }
                    }
                }

                for (var i = 0; i < gameData.votes.length; i++) {
                    if (currentDay == gameData.votes[i].day) {
                        for (var j = 0; j < targets.length; j++) {
                            var remainingVoters = activeVoters[targets[j]].slice(0);
                            for (var z = remainingVoters.length - 1; z >= 0; z--) {
                                if (remainingVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, remove every previous vote from the active votes
                                    remainingVoters.splice(z, 1);
                                }
                            }
                            var markedVoters = voters[targets[j]].slice(0);
                            for (var z = markedVoters.length - 1; z >= 0; z--) {
                                if (markedVoters[z] == gameData.votes[i].voter) {
                                    // every time a new vote is given, mark every previous vote with the mark "!" (unvoted) in the general votes
                                    markedVoters[z] = "!" + markedVoters[z];
                                }
                            }
                            activeVoters[targets[j]] = remainingVoters;
                            voters[targets[j]] = markedVoters;
                            if (gameData.votes[i].target.toLowerCase() == targets[j].toLowerCase() && gameData.votes[i].target != "") {
                                // push every voter of the current day to the objects as a value of their vote target
                                voters[targets[j]].push(gameData.votes[i].voter);
                                activeVoters[targets[j]].push(gameData.votes[i].voter);
                            }
                        }
                    }
                }

                for (var i = 0; i < targets.length; i++) {
                    var activesList = activeVoters[targets[i]];
                    for (var j = 0; j < activesList.length; j++) {
                        for (var z = nonvoters.length - 1; z >= 0; z--) {
                            if (activesList[j] == nonvoters[z]) {
                                // remove every currently active voter from the "Not Voting" list
                                nonvoters.splice(z, 1);
                            }
                        }
                    }
                }

                gameToHtml += "

Day " + currentDay + " Votecount
";

                for (var i = 0; i < targets.length; i++) {
                    var mainVotersList = voters[targets[i]].slice(0);
                    for (var j = 0; j < mainVotersList.length; j++) {
                            if (mainVotersList[j].indexOf("!") != -1) {
                                var nameWithoutMark = mainVotersList[j].substring(1);
                                mainVotersList[j] = "<s>" + nameWithoutMark + "</s>";
                            }
                    }

                    gameToHtml += "
" + targets[i] + " (" + activeVoters[targets[i]].length + "): " + mainVotersList.join(', ');
            }

                gameToHtml += '

Not Voting (' + nonvoters.length + '): ' + nonvoters.join(', ');
        }

            var firstNewDayVote = false;
            currentDay = 0;

            for (var i = 0; i < gameData.votes.length; i++) {
                var post = gameData.votes[i].index;
                var page = Math.floor(post/20) + 1;
                var address = gameData.game.url + "?page=" + page + "#" + post;

                if (currentDay != gameData.votes[i].day) {
                    firstNewDayVote = true;
                    currentDay = gameData.votes[i].day;
                }
                if (firstNewDayVote === true) {
                    gameToHtml += "

Day " + gameData.votes[i].day + "
";
                    firstNewDayVote = false;
                }
                if (gameData.votes[i].target == "") {
                    gameToHtml += '
' + gameData.votes[i].voter + " unvoted";
                } else if (gameData.votes[i].target == null) {
                    gameToHtml += '
' + gameData.votes[i].voter + " gave an invalid vote!";
                } else {
                    gameToHtml += '
' + gameData.votes[i].voter +
                        " voted for " + gameData.votes[i].target + "";
                }
            }

            if (gameData.votes.length > 0) {
                gameToHtml += '

<textarea id="reply_area" cols=80 rows=25 name="bericht" style="font:10pt Arial; margin-bottom: 4px; width:732px">';
                currentDay = gameData.votes[gameData.votes.length - 1].day;

                gameToHtml += "[blue][b][u][big]Day " + currentDay + " Votecount[/big][/u][/b][/blue]\r\n\r\n";

                for (var i = 0; i < targets.length; i++) {
                    var votersList = voters[targets[i]].slice(0);
                    for (var j = 0; j < votersList.length; j++) {
                            if (votersList[j].indexOf("!") != -1) {
                                var nameWithoutMark = votersList[j].substring(1);
                                votersList[j] = "[s]" + nameWithoutMark + "[/s]";
                            }
                    }

                    gameToHtml += "[b]" + targets[i] + " (" + activeVoters[targets[i]].length + "):[/b] " + votersList.join(', ') + "\r\n";
            }

                gameToHtml += '\r\n' + '[b]Not Voting (' + nonvoters.length + '):[/b] ' + nonvoters.join(', ');
                gameToHtml += '</textarea>';
        }

            if (gameData.votes.length === 0) {
                gameToHtml += "
No votes have been extracted from the given thread yet (this may take more time or there may have been an error while reading the thread)
";
            }

            document.getElementById("gamedata").innerHTML = gameToHtml;
        } else {
            console.log("Error. Status code " + req.status);
        }
    };

    req.send(null);
    $("#index").addClass("hidden");
    $("#gameview").removeClass("hidden");
}

function deletePlayer(id) {
    "use strict";
    $.post("/delete-player", {id: id});
    window.location.reload();
}

function deleteGame(id) {
    "use strict";
    $.post("/delete-game", {id: id});
}

function hideGame() {
    "use strict";
    $("#gameview").addClass("hidden");
    $("#index").removeClass("hidden");
    window.location.hash = "";
}

function addPlayer(gameid) {
	"use strict";
	if (document.getElementById("newPlayer").value) {
		var player = {"game": gameid, "name": document.getElementById("newPlayer").value}
		$.post("/add-player", player);
		window.location.reload();
	}
}
requestData();<|endoftext|>


<commit_before>// Copyright 2011 Mark Cavage, Inc.  All rights reserved.

var assert = require('assert');
var util = require('util');

var Filter = require('./filter');

var Protocol = require('../protocol');

///--- API

function ExtensibleFilter(options) {
  if (typeof(options) === 'object') {
    if (options.rule && typeof(options.rule) !== 'string')
      throw new TypeError('options.rule must be a string');
    if (options.matchType && typeof(options.matchType) !== 'string')
      throw new TypeError('options.type must be a string');
    if (options.value && typeof(options.value) !== 'string')
      throw new TypeError('options.value (string) required');
  } else {
    options = {};
  }

  this.matchType = options.matchType || null;
  this.rule = options.rule || null;
  this.value = options.value || '';
  this.dnAttributes = options.dnAttributes || false;
  options.type = Protocol.FILTER_EXT;
  Filter.call(this, options);

  var self = this;
  this.__defineGetter__('json', function() {
    return {
      type: 'ExtensibleMatch',
      matchRule: self.rule,
      matchType: self.matchType,
      matchValue: self.value,
      dnAttributes: self.dnAttributes
    };
  });
  this.__defineGetter__('matchingRule', function() {
    return self.rule;
  });
  this.__defineGetter__('matchValue', function() {
    return self.value;
  });
}
util.inherits(ExtensibleFilter, Filter);
module.exports = ExtensibleFilter;

ExtensibleFilter.prototype.toString = function() {
  var str = '(';

  if (this.matchType)
    str += this.matchType;

  str += ':';

  if (this.dnAttributes)
    str += 'dn:';

  if (this.rule)
    str += this.rule + ':';

  return (str + '=' + this.value + ')');
};

/**
 * THIS IS A STUB!
 *
 * ldapjs does not support server side extensible matching. This class exists
 * only for the client to send them.
 *
 * @param {Object} target the target object.
 * @return {Boolean} false always.
 */
ExtensibleFilter.prototype.matches = function(target) {
  if (typeof(target) !== 'object')
    throw new TypeError('target (object) required');

  return false;
};

ExtensibleFilter.prototype.parse = function(ber) {
  throw new Error('ExtensibleFilter not supported');
};

ExtensibleFilter.prototype._toBer = function(ber) {
  assert.ok(ber);

  if (this.rule)
    ber.writeString(this.rule, 0x81);
  if (this.matchType)
    ber.writeString(this.matchType, 0x82);

  ber.writeString(this.value, 0x83);
  if (this.dnAttributes)
    ber.writeBoolean(this.dnAttributes, 0x84);

  return ber;
};
<commit_msg>Trivial server side extensible search filter support<commit_after>// Copyright 2011 Mark Cavage, Inc.  All rights reserved.

var assert = require('assert');
var util = require('util');

var Filter = require('./filter');

var Protocol = require('../protocol');

///--- API

function ExtensibleFilter(options) {
  if (typeof(options) === 'object') {
    if (options.rule && typeof(options.rule) !== 'string')
      throw new TypeError('options.rule must be a string');
    if (options.matchType && typeof(options.matchType) !== 'string')
      throw new TypeError('options.type must be a string');
    if (options.value && typeof(options.value) !== 'string')
      throw new TypeError('options.value (string) required');
  } else {
    options = {};
  }

  this.matchType = options.matchType || null;
  this.rule = options.rule || null;
  this.value = options.value || '';
  this.dnAttributes = options.dnAttributes || false;
  options.type = Protocol.FILTER_EXT;
  Filter.call(this, options);

  var self = this;
  this.__defineGetter__('json', function() {
    return {
      type: 'ExtensibleMatch',
      matchRule: self.rule,
      matchType: self.matchType,
      matchValue: self.value,
      dnAttributes: self.dnAttributes
    };
  });
  this.__defineGetter__('matchingRule', function() {
    return self.rule;
  });
  this.__defineGetter__('matchValue', function() {
    return self.value;
  });
}
util.inherits(ExtensibleFilter, Filter);
module.exports = ExtensibleFilter;

ExtensibleFilter.prototype.toString = function() {
  var str = '(';

  if (this.matchType)
    str += this.matchType;

  str += ':';

  if (this.dnAttributes)
    str += 'dn:';

  if (this.rule)
    str += this.rule + ':';

  return (str + '=' + this.value + ')');
};

/**
 * THIS IS A STUB!
 *
 * ldapjs does not support server side extensible matching. This class exists
 * only for the client to send them.
 *
 * @param {Object} target the target object.
 * @return {Boolean} false always.
 */
ExtensibleFilter.prototype.matches = function(target) {
  if (typeof(target) !== 'object')
    throw new TypeError('target (object) required');

  if (this.dnAttribute)
    throw new Error('ExtensibleMatch dnAttributes not supported');

  if (!this.value)
    return false;

  var self = this;
  if (this.matchType && target.hasOwnProperty(this.matchType)) {
    return Filter.multi_test(function(v) {
      if (self.rule === '2.5.13.2')
        return self.value.toLowerCase() === v.toLowerCase();

      return self.value === v;
    }, target[this.matchType]);
  }

  return false;
};

ExtensibleFilter.prototype.parse = function(ber) {
  var end = ber.offset + ber.length;
  while (ber.offset < end) {
    var tag = ber.peek();
    switch (tag) {
    case 0x81:
      this.rule = ber.readString(tag);
      break;
    case 0x82:
      this.matchType = ber.readString(tag);
      break;
    case 0x83:
      this.value = ber.readString(tag);
      break;
    case 0x84:
      this.dnAttributes = ber.readBoolean(tag);
      break;
    default:
      throw new Error('Invalid ext_match filter type: 0x' + tag.toString(16));
    }
  }

  return true;
};

ExtensibleFilter.prototype._toBer = function(ber) {
  assert.ok(ber);

  if (this.rule)
    ber.writeString(this.rule, 0x81);
  if (this.matchType)
    ber.writeString(this.matchType, 0x82);

  ber.writeString(this.value, 0x83);
  if (this.dnAttributes)
    ber.writeBoolean(this.dnAttributes, 0x84);

  return ber;
};
<|endoftext|>


<commit_before>import I18n from "i18n-js";
import {isEmpty} from "../utils/utils";

export const ROLES = {
    ADMIN: {icon: "fa fa-star", name: "admin", role: "ADMIN"},
    OWNER: {icon: "fa fa-universal-access", name: "owner", role: "OWNER"},
    MANAGER: {icon: "fa fa-black-tie", name: "manager", role: "MANAGER"},
    MEMBER: {icon: "fa fa-user", name: "member", role: "MEMBER"},
    SUPER_ADMIN: {name: "super_admin", role: "SUPER_ADMIN"},
    JOIN_REQUEST: {icon: "fa fa-envelope", name: "join_request", role: "JOIN_REQUEST"},
    INVITATION: {icon: "fa fa-clock-o", name: "invitation", role: "INVITATION"}
};

export function labelForRole(role) {
    return I18n.t(`icon_legend.${ROLES[role].name}`);
}

export function allowedToLeave(team, currentUser) {
    const isMember = team.memberships.find(membership => membership.urnPerson === currentUser.urn);
    const admins = team.memberships
        .filter(membership => (membership.role === ROLES.ADMIN.role || membership.role === ROLES.OWNER.role)
            && membership.urnPerson !== currentUser.urn);
    return admins.length > 0 && !isEmpty(isMember) ;
}

export function hasOneAdmin(team, currentUser) {
    const pendingAdminInvitations = (team.invitations || []).filter(invitation => (invitation.intendedRole === ROLES.ADMIN.role ||
        invitation.intendedRole === ROLES.OWNER.role) && !invitation.declined);
    const hasPendingAdminInvitations = pendingAdminInvitations.length > 0;
    const admins = team.memberships
        .filter(membership => (membership.role === ROLES.ADMIN.role || membership.role === ROLES.OWNER.role)
            && membership.urnPerson !== currentUser.urn);
    return admins.length === 0 && !hasPendingAdminInvitations;
}

export function currentUserRoleInTeam(team, currentUser) {
    if (currentUser.superAdminModus) {
        return "SUPER_ADMIN";
    }
    return team.memberships.filter(membership => membership.urnPerson === currentUser.urn)[0].role;
}

export function isOnlyAdmin(team, currentUser) {
    const admins = team.memberships.filter(membership => membership.role === ROLES.ADMIN.role || membership.role === ROLES.OWNER.role);
    const userRoleInTeam = currentUserRoleInTeam(team, currentUser);
    return admins.length === 1 && (userRoleInTeam === ROLES.ADMIN.role || userRoleInTeam === ROLES.OWNER.role);
}

export function iconForRole(role) {
    return ROLES[role].icon;
}
<commit_msg>Formatting<commit_after>import I18n from "i18n-js";
import {isEmpty} from "../utils/utils";

export const ROLES = {
    ADMIN: {icon: "fa fa-star", name: "admin", role: "ADMIN"},
    OWNER: {icon: "fa fa-universal-access", name: "owner", role: "OWNER"},
    MANAGER: {icon: "fa fa-black-tie", name: "manager", role: "MANAGER"},
    MEMBER: {icon: "fa fa-user", name: "member", role: "MEMBER"},
    SUPER_ADMIN: {name: "super_admin", role: "SUPER_ADMIN"},
    JOIN_REQUEST: {icon: "fa fa-envelope", name: "join_request", role: "JOIN_REQUEST"},
    INVITATION: {icon: "fa fa-clock-o", name: "invitation", role: "INVITATION"}
};

export function labelForRole(role) {
    return I18n.t(`icon_legend.${ROLES[role].name}`);
}

export function allowedToLeave(team, currentUser) {
    const isMember = team.memberships.find(membership => membership.urnPerson === currentUser.urn);
    const admins = team.memberships
        .filter(membership => (membership.role === ROLES.ADMIN.role || membership.role === ROLES.OWNER.role)
            && membership.urnPerson !== currentUser.urn);
    return admins.length > 0 && !isEmpty(isMember) ;
}
w
export function hasOneAdmin(team, currentUser) {
    const pendingAdminInvitations = (team.invitations || []).filter(invitation => (invitation.intendedRole === ROLES.ADMIN.role ||
        invitation.intendedRole === ROLES.OWNER.role) && !invitation.declined);
    const hasPendingAdminInvitations = pendingAdminInvitations.length > 0;
    const admins = team.memberships
        .filter(membership => (membership.role === ROLES.ADMIN.role || membership.role === ROLES.OWNER.role)
            && membership.urnPerson !== currentUser.urn);
    return admins.length === 0 && !hasPendingAdminInvitations;
}

export function currentUserRoleInTeam(team, currentUser) {
    if (currentUser.superAdminModus) {
        return "SUPER_ADMIN";
    }
    return team.memberships.filter(membership => membership.urnPerson === currentUser.urn)[0].role;
}

export function isOnlyAdmin(team, currentUser) {
    const admins = team.memberships.filter(membership => membership.role === ROLES.ADMIN.role || membership.role === ROLES.OWNER.role);
    const userRoleInTeam = currentUserRoleInTeam(team, currentUser);
    return admins.length === 1 && (userRoleInTeam === ROLES.ADMIN.role || userRoleInTeam === ROLES.OWNER.role);
}

export function iconForRole(role) {
    return ROLES[role].icon;
}
<|endoftext|>


<commit_before>const Boom = require('boom')
const Joi = require('joi')

const listUserRoute = {
    register: function (server, options, next) {
        server.route({
            method: 'GET',
            path: '/api/users',
            config: {
                auth: 'jwt',
                tags: ['api'],
                description: 'List Users',
                notes: 'List users',
                handler: function (request, reply) {
                    // Invoke a Seneca action using the request decoration
                    console.log(request.headers)
                    request.seneca.act({
                        src: 'main',
                        service: 'user',
                        cmd: 'list',
                    }, (err, result) => {

                        if (err) {
                            const error = err.toString()
                            return reply(Boom.internal(error))
                        }

                        return reply(result);
                    });
                },
                response: {
                    modify: true,
                    options: {
                        stripUnknown: true,
                    },
                    schema: Joi.array().items(Joi.object().keys({
                        _id: Joi.string().required(),
                        name: Joi.string().required(),
                        email: Joi.string().required(),
                    })),
                },
                validate: {
                    headers: Joi.object().keys({
                        authorization: Joi.string().optional(),
                    }).unknown(),
                }
            }

        });
        next();
    },
};

listUserRoute.register.attributes = {
    name: 'listUserRoute',
    version: '1.0.0'
};

module.exports = listUserRoute
<commit_msg>Removing console.log<commit_after>const Boom = require('boom')
const Joi = require('joi')

const listUserRoute = {
    register: function (server, options, next) {
        server.route({
            method: 'GET',
            path: '/api/users',
            config: {
                auth: 'jwt',
                tags: ['api'],
                description: 'List Users',
                notes: 'List users',
                handler: function (request, reply) {
                    // Invoke a Seneca action using the request decoration
                    request.seneca.act({
                        src: 'main',
                        service: 'user',
                        cmd: 'list',
                    }, (err, result) => {

                        if (err) {
                            const error = err.toString()
                            return reply(Boom.internal(error))
                        }

                        return reply(result);
                    });
                },
                response: {
                    modify: true,
                    options: {
                        stripUnknown: true,
                    },
                    schema: Joi.array().items(Joi.object().keys({
                        _id: Joi.string().required(),
                        name: Joi.string().required(),
                        email: Joi.string().required(),
                    })),
                },
                validate: {
                    headers: Joi.object().keys({
                        authorization: Joi.string().optional(),
                    }).unknown(),
                }
            }

        });
        next();
    },
};

listUserRoute.register.attributes = {
    name: 'listUserRoute',
    version: '1.0.0'
};

module.exports = listUserRoute
<|endoftext|>