<commit_before>// ===============================================================
// Global constants
// ===============================================================
var STORAGE = chrome.storage.local;
var OPTS_PREFIX = 'opts:';
var JOEQUERY_TWILIO_URL = 'http://twilio.joequery.me/sms';
var ENTER_KEYCODE = 13;
var TOURNEY_NAME = (function(){
    // Only applicable on challonge pages
    if(document.URL.search('challonge') == -1 )
        return '';
    else
        return document.querySelector('#title').textContent.trim();
})();
var NAMESPACE = TOURNEY_NAME + ':'
var DEFAULT_MESSAGE_TEMPLATE_OPTIONS = [
    {
        'label': 'Match starting now',
        'template': "{{player1}} vs {{player2}} is starting now."
    },
    {
        'label': 'Match up next',
        'template': "{{player1}} vs {{player2}} is next. Head to your station"
    },
    {
        'label': 'Match delayed',
        'template': "{{player1}} vs {{player2}} has been delayed."
    }
];

// ===============================================================
// JS Utilities
// ===============================================================
var arrays_are_equal = function(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false;
    if (a.length != b.length) return false;
    for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
    }
    return true;
};

var endswith = function(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
};

var normalize_url = function(url){
    var url_copy = url; // document.URL is mutable when passed in
    if(endswith(url_copy, '#'))
        url_copy = url_copy.substr(0, url_copy.length-1);

    if(!endswith(url_copy, '/'))
        url_copy += '/';

    return url_copy;
};

// ===============================================================
// DOM helper functions
// ===============================================================
var each_$ = function($elements, handler){
    Array.prototype.forEach.call($elements, handler);
};

var add_listener = function($elements, the_event, handler){
    each_$($elements, function($el, i){
        $el.addEventListener(the_event, handler);
    });

};

var find_children = function($elements, child_selector){
    var children = [];
    each_$($elements, function($el, i){
        var this_els_children = $el.querySelectorAll(child_selector);
        for(var i=0; i<this_els_children.length; i++)
            children.push(this_els_children[i]);
    });
    return children;
};

var get_parent = function($el, n){
    var $the_parent = $el;
    for(var i=0; i<n; i++){
        $the_parent = $the_parent.parentNode;
    }
    return $the_parent;
};

/*
 * handler takes the matched element as an argument. child_selector is a string.
 */
var dynamic_child_bind = function($the_parent, child_selector, the_event, handler){
    $the_parent.addEventListener(the_event, function(e){
        var $child_objs = $the_parent.querySelectorAll(child_selector);
        if(!$child_objs.length)
            return;

        var child_objs_arr = Array.prototype.slice.call($child_objs);
        if(child_objs_arr.indexOf(e.target) != -1){
            handler(e.target, e);
        }
    }, true);
};

/*
 * Only use this when dynamic_child_bind is not sufficient.
 */
var dynamic_global_bind = function($the_parent, selector, the_event, handler){
    var $body = document.querySelector('body');
    $body.addEventListener(the_event, function(e){
        var $child_objs = $the_parent.querySelectorAll(selector);
        if(!$child_objs.length)
            return;

        var child_objs_arr = Array.prototype.slice.call($child_objs);
        if(child_objs_arr.indexOf(e.target) != -1){
            handler(e.target, e);
        }
    }, true);
};

// ===============================================================
// Modal helpers
// ===============================================================

/*
 * This is idempodent, feel free to call multiple times.
 */
var init_modal_structure = function(){
    var $inner_wrap = document.querySelector('.inner-wrap');
    var modal_exists = !!$inner_wrap.querySelector('.modal');
    if(!modal_exists){
        var modal_html = ghetto_render_template('modal');
        $inner_wrap.insertAdjacentHTML('afterbegin', modal_html);
    }

    // Since we can't access the javascript to call the modal, we will rely on
    // the fact that bootstrap activates the modal when an element with
    // attribute data-toggle="modal" is clicked.
    var modal_trigger_exists = !!$inner_wrap.querySelector('#show_modal');
    if(!modal_trigger_exists){
        var span_html = "";
        $inner_wrap.insertAdjacentHTML('afterbegin', span_html);
    }
};

var display_modal = function(modal_html){
    init_modal_structure();
    var $inner_wrap = document.querySelector('.inner-wrap');
    var $trigger = $inner_wrap.querySelector('#show_modal');
    var $modal_div = document.querySelector('#challonge_tournaments_modal div');
    $modal_div.innerHTML = modal_html;
    $trigger.click();
};

var close_modal = function(){
    var $close_button = document.querySelector("a[data-dismiss=modal]");
    $close_button.click();
};

// ===============================================================
// AJAX helper functions
// ===============================================================
/*
 * This is syncronous to avoid callback hell.
 */
var get_request = function(url){
    var request = new XMLHttpRequest();
    request.open('GET', url, false);
    request.onload = function(){
        if (request.status == 200){
            return request;
        }
        else{
            return null;
        }
    };
    request.send();
    return request.onload();
};

// ===============================================================
// Template helper functions
// ===============================================================
var get_template = function(template_name){
    var template_path = "templates/partials/" + template_name + ".html"
    var template_url = chrome.extension.getURL(template_path);
    var resp = get_request(template_url);
    var raw_template = resp.responseText;
    return raw_template;
};

/*
 * Don't include the template/ path with the template_name or the extension.
 * Returns the html string
 */
var render_template = function(template_name, context){
    context = arguments.length == 2 ? context : {};
    var raw_template = get_template(template_name);
    var template_html = Mustache.to_html(raw_template, context);
    return template_html;
};

/*
 * Avoid using Mustache when possible since it seems to be slow. It's useful for
 * complex templates still. Only plain variables allowed in the template here.
 */
var ghetto_mustache = function(template, context){
    for (var c in context) {
        if (context.hasOwnProperty(c)) {
            // How to replace all in javascript
            template = template.split("{{" + c + "}}").join(context[c]);
        }
    }
    return template;
};

var ghetto_render_template = function(template_name, context){
    context = arguments.length == 2 ? context : {};
    var raw_template = get_template(template_name);
    var template_html = ghetto_mustache(raw_template, context);
    return template_html;
};

// ==================================================================
// Storage helpers
// ==================================================================
var set_storage = function(key, value, callback){
    var no_callback_provided = arguments.count == 2;
    if(no_callback_provided){
        callback = function(){};
    }

    // Only way to get variable names as an object key in js
    var q  = {};
    q[key] = value;
    STORAGE.set(q, callback);
};

/*
 * Provide a prefix so that the same username can be used in multiple
 * tournaments without assuming they are the same person.
 */
var namespaced_name = function(player){
    return NAMESPACE + player;
};

/*
 * You can delete the phone entry by passing the empty string to the phone.
 */
var set_player_phone = function(player_name, phone, callback){
    player_name = namespaced_name(player_name);

    var no_callback_provided = arguments.count == 2;
    if(no_callback_provided){
        callback = function(){};
    }

    var should_delete_entry = phone === '';
    if(should_delete_entry){
        STORAGE.remove(player_name, callback);
    }
    else{
        set_storage(player_name, phone, callback);
    }

};

var with_player_phones = function(player_names, callback){
    var namespaced_names = [];
    for(var i=0; i<player_names.length; i++){
        namespaced_names.push(namespaced_name(player_names[i]));
    }

    STORAGE.get(namespaced_names, function(data){
        // Don't force the user of this helper function to deal with the
        // namespacing.
        var normal_names = {};
        var name;

        for (var d in data) {
            if (data.hasOwnProperty(d)) {
                name = d.substr(NAMESPACE.length);
                normal_names[name] = data[d];
            }
        }
        callback(normal_names);
    });
};

// ==================================================================
// Text message helpers
// ==================================================================
var send_text_message = function(to_nums, msg_body, callback){
    var no_callback_provided = arguments.count == 2;
    if(no_callback_provided){
        callback = function(request){};
    }

    STORAGE.get(['ACCESS_TOKEN', 'GATEWAY_URL'], function(data){
        var access_token = data['ACCESS_TOKEN'];
        var gateway_url = data['GATEWAY_URL'] || JOEQUERY_TWILIO_URL;
        msg_body = TOURNEY_NAME + ': ' + msg_body;
        post_data = {
            'to': to_nums,
            'body': msg_body,
            'access_token': access_token
        }
        var request = new XMLHttpRequest();
        request.open('POST', gateway_url, true);
        request.onload = function(){
            callback(request);
        }
        request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        request.send(JSON.stringify(post_data));
    });
}

// ==================================================================
// Message template helpers
// ==================================================================
var with_custom_message_templates = function(callback){
    STORAGE.get(['MESSAGE_TEMPLATES'], function(data){
        var msg_templates_json = data['MESSAGE_TEMPLATES'] || '[]';
        var msg_templates_obj = JSON.parse(msg_templates_json);
        callback(msg_templates_obj);
    });
};

var with_message_templates = function(callback){
    with_custom_message_templates(function(templates){
        var the_templates;
        if(templates.length)
            the_templates = templates;
        else
            the_templates = DEFAULT_MESSAGE_TEMPLATE_OPTIONS;
        callback(the_templates);
    });
};

// ==================================================================
// Debug helpers
// ==================================================================
var storage_dump = function(){
    STORAGE.get(null, function(data){
        console.log(data);
        STORAGE.getBytesInUse(null, function(bytes){
            console.log("Bytes in use: " + bytes);
        });
    });
};
<commit_msg>Use chrome sync storage<commit_after>// ===============================================================
// Global constants
// ===============================================================
var STORAGE = chrome.storage.sync;
var OPTS_PREFIX = 'opts:';
var JOEQUERY_TWILIO_URL = 'http://twilio.joequery.me/sms';
var ENTER_KEYCODE = 13;
var TOURNEY_NAME = (function(){
    // Only applicable on challonge pages
    if(document.URL.search('challonge') == -1 )
        return '';
    else
        return document.querySelector('#title').textContent.trim();
})();
var NAMESPACE = TOURNEY_NAME + ':'
var DEFAULT_MESSAGE_TEMPLATE_OPTIONS = [
    {
        'label': 'Match starting now',
        'template': "{{player1}} vs {{player2}} is starting now."
    },
    {
        'label': 'Match up next',
        'template': "{{player1}} vs {{player2}} is next. Head to your station"
    },
    {
        'label': 'Match delayed',
        'template': "{{player1}} vs {{player2}} has been delayed."
    }
];

// ===============================================================
// JS Utilities
// ===============================================================
var arrays_are_equal = function(a, b) {
    if (a === b) return true;
    if (a == null || b == null) return false;
    if (a.length != b.length) return false;
    for (var i = 0; i < a.length; ++i) {
        if (a[i] !== b[i]) return false;
    }
    return true;
};

var endswith = function(str, suffix) {
        return str.indexOf(suffix, str.length - suffix.length) !== -1;
};

var normalize_url = function(url){
    var url_copy = url; // document.URL is mutable when passed in
    if(endswith(url_copy, '#'))
        url_copy = url_copy.substr(0, url_copy.length-1);

    if(!endswith(url_copy, '/'))
        url_copy += '/';

    return url_copy;
};

// ===============================================================
// DOM helper functions
// ===============================================================
var each_$ = function($elements, handler){
    Array.prototype.forEach.call($elements, handler);
};

var add_listener = function($elements, the_event, handler){
    each_$($elements, function($el, i){
        $el.addEventListener(the_event, handler);
    });

};

var find_children = function($elements, child_selector){
    var children = [];
    each_$($elements, function($el, i){
        var this_els_children = $el.querySelectorAll(child_selector);
        for(var i=0; i<this_els_children.length; i++)
            children.push(this_els_children[i]);
    });
    return children;
};

var get_parent = function($el, n){
    var $the_parent = $el;
    for(var i=0; i<n; i++){
        $the_parent = $the_parent.parentNode;
    }
    return $the_parent;
};

/*
 * handler takes the matched element as an argument. child_selector is a string.
 */
var dynamic_child_bind = function($the_parent, child_selector, the_event, handler){
    $the_parent.addEventListener(the_event, function(e){
        var $child_objs = $the_parent.querySelectorAll(child_selector);
        if(!$child_objs.length)
            return;

        var child_objs_arr = Array.prototype.slice.call($child_objs);
        if(child_objs_arr.indexOf(e.target) != -1){
            handler(e.target, e);
        }
    }, true);
};

/*
 * Only use this when dynamic_child_bind is not sufficient.
 */
var dynamic_global_bind = function($the_parent, selector, the_event, handler){
    var $body = document.querySelector('body');
    $body.addEventListener(the_event, function(e){
        var $child_objs = $the_parent.querySelectorAll(selector);
        if(!$child_objs.length)
            return;

        var child_objs_arr = Array.prototype.slice.call($child_objs);
        if(child_objs_arr.indexOf(e.target) != -1){
            handler(e.target, e);
        }
    }, true);
};

// ===============================================================
// Modal helpers
// ===============================================================

/*
 * This is idempodent, feel free to call multiple times.
 */
var init_modal_structure = function(){
    var $inner_wrap = document.querySelector('.inner-wrap');
    var modal_exists = !!$inner_wrap.querySelector('.modal');
    if(!modal_exists){
        var modal_html = ghetto_render_template('modal');
        $inner_wrap.insertAdjacentHTML('afterbegin', modal_html);
    }

    // Since we can't access the javascript to call the modal, we will rely on
    // the fact that bootstrap activates the modal when an element with
    // attribute data-toggle="modal" is clicked.
    var modal_trigger_exists = !!$inner_wrap.querySelector('#show_modal');
    if(!modal_trigger_exists){
        var span_html = "";
        $inner_wrap.insertAdjacentHTML('afterbegin', span_html);
    }
};

var display_modal = function(modal_html){
    init_modal_structure();
    var $inner_wrap = document.querySelector('.inner-wrap');
    var $trigger = $inner_wrap.querySelector('#show_modal');
    var $modal_div = document.querySelector('#challonge_tournaments_modal div');
    $modal_div.innerHTML = modal_html;
    $trigger.click();
};

var close_modal = function(){
    var $close_button = document.querySelector("a[data-dismiss=modal]");
    $close_button.click();
};

// ===============================================================
// AJAX helper functions
// ===============================================================
/*
 * This is syncronous to avoid callback hell.
 */
var get_request = function(url){
    var request = new XMLHttpRequest();
    request.open('GET', url, false);
    request.onload = function(){
        if (request.status == 200){
            return request;
        }
        else{
            return null;
        }
    };
    request.send();
    return request.onload();
};

// ===============================================================
// Template helper functions
// ===============================================================
var get_template = function(template_name){
    var template_path = "templates/partials/" + template_name + ".html"
    var template_url = chrome.extension.getURL(template_path);
    var resp = get_request(template_url);
    var raw_template = resp.responseText;
    return raw_template;
};

/*
 * Don't include the template/ path with the template_name or the extension.
 * Returns the html string
 */
var render_template = function(template_name, context){
    context = arguments.length == 2 ? context : {};
    var raw_template = get_template(template_name);
    var template_html = Mustache.to_html(raw_template, context);
    return template_html;
};

/*
 * Avoid using Mustache when possible since it seems to be slow. It's useful for
 * complex templates still. Only plain variables allowed in the template here.
 */
var ghetto_mustache = function(template, context){
    for (var c in context) {
        if (context.hasOwnProperty(c)) {
            // How to replace all in javascript
            template = template.split("{{" + c + "}}").join(context[c]);
        }
    }
    return template;
};

var ghetto_render_template = function(template_name, context){
    context = arguments.length == 2 ? context : {};
    var raw_template = get_template(template_name);
    var template_html = ghetto_mustache(raw_template, context);
    return template_html;
};

// ==================================================================
// Storage helpers
// ==================================================================
var set_storage = function(key, value, callback){
    var no_callback_provided = arguments.count == 2;
    if(no_callback_provided){
        callback = function(){};
    }

    // Only way to get variable names as an object key in js
    var q  = {};
    q[key] = value;
    STORAGE.set(q, callback);
};

/*
 * Provide a prefix so that the same username can be used in multiple
 * tournaments without assuming they are the same person.
 */
var namespaced_name = function(player){
    return NAMESPACE + player;
};

/*
 * You can delete the phone entry by passing the empty string to the phone.
 */
var set_player_phone = function(player_name, phone, callback){
    player_name = namespaced_name(player_name);

    var no_callback_provided = arguments.count == 2;
    if(no_callback_provided){
        callback = function(){};
    }

    var should_delete_entry = phone === '';
    if(should_delete_entry){
        STORAGE.remove(player_name, callback);
    }
    else{
        set_storage(player_name, phone, callback);
    }

};

var with_player_phones = function(player_names, callback){
    var namespaced_names = [];
    for(var i=0; i<player_names.length; i++){
        namespaced_names.push(namespaced_name(player_names[i]));
    }

    STORAGE.get(namespaced_names, function(data){
        // Don't force the user of this helper function to deal with the
        // namespacing.
        var normal_names = {};
        var name;

        for (var d in data) {
            if (data.hasOwnProperty(d)) {
                name = d.substr(NAMESPACE.length);
                normal_names[name] = data[d];
            }
        }
        callback(normal_names);
    });
};

// ==================================================================
// Text message helpers
// ==================================================================
var send_text_message = function(to_nums, msg_body, callback){
    var no_callback_provided = arguments.count == 2;
    if(no_callback_provided){
        callback = function(request){};
    }

    STORAGE.get(['ACCESS_TOKEN', 'GATEWAY_URL'], function(data){
        var access_token = data['ACCESS_TOKEN'];
        var gateway_url = data['GATEWAY_URL'] || JOEQUERY_TWILIO_URL;
        msg_body = TOURNEY_NAME + ': ' + msg_body;
        post_data = {
            'to': to_nums,
            'body': msg_body,
            'access_token': access_token
        }
        var request = new XMLHttpRequest();
        request.open('POST', gateway_url, true);
        request.onload = function(){
            callback(request);
        }
        request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        request.send(JSON.stringify(post_data));
    });
}

// ==================================================================
// Message template helpers
// ==================================================================
var with_custom_message_templates = function(callback){
    STORAGE.get(['MESSAGE_TEMPLATES'], function(data){
        var msg_templates_json = data['MESSAGE_TEMPLATES'] || '[]';
        var msg_templates_obj = JSON.parse(msg_templates_json);
        callback(msg_templates_obj);
    });
};

var with_message_templates = function(callback){
    with_custom_message_templates(function(templates){
        var the_templates;
        if(templates.length)
            the_templates = templates;
        else
            the_templates = DEFAULT_MESSAGE_TEMPLATE_OPTIONS;
        callback(the_templates);
    });
};

// ==================================================================
// Debug helpers
// ==================================================================
var storage_dump = function(){
    STORAGE.get(null, function(data){
        console.log(data);
        STORAGE.getBytesInUse(null, function(bytes){
            console.log("Bytes in use: " + bytes);
        });
    });
};
<|endoftext|>


<commit_before>/**
 * cbpAnimatedHeader.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var cbpAnimatedHeader = (function() {

	var docElem = document.documentElement,
		header = document.querySelector( '.navbar-fixed-top' ),
		didScroll = false,
		changeHeaderOn = 300;

	function init() {
		window.addEventListener( 'scroll', function( event ) {
			if( !didScroll ) {
				didScroll = true;
				setTimeout( scrollPage, 250 );
			}
		}, false );
	}

	function scrollPage() {
		var sy = scrollY();
		if ( sy >= changeHeaderOn ) {
			classie.add( header, 'navbar-shrink' );
		}
		else {
			classie.remove( header, 'navbar-shrink' );
		}
		didScroll = false;
	}

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	init();

})();
<commit_msg>Update cbpAnimatedHeader.js<commit_after>/**
 * cbpAnimatedHeader.js v1.0.0
 * http://www.codrops.com
 *
 * Licensed under the MIT license.
 * http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright 2013, Codrops
 * http://www.codrops.com
 */
var cbpAnimatedHeader = (function() {

	var docElem = document.documentElement,
		header = document.querySelector( '.navbar-fixed-top' ),
		didScroll = false,
		changeHeaderOn = 300;

	function init() {
		window.addEventListener( 'scroll', function( event ) {
			if( !didScroll ) {
				didScroll = true;
				setTimeout( scrollPage, 250 );
			}
		}, false );
	}

	function scrollPage() {
		var sy = scrollY();
		if ( sy >= changeHeaderOn ) {
			classie.add( header, 'navbar-shrink' );
		}
		else {
			classie.remove( header, 'navbar-shrink' );
		}
		didScroll = true;
	}

	function scrollY() {
		return window.pageYOffset || docElem.scrollTop;
	}

	init();

})();
<|endoftext|>


<commit_before>(function() {
    function debug(msg) {
	// Find the debug section
	var log = document.getElementById("debuglog");

	if(!log) {
	    log = document.createElement("div");
	    log.id = "debuglog";
	    log.innerHTML = "
Debug Log
";
	    document.body.appendChild(log);
	}

	var pre = document.createElement("pre");
	var text = document.createTextNode(msg);
	pre.appendChild(text);
	log.appendChild(pre);
    }

    var lwr = 'abcdefghijklmnopqrstuvwxyzåäö';
    var upr = lwr.toUpperCase();

    function isValid(parm,val) {
	if (parm == "") return true;
	for (i=0; i<parm.length; i++) {
	    if (val.indexOf(parm.charAt(i),0) == -1) return false;
	}
	return true;
    }
    function isAlpha(parm) {
	return isValid(parm,lwr+upr);
    }

    var images = {
	'a': 'a.jpg',
	'b': 'b.jpg',
	'c': 'c.jpg',
	'd': 'd.jpg',
	'e': 'e.png',
	'f': 'f.jpg',
	'g': 'g.jpg',
	'h': 'h.jpg',
	'i': 'i.png',
	'j': 'j.jpg',
	'k': 'k.jpg',
	'l': 'l.jpg',
	'm': 'm.jpg',
	'n': 'n.jpg',
	'o': 'o.jpg',
	'p': 'p.png',
	'q': 'q.jpg',
	'r': 'r.jpg',
	's': 's.jpg',
	't': 't.jpg',
	'u': 'u.jpg',
	'v': 'v.png',
	'w': 'w.jpg',
	'x': 'x.png',
	'y': 'y.png',
	'z': 'z.jpg',
	'å': 'a_o.jpg',
	'ä': 'a_uml.png',
	'ö': 'o_uml.jpg',
    };

    function get_image(key) {
	key = key.toLowerCase();
	return images[key] || 'a.jpg';
    }

    function get_sound_name(key) {
	key = key.toLowerCase();
	if(key == 'ä')
	    return "a_uml";
	else if(key == "å")
	    return "a_o";
	else if(key == "ö")
	    return "o_uml";
	else
	    return key.toLowerCase();
    }

    function get_entry(key) {
	if(key == null || !isAlpha(key)) {
	    return null;
	}
	key = key.toUpperCase();
	entry = new Object();
	entry.title = key.toUpperCase() + " " + key.toLowerCase();
	entry.image = get_image(key);
	entry.sound = get_sound_name(key);
	return entry;
    }

    function update_image(image_name) {
	imgFldr = 'images/';
	$("#image").attr('src', imgFldr+image_name);
    }

    // Key should be one-character string
    function update_key(key) {
	entry = get_entry(key);
	if(entry == null) {
	    return;
	}
	$("#greeting").text("");
	$("#key_label").text(entry.title);
	update_image(entry.image);
	play_sound(entry.sound);
    }

    function generate_sound_name(name, extension) {
	return "audio/" + name + "." + extension;
    }

    var a = null;

    function play_sound(name) {
	if(a != null) {
     	    a.pause();
	} else {
	    a = new Audio();
	}
	if(a.canPlayType("audio/mp3")) {
	    name = generate_sound_name(name, "mp3");
	    a.src = name;
	    a.play();
	} else if(a.canPlayType("audio/ogg; codec=vorbis")) {
	    name = generate_sound_name(name, "ogg");
	    a.src = name;
	    a.play();
	} else {
	    debug("audio/mp3 not supported");
	}
    }

    // Register keypress listener
    $(function() {
	$(window).keypress(function(e) {
	    var key = e.which;
	    // debug(key);
	    str = String.fromCharCode(key);
	    update_key(str);
	});
    });
}());

<commit_msg>resize + hide image at beginning<commit_after>(function() {
    function debug(msg) {
	// Find the debug section
	var log = document.getElementById("debuglog");

	if(!log) {
	    log = document.createElement("div");
	    log.id = "debuglog";
	    log.innerHTML = "
Debug Log
";
	    document.body.appendChild(log);
	}

	var pre = document.createElement("pre");
	var text = document.createTextNode(msg);
	pre.appendChild(text);
	log.appendChild(pre);
    }

    var lwr = 'abcdefghijklmnopqrstuvwxyzåäö';
    var upr = lwr.toUpperCase();

    function isValid(parm,val) {
	if (parm == "") return true;
	for (i=0; i<parm.length; i++) {
	    if (val.indexOf(parm.charAt(i),0) == -1) return false;
	}
	return true;
    }
    function isAlpha(parm) {
	return isValid(parm,lwr+upr);
    }

    var images = {
	'a': 'a.jpg',
	'b': 'b.jpg',
	'c': 'c.jpg',
	'd': 'd.jpg',
	'e': 'e.png',
	'f': 'f.jpg',
	'g': 'g.jpg',
	'h': 'h.jpg',
	'i': 'i.png',
	'j': 'j.jpg',
	'k': 'k.jpg',
	'l': 'l.jpg',
	'm': 'm.jpg',
	'n': 'n.jpg',
	'o': 'o.jpg',
	'p': 'p.png',
	'q': 'q.jpg',
	'r': 'r.jpg',
	's': 's.jpg',
	't': 't.jpg',
	'u': 'u.jpg',
	'v': 'v.png',
	'w': 'w.jpg',
	'x': 'x.png',
	'y': 'y.png',
	'z': 'z.jpg',
	'å': 'a_o.jpg',
	'ä': 'a_uml.png',
	'ö': 'o_uml.jpg',
    };

    function get_image(key) {
	key = key.toLowerCase();
	return images[key] || 'a.jpg';
    }

    function get_sound_name(key) {
	key = key.toLowerCase();
	if(key == 'ä')
	    return "a_uml";
	else if(key == "å")
	    return "a_o";
	else if(key == "ö")
	    return "o_uml";
	else
	    return key.toLowerCase();
    }

    function get_entry(key) {
	if(key == null || !isAlpha(key)) {
	    return null;
	}
	key = key.toUpperCase();
	entry = new Object();
	entry.title = key.toUpperCase() + " " + key.toLowerCase();
	entry.image = get_image(key);
	entry.sound = get_sound_name(key);
	return entry;
    }

    function update_image(image_name) {
	imgFldr = 'images/';
	$("#image").attr('src', imgFldr+image_name);
	resizeImage();
    }

    function resizeImage() {
	var window_height = $(window).height();
	var window_width  = $(window).width();
	var image = document.images[0];
	var image_width   = image.width;
	var image_height  = image.height
	var height_ratio  = image_height / window_height
	var width_ratio   = image_width / window_width
	if (height_ratio > width_ratio)
	{
		image.style.width  = "auto"
		image.style.height = "100%"
	}
	else
	{
		image.style.width  = "100%"
		image.style.height = "auto"
	}
    }

    // Key should be one-character string
    function update_key(key) {
	entry = get_entry(key);
	if(entry == null) {
	    return;
	}
	$("#greeting").text("");
	$("#key_label").text(entry.title);
	update_image(entry.image);
	$("#image").show();
	play_sound(entry.sound);
    }

    function generate_sound_name(name, extension) {
	return "audio/" + name + "." + extension;
    }

    var a = null;

    function play_sound(name) {
	if(a != null) {
     	    a.pause();
	} else {
	    a = new Audio();
	}
	if(a.canPlayType("audio/mp3")) {
	    name = generate_sound_name(name, "mp3");
	    a.src = name;
	    a.play();
	} else if(a.canPlayType("audio/ogg; codec=vorbis")) {
	    name = generate_sound_name(name, "ogg");
	    a.src = name;
	    a.play();
	} else {
	    debug("audio/mp3 not supported");
	}
    }

    // Register keypress listener
    $(function() {
	$("#image").hide();
	$(window).keypress(function(e) {
	    var key = e.which;
	    // debug(key);
	    str = String.fromCharCode(key);
	    update_key(str);
	});
    });
}());

<|endoftext|>


<commit_before>var expect = require('chai').expect;
var snfe = require('../build/index').snfe;

describe('Basics', function() {

    it('should strip function name as expected', function() {

        var testCases = [{
            raw: 'var test1 = function b(a,b,c){};',
            expected: 'var test1 = function(a,b,c){};'
        }, {
            raw: 'var test1 = function anonymous(a,anonymous,c){};',
            expected: 'var test1 = function(a,anonymous,c){};'
        }, {
            raw: 'var test2 = [function c(a,b,c){}];',
            expected: 'var test2 = [function(a,b,c){}];'
        }, {
            raw: 'var test3 = (function d(c,d,e){return "hello";})();',
            expected: 'var test3 = (function(c,d,e){return "hello";})();'
        }, {
            raw: 'var test4 = { test: function e(d,e,f){} };',
            expected: 'var test4 = { test: function(d,e,f){} };'
        }, {
            raw: 'var test4 = { test: !function e(d,e,f){} };',
            expected: 'var test4 = { test: !function(d,e,f){} };'
        }];

        for (var c = 0; c < testCases.length; c++) {
            var raw = testCases[c].raw;
            var expected = testCases[c].expected;
            var result = snfe(raw);
            expect(result).to.be.equal(expected);
        }
    });

    it('should not strip function name because JS is case-sensitive', function() {
        var testCases = [{
            raw: 'var test1 = function B(a,b,c){};',
            expected: 'var test1 = function B(a,b,c){};'
        }, {
            raw: 'var test1 = function Anonymous(a,anonymous,c){};',
            expected: 'var test1 = function Anonymous(a,anonymous,c){};'
        }, {
            raw: 'var test2 = [function C(a,b,c){}];',
            expected: 'var test2 = [function C(a,b,c){}];'
        }, {
            raw: 'var test3 = (function D(c,d,e){return "hello";})();',
            expected: 'var test3 = (function D(c,d,e){return "hello";})();'
        }, {
            raw: 'var test4 = { test: function E(d,e,f){} };',
            expected: 'var test4 = { test: function E(d,e,f){} };'
        }, {
            raw: 'var test4 = { test: !function E(d,e,f){} };',
            expected: 'var test4 = { test: !function E(d,e,f){} };'
        }];
        for (var c = 0; c < testCases.length; c++) {
            var raw = testCases[c].raw;
            var expected = testCases[c].expected;
            var result = snfe(raw);
            expect(result).to.be.equal(expected);
        }
    });
    it('should throw expecetion when input is empty', function(){
        expect(function() {
            snfe('');
        }).to.throw('input was empty');
    });

    it('should throw expecetion when input is invalid', function(){
        expect(function() {
            snfe();
        }).to.throw('input must be a string');
    });

});

describe('Basics', function(){

});
<commit_msg>Update task name<commit_after>var expect = require('chai').expect;
var snfe = require('../build/index').snfe;

describe('Basics', function() {

    it('should strip function name as expected', function() {

        var testCases = [{
            raw: 'var test1 = function b(a,b,c){};',
            expected: 'var test1 = function(a,b,c){};'
        }, {
            raw: 'var test1 = function anonymous(a,anonymous,c){};',
            expected: 'var test1 = function(a,anonymous,c){};'
        }, {
            raw: 'var test2 = [function c(a,b,c){}];',
            expected: 'var test2 = [function(a,b,c){}];'
        }, {
            raw: 'var test3 = (function d(c,d,e){return "hello";})();',
            expected: 'var test3 = (function(c,d,e){return "hello";})();'
        }, {
            raw: 'var test4 = { test: function e(d,e,f){} };',
            expected: 'var test4 = { test: function(d,e,f){} };'
        }, {
            raw: 'var test4 = { test: !function e(d,e,f){} };',
            expected: 'var test4 = { test: !function(d,e,f){} };'
        }];

        for (var c = 0; c < testCases.length; c++) {
            var raw = testCases[c].raw;
            var expected = testCases[c].expected;
            var result = snfe(raw);
            expect(result).to.be.equal(expected);
        }
    });

    it('should not strip function name because JS is case-sensitive', function() {
        var testCases = [{
            raw: 'var test1 = function B(a,b,c){};',
            expected: 'var test1 = function B(a,b,c){};'
        }, {
            raw: 'var test1 = function Anonymous(a,anonymous,c){};',
            expected: 'var test1 = function Anonymous(a,anonymous,c){};'
        }, {
            raw: 'var test2 = [function C(a,b,c){}];',
            expected: 'var test2 = [function C(a,b,c){}];'
        }, {
            raw: 'var test3 = (function D(c,d,e){return "hello";})();',
            expected: 'var test3 = (function D(c,d,e){return "hello";})();'
        }, {
            raw: 'var test4 = { test: function E(d,e,f){} };',
            expected: 'var test4 = { test: function E(d,e,f){} };'
        }, {
            raw: 'var test4 = { test: !function E(d,e,f){} };',
            expected: 'var test4 = { test: !function E(d,e,f){} };'
        }];
        for (var c = 0; c < testCases.length; c++) {
            var raw = testCases[c].raw;
            var expected = testCases[c].expected;
            var result = snfe(raw);
            expect(result).to.be.equal(expected);
        }
    });
    it('should throw expecetion when input is empty', function(){
        expect(function() {
            snfe('');
        }).to.throw('input was empty');
    });

    it('should throw expecetion when input is invalid', function(){
        expect(function() {
            snfe();
        }).to.throw('input must be a string');
    });

});

describe('TODO', function(){});<|endoftext|>


<commit_before>exports.productionVersionId = "8e27a2602f0e";<commit_msg>Incrementing Production Version.<commit_after>exports.productionVersionId = "9c84d80efebb";<|endoftext|>


<commit_before>//https://stackoverflow.com/a/20548330/8480874

var g_SongPlaying = false;
var g_PauseEvent = new CustomEvent("Pause Song", { "detail": "Event to let any playing song know it needs to pause" });

function Sample(obj, title, desc, src_audio, src_cover) {

    // safety check for myself...
    if( ! $(obj).hasClass('audio_box') ) {
        alert('dumn ass u need to pass a .audio_box!!');
    }
    this.root = $(obj)[0];
    this.title = title;
    this.desc = desc;
    this.id = hash(src_audio);

    generateHTML(this, src_audio, src_cover);

    this.audio = $('#audio' + this.id);
    this.play_btn = $('#play_btn' + this.id);
    this.pause_btn = $('#pause_btn' + this.id);
    this.volume_btn = $('#volume_btn' + this.id);
    this.range = $('#range' + this.id);
    this.slider = $('#slider' + this.id);
    this.prog = $('#prog' + this.id);
    this.prog.tooltip_shown = false;
    this.prog_bar = $('#prog_bar' + this.id);
    this.time = $('#timestamp' + this.id);

    /* init members */
    this.audio[0].volume = 0.8;
    this.pause_btn.hide();
    this.range.hide();

    /* Member Functions */
    this.play = function() {
        document.dispatchEvent(g_PauseEvent);
        while(g_SongPlaying) { }
        $(this).toggle();
        $('#' + this.id.replace('play', 'pause')).toggle();
        g_SongPlaying = true;
        $('#' + this.id.replace('play_btn', 'audio')).trigger('play');
    }

    this.pause = function() {
        $('#' + this.id.replace('pause_btn', 'audio')).trigger('pause');
        g_SongPlaying = false;
        $(this).toggle();
        $('#' + this.id.replace('pause', 'play')).toggle();
    }

    this.stop = function() {
        this.audio.trigger('pause');
        this.audio.currentTime = 0;
        g_SongPlaying = false;
        this.play_btn.show();
        this.pause_btn.hide();
    }

    this.setTooltip = function(e) {
        var offset = this.offsetWidth;
        if( ! this.tooltip_shown ) {
            this.tooltip_shown = true;
            $(this).tooltip('show');
            $('.tooltip').css('margin-top', '-5px');
        }
        $('.tooltip').css('left', e.offsetX.toString() + 'px');
        $('.tooltip-inner').text( track(e,offset, this.id.replace('prog', '')) );
    }

    this.removeTooltip = function() {
        $(this).tooltip('hide');
        this.tooltip_shown = false;
    }

    this.seek = function(e) {
        //console.log("pb1 cliked!",e);
        var percent = e.offsetX / this.offsetWidth;
        //console.log(percent);
        var audio = $('#' + this.id.replace('prog', 'audio'));
        audio[0].currentTime = Math.floor(percent * audio[0].duration);
    }

    this.showVolumeButton = function(id) {
        $('#range' + id).hide();
        $('#volume_btn' + id).show();
    }

    this.showVolumeSlider = function() {
        $('#volume_btn' + this.id).hide();
        $('#range' + this.id).show();
    }

    /* event listeners */
    this.play_btn.click(this.play);
    this.pause_btn.click(this.pause);
    this.root.addEventListener(g_PauseEvent, this.pause);
    this.volume_btn.hover(this.showVolumeSlider(this.id));
    this.range.mouseleave(this.showVolumeButton(this.id));
    this.audio[0].addEventListener('ended', this.stop);
    this.audio[0].addEventListener('ontimeupdate', this.update);
    this.prog.click(this.seek);
    this.prog.mousemove(this.setTooltip);
    this.prog.mouseleave(this.removeTooltip);

    // utility functions
    function hash(str) {
        var hash = 0, i, chr;
        if (str.length === 0) return hash;
        for (i = 0; i < str.length; i++) {
            chr   = str.charCodeAt(i);
            hash  = ((hash << 5) - hash) + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    }

    function generateHTML(obj, src_audio, src_cover) {
        obj.root.innerHTML += '

';
        obj.root.innerHTML += '

' + obj.title + ' by N.Gattuso

' + obj.desc + '

<input id="slider' + obj.id + '" class="range-slider__range" type="range" value="80" min="0" max="100" step="5" for="#s2">0

0:00

<audio id="audio' + obj.id + '" src="' + src_audio + '" preload="metadata"  ontimeupdate="update(' + obj.id + ');"></audio>

';
    }

    function track(e, offset, id) {
        var percent = e.offsetX / offset;
        var audio = $('#audio' + id);
        var time = percent * audio[0].duration;
        mins = Math.floor(time/60,10),
        secs = Math.floor(time - mins*60);
        var text = '' + mins.toString() + ':';
        text += secs > 9 ? secs.toString() : '0' + secs.toString();
        //console.log(text);

        return text;
    }
}

function update(id) {
    //console.log('timeupdate');
    $('#prog_bar' + id.toString()).css('width', (($('#audio' + id.toString())[0].currentTime / $('#audio' + id.toString())[0].duration)*100) + '%').attr('aria-valuenow', ($('#audio' + id.toString())[0].currentTime / $('#audio' + id.toString())[0].duration)*100);

    var rem = parseInt($('#audio' + id.toString())[0].duration - $('#audio' + id.toString())[0].currentTime, 10),
    mins = Math.floor(rem/60,10),
    secs = rem - mins*60;

    $('#timestamp' + id.toString()).text('-' + mins + ':' + (secs > 9 ? secs : '0' + secs));
}

$(document).ready(function() {
    $('[data-toggle="tooltip"]').tooltip({
        delay: {
            show: 500,
            hide: 100
        }
    });
});
<commit_msg>show/hide volume slider now working<commit_after>//https://stackoverflow.com/a/20548330/8480874

var g_SongPlaying = false;
var g_PauseEvent = new CustomEvent("Pause Song", { "detail": "Event to let any playing song know it needs to pause" });

function Sample(obj, title, desc, src_audio, src_cover) {

    // safety check for myself...
    if( ! $(obj).hasClass('audio_box') ) {
        alert('dumn ass u need to pass a .audio_box!!');
    }
    this.root = $(obj)[0];
    this.title = title;
    this.desc = desc;
    this.id = hash(src_audio);

    generateHTML(this, src_audio, src_cover);

    this.audio = $('#audio' + this.id);
    this.play_btn = $('#play_btn' + this.id);
    this.pause_btn = $('#pause_btn' + this.id);
    this.volume_btn = $('#volume_btn' + this.id);
    this.range = $('#range' + this.id);
    this.slider = $('#slider' + this.id);
    this.prog = $('#prog' + this.id);
    this.prog.tooltip_shown = false;
    this.prog_bar = $('#prog_bar' + this.id);
    this.time = $('#timestamp' + this.id);

    /* init members */
    this.audio[0].volume = 0.8;
    this.pause_btn.hide();
    this.range.hide();

    /* Member Functions */
    this.play = function() {
        document.dispatchEvent(g_PauseEvent);
        while(g_SongPlaying) { }
        $(this).toggle();
        $('#' + this.id.replace('play', 'pause')).toggle();
        g_SongPlaying = true;
        $('#' + this.id.replace('play_btn', 'audio')).trigger('play');
    }

    this.pause = function() {
        $('#' + this.id.replace('pause_btn', 'audio')).trigger('pause');
        g_SongPlaying = false;
        $(this).toggle();
        $('#' + this.id.replace('pause', 'play')).toggle();
    }

    this.stop = function() {
        this.audio.trigger('pause');
        this.audio.currentTime = 0;
        g_SongPlaying = false;
        this.play_btn.show();
        this.pause_btn.hide();
    }

    this.setTooltip = function(e) {
        var offset = this.offsetWidth;
        if( ! this.tooltip_shown ) {
            this.tooltip_shown = true;
            $(this).tooltip('show');
            $('.tooltip').css('margin-top', '-5px');
        }
        $('.tooltip').css('left', e.offsetX.toString() + 'px');
        $('.tooltip-inner').text( track(e,offset, this.id.replace('prog', '')) );
    }

    this.removeTooltip = function() {
        $(this).tooltip('hide');
        this.tooltip_shown = false;
    }

    this.seek = function(e) {
        //console.log("pb1 cliked!",e);
        var percent = e.offsetX / this.offsetWidth;
        //console.log(percent);
        var audio = $('#' + this.id.replace('prog', 'audio'));
        audio[0].currentTime = Math.floor(percent * audio[0].duration);
    }

    this.showVolumeButton = function() {
        var id = this.id.replace('range', '')
        $('#range' + id).hide();
        $('#volume_btn' + id).show();
    }

    this.showVolumeSlider = function() {
        var id = this.id.replace('volume_btn', '')
        $('#volume_btn' + id).hide();
        $('#range' + id).show();
    }

    /* event listeners */
    this.play_btn.click(this.play);
    this.pause_btn.click(this.pause);
    this.root.addEventListener(g_PauseEvent, this.pause);
    this.volume_btn.hover(this.showVolumeSlider);
    this.range.mouseleave(this.showVolumeButton);
    this.audio[0].addEventListener('ended', this.stop);
    this.prog.click(this.seek);
    this.prog.mousemove(this.setTooltip);
    this.prog.mouseleave(this.removeTooltip);

    // utility functions
    function hash(str) {
        var hash = 0, i, chr;
        if (str.length === 0) return hash;
        for (i = 0; i < str.length; i++) {
            chr   = str.charCodeAt(i);
            hash  = ((hash << 5) - hash) + chr;
            hash |= 0; // Convert to 32bit integer
        }
        return hash;
    }

    function generateHTML(obj, src_audio, src_cover) {
        obj.root.innerHTML += '

';
        obj.root.innerHTML += '

' + obj.title + ' by N.Gattuso

' + obj.desc + '

<input id="slider' + obj.id + '" class="range-slider__range" type="range" value="80" min="0" max="100" step="5" for="#s2">0

0:00

<audio id="audio' + obj.id + '" src="' + src_audio + '" preload="metadata"  ontimeupdate="update(' + obj.id + ');"></audio>

';
    }

    function track(e, offset, id) {
        var percent = e.offsetX / offset;
        var audio = $('#audio' + id);
        var time = percent * audio[0].duration;
        mins = Math.floor(time/60,10),
        secs = Math.floor(time - mins*60);
        var text = '' + mins.toString() + ':';
        text += secs > 9 ? secs.toString() : '0' + secs.toString();
        //console.log(text);

        return text;
    }
}

function update(id) {
    //console.log('timeupdate');
    $('#prog_bar' + id.toString()).css('width', (($('#audio' + id.toString())[0].currentTime / $('#audio' + id.toString())[0].duration)*100) + '%').attr('aria-valuenow', ($('#audio' + id.toString())[0].currentTime / $('#audio' + id.toString())[0].duration)*100);

    var rem = parseInt($('#audio' + id.toString())[0].duration - $('#audio' + id.toString())[0].currentTime, 10),
    mins = Math.floor(rem/60,10),
    secs = rem - mins*60;

    $('#timestamp' + id.toString()).text('-' + mins + ':' + (secs > 9 ? secs : '0' + secs));
}

$(document).ready(function() {
    $('[data-toggle="tooltip"]').tooltip({
        delay: {
            show: 500,
            hide: 100
        }
    });
});
<|endoftext|>


<commit_before>// An UploadDocument is an in-progress file upload, currently waiting in the queue.
dc.model.UploadDocument = Backbone.Model.extend({

  FILE_EXTENSION_MATCHER : /\.([^.]+)$/,

  MAX_FILE_SIZE : 209715200, // 200 Megabytes

  // When creating an UploadDocument, we pull off some properties that
  // are on the file object, and attach them as attributes.
  set : function(attrs) {
    var file = attrs.file;
    if (file) {
      delete attrs.file;
      var fileName    = file.fileName || file.name;
      fileName        = fileName.match(/[^\/\\]+$/)[0]; // C:\fakepath\yatta yatta.pdf => yatta yatta.pdf
      attrs.title     = dc.inflector.titleize(fileName.replace(this.FILE_EXTENSION_MATCHER, ''));
      var extMatch    = fileName.match(this.FILE_EXTENSION_MATCHER);
      attrs.extension = extMatch && extMatch[1];
      attrs.size      = file.fileSize || null;
    }
    Backbone.Model.prototype.set.call(this, attrs);
  },

  overSizeLimit : function() {
    return this.get('size') >= this.MAX_FILE_SIZE;
  }

});

// The set of UploadDocuments is ordered by the position in which they were added.
dc.model.UploadDocumentSet = Backbone.Collection.extend({

  model : dc.model.UploadDocument,

  comparator : function(model) {
    return model.get('position');
  }

});

window.UploadDocuments = new dc.model.UploadDocumentSet();<commit_msg>UploadDocument should try file.size if file.fileSize is undefined.<commit_after>// An UploadDocument is an in-progress file upload, currently waiting in the queue.
dc.model.UploadDocument = Backbone.Model.extend({

  FILE_EXTENSION_MATCHER : /\.([^.]+)$/,

  MAX_FILE_SIZE : 209715200, // 200 Megabytes

  // When creating an UploadDocument, we pull off some properties that
  // are on the file object, and attach them as attributes.
  set : function(attrs) {
    var file = attrs.file;
    if (file) {
      delete attrs.file;
      var fileName    = file.fileName || file.name;
      fileName        = fileName.match(/[^\/\\]+$/)[0]; // C:\fakepath\yatta yatta.pdf => yatta yatta.pdf
      attrs.title     = dc.inflector.titleize(fileName.replace(this.FILE_EXTENSION_MATCHER, ''));
      var extMatch    = fileName.match(this.FILE_EXTENSION_MATCHER);
      attrs.extension = extMatch && extMatch[1];
      attrs.size      = file.fileSize || file.size || null;
    }
    Backbone.Model.prototype.set.call(this, attrs);
  },

  overSizeLimit : function() {
    return this.get('size') >= this.MAX_FILE_SIZE;
  }

});

// The set of UploadDocuments is ordered by the position in which they were added.
dc.model.UploadDocumentSet = Backbone.Collection.extend({

  model : dc.model.UploadDocument,

  comparator : function(model) {
    return model.get('position');
  }

});

window.UploadDocuments = new dc.model.UploadDocumentSet();<|endoftext|>


<commit_before>$(document).ready(function(){
  $.ajax({
    type: "GET",
    url: "/api/users",
    async: true,
    dataType: "json",
    success: function(users){
      for (var i=0; i<users.length; i++) {
        var option = document.createElement("option");
        option.text = users[i].name
        option.value = users[i].id
        var select = document.getElementById("userList");
        select.appendChild(option);
      }

    }
  });

  $(document).on('change', '#userList', function(){
    $.ajax({
      type: "GET",
      url: "/api/users/" + $('#userList').val(),
      async: true,
      //data: JSON.stringify({ id: $('#userList').val() }),
      dataType: "json",
      success: function(user){
        console.log(user);
      }
    });
  });
});
<commit_msg>removed ajax request to fetch user list. list is not passwed to view<commit_after>$(document).ready(function(){
  $(document).on('click', '.userList', function(){
    if($(this).attr('uid') != ''){
      $.ajax({
        type: "GET",
        url: "/api/users/" + $(this).attr('uid'),
        async: true,
        //data: JSON.stringify({ id: $('#userList').val() }),
        dataType: "json",
        success: function(user){
          user = user[0];
          $('input[name="id"]').val(user.id);
          $('input[name="name"]').val(user.name);
          $('input[name="email"]').val(user.email);
          if(user.admin){
            $('#adminTrue').parent().addClass('active');
          }else{
            $('#adminFalse').parent().addClass('active');
          }
          if(user.locked){
            $('#lockedTrue').parent().addClass('active');
          }else{
            $('#lockedFalse').parent().addClass('active');
          }
          $('#editUser').show();
        }
      });
    }else{
      $('#editUser').hide();
    }
  });

  $(document).on('click', '#updateUser', function(){
    var adminState, lockedState;
    if($('#adminTrue').parent().hasClass('active')){
      adminState = 1;
    }else{
      adminState = 0;
    }
    if($('#lockedTrue').parent().hasClass('active')){
      lockedState = 1;
    }else{
      lockedState = 0;
    }
    $.ajax({
      type: "PUT",
      url: "/api/users/update",
      async: true,
      data: {
        id: $('input[name="id"]').val(),
        name: $('input[name="name"]').val(),
        email: $('input[name="email"]').val(),
        admin: adminState,
        locked: lockedState
      },
      dataType: "json",
      success: function(result){
        if(result.Error){
          $('#errorBox').text(result.Message).slideDown();
          setTimeout(function(){$('#errorBox').slideUp()}, 10000);
        }else{
          $('#messageBox').text(result.Message).slideDown();
          setTimeout(function(){$('#messageBox').slideUp()}, 5000);
        }
      }
    });
  });
});
<|endoftext|>


<commit_before>// Shows the number of characters left when typing in a textarea
;(function( w ){
	var $ = w.jQuery;

	function CharacterCounter( el ) {
		var $el = $(el);

		if( $el.data("CharacterCounter") ){
			return;
		}
		$el.data( "CharacterCounter", this );

		this.$el = $el;
		this.$label = $(
			"[data-maxlength-count='" + this.$el.attr("id") + "']," +
				"[data-minlength-count='" + this.$el.attr("id") + "']"
		);

		this.characterCounter.call( el, this.$label );
	}

	CharacterCounter.prototype.characterCounter = function( $label ) {
		var $parent = $label.parent().addClass( "character-counter plural" ),
			max = parseFloat( $( this ).attr( "maxlength" ) ),
			min = parseFloat( $( this ).attr( "minlength" ) ),
			newval;

		if ( $label.length ){
			$( this ).unbind( ".charcount").bind( "input.charcount keyup.charcount", function(){
				newval = ( max || min ) - this.value.replace(/\r\n|\n/g, "__").length;
				$label.html( "" + newval );
				var add = [];
				var remove = [ "min max limit" ];
				if( newval !== 1 ) {
					remove.push( "singular" );
					add.push( "plural" );
				} else {
					add.push( "singular" );
					remove.push( "plural" );
				}
				var hitMax = max && newval === 0;
				var hitMin = min && newval <= 0;
				if( hitMax || hitMin ){
					add.push( "limit " + ( hitMax ? "max" : "min" ) );
					$label.html( "0" );
				}
				$parent.removeClass( remove.join( " " ) ).addClass( add.join( " " ) );
			});
		}
	};

	CharacterCounter.selectors = [
		"textarea[maxlength]",
		"textarea[minlength]"
	];

	$( w.document ).bind( "enhance", function( e ) {
		//textarea max-length counter
		$( e.target ).find( CharacterCounter.selectors.join(",") ).each(function(){
			new CharacterCounter( this );
		});
	});

}( typeof global !== "undefined" ? global : this ));
<commit_msg>refactor to testable setup<commit_after>// Shows the number of characters left when typing in a textarea
;(function( w ){
	var $ = w.jQuery;

	function CharacterCounter( el ) {
		var $el = $(el);

		if( $el.data("CharacterCounter") ){
			return;
		}
		$el.data( "CharacterCounter", this );

		var self = this;

		this.$el = $el;
		this.$label = $(
			"[data-maxlength-count='" + this.$el.attr("id") + "']," +
				"[data-minlength-count='" + this.$el.attr("id") + "']"
		);

		this.$parent = this.$label.parent().addClass( "character-counter plural" );
		this.max = parseFloat( this.$el.attr( "maxlength" ), 10 );
		this.min = parseFloat( this.$el.attr( "minlength" ), 10 );

		if ( this.$label.length ){
			this.$el
				.unbind( ".charcount")
				.bind( "input.charcount keyup.charcount", function(){
					self.characterCount();
				});
		}
	}

	// TODO duplication with maxlength input
	CharacterCounter.prototype.valueLength = function(){
		return this.$el[0].value.replace(/\r\n|\n/g, "__").length;
	};

	CharacterCounter.prototype.characterCount = function( $label ) {
		var newval = ( this.max || this.min ) - this.valueLength();

		this.$label.html( "" + newval );
		var add = [];
		var remove = [ "min max limit" ];
		if( newval !== 1 ) {
			remove.push( "singular" );
			add.push( "plural" );
		} else {
			add.push( "singular" );
			remove.push( "plural" );
		}

		var hitMax = this.max && newval === 0;
		var hitMin = this.min && newval <= 0;

		if( hitMax || hitMin ){
			add.push( "limit " + ( hitMax ? "max" : "min" ) );
			this.$label.html( "0" );
		}

		this.$parent.removeClass( remove.join( " " ) ).addClass( add.join( " " ) );
	};

	CharacterCounter.selectors = [
		"textarea[maxlength]",
		"textarea[minlength]"
	];

	$( w.document ).bind( "enhance", function( e ) {
		//textarea max-length counter
		$( e.target ).find( CharacterCounter.selectors.join(",") ).each(function(){
			new CharacterCounter( this );
		});
	});

}( typeof global !== "undefined" ? global : this ));
<|endoftext|>


<commit_before>// This is a pointer file, it tells the Firefox installer what config file to use.
// Edit the file specified below (in this case, "firefox-custom-settings.js" to customize your installation.

// Don't obscure config file name
pref("general.config.obscure_value", 0);
pref("general.config.filename", "firefox-custom-settings.js");<commit_msg>Delete local-settings.js<commit_after><|endoftext|>


<commit_before>var webpack = require('webpack');

// Base config
//
var webpackConfig = {
  entry: {
    'main': './src/js/main.js',
  },
  output: {
    path: __dirname + '/assets',
    filename: '[name].js'
  },
  module: {
    loaders: [
      {
        // https://www.npmjs.org/package/sass-loader
        //
        test: /\.scss$/,
        loader: "style!css!sass?outputStyle=expanded"
      }
    ],
  },
  plugins: []
};

// Extra plugin definitions

// Watch files that is not required with webpack
// https://github.com/webpack/webpack-dev-server/issues/34
//
function WatchExternalFilesPlugin() {}
WatchExternalFilesPlugin.prototype.apply = function(compiler) {
  compiler.plugin("after-compile", function(compilation, callback) {
    compilation.fileDependencies.push("index.html");
    callback();
  });
};

// Configuration based on environments
//
if(process.env.NODE_ENV === 'production'){
  webpackConfig.plugins.push(new webpack.optimize.UglifyJsPlugin({
    sourceMap: false
  }));
  webpackConfig.output.path = './assets'; // Bug?

}else{
  webpackConfig.plugins.push(new WatchExternalFilesPlugin());
  webpackConfig.debug = true;
  webpackConfig.devtool = '#source-map'
}

module.exports = webpackConfig;<commit_msg>Trivial<commit_after>var webpack = require('webpack');

// Base config
//
var webpackCfg = {
  entry: {
    'main': './src/js/main.js',
  },
  output: {
    path: __dirname + '/assets',
    filename: '[name].js'
  },
  module: {
    loaders: [
      {
        // https://www.npmjs.org/package/sass-loader
        //
        test: /\.scss$/,
        loader: "style!css!sass?outputStyle=expanded"
      }
    ],
  },
  plugins: []
};

// Extra plugin definitions

// Watch files that is not required with webpack
// https://github.com/webpack/webpack-dev-server/issues/34
//
function WatchExternalFilesPlugin() {}
WatchExternalFilesPlugin.prototype.apply = function(compiler) {
  compiler.plugin("after-compile", function(compilation, callback) {
    compilation.fileDependencies.push("index.html");
    callback();
  });
};

// Configuration based on environments
//
if(process.env.NODE_ENV === 'production'){
  webpackCfg.plugins.push(new webpack.optimize.UglifyJsPlugin({
    sourceMap: false
  }));
  webpackCfg.output.path = './assets'; // Bug?

}else{
  webpackCfg.plugins.push(new WatchExternalFilesPlugin());
  webpackCfg.debug = true;
  webpackCfg.devtool = '#source-map'
}

module.exports = webpackCfg;<|endoftext|>


<commit_before>"use strict";

function soma(numeroA, numeroB) {
    return numeroA + numeroB;
}
function subtrair(numeroA, numeroB) {
    return numeroA - numeroB;
}
function multiplicar(numeroA, numeroB) {
    return numeroA * numeroB;
}
function dividir(numeroA, numeroB) {
    return numeroA / numeroB;
}

function ativarBotao($botao,$metodo) {
    $botao.addEventListener("click", function () {
        var numeroA = Number(campoA.value),
            numeroB = Number(campoB.value);

        document.getElementById("resultado").innerHTML = $metodo(numeroA, numeroB);
    });

}

window.onload = function () {
    var botaoSOMAR = document.getElementById("somar"),
        botaoSUBTRAIR = document.getElementById("subtrair"),
        botaoMULTIPLICAR = document.getElementById("multiplicar"),
        botaoDIVIDIR = document.getElementById("dividir");

    var campoA = document.getElementById("campoA"),
        campoB = document.getElementById("campoB");

    ativarBotao(botaoSOMAR,soma);
    ativarBotao(botaoSUBTRAIR,subtrair);
    ativarBotao(botaoMULTIPLICAR,multiplicar);
    ativarBotao(botaoDIVIDIR,dividir);
};

<commit_msg>Demonstração de algumas validações deste scripts<commit_after>"use strict";

function soma(numeroA, numeroB) {
    return numeroA + numeroB;
}
function subtrair(numeroA, numeroB) {
    return numeroA - numeroB;
}
function multiplicar(numeroA, numeroB) {
    return numeroA * numeroB;
}
function dividir(numeroA, numeroB) {
    if(numeroA == 0 || numeroB == 0){
        return "Ops, ZERO ??";
    }
    return numeroA / numeroB;
}

function validarCampoNaN($campo){
    if(isNaN($campo.value)){
        $campo.value = "";
        $campo.placeholder = "Digite um numero";
        return 0;
    }else{
        return Number(campoB.value)
    };
}

function ativarBotao($botao,$metodo) {
    $botao.addEventListener("click", function () {
        var numeroA = validarCampoNaN(campoA),
            numeroB = validarCampoNaN(campoB);

        document.getElementById("resultado").innerHTML = $metodo(numeroA, numeroB);
    });

}

window.onload = function () {
    var botaoSOMAR = document.getElementById("somar"),
        botaoSUBTRAIR = document.getElementById("subtrair"),
        botaoMULTIPLICAR = document.getElementById("multiplicar"),
        botaoDIVIDIR = document.getElementById("dividir");

    var campoA = document.getElementById("campoA"),
        campoB = document.getElementById("campoB");

    ativarBotao(botaoSOMAR,soma);
    ativarBotao(botaoSUBTRAIR,subtrair);
    ativarBotao(botaoMULTIPLICAR,multiplicar);
    ativarBotao(botaoDIVIDIR,dividir);
};

<|endoftext|>


<commit_before>function(args) {
/*
/Users/fquraish/yazz/a.accdb
is_app(true)
component_type("VB")
display_name("ms_excel client control")
description("This will return the ms_excel control")
base_component_id("ms_excel_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "excel_file_path",
            name:   "ms_excel file path",
            design_time_only_events: true,
            //type:   "File",
            type:   "String"
        }
        ,
        {
            id:     "design_time_text",
            name:   "Design Time Text",
            type:   "String",
            default: "Microsoft Excel control",
            help:       `
Help text for
                            text property

`
        }

        ,
        {
            id:     "result",
            name:   "result",
            type:   "Array",
            default:    []
        }
        ,
        {
            id:         "runQuery",
            pre_snippet: `await `,
            snippet:    `runQuery()`,
            name:       "runQuery",
            type:       "Action",
            help:       `
Help text for
                            runQuery function

The SQL is store in the "sql" property

`
        }
        ,

        {
            id:     "getSheets",
            pre_snippet: `await `,
            name:   "getSheets()",
            snippet:    `getSheets()`,
            type:   "Action"
        }
        ,
        {
            id:     "getSheetDetails",
            name:   "getSheetDetails('SHEET_NAME')",
            type:   "Action"
        }
        ,
        {
            id:     "connect",
            pre_snippet: `await `,
            name:   "connect",
            type:   "Action"
        }
        ,
        {
            id:     "getWorkbook",
            pre_snippet: `await `,
            name:   "getWorkbook()",
            snippet:    `getWorkbook()`,
            type:   "Action"
        }
        ,

        {
            id:     "getColumns",
            name:   "getColumns",
            type:   "Action"
        }
        ,

        {
            id:         "design_mode_table",
            name:       "Design Table",
            type:       "String",
            default:    "",
            hidden:     true
        }
        ,
        {
            id:     "on_property_changed",
            name:   "on_property_changed",
            type:   "Event",
            help:       `
Help text for
                            click_event event

`,
            default: `
                if (property == "excel_file_path") {
                  await me.connect();
              }
`
        }
        ,
        {
            id:         "isExcelAvailable",
            name:       "Is Excel Available?",
            type:       "Select",
            default:    "False",
            values:     [
                            {display: "True",   value: "True"},
                            {display: "False",  value: "False"}
                        ]
                        ,
            design_time_only_events: true
        }
        ,

        {
            id:     "getSheet",
            name:   "getSheet",
            type:   "Action"
        }
        ,
        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,

        {
            id:     "sheet",
            name:   "Sheet",
            type:   "String"
        }
    ]
)//properties
logo_url("/driver_icons/excel.png")
*/
    Vue.component("ms_excel_control",{
        props: [  "meta",  "args",  "properties",  "name",  "refresh",  "design_mode"  ]
        ,
        template: `

                                                {{properties.design_time_text}}

                                                        Data source connection

                                                    Sheets

                                                    Cells

                                                Connection

                                                    Connected

                                                    Not Connected

                                                      {{thisSheetName}}

                                                Sheet "{{sheetName}}"

`
        ,
        data: function() {
            return {
                sheetDetails:              { },
                sheetNames:                [ ],
                sheetName:                  null,
                workbook:                   null,
                designDetailTab:           "connection"
            }
        }
        ,
        watch: {
          // This would be called anytime the value of the input changes
          refresh(newValue, oldValue) {
              if (isValidObject(this.args)) {
                  //this.design_time_text = this.args.design_time_text
              }
          }
        },
        mounted: async function() {
            registerComponent(this)

              await this.connect()
              await this.getWorkbook()
              await this.getSheets()
        }
        ,
        methods: {

            getSheets: async function() {
              let mm = this
              console.log("In getSheets")

              let result=null

              result = mm.workbook.SheetNames
             //debugger

             //alert("runQuery: " + JSON.stringify(result,null,2))
             //console.log(JSON.stringify(result,null,2))
             let retTables = []
             if (result) {
                 this.sheetNames   = []
                 this.sheetDetails = {}
                 //alert(JSON.stringify(result,null,2))
                 for (var i=0;i<result.length;i++) {
                     this.sheetNames.push(result[i])
                     this.sheetDetails[result[i]] = {name: result[i]}
                 }
             }
             //debugger
             return this.sheetNames
            }
            ,

            getSheetDetails: function(sheetName)
            {
                return this.sheetDetails[sheetName]
            }
            ,

            getColumns: async function() {
                console.log("In getColumns")

                if (this.design_mode) {
                    var result = await callFunction(
                                        {
                                            driver_name: "excel_server",
                                            method_name: "excel_sql"  }
                                            ,{
                                                path:            this.properties.excel_file_path,
                                                get_columns:     true,
                                                table:           this.args.design_mode_table
                                             })

                   //alert("runQuery: " + JSON.stringify(result,null,2))
                   console.log(JSON.stringify(result,null,2))
                   let retTables = []
                   if (result) {
                       this.args.columns = []
                       //alert(JSON.stringify(result,null,2))
                       for (var i=0;i<result.length;i++) {
                           this.args.columns.push(result[i])
                           retTables.push(result[i])

                       }
                   }

                   return retTables
                }
            }
            ,

            connect: async function() {
                let mm = this
                try {
                    var result = await callFunction(
                                        {
                                            driver_name: "excel_server",
                                            method_name: "excel_sql"  }
                                            ,{
                                                connect:         true,
                                                path:            this.properties.excel_file_path
                                             })
                    if (result.err) {
                        mm.properties.isExcelAvailable = "False"
                        return false
                    } else {
                        mm.properties.isExcelAvailable = "True"
                        return true
                    }
                } catch (catchErr) {
                    mm.properties.isExcelAvailable = "False"
                    return false
                }
            }
            ,

            getWorkbook: async function() {
                let mm = this

                if (mm.properties.isExcelAvailable == "True") {
                  try {
                      var result = await callFunction(
                                          {
                                              driver_name: "excel_server",
                                              method_name: "excel_sql"  }
                                              ,{
                                                  get_workbook:     true,
                                                  path:             this.properties.excel_file_path
                                               })
                      if (result.err) {
                          mm.properties.isExcelAvailable = "False"
                          return {error: true}
                      } else {
                          mm.properties.isExcelAvailable = "True"
                          mm.workbook = XLSX.utils.book_new();
                          let sheetNames = Object.keys(result.value)
                          for (let sheetIndex=0 ; sheetIndex < sheetNames.length; sheetIndex++) {
                              let sheetName = sheetNames[sheetIndex]
                              const ws = XLSX.utils.json_to_sheet(result.value[sheetName]);
                              XLSX.utils.book_append_sheet(mm.workbook, ws, sheetName);
                          }

                          return result.value
                      }
                  } catch (catchErr) {
                      mm.properties.isExcelAvailable = "False"
                      return {error: true}
                  }

                }
            }
            ,

            runQuery: async function() {
                if (!this.design_mode) {
                    var result = await callFunction(
                                        {
                                            driver_name: "excel_server",
                                            method_name: "excel_sql"  }
                                            ,{
                                                get_data:        true,
                                                table:           this.properties.select_table,
                                                path:            this.properties.excel_file_path
                                             })

                   //alert("runQuery: " + JSON.stringify(result,null,2))
                   console.log(JSON.stringify(result,null,2))
                   if (result) {

                        //select_columns
                        this.args.result  = []
                        for (let rownum=0; rownum<result.length; rownum++) {
                            let origrow = result[rownum]
                            let outputRow = {}
                            //debugger
                            if (this.properties.select_columns && (this.properties.select_columns.length  >  0)) {
                                for (let i = 0; i < this.properties.select_columns.length; i++) {
                                    let thisColName = this.properties.select_columns[i].name
                                    outputRow[  thisColName  ] = origrow[  thisColName  ]
                                  }
                            } else {
                                outputRow = origrow
                            }
                                this.args.result.push(  outputRow  )
                        }

                        return this.args.result
                   }

               }
                this.args.result = []
                this.changedFn()
                return {}
            }
            ,
            changedFn: function() {
                if (isValidObject(this.args)) {
                    //this.args.text = this.text

                }
            }
            ,

            getSheet: async function() {
                var result = await callFunction(
                                    {
                                        driver_name: "excel_server",
                                        method_name: "excel_sql"  }
                                        ,{
                                            get_data:        true,
                                            table:           this.properties.select_table,
                                            path:            this.properties.excel_file_path
                                         })

               //alert("runQuery: " + JSON.stringify(result,null,2))
               console.log(JSON.stringify(result,null,2))
               if (result) {

                    //select_columns
                    this.args.result  = result
                    return this.args.result
               }

                this.args.result = []
                this.changedFn()
                return {}
            }
            ,

            selectSheet(aSheet) {
              let mm = this
              debugger

            }

        }
    })
}
<commit_msg>Try to find tabular data tab added<commit_after>function(args) {
/*
/Users/fquraish/yazz/a.accdb
is_app(true)
component_type("VB")
display_name("ms_excel client control")
description("This will return the ms_excel control")
base_component_id("ms_excel_control")
load_once_from_file(true)
visibility("PRIVATE")
read_only(true)
properties(
    [
        {
            id:     "excel_file_path",
            name:   "ms_excel file path",
            design_time_only_events: true,
            //type:   "File",
            type:   "String"
        }
        ,
        {
            id:     "design_time_text",
            name:   "Design Time Text",
            type:   "String",
            default: "Microsoft Excel control",
            help:       `
Help text for
                            text property

`
        }

        ,
        {
            id:     "result",
            name:   "result",
            type:   "Array",
            default:    []
        }
        ,
        {
            id:         "runQuery",
            pre_snippet: `await `,
            snippet:    `runQuery()`,
            name:       "runQuery",
            type:       "Action",
            help:       `
Help text for
                            runQuery function

The SQL is store in the "sql" property

`
        }
        ,

        {
            id:     "getSheets",
            pre_snippet: `await `,
            name:   "getSheets()",
            snippet:    `getSheets()`,
            type:   "Action"
        }
        ,
        {
            id:     "getSheetDetails",
            name:   "getSheetDetails('SHEET_NAME')",
            type:   "Action"
        }
        ,
        {
            id:     "connect",
            pre_snippet: `await `,
            name:   "connect",
            type:   "Action"
        }
        ,
        {
            id:     "getWorkbook",
            pre_snippet: `await `,
            name:   "getWorkbook()",
            snippet:    `getWorkbook()`,
            type:   "Action"
        }
        ,

        {
            id:     "getColumns",
            name:   "getColumns",
            type:   "Action"
        }
        ,

        {
            id:         "design_mode_table",
            name:       "Design Table",
            type:       "String",
            default:    "",
            hidden:     true
        }
        ,
        {
            id:     "on_property_changed",
            name:   "on_property_changed",
            type:   "Event",
            help:       `
Help text for
                            click_event event

`,
            default: `
                if (property == "excel_file_path") {
                  await me.connect();
              }
`
        }
        ,
        {
            id:         "isExcelAvailable",
            name:       "Is Excel Available?",
            type:       "Select",
            default:    "False",
            values:     [
                            {display: "True",   value: "True"},
                            {display: "False",  value: "False"}
                        ]
                        ,
            design_time_only_events: true
        }
        ,

        {
            id:     "getSheet",
            name:   "getSheet",
            type:   "Action"
        }
        ,
        {
            id:         "has_details_ui",
            name:       "Has details UI?",
            type:       "Boolean",
            default:    true,
            hidden:     true
        }
        ,

        {
            id:     "sheet",
            name:   "Sheet",
            type:   "String"
        }
    ]
)//properties
logo_url("/driver_icons/excel.png")
*/
    Vue.component("ms_excel_control",{
        props: [  "meta",  "args",  "properties",  "name",  "refresh",  "design_mode"  ]
        ,
        template: `

                                                {{properties.design_time_text}}

                                                        Data source connection

                                                    Sheets

                                                    Find table data

                                                Connection

                                                    Connected

                                                    Not Connected

                                                      {{thisSheetName}}

                                                Sheet "{{sheetName}}"

`
        ,
        data: function() {
            return {
                sheetDetails:              { },
                sheetNames:                [ ],
                sheetName:                  null,
                workbook:                   null,
                designDetailTab:           "connection"
            }
        }
        ,
        watch: {
          // This would be called anytime the value of the input changes
          refresh(newValue, oldValue) {
              if (isValidObject(this.args)) {
                  //this.design_time_text = this.args.design_time_text
              }
          }
        },
        mounted: async function() {
            registerComponent(this)

              await this.connect()
              await this.getWorkbook()
              await this.getSheets()
        }
        ,
        methods: {

            getSheets: async function() {
              let mm = this
              console.log("In getSheets")

              let result=null

              result = mm.workbook.SheetNames
             //debugger

             //alert("runQuery: " + JSON.stringify(result,null,2))
             //console.log(JSON.stringify(result,null,2))
             let retTables = []
             if (result) {
                 this.sheetNames   = []
                 this.sheetDetails = {}
                 //alert(JSON.stringify(result,null,2))
                 for (var i=0;i<result.length;i++) {
                     this.sheetNames.push(result[i])
                     this.sheetDetails[result[i]] = {name: result[i]}
                 }
             }
             //debugger
             return this.sheetNames
            }
            ,

            getSheetDetails: function(sheetName)
            {
                return this.sheetDetails[sheetName]
            }
            ,

            getColumns: async function() {
                console.log("In getColumns")

                if (this.design_mode) {
                    var result = await callFunction(
                                        {
                                            driver_name: "excel_server",
                                            method_name: "excel_sql"  }
                                            ,{
                                                path:            this.properties.excel_file_path,
                                                get_columns:     true,
                                                table:           this.args.design_mode_table
                                             })

                   //alert("runQuery: " + JSON.stringify(result,null,2))
                   console.log(JSON.stringify(result,null,2))
                   let retTables = []
                   if (result) {
                       this.args.columns = []
                       //alert(JSON.stringify(result,null,2))
                       for (var i=0;i<result.length;i++) {
                           this.args.columns.push(result[i])
                           retTables.push(result[i])

                       }
                   }

                   return retTables
                }
            }
            ,

            connect: async function() {
                let mm = this
                try {
                    var result = await callFunction(
                                        {
                                            driver_name: "excel_server",
                                            method_name: "excel_sql"  }
                                            ,{
                                                connect:         true,
                                                path:            this.properties.excel_file_path
                                             })
                    if (result.err) {
                        mm.properties.isExcelAvailable = "False"
                        return false
                    } else {
                        mm.properties.isExcelAvailable = "True"
                        return true
                    }
                } catch (catchErr) {
                    mm.properties.isExcelAvailable = "False"
                    return false
                }
            }
            ,

            getWorkbook: async function() {
                let mm = this

                if (mm.properties.isExcelAvailable == "True") {
                  try {
                      var result = await callFunction(
                                          {
                                              driver_name: "excel_server",
                                              method_name: "excel_sql"  }
                                              ,{
                                                  get_workbook:     true,
                                                  path:             this.properties.excel_file_path
                                               })
                      if (result.err) {
                          mm.properties.isExcelAvailable = "False"
                          return {error: true}
                      } else {
                          mm.properties.isExcelAvailable = "True"
                          mm.workbook = XLSX.utils.book_new();
                          let sheetNames = Object.keys(result.value)
                          for (let sheetIndex=0 ; sheetIndex < sheetNames.length; sheetIndex++) {
                              let sheetName = sheetNames[sheetIndex]
                              const ws = XLSX.utils.json_to_sheet(result.value[sheetName]);
                              XLSX.utils.book_append_sheet(mm.workbook, ws, sheetName);
                          }

                          return result.value
                      }
                  } catch (catchErr) {
                      mm.properties.isExcelAvailable = "False"
                      return {error: true}
                  }

                }
            }
            ,

            runQuery: async function() {
                if (!this.design_mode) {
                    var result = await callFunction(
                                        {
                                            driver_name: "excel_server",
                                            method_name: "excel_sql"  }
                                            ,{
                                                get_data:        true,
                                                table:           this.properties.select_table,
                                                path:            this.properties.excel_file_path
                                             })

                   //alert("runQuery: " + JSON.stringify(result,null,2))
                   console.log(JSON.stringify(result,null,2))
                   if (result) {

                        //select_columns
                        this.args.result  = []
                        for (let rownum=0; rownum<result.length; rownum++) {
                            let origrow = result[rownum]
                            let outputRow = {}
                            //debugger
                            if (this.properties.select_columns && (this.properties.select_columns.length  >  0)) {
                                for (let i = 0; i < this.properties.select_columns.length; i++) {
                                    let thisColName = this.properties.select_columns[i].name
                                    outputRow[  thisColName  ] = origrow[  thisColName  ]
                                  }
                            } else {
                                outputRow = origrow
                            }
                                this.args.result.push(  outputRow  )
                        }

                        return this.args.result
                   }

               }
                this.args.result = []
                this.changedFn()
                return {}
            }
            ,
            changedFn: function() {
                if (isValidObject(this.args)) {
                    //this.args.text = this.text

                }
            }
            ,

            getSheet: async function() {
                var result = await callFunction(
                                    {
                                        driver_name: "excel_server",
                                        method_name: "excel_sql"  }
                                        ,{
                                            get_data:        true,
                                            table:           this.properties.select_table,
                                            path:            this.properties.excel_file_path
                                         })

               //alert("runQuery: " + JSON.stringify(result,null,2))
               console.log(JSON.stringify(result,null,2))
               if (result) {

                    //select_columns
                    this.args.result  = result
                    return this.args.result
               }

                this.args.result = []
                this.changedFn()
                return {}
            }
            ,

            selectSheet(aSheet) {
              let mm = this
              debugger

            }

        }
    })
}
<|endoftext|>