<commit_before>var nodemailer = require('nodemailer'),
    fs = require('fs'),
    //var body = fs.readFileSync("body.html", "utf8");
    path = require('path'),
    fs = require('fs'),
    MailParser = require("mailparser").MailParser,
    Mbox = require('node-mbox'),
    mongoose = require('mongoose'),
    async = require('async'),
    crypto = require('crypto'),
    animal = require('animal-id');

animal.useSeparator('_');

var Pseudonym = require('./models/pseudonym').Pseudonym,
    Pseudohash = require('./models/pseudohash').Pseudohash

mongoose.connect('mongodb://localhost/6857', function(err) {
    if(err) throw err;
})

if (process.getuid() != 0) {
    throw "You must run the mail parser as root!"
}

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    host: 'localhost',
    port: 25,
    tls: {rejectUnauthorized: false}
});

//begin execution with this call
watch();

function watch(){
    var mbox

    fs.watchFile('/var/mail/bob',function(curr,prev){
        mbox = new Mbox('/var/mail/bob',{});

        mbox.on('message', function(msg) {
                mbox.lastm = msg
        })

        mbox.on('end', function() {
            var mailparser = new MailParser();

            mailparser.on("end", function(mail_object){
                mapAES(mail_object)
                //mapPlainText(mail_object)
            });

            mailparser.write(mbox.lastm)
            mailparser.end()
            mbox = {}
        });
    })
}

//currently only supports 1 recipient, although more is totally possible to implement
function mapAES(mail_object){
    var sender = mail_object.from[0].address
    var subject = mail_object.subject
    var query_string = subject.split("||")[subject.split("||").length-1]
    var qs = parseQS(query_string)

    if(subject.indexOf("||") != -1)
        subject = subject.substring(0,subject.lastIndexOf("||"))

    var p = mail_object.to[0].name //pseudonym they are sending to (if none, new message)

    console.log("---")
    console.log(sender)
    console.log(subject)
    console.log(mail_object.to)
    console.log("---")

    var message = {}
    message.to = []
    message.subject = subject
    message.body = mail_object.text

    if(!p || p == ""){
        //new conversation (not replying)

        if(!qs.to || qs.to == "")
            return //should we notify sender that their mail didn't go through?

        var recipient = mail_object.to[0].address

        var pseudohash = new Pseudohash({});

        var pseudo1 = genPseudo(); //initiator
        var pseudo2 = genPseudo(); //receiver

        //encrypted with pseudo2
        var map1 = {
            email:sender, //initiator
            pseudonym: pseudo2 //receiver
        }

        //encrypted with pseudo1
        var map2 = {
            email:recipient, //receiver
            pseudonym: pseudo1 //initiator
        }

        pseudohash.hash = pseudo1
        pseudohash.hash2 = pseudo2
        pseudohash.map_cipher = AESEncrypt(map1,pseudo2)
        pseudohash.map_cipher2 = AESEncrypt(map2,pseudo1)

        pseudohash.save(function(err,savedP){
            if(err)
                throw err

            message.to.append(recipient)
            message.from = pseudo1

            send(message)
        })
    }
    else{
        var hash = SHA256(p)

        pseudohash.findOne({$or: [{hash1:hash},{hash2:hash}]}).exec(function(err,pseudohash){
            if(err)
                throw err

            if(!pseudohash)
                return //should we notify sender their email didn't go through?

            var mapCipher = pseudohash.map_cipher
            var key = p

            if(hash == pseudohash.hash)
                mapCipher = pseudohash.map_cipher2

            var map = JSON.parse(AESDecrypt(mapCipher,key))

            message.to.append(map.email)
            message.from = map.pseudonym

            send(message)
        })
    }
}

function mapPlainText(){
    var sender = mail_object.from[0].address
    var subject = mail_object.subject
    var query_string = subject.split("||")[subject.split("||").length-1]
    var qs = parseQS(query_string)

    if(subject.indexOf("||") != -1)
        subject = subject.substring(0,subject.lastIndexOf("||"))

    console.log("---")
    console.log(sender)
    console.log(subject)
    console.log(mail_object.to)
    console.log("---")

    var p = mail_object.to[0].name

    var message = {}
    message.to = []
    message.subject = subject
    message.body = mail_object.text
    if(!message.body)
        message.body = mail_object.html

    if(!p || p == ""){
        //new conversation (not replying)
        if(!qs.to || qs.to == "")
            return

        Pseudonym.findOne({initiator:sender,receiver:qs.to}).exec(function(err,pseudonym){
            if(err)
                throw err
            if(pseudonym){
                message.from = pseudonym.initiator_pseudonym
                message.to.push(qs.to)
                return send(message)
            }
            else{
                Pseudonym.findOne({initiator:qs.to,receiver:sender}).exec(function(err,pseudonym){
                    if(err)
                        throw err
                    if(pseudonym){
                        message.from = pseudonym.receiver_pseudonym
                        message.to.push(qs.to)
                        return send(message)
                    }
                    else{
                        var i_pseudo = genPseudo();
                        var r_pseudo = genPseudo();

                        var newPseudo = new Pseudonym({})
                        newPseudo.initiator = sender
                        newPseudo.initiator_pseudonym = i_pseudo
                        newPseudo.receiver = qs.to
                        newPseudo.receiver_pseudonym = r_pseudo
                        newPseudo.save(function(err,nps){
                            if(err)
                                throw err
                            message.from = nps.initiator_pseudonym
                            message.to.push(qs.to)
                            return send(message)
                        })
                    }
                })
            }
        })
    }
    else{
        //replying
        if(!p || p == "")
            return

        Pseudonym.findOne({initiator:sender,receiver_pseudonym:p}).exec(function(err,pseudonym){
            if(err)
                throw err
            if(pseudonym){
                if(qs.destroy == 'true')
                    return destroy(pseudonym)
                message.from = pseudonym.initiator_pseudonym
                message.to.push(pseudonym.receiver)
                return send(message)
            }
            else{
                Pseudonym.findOne({receiver:sender,initiator_pseudonym:p}).exec(function(err,pseudonym){
                    if(err)
                        throw err
                    if(pseudonym){
                        if(qs.destroy == 'true')
                            return destroy(pseudonym)
                                        message.from = pseudonym.receiver_pseudonym
                                                message.to.push(pseudonym.initiator)
                        return send(message)
                    }
                    else{
                        return //they borked the pseudonym
                    }
                })
            }
        })
    }
}

//this parser is horrible right now. I guess I should fix that later?
function parseQS(query_string){
    var qs = {}
    var parts = query_string.split(";")
    parts.forEach(function(p){
        var keyval = p.split(":")
        //var val
        //if(keyval[1].indexOf(",") != -1){
        //  val = keyval[1].split(",")
        //}
        //else
        //  val = keyval[1]
        qs[keyval[0]] = keyval[1]
    })

    return qs
}

function SHA256(message){
    return crypto.createHash('sha256').update(message).digest('base64');
}

function AESEncrypt(message,key){
    var cipher = crypto.createCipher("aes-256-ctr",key)
    var crypted = cipher.update(message,'utf8','hex')
    crypted += cipher.final('hex')
    return crypted;
}

function AESDecrypt(cipher,key){
    var decipher = crypto.createDecipher("aes-256-ctr",key)
    var dec = decipher.update(cipher,'hex','utf8')
    dec += decipher.final('utf8');
    return dec;
}

function genPseudo(){
    var animalName = animal.getId()
    animalName = animalName + uuidGen()
    return animalName
}

//destroy pseudnym lookup
function destroy(pseudonym){
    console.log("hello?")
    var email1 = pseudonym.receiver
    var email2 = pseudonym.initiator
    pseudonym.remove(function(err){
        send({from:"Ronald Rivest",to:[email1,email2],subject:"Link between " + pseudonym.receiver_pseudonym + " and " + pseudonym.initiator_pseudonym + " destroyed." })
    })
}

// send mail with defined transport object
function send(message){
    console.log(message)
    var recipients = message.to
        recipients.forEach(function(r){
        var mailOptions = {
                        from: message.from + " <rivest@mit.edu>", // sender address
                        replyTo: message.from + ' <bob@ec2-52-11-124-104.us-west-2.compute.amazonaws.com>',
                        to: '', // list of receivers,
                        subject: message.subject, // Subject line
                        text: message.body, // plaintext body
                        html: "",//body,
                        xMailer: '6857 Mailer'
                };
                mailOptions.bcc = r

                transporter.sendMail(mailOptions, function(error, info){
                        if(error){
                                console.log(error);
                        }else{
                                //console.log('Message sent to ' + member.email + ': ' + info.response);
                            //fs.truncate('/var/mail/bob', 0, function(){console.log('done')})
                console.log("sent")
            }
                });
        })
}

function uuidGen(){ //uuid logic based off of http://stackoverflow.com/a/2117523/1459449
    var uuid = 'xxxxyxxxyxxx'.replace(
        /[xy]/g,
        function (c) {
            var r = Math.random() * 16 | 0, //(0 to 15)
                v = c === 'x' ? r : (r & 0x3 | 0x8) //v = 0 to F (hex)
            return v.toString(16)
        }
    );

    return uuid
}
<commit_msg>pseudohash working<commit_after>var nodemailer = require('nodemailer'),
    fs = require('fs'),
    //var body = fs.readFileSync("body.html", "utf8");
    path = require('path'),
    fs = require('fs'),
    MailParser = require("mailparser").MailParser,
    Mbox = require('node-mbox'),
    mongoose = require('mongoose'),
    async = require('async'),
    crypto = require('crypto'),
    animal = require('animal-id');

animal.useSeparator('_');

var Pseudonym = require('./models/pseudonym').Pseudonym,
    Pseudohash = require('./models/pseudohash').Pseudohash

mongoose.connect('mongodb://localhost/6857', function(err) {
    if(err) throw err;
})

if (process.getuid() != 0) {
    throw "You must run the mail parser as root!"
}

// create reusable transporter object using SMTP transport
var transporter = nodemailer.createTransport({
    host: 'localhost',
    port: 25,
    tls: {rejectUnauthorized: false}
});

//begin execution with this call
watch();

function watch(){
    var mbox

    fs.watchFile('/var/mail/bob',function(curr,prev){
        mbox = new Mbox('/var/mail/bob',{});

        mbox.on('message', function(msg) {
                mbox.lastm = msg
        })

        mbox.on('end', function() {
            var mailparser = new MailParser();

            mailparser.on("end", function(mail_object){
                mapAES(mail_object)
                //mapPlainText(mail_object)
            });

            mailparser.write(mbox.lastm)
            mailparser.end()
            mbox = {}
        });
    })
}

//currently only supports 1 recipient, although more is totally possible to implement
function mapAES(mail_object){
    var sender = mail_object.from[0].address
    var subject = mail_object.subject
    var query_string = subject.split("||")[subject.split("||").length-1]
    var qs = parseQS(query_string)

    if(subject.indexOf("||") != -1)
        subject = subject.substring(0,subject.lastIndexOf("||"))

    var p = mail_object.to[0].name //pseudonym they are sending to (if none, new message)

    console.log("---")
    console.log(sender)
    console.log(subject)
    console.log(mail_object.to)
    console.log("---")

    var message = {}
    message.to = []
    message.subject = subject
    message.body = mail_object.text

    if(!p || p == ""){
        //new conversation (not replying)

        if(!qs.to || qs.to == "")
            return //should we notify sender that their mail didn't go through?

        var recipient = qs.to

        var pseudohash = new Pseudohash({});

        var pseudo1 = genPseudo(); //initiator
        var pseudo2 = genPseudo(); //receiver

        //encrypted with pseudo1
        var map1 = {
            email:sender, //initiator
            pseudonym: pseudo2 //receiver
        }

        //encrypted with pseudo2
        var map2 = {
            email:recipient, //receiver
            pseudonym: pseudo1 //initiator
        }

        pseudohash.hash = SHA256(pseudo1)
        pseudohash.hash2 = SHA256(pseudo2)
        pseudohash.map_cipher = AESEncrypt(JSON.stringify(map1),pseudo1)
        pseudohash.map_cipher2 = AESEncrypt(JSON.stringify(map2),pseudo2)

        pseudohash.save(function(err,savedP){
            if(err)
                throw err

            message.to.push(recipient)
            message.from = pseudo1

            send(message)
        })
    }
    else{
        var hash = SHA256(p)

	console.log(p)
        Pseudohash.findOne({$or: [{hash:hash},{hash2:hash}]}).exec(function(err,pseudohash){
            if(err)
                throw err
	    console.log(pseudohash)
            if(!pseudohash)
                return //should we notify sender their email didn't go through?

            var mapCipher = pseudohash.map_cipher2
            var key = p

            if(hash == pseudohash.hash)
                mapCipher = pseudohash.map_cipher

	    var map
	    try{
		map = JSON.parse(AESDecrypt(mapCipher,key))
	    }
	    catch(err){
		return //invalid key
	    }

            message.to.push(map.email)
            message.from = map.pseudonym

            send(message)
        })
    }
}

function mapPlainText(){
    var sender = mail_object.from[0].address
    var subject = mail_object.subject
    var query_string = subject.split("||")[subject.split("||").length-1]
    var qs = parseQS(query_string)

    if(subject.indexOf("||") != -1)
        subject = subject.substring(0,subject.lastIndexOf("||"))

    console.log("---")
    console.log(sender)
    console.log(subject)
    console.log(mail_object.to)
    console.log("---")

    var p = mail_object.to[0].name

    var message = {}
    message.to = []
    message.subject = subject
    message.body = mail_object.text
    if(!message.body)
        message.body = mail_object.html

    if(!p || p == ""){
        //new conversation (not replying)
        if(!qs.to || qs.to == "")
            return

        Pseudonym.findOne({initiator:sender,receiver:qs.to}).exec(function(err,pseudonym){
            if(err)
                throw err
            if(pseudonym){
                message.from = pseudonym.initiator_pseudonym
                message.to.push(qs.to)
                return send(message)
            }
            else{
                Pseudonym.findOne({initiator:qs.to,receiver:sender}).exec(function(err,pseudonym){
                    if(err)
                        throw err
                    if(pseudonym){
                        message.from = pseudonym.receiver_pseudonym
                        message.to.push(qs.to)
                        return send(message)
                    }
                    else{
                        var i_pseudo = genPseudo();
                        var r_pseudo = genPseudo();

                        var newPseudo = new Pseudonym({})
                        newPseudo.initiator = sender
                        newPseudo.initiator_pseudonym = i_pseudo
                        newPseudo.receiver = qs.to
                        newPseudo.receiver_pseudonym = r_pseudo
                        newPseudo.save(function(err,nps){
                            if(err)
                                throw err
                            message.from = nps.initiator_pseudonym
                            message.to.push(qs.to)
                            return send(message)
                        })
                    }
                })
            }
        })
    }
    else{
        //replying
        if(!p || p == "")
            return

        Pseudonym.findOne({initiator:sender,receiver_pseudonym:p}).exec(function(err,pseudonym){
            if(err)
                throw err
            if(pseudonym){
                if(qs.destroy == 'true')
                    return destroy(pseudonym)
                message.from = pseudonym.initiator_pseudonym
                message.to.push(pseudonym.receiver)
                return send(message)
            }
            else{
                Pseudonym.findOne({receiver:sender,initiator_pseudonym:p}).exec(function(err,pseudonym){
                    if(err)
                        throw err
                    if(pseudonym){
                        if(qs.destroy == 'true')
                            return destroy(pseudonym)
                                        message.from = pseudonym.receiver_pseudonym
                                                message.to.push(pseudonym.initiator)
                        return send(message)
                    }
                    else{
                        return //they borked the pseudonym
                    }
                })
            }
        })
    }
}

//this parser is horrible right now. I guess I should fix that later?
function parseQS(query_string){
    var qs = {}
    var parts = query_string.split(";")
    parts.forEach(function(p){
        var keyval = p.split(":")
        //var val
        //if(keyval[1].indexOf(",") != -1){
        //  val = keyval[1].split(",")
        //}
        //else
        //  val = keyval[1]
        qs[keyval[0]] = keyval[1]
    })

    return qs
}

function SHA256(message){
    return crypto.createHash('sha256').update(message).digest('base64');
}

function AESEncrypt(message,key){
    var cipher = crypto.createCipher("aes-256-ctr",key)
    var crypted = cipher.update(message,'utf8','hex')
    crypted += cipher.final('hex')
    return crypted;
}

function AESDecrypt(cipher,key){
    var decipher = crypto.createDecipher("aes-256-ctr",key)
    var dec = decipher.update(cipher,'hex','utf8')
    dec += decipher.final('utf8');
    return dec;
}

function genPseudo(){
    var animalName = animal.getId()
    animalName = animalName + uuidGen()
    return animalName
}

//destroy pseudnym lookup
function destroy(pseudonym){
    console.log("hello?")
    var email1 = pseudonym.receiver
    var email2 = pseudonym.initiator
    pseudonym.remove(function(err){
        send({from:"Ronald Rivest",to:[email1,email2],subject:"Link between " + pseudonym.receiver_pseudonym + " and " + pseudonym.initiator_pseudonym + " destroyed." })
    })
}

// send mail with defined transport object
function send(message){
    console.log(message)
    var recipients = message.to
        recipients.forEach(function(r){
        var mailOptions = {
                        from: message.from + " <rivest@mit.edu>", // sender address
                        replyTo: message.from + ' <bob@ec2-52-11-124-104.us-west-2.compute.amazonaws.com>',
                        to: '', // list of receivers,
                        subject: message.subject, // Subject line
                        text: message.body, // plaintext body
                        html: "",//body,
                        xMailer: '6857 Mailer'
                };
                mailOptions.bcc = r

                transporter.sendMail(mailOptions, function(error, info){
                        if(error){
                                console.log(error);
                        }else{
                                //console.log('Message sent to ' + member.email + ': ' + info.response);
                            //fs.truncate('/var/mail/bob', 0, function(){console.log('done')})
                console.log("sent")
            }
                });
        })
}

function uuidGen(){ //uuid logic based off of http://stackoverflow.com/a/2117523/1459449
    var uuid = 'xxxxyxxxyxxx'.replace(
        /[xy]/g,
        function (c) {
            var r = Math.random() * 16 | 0, //(0 to 15)
                v = c === 'x' ? r : (r & 0x3 | 0x8) //v = 0 to F (hex)
            return v.toString(16)
        }
    );

    return uuid
}
<|endoftext|>


<commit_before>/*   Copyright 2017 Agneta Network Applications, LLC.
 *
 *   Source file: main/config.js
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
const error = require('./error');
const configstore = require('configstore');
const path = require('path');
const fs = require('fs');

var port = parseFloat(process.env.PORT) || 8181;
var protocol = process.env.PROTOCOL || 'https';
var hostName = process.env.HOST_NAME || 'localhost';
var host = process.env.ENDPOINT || 'localhost';
var env = process.env.NODE_ENV || 'development';

//-------------------------------------

if (!port) {
  error.config(port, 'PORT');
}

var appConfigPath = path.join(process.cwd(), 'config.json');
var appConfig = {};

if (fs.existsSync(appConfigPath)) {
  appConfig = require(appConfigPath);
}

var result = {
  port: port,
  host: host,
  app: appConfig,
  protocol: protocol,
  env: env,
  hostName: hostName,
  socket: {
    path: '/socket'
  }
};

result.agneta = new configstore('global', null, {
  globalConfigPath: true
});

module.exports = result;
<commit_msg>lint fix<commit_after>/*   Copyright 2017 Agneta Network Applications, LLC.
 *
 *   Source file: main/config.js
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 */
const error = require('./error');
const configstore = require('configstore');
const path = require('path');
const fs = require('fs');

var port = parseFloat(process.env.PORT) || 8181;
var hostName = process.env.HOST_NAME || 'localhost';
var host = process.env.ENDPOINT || 'localhost';
var env = process.env.NODE_ENV || 'development';

//-------------------------------------

if (!port) {
  error.config(port, 'PORT');
}

var appConfigPath = path.join(process.cwd(), 'config.json');
var appConfig = {};

if (fs.existsSync(appConfigPath)) {
  appConfig = require(appConfigPath);
}

var result = {
  port: port,
  host: host,
  app: appConfig,
  env: env,
  hostName: hostName,
  socket: {
    path: '/socket'
  }
};

result.agneta = new configstore('global', null, {
  globalConfigPath: true
});

module.exports = result;
<|endoftext|>


<commit_before><commit_msg>Complete p26 in js<commit_after>repeatingDecimalSequenceLength = function(divisor) {
  var statuses = {};
  var decimalSequence = '';
  var currentDividend = 10;
  var startIndex;

  for (var sequenceIndex = 0; statuses[currentDividend] == undefined; sequenceIndex++) {
    statuses[currentDividend] = sequenceIndex;
    decimalSequence += (Math.floor(currentDividend / divisor)).toString();
    currentDividend = (currentDividend % divisor) * 10;
    startIndex = statuses[currentDividend];
  }

  var finalSequence = decimalSequence.split('').splice(startIndex, Infinity).join('');

  if (finalSequence == '0') {
    return 0;
  } else {
    return finalSequence.length;
  }
}

var highestSequenceLength = [0, 0]

for (var divisor = 2; divisor < 1000; divisor++) {
  var nextSequencelength = repeatingDecimalSequenceLength(divisor);
  if (nextSequencelength > highestSequenceLength[1]) {
    highestSequenceLength[0] = divisor;
    highestSequenceLength[1] = nextSequencelength;
  }
}

console.log(highestSequenceLength[0]);
<|endoftext|>


<commit_before>// vim: set ts=2 sts=2 et sw=2:

(function($){
    $.filtertable = {

      refresh_actions: function(store, actions, targetbox, requires_selection) {
        targetbox.empty();
        $.each(actions, function(i, action) {
            var box = $("

").appendTo(targetbox);
            var button = $("")
              .html(action.label)
              .attr("href", requires_selection?"#":action.url)
              .appendTo(box);
            $.each(action.cssclasses, function(ci, cssclass) {
                button.addClass(cssclass);
              });
            if(requires_selection) {
              button.click(function() {
                  var checked = store.result_table.find("tbody input:checkbox:checked");
                  if(checked.length == 0) {
                    store.noselection_dialog.dialog("open");
                    return false;
                  }

                  if(action.confirm_title && action.confirm_message) {
                    store.confirm_dialog_messagebox.empty();
                    $("").html(action.confirm_message)
                      .appendTo(store.confirm_dialog_messagebox);
                    store.confirm_dialog_selectionbox.empty();
                    var ul = $("

")
                      .appendTo(store.confirm_dialog_selectionbox);
                    $.each(checked, function(index, checkbox) {
                      //var tr = checkbox.parent();
                      $("

")
                        .html($(checkbox).attr("title"))
                        .appendTo(ul);
                    });
                    store.confirm_dialog.dialog({
                        modal: true,
                        title: action.confirm_title,
                        width: 500,
                        height: 300,
                        buttons: {
                          "Ok": function() {
                            $(this).dialog("close");
                            $(this).dialog("destroy");
                            store.form.attr("action", action.url);
                            store.form.submit();
                          },
                          Cancel: function() {
                            $(this).dialog("close");
                            $(this).dialog("destroy");
                          }
                        },
                      });
                    return false;
                  } else {
                    store.form.attr("action", action.url);
                    store.form.submit();
                  }
                });
            }
          });
      },

      refresh_filters: function(store, filterview, filteredsize) {
        store.filterbox.empty();
        $.each(filterview, function(filterindex, filter) {
            var box = $("

").appendTo(store.filterbox);
            $("

").html(filter.title).appendTo(box);
            var ul = $("

").appendTo(box);
            //var idprefix = store.id + "-filter-" + filterindex + "-";
            if(filter.multiselect) {
              var li = $("

").appendTo(ul);
              var toggleall = $("")
                .attr("href", "#")
                .html("Check/uncheck all")
                .appendTo(li);
              toggleall.click(function() {
                  $.filtertable.refresh(store,
                    {checkall_in_filter:filterindex});
                  return false;
                });
            }
            $.each(filter.labels, function(i, label) {
                //var id = idprefix + i;
                var li = $("

").appendTo(ul);
                var button = $("<input></input>")
                  .attr("type", filter.multiselect?"checkbox":"radio")
                  .appendTo(li);
                if (label.selected) {
                  button.attr("checked", "checked");
                };
                var lbl = $("")
                  .attr("href", "#")
                  .html(label.label)
                  .appendTo(li);
                var count = $("")
                  .addClass("filtertable-filtercount")
                  .appendTo(lbl);

                // Events
                lbl.click(function() {
                    button.click();
                    return false;
                  });
                button.click(function() {
                    var opt = {};
                    opt["filter_selected_"+filterindex] = i;
                    $.filtertable.refresh(store, opt);
                    return false;
                  });

                if(store.resultcount_supported) {
                  var opt = {countonly:"yes"};
                  opt["filter_selected_"+filterindex] = i;
                  $.getJSON(store.jsonurl, opt, function(json) {
                      var v = json.filteredsize;
                      if(filter.multiselect) {
                        v = json.filteredsize - filteredsize;
                        if(v >= 0)
                          v = "+" + v;
                      }
                      count.html(" (" + v + ")");
                      $.filtertable.recalc_accordion(store);
                    });
                }
              });
          });
      },

      create_header: function(store, has_selactions, columns, use_rowactions,
          order_by, order_asc) {
        var thead = $("

")
          .addClass("ui-widget-header");
        var tr = $("

").appendTo(thead);
        if(has_selactions) {
          var th = $("	")
            .addClass("filtertable-checkboxcell")
            .addClass("ui-state-default")
            .appendTo(tr);
          var checkall = $("<input/>")
            .attr("type", "checkbox")
            .appendTo(th);
          checkall.click(function() {
              var qry = store.result_table.find("input:checkbox");
              var checked = checkall.is(":checked");
              qry.attr("checked", checked);
            });
        }
        $.each(columns, function(i, col) {
            var th = $("	")
              .addClass("ui-state-default")
              .html(col.title)
              .appendTo(tr);
            if(col.can_order) {
              var icon = $("")
                .addClass("ui-icon")
                .addClass("devilry-th-ui-icon")
                .appendTo(th);

              th.addClass("devilry-th-clickable")
              if(order_by == i) {
                icon.addClass(order_asc?"ui-icon-triangle-1-n":"ui-icon-triangle-1-s")
                th.addClass("ui-state-active");
              } else {
                icon.addClass("ui-icon-carat-2-n-s");
              }
              th.click(function() {
                  $.filtertable.refresh(store, {order_by:i});
                  return false;
                });
            }
          });
        if(use_rowactions) {
          var th = $("	")
            .addClass("ui-state-default")
            .html(" ")
            .appendTo(tr);
        }
        return thead;
      },

      create_body: function(data, has_selactions, id) {
        var name = id + "-checkbox";
        var tbody = $("

")
        $.each(data, function(i, row) {
            var tr = $("

")
              .addClass(i%2?"even":"odd")
              .appendTo(tbody);
            if(has_selactions) {
              var td = $("	")
                .addClass("filtertable-checkboxcell")
                .appendTo(tr);
              var checkbox = $("<input/>")
                .attr("type", "checkbox")
                .attr("name", name)
                .attr("value", row.id)
                .attr("title", row.title)
                .appendTo(td);
            }
            $.each(row.cells, function(index, cell) {
                var td = $("	")
                  .html(cell.value)
                  .appendTo(tr);
                if (cell.cssclass) {
                  td.addClass(cell.cssclass);
                };
              });
            if(row.actions.length > 0) {
                var td = $("	").appendTo(tr);
                $.each(row.actions, function(i, action) {
                    $("")
                      .html(action.label)
                      .attr("href", action.url)
                      .button()
                      .appendTo(td);
                  });
            };
          });
        return tbody;
      },

      refresh_table: function(store, json) {
        store.result_table.empty();
        var has_selactions = json.selectionactions.length > 0;
        var thead = $.filtertable.create_header(store, has_selactions,
          json.columns, json.use_rowactions, json.order_by, json.order_asc);
        thead.appendTo(store.result_table);
        var tbody = $.filtertable.create_body(json.data, has_selactions, store.id);
        tbody.appendTo(store.result_table);
      },

      refresh_pagechanger: function(store, filteredsize, currentpage, perpage) {
        store.pagechangerbox.empty();
        var pages = parseInt("" + filteredsize / perpage) + 1;
        if(filteredsize % perpage == 0) {
          pages --;
        }
        if(pages == 0) {
          pages = 1;
        }
        var pagelabel = $("

")
          .addClass("filtertable-pagelabel")
          .html("Page " + (currentpage+1) + " of " + pages);
        var slider = $("

");
        pagelabel.appendTo(store.pagechangerbox);
        slider.appendTo(store.pagechangerbox);
        slider.slider({
            max: pages - 1,
            value: currentpage,
            slide: function(e, ui) {
              pagelabel.html("Page " + (ui.value+1) + " of " + pages);
            },
            change: function(e, ui) {
              $.filtertable.refresh(store, {gotopage:ui.value});
            }
        });
      },

      refresh_optional_cols: function(store, all_columns) {
        store.colsettingsbox.empty();
        $("
Optional columns
").appendTo(store.colsettingsbox);
        $.each(all_columns, function(index, colinfo) {
            if(colinfo.col.optional) {
              $("

").boxWithLabel({
                  label: colinfo.col.title,
                  value: index,
                  checked: colinfo.is_active
                }).appendTo(store.colsettingsbox);
            }
          });
        var button = $("<button></button>")
          .html("Refresh")
          .button({
              text: true,
              icons: {primary: "ui-icon-arrowrefresh-1-w"}
            })
          .appendTo(store.colsettingsbox);
        button.click(function() {
            var ch = store.colsettingsbox.find("input:checkbox:checked");
            if(ch.length == 0) {
              opt = {active_cols:"none"};
            } else {
              var opt = [];
              $.each(ch, function(index, checkbox) {
                  opt.push({name:"active_cols", value:checkbox.value});
                });
            }
            $.filtertable.refresh(store, opt);
            return false;
            //return false;
          });
      },

      recalc_accordion: function(store) {
        store.sidebar.accordion("option", "autoHeight", true);
        store.sidebar.accordion("resize");
      },

      refresh: function(store, options) {
        $.getJSON(store.jsonurl, options, function(json) {
            $.filtertable.refresh_filters(store, json.filterview, json.filteredsize);
            $.filtertable.refresh_actions(store,
              json.selectionactions, store.selectionactionsbox,
              true);
            $.filtertable.refresh_actions(store,
              json.relatedactions, store.relatedactionsbox);
            $.filtertable.refresh_table(store, json);
            $.filtertable.refresh_pagechanger(store, json.filteredsize,
              json.currentpage, json.perpage);
            $.filtertable.refresh_optional_cols(store, json.all_columns);

            store.searchfield.val(json.search);
            store.statusmsgbox.html(json.statusmsg);
            store.perpagefield.val(json.perpage);
            $.filtertable.recalc_accordion(store);
          });
      }
    };

    $.fn.filtertable = function(jsonurl, resultcount_supported) {
      return this.each(function() {
          var id = $(this).attr("id");
          var store = {};
          store.id = id;
          store.jsonurl = jsonurl;
          store.form = $(this).find("form").first();
          store.searchbox = $(this).find(".filtertable-searchbox").first();
          store.selectionactionsbox = $(this).find(".filtertable-selectionactions").first();
          store.relatedactionsbox = $(this).find(".filtertable-relatedactions").first();
          store.filterbox = $(this).find(".filtertable-filters").first();
          store.result_table = $(this).find(".filtertable-table").first();
          store.pagechangerbox = $(this).find(".filtertable-pagechanger").first();
          store.searchfield = $(this).find(".filtertable-searchfield").first();
          store.statusmsgbox = $(this).find(".filtertable-statusmsg").first();
          store.colsettingsbox = $(this).find(".filtertable-settings-cols").first();
          store.resultcount_supported = resultcount_supported;

          // Show this dialog when selecting a action when no rows are
          // selected.
          store.noselection_dialog = $(this).find(".filtertable-noselection-dialog").first();
          store.noselection_dialog.dialog({
              modal: true,
              autoOpen: false,
              buttons: {
                "Ok": function() {
                  $( this ).dialog( "close" );
                }
              },
            });

          // Show this dialog when selecting a action that requires
          // confirmation
          store.confirm_dialog = $(this).find(".filtertable-confirm-selection-dialog").first();
          store.confirm_dialog_messagebox = store.confirm_dialog.children("p").children().last();
          store.confirm_dialog_selectionbox = store.confirm_dialog.children("div").first();

          // Setup the accordion sidebar
          store.sidebar = $("#" + id + "-filtertable-sidebar");
          store.sidebar.accordion({
            header: "h3",
            autoHeight: false,
            event: "mouseover"
          });

          // Search
          store.searchfield.keydown(function(e) {
              if (e.keyCode==13) {
                $.filtertable.refresh(store, {search:store.searchfield.val()});
                return false;
              }
            });
          var searchbtn = $(this).find(".filtertable-searchbtn").first();
          searchbtn.button({
            text: false,
            icons: {primary: "ui-icon-search"}
          });
          searchbtn.click(function(e) {
              $.filtertable.refresh(store, {search:store.searchfield.val()});
              return false;
            });

          // Reset filters
          var resetbtn = $(this).find(".filtertable-reset-button").first();
          resetbtn.click(function(e) {
              $.filtertable.refresh(store, {reset:"yes"});
              return false;
            });

          // Settings
          store.perpagefield = $(this).find(".filtertable-perpagefield").first();
          store.perpagefield.keydown(function(e) {
              if (e.keyCode==13) {
                $.filtertable.refresh(store, {perpage:store.perpagefield.val()});
                return false;
              }
            });
          var perpage_updatebtn = $(this).find(".filtertable-perpage-updatebtn").first();
          perpage_updatebtn.button({
            text: false,
            icons: {primary: "ui-icon-arrowrefresh-1-w"}
          });
          perpage_updatebtn.click(function(e) {
              $.filtertable.refresh(store, {perpage:store.perpagefield.val()});
              return false;
            });
          var perpage_allbtn = $(this).find(".filtertable-perpage-allbtn").first();
          perpage_allbtn.button({
            text: true,
          });
          perpage_allbtn.click(function(e) {
              $.filtertable.refresh(store, {perpage:"all"});
              return false;
            });

          // Set initial data
          $.filtertable.refresh(store);
        });

    };
  })(jQuery);
<commit_msg>Store 'confirm title' in data.<commit_after>// vim: set ts=2 sts=2 et sw=2:

(function($){
    $.filtertable = {

      refresh_actions: function(store, actions, targetbox, requires_selection) {
        targetbox.empty();
        $.each(actions, function(i, action) {
            var box = $("

").appendTo(targetbox);
            var button = $("")
              .html(action.label)
              .attr("href", requires_selection?"#":action.url)
              .appendTo(box);
            $.each(action.cssclasses, function(ci, cssclass) {
                button.addClass(cssclass);
              });
            if(requires_selection) {
              button.click(function() {
                  var checked = store.result_table.find("tbody input:checkbox:checked");
                  if(checked.length == 0) {
                    store.noselection_dialog.dialog("open");
                    return false;
                  }

                  if(action.confirm_title && action.confirm_message) {
                    store.confirm_dialog_messagebox.empty();
                    $("").html(action.confirm_message)
                      .appendTo(store.confirm_dialog_messagebox);
                    store.confirm_dialog_selectionbox.empty();
                    var ul = $("

")
                      .appendTo(store.confirm_dialog_selectionbox);
                    $.each(checked, function(index, checkbox) {
                      //var tr = checkbox.parent();
                      $("

")
                        .html($(checkbox).data("title"))
                        .appendTo(ul);
                    });
                    store.confirm_dialog.dialog({
                        modal: true,
                        title: action.confirm_title,
                        width: 500,
                        height: 300,
                        buttons: {
                          "Ok": function() {
                            $(this).dialog("close");
                            $(this).dialog("destroy");
                            store.form.attr("action", action.url);
                            store.form.submit();
                          },
                          Cancel: function() {
                            $(this).dialog("close");
                            $(this).dialog("destroy");
                          }
                        },
                      });
                    return false;
                  } else {
                    store.form.attr("action", action.url);
                    store.form.submit();
                  }
                });
            }
          });
      },

      refresh_filters: function(store, filterview, filteredsize) {
        store.filterbox.empty();
        $.each(filterview, function(filterindex, filter) {
            var box = $("

").appendTo(store.filterbox);
            $("

").html(filter.title).appendTo(box);
            var ul = $("

").appendTo(box);
            //var idprefix = store.id + "-filter-" + filterindex + "-";
            if(filter.multiselect) {
              var li = $("

").appendTo(ul);
              var toggleall = $("")
                .attr("href", "#")
                .html("Check/uncheck all")
                .appendTo(li);
              toggleall.click(function() {
                  $.filtertable.refresh(store,
                    {checkall_in_filter:filterindex});
                  return false;
                });
            }
            $.each(filter.labels, function(i, label) {
                //var id = idprefix + i;
                var li = $("

").appendTo(ul);
                var button = $("<input></input>")
                  .attr("type", filter.multiselect?"checkbox":"radio")
                  .appendTo(li);
                if (label.selected) {
                  button.attr("checked", "checked");
                };
                var lbl = $("")
                  .attr("href", "#")
                  .html(label.label)
                  .appendTo(li);
                var count = $("")
                  .addClass("filtertable-filtercount")
                  .appendTo(lbl);

                // Events
                lbl.click(function() {
                    button.click();
                    return false;
                  });
                button.click(function() {
                    var opt = {};
                    opt["filter_selected_"+filterindex] = i;
                    $.filtertable.refresh(store, opt);
                    return false;
                  });

                if(store.resultcount_supported) {
                  var opt = {countonly:"yes"};
                  opt["filter_selected_"+filterindex] = i;
                  $.getJSON(store.jsonurl, opt, function(json) {
                      var v = json.filteredsize;
                      if(filter.multiselect) {
                        v = json.filteredsize - filteredsize;
                        if(v >= 0)
                          v = "+" + v;
                      }
                      count.html(" (" + v + ")");
                      $.filtertable.recalc_accordion(store);
                    });
                }
              });
          });
      },

      create_header: function(store, has_selactions, columns, use_rowactions,
          order_by, order_asc) {
        var thead = $("

")
          .addClass("ui-widget-header");
        var tr = $("

").appendTo(thead);
        if(has_selactions) {
          var th = $("	")
            .addClass("filtertable-checkboxcell")
            .addClass("ui-state-default")
            .appendTo(tr);
          var checkall = $("<input/>")
            .attr("type", "checkbox")
            .appendTo(th);
          checkall.click(function() {
              var qry = store.result_table.find("input:checkbox");
              var checked = checkall.is(":checked");
              qry.attr("checked", checked);
            });
        }
        $.each(columns, function(i, col) {
            var th = $("	")
              .addClass("ui-state-default")
              .html(col.title)
              .appendTo(tr);
            if(col.can_order) {
              var icon = $("")
                .addClass("ui-icon")
                .addClass("devilry-th-ui-icon")
                .appendTo(th);

              th.addClass("devilry-th-clickable")
              if(order_by == i) {
                icon.addClass(order_asc?"ui-icon-triangle-1-n":"ui-icon-triangle-1-s")
                th.addClass("ui-state-active");
              } else {
                icon.addClass("ui-icon-carat-2-n-s");
              }
              th.click(function() {
                  $.filtertable.refresh(store, {order_by:i});
                  return false;
                });
            }
          });
        if(use_rowactions) {
          var th = $("	")
            .addClass("ui-state-default")
            .html(" ")
            .appendTo(tr);
        }
        return thead;
      },

      create_body: function(data, has_selactions, id) {
        var name = id + "-checkbox";
        var tbody = $("

")
        $.each(data, function(i, row) {
            var tr = $("

")
              .addClass(i%2?"even":"odd")
              .appendTo(tbody);
            if(has_selactions) {
              var td = $("	")
                .addClass("filtertable-checkboxcell")
                .appendTo(tr);
              var checkbox = $("<input/>")
                .attr("type", "checkbox")
                .attr("name", name)
                .attr("value", row.id)
                .data("title", row.title)
                .appendTo(td);
            }
            $.each(row.cells, function(index, cell) {
                var td = $("	")
                  .html(cell.value)
                  .appendTo(tr);
                if (cell.cssclass) {
                  td.addClass(cell.cssclass);
                };
              });
            if(row.actions.length > 0) {
                var td = $("	").appendTo(tr);
                $.each(row.actions, function(i, action) {
                    $("")
                      .html(action.label)
                      .attr("href", action.url)
                      .button()
                      .appendTo(td);
                  });
            };
          });
        return tbody;
      },

      refresh_table: function(store, json) {
        store.result_table.empty();
        var has_selactions = json.selectionactions.length > 0;
        var thead = $.filtertable.create_header(store, has_selactions,
          json.columns, json.use_rowactions, json.order_by, json.order_asc);
        thead.appendTo(store.result_table);
        var tbody = $.filtertable.create_body(json.data, has_selactions, store.id);
        tbody.appendTo(store.result_table);
      },

      refresh_pagechanger: function(store, filteredsize, currentpage, perpage) {
        store.pagechangerbox.empty();
        var pages = parseInt("" + filteredsize / perpage) + 1;
        if(filteredsize % perpage == 0) {
          pages --;
        }
        if(pages == 0) {
          pages = 1;
        }
        var pagelabel = $("

")
          .addClass("filtertable-pagelabel")
          .html("Page " + (currentpage+1) + " of " + pages);
        var slider = $("

");
        pagelabel.appendTo(store.pagechangerbox);
        slider.appendTo(store.pagechangerbox);
        slider.slider({
            max: pages - 1,
            value: currentpage,
            slide: function(e, ui) {
              pagelabel.html("Page " + (ui.value+1) + " of " + pages);
            },
            change: function(e, ui) {
              $.filtertable.refresh(store, {gotopage:ui.value});
            }
        });
      },

      refresh_optional_cols: function(store, all_columns) {
        store.colsettingsbox.empty();
        $("
Optional columns
").appendTo(store.colsettingsbox);
        $.each(all_columns, function(index, colinfo) {
            if(colinfo.col.optional) {
              $("

").boxWithLabel({
                  label: colinfo.col.title,
                  value: index,
                  checked: colinfo.is_active
                }).appendTo(store.colsettingsbox);
            }
          });
        var button = $("<button></button>")
          .html("Refresh")
          .button({
              text: true,
              icons: {primary: "ui-icon-arrowrefresh-1-w"}
            })
          .appendTo(store.colsettingsbox);
        button.click(function() {
            var ch = store.colsettingsbox.find("input:checkbox:checked");
            if(ch.length == 0) {
              opt = {active_cols:"none"};
            } else {
              var opt = [];
              $.each(ch, function(index, checkbox) {
                  opt.push({name:"active_cols", value:checkbox.value});
                });
            }
            $.filtertable.refresh(store, opt);
            return false;
            //return false;
          });
      },

      recalc_accordion: function(store) {
        store.sidebar.accordion("option", "autoHeight", true);
        store.sidebar.accordion("resize");
      },

      refresh: function(store, options) {
        $.getJSON(store.jsonurl, options, function(json) {
            $.filtertable.refresh_filters(store, json.filterview, json.filteredsize);
            $.filtertable.refresh_actions(store,
              json.selectionactions, store.selectionactionsbox,
              true);
            $.filtertable.refresh_actions(store,
              json.relatedactions, store.relatedactionsbox);
            $.filtertable.refresh_table(store, json);
            $.filtertable.refresh_pagechanger(store, json.filteredsize,
              json.currentpage, json.perpage);
            $.filtertable.refresh_optional_cols(store, json.all_columns);

            store.searchfield.val(json.search);
            store.statusmsgbox.html(json.statusmsg);
            store.perpagefield.val(json.perpage);
            $.filtertable.recalc_accordion(store);
          });
      }
    };

    $.fn.filtertable = function(jsonurl, resultcount_supported) {
      return this.each(function() {
          var id = $(this).attr("id");
          var store = {};
          store.id = id;
          store.jsonurl = jsonurl;
          store.form = $(this).find("form").first();
          store.searchbox = $(this).find(".filtertable-searchbox").first();
          store.selectionactionsbox = $(this).find(".filtertable-selectionactions").first();
          store.relatedactionsbox = $(this).find(".filtertable-relatedactions").first();
          store.filterbox = $(this).find(".filtertable-filters").first();
          store.result_table = $(this).find(".filtertable-table").first();
          store.pagechangerbox = $(this).find(".filtertable-pagechanger").first();
          store.searchfield = $(this).find(".filtertable-searchfield").first();
          store.statusmsgbox = $(this).find(".filtertable-statusmsg").first();
          store.colsettingsbox = $(this).find(".filtertable-settings-cols").first();
          store.resultcount_supported = resultcount_supported;

          // Show this dialog when selecting a action when no rows are
          // selected.
          store.noselection_dialog = $(this).find(".filtertable-noselection-dialog").first();
          store.noselection_dialog.dialog({
              modal: true,
              autoOpen: false,
              buttons: {
                "Ok": function() {
                  $( this ).dialog( "close" );
                }
              },
            });

          // Show this dialog when selecting a action that requires
          // confirmation
          store.confirm_dialog = $(this).find(".filtertable-confirm-selection-dialog").first();
          store.confirm_dialog_messagebox = store.confirm_dialog.children("p").children().last();
          store.confirm_dialog_selectionbox = store.confirm_dialog.children("div").first();

          // Setup the accordion sidebar
          store.sidebar = $("#" + id + "-filtertable-sidebar");
          store.sidebar.accordion({
            header: "h3",
            autoHeight: false,
            event: "mouseover"
          });

          // Search
          store.searchfield.keydown(function(e) {
              if (e.keyCode==13) {
                $.filtertable.refresh(store, {search:store.searchfield.val()});
                return false;
              }
            });
          var searchbtn = $(this).find(".filtertable-searchbtn").first();
          searchbtn.button({
            text: false,
            icons: {primary: "ui-icon-search"}
          });
          searchbtn.click(function(e) {
              $.filtertable.refresh(store, {search:store.searchfield.val()});
              return false;
            });

          // Reset filters
          var resetbtn = $(this).find(".filtertable-reset-button").first();
          resetbtn.click(function(e) {
              $.filtertable.refresh(store, {reset:"yes"});
              return false;
            });

          // Settings
          store.perpagefield = $(this).find(".filtertable-perpagefield").first();
          store.perpagefield.keydown(function(e) {
              if (e.keyCode==13) {
                $.filtertable.refresh(store, {perpage:store.perpagefield.val()});
                return false;
              }
            });
          var perpage_updatebtn = $(this).find(".filtertable-perpage-updatebtn").first();
          perpage_updatebtn.button({
            text: false,
            icons: {primary: "ui-icon-arrowrefresh-1-w"}
          });
          perpage_updatebtn.click(function(e) {
              $.filtertable.refresh(store, {perpage:store.perpagefield.val()});
              return false;
            });
          var perpage_allbtn = $(this).find(".filtertable-perpage-allbtn").first();
          perpage_allbtn.button({
            text: true,
          });
          perpage_allbtn.click(function(e) {
              $.filtertable.refresh(store, {perpage:"all"});
              return false;
            });

          // Set initial data
          $.filtertable.refresh(store);
        });

    };
  })(jQuery);
<|endoftext|>


<commit_before>var quotesANDauthors = "If you want to achieve greatness stop asking for permission. ~Anonymous,, Things work out best for those who make the best of how things work out. ~John Wooden,, To live a creative life, we must lose our fear of being wrong. ~Anonymous,, If you are not willing to risk the usual you will have to settle for the ordinary. ~Jim Rohn,, Trust because you are willing to accept the risk, not because it’s safe or certain. ~Anonymous,, Take up one idea. Make that one idea your life - think of it, dream of it, live on that idea. Let the brain, muscles, nerves, every part of your body, be full of that idea, and just leave every other idea alone. This is the way to success. ~Swami Vivekananda,, All our dreams can come true if we have the courage to pursue them. ~Walt Disney,, Good things come to people who wait, but better things come to those who go out and get them. ~Anonymous,, If you do what you always did, you will get what you always got. ~Anonymous,, Success is walking from failure to failure with no loss of enthusiasm. ~Winston Churchill,, Just when the caterpillar thought the world was ending, he turned into a butterfly. ~Proverb,, Successful entrepreneurs are givers and not takers of positive energy. ~Anonymous,, Whenever you see a successful person you only see the public glories, never the private sacrifices to reach them. ~Vaibhav Shah,, Opportunities don’t happen, you create them. ~Chris Grosser,, Try not to become a person of success, but rather try to become a person of value. ~Albert Einstein,, Great minds discuss ideas; average minds discuss events; small minds discuss people. ~Eleanor Roosevelt,, I have not failed. I’ve just found 10,000 ways that won’t work. ~Thomas A. Edison,, If you don’t value your time, neither will others. Stop giving away your time and talents- start charging for it. ~Kim Garst,, A successful man is one who can lay a firm foundation with the bricks others have thrown at him. ~David Brinkley,, No one can make you feel inferior without your consent. ~Eleanor Roosevelt,, The whole secret of a successful life is to find out what is one’s destiny to do, and then do it. ~Henry Ford,, If you’re going through hell keep going. ~Winston Churchill,, The ones who are crazy enough to think they can change the world, are the ones that do. ~Anonymous,, Don’t raise your voice, improve your argument. ~Anonymous,, What seems to us as bitter trials are often blessings in disguise.~ Oscar Wilde,, The meaning of life is to find your gift. The purpose of life is to give it away. ~Anonymous,, The distance between insanity and genius is measured only by success. ~Bruce Feirstein,, When you stop chasing the wrong things you give the right things a chance to catch you. ~Lolly Daskal,, Don’t be afraid to give up the good to go for the great. ~John D. Rockefeller,, No masterpiece was ever created by a lazy artist.~ Anonymous,, Happiness is a butterfly, which when pursued, is always beyond your grasp, but which, if you will sit down quietly, may alight upon you. ~Nathaniel Hawthorne,, If you can’t explain it simply, you don’t understand it well enough. ~Albert Einstein,, Blessed are those who can give without remembering and take without forgetting. ~Anonymous,, Do one thing every day that scares you. ~Anonymous,, What’s the point of being alive if you don’t at least try to do something remarkable. ~Anonymous,, Life is not about finding yourself. Life is about creating yourself. ~Lolly Daskal,, Nothing in the world is more common than unsuccessful people with talent. ~Anonymous,, Knowledge is being aware of what you can do. Wisdom is knowing when not to do it. ~Anonymous,, Your problem isn’t the problem. Your reaction is the problem. ~Anonymous,, You can do anything, but not everything. ~Anonymous,, Innovation distinguishes between a leader and a follower. ~Steve Jobs,, There are two types of people who will tell you that you cannot make a difference in this world: those who are afraid to try and those who are afraid you will succeed. ~Ray Goforth,, Thinking should become your capital asset, no matter whatever ups and downs you come across in your life. ~Dr. APJ Kalam,, I find that the harder I work, the more luck I seem to have. ~Thomas Jefferson,, The starting point of all achievement is desire. ~Napolean Hill,, Success is the sum of small efforts, repeated day-in and day-out. ~Robert Collier,, If you want to achieve excellence, you can get there today. As of this second, quit doing less-than-excellent work. ~Thomas J. Watson,, All progress takes place outside the comfort zone. ~Michael John Bobak,, You may only succeed if you desire succeeding; you may only fail if you do not mind failing. ~Philippos,, Courage is resistance to fear, mastery of fear - not absense of fear. ~Mark Twain,, Only put off until tomorrow what you are willing to die having left undone. ~Pablo Picasso,, People often say that motivation doesn’t last. Well, neither does bathing - that’s why we recommend it daily. ~Zig Ziglar,, We become what we think about most of the time, and that’s the strangest secret. ~Earl Nightingale,, The only place where success comes before work is in the dictionary. ~Vidal Sassoon,, The best reason to start an organization is to make meaning; to create a product or service to make the world a better place. ~Guy Kawasaki,, I find that when you have a real interest in life and a curious life, that sleep is not the most important thing. ~Martha Stewart,, It’s not what you look at that matters, it’s what you see. ~Anonymous,, The road to success and the road to failure are almost exactly the same. ~Colin R. Davis,, The function of leadership is to produce more leaders, not more followers. ~Ralph Nader,, Success is liking yourself, liking what you do, and liking how you do it. ~Maya Angelou,, As we look ahead into the next century, leaders will be those who empower others. ~Bill Gates,, A real entrepreneur is somebody who has no safety net underneath them. ~Henry Kravis,, The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself. ~Mark Caine,, People who succeed have momentum. The more they succeed, the more they want to succeed, and the more they find a way to succeed. Similarly, when someone is failing, the tendency is to get on a downward spiral that can even become a self-fulfilling prophecy. ~Tony Robbins,, When I dare to be powerful - to use my strength in the service of my vision, then it becomes less and less important whether I am afraid. ~Audre Lorde,, Whenever you find yourself on the side of the majority, it is time to pause and reflect. ~Mark Twain,, The successful warrior is the average man, with laser-like focus. ~Bruce Lee,, Take up one idea. Make that one idea your life — think of it, dream of it, live on that idea. Let the brain, muscles, nerves, every part of your body, be full of that idea, and just leave every other idea alone. This is the way to success. ~Swami Vivekananda,, Develop success from failures. Discouragement and failure are two of the surest stepping stones to success. ~Dale Carnegie,, If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much. ~ Jim Rohn,, If you genuinely want something, don’t wait for it — teach yourself to be impatient. ~Gurbaksh Chahal,, Don’t let the fear of losing be greater than the excitement of winning. ~Robert Kiyosaki,, If you want to make a permanent change, stop focusing on the size of your problems and start focusing on the size of you! ~T. Harv Eker,, You can’t connect the dots looking forward; you can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something - your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life. ~Steve Jobs,, Successful people do what unsuccessful people are not willing to doDon’t wish it were easier, wish you were better. ~Jim Rohn,, The number one reason people fail in life is because they listen to their friends, family, and neighbors. ~Napoleon Hill,, The reason most people never reach their goals is that they don’t define them, or ever seriously consider them as believable or achievable. Winners can tell you where they are going, what they plan to do along the way, and who will be sharing the adventure with them. ~Denis Watiley,, In my experience, there is only one motivation, and that is desire. No reasons or principle contain it or stand against it. ~Jane Smiley,, Success does not consist in never making mistakes but in never making the same one a second time. ~George Bernard Shaw,, I don’t want to get to the end of my life and find that I lived just the length of it. I want to have lived the width of it as well. ~Diane Ackerman,, You must expect great things of yourself before you can do them. ~Michael Jordan,, Motivation is what gets you started. Habit is what keeps you going. ~Jim Ryun,, People rarely succeed unless they have fun in what they are doing. ~Dale Carnegie,, There is no chance, no destiny, no fate, that can hinder or control the firm resolve of a determined soul. ~Ella Wheeler Wilcox,, Our greatest fear should not be of failure but of succeeding at things in life that don’t really matter. ~Francis Chan,, You’ve got to get up every morning with determination if you’re going to go to bed with satisfaction. ~George Lorimer,, To be successful you must accept all challenges that come your way. You can’t just accept the ones you like. ~Mike Gafka,, Success is...knowing your purpose in life, growing to reach your maximum potential, and sowing seeds that benefit others. ~ John C. Maxwell,, Be miserable. Or motivate yourself. Whatever has to be done, it’s always your choice. ~Wayne Dyer,, To accomplish great things, we must not only act, but also dream, not only plan, but also believe.~ Anatole France,, Most of the important things in the world have been accomplished by people who have kept on trying when there seemed to be no help at all. ~Dale Carnegie,, You measure the size of the accomplishment by the obstacles you had to overcome to reach your goals. ~Booker T. Washington,, Real difficulties can be overcome; it is only the imaginary ones that are unconquerable. ~Theodore N. Vail,, It is better to fail in originality than to succeed in imitation. ~Herman Melville,, Fortune sides with him who dares. ~Virgil,, Little minds are tamed and subdued by misfortune; but great minds rise above it. ~Washington Irving,, Failure is the condiment that gives success its flavor. ~Truman Capote,, Don’t let what you cannot do interfere with what you can do. ~John R. Wooden,, You may have to fight a battle more than once to win it. ~Margaret Thatcher";
//separated by a doublt comma

var quote = "If you want to achieve greatness stop asking for permission. ,, To live a creative life, we must lose our fear of being wrong. ,, Opportunities don’t happen, you create them. ,, I have not failed. I’ve just found 10,000 ways that won’t work. ,, No one can make you feel inferior without your consent. ,, If you’re going through hell keep going. ,, Don’t raise your voice, improve your argument. ,, Don’t be afraid to give up the good to go for the great. ,, No masterpiece was ever created by a lazy artist.,, Do one thing every day that scares you. ,, Your problem isn’t the problem. Your reaction is the problem. ,, You can do anything, but not everything. ,, Innovation distinguishes between a leader and a follower. ,, I find that the harder I work, the more luck I seem to have. ,, The starting point of all achievement is desire. ,, All progress takes place outside the comfort zone. ,, It’s not what you look at that matters, it’s what you see. ,, Fortune sides with him who dares. ,, Failure is the condiment that gives success its flavor. ,, Don’t let what you cannot do interfere with what you can do. ,, You may have to fight a battle more than once to win it.";
var quoteArray = quote.split(',,');

var author = "Anonymous,,Anonymous,,Chris Grosser,,Thomas A. Edison,,Eleanor Roosevelt,,Winston Churchill,,Anonymous,,John D. Rockefeller,, Anonymous,,Anonymous,,Anonymous,,Anonymous,,Steve Jobs,,Thomas Jefferson,,Napolean Hill,,Michael John Bobak,,Anonymous,,Virgil,,Truman Capote,,John R. Wooden,,Margaret Thatcher";
var authorArray = author.split(',,');

var randomNum = function(max) {
    return Math.ceil(Math.random() * max);
}
function getNum() {
    return randomNum(quoteArray.length);
}

//check4mobile
if (isMobile()) {

  $(document).ready(function() {
    $("#controllerImg").on("tap", function(e) {
        e.preventDefault();
        $(".controller").addClass('animated');
        $(".controller").addClass('wobble');
        setTimeout(function() {
            $('.controller').removeClass('animated');
            $(".controller").removeClass('wobble');
        }, 1000);

        let idx = getNum();
        let quoteAt = quoteArray[idx];
        let authorAt = authorArray[idx];
        $(".quoteBox").html("
" + quoteAt + '
' + '
' + "-" + authorAt.fontsize(2) + "
");
    })
});

}
else {

    $(document).ready(function() {
    $("#controllerImg").click(function(e) {
        e.preventDefault();
        $(".controller").addClass('animated');
        $(".controller").addClass('wobble');
        setTimeout(function() {
            $('.controller').removeClass('animated');
            $(".controller").removeClass('wobble');
        }, 1000);

        let idx = getNum();
        let quoteAt = quoteArray[idx];
        let authorAt = authorArray[idx];
        $(".quoteBox").html("
" + quoteAt + '
' + '
' + "-" + authorAt.fontsize(2) + "
");
    })
});

}

function isMobile() {
  if (typeof window.orientation !== 'undefined') {
    return true;
  }
  else {
    return false;
  }
}

$(document).ready(function() {
    $("#controllerImg").click(function(e) {
        e.preventDefault();
        $(".controller").addClass('animated');
        $(".controller").addClass('wobble');
        setTimeout(function() {
            $('.controller').removeClass('animated');
            $(".controller").removeClass('wobble');
        }, 1000);

        let idx = getNum();
        let quoteAt = quoteArray[idx];
        let authorAt = authorArray[idx];
        $(".quoteBox").html("
" + quoteAt + '
' + '
' + "-" + authorAt.fontsize(2) + "
");
    })
});

//power button
$(document).ready(function() {
    $(".brightness-icon").click(function(e) {
    	e.preventDefault();
    	$(".quote-container-col").toggleClass( "bgYellow" );
    	$(".brightness-icon").toggleClass( "greenLtrs" );
    	$(".quoteBox").toggleClass( "darkenBg" );
    	$(".body").toggleClass( "bgBlue" );
    })
});

//api call
$(document).ready(function() {
    $("#controllerImg").click(function(e) {
        e.preventDefault();

        $.getJSON( "http://api.forismatic.com/api/1.0/" + "?callback=?", function( data ) {
            if (json.length != 0){
            alert(data + "success!");
            }
            alert(error);
        })

    })
});

<commit_msg>Update scripts.js<commit_after>var quotesANDauthors = "If you want to achieve greatness stop asking for permission. ~Anonymous,, Things work out best for those who make the best of how things work out. ~John Wooden,, To live a creative life, we must lose our fear of being wrong. ~Anonymous,, If you are not willing to risk the usual you will have to settle for the ordinary. ~Jim Rohn,, Trust because you are willing to accept the risk, not because it’s safe or certain. ~Anonymous,, Take up one idea. Make that one idea your life - think of it, dream of it, live on that idea. Let the brain, muscles, nerves, every part of your body, be full of that idea, and just leave every other idea alone. This is the way to success. ~Swami Vivekananda,, All our dreams can come true if we have the courage to pursue them. ~Walt Disney,, Good things come to people who wait, but better things come to those who go out and get them. ~Anonymous,, If you do what you always did, you will get what you always got. ~Anonymous,, Success is walking from failure to failure with no loss of enthusiasm. ~Winston Churchill,, Just when the caterpillar thought the world was ending, he turned into a butterfly. ~Proverb,, Successful entrepreneurs are givers and not takers of positive energy. ~Anonymous,, Whenever you see a successful person you only see the public glories, never the private sacrifices to reach them. ~Vaibhav Shah,, Opportunities don’t happen, you create them. ~Chris Grosser,, Try not to become a person of success, but rather try to become a person of value. ~Albert Einstein,, Great minds discuss ideas; average minds discuss events; small minds discuss people. ~Eleanor Roosevelt,, I have not failed. I’ve just found 10,000 ways that won’t work. ~Thomas A. Edison,, If you don’t value your time, neither will others. Stop giving away your time and talents- start charging for it. ~Kim Garst,, A successful man is one who can lay a firm foundation with the bricks others have thrown at him. ~David Brinkley,, No one can make you feel inferior without your consent. ~Eleanor Roosevelt,, The whole secret of a successful life is to find out what is one’s destiny to do, and then do it. ~Henry Ford,, If you’re going through hell keep going. ~Winston Churchill,, The ones who are crazy enough to think they can change the world, are the ones that do. ~Anonymous,, Don’t raise your voice, improve your argument. ~Anonymous,, What seems to us as bitter trials are often blessings in disguise.~ Oscar Wilde,, The meaning of life is to find your gift. The purpose of life is to give it away. ~Anonymous,, The distance between insanity and genius is measured only by success. ~Bruce Feirstein,, When you stop chasing the wrong things you give the right things a chance to catch you. ~Lolly Daskal,, Don’t be afraid to give up the good to go for the great. ~John D. Rockefeller,, No masterpiece was ever created by a lazy artist.~ Anonymous,, Happiness is a butterfly, which when pursued, is always beyond your grasp, but which, if you will sit down quietly, may alight upon you. ~Nathaniel Hawthorne,, If you can’t explain it simply, you don’t understand it well enough. ~Albert Einstein,, Blessed are those who can give without remembering and take without forgetting. ~Anonymous,, Do one thing every day that scares you. ~Anonymous,, What’s the point of being alive if you don’t at least try to do something remarkable. ~Anonymous,, Life is not about finding yourself. Life is about creating yourself. ~Lolly Daskal,, Nothing in the world is more common than unsuccessful people with talent. ~Anonymous,, Knowledge is being aware of what you can do. Wisdom is knowing when not to do it. ~Anonymous,, Your problem isn’t the problem. Your reaction is the problem. ~Anonymous,, You can do anything, but not everything. ~Anonymous,, Innovation distinguishes between a leader and a follower. ~Steve Jobs,, There are two types of people who will tell you that you cannot make a difference in this world: those who are afraid to try and those who are afraid you will succeed. ~Ray Goforth,, Thinking should become your capital asset, no matter whatever ups and downs you come across in your life. ~Dr. APJ Kalam,, I find that the harder I work, the more luck I seem to have. ~Thomas Jefferson,, The starting point of all achievement is desire. ~Napolean Hill,, Success is the sum of small efforts, repeated day-in and day-out. ~Robert Collier,, If you want to achieve excellence, you can get there today. As of this second, quit doing less-than-excellent work. ~Thomas J. Watson,, All progress takes place outside the comfort zone. ~Michael John Bobak,, You may only succeed if you desire succeeding; you may only fail if you do not mind failing. ~Philippos,, Courage is resistance to fear, mastery of fear - not absense of fear. ~Mark Twain,, Only put off until tomorrow what you are willing to die having left undone. ~Pablo Picasso,, People often say that motivation doesn’t last. Well, neither does bathing - that’s why we recommend it daily. ~Zig Ziglar,, We become what we think about most of the time, and that’s the strangest secret. ~Earl Nightingale,, The only place where success comes before work is in the dictionary. ~Vidal Sassoon,, The best reason to start an organization is to make meaning; to create a product or service to make the world a better place. ~Guy Kawasaki,, I find that when you have a real interest in life and a curious life, that sleep is not the most important thing. ~Martha Stewart,, It’s not what you look at that matters, it’s what you see. ~Anonymous,, The road to success and the road to failure are almost exactly the same. ~Colin R. Davis,, The function of leadership is to produce more leaders, not more followers. ~Ralph Nader,, Success is liking yourself, liking what you do, and liking how you do it. ~Maya Angelou,, As we look ahead into the next century, leaders will be those who empower others. ~Bill Gates,, A real entrepreneur is somebody who has no safety net underneath them. ~Henry Kravis,, The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself. ~Mark Caine,, People who succeed have momentum. The more they succeed, the more they want to succeed, and the more they find a way to succeed. Similarly, when someone is failing, the tendency is to get on a downward spiral that can even become a self-fulfilling prophecy. ~Tony Robbins,, When I dare to be powerful - to use my strength in the service of my vision, then it becomes less and less important whether I am afraid. ~Audre Lorde,, Whenever you find yourself on the side of the majority, it is time to pause and reflect. ~Mark Twain,, The successful warrior is the average man, with laser-like focus. ~Bruce Lee,, Take up one idea. Make that one idea your life — think of it, dream of it, live on that idea. Let the brain, muscles, nerves, every part of your body, be full of that idea, and just leave every other idea alone. This is the way to success. ~Swami Vivekananda,, Develop success from failures. Discouragement and failure are two of the surest stepping stones to success. ~Dale Carnegie,, If you don’t design your own life plan, chances are you’ll fall into someone else’s plan. And guess what they have planned for you? Not much. ~ Jim Rohn,, If you genuinely want something, don’t wait for it — teach yourself to be impatient. ~Gurbaksh Chahal,, Don’t let the fear of losing be greater than the excitement of winning. ~Robert Kiyosaki,, If you want to make a permanent change, stop focusing on the size of your problems and start focusing on the size of you! ~T. Harv Eker,, You can’t connect the dots looking forward; you can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something - your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life. ~Steve Jobs,, Successful people do what unsuccessful people are not willing to doDon’t wish it were easier, wish you were better. ~Jim Rohn,, The number one reason people fail in life is because they listen to their friends, family, and neighbors. ~Napoleon Hill,, The reason most people never reach their goals is that they don’t define them, or ever seriously consider them as believable or achievable. Winners can tell you where they are going, what they plan to do along the way, and who will be sharing the adventure with them. ~Denis Watiley,, In my experience, there is only one motivation, and that is desire. No reasons or principle contain it or stand against it. ~Jane Smiley,, Success does not consist in never making mistakes but in never making the same one a second time. ~George Bernard Shaw,, I don’t want to get to the end of my life and find that I lived just the length of it. I want to have lived the width of it as well. ~Diane Ackerman,, You must expect great things of yourself before you can do them. ~Michael Jordan,, Motivation is what gets you started. Habit is what keeps you going. ~Jim Ryun,, People rarely succeed unless they have fun in what they are doing. ~Dale Carnegie,, There is no chance, no destiny, no fate, that can hinder or control the firm resolve of a determined soul. ~Ella Wheeler Wilcox,, Our greatest fear should not be of failure but of succeeding at things in life that don’t really matter. ~Francis Chan,, You’ve got to get up every morning with determination if you’re going to go to bed with satisfaction. ~George Lorimer,, To be successful you must accept all challenges that come your way. You can’t just accept the ones you like. ~Mike Gafka,, Success is...knowing your purpose in life, growing to reach your maximum potential, and sowing seeds that benefit others. ~ John C. Maxwell,, Be miserable. Or motivate yourself. Whatever has to be done, it’s always your choice. ~Wayne Dyer,, To accomplish great things, we must not only act, but also dream, not only plan, but also believe.~ Anatole France,, Most of the important things in the world have been accomplished by people who have kept on trying when there seemed to be no help at all. ~Dale Carnegie,, You measure the size of the accomplishment by the obstacles you had to overcome to reach your goals. ~Booker T. Washington,, Real difficulties can be overcome; it is only the imaginary ones that are unconquerable. ~Theodore N. Vail,, It is better to fail in originality than to succeed in imitation. ~Herman Melville,, Fortune sides with him who dares. ~Virgil,, Little minds are tamed and subdued by misfortune; but great minds rise above it. ~Washington Irving,, Failure is the condiment that gives success its flavor. ~Truman Capote,, Don’t let what you cannot do interfere with what you can do. ~John R. Wooden,, You may have to fight a battle more than once to win it. ~Margaret Thatcher";
//separated by a doublt comma

var quote = "If you want to achieve greatness stop asking for permission. ,, To live a creative life, we must lose our fear of being wrong. ,, Opportunities don’t happen, you create them. ,, I have not failed. I’ve just found 10,000 ways that won’t work. ,, No one can make you feel inferior without your consent. ,, If you’re going through hell keep going. ,, Don’t raise your voice, improve your argument. ,, Don’t be afraid to give up the good to go for the great. ,, No masterpiece was ever created by a lazy artist.,, Do one thing every day that scares you. ,, Your problem isn’t the problem. Your reaction is the problem. ,, You can do anything, but not everything. ,, Innovation distinguishes between a leader and a follower. ,, I find that the harder I work, the more luck I seem to have. ,, The starting point of all achievement is desire. ,, All progress takes place outside the comfort zone. ,, It’s not what you look at that matters, it’s what you see. ,, Fortune sides with him who dares. ,, Failure is the condiment that gives success its flavor. ,, Don’t let what you cannot do interfere with what you can do. ,, You may have to fight a battle more than once to win it.";
var quoteArray = quote.split(',,');

var author = "Anonymous,,Anonymous,,Chris Grosser,,Thomas A. Edison,,Eleanor Roosevelt,,Winston Churchill,,Anonymous,,John D. Rockefeller,, Anonymous,,Anonymous,,Anonymous,,Anonymous,,Steve Jobs,,Thomas Jefferson,,Napolean Hill,,Michael John Bobak,,Anonymous,,Virgil,,Truman Capote,,John R. Wooden,,Margaret Thatcher";
var authorArray = author.split(',,');

var randomNum = function(max) {
    return Math.ceil(Math.random() * max);
}
function getNum() {
    return randomNum(quoteArray.length);
}

$(document).ready(function() {
    $("#controllerImg").click(function(e) {
        e.preventDefault();
        $(".controller").addClass('animated');
        $(".controller").addClass('wobble');
        setTimeout(function() {
            $('.controller').removeClass('animated');
            $(".controller").removeClass('wobble');
        }, 1000);

        let idx = getNum();
        let quoteAt = quoteArray[idx];
        let authorAt = authorArray[idx];
        $(".quoteBox").html("
" + quoteAt + '
' + '
' + "-" + authorAt.fontsize(2) + "
");
    })
});

//power button
$(document).ready(function() {
    $(".brightness-icon").click(function(e) {
    	e.preventDefault();
    	$(".quote-container-col").toggleClass( "bgYellow" );
    	$(".brightness-icon").toggleClass( "greenLtrs" );
    	$(".quoteBox").toggleClass( "darkenBg" );
    	$(".body").toggleClass( "bgBlue" );
    })
});

<|endoftext|>


<commit_before>diamondash.components.structures = function() {
  var utils = diamondash.utils;

  function Extendable() {}
  Extendable.extend = Backbone.Model.extend;

  var Eventable = Extendable.extend(Backbone.Events);

  var ColorMaker = Extendable.extend({
    constructor: function(options) {
      options = _({}).defaults(options, this.defaults);
      this.colors = options.scale.domain(d3.range(0, options.n));
      this.i = 0;
    },

    defaults: {
      scale: d3.scale.category10(),
      n: 10
    },

    next: function() {
      return this.colors(this.i++);
    }
  });

  Registry = Eventable.extend({
    constructor: function(items) {
      this.items = {};

      _(items || {}).each(function(data, name) {
        this.add(name, data);
      }, this);
    },

    processAdd: function(name, data) {
      return data;
    },

    processGet: function(name, data) {
      return data;
    },

    add: function(name, data) {
      if (name in this.items) {
        throw new Error("'" + name + "' is already registered.");
      }

      data = this.processAdd(name, data);
      this.trigger('add', name, data);
      this.items[name] = data;
    },

    get: function(name) {
      return this.processGet(name, this.items[name]);
    },

    remove: function(name) {
      var data = this.items[name];
      this.trigger('remove', name, data);
      delete this.items[name];
      return data;
    }
  });

  var ViewSet = Extendable.extend.call(Backbone.ChildViewContainer, {
    keyOf: function(view) {
      return _(view).result('id');
    },

    ensureKey: function(obj) {
      return obj instanceof Backbone.View
        ? this.keyOf(obj)
        : obj;
    },

    get: function(key) {
      return this.findByCustom(key);
    },

    add: function(widget, key) {
      if (typeof key == 'undefined') { key = this.keyOf(widget); }
      return ViewSet.__super__.add.call(this, widget, key);
    },

    remove: function(obj) {
      var widget = this.get(this.ensureKey(obj));
      if (widget) { ViewSet.__super__.remove.call(this, widget); }
      return this;
    },

    each: function(fn, that) {
      that = that || this;

      for (var k in this._indexByCustom) {
        fn.call(that, this.get(k), k);
      }
    }
  });

  ViewSet.extend = Extendable.extend;

  var SubviewSet = ViewSet.extend({
    constructor: function(options) {
      SubviewSet.__super__.constructor.call(this);
      this.parent = options.parent;
    },

    selector: function(key) {
      return key;
    },

    render: function() {
      this.each(function(view, key) {
        view.setElement(this.parent.$(this.selector(key)), true);
      }, this);

      this.apply('render', arguments);
    }
  });

  return {
    Extendable: Extendable,
    Eventable: Eventable,
    Registry: Registry,
    ColorMaker: ColorMaker,
    ViewSet: ViewSet,
    SubviewSet: SubviewSet
  };
}.call(this);
<commit_msg>Allow a SubviewSet's parent instance to be aliased<commit_after>diamondash.components.structures = function() {
  var utils = diamondash.utils;

  function Extendable() {}
  Extendable.extend = Backbone.Model.extend;

  var Eventable = Extendable.extend(Backbone.Events);

  var ColorMaker = Extendable.extend({
    constructor: function(options) {
      options = _({}).defaults(options, this.defaults);
      this.colors = options.scale.domain(d3.range(0, options.n));
      this.i = 0;
    },

    defaults: {
      scale: d3.scale.category10(),
      n: 10
    },

    next: function() {
      return this.colors(this.i++);
    }
  });

  Registry = Eventable.extend({
    constructor: function(items) {
      this.items = {};

      _(items || {}).each(function(data, name) {
        this.add(name, data);
      }, this);
    },

    processAdd: function(name, data) {
      return data;
    },

    processGet: function(name, data) {
      return data;
    },

    add: function(name, data) {
      if (name in this.items) {
        throw new Error("'" + name + "' is already registered.");
      }

      data = this.processAdd(name, data);
      this.trigger('add', name, data);
      this.items[name] = data;
    },

    get: function(name) {
      return this.processGet(name, this.items[name]);
    },

    remove: function(name) {
      var data = this.items[name];
      this.trigger('remove', name, data);
      delete this.items[name];
      return data;
    }
  });

  var ViewSet = Extendable.extend.call(Backbone.ChildViewContainer, {
    keyOf: function(view) {
      return _(view).result('id');
    },

    ensureKey: function(obj) {
      return obj instanceof Backbone.View
        ? this.keyOf(obj)
        : obj;
    },

    get: function(key) {
      return this.findByCustom(key);
    },

    add: function(widget, key) {
      if (typeof key == 'undefined') { key = this.keyOf(widget); }
      return ViewSet.__super__.add.call(this, widget, key);
    },

    remove: function(obj) {
      var widget = this.get(this.ensureKey(obj));
      if (widget) { ViewSet.__super__.remove.call(this, widget); }
      return this;
    },

    each: function(fn, that) {
      that = that || this;

      for (var k in this._indexByCustom) {
        fn.call(that, this.get(k), k);
      }
    }
  });

  ViewSet.extend = Extendable.extend;

  var SubviewSet = ViewSet.extend({
    parentAlias: 'parent',

    constructor: function(options) {
      SubviewSet.__super__.constructor.call(this);

      this.parent = options[this.parentAlias];
      this[this.parentAlias] = this.parent;
    },

    selector: function(key) {
      return key;
    },

    render: function() {
      this.each(function(view, key) {
        view.setElement(this.parent.$(this.selector(key)), true);
      }, this);

      this.apply('render', arguments);
    }
  });

  return {
    Extendable: Extendable,
    Eventable: Eventable,
    Registry: Registry,
    ColorMaker: ColorMaker,
    ViewSet: ViewSet,
    SubviewSet: SubviewSet
  };
}.call(this);
<|endoftext|>