<commit_before>///////////Global vars/////////////
var baseUrl = "http://localhost:5000";
// global website base, set to localhost for testing
//var baseUrl = "http://eyebrowse.herokuapp.com"

///////////Models//////////////

//This object can represent either a whitelist or blacklist for a given user. On an update send results to server to update stored data. On intialization set is synced with server. Should allow offline syncing in the future.
var FilterListItem = Backbone.Model.extend({
    parse: function(data) {
        if (data != null) {
            return {
                url : data.url,
                id : data.id,
            }
        }
    },
});

var FilterList = Backbone.Collection.extend({

    model: FilterListItem,

    initialize: function(type) {
        _.bindAll(this);
        this.type = type;
        this.fetch()
    },
    getType : function() {
        return this.get('type')
    },
    url : function() {
        return getApiURL(this.type)
    },
    parse: function(data, res){
        if (res.status === 200) {
            return data.objects;
        }
        user.logout() //triggers logout badge update
    },
});

//User object holds the status of the user, the cookie from the server, preferences for eyebrowse, whitelist, blacklist, etc
var User = Backbone.Model.extend({
    defaults: {
        'loggedIn' : false,
        'whitelist' : new FilterList('whitelist'),
        'blacklist' : new FilterList('blacklist'),
        'username' : '',
        'resourceURI' : '/api/v1/user/',
    },

    initialize : function() {
        _.bindAll(this); //allow access to 'this' in callbacks with 'this' meaning the object not the context of the callback

    },

    getWhitelist : function() {
        return this.get('whitelist')
    },

    getBlacklist : function() {
        return this.get('blacklist')
    },

    getUsername : function() {
        return this.get('username')
    },

    getResourceURI : function() {
        return this.get('resourceURI')
    },

    isLoggedIn : function() {
        return this.get('loggedIn')
    },

    //when the user is logged in set the boolean to give logged in views.
    setLogin : function(status) {
        this.set({
            'loggedIn': status,
        });
        var map = {
            'true' : 'login',
            'false' : 'logout'
        };

        loginBadge(map[status]);
    },

    login : function() {
        this.setLogin(true);
    },

    logout : function() {
        this.setLogin(false);
    },

    setUsername : function(username) {
        this.set({
            'username': username,
        });
        this.setResourceURI(username);
    },

    setResourceURI : function(username) {
        this.set({
            'resourceURI' : sprintf('/api/v1/user/%s/', username)
        })
    },

    //check if a url is in the blacklist
    inBlackList : function(url) {
        return this.inSet('blacklist', url)
    },

    //check if a url is in the whitelise
    inWhitelist : function(url) {
        return this.inSet('whitelist', url)
    },

    //check if url is in a set (either whitelist or blacklist)
    // documentation for URL.js : http://medialize.github.com/URI.js/docs.html
    inSet : function(setType, url) {
        var set = this.get(setType);
        var uri = new URI(url)
        var hostname = uri.hostname();
        var protocol = uri.protocol();
        return (set.where({'url' : hostname}).length != 0 || set.where({"url" : protocol}).length != 0 || set.where(url).length != 0)
    },
});

/*
    inputs:
    tabId - indentifer of tab (unique to session only)
    url - url of the tab making the request
    favIconUrl - used for displaying content
    title - title of the webpage the tab is displaying
    event_type - whether a tab is opening or closing/navigating to a new page etc
*/
function openItem(tabId, url, favIconUrl, title, event_type) {
    var timeCheck = checkTimeDelta();
    var uri = new URI(url);
    //if its not in the whitelist lets check that the user has it
    if (!user.inWhitelist(url) && !user.inBlackList(url)) {

        timeCheck.allow = false; // we need to wait for prompt callback
        chrome.tabs.sendMessage(tabId, {"action": "prompt"},function(res){
                if (res != undefined && res.prompRes == 'allow') {
                    finishOpen(tabId, url, favIconUrl, title, event_type);
                }
            });

    } else if (user.inBlackList(url)) {
        return
    }

    if (timeCheck.allow){
        finishOpen(tabId, url, favIconUrl, title, event_type, timeCheck.time);
    }
}

function finishOpen(tabId, url, favIconUrl, title, event_type, time) {

    if (activeItem != undefined) {
        closeItem(activeItem.tabId, activeItem.url, 'blur', time);
    };

    //reassign the active item to be the current tab
    activeItem = {
        'tabId' : tabId,
        'url' : url,
        'favIconUrl' : favIconUrl,
        'title' : title,
        'start_event' : event_type,
        'start_time' : new Date(),
    };
}

/*
    There is only ever one activeItem at a time so only close out the active one.
    This event will be fired when a tab is closed or unfocused but we would have already 'closed' the item so we don't want to do it again.
*/
function closeItem(tabId, url, event_type, time, callback) {
    if (activeItem === undefined) return;
    var time = time || new Date(); // time is undefined for destroy event
    var callback = callback || false;
    if (activeItem.tabId === tabId && !user.inBlackList(url)) {
        //write to local storage
        var item = $.extend({}, activeItem); //copy activeItem

        item.end_event = event_type;
        item.end_time = time;
        item.total_time = item.end_time - item.start_time;
        item.humanize_time = moment.humanizeDuration(item.total_time);
        local_history.push(item);

        // send data for server and sync whitelist/blacklist
        if (local_history.length > 2) {
            console.log("dumping data");
            dumpData();
            user.getWhitelist().fetch();
            user.getBlacklist().fetch();
        }
        updateBadge();
    }
    if (callback) {
        callback();
    }
}

function executeMessage(request, sender, sendResponse) {
    var message = JSON.parse(request);
    var action = message.action;
    if (action == "filterlist") {
        handleFilterListMsg(message);
    } else if (action == "idle") {
       handleIdleMsg(message, sender.tab.id);
    } else {
        console.log("Action not supported");
    }
}

function handleFilterListMsg(message) {
    var type = message.type;
    var url = message.url;
    var list;
    if (type == 'whitelist') {
        list = user.getWhitelist();
    } else if (type == 'blacklist') {
        list = user.getBlacklist();
    } else {
        return
    }
    m = list.create({
        'url' : url,
        'user' : user.getResourceURI(),
    });

    localStorage['user'] = JSON.stringify(user);
}

function handleIdleMsg(message, tabId) {
    var type = message.type;
    if (type == 'openItem')  {
        openTab(tabId, 'focus');
    } else if (type == 'closeItem' && activeItem != undefined) {
        closeTab(tabId, 'idle', function() {
                activeItem = undefined;
            });
    }
}

/*
    Posts data to server
*/
function dumpData() {
    backlog = []
    var url = getApiURL('history-data');
    $.each(local_history, function(index, item){
        console.log(item);
        payload = serializePayload(item);
        $.ajax({
            type: 'POST',
            url: url,
            data: payload,
            dataType: "application/json",
            processData:  false,
            contentType: "application/json",
            error: function(jqXHR, textStatus, errorThrown){
                // log the error to the console
                console.log(
                    "The following error occured: "+
                    textStatus, errorThrown
                );
                backlog.push(item);
                if (index == local_history.length) {
                    local_history = backlog;
                }
            }
        });
    });
}

/*
    checks if the time between the current event and the active item is greater than the delta. Default delta is 900ms
*/
function checkTimeDelta(delta) {
    var delta = delta || 900
    var now = new Date();
    var allow = true; // default to true allows active item to be set initially
    if (activeItem != undefined) {
        allow = (now.getTime() - activeItem.start_time) > delta
    }

    return {
        'allow' : allow,
        'time' : now,
    }
}

function getApiURL(resource, id, params) {
    params = params || {};
    var apiBase = sprintf('%s/api/v1/%s', baseUrl, resource);
    var getParams = ''
    $.each(params, function(key, val){
        getParams += sprintf("&%s=%s", key, val);
    });
    if (id != null) {
        apiBase += '/' + id;
    }
    return apiBase
    //return sprintf("%s/?format=json%s", apiBase, getParams)
}

/////////init models///////
function loadLocalHistory() {
    localString = localStorage['local_history'];
    localString = (localString) ? localString : "[]"; // catch undefined case
    return JSON.parse(localString);
}

function loadLocalUser() {
    localString = localStorage['user']
    if (!localString) {
        return new User();
    }
    var u = new User();
    o = JSON.parse(localString);
    u['username'] = o['username'];
    u['loggedIn'] = false;
    u['blacklist'] = o['blacklist'];
    u['whitelist'] = o['whitelist'];
    u['resourceURI'] = o['resourceURI'];

    return u
}

//  Check if these are already set to avoid overwriting.
function localSetIfNull(key,value) {
    if (localStorage.getItem(key) === null) {
        console.log(key + " not set. Setting now to " + value);
        localStorage.setItem(key,value);
    } else {
        console.log(key + " already set. Leaving it alone. Value is " + localStorage.getItem(key));
    }
}

//converts the data to JSON serialized
function serializePayload(payload) {
    payload.start_time = payload.start_time
    payload.end_time = payload.end_time
    payload.user = user.getResourceURI();
    console.log(payload)
    return JSON.stringify(payload);
}

// dictionary mapping all open items. Keyed on tabIds and containing all information to be written to the log.
var activeItem;

local_history = loadLocalHistory();

user = loadLocalUser();
initBadge()

localSetIfNull("baseUrl", baseUrl);

<commit_msg>bugs with resetting local history<commit_after>///////////Global vars/////////////
var baseUrl = "http://localhost:5000";
// global website base, set to localhost for testing
//var baseUrl = "http://eyebrowse.herokuapp.com"

///////////Models//////////////

//This object can represent either a whitelist or blacklist for a given user. On an update send results to server to update stored data. On intialization set is synced with server. Should allow offline syncing in the future.
var FilterListItem = Backbone.Model.extend({
    parse: function(data) {
        if (data != null) {
            return {
                url : data.url,
                id : data.id,
            }
        }
    },
});

var FilterList = Backbone.Collection.extend({

    model: FilterListItem,

    initialize: function(type) {
        _.bindAll(this);
        this.type = type;
        this.fetch()
    },
    getType : function() {
        return this.get('type')
    },
    url : function() {
        return getApiURL(this.type)
    },
    parse: function(data, res){
        if (res.status === 200) {
            return data.objects;
        }
        user.logout() //triggers logout badge update
    },
});

//User object holds the status of the user, the cookie from the server, preferences for eyebrowse, whitelist, blacklist, etc
var User = Backbone.Model.extend({
    defaults: {
        'loggedIn' : false,
        'whitelist' : new FilterList('whitelist'),
        'blacklist' : new FilterList('blacklist'),
        'username' : '',
        'resourceURI' : '/api/v1/user/',
    },

    initialize : function() {
        _.bindAll(this); //allow access to 'this' in callbacks with 'this' meaning the object not the context of the callback

    },

    getWhitelist : function() {
        return this.get('whitelist')
    },

    getBlacklist : function() {
        return this.get('blacklist')
    },

    getUsername : function() {
        return this.get('username')
    },

    getResourceURI : function() {
        return this.get('resourceURI')
    },

    isLoggedIn : function() {
        return this.get('loggedIn')
    },

    //when the user is logged in set the boolean to give logged in views.
    setLogin : function(status) {
        this.set({
            'loggedIn': status,
        });
        var map = {
            'true' : 'login',
            'false' : 'logout'
        };

        loginBadge(map[status]);
    },

    login : function() {
        this.setLogin(true);
    },

    logout : function() {
        this.setLogin(false);
    },

    setUsername : function(username) {
        this.set({
            'username': username,
        });
        this.setResourceURI(username);
    },

    setResourceURI : function(username) {
        this.set({
            'resourceURI' : sprintf('/api/v1/user/%s/', username)
        })
    },

    //check if a url is in the blacklist
    inBlackList : function(url) {
        return this.inSet('blacklist', url)
    },

    //check if a url is in the whitelise
    inWhitelist : function(url) {
        return this.inSet('whitelist', url)
    },

    //check if url is in a set (either whitelist or blacklist)
    // documentation for URL.js : http://medialize.github.com/URI.js/docs.html
    inSet : function(setType, url) {
        var set = this.get(setType);
        var uri = new URI(url)
        var hostname = uri.hostname();
        var protocol = uri.protocol();
        return (set.where({'url' : hostname}).length != 0 || set.where({"url" : protocol}).length != 0 || set.where(url).length != 0)
    },
});

/*
    inputs:
    tabId - indentifer of tab (unique to session only)
    url - url of the tab making the request
    favIconUrl - used for displaying content
    title - title of the webpage the tab is displaying
    event_type - whether a tab is opening or closing/navigating to a new page etc
*/
function openItem(tabId, url, favIconUrl, title, event_type) {
    var timeCheck = checkTimeDelta();
    var uri = new URI(url);
    //if its not in the whitelist lets check that the user has it
    if (!user.inWhitelist(url) && !user.inBlackList(url)) {

        timeCheck.allow = false; // we need to wait for prompt callback
        chrome.tabs.sendMessage(tabId, {"action": "prompt"},function(res){
                if (res != undefined && res.prompRes == 'allow') {
                    finishOpen(tabId, url, favIconUrl, title, event_type);
                }
            });

    } else if (user.inBlackList(url)) {
        return
    }

    if (timeCheck.allow){
        finishOpen(tabId, url, favIconUrl, title, event_type, timeCheck.time);
    }
}

function finishOpen(tabId, url, favIconUrl, title, event_type, time) {

    if (activeItem != undefined) {
        closeItem(activeItem.tabId, activeItem.url, 'blur', time);
    };

    //reassign the active item to be the current tab
    activeItem = {
        'tabId' : tabId,
        'url' : url,
        'favIconUrl' : favIconUrl,
        'title' : title,
        'start_event' : event_type,
        'start_time' : new Date(),
    };
}

/*
    There is only ever one activeItem at a time so only close out the active one.
    This event will be fired when a tab is closed or unfocused but we would have already 'closed' the item so we don't want to do it again.
*/
function closeItem(tabId, url, event_type, time, callback) {
    if (activeItem === undefined) return;
    var time = time || new Date(); // time is undefined for destroy event
    var callback = callback || false;
    if (activeItem.tabId === tabId && !user.inBlackList(url)) {
        //write to local storage
        var item = $.extend({}, activeItem); //copy activeItem

        item.end_event = event_type;
        item.end_time = time;
        item.total_time = item.end_time - item.start_time;
        item.humanize_time = moment.humanizeDuration(item.total_time);
        local_history.push(item);

        // send data for server and sync whitelist/blacklist
        if (local_history.length > 2) {
            console.log("dumping data");
            dumpData();
            user.getWhitelist().fetch();
            user.getBlacklist().fetch();
        }
        updateBadge();
    }
    if (callback) {
        callback();
    }
}

function executeMessage(request, sender, sendResponse) {
    var message = JSON.parse(request);
    var action = message.action;
    if (action == "filterlist") {
        handleFilterListMsg(message);
    } else if (action == "idle") {
       handleIdleMsg(message, sender.tab.id);
    } else {
        console.log("Action not supported");
    }
}

function handleFilterListMsg(message) {
    var type = message.type;
    var url = message.url;
    var list;
    if (type == 'whitelist') {
        list = user.getWhitelist();
    } else if (type == 'blacklist') {
        list = user.getBlacklist();
    } else {
        return
    }
    m = list.create({
        'url' : url,
        'user' : user.getResourceURI(),
    });

    localStorage['user'] = JSON.stringify(user);
}

function handleIdleMsg(message, tabId) {
    var type = message.type;
    if (type == 'openItem')  {
        openTab(tabId, 'focus');
    } else if (type == 'closeItem' && activeItem != undefined) {
        closeTab(tabId, 'idle', function() {
                activeItem = undefined;
            });
    }
}

/*
    Posts data to server
*/
function dumpData() {
    var backlog = []
    var url = getApiURL('history-data');
    $.each(local_history, function(index, item){
        payload = serializePayload(item);
        $.ajax({
            type: 'POST',
            url: url,
            data: payload,
            dataType: "text",
            processData:  false,
            contentType: "application/json",
            error: function(jqXHR, textStatus, errorThrown){
                // log the error to the console
                console.log(
                    "The following error occured: "+
                    textStatus, errorThrown
                );
                backlog.push(item);
                if (index == local_history.length-1) {
                    local_history = backlog;
                }
            },
            success: function(data, textStatus, jqXHR) {
               if (index == local_history.length-1) {
                    local_history = [];
                }
            },
        });
    });
}

/*
    checks if the time between the current event and the active item is greater than the delta. Default delta is 900ms
*/
function checkTimeDelta(delta) {
    var delta = delta || 900
    var now = new Date();
    var allow = true; // default to true allows active item to be set initially
    if (activeItem != undefined) {
        allow = (now.getTime() - activeItem.start_time) > delta
    }

    return {
        'allow' : allow,
        'time' : now,
    }
}

function getApiURL(resource, id, params) {
    params = params || {};
    var apiBase = sprintf('%s/api/v1/%s', baseUrl, resource);
    var getParams = ''
    $.each(params, function(key, val){
        getParams += sprintf("&%s=%s", key, val);
    });
    if (id != null) {
        apiBase += '/' + id;
    }
    return apiBase
    //return sprintf("%s/?format=json%s", apiBase, getParams)
}

/////////init models///////
function loadLocalHistory() {
    localString = localStorage['local_history'];
    localString = (localString) ? localString : "[]"; // catch undefined case
    return JSON.parse(localString);
}

function loadLocalUser() {
    localString = localStorage['user']
    if (!localString) {
        return new User();
    }
    var u = new User();
    o = JSON.parse(localString);
    u['username'] = o['username'];
    u['loggedIn'] = false;
    u['blacklist'] = o['blacklist'];
    u['whitelist'] = o['whitelist'];
    u['resourceURI'] = o['resourceURI'];

    return u
}

//  Check if these are already set to avoid overwriting.
function localSetIfNull(key,value) {
    if (localStorage.getItem(key) === null) {
        console.log(key + " not set. Setting now to " + value);
        localStorage.setItem(key,value);
    } else {
        console.log(key + " already set. Leaving it alone. Value is " + localStorage.getItem(key));
    }
}

//converts the data to JSON serialized
function serializePayload(payload) {
    payload.start_time = payload.start_time
    payload.end_time = payload.end_time
    payload.user = user.getResourceURI();
    console.log(payload)
    return JSON.stringify(payload);
}

// dictionary mapping all open items. Keyed on tabIds and containing all information to be written to the log.
var activeItem;

local_history = loadLocalHistory();

user = loadLocalUser();
initBadge()

localSetIfNull("baseUrl", baseUrl);

<|endoftext|>


<commit_before>/**
 * Created by ssmith on 12/29/15.
 */
var ws = new SockJS('http://' + window.location.hostname + ':15674/stomp');
var client = Stomp.over(ws);
var user = 'guest';
var pass = 'guest';
var vhost = '/';
var time_refresh = 1000;

// SockJS does not support heart-beat: disable heart-beats
client.heartbeat.outgoing = 0;
client.heartbeat.incoming = 0;

/**
 * A weather message has been sent, parse and display it
 * TODO: Determine data structure and parse it to make it pretty
 * @param data
 */
var on_message_weather = function (data) {
    obj = JSON.parse(data);
    updateTime = new Date(obj.timestamp);
    $('#temperature').text(obj.temperature + "°");
    $('#location').text(obj.location);
    $('#updatedAt').text('Last updated at ' + moment(updateTime).format('LT'));
    $('#icon').attr("src", obj.icon);
}

/**
 * When a message is sent to this it means that an updated version of the
 * application has been downloaded, refresh the page
 */
var on_message_update = function () {
    window.location.reload();
}

/**
 * A message......message has been sent, display it
 * @param data
 */
var on_message_msg = function (data) {
    var content = $('#message');
    content.text(data);
}

/**
 * A weather message has been sent, parse and display it
 * TODO: Determine data structure and parse it to make it pretty
 * @param data
 */
var on_message_irc = function (data) {
    var content = $('#irc');
    obj = JSON.parse(data);
    updateTime = new Date(obj.timestamp);
    var display = '[' + moment(updateTime).format('LT') +'] ' + obj.username + ': ' + obj.message;
    content.text(display);
}

/**
 * Connect to RabbitMQ to get weather updates
 * @param x
 */
var on_connect = function (x) {
    client.subscribe("/topic/weather", function (d) {
        on_message_weather(d.body);
    });
    client.subscribe("/topic/message", function (d) {
        on_message_msg(d.body);
    });
    client.subscribe("/topic/upgrade", function (_) {
        on_message_update();
    });
    client.subscribe("/topic/irc", function (d) {
        on_message_irc(d.body);
    });
};

var on_error = function () {
    console.log('error');
};

/**
 * Requests updates from services, only used when the page first loads
 */
function request_updates() {
    client.send("/topic/update", {"content-type": "text/plain"}, "test");
}

function display_c() {
    setTimeout('display_ct()', time_refresh);
}

function display_ct() {
    time = moment(new Date()).format('llll');
    $('#time').text(time);

    display_c();
}

$(window).load(function () {
    client.connect(user, pass, on_connect, on_error, vhost);
    display_ct();
    //setTimeout is a hack to make sure that the connection is established
    setTimeout('request_updates()', 3000);
});<commit_msg>No need for a message body on the on-demand update request<commit_after>/**
 * Created by ssmith on 12/29/15.
 */
var ws = new SockJS('http://' + window.location.hostname + ':15674/stomp');
var client = Stomp.over(ws);
var user = 'guest';
var pass = 'guest';
var vhost = '/';
var time_refresh = 1000;

// SockJS does not support heart-beat: disable heart-beats
client.heartbeat.outgoing = 0;
client.heartbeat.incoming = 0;

/**
 * A weather message has been sent, parse and display it
 * TODO: Determine data structure and parse it to make it pretty
 * @param data
 */
var on_message_weather = function (data) {
    obj = JSON.parse(data);
    updateTime = new Date(obj.timestamp);
    $('#temperature').text(obj.temperature + "°");
    $('#location').text(obj.location);
    $('#updatedAt').text('Last updated at ' + moment(updateTime).format('LT'));
    $('#icon').attr("src", obj.icon);
}

/**
 * When a message is sent to this it means that an updated version of the
 * application has been downloaded, refresh the page
 */
var on_message_update = function () {
    window.location.reload();
}

/**
 * A message......message has been sent, display it
 * @param data
 */
var on_message_msg = function (data) {
    var content = $('#message');
    content.text(data);
}

/**
 * A weather message has been sent, parse and display it
 * TODO: Determine data structure and parse it to make it pretty
 * @param data
 */
var on_message_irc = function (data) {
    var content = $('#irc');
    obj = JSON.parse(data);
    updateTime = new Date(obj.timestamp);
    var display = '[' + moment(updateTime).format('LT') +'] ' + obj.username + ': ' + obj.message;
    content.text(display);
}

/**
 * Connect to RabbitMQ to get weather updates
 * @param x
 */
var on_connect = function (x) {
    client.subscribe("/topic/weather", function (d) {
        on_message_weather(d.body);
    });
    client.subscribe("/topic/message", function (d) {
        on_message_msg(d.body);
    });
    client.subscribe("/topic/upgrade", function (_) {
        on_message_update();
    });
    client.subscribe("/topic/irc", function (d) {
        on_message_irc(d.body);
    });
};

var on_error = function () {
    console.log('error');
};

/**
 * Requests updates from services, only used when the page first loads
 */
function request_updates() {
    client.send("/topic/update");
}

function display_c() {
    setTimeout('display_ct()', time_refresh);
}

function display_ct() {
    time = moment(new Date()).format('llll');
    $('#time').text(time);

    display_c();
}

$(window).load(function () {
    client.connect(user, pass, on_connect, on_error, vhost);
    display_ct();
    //setTimeout is a hack to make sure that the connection is established
    setTimeout('request_updates()', 3000);
});<|endoftext|>


<commit_before>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function backToTop() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

function passwordsMatch() {
  console.log("passwordsMatch()");

  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");
    $('#passwordError').addClass("hidden");

    return true;
  }

  $('#passGroup').addClass("has-error");
  $('#passwordError').removeClass("hidden");

  backToTop();

  return false;
}

function onMessageChange() {
    console.log("onMessageChange()");
    var m = $('#message');

    $("#count").text( m.val().length  );

    m.autosize({ append: '\n'});
    m.trigger('autosize.resize');
}

function messageUpdated() {
  $('#message').select();
  onMessageChange();
}

function clearMessage() {
  bootbox.confirm("Clear message?", function(result) {
    if(result == true) {
      $('#message').val('');
      onMessageChange();
    }
  });
}

function pageEncrypt() {
  console.log("pageEncrypt()");
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

function pageDecrypt() {
  console.log("pageDecrypt()");
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

require(['require-config'], function(config) {

	console.log("main.");

	require.config(config);

	require(
		[
			'jquery',
			'jquery.autosize',
			'sha256',
			'aes',
			'bootstrap',
			'bootstrap.mods',
			'bootbox',
			'add2home',
			'globals/utils',
			'dropins'
		],
		function() {

			console.log("main()");

			$("#message").change( onMessageChange );
			$("#message").keyup( onMessageChange );

			$('#encrypt').click( pageEncrypt );
			$('#decrypt').click( pageDecrypt );

			$('#backToTop').click( backToTop );
			$('#clearMessage').click( clearMessage );

			onMessageChange();

			$('#splashscreen').delay( 1000 ).fadeOut('slow');
		}
	);
});
<commit_msg>formatting cleanup<commit_after>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function backToTop() {
  $("html, body").animate({ scrollTop: 0 }, "slow");
}

function passwordsMatch() {
  console.log("passwordsMatch()");

  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");
    $('#passwordError').addClass("hidden");

    return true;
  }

  $('#passGroup').addClass("has-error");
  $('#passwordError').removeClass("hidden");

  backToTop();

  return false;
}

function onMessageChange() {
    console.log("onMessageChange()");
    var m = $('#message');

    $("#count").text( m.val().length  );

    m.autosize({ append: '\n'});
    m.trigger('autosize.resize');
}

function messageUpdated() {
  $('#message').select();
  onMessageChange();
}

function clearMessage() {
  bootbox.confirm("Clear message?", function(result) {
    if(result == true) {
      $('#message').val('');
      onMessageChange();
    }
  });
}

function pageEncrypt() {
  console.log("pageEncrypt()");
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

function pageDecrypt() {
  console.log("pageDecrypt()");
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    messageUpdated();
  }
}

require(['require-config'], function(config) {

  console.log("main.");

  require.config(config);

  require(
    [
      'jquery',
      'jquery.autosize',
      'sha256',
      'aes',
      'bootstrap',
      'bootstrap.mods',
      'bootbox',
      'add2home',
      'globals/utils',
      'dropins'
    ],
    function() {

      console.log("main()");

      $("#message").change( onMessageChange );
      $("#message").keyup( onMessageChange );

      $('#encrypt').click( pageEncrypt );
      $('#decrypt').click( pageDecrypt );

      $('#backToTop').click( backToTop );
      $('#clearMessage').click( clearMessage );

      onMessageChange();

      $('#splashscreen').delay( 1000 ).fadeOut('slow');
    }
  );
});
<|endoftext|>


<commit_before>function resize(width, height, speed, callback) {
	$('html').animate({'width': width, 'height': height}, speed, callback);
}
$(document).ready(function(){
    if (window.location.pathname == '/popup.html')
        resize(250, 160, 1000);
    $('body').fadeIn('fast');

    // Back to menu
    $('#backbutton').click(function() {
        $('body').fadeOut(50);
        resize(250, 160, 500, function(){window.location = '../popup.html';});
    });

    // Menu item click
    $('.menuitem').click(function() {
        $('body').fadeOut(50);
    });

	// Backwards Text
	$('#item-one').hover(function() {
		$('#item-one').html('txeT esreveR');
        $('#item-one').css('color', 'black');
    },
    function() {
		$('#item-one').html('Reverse Text');
        $('#item-one').css('color', 'grey');
    }).click(function() {
        resize(250, 275, 500, function(){window.location = 'tools/reverse.html';});
    });

    // Upside-down Text
    $('#item-two').hover(function() {
        $('#item-two').css('transform', 'rotate(-180deg)');
        $('#item-two').css('border-bottom', 'none');
        $('#item-two').css('border-top', 'solid 1px grey');
        $('#item-two').css('color', 'black');
    },
    function() {
        $('#item-two').css('transform', 'rotate(0deg)');
        $('#item-two').css('border-bottom', 'solid 1px grey');
        $('#item-two').css('border-top', 'none');
        $('#item-two').css('color', 'grey');
    }).click(function() {
        resize(250, 275, 500, function(){window.location = 'tools/flip.html';});
    });

    // Rainbow Text
    $('#item-three').hover(function() {
        $('#item-three').html('Rainbow Text');
    },
    function() {
        $('#item-three').html('Rainbow Text');
    }).click(function() {
        resize(250, 355, 500, function(){window.location = 'tools/rainbow.html';});
    });
});<commit_msg>Removed the resize code I added yesterday.<commit_after>function resize(width, height, speed, callback) {
	$('html').animate({'width': width, 'height': height}, speed, callback);
}
$(document).ready(function(){
    $('body').fadeIn('fast');

    // Back to menu
    $('#backbutton').click(function() {
        $('body').fadeOut(50);
        resize(250, 160, 500, function(){window.location = '../popup.html';});
    });

    // Menu item click
    $('.menuitem').click(function() {
        $('body').fadeOut(50);
    });

	// Backwards Text
	$('#item-one').hover(function() {
		$('#item-one').html('txeT esreveR');
        $('#item-one').css('color', 'black');
    },
    function() {
		$('#item-one').html('Reverse Text');
        $('#item-one').css('color', 'grey');
    }).click(function() {
        resize(250, 275, 500, function(){window.location = 'tools/reverse.html';});
    });

    // Upside-down Text
    $('#item-two').hover(function() {
        $('#item-two').css('transform', 'rotate(-180deg)');
        $('#item-two').css('border-bottom', 'none');
        $('#item-two').css('border-top', 'solid 1px grey');
        $('#item-two').css('color', 'black');
    },
    function() {
        $('#item-two').css('transform', 'rotate(0deg)');
        $('#item-two').css('border-bottom', 'solid 1px grey');
        $('#item-two').css('border-top', 'none');
        $('#item-two').css('color', 'grey');
    }).click(function() {
        resize(250, 275, 500, function(){window.location = 'tools/flip.html';});
    });

    // Rainbow Text
    $('#item-three').hover(function() {
        $('#item-three').html('Rainbow Text');
    },
    function() {
        $('#item-three').html('Rainbow Text');
    }).click(function() {
        resize(250, 355, 500, function(){window.location = 'tools/rainbow.html';});
    });
});<|endoftext|>


<commit_before>'use strict';

var cache = new LastFMCache();

/* Create a LastFM object: keys defined in config.js */
var lastfm = new LastFM({
    apiKey        : apiKey,
    apiSecret : apiSecret,
    cache         : cache
});

var events, node, contentnode = $(document.body).find('.row');

var util = {
    getEventObject: function (event) {
        if (event.artists.artist) {
            $(node.find('p')[0]).append(
                ''
                + [].concat(event.artists.artist).join(', ')
                + ''
                + '
');
            debugger;
            return {
                eventid: event.id,
                artists: event.artists,
                venueid: event.venue.id,
                venuelabel: event.venue.name + event.venue.location.postalcode + event.venue.location.city,
                venuecity: event.venue.location.city,
                date: event.startDate,
                day: event.startDate, //mapping wochentag
                attendance: event.attendance,
                attendees: '' //event.getAttendees
            }
        }
        return {};
    },

    getNode: function () {
        //return $('

Heading

View details »

')
        return $('

Heading

')
    },

    getDefaultVenues: function () {
        return {
            cologne: ['8778655',    //Underground
                      '8787338',    //E-Werk
                      '8778353',    //Live Music Hall
                      '8852183',    //Sonic Ballroom
                      '8780273',    //MTC
                      '8850228'],   //Essigfabrik
            siegen: ['8781504',     //Vortex
                     '8781389',     //BlueBox
                     '8870288',     //LYZ
                     '8825365',     //VEB
                     '8782593',     //meyer
                     '8829101',     //Kultkaff
                     '9088822',     //Burger King
                     '8917754',     //Shamrock
                     '8804055'],    //Casablanca
            olpe: ['8782682',       //OT
                   '8918880',       //Mythos
                   '8915189',       //Villa
                   '9068483',       //Pub
                   '8999095',       //Biggepavilion
                   '8915220',       //Stadthalle
                   '8915442',       //Marktplatz
                   '8916590',       //OT Grevenbrück
                   '8782130',       //Stadtschänke
                   '9005541',       //Old Mill
                   '8929879',       //KOT Wenden
                   '8819113',       //Noisebox
                   '8865281',       //Stadthalle Attendorn
                   '8918826',       //Blaues Haus
                   '8785391'],      //Alte Druckerei
            bochum: ['8779889',     //Matrix
                     '8795925']     //Bahnhof Langendreer
        }
    }
};

//api wrapper
var wrapper = {
    getEvents: function (venue) {
        return lastfm.venue.getEvents({ venue: venue});
    }
};

//main
var render = function (venues) {
  //render
  contentnode.empty();
  _.each(venues, function (id) {
      wrapper.getEvents(id)
          .done(function(data) {
              //any events for this venue?
              if (data.events['@attr']) {
                  //ensure array
                  var event = [].concat(data.events.event)
                  //output node
                  node = util.getNode();
                  node.find('h2')
                    .html('' + ' ' + data.events['@attr'].venue + '');
                  events = _.map(event, util.getEventObject); //also add artist to node
                  //dom append and draw
                  contentnode.append(node);
              }
          });
  })
}

var navigate = function () {
    if (location.hash.substr(0, 1) === '#' && location.hash.length > 1) {
        //hash to numeric
        var isNumber = location.hash.substr(1).replace(/[0-9,]/g, '') === '';
        //render
        if (isNumber) {
            render(location.hash.substr(1).split(','));
        }
        else if (util.getDefaultVenues()[location.hash.substr(1)]) {
            location.hash = '#' + util.getDefaultVenues()[location.hash.substr(1)];
        }
        else {
          render();
        }
    } else {
        //use default locations instead
        location.hash = '#' + (_.flatten(util.getDefaultVenues()).join(','))
    }
};
window.onhashchange = navigate;
navigate();
<commit_msg>added date of event to view<commit_after>'use strict';

var cache = new LastFMCache();

/* Create a LastFM object: keys defined in config.js */
var lastfm = new LastFM({
    apiKey        : apiKey,
    apiSecret : apiSecret,
    cache         : cache
});

var events, node, contentnode = $(document.body).find('.row');

var util = {
    toIso: function (date) {
        var dd = date.getDate(),
            mm = date.getMonth() + 1,
            yyyy = date.getFullYear();
        //leading zero
        dd = dd < 10 ? '0' + dd : dd;
        mm = mm < 10 ? '0' + mm : mm;
        return yyyy + '-' + mm + '-' + dd;
    },

    getEventObject: function (event) {
        if (event.artists.artist) {
            $(node.find('p')[0]).append(
                util.toIso(new Date(event.startDate))
                + ': '
                + ''
                + [].concat(event.artists.artist).join(', ')
                + ''
                + '
');

            return {
                eventid: event.id,
                artists: event.artists,
                venueid: event.venue.id,
                venuelabel: event.venue.name + event.venue.location.postalcode + event.venue.location.city,
                venuecity: event.venue.location.city,
                date: event.startDate,
                day: event.startDate, //mapping wochentag
                attendance: event.attendance,
                attendees: '' //event.getAttendees
            }
        }
        return {};
    },

    getNode: function () {
        //return $('

Heading

View details »

')
        return $('

Heading

')
    },

    getDefaultVenues: function () {
        return {
            cologne: ['8778655',    //Underground
                      '8787338',    //E-Werk
                      '8778353',    //Live Music Hall
                      '8852183',    //Sonic Ballroom
                      '8780273',    //MTC
                      '8850228'],   //Essigfabrik
            siegen: ['8781504',     //Vortex
                     '8781389',     //BlueBox
                     '8870288',     //LYZ
                     '8825365',     //VEB
                     '8782593',     //meyer
                     '8829101',     //Kultkaff
                     '9088822',     //Burger King
                     '8917754',     //Shamrock
                     '8804055'],    //Casablanca
            olpe: ['8782682',       //OT
                   '8918880',       //Mythos
                   '8915189',       //Villa
                   '9068483',       //Pub
                   '8999095',       //Biggepavilion
                   '8915220',       //Stadthalle
                   '8915442',       //Marktplatz
                   '8916590',       //OT Grevenbrück
                   '8782130',       //Stadtschänke
                   '9005541',       //Old Mill
                   '8929879',       //KOT Wenden
                   '8819113',       //Noisebox
                   '8865281',       //Stadthalle Attendorn
                   '8918826',       //Blaues Haus
                   '8785391'],      //Alte Druckerei
            bochum: ['8779889',     //Matrix
                     '8795925']     //Bahnhof Langendreer
        }
    }
};

//api wrapper
var wrapper = {
    getEvents: function (venue) {
        return lastfm.venue.getEvents({ venue: venue});
    }
};

//main
var render = function (venues) {
  //render
  contentnode.empty();
  _.each(venues, function (id) {
      wrapper.getEvents(id)
          .done(function(data) {
              //any events for this venue?
              if (data.events['@attr']) {
                  //ensure array
                  var event = [].concat(data.events.event)
                  //output node
                  node = util.getNode();
                  node.find('h2')
                    .html('' + ' ' + data.events['@attr'].venue + '');
                  events = _.map(event, util.getEventObject); //also add artist to node
                  //dom append and draw
                  contentnode.append(node);
              }
          });
  })
}

var navigate = function () {
    if (location.hash.substr(0, 1) === '#' && location.hash.length > 1) {
        //hash to numeric
        var isNumber = location.hash.substr(1).replace(/[0-9,]/g, '') === '';
        //render
        if (isNumber) {
            render(location.hash.substr(1).split(','));
        }
        else if (util.getDefaultVenues()[location.hash.substr(1)]) {
            location.hash = '#' + util.getDefaultVenues()[location.hash.substr(1)];
        }
        else {
          render();
        }
    } else {
        //use default locations instead
        location.hash = '#' + (_.flatten(util.getDefaultVenues()).join(','))
    }
};
window.onhashchange = navigate;
navigate();
<|endoftext|>


<commit_before>/**
 * @jsx React.DOM
 */

"use strict";

define(["react", "models", "ka", "storage"], function(React, models, KA, Storage) {

    function partial( fn /*, args...*/) {
      var aps = Array.prototype.slice;
      var args = aps.call(arguments, 1);
      return function() {
        return fn.apply(this, args.concat(aps.call(arguments)));
      };
    }

    var DomainColorMap = {
        "new-and-noteworthy": "#ffffff",
        "math": "#156278",
        "science": "#822F3D",
        "economics-finance-domain": "#BB7B31",
        "humanities": "#C43931",
        "computing": "#568F3D",
        "test-prep": "#512D60",
        "partner-content": "#399B7C",
        "talks-and-interviews": "#3C5466",
        "coach-res": "#3C5466",
        "::app-search": "#3C5466"
    };

    var TopicItem = React.createClass({
        getInitialState: function() {
            return {};
        },
        render: function() {
            var divStyle = {
                float: "left;",
                width: "12px;",
                height: "100%",
                backgroundColor: DomainColorMap[this.props.topic.get("slug")]
            };
            return

                { this.props.topic.isRootChild() ?
 : null }

{this.props.topic.get("title")}

;
        }
    });

    var VideoItem = React.createClass({
        //console.log('inside video node: ' + this.props.completed);
        render: function() {
            var cx = React.addons.classSet;
            var videoNodeClass = cx({
              'video-node': true,
              'completed': this.props.completed
            });
            var pipeClassObj = {
                'pipe': true,
                'completed': this.props.completed
            };
            var subwayIconClassObj = {
                'subway-icon': true
            };
            var parentDomain = this.props.video.getParentDomain();
            subwayIconClassObj[parentDomain.get("id")] = true;
            pipeClassObj[parentDomain.get("id")] = true;
            var subwayIconClass = cx(subwayIconClassObj);
            var pipeClass = cx(pipeClassObj);
            console.log('subway icon class;');
            console.log(subwayIconClass);
            return

{this.props.video.get("title")}

;
        }
    });

    var BackButton = React.createClass({
        render: function() {
            return

                    Back

;
        }
    });

    var SigninButton = React.createClass({
        render: function() {
            var divStyle = {
                textAlign: "right",
                marginRight: "15px"
            };
            return

                    Sign In

;
        }
    });

    var TopicViewer = React.createClass({
        componentDidMount: function() {
        },
        render: function() {
            if (this.props.topic.get("topics")) {
                var topics = _(this.props.topic.get("topics").models).map((topic) => {
                    return <TopicItem topic={topic}
                                      onClickTopic={this.props.onClickTopic}
                                      key={topic.get("slug")}/>;
                });
            }

            if (this.props.topic.get("videos")) {
                var videos = _(this.props.topic.get("videos").models).map((video) => {
                    var completed = KA.completedVideos.indexOf(video.get("id")) !== -1;
                    console.log('is video complete: ' + completed);
                    return <VideoItem video={video}
                                      onClickVideo={this.props.onClickVideo}
                                      key={video.get("slug")} completed={completed} />;
                });
            }

            var topicList =

                            { !KA.isLoggedIn() ?
                                <SigninButton model={this.props.topic}
                                              onClickSignin={this.props.onClickSignin}/> : null }
                            {topics}
                            {videos}

;
            return

                    {topicList}

;
        }
    });

    var VideoListViewer = React.createClass({
        render: function() {
            if (this.props.collection.models) {
                var videos = _(this.props.collection.models).map((video) => {
                    return <VideoItem video={video}
                                      onClickVideo={this.props.onClickVideo}
                                      key={video.get("slug")}/>;
                });
            }

            var topicList =

                    {videos}

;

            return

                    {topicList}

;
        }
    });

    var VideoViewer = React.createClass({
        render: function() {
            return

                 <video width="320" height="240" controls>
                    <source src={this.props.video.get("download_urls").mp4} type="video/mp4"/>
                 </video>

;
        }
    });

    var AppHeader = React.createClass({
        render: function() {
                var backButton;
                if (this.props.model.get("parent")) {
                    backButton = <BackButton model={this.props.model}
                                             onClickBack={this.props.onClickBack}/>;
                }

                var parentDomain = this.props.model.getParentDomain();
                var style;
                if (parentDomain) {
                    var domainColor = DomainColorMap[parentDomain.get("slug")];
                    if (domainColor) {
                        style = {
                            backgroundColor: domainColor
                        };
                    }
                }

                var title = "Khan Academy";
                if (this.props.model.get("translated_title")) {
                    title = this.props.model.get("translated_title");
                } else if (this.props.model.isVideoList()) {
                    title = "Search";
                }

                return

                        {backButton}

{title}

                    <Search model={this.props.model}
                            onSearch={this.props.onSearch}/>

;
        }
    });

    var Search = React.createClass({
        getInitialState: function() {
            return {value: ''};
        },
        componentWillReceiveProps: function() {
            this.state.value = '';
        },
        onChange: function(event) {
            var search = event.target.value;
            this.setState({value: search});
            this.props.onSearch(search);
        },
        render: function() {
            var style = {
                width: "100%",
                height: "3em;",
                position: "relative"
            };
            var text = "Search...";
            if (this.props.model.get("translated_title")) {
                text = "Search " + this.props.model.get("translated_title");
            }
            return

                <input type="text"
                       placeholder={text}
                       value={this.state.value}
                       required=""
                       style={style}
                       onChange={this.onChange}/>

;

        }
    });

    var MainView = React.createClass({
        getInitialState: function() {
            return {
                currentModel: this.props.model
            };
        },
        onClickVideo: function(model) {
            this.setState({currentModel: model});
        },
        onClickTopic: function(model) {
            this.setState({currentModel: model});
        },
        onClickBack: function(model) {
            this.setState({currentModel: model.get("parent")});
        },
        onClickSignin: function() {
            KA.login();
        },
        onSearch: function(search) {
            if (!search) {
                this.setState({"currentModel": this.state.searchingModel, searchingModel: null});
                return;
            }
            var searchingModel = this.state.searchingModel;
            if (!searchingModel) {
                searchingModel = this.state.currentModel;
            }
            var results = searchingModel.findVideos(search);
            var videoList = new models.VideoList(results);
            this.setState({"currentModel": videoList, searchingModel: searchingModel});
        },
        render: function() {
            var control;
            if (this.state.currentModel.isTopic()) {
                control = <TopicViewer topic={this.state.currentModel}
                                       onClickTopic={this.onClickTopic}
                                       onClickVideo={this.onClickVideo}
                                       onClickSignin={this.onClickSignin}/>;
            } else if (this.state.currentModel.isVideoList()) {
                control = <VideoListViewer collection={this.state.currentModel}/>;
            } else {
                control = <VideoViewer  video={this.state.currentModel}/>;
            }
            //return
{control}
;
            return

                <AppHeader model={this.state.currentModel}
                           onClickBack={this.onClickBack}
                           onSearch={this.onSearch}/>
                {control}

;
        }
    });

    /*
    // I thought this was supposed to be needed, but it seems to not be needed
    $.ajaxSetup({
        xhr: function() {return new window.XMLHttpRequest({mozSystem: true});}
    });
    */

    var mountNode = document.getElementById("app");

    // Init everything
    $.when(Storage.init(), KA.init()).done(function(topicData) {
        KA.getTopicTree().done(function(topicTreeData) {
            var topic = new models.TopicModel(topicTreeData, {parse: true});
            React.renderComponent(<MainView model={topic}/>, mountNode);
            Storage.readText("data.json").done(function(data) {
                console.log('read: ' + data);
            });
            if (KA.isLoggedIn()) {
                KA.getUserVideos().done(function(data) {
                    console.log("getUserVideos:");
                    console.log(data);
                });
            } else {
                console.log('Not logged in!');
            }

            // TODO: remove, just for easy inpsection
            window.topic = topic;
            window.KA = KA;
            window.React = React;
        });
     });
});
<commit_msg>Allow video icon to be clicked too<commit_after>/**
 * @jsx React.DOM
 */

"use strict";

define(["react", "models", "ka", "storage"], function(React, models, KA, Storage) {

    function partial( fn /*, args...*/) {
      var aps = Array.prototype.slice;
      var args = aps.call(arguments, 1);
      return function() {
        return fn.apply(this, args.concat(aps.call(arguments)));
      };
    }

    var DomainColorMap = {
        "new-and-noteworthy": "#ffffff",
        "math": "#156278",
        "science": "#822F3D",
        "economics-finance-domain": "#BB7B31",
        "humanities": "#C43931",
        "computing": "#568F3D",
        "test-prep": "#512D60",
        "partner-content": "#399B7C",
        "talks-and-interviews": "#3C5466",
        "coach-res": "#3C5466",
        "::app-search": "#3C5466"
    };

    var TopicItem = React.createClass({
        getInitialState: function() {
            return {};
        },
        render: function() {
            var divStyle = {
                float: "left;",
                width: "12px;",
                height: "100%",
                backgroundColor: DomainColorMap[this.props.topic.get("slug")]
            };
            return

                { this.props.topic.isRootChild() ?
 : null }

{this.props.topic.get("title")}

;
        }
    });

    var VideoItem = React.createClass({
        //console.log('inside video node: ' + this.props.completed);
        render: function() {
            var cx = React.addons.classSet;
            var videoNodeClass = cx({
              'video-node': true,
              'completed': this.props.completed
            });
            var pipeClassObj = {
                'pipe': true,
                'completed': this.props.completed
            };
            var subwayIconClassObj = {
                'subway-icon': true
            };
            var parentDomain = this.props.video.getParentDomain();
            subwayIconClassObj[parentDomain.get("id")] = true;
            pipeClassObj[parentDomain.get("id")] = true;
            var subwayIconClass = cx(subwayIconClassObj);
            var pipeClass = cx(pipeClassObj);
            console.log('subway icon class;');
            console.log(subwayIconClass);
            return

{this.props.video.get("title")}

;
        }
    });

    var BackButton = React.createClass({
        render: function() {
            return

                    Back

;
        }
    });

    var SigninButton = React.createClass({
        render: function() {
            var divStyle = {
                textAlign: "right",
                marginRight: "15px"
            };
            return

                    Sign In

;
        }
    });

    var TopicViewer = React.createClass({
        componentDidMount: function() {
        },
        render: function() {
            if (this.props.topic.get("topics")) {
                var topics = _(this.props.topic.get("topics").models).map((topic) => {
                    return <TopicItem topic={topic}
                                      onClickTopic={this.props.onClickTopic}
                                      key={topic.get("slug")}/>;
                });
            }

            if (this.props.topic.get("videos")) {
                var videos = _(this.props.topic.get("videos").models).map((video) => {
                    var completed = KA.completedVideos.indexOf(video.get("id")) !== -1;
                    console.log('is video complete: ' + completed);
                    return <VideoItem video={video}
                                      onClickVideo={this.props.onClickVideo}
                                      key={video.get("slug")} completed={completed} />;
                });
            }

            var topicList =

                            { !KA.isLoggedIn() ?
                                <SigninButton model={this.props.topic}
                                              onClickSignin={this.props.onClickSignin}/> : null }
                            {topics}
                            {videos}

;
            return

                    {topicList}

;
        }
    });

    var VideoListViewer = React.createClass({
        render: function() {
            if (this.props.collection.models) {
                var videos = _(this.props.collection.models).map((video) => {
                    return <VideoItem video={video}
                                      onClickVideo={this.props.onClickVideo}
                                      key={video.get("slug")}/>;
                });
            }

            var topicList =

                    {videos}

;

            return

                    {topicList}

;
        }
    });

    var VideoViewer = React.createClass({
        render: function() {
            return

                 <video width="320" height="240" controls>
                    <source src={this.props.video.get("download_urls").mp4} type="video/mp4"/>
                 </video>

;
        }
    });

    var AppHeader = React.createClass({
        render: function() {
                var backButton;
                if (this.props.model.get("parent")) {
                    backButton = <BackButton model={this.props.model}
                                             onClickBack={this.props.onClickBack}/>;
                }

                var parentDomain = this.props.model.getParentDomain();
                var style;
                if (parentDomain) {
                    var domainColor = DomainColorMap[parentDomain.get("slug")];
                    if (domainColor) {
                        style = {
                            backgroundColor: domainColor
                        };
                    }
                }

                var title = "Khan Academy";
                if (this.props.model.get("translated_title")) {
                    title = this.props.model.get("translated_title");
                } else if (this.props.model.isVideoList()) {
                    title = "Search";
                }

                return

                        {backButton}

{title}

                    <Search model={this.props.model}
                            onSearch={this.props.onSearch}/>

;
        }
    });

    var Search = React.createClass({
        getInitialState: function() {
            return {value: ''};
        },
        componentWillReceiveProps: function() {
            this.state.value = '';
        },
        onChange: function(event) {
            var search = event.target.value;
            this.setState({value: search});
            this.props.onSearch(search);
        },
        render: function() {
            var style = {
                width: "100%",
                height: "3em;",
                position: "relative"
            };
            var text = "Search...";
            if (this.props.model.get("translated_title")) {
                text = "Search " + this.props.model.get("translated_title");
            }
            return

                <input type="text"
                       placeholder={text}
                       value={this.state.value}
                       required=""
                       style={style}
                       onChange={this.onChange}/>

;

        }
    });

    var MainView = React.createClass({
        getInitialState: function() {
            return {
                currentModel: this.props.model
            };
        },
        onClickVideo: function(model) {
            this.setState({currentModel: model});
        },
        onClickTopic: function(model) {
            this.setState({currentModel: model});
        },
        onClickBack: function(model) {
            this.setState({currentModel: model.get("parent")});
        },
        onClickSignin: function() {
            KA.login();
        },
        onSearch: function(search) {
            if (!search) {
                this.setState({"currentModel": this.state.searchingModel, searchingModel: null});
                return;
            }
            var searchingModel = this.state.searchingModel;
            if (!searchingModel) {
                searchingModel = this.state.currentModel;
            }
            var results = searchingModel.findVideos(search);
            var videoList = new models.VideoList(results);
            this.setState({"currentModel": videoList, searchingModel: searchingModel});
        },
        render: function() {
            var control;
            if (this.state.currentModel.isTopic()) {
                control = <TopicViewer topic={this.state.currentModel}
                                       onClickTopic={this.onClickTopic}
                                       onClickVideo={this.onClickVideo}
                                       onClickSignin={this.onClickSignin}/>;
            } else if (this.state.currentModel.isVideoList()) {
                control = <VideoListViewer collection={this.state.currentModel}/>;
            } else {
                control = <VideoViewer  video={this.state.currentModel}/>;
            }
            //return
{control}
;
            return

                <AppHeader model={this.state.currentModel}
                           onClickBack={this.onClickBack}
                           onSearch={this.onSearch}/>
                {control}

;
        }
    });

    /*
    // I thought this was supposed to be needed, but it seems to not be needed
    $.ajaxSetup({
        xhr: function() {return new window.XMLHttpRequest({mozSystem: true});}
    });
    */

    var mountNode = document.getElementById("app");

    // Init everything
    $.when(Storage.init(), KA.init()).done(function(topicData) {
        KA.getTopicTree().done(function(topicTreeData) {
            var topic = new models.TopicModel(topicTreeData, {parse: true});
            React.renderComponent(<MainView model={topic}/>, mountNode);
            Storage.readText("data.json").done(function(data) {
                console.log('read: ' + data);
            });
            if (KA.isLoggedIn()) {
                KA.getUserVideos().done(function(data) {
                    console.log("getUserVideos:");
                    console.log(data);
                });
            } else {
                console.log('Not logged in!');
            }

            // TODO: remove, just for easy inpsection
            window.topic = topic;
            window.KA = KA;
            window.React = React;
        });
     });
});
<|endoftext|>


<commit_before>// $(document).ready(function(){

  $(window).bind("load", function () {

  $('.multiple-items').slick({
    // dots: true,
    arrows: true,
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 5000,
    cssEase: 'linear'

  });

  // alert('hello world');
  //Mobile Company Intro Text Expand//
  $('#choirVidButton').click(function(){
    $('#choirVideo').toggle('slow');
    $('#choirVidButton').toggle();
    $('#vidCaption').toggle();
    $('.consultationText').toggle('slow');
    $('#choirBack').toggle();
  });

  $('#choirBack').click(function() {
    $('#choirVideo').toggle('slow');
    $('.consultationText').toggle('slow');
    $('#vidCaption').toggle('slow');
    $('#choirBack').toggle();
    $('#choirVidButton').toggle();
  });

  var contactform =  document.getElementById('contactform');
    //  'soundguytravis' + '@' + 'hotmail' + '.' + 'com');
     //  contactform.setAttribute('action', '//formspree.io/' +
      'wendyfiddles' + '@' + 'comcast' + '.' + 'net');
});

// });
<commit_msg>continued<commit_after>// $(document).ready(function(){

  $(window).bind("load", function () {

  $('.multiple-items').slick({
    // dots: true,
    arrows: true,
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1,
    autoplay: true,
    autoplaySpeed: 5000,
    cssEase: 'linear'

  });

  // alert('hello world');
  //Mobile Company Intro Text Expand//
  $('#choirVidButton').click(function(){
    $('#choirVideo').toggle('slow');
    $('#choirVidButton').toggle();
    $('#vidCaption').toggle();
    $('.consultationText').toggle('slow');
    $('#choirBack').toggle();
  });

  $('#choirBack').click(function() {
    $('#choirVideo').toggle('slow');
    $('.consultationText').toggle('slow');
    $('#vidCaption').toggle('slow');
    $('#choirBack').toggle();
    $('#choirVidButton').toggle();
  });

  var contactform =  document.getElementById('contactform');
    //  'soundguytravis' + '@' + 'hotmail' + '.' + 'com');
      contactform.setAttribute('action', '//formspree.io/' +
      'wendyfiddles' + '@' + 'comcast' + '.' + 'net');
});

// });
<|endoftext|>


<commit_before>$(function () {

    // Preload stuff
    var loader = new PxLoader(),
        bgImg = loader.addImage('img/bg.jpg'),
        earthImg = loader.addImage('img/earth-bg.png'),
        ufoImg = loader.addImage('img/ufo.png'),
        earthImg = loader.addImage('img/mute-off.png'),
        earthImg = loader.addImage('img/mute-on.png');

    loader.start();

    // Execute after preloading has finished
    loader.addCompletionListener(function() {

        // Init background image
        $.backstretch(["img/bg.jpg"]);

        // Init sounds
        soundArray = new Array();
        soundArray[0] = new Soundgun("sounds/theme.ogg");
        soundArray[1] = new Soundgun("sounds/hit.ogg");
        soundArray[2] = new Soundgun("sounds/gameover.ogg");
        var muteButton = $('#mute-button');

        // Set loop for theme
        soundArray[0].loop();

        // Check if the browser supports cookies & if the user has left mute on last time
        if (Cookies.enabled) {
            if (Cookies.get("pongMuteState") == 1) {
                $('#mute-button').css('background-image', 'url(img/mute-on.png)');
                soundArray[0].setVolume(0); // Theme
                soundArray[1].setVolume(0); // Hit
                soundArray[2].setVolume(0); // Gameover
            } else {
                soundArray[0].setVolume(0.5); // Theme
                soundArray[1].setVolume(1); // Hit
                soundArray[2].setVolume(1); // Gameover
            }
        };

        // Init changing text
        var time = new Textgun("#time");
        var score = new Textgun("#score");

        var engine;
        var timer = new Timer();
        var timeInterval;

        // Start game function
        function startGame() {

            // Play theme
            soundArray[0].play();

            // Init score
            score.useTransition(1);
            score.setValue('0');
            // Start timer
            timer.start();
            timeInterval = setInterval(function() {time.setValue(timer.getFormattedTime(timer.getCurrentTime()));}, 100);
            // Start engine
            engine = new PongEngine(ufoImg);
            engine.startEngine();
        }

        var upPressed = function() {
            console.log("up");
            engine.ball.movingVector.elements[1]--;
        },
            downPressed = function() {
                console.log("down");
                engine.ball.movingVector.elements[1]++;
            },
            rightPressed = function() {
                // for now, move paddle 10 times right
                for(var i =  0; i < 10; i++) {
                    engine.paddle.movePaddleRight();
                }
            },
            leftPressed = function() {
                for(var i = 0; i < 10; i++) {
                    engine.paddle.movePaddleLeft();
                }
            };

        var keyHandlers = {39: rightPressed, 38: upPressed, 37: leftPressed, 40: downPressed};

        $(document).keydown(function(e, v) {
            var isArrowkey = function(keycode) {
                return keycode >= 37 && keycode <= 40;
            },
                forwardKeyPress = true;

            if (!isArrowkey(e.keyCode)) {
                forwardKeyPress = true;
            }  else {
                try {
                    keyHandlers[e.keyCode]();
                } catch(e) {
                    // Do nothing
                }
                forwardKeyPress = false;
            }
            return forwardKeyPress;
        });

        // Bind start game button
        $("#start-button").click(function() {
            $("#start-game-modal").hide();
            startGame();
        });

        // Bind all game events. Game engine triggers them to canvas
        $('#main-canvas').bind('collision', function() {
            console.log("there was a collision!");
            soundArray[1].play();
            score.setValue(Number(score.getValue()) + 150);
        });
        $('#main-canvas').bind('gameOver', function() {
            soundArray[2].play();
            soundArray[0].pause();
            engine.stopEngine();
            timer.stop();
            time.setValue(timer.getFormattedTime(timer.getFinalTime()));
            clearInterval(timeInterval);

            // Display the nameModal
            $('#nameModal').fadeIn();

        });

        // When user submits scoreform
        $('#scoreform').submit(function(){
            var newnick = $('#nick').val();
            var newtime = timer.getFormattedTime(timer.getFinalTime());
            var newscore = score.getValue();
            var dataString = 'nick=' + newnick + '&time=' + newtime + '&score=' + newscore;
            $.ajax({
                type: 'POST',
                url: 'commit.php',
                data: dataString,
                success: function(data) {
                    if(newnick == "") { newnick = "anonymous"; }
                    loadHighscore(newnick, newtime, newscore);
                    console.log(newnick + "," + newtime + "," + newscore);
                    $('#nameModal').fadeOut();
                    $('html, body').animate({
                        scrollTop: $("#score-board").offset().top
                    }, 1500);
                    $('#start-game-modal').fadeIn();
                },
                error: function(data) {
                    $('error-modal').fadeIn();
                }
            });
            return false;
        });

        // When user restarts game
        $('#no-button').click(function(){
            $('#nameModal').fadeOut();
            startGame();
        });

        // When clics error refres page
        $('#reload-page-button').click(function(){
            window.location.reload();
        });

        $('#mute-button').click(function(){
            if (muteButton.css('background-image').indexOf('mute-off.png') != -1) {
                muteButton.css('background-image', 'url(img/mute-on.png)');
            } else {
                muteButton.css('background-image', 'url(img/mute-off.png)');
            }
            toggleMute(soundArray);
        });

        // refresh-images rotation value
        var rotationValue = 0;
        $(".refresh-image").click(function(){
            console.log("rotate clicked");
            rotationValue += 720;
            $(this).rotate({
                animateTo: rotationValue,
                duration: 2000
            });
        });

    });

});
<commit_msg>made refresh button to really refresh highscores<commit_after>$(function () {

    // Preload stuff
    var loader = new PxLoader(),
        bgImg = loader.addImage('img/bg.jpg'),
        earthImg = loader.addImage('img/earth-bg.png'),
        ufoImg = loader.addImage('img/ufo.png'),
        earthImg = loader.addImage('img/mute-off.png'),
        earthImg = loader.addImage('img/mute-on.png');

    loader.start();

    // Execute after preloading has finished
    loader.addCompletionListener(function() {

        // Init background image
        $.backstretch(["img/bg.jpg"]);

        // Init sounds
        soundArray = new Array();
        soundArray[0] = new Soundgun("sounds/theme.ogg");
        soundArray[1] = new Soundgun("sounds/hit.ogg");
        soundArray[2] = new Soundgun("sounds/gameover.ogg");
        var muteButton = $('#mute-button');

        // Set loop for theme
        soundArray[0].loop();

        // Check if the browser supports cookies & if the user has left mute on last time
        if (Cookies.enabled) {
            if (Cookies.get("pongMuteState") == 1) {
                $('#mute-button').css('background-image', 'url(img/mute-on.png)');
                soundArray[0].setVolume(0); // Theme
                soundArray[1].setVolume(0); // Hit
                soundArray[2].setVolume(0); // Gameover
            } else {
                soundArray[0].setVolume(0.5); // Theme
                soundArray[1].setVolume(1); // Hit
                soundArray[2].setVolume(1); // Gameover
            }
        };

        // Init changing text
        var time = new Textgun("#time");
        var score = new Textgun("#score");

        var engine;
        var timer = new Timer();
        var timeInterval;

        // Start game function
        function startGame() {

            // Play theme
            soundArray[0].play();

            // Init score
            score.useTransition(1);
            score.setValue('0');
            // Start timer
            timer.start();
            timeInterval = setInterval(function() {time.setValue(timer.getFormattedTime(timer.getCurrentTime()));}, 100);
            // Start engine
            engine = new PongEngine(ufoImg);
            engine.startEngine();
        }

        var upPressed = function() {
            console.log("up");
            engine.ball.movingVector.elements[1]--;
        },
            downPressed = function() {
                console.log("down");
                engine.ball.movingVector.elements[1]++;
            },
            rightPressed = function() {
                // for now, move paddle 10 times right
                for(var i =  0; i < 10; i++) {
                    engine.paddle.movePaddleRight();
                }
            },
            leftPressed = function() {
                for(var i = 0; i < 10; i++) {
                    engine.paddle.movePaddleLeft();
                }
            };

        var keyHandlers = {39: rightPressed, 38: upPressed, 37: leftPressed, 40: downPressed};

        $(document).keydown(function(e, v) {
            var isArrowkey = function(keycode) {
                return keycode >= 37 && keycode <= 40;
            },
                forwardKeyPress = true;

            if (!isArrowkey(e.keyCode)) {
                forwardKeyPress = true;
            }  else {
                try {
                    keyHandlers[e.keyCode]();
                } catch(e) {
                    // Do nothing
                }
                forwardKeyPress = false;
            }
            return forwardKeyPress;
        });

        // Bind start game button
        $("#start-button").click(function() {
            $("#start-game-modal").hide();
            startGame();
        });

        // Bind all game events. Game engine triggers them to canvas
        $('#main-canvas').bind('collision', function() {
            console.log("there was a collision!");
            soundArray[1].play();
            score.setValue(Number(score.getValue()) + 150);
        });
        $('#main-canvas').bind('gameOver', function() {
            soundArray[2].play();
            soundArray[0].pause();
            engine.stopEngine();
            timer.stop();
            time.setValue(timer.getFormattedTime(timer.getFinalTime()));
            clearInterval(timeInterval);

            // Display the nameModal
            $('#nameModal').fadeIn();

        });

        // When user submits scoreform
        $('#scoreform').submit(function(){
            var newnick = $('#nick').val();
            var newtime = timer.getFormattedTime(timer.getFinalTime());
            var newscore = score.getValue();
            var dataString = 'nick=' + newnick + '&time=' + newtime + '&score=' + newscore;
            $.ajax({
                type: 'POST',
                url: 'commit.php',
                data: dataString,
                success: function(data) {
                    if(newnick == "") { newnick = "anonymous"; }
                    loadHighscore(newnick, newtime, newscore);
                    console.log(newnick + "," + newtime + "," + newscore);
                    $('#nameModal').fadeOut();
                    $('html, body').animate({
                        scrollTop: $("#score-board").offset().top
                    }, 1500);
                    $('#start-game-modal').fadeIn();
                },
                error: function(data) {
                    $('error-modal').fadeIn();
                }
            });
            return false;
        });

        // When user restarts game
        $('#no-button').click(function(){
            $('#nameModal').fadeOut();
            startGame();
        });

        // When clics error refres page
        $('#reload-page-button').click(function(){
            window.location.reload();
        });

        $('#mute-button').click(function(){
            if (muteButton.css('background-image').indexOf('mute-off.png') != -1) {
                muteButton.css('background-image', 'url(img/mute-on.png)');
            } else {
                muteButton.css('background-image', 'url(img/mute-off.png)');
            }
            toggleMute(soundArray);
        });

        // refresh-images rotation value
        var rotationValue = 0;
        $(".refresh-image").click(function(){
            loadHighscore(null, null, null);
            rotationValue += 720;
            $(this).rotate({
                animateTo: rotationValue,
                duration: 2000
            });
        });

    });

});
<|endoftext|>


<commit_before>---
layout: null
---
$(document).ready(function () {
  $('a.blog-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
    }
  })

/*  if (window.location.hash && window.location.hash == '#blog') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }
  alert('window.location.pathname');*/

/*  if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}/index.html') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }
*/
    if (window.location.pathname !== 'wrong.com' && window.location.pathname !== 'wrongagain.com') {
      $('.panel-cover').addClass('panel-cover--collapsed')
    }

  $('.btn-mobile-menu').click(function () {
    $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

  $('.navigation-wrapper .blog-button').click(function () {
    $('.navigation-wrapper').toggleClass('visible')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

})
<commit_msg>what's up alert<commit_after>---
layout: null
---
$(document).ready(function () {
  alert("what's up")
  $('a.blog-button').click(function (e) {
    if ($('.panel-cover').hasClass('panel-cover--collapsed')) return
    currentWidth = $('.panel-cover').width()
    if (currentWidth < 960) {
      $('.panel-cover').addClass('panel-cover--collapsed')
      $('.content-wrapper').addClass('animated slideInRight')
    } else {
      $('.panel-cover').css('max-width', currentWidth)
      $('.panel-cover').animate({'max-width': '530px', 'width': '40%'}, 400, swing = 'swing', function () {})
    }
  })

/*  if (window.location.hash && window.location.hash == '#blog') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }
  alert('window.location.pathname');*/

/*  if (window.location.pathname !== '{{ site.baseurl }}' && window.location.pathname !== '{{ site.baseurl }}/index.html') {
    $('.panel-cover').addClass('panel-cover--collapsed')
  }
*/
    if (window.location.pathname !== 'wrong.com' && window.location.pathname !== 'wrongagain.com') {
      $('.panel-cover').addClass('panel-cover--collapsed')
    }

  $('.btn-mobile-menu').click(function () {
    $('.navigation-wrapper').toggleClass('visible animated bounceInDown')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

  $('.navigation-wrapper .blog-button').click(function () {
    $('.navigation-wrapper').toggleClass('visible')
    $('.btn-mobile-menu__icon').toggleClass('icon-list icon-x-circle animated fadeIn')
  })

})
<|endoftext|>