<commit_before>
var Zoo = {

    nodes: null, // The total list of all nodes
    meta: null, // The database-specific functions
    tags: null, // The list of all tags

    // Initialize the zoo once for all
    init: function() {
        this.initPanel();
        Filter.init();
        Contextmenu.init();

        var data = this.getUrlData();
        if(data.zoo) {
            $('#zoo select').val(data.zoo);
        }
        $('#zoo select').trigger('change');
    },

    initPanel: function() {

        // Make the parts collapsible
        $('#panel legend').click(function() {
            $(this).next().toggle('blind', {'direction': 'up'});
        });

    },

    // Call Mathjax if necessary to compute the size of nodes
    // And the div object, and then call the callback function
    getNodesSize: function(nodes, callback) {
        var size = $('#size');
        var hasElements = false;
        for(var key in nodes) {
            if(nodes[key].size) continue;
            hasElements = true;
            size.append('
' + nodes[key].label + '
');
        }
        if(!hasElements) {
            callback.call(this);
            return;
        }

        if(!this.computingSize)
            MathJax.Hub.Queue(["Typeset",MathJax.Hub, size.get(0)]);
        this.computingSize = true;
        MathJax.Hub.Queue(function() {
            // Get the size of each node
            for(var key in nodes) {
                if(nodes[key].size) continue;
                var div = $('#size_' + Tools.escapeChars(key));
                nodes[key].size = { width: div.width(), height: div.height() };
                nodes[key].div = div;
                div.remove();
            }
            Zoo.computingSize = false;
            callback.call(this);
        });
    },

    getUrlData() {
        var url = window.location.href;
        if(url.indexOf('#') == -1) return {};
        return JSON.parse(url.substring(url.indexOf("#")+1));
    },

    setUrlData(data) {
        window.location.href = '#' + JSON.stringify(data);
    },

    load: function(value) {
        if(value == 'custom') {
            $('#zoo p + p input').get(0).value = '';
            $('#zoo p + p').show();
        }
        else {
            $('#zoo p + p').hide();
            this.loadUrl(value);
        }
    },

    loadLocal: function(files) {
        var file = files[0];
        var fr = new FileReader();
        fr.onload = function() {
            Zoo.loadUrl(fr.result);
        };
        fr.readAsDataURL(file);
    },

    loadUrl: function(zooUrl) {

        var urlData = this.getUrlData();
        if(urlData.zoo != zooUrl) {
            this.setUrlData({ zoo : zooUrl });
        }
        this.disablePanel();
        $.getJSON(zooUrl, function(zoo) { Zoo.create(zoo) });
    },

    // Create the zoo from a database
    create: function(zoo) {

        this.nodes = zoo.nodes;

        // Extracts tags out of nodes
        this.tags = {};
        for(var key in zoo.nodes) {
            for(var i=0; i<zoo.nodes[key].tags.length; i++) {
                this.tags[zoo.nodes[key].tags[i]] = true;
            }
        }

        // Transform meta into functions
        this.initMeta(zoo.meta);

        // Format nodes
        for(var src in zoo.nodes) {
            var node = zoo.nodes[src];
            node.key = src;
            node.label = Tools.toTex(node.label);
            for(var dest in node.edges) {
                node.edges[dest].src = node;
                node.edges[dest].dest = zoo.nodes[dest];
            }
        }

        this.createPanel();

        // Draw a new graph
        this.newGraph();

    },

    initMeta : function(meta) {
        if(!meta) {
            meta = {};
        }

        // Init the edges part
        if(!meta.edgeKinds) {
            meta.edgeKinds = [];
        }
        meta.selectedEdgeKind = 0;
        if(!meta.edgeKinds.length) {
            meta.edgeKinds.push({
                                "label" : "Implication",
                                "functionBody" : "if(!edge.properties.implication) return 2; return edge.properties.implication.value ? 1 : 0;"
            });
        }
        for(var i=0; i<meta.edgeKinds.length; i++) {
            meta.edgeKinds[i].func = new Function('edge', 'context', meta.edgeKinds[i].functionBody);
        }

        // Init the colorings part
        if(!meta.colorings) {
            meta.colorings = [];
        }
        meta.selectedColoring = 0;
        if(!meta.colorings.length) {
            meta.colorings.push({
                                "label" : "By category",
                                "colors" : [ {color: "lightblue", label: "Default category"},
                                            { color: "lightgreen", label:  "Non-default category"} ],
                "coloring" : "return node.tags.indexOf('default') == -1 ? 'lightgreen' : 'lightblue';"
            });
        }
        for(var i=0; i<meta.colorings.length; i++) {
            meta.colorings[i].coloring = new Function('node', 'context', meta.colorings[i].coloring);
        }

        meta.colorings.push(Select.coloring);

        this.meta = meta;
    },

    // Draw a new graph
    newGraph: function() {
        Graph.init({
           meta: {
               filterEdge: this.meta.edgeKinds[this.meta.selectedEdgeKind].func,
               colorNode: this.meta.colorings[this.meta.selectedColoring].coloring,
               graphviz: $.extend(true, {
                    rankdir: 'TB'
               }, this.meta.graphviz)
           },
           finished: function() { Zoo.enablePanel() }
       });
    },

    nodesToKeys: function(nodes) {
        var keys = [];
        for(var i=0; i<nodes.length; i++) {
            keys.push(nodes[i].key);
        }
        return keys;
    },

    keysToNodes: function(keys) {
        var nodes = [];
        for(var i=0; i<keys.length; i++) {
            nodes.push(this.nodes[keys[i]]);
        }
        return nodes;
    },

    createPanel: function() {

        this.createLegend();

        // Init the filters
        Filter.initDatabase();
    },

    // Init the legend panel
    // Call it once per database
    createLegend: function() {

        var urlData = this.getUrlData();
        var edgeNode  = $('#edge_function select');
        edgeNode.empty();
        for(var i=0; i<this.meta.edgeKinds.length; i++) {
            edgeNode.append('<option value="' + i + '">' + this.meta.edgeKinds[i].label + '</option>');
        }
        if(typeof urlData.edgeKind != 'undefined') {
            edgeNode.val(urlData.edgeKind);
            this.meta.selectedEdgeKind = urlData.edgeKind;
        }

        var coloringNode = $('#coloring_function select');
        coloringNode.removeAttr('disabled');
        coloringNode.empty();
        for(var i=0; i<this.meta.colorings.length-1; i++) {
            coloringNode.append('<option value="' + i + '">' + this.meta.colorings[i].label + '</option>');
        }
        if(typeof urlData.coloring != 'undefined') {
            coloringNode.val(urlData.coloring);
            this.meta.selectedColoring = urlData.coloring;
        }

        this.updateColoringLegend();

    },

    disablePanel: function() {
        $('#block').show();

    },

    enablePanel: function() {
        $('#block').hide();
    },

    changeEdgeKind: function(key) {
        this.meta.selectedEdgeKind = key;
        var urlData = this.getUrlData();
        urlData.edgeKind = key;
        this.setUrlData(urlData);
        this.newGraph();
    },

    changeColoring: function(key) {
        this.meta.selectedColoring = key;
        this.updateColoringLegend();
        if(!Select.hasSelectedNodes()) {
            var urlData = this.getUrlData();
            urlData.coloring = key;
            this.setUrlData(urlData);
        }
        Graph.setColoring(this.meta.colorings[this.meta.selectedColoring].coloring);
    },

    updateColoringLegend: function() {
        var ul = $('#coloring_function + ul');
        var coloring = this.meta.colorings[this.meta.selectedColoring];
        ul.empty();
        for(var i=0; i<coloring.colors.length; i++) {
            var background = coloring.colors[i].color;
            if(background.indexOf(':') != -1) {
                var c = background.split(':');
                background = 'repeating-linear-gradient(125deg,' + c[0] + ',' + c[0] + ' 2px,' + c[1] + ' 2px,' + c[1] + ' 4px);';
            }
            ul.append('

 ' + coloring.colors[i].label + '');
        }
    }
};

<commit_msg>Fixed a bug.<commit_after>
var Zoo = {

    nodes: null, // The total list of all nodes
    meta: null, // The database-specific functions
    tags: null, // The list of all tags

    // Initialize the zoo once for all
    init: function() {
        this.initPanel();
        Filter.init();
        Contextmenu.init();

        var data = this.getUrlData();
        if(data.zoo) {
            $('#zoo select').val(data.zoo);
        }
        $('#zoo select').trigger('change');
    },

    initPanel: function() {

        // Make the parts collapsible
        $('#panel legend').click(function() {
            $(this).next().toggle('blind', {'direction': 'up'});
        });

    },

    // Call Mathjax if necessary to compute the size of nodes
    // And the div object, and then call the callback function
    getNodesSize: function(nodes, callback) {
        var size = $('#size');
        var hasElements = false;
        for(var key in nodes) {
            if(nodes[key].size) continue;
            hasElements = true;
            size.append('
' + nodes[key].label + '
');
        }
        if(!hasElements) {
            callback.call(this);
            return;
        }

        if(!this.computingSize)
            MathJax.Hub.Queue(["Typeset",MathJax.Hub, size.get(0)]);
        this.computingSize = true;
        MathJax.Hub.Queue(function() {
            // Get the size of each node
            for(var key in nodes) {
                if(nodes[key].size) continue;
                var div = $('#size_' + Tools.escapeChars(key));
                nodes[key].size = { width: div.width(), height: div.height() };
                nodes[key].div = div;
                div.remove();
            }
            Zoo.computingSize = false;
            callback.call(this);
        });
    },

    getUrlData() {
        var url = decodeURIComponent(window.location.href);
        if(url.indexOf('#') == -1) return {};
        return JSON.parse(url.substring(url.indexOf("#")+1));
    },

    setUrlData(data) {
        window.location.href = '#' + JSON.stringify(data);
    },

    load: function(value) {
        if(value == 'custom') {
            $('#zoo p + p input').get(0).value = '';
            $('#zoo p + p').show();
        }
        else {
            $('#zoo p + p').hide();
            this.loadUrl(value);
        }
    },

    loadLocal: function(files) {
        var file = files[0];
        var fr = new FileReader();
        fr.onload = function() {
            Zoo.loadUrl(fr.result);
        };
        fr.readAsDataURL(file);
    },

    loadUrl: function(zooUrl) {

        var urlData = this.getUrlData();
        if(urlData.zoo != zooUrl) {
            this.setUrlData({ zoo : zooUrl });
        }
        this.disablePanel();
        $.getJSON(zooUrl, function(zoo) { Zoo.create(zoo) });
    },

    // Create the zoo from a database
    create: function(zoo) {

        this.nodes = zoo.nodes;

        // Extracts tags out of nodes
        this.tags = {};
        for(var key in zoo.nodes) {
            for(var i=0; i<zoo.nodes[key].tags.length; i++) {
                this.tags[zoo.nodes[key].tags[i]] = true;
            }
        }

        // Transform meta into functions
        this.initMeta(zoo.meta);

        // Format nodes
        for(var src in zoo.nodes) {
            var node = zoo.nodes[src];
            node.key = src;
            node.label = Tools.toTex(node.label);
            for(var dest in node.edges) {
                node.edges[dest].src = node;
                node.edges[dest].dest = zoo.nodes[dest];
            }
        }

        this.createPanel();

        // Draw a new graph
        this.newGraph();

    },

    initMeta : function(meta) {
        if(!meta) {
            meta = {};
        }

        // Init the edges part
        if(!meta.edgeKinds) {
            meta.edgeKinds = [];
        }
        meta.selectedEdgeKind = 0;
        if(!meta.edgeKinds.length) {
            meta.edgeKinds.push({
                                "label" : "Implication",
                                "functionBody" : "if(!edge.properties.implication) return 2; return edge.properties.implication.value ? 1 : 0;"
            });
        }
        for(var i=0; i<meta.edgeKinds.length; i++) {
            meta.edgeKinds[i].func = new Function('edge', 'context', meta.edgeKinds[i].functionBody);
        }

        // Init the colorings part
        if(!meta.colorings) {
            meta.colorings = [];
        }
        meta.selectedColoring = 0;
        if(!meta.colorings.length) {
            meta.colorings.push({
                                "label" : "By category",
                                "colors" : [ {color: "lightblue", label: "Default category"},
                                            { color: "lightgreen", label:  "Non-default category"} ],
                "coloring" : "return node.tags.indexOf('default') == -1 ? 'lightgreen' : 'lightblue';"
            });
        }
        for(var i=0; i<meta.colorings.length; i++) {
            meta.colorings[i].coloring = new Function('node', 'context', meta.colorings[i].coloring);
        }

        meta.colorings.push(Select.coloring);

        this.meta = meta;
    },

    // Draw a new graph
    newGraph: function() {
        Graph.init({
           meta: {
               filterEdge: this.meta.edgeKinds[this.meta.selectedEdgeKind].func,
               colorNode: this.meta.colorings[this.meta.selectedColoring].coloring,
               graphviz: $.extend(true, {
                    rankdir: 'TB'
               }, this.meta.graphviz)
           },
           finished: function() { Zoo.enablePanel() }
       });
    },

    nodesToKeys: function(nodes) {
        var keys = [];
        for(var i=0; i<nodes.length; i++) {
            keys.push(nodes[i].key);
        }
        return keys;
    },

    keysToNodes: function(keys) {
        var nodes = [];
        for(var i=0; i<keys.length; i++) {
            nodes.push(this.nodes[keys[i]]);
        }
        return nodes;
    },

    createPanel: function() {

        this.createLegend();

        // Init the filters
        Filter.initDatabase();
    },

    // Init the legend panel
    // Call it once per database
    createLegend: function() {

        var urlData = this.getUrlData();
        var edgeNode  = $('#edge_function select');
        edgeNode.empty();
        for(var i=0; i<this.meta.edgeKinds.length; i++) {
            edgeNode.append('<option value="' + i + '">' + this.meta.edgeKinds[i].label + '</option>');
        }
        if(typeof urlData.edgeKind != 'undefined') {
            edgeNode.val(urlData.edgeKind);
            this.meta.selectedEdgeKind = urlData.edgeKind;
        }

        var coloringNode = $('#coloring_function select');
        coloringNode.removeAttr('disabled');
        coloringNode.empty();
        for(var i=0; i<this.meta.colorings.length-1; i++) {
            coloringNode.append('<option value="' + i + '">' + this.meta.colorings[i].label + '</option>');
        }
        if(typeof urlData.coloring != 'undefined') {
            coloringNode.val(urlData.coloring);
            this.meta.selectedColoring = urlData.coloring;
        }

        this.updateColoringLegend();

    },

    disablePanel: function() {
        $('#block').show();

    },

    enablePanel: function() {
        $('#block').hide();
    },

    changeEdgeKind: function(key) {
        this.meta.selectedEdgeKind = key;
        var urlData = this.getUrlData();
        urlData.edgeKind = key;
        this.setUrlData(urlData);
        this.newGraph();
    },

    changeColoring: function(key) {
        this.meta.selectedColoring = key;
        this.updateColoringLegend();
        if(!Select.hasSelectedNodes()) {
            var urlData = this.getUrlData();
            urlData.coloring = key;
            this.setUrlData(urlData);
        }
        Graph.setColoring(this.meta.colorings[this.meta.selectedColoring].coloring);
    },

    updateColoringLegend: function() {
        var ul = $('#coloring_function + ul');
        var coloring = this.meta.colorings[this.meta.selectedColoring];
        ul.empty();
        for(var i=0; i<coloring.colors.length; i++) {
            var background = coloring.colors[i].color;
            if(background.indexOf(':') != -1) {
                var c = background.split(':');
                background = 'repeating-linear-gradient(125deg,' + c[0] + ',' + c[0] + ' 2px,' + c[1] + ' 2px,' + c[1] + ' 4px);';
            }
            ul.append('

 ' + coloring.colors[i].label + '');
        }
    }
};

<|endoftext|>


<commit_before>// Switch to results view
//PD_vote8374733(1);

var voteCount = 0;

var voteUrl = "http://static.polldaddy.com/p/8374733.js";
var messageEl = _$("message");
var lastAttemptEl = _$("last-attempt");
var nextAttemptEl = _$("next-attempt");

var isAutoVoteAttempt = false;

function doVote() {
  // Switch to vote view
  PDV_go8374733();

  // Reset cookies
  PD_ck8374733 = 0;
  docCookies.removeAll();

  isAutoVoteAttempt = true;

  var POLL_ID = 8374733;

  var answerArr = window['PDV_A' + POLL_ID];
  var answer = "";
  for (var i = 0; i < answerArr.length; ++i) {
    if (answerArr[i][1] === 'Washington State') {
      answer = answerArr[1][0];
    }
  }

  if (answer == "") {
    messageEl.textContent = "Something broke :( Where's the WSU option?";
    lastAttemptEl = "";
    nextAttemptEl = "";
  } else {
    _$("PDI_answer" + answer).checked = true;
    var blob = {pageX: 100, pageY: 100};

    PD_prevote8374733(blob);
  }
}

var pd_callback = function(resultString) {
  var jsonR = JSON.parse(resultString);
  if (jsonR["result"] !== "load") {
    if (jsonR["result"] === "registered") {
      ++voteCount;
    }

    // Prevent overly clicky people from screwing things up
    if (isAutoVoteAttempt) {
      timeOut();
    }

    messageEl.textContent = voteCount + " successful Coug votes made....Go Cougs!";
    lastAttemptEl.textContent = "Last attempt made at " + simplyTime(new Date(Date.now()));
  }
}

function timeOut() {
  var hourMillis = 1 * 60 * 60 * 1000;
  var date = new Date(Date.now() + hourMillis);
  nextAttemptEl.textContent = "Next attempt at " + simplyTime(date);
  setTimeout(doVote, hourMillis);
}

function simplyTime(date) {
  return date.toLocaleTimeString();
}

// Source: developer.mozilla.org/en-US/docs/Web/API/document.cookie
var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    //if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    //return true;
  },
  removeAll: function() {
    var outSide = this;
    this.keys().forEach(function(item) {
      outSide.removeItem(item, '/');
    });
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

doVote();

<commit_msg>Cookie added to keep track of votes over browser refreshes<commit_after>// Cookie parser
// Source: developer.mozilla.org/en-US/docs/Web/API/document.cookie
var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  removeAll: function() {
    var outSide = this;
    this.keys().forEach(function(item) {
      outSide.removeItem(item, '/');
    });
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

// Switch to results view
//PD_vote8374733(1);

var voteUrl = "http://static.polldaddy.com/p/8374733.js";
var messageEl = _$("message");
var lastAttemptEl = _$("last-attempt");
var nextAttemptEl = _$("next-attempt");

var isAutoVoteAttempt = false;
var voteCount = parseInt(docCookies.getItem('vote-count') || 0);

function doVote() {
  // Switch to vote view
  PDV_go8374733();

  // Reset cookies
  PD_ck8374733 = 0;
  docCookies.removeItem(PD_ck_name8374733 + "_" + PDV_version8374733);

  isAutoVoteAttempt = true;

  var POLL_ID = 8374733;

  var answerArr = window['PDV_A' + POLL_ID];
  var answer = "";
  for (var i = 0; i < answerArr.length; ++i) {
    if (answerArr[i][1] === 'Washington State') {
      answer = answerArr[1][0];
    }
  }

  if (answer == "") {
    messageEl.textContent = "Something broke :( Where's the WSU option?";
    lastAttemptEl = "";
    nextAttemptEl = "";
  } else {
    _$("PDI_answer" + answer).checked = true;
    var blob = {pageX: 100, pageY: 100};

    PD_prevote8374733(blob);
  }
}

function pd_callback(resultString) {
  var jsonR = JSON.parse(resultString);
  if (jsonR["result"] !== "load") {
    if (jsonR["result"] === "registered") {
      ++voteCount;
      docCookies.setItem('vote-count', voteCount, Infinity);
    }

    // Prevent overly clicky people from screwing things up
    if (isAutoVoteAttempt) {
      timeOut();
    }

    messageEl.textContent = voteCount + " successful Coug votes made....Go Cougs!";
    lastAttemptEl.textContent = "Last attempt made at " + simplyTime(new Date(Date.now()));
  }
}

function timeOut() {
  var hourMillis = 1 * 60 * 60 * 1000;
  var date = new Date(Date.now() + hourMillis);
  nextAttemptEl.textContent = "Next attempt at " + simplyTime(date);
  setTimeout(doVote, hourMillis);
}

function simplyTime(date) {
  return date.toLocaleTimeString();
}

doVote();

<|endoftext|>


<commit_before><commit_msg>re-added mocha test to test task<commit_after><|endoftext|>


<commit_before><commit_msg>disable cache for imagemin task<commit_after><|endoftext|>


<commit_before><commit_msg>updated travis<commit_after><|endoftext|>


<commit_before><commit_msg>Added more .js options to builds<commit_after><|endoftext|>


<commit_before><commit_msg>finish<commit_after><|endoftext|>


<commit_before><commit_msg>update grunt task for material unicode<commit_after><|endoftext|>


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

require("prototype");

var Launcher = $prototype(null);

Launcher.setTooltip = function(tooltip)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.setTooltip", tooltip || "");
}

Launcher.setActions = function(actions)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.setActions", actions);
}

Launcher.removeActions = function(actions)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.removeActions", actions);
}

Launcher.addAction = function(action)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.addAction", action);
}

Launcher.removeAction = function(action)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.removeAction", action);
}

// export public items
Nuvola.Launcher = Launcher;
Nuvola.launcher = $object(Launcher);
<commit_msg>Fix Launcher.removeActions signature<commit_after>/*
 * Copyright 2014 Jiří Janoušek <janousek.jiri@gmail.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 *    list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

require("prototype");

var Launcher = $prototype(null);

Launcher.setTooltip = function(tooltip)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.setTooltip", tooltip || "");
}

Launcher.setActions = function(actions)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.setActions", actions);
}

Launcher.removeActions = function()
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.removeActions");
}

Launcher.addAction = function(action)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.addAction", action);
}

Launcher.removeAction = function(action)
{
	Nuvola._sendMessageAsync("Nuvola.Launcher.removeAction", action);
}

// export public items
Nuvola.Launcher = Launcher;
Nuvola.launcher = $object(Launcher);
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */

(function(scope) {

  // imports

  var log = window.logFlags || {};
  var EVENT_PREFIX = 'on-';

  // instance events api
  var events = {
    // read-only
    EVENT_PREFIX: EVENT_PREFIX,
    // event listeners on host
    addHostListeners: function() {
      var events = this.eventDelegates;
      log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events);
      // NOTE: host events look like bindings but really are not;
      // (1) we don't want the attribute to be set and (2) we want to support
      // multiple event listeners ('host' and 'instance') and Node.bind
      // by default supports 1 thing being bound.
      for (var type in events) {
        var methodName = events[type];
        PolymerGestures.addEventListener(this, type, this.element.getEventHandler(this, this, methodName));
      }
    },
    // call 'method' or function method on 'obj' with 'args', if the method exists
    dispatchMethod: function(obj, method, args) {
      if (obj) {
        log.events && console.group('[%s] dispatch [%s]', obj.localName, method);
        var fn = typeof method === 'function' ? method : obj[method];
        if (fn) {
          fn[args ? 'apply' : 'call'](obj, args);
        }
        log.events && console.groupEnd();
        Platform.flush();
      }
    }
  };

  // exports

  scope.api.instance.events = events;

  // alias PolymerGestures event listener logic
  scope.addEventListener = PolymerGestures.addEventListener;
  scope.removeEventListener = PolymerGestures.removeEventListener;

})(Polymer);
<commit_msg>Wrap nodes before calling PolymerGestures.addEventListener and removeEventListener<commit_after>/*
 * Copyright (c) 2014 The Polymer Project Authors. All rights reserved.
 * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
 * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
 * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
 * Code distributed by Google as part of the polymer project is also
 * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
 */

(function(scope) {

  // imports

  var log = window.logFlags || {};
  var EVENT_PREFIX = 'on-';

  // instance events api
  var events = {
    // read-only
    EVENT_PREFIX: EVENT_PREFIX,
    // event listeners on host
    addHostListeners: function() {
      var events = this.eventDelegates;
      log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events);
      // NOTE: host events look like bindings but really are not;
      // (1) we don't want the attribute to be set and (2) we want to support
      // multiple event listeners ('host' and 'instance') and Node.bind
      // by default supports 1 thing being bound.
      for (var type in events) {
        var methodName = events[type];
        PolymerGestures.addEventListener(this, type, this.element.getEventHandler(this, this, methodName));
      }
    },
    // call 'method' or function method on 'obj' with 'args', if the method exists
    dispatchMethod: function(obj, method, args) {
      if (obj) {
        log.events && console.group('[%s] dispatch [%s]', obj.localName, method);
        var fn = typeof method === 'function' ? method : obj[method];
        if (fn) {
          fn[args ? 'apply' : 'call'](obj, args);
        }
        log.events && console.groupEnd();
        Platform.flush();
      }
    }
  };

  // exports

  scope.api.instance.events = events;

  // alias PolymerGestures event listener logic
  scope.addEventListener = function(node, eventType, handlerFn, capture) {
    PolymerGestures.addEventListener(wrap(node), eventType, handlerFn, capture);
  };
  scope.removeEventListener = function(node, eventType, handlerFn, capture) {
    PolymerGestures.removeEventListener(wrap(node), eventType, handlerFn, capture);
  };

})(Polymer);
<|endoftext|>


<commit_before>/*global NMTdata,window*/
/***
 * Provides data and methods for serving ads.
 * @author: Duane.Jennings@niit-mediatech.com
 * @version: 201507260903:443263
 *
 */
var NMTdata = NMTdata || {};

    NMTdata.ads = (function () {
        // REQUIRES: NMTdata.data module to be loaded prior to this module.
        // ads related methods and properties.
        if(!window.console){
            console={};
            console.log = function(){};
        }
        console.log("NMTdata.ads init");

        var data = NMTdata.data,
        adunitPrefixDomainMappings = new Array(),
        adunitPrefixURLMappings = new Array(),
        adunitPathMappings = new Array(),
        adunitURLMappings = new Array(),
        cccPathMappings = new Array(),
        cccURLMappings = new Array(),
        i = 0,
        mmo_ccc = '',
        mmo_console = '',
        pathlength = 0,
        maxAdunitPathLength = 3,  // limit the adunit path elements.
        dfp_adunit_prefix = '', // example: /11365842/peninsulaclarion.com
        dfp_adunit = '', // example: /news/local
		dfp_ccc = ''; // customTargeting value

        // AdPay global variable for classifieds category.
        if (typeof paperCategoryID == 'undefined') paperCategoryID = 'classifieds';

////////////////////////////////////////////////////////////////////////
/***
 * mapping_version: 201603221057:443265
 */
dfp_adunit_prefix = '/11365842/savannahnow.com';
        adunitPrefixDomainMappings = [
                                      // These mappings will do a contains match against domain host.
                                      // MBU custom mappings
                                      {'msms\.savannahnow\.com': '/11365842/msms.savannahnow.com'},
                                      {'dev\.savannahnow\.com': '/11365842/msms.savannahnow.com'},
                                      {'qa\.savannahnow\.com': '/11365842/msms.savannahnow.com'},
                                      {'autos\.coastalautos\.com': '/11365842/savannahnow.com/autos'},
                                      {'bis\.yelvington\.com': '/11365842/businessinsavannah.com'},
                                      {'businessinsavannah\.com': '/11365842/businessinsavannah.com'},
                                      {'classifieds\.savannahnow\.com': '/11365842/savannahnow.com/classifieds'},
                                      {'class\.savannahnow\.com': '/11365842/savannahnow.com/classifieds'},
                                      {'coastalmommies\.com': '/11365842/coastalmommies.com'},
                                      {'^dining\.savannahnow\.com': '/11365842/savannahnow.com/diningguide'},
                                      {'dosavannah\.com': '/11365842/savannahnow.com/entertainment'},
                                      {'events\.savannahnow\.com': '/11365842/savannahnow.com/events'},
                                      {'giftguide\.': '/11365842/giftguide.savannahnow.com'},
                                      {'health\.': '/11365842/savannahnow.com/health'},
                                      {'physicianguide\.': '/11365842/savannahnow.com/physicianguide'},
                                      {'^m\.savannahnow\.com': '/11365842/m.savannahnow.com'},
                                      {'^m\.pfsav': '/11365842/m.savannahnow.com'},
                                      {'^www\.jaspersuntimes\.com': '/11365842/savannahnow.com/jaspersuntimes'},
                                      {'jaspercountysun\.com': '/11365842/savannahnow.com/jaspersuntimes'},
                                      {'jobs\.savannahnow\.com': '/11365842/savannahnow.com/jobs'},
                                      {'savannahhomesforsale\.com': '/11365842/savannahhomesforsale.com'},
                                      {'savannahmagazine\.com': '/11365842/savannahmagazine.com'},
                                      {'spotted\.savannahnow\.com': '/11365842/savannahnow.com/spotted'},
                                      {'rentals\.savannahnow\.com': '/11365842/savannahnow.com/rentals'},
                                      {'thebootandjetstream\.com': '/11365842/thebootandjetstream.com'},
                                      {'weddings\.savannahmagazine\.com': '/11365842/savannahmagazine.com/weddings'},
                                      {'legacy\.com': '/11365842/savannahnow.com/obits'}
                              ];

        adunitPathMappings = [
                              // MBU custom mappings
                              {'^\/fast-physicianguide.php': '/physicianguide'},
                              // Common mappings
                              {'^\/homepageSMN$': '/homepage'}
                      ];

adunitPathMappings.push({'\/effinghamnow$': '/effinghamnow/homepage'});
adunitPathMappings.push({'\/bryancountynow$': '/bryancountynow/homepage'});

        cccPathMappings = [
                           // MBU custom mappings
                           {'^\/homepageSMN$': 'homepage'}
                   ];
/***
 * common mappings: 201504241333:447642
 */
        adunitURLMappings.push({'\.adpay\.com': '/classifieds'});

        adunitPathMappings.push({'^\/home$': '/homepage'});
        adunitPathMappings.push({'^\/home/am$': '/homepage'});
        adunitPathMappings.push({'^\/home/pm$': '/homepage'});
        adunitPathMappings.push({'^\/index$': '/homepage'});
        adunitPathMappings.push({'^\/$': '/homepage'});

        cccURLMappings.push({'\/clicknbuy\.aspx': NMTdata.data.getQueryParam("pcatid") || paperCategoryID});
        cccURLMappings.push({'\/searchresults\.aspx': NMTdata.data.getQueryParam("pcatid") || paperCategoryID});

        cccURLMappings.push({'spotted.+\/mediadetail\/': NMTdata.data.getQueryParam("gId")});
        cccURLMappings.push({'spotted.+\/galleries\?': NMTdata.data.getQueryParam("groupId")});
        adunitURLMappings.push({'adiciotest\.': '/homes'});

        cccPathMappings.push({'^\/$': 'homepage'});
////////////////////////////////////////////////////////////////////////

        // Process domain mapping for dfp_adunit_prefix
        dfp_adunit_prefix = data.processMapping(adunitPrefixDomainMappings, location.host, dfp_adunit_prefix);

        // Process URL mapping for dfp_adunit_prefix
        dfp_adunit_prefix = data.processMapping(adunitPrefixURLMappings, document.URL, dfp_adunit_prefix);

        // build dfp_adunit default value
        // Limit adunit to 3 path elements.
        pathlength = (data.pathnames.length > maxAdunitPathLength) ? maxAdunitPathLength : data.pathnames.length;
        for (i = 0; i < pathlength; i++) {
            if (data.pathnames[i] !== '') {
                dfp_adunit += '/' + data.pathnames[i].slice(0,100);
            }
        }

        // Process Path mappings for dfp_adunit
        dfp_adunit = data.processMapping(adunitPathMappings, window.location.pathname, dfp_adunit);
        // Process URL mappings for dfp_adunit
        dfp_adunit = data.processMapping(adunitURLMappings, document.URL, dfp_adunit);

        // dfp_ccc default value
        // Paths that have trailing slash will leave the last path element empty.
        // Let's check for this case and go back one more for the ccc value.
        if (data.pathnames.length > 1 && data.pathnames[data.pathnames.length-1] == '') {
            dfp_ccc = data.pathnames[data.pathnames.length - 2];
        } else {
            dfp_ccc = data.pathnames[data.pathnames.length - 1];
        }

        // Process Path mappings for dfp_ccc
        dfp_ccc = data.processMapping(cccPathMappings, window.location.pathname, dfp_ccc);
        // Process URL mappings for dfp_ccc
        dfp_ccc = data.processMapping(cccURLMappings, document.URL, dfp_ccc);

        // override dfp_ccc with query_string mmo_ccc
        mmo_ccc = data.getQueryParam('mmo_ccc');
        if (mmo_ccc !== undefined) { dfp_ccc = mmo_ccc; }

        // Google DFP has 40 character limit on targeting values.
        dfp_ccc = dfp_ccc.slice(0,40);

        // Google DFP does not allow certain characters for adunit values.
        dfp_adunit = dfp_adunit.replace(/\s/g, '-');
        dfp_adunit = dfp_adunit.replace(/%20/g, '-');
        dfp_adunit = dfp_adunit.replace(/,/g, '-');
        dfp_adunit = dfp_adunit.replace(/%2C/g, '-');
        dfp_adunit = dfp_adunit.replace(/'/g, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(/%/g, '');

        // output debug information to console
        mmo_console = data.getQueryParam('google_console');
        if (mmo_console !== undefined) {
            console.log("NMTdata.ads.dfp_adunit_prefix: "+dfp_adunit_prefix);
            console.log("NMTdata.ads.dfp_adunit: "+dfp_adunit);
            console.log("DFP AdUnit: "+dfp_adunit_prefix+dfp_adunit);
            console.log("NMTdata.ads.dfp_ccc: "+dfp_ccc);
        }

        // output debug information to console
        mmo_console = data.getQueryParam('nmt_console');
        if (mmo_console !== undefined) {
            document.write("
NMTdata.ads.dfp_adunit_prefix: "+dfp_adunit_prefix);
            document.write("
NMTdata.ads.dfp_adunit: "+dfp_adunit);
            document.write("
DFP AdUnit: "+dfp_adunit_prefix+dfp_adunit);
            document.write("
NMTdata.ads.dfp_ccc: "+data.escapeHtml(dfp_ccc));
        }

        return { // return object
            dfp_nmt_mapping_version: '201603221057:443265',
            dfp_nmt_ads_version: '201507260903:443263',
            dfp_adunit_prefix: dfp_adunit_prefix,
            dfp_adunit: dfp_adunit,
            dfp_ccc: data.escapeHtml(dfp_ccc)
        };

    }());

<commit_msg>Adjusted mapping order for weddings.savannahmagazine.com<commit_after>/*global NMTdata,window*/
/***
 * Provides data and methods for serving ads.
 * @author: Duane.Jennings@niit-mediatech.com
 * @version: 201507260903:443263
 *
 */
var NMTdata = NMTdata || {};

    NMTdata.ads = (function () {
        // REQUIRES: NMTdata.data module to be loaded prior to this module.
        // ads related methods and properties.
        if(!window.console){
            console={};
            console.log = function(){};
        }
        console.log("NMTdata.ads init");

        var data = NMTdata.data,
        adunitPrefixDomainMappings = new Array(),
        adunitPrefixURLMappings = new Array(),
        adunitPathMappings = new Array(),
        adunitURLMappings = new Array(),
        cccPathMappings = new Array(),
        cccURLMappings = new Array(),
        i = 0,
        mmo_ccc = '',
        mmo_console = '',
        pathlength = 0,
        maxAdunitPathLength = 3,  // limit the adunit path elements.
        dfp_adunit_prefix = '', // example: /11365842/peninsulaclarion.com
        dfp_adunit = '', // example: /news/local
		dfp_ccc = ''; // customTargeting value

        // AdPay global variable for classifieds category.
        if (typeof paperCategoryID == 'undefined') paperCategoryID = 'classifieds';

////////////////////////////////////////////////////////////////////////
/***
 * mapping_version: 201603221059:443265
 */
dfp_adunit_prefix = '/11365842/savannahnow.com';
        adunitPrefixDomainMappings = [
                                      // These mappings will do a contains match against domain host.
                                      // MBU custom mappings
                                      {'msms\.savannahnow\.com': '/11365842/msms.savannahnow.com'},
                                      {'dev\.savannahnow\.com': '/11365842/msms.savannahnow.com'},
                                      {'qa\.savannahnow\.com': '/11365842/msms.savannahnow.com'},
                                      {'autos\.coastalautos\.com': '/11365842/savannahnow.com/autos'},
                                      {'bis\.yelvington\.com': '/11365842/businessinsavannah.com'},
                                      {'businessinsavannah\.com': '/11365842/businessinsavannah.com'},
                                      {'classifieds\.savannahnow\.com': '/11365842/savannahnow.com/classifieds'},
                                      {'class\.savannahnow\.com': '/11365842/savannahnow.com/classifieds'},
                                      {'coastalmommies\.com': '/11365842/coastalmommies.com'},
                                      {'^dining\.savannahnow\.com': '/11365842/savannahnow.com/diningguide'},
                                      {'dosavannah\.com': '/11365842/savannahnow.com/entertainment'},
                                      {'events\.savannahnow\.com': '/11365842/savannahnow.com/events'},
                                      {'giftguide\.': '/11365842/giftguide.savannahnow.com'},
                                      {'health\.': '/11365842/savannahnow.com/health'},
                                      {'physicianguide\.': '/11365842/savannahnow.com/physicianguide'},
                                      {'^m\.savannahnow\.com': '/11365842/m.savannahnow.com'},
                                      {'^m\.pfsav': '/11365842/m.savannahnow.com'},
                                      {'^www\.jaspersuntimes\.com': '/11365842/savannahnow.com/jaspersuntimes'},
                                      {'jaspercountysun\.com': '/11365842/savannahnow.com/jaspersuntimes'},
                                      {'jobs\.savannahnow\.com': '/11365842/savannahnow.com/jobs'},
                                      {'savannahhomesforsale\.com': '/11365842/savannahhomesforsale.com'},
                                      {'weddings\.savannahmagazine\.com': '/11365842/savannahmagazine.com/weddings'},
                                      {'savannahmagazine\.com': '/11365842/savannahmagazine.com'},
                                      {'spotted\.savannahnow\.com': '/11365842/savannahnow.com/spotted'},
                                      {'rentals\.savannahnow\.com': '/11365842/savannahnow.com/rentals'},
                                      {'thebootandjetstream\.com': '/11365842/thebootandjetstream.com'},
                                      {'legacy\.com': '/11365842/savannahnow.com/obits'}
                              ];

        adunitPathMappings = [
                              // MBU custom mappings
                              {'^\/fast-physicianguide.php': '/physicianguide'},
                              // Common mappings
                              {'^\/homepageSMN$': '/homepage'}
                      ];

adunitPathMappings.push({'\/effinghamnow$': '/effinghamnow/homepage'});
adunitPathMappings.push({'\/bryancountynow$': '/bryancountynow/homepage'});

        cccPathMappings = [
                           // MBU custom mappings
                           {'^\/homepageSMN$': 'homepage'}
                   ];
/***
 * common mappings: 201504241333:447642
 */
        adunitURLMappings.push({'\.adpay\.com': '/classifieds'});

        adunitPathMappings.push({'^\/home$': '/homepage'});
        adunitPathMappings.push({'^\/home/am$': '/homepage'});
        adunitPathMappings.push({'^\/home/pm$': '/homepage'});
        adunitPathMappings.push({'^\/index$': '/homepage'});
        adunitPathMappings.push({'^\/$': '/homepage'});

        cccURLMappings.push({'\/clicknbuy\.aspx': NMTdata.data.getQueryParam("pcatid") || paperCategoryID});
        cccURLMappings.push({'\/searchresults\.aspx': NMTdata.data.getQueryParam("pcatid") || paperCategoryID});

        cccURLMappings.push({'spotted.+\/mediadetail\/': NMTdata.data.getQueryParam("gId")});
        cccURLMappings.push({'spotted.+\/galleries\?': NMTdata.data.getQueryParam("groupId")});
        adunitURLMappings.push({'adiciotest\.': '/homes'});

        cccPathMappings.push({'^\/$': 'homepage'});
////////////////////////////////////////////////////////////////////////

        // Process domain mapping for dfp_adunit_prefix
        dfp_adunit_prefix = data.processMapping(adunitPrefixDomainMappings, location.host, dfp_adunit_prefix);

        // Process URL mapping for dfp_adunit_prefix
        dfp_adunit_prefix = data.processMapping(adunitPrefixURLMappings, document.URL, dfp_adunit_prefix);

        // build dfp_adunit default value
        // Limit adunit to 3 path elements.
        pathlength = (data.pathnames.length > maxAdunitPathLength) ? maxAdunitPathLength : data.pathnames.length;
        for (i = 0; i < pathlength; i++) {
            if (data.pathnames[i] !== '') {
                dfp_adunit += '/' + data.pathnames[i].slice(0,100);
            }
        }

        // Process Path mappings for dfp_adunit
        dfp_adunit = data.processMapping(adunitPathMappings, window.location.pathname, dfp_adunit);
        // Process URL mappings for dfp_adunit
        dfp_adunit = data.processMapping(adunitURLMappings, document.URL, dfp_adunit);

        // dfp_ccc default value
        // Paths that have trailing slash will leave the last path element empty.
        // Let's check for this case and go back one more for the ccc value.
        if (data.pathnames.length > 1 && data.pathnames[data.pathnames.length-1] == '') {
            dfp_ccc = data.pathnames[data.pathnames.length - 2];
        } else {
            dfp_ccc = data.pathnames[data.pathnames.length - 1];
        }

        // Process Path mappings for dfp_ccc
        dfp_ccc = data.processMapping(cccPathMappings, window.location.pathname, dfp_ccc);
        // Process URL mappings for dfp_ccc
        dfp_ccc = data.processMapping(cccURLMappings, document.URL, dfp_ccc);

        // override dfp_ccc with query_string mmo_ccc
        mmo_ccc = data.getQueryParam('mmo_ccc');
        if (mmo_ccc !== undefined) { dfp_ccc = mmo_ccc; }

        // Google DFP has 40 character limit on targeting values.
        dfp_ccc = dfp_ccc.slice(0,40);

        // Google DFP does not allow certain characters for adunit values.
        dfp_adunit = dfp_adunit.replace(/\s/g, '-');
        dfp_adunit = dfp_adunit.replace(/%20/g, '-');
        dfp_adunit = dfp_adunit.replace(/,/g, '-');
        dfp_adunit = dfp_adunit.replace(/%2C/g, '-');
        dfp_adunit = dfp_adunit.replace(/'/g, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(//ig, '');
        dfp_adunit = dfp_adunit.replace(/%/g, '');

        // output debug information to console
        mmo_console = data.getQueryParam('google_console');
        if (mmo_console !== undefined) {
            console.log("NMTdata.ads.dfp_adunit_prefix: "+dfp_adunit_prefix);
            console.log("NMTdata.ads.dfp_adunit: "+dfp_adunit);
            console.log("DFP AdUnit: "+dfp_adunit_prefix+dfp_adunit);
            console.log("NMTdata.ads.dfp_ccc: "+dfp_ccc);
        }

        // output debug information to console
        mmo_console = data.getQueryParam('nmt_console');
        if (mmo_console !== undefined) {
            document.write("
NMTdata.ads.dfp_adunit_prefix: "+dfp_adunit_prefix);
            document.write("
NMTdata.ads.dfp_adunit: "+dfp_adunit);
            document.write("
DFP AdUnit: "+dfp_adunit_prefix+dfp_adunit);
            document.write("
NMTdata.ads.dfp_ccc: "+data.escapeHtml(dfp_ccc));
        }

        return { // return object
            dfp_nmt_mapping_version: '201603221059:443265',
            dfp_nmt_ads_version: '201507260903:443263',
            dfp_adunit_prefix: dfp_adunit_prefix,
            dfp_adunit: dfp_adunit,
            dfp_ccc: data.escapeHtml(dfp_ccc)
        };

    }());

<|endoftext|>


<commit_before>// Taken from Read the Docs
// And heavily modified.

// Searching as the user types.
(function(){

  // Save a reference to the global object.
  var root = this;

  // Global Search object on which public functions can be added
  var Search;
  Search = root.Search = {};

  // for instituting a delay between keypresses and searches
  var timer = null;
  var delay = 250;
  var lastQuery = null;
  var useApi = true;

  // Check if the browser supports history manipulation so
  // we can change the URL upon instant searches
  var replaceStateSupported = (typeof history.replaceState === "function");

  // queue of current requests
  var xhr = [];

  var $input, $project, $button, $results, $title, $selected_facets = null;
  var $search_module = null

  function init() {
    $input = $('#id_site_search_2');
    $project = $("#id_project");
    $button = $('#id_search_button');
    $results = $("#id_search_result");
    $title = $("#id_search_title");
    $selected_facets = $("#id_selected_facets");
    $search_module = $('#search_module')

    // minimum requirements for this script to kick in...
    if(!$input.length || !$results.length) {
      return false;
    } else {
      lastQuery = queryString()
      bind();
    }
  }
  Search.init = init;

  // Setup the bindings for clicking search or keypresses
  function bind() {

    // Set a delay so not _every_ keystroke sends a search
    $input.keyup(function(ev) {

      // Don't do anything unless the query has changed
      if(lastQuery == queryString()) {
        return;
      }

      if(timer) {
        clearTimeout(timer);
      }
      timer = setTimeout("Search.run()", delay);
    });

    // $button.click(Search.run);
  }

  // Abort all existing XHR requests, since a new search is starting
  function abortCurrentXHR() {
    var request = xhr.pop();
    while(request) {
      request.abort();
      request = xhr.pop();
    }
  }

  // Replace the search results HTML with `html` (string)
  function replaceResults(html) {
    $results.empty();
    $results.append(html);
    $title.html(getTitle());

    if(html.replace(/\s+/, '').length)
      $search_module.addClass('visible')
    else
      $search_module.removeClass('visible')
  }

  // Construct the results HTML
  // TODO: Use a template!
  function buildHTML(results) {
    var html = [];
    for (var i=0; i<results.length; i++) {
      obj = results[i]
      project = obj['project']
      slug = obj['slug']
      url = "/_/" + project + "/" + slug + "/"
      html.push([
        '

',
          $('
')
            .append($('

')
              .append($('')
                  .attr('href', url)
                  .text(slug)
                )
              ).html(),
          "
",
        "
"].join('')
      );
    }
    return html.join('');
  }

  // Pop the last search off the queue and render the `results`
  function onResultsReceived(results) {
    // remove the request from the queue
    xhr.pop();
    lastQuery = queryString()
    replaceResults(buildHTML(results));
    replaceState();
    $("#id_remove_facets").attr('href', removeFacetsUrl());
  }

  // Replace the URL with the one corresponding to the current search
  function replaceState() {
    if(!replaceStateSupported) {
      return;
    }
    var url = "?" + queryString();
    var title = getTitle() + " | Search";
    window.history.replaceState({}, title, url);
  }

  // Page title
  function getTitle() {
    return "Results for " + $("#id_site_search_2").val();
  }

  // Params used in the search
  function getSearchData() {
    var data = {
      slug: getKeywords(),
      project: getProject(),
    }
    return data;
  }

  // e.g. q=my+search&selected_facets=project_exact:Read%20The%20Docs
  function queryString() {
    return jQuery.param(getSearchData());
  }
  Search.queryString = queryString

  // The active query value
  function getKeywords() {
   return $input.val()
  }

  // The active query value
  function getProject() {
   return $project.val()
  }

  // Url for the current query with any facet filters removed
  function removeFacetsUrl() {
    return '?' + jQuery.param({q: getKeywords()});
  }

  // Perform the ajax request to get the search results from the API
  function run(ev) {
    if(ev) {
        ev.preventDefault();
    }
    abortCurrentXHR();

    // Don't do anything if there is no query
    if(getKeywords() == '') {
      $results.empty();
      $search_module.removeClass('visible')
      $title.html("No search term entered");
      return;
    }

    var data = getSearchData();
    if(useApi) {
        apiSearch(data);
    }

  }
  Search.run = run;

  // TODO: The api search is incomplete. It doesn't take into account
  // facets nor pagination. It's a partial implemenation.
  function apiSearch(data) {
     var project = $project[0].value
     xhr.push(jQuery.ajax({
      type: 'GET',
      url: "/_api/v1/redirect/" + project + "/",
      data: data,
      dataType: 'jsonp',
      success: function(res, text, xhqr) {
        onResultsReceived(res.objects);
      }
    }));
  }

}).call(this);
<commit_msg>i am dumb<commit_after>// Taken from Read the Docs
// And heavily modified.

// Searching as the user types.
(function(){

  // Save a reference to the global object.
  var root = this;

  // Global Search object on which public functions can be added
  var Search;
  Search = root.Search = {};

  // for instituting a delay between keypresses and searches
  var timer = null;
  var delay = 250;
  var lastQuery = null;
  var useApi = true;

  // Check if the browser supports history manipulation so
  // we can change the URL upon instant searches
  var replaceStateSupported = (typeof history.replaceState === "function");

  // queue of current requests
  var xhr = [];

  var $input, $project, $button, $results, $title, $selected_facets = null;
  var $search_module = null

  function init() {
    $input = $('#id_site_search_2');
    $project = $("#id_project");
    $button = $('#id_search_button');
    $results = $("#id_search_result");
    $title = $("#id_search_title");
    $selected_facets = $("#id_selected_facets");
    $search_module = $('#search_module')

    // minimum requirements for this script to kick in...
    if(!$input.length || !$results.length) {
      return false;
    } else {
      lastQuery = queryString()
      bind();
    }
  }
  Search.init = init;

  // Setup the bindings for clicking search or keypresses
  function bind() {

    // Set a delay so not _every_ keystroke sends a search
    $input.keyup(function(ev) {

      // Don't do anything unless the query has changed
      if(lastQuery == queryString()) {
        return;
      }

      if(timer) {
        clearTimeout(timer);
      }
      timer = setTimeout("Search.run()", delay);
    });

    // $button.click(Search.run);
  }

  // Abort all existing XHR requests, since a new search is starting
  function abortCurrentXHR() {
    var request = xhr.pop();
    while(request) {
      request.abort();
      request = xhr.pop();
    }
  }

  // Replace the search results HTML with `html` (string)
  function replaceResults(html) {
    $results.empty();
    $results.append(html);
    $title.html(getTitle());

    if(html.replace(/\s+/, '').length)
      $search_module.addClass('visible')
    else
      $search_module.removeClass('visible')
  }

  // Construct the results HTML
  // TODO: Use a template!
  function buildHTML(results) {
    var html = [];
    for (var i=0; i<results.length; i++) {
      obj = results[i]
      project = obj['project']
      slug = obj['slug']
      url = "/_/" + project + "/" + slug + "/"
      html.push([
        '
',
          $('
')
            .append($('

')
              .append($('')
                  .attr('href', url)
                  .text(slug)
                )
              ).html(),
        "
"].join('')
      );
    }
    return html.join('');
  }

  // Pop the last search off the queue and render the `results`
  function onResultsReceived(results) {
    // remove the request from the queue
    xhr.pop();
    lastQuery = queryString()
    replaceResults(buildHTML(results));
    replaceState();
    $("#id_remove_facets").attr('href', removeFacetsUrl());
  }

  // Replace the URL with the one corresponding to the current search
  function replaceState() {
    if(!replaceStateSupported) {
      return;
    }
    var url = "?" + queryString();
    var title = getTitle() + " | Search";
    window.history.replaceState({}, title, url);
  }

  // Page title
  function getTitle() {
    return "Results for " + $("#id_site_search_2").val();
  }

  // Params used in the search
  function getSearchData() {
    var data = {
      slug: getKeywords(),
      project: getProject(),
    }
    return data;
  }

  // e.g. q=my+search&selected_facets=project_exact:Read%20The%20Docs
  function queryString() {
    return jQuery.param(getSearchData());
  }
  Search.queryString = queryString

  // The active query value
  function getKeywords() {
   return $input.val()
  }

  // The active query value
  function getProject() {
   return $project.val()
  }

  // Url for the current query with any facet filters removed
  function removeFacetsUrl() {
    return '?' + jQuery.param({q: getKeywords()});
  }

  // Perform the ajax request to get the search results from the API
  function run(ev) {
    if(ev) {
        ev.preventDefault();
    }
    abortCurrentXHR();

    // Don't do anything if there is no query
    if(getKeywords() == '') {
      $results.empty();
      $search_module.removeClass('visible')
      $title.html("No search term entered");
      return;
    }

    var data = getSearchData();
    if(useApi) {
        apiSearch(data);
    }

  }
  Search.run = run;

  // TODO: The api search is incomplete. It doesn't take into account
  // facets nor pagination. It's a partial implemenation.
  function apiSearch(data) {
     var project = $project[0].value
     xhr.push(jQuery.ajax({
      type: 'GET',
      url: "/_api/v1/redirect/" + project + "/",
      data: data,
      dataType: 'jsonp',
      success: function(res, text, xhqr) {
        onResultsReceived(res.objects);
      }
    }));
  }

}).call(this);
<|endoftext|>


<commit_before>/*
* AUI Base
*/
AUI.add('aui-base', function(A) {

	A.mix(A.Array, {
		remove: function(a, from, to) {
		  var rest = a.slice((to || from) + 1 || a.length);
		  a.length = (from < 0) ? (a.length + from) : from;

		  return a.push.apply(a, rest);
		},

		removeItem: function(a, item) {
			var index = A.Array.indexOf(a, item);

			return A.Array.remove(a, index);
		}
	});

	// Courtesy of: http://simonwillison.net/2006/Jan/20/escape/
	A.Lang.escapeRegEx = function(str) {
		return str.replace(/([.*+?^$(){}|[\]\/\\])/g, '\\$1');
	};

}, '@VERSION', { requires: [ 'yui-base', 'base' ] });

/*
* AUI Delayed Task
*/

AUI.add('delayed-task', function(A) {

	var DelayedTask = function(fn, scope, args) {
		var instance = this;

		instance._args = args;
		instance._delay = 0;
		instance._fn = fn;
		instance._id = null;
		instance._scope = scope || instance;
		instance._time = 0;

		instance._base = function() {
			var now = instance._getTime();

			if (now - instance._time >= instance._delay) {
				clearInterval(instance._id);

				instance._id = null;

				instance._fn.apply(instance._scope, instance._args || []);
			}
		};
	};

	DelayedTask.prototype = {
		delay: function(delay, newFn, newScope, newArgs) {
			var instance = this;

			if (instance._id && instance._delay != delay) {
				instance.cancel();
			}

			instance._delay = delay || instance._delay;
			instance._time = instance._getTime();

			instance._fn = newFn || instance._fn;
			instance._scope = newScope || instance._scope;
			instance._args = newArgs || instance._args;

			if (!A.Lang.isArray(instance._args)) {
				instance._args = [instance._args];
			}

			if (!instance._id) {
				if (instance._delay > 0) {
					instance._id = setInterval(instance._base, instance._delay);
				}
				else {
					instance._base();
				}
			}
		},

		cancel: function() {
			var instance = this;

			if (instance._id) {
				clearInterval(instance._id);

				instance._id = null;
			}
		},

		_getTime: function() {
			var instance = this;

			return (+new Date());
		}
	};

	A.DelayedTask = DelayedTask;

}, '@VERSION', { requires: [ 'yui-base' ] });

/*
* AUI Node
*/

AUI.add('aui-node', function(A) {

	var Lang = A.Lang,
		isArray = Lang.isArray,
		isString = Lang.isString,
		isUndefined = Lang.isUndefined,

		INNER_HTML = 'innerHTML',
		NEXT_SIBLING = 'nextSibling',
		NONE = 'none',
		PARENT_NODE = 'parentNode',
		SCRIPT = 'script',
		VALUE = 'value';

	A.mix(A.Node.prototype, {
		appendTo: function(selector) {
			var instance = this;

			A.get(selector).append(instance);

			return instance;
		},

		attr: function(name, value) {
			var instance = this;

			if (!isUndefined(value)) {
				return instance.set(name, value);
			}
			else {
				return instance.get(name) || instance.getAttribute(name);
			}
		},

		empty: function() {
			var instance = this;

			instance.queryAll('>*').remove();

			var el = A.Node.getDOMNode(instance);

			while (el.firstChild) {
				el.removeChild(el.firstChild);
			}

			return instance;
		},

		getDOM: function() {
			var instance = this;

			return A.Node.getDOMNode(instance);
		},

		guid: function(prefix) {
			var instance = this;
			var currentId = instance.get('id');

			if (!currentId) {
				currentId = A.stamp(instance);

				instance.set('id', currentId);
			}

			return currentId;
		},

		hide: function(cssClass) {
			var instance = this;

			instance.addClass(cssClass || instance._hideClass || 'aui-helper-hidden');

			return instance;
		},

		html: function() {
			var args = arguments, length = args.length;

			if (length) {
				this.set(INNER_HTML, args[0]);
			}
			else {
				return this.get(INNER_HTML);
			}

			return this;
		},

		outerHTML: function() {
			var instance = this;
			var temp = A.Node.create('

').append(this);

			try {
				return temp.html();
			}
			catch(e) {}
			finally {
				temp = null;
			}
		},

		placeAfter: function(content) {
			var instance = this;

			var parent = instance.get(PARENT_NODE);

			if (parent) {
				parent.insertBefore(content, instance.get(NEXT_SIBLING));
			}
		},

		placeBefore: function(content) {
			var instance = this;

			var parent = instance.get(PARENT_NODE);

			if (parent) {
				parent.insertBefore(content, instance);
			}
		},

		prependTo: function(selector) {
			var instance = this;

			A.get(selector).prepend(instance);
		},

		resetId: function(prefix) {
			var instance = this;

			instance.attr('id', A.guid(prefix));

			return instance;
		},

		selectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'off';
			instance.detach('selectstart');

			instance.setStyles(
				{
					'MozUserSelect': '',
					'KhtmlUserSelect': ''
				}
			);

			instance.removeClass('aui-helper-unselectable');

			return instance;
		},

		show: function(cssClass) {
			var instance = this;

			instance.removeClass(cssClass || instance._hideClass || 'aui-helper-hidden')

			return instance;
		},

		swallowEvent: function(eventName, preventDefault) {
			var instance = this;

			var fn = function(event) {
				event.stopPropagation();

				if (preventDefault) {
					event.preventDefault();

					event.halt();
				}

				return false;
			};

			if(isArray(eventName)) {
				A.Array.each(
					eventName,
					function(name) {
						instance.on(name, fn);
					}
				);

				return this;
			}
			else {
				instance.on(eventName, fn);
			}

			return instance;
		},

		text: function(text) {
			var instance = this;
			var el = instance.getDOM();

			if (!isUndefined(text)) {
				text = A.DOM._getDoc(el).createTextNode(text);

				return instance.empty().append(text);
			}

			return instance._getText(el.childNodes);
		},

		unselectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'on';

			instance.swallowEvent('selectstart', true);

			instance.setStyles(
				{
					'MozUserSelect': NONE,
					'KhtmlUserSelect': NONE
				}
			);

			instance.addClass('aui-helper-unselectable');

			return instance;
		},

		val: function(value) {
			var instance = this;

			return instance.attr(VALUE, value);
		},

		_getText: function(childNodes) {
			var instance = this;

			var length = childNodes.length;
			var childNode;

			var str = [];

			for (var i = 0; i < length; i++) {
				childNode = childNodes[i];

				if (childNode && childNode.nodeType != 8) {
					if (childNode.nodeType != 1) {
						str.push(childNode.nodeValue);
					}

					if (childNode.childNodes) {
						str.push(instance._getText(childNode.childNodes));
					}
				}
			}

			return str.join('');
		}
	}, true);

	A.mix(A.Node, {
		globalEval: function(data) {
			if ( data && /\S/.test(data) ) {
				var head = document.getElementsByTagName('head')[0] || document.documentElement;
				var script = document.createElement('script');

				script.type = 'text/javascript';

				if (AUI.support.scriptEval) {
					script.appendChild(document.createTextNode(data));
				}
				else {
					script.text = data;
				}

				head.insertBefore(script, head.firstChild);
				head.removeChild(script);
			}
		},

		evalScript: function(elem) {
			if (elem.src) {
				A.io(elem.src, {
					async: false,
					on: {
						complete: function(i, o) {
							A.Node.globalEval(o.responseText);
						}
					}
				});
			}
			else {
				A.Node.globalEval(elem.text || elem.textContent || elem.innerHTML || '');
			}
		},

		clean: function(html) {
			var TPL_NODE = '

',
				IE_FIX_PADDING_NODE = '
_
';

			// instead of fix all tags to "XHTML"-style, make the firstChild be a valid non-empty tag
			html = IE_FIX_PADDING_NODE + A.Lang.trim(html);

			delete A.DOM._cloneCache[html];

			// wrap in a nodeType == 1, nodeType 11 (document fragment) does not support getElementsByTagName
			var temp = A.Node.create(TPL_NODE).append(
				A.Node.create(html)
			);

			var scripts = temp.getElementsByTagName(SCRIPT);

			scripts.each(function(elem) {
				elem.remove();
			});

			temp.removeChild(A.Node.getDOMNode(temp).firstChild);

			var html = temp.html();

			// avoid IE6 memory leak
			temp = null;

			return [ html, scripts ];
		},

		domManip: function(html, callback) {
			var clean = A.Node.clean(html);
			var content = clean[0];
			var scripts = clean[1];

			if (callback) {
				callback.apply(this, [ content ]);
			}

			scripts.each(function(elem) {
				A.Node.evalScript( A.Node.getDOMNode(elem) );
			});
		}
	});

	A.Node.ATTRS.innerHTML = {
		setter: function(v) {
			var instance = this;

			var defaultSetter = function(value) {
				A.Node.DEFAULT_SETTER.apply(instance, [ INNER_HTML, value ]);
			};

			if (isString(v)) {
				// eval scripts
				v = A.Node.domManip(v, defaultSetter);
			}
			else {
				defaultSetter(v);
			}
		}
	};

	A.NodeList.importMethod(
		A.Node.prototype,
		[
			'after',

			'appendTo',

			'attr',

			'before',

			'empty',

			'hide',

			'html',

			'outerHTML',

			'prepend',

			'prependTo',

			'selectable',

			'show',

			'text',

			'unselectable'
		]
	);

	A.NodeList.prototype.getDOM = function() {
		return A.NodeList.getDOMNodes(this);
	};

	A.mix(
		A,
		{
			getBody: function() {
				var instance = this;

				if (!instance._bodyNode) {
					instance._bodyNode = A.get(document.body);
				}

				return instance._bodyNode;
			},

			getDoc: function() {
				var instance = this;

				if (!instance._documentNode) {
					instance._documentNode = A.get(document);
				}

				return instance._documentNode;
			},

			getWin: function() {
				var instance = this;

				if (!instance._windowNode) {
					instance._windowNode = A.get(window);
				}

				return instance._windowNode;
			}
		}
	);

}, '@VERSION', { requires: [ 'node' ] });<commit_msg>Adding .toggle to Node<commit_after>/*
* AUI Base
*/
AUI.add('aui-base', function(A) {

	A.mix(A.Array, {
		remove: function(a, from, to) {
		  var rest = a.slice((to || from) + 1 || a.length);
		  a.length = (from < 0) ? (a.length + from) : from;

		  return a.push.apply(a, rest);
		},

		removeItem: function(a, item) {
			var index = A.Array.indexOf(a, item);

			return A.Array.remove(a, index);
		}
	});

	// Courtesy of: http://simonwillison.net/2006/Jan/20/escape/
	A.Lang.escapeRegEx = function(str) {
		return str.replace(/([.*+?^$(){}|[\]\/\\])/g, '\\$1');
	};

}, '@VERSION', { requires: [ 'yui-base', 'base' ] });

/*
* AUI Delayed Task
*/

AUI.add('delayed-task', function(A) {

	var DelayedTask = function(fn, scope, args) {
		var instance = this;

		instance._args = args;
		instance._delay = 0;
		instance._fn = fn;
		instance._id = null;
		instance._scope = scope || instance;
		instance._time = 0;

		instance._base = function() {
			var now = instance._getTime();

			if (now - instance._time >= instance._delay) {
				clearInterval(instance._id);

				instance._id = null;

				instance._fn.apply(instance._scope, instance._args || []);
			}
		};
	};

	DelayedTask.prototype = {
		delay: function(delay, newFn, newScope, newArgs) {
			var instance = this;

			if (instance._id && instance._delay != delay) {
				instance.cancel();
			}

			instance._delay = delay || instance._delay;
			instance._time = instance._getTime();

			instance._fn = newFn || instance._fn;
			instance._scope = newScope || instance._scope;
			instance._args = newArgs || instance._args;

			if (!A.Lang.isArray(instance._args)) {
				instance._args = [instance._args];
			}

			if (!instance._id) {
				if (instance._delay > 0) {
					instance._id = setInterval(instance._base, instance._delay);
				}
				else {
					instance._base();
				}
			}
		},

		cancel: function() {
			var instance = this;

			if (instance._id) {
				clearInterval(instance._id);

				instance._id = null;
			}
		},

		_getTime: function() {
			var instance = this;

			return (+new Date());
		}
	};

	A.DelayedTask = DelayedTask;

}, '@VERSION', { requires: [ 'yui-base' ] });

/*
* AUI Node
*/

AUI.add('aui-node', function(A) {

	var Lang = A.Lang,
		isArray = Lang.isArray,
		isString = Lang.isString,
		isUndefined = Lang.isUndefined,

		INNER_HTML = 'innerHTML',
		NEXT_SIBLING = 'nextSibling',
		NONE = 'none',
		PARENT_NODE = 'parentNode',
		SCRIPT = 'script',
		VALUE = 'value';

	A.mix(A.Node.prototype, {
		appendTo: function(selector) {
			var instance = this;

			A.get(selector).append(instance);

			return instance;
		},

		attr: function(name, value) {
			var instance = this;

			if (!isUndefined(value)) {
				return instance.set(name, value);
			}
			else {
				return instance.get(name) || instance.getAttribute(name);
			}
		},

		empty: function() {
			var instance = this;

			instance.queryAll('>*').remove();

			var el = A.Node.getDOMNode(instance);

			while (el.firstChild) {
				el.removeChild(el.firstChild);
			}

			return instance;
		},

		getDOM: function() {
			var instance = this;

			return A.Node.getDOMNode(instance);
		},

		guid: function(prefix) {
			var instance = this;
			var currentId = instance.get('id');

			if (!currentId) {
				currentId = A.stamp(instance);

				instance.set('id', currentId);
			}

			return currentId;
		},

		hide: function(cssClass) {
			var instance = this;

			instance.addClass(cssClass || instance._hideClass || 'aui-helper-hidden');

			return instance;
		},

		html: function() {
			var args = arguments, length = args.length;

			if (length) {
				this.set(INNER_HTML, args[0]);
			}
			else {
				return this.get(INNER_HTML);
			}

			return this;
		},

		outerHTML: function() {
			var instance = this;
			var temp = A.Node.create('

').append(this);

			try {
				return temp.html();
			}
			catch(e) {}
			finally {
				temp = null;
			}
		},

		placeAfter: function(content) {
			var instance = this;

			var parent = instance.get(PARENT_NODE);

			if (parent) {
				parent.insertBefore(content, instance.get(NEXT_SIBLING));
			}
		},

		placeBefore: function(content) {
			var instance = this;

			var parent = instance.get(PARENT_NODE);

			if (parent) {
				parent.insertBefore(content, instance);
			}
		},

		prependTo: function(selector) {
			var instance = this;

			A.get(selector).prepend(instance);
		},

		resetId: function(prefix) {
			var instance = this;

			instance.attr('id', A.guid(prefix));

			return instance;
		},

		selectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'off';
			instance.detach('selectstart');

			instance.setStyles(
				{
					'MozUserSelect': '',
					'KhtmlUserSelect': ''
				}
			);

			instance.removeClass('aui-helper-unselectable');

			return instance;
		},

		show: function(cssClass) {
			var instance = this;

			instance.removeClass(cssClass || instance._hideClass || 'aui-helper-hidden')

			return instance;
		},

		swallowEvent: function(eventName, preventDefault) {
			var instance = this;

			var fn = function(event) {
				event.stopPropagation();

				if (preventDefault) {
					event.preventDefault();

					event.halt();
				}

				return false;
			};

			if(isArray(eventName)) {
				A.Array.each(
					eventName,
					function(name) {
						instance.on(name, fn);
					}
				);

				return this;
			}
			else {
				instance.on(eventName, fn);
			}

			return instance;
		},

		text: function(text) {
			var instance = this;
			var el = instance.getDOM();

			if (!isUndefined(text)) {
				text = A.DOM._getDoc(el).createTextNode(text);

				return instance.empty().append(text);
			}

			return instance._getText(el.childNodes);
		},

		toggle: function(cssClass) {
			var instance = this;

			var action = 'hide';
			var hideClass = cssClass || instance._hideClass || 'aui-helper-hidden';

			if (instance.hasClass(hideClass)) {
				action = 'show';
			}

			instance[action](hideClass);
		},

		unselectable: function() {
			var instance = this;

			instance.getDOM().unselectable = 'on';

			instance.swallowEvent('selectstart', true);

			instance.setStyles(
				{
					'MozUserSelect': NONE,
					'KhtmlUserSelect': NONE
				}
			);

			instance.addClass('aui-helper-unselectable');

			return instance;
		},

		val: function(value) {
			var instance = this;

			return instance.attr(VALUE, value);
		},

		_getText: function(childNodes) {
			var instance = this;

			var length = childNodes.length;
			var childNode;

			var str = [];

			for (var i = 0; i < length; i++) {
				childNode = childNodes[i];

				if (childNode && childNode.nodeType != 8) {
					if (childNode.nodeType != 1) {
						str.push(childNode.nodeValue);
					}

					if (childNode.childNodes) {
						str.push(instance._getText(childNode.childNodes));
					}
				}
			}

			return str.join('');
		}
	}, true);

	A.mix(A.Node, {
		globalEval: function(data) {
			if ( data && /\S/.test(data) ) {
				var head = document.getElementsByTagName('head')[0] || document.documentElement;
				var script = document.createElement('script');

				script.type = 'text/javascript';

				if (AUI.support.scriptEval) {
					script.appendChild(document.createTextNode(data));
				}
				else {
					script.text = data;
				}

				head.insertBefore(script, head.firstChild);
				head.removeChild(script);
			}
		},

		evalScript: function(elem) {
			if (elem.src) {
				A.io(elem.src, {
					async: false,
					on: {
						complete: function(i, o) {
							A.Node.globalEval(o.responseText);
						}
					}
				});
			}
			else {
				A.Node.globalEval(elem.text || elem.textContent || elem.innerHTML || '');
			}
		},

		clean: function(html) {
			var TPL_NODE = '

',
				IE_FIX_PADDING_NODE = '
_
';

			// instead of fix all tags to "XHTML"-style, make the firstChild be a valid non-empty tag
			html = IE_FIX_PADDING_NODE + A.Lang.trim(html);

			delete A.DOM._cloneCache[html];

			// wrap in a nodeType == 1, nodeType 11 (document fragment) does not support getElementsByTagName
			var temp = A.Node.create(TPL_NODE).append(
				A.Node.create(html)
			);

			var scripts = temp.getElementsByTagName(SCRIPT);

			scripts.each(function(elem) {
				elem.remove();
			});

			temp.removeChild(A.Node.getDOMNode(temp).firstChild);

			var html = temp.html();

			// avoid IE6 memory leak
			temp = null;

			return [ html, scripts ];
		},

		domManip: function(html, callback) {
			var clean = A.Node.clean(html);
			var content = clean[0];
			var scripts = clean[1];

			if (callback) {
				callback.apply(this, [ content ]);
			}

			scripts.each(function(elem) {
				A.Node.evalScript( A.Node.getDOMNode(elem) );
			});
		}
	});

	A.Node.ATTRS.innerHTML = {
		setter: function(v) {
			var instance = this;

			var defaultSetter = function(value) {
				A.Node.DEFAULT_SETTER.apply(instance, [ INNER_HTML, value ]);
			};

			if (isString(v)) {
				// eval scripts
				v = A.Node.domManip(v, defaultSetter);
			}
			else {
				defaultSetter(v);
			}
		}
	};

	A.NodeList.importMethod(
		A.Node.prototype,
		[
			'after',

			'appendTo',

			'attr',

			'before',

			'empty',

			'hide',

			'html',

			'outerHTML',

			'prepend',

			'prependTo',

			'selectable',

			'show',

			'text',

			'unselectable'
		]
	);

	A.NodeList.prototype.getDOM = function() {
		return A.NodeList.getDOMNodes(this);
	};

	A.mix(
		A,
		{
			getBody: function() {
				var instance = this;

				if (!instance._bodyNode) {
					instance._bodyNode = A.get(document.body);
				}

				return instance._bodyNode;
			},

			getDoc: function() {
				var instance = this;

				if (!instance._documentNode) {
					instance._documentNode = A.get(document);
				}

				return instance._documentNode;
			},

			getWin: function() {
				var instance = this;

				if (!instance._windowNode) {
					instance._windowNode = A.get(window);
				}

				return instance._windowNode;
			}
		}
	);

}, '@VERSION', { requires: [ 'node' ] });<|endoftext|>


<commit_before>;(function() {

	// Based on jQuery.extend
	var extend = function() {
		// copy reference to target object
		var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, toString = Object.prototype.toString;

		var isFunction = function( obj ) {
			return toString.call(obj) === "[object Function]";
		};

		// Handle a deep copy situation
		if ( typeof target === "boolean" ) {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ( typeof target !== "object" && !isFunction(target) ) {
			target = {};
		}

		// extend Object itself if only one argument is passed
		if ( length == i ) {
			target = this;
			--i;
		}

		for ( ; i < length; i++ ) {
			// Only deal with non-null/undefined values
			if ( (options = arguments[ i ]) != null ) {
				// Extend the base object
				for ( var name in options ) {
					var src = target[ name ], copy = options[ name ];

					// Prevent never-ending loop
					if ( target === copy ) {
						continue;
					}

					// Recurse if we're merging object values
					if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
						target[ name ] = extend( deep,
							// Never move original objects, clone them
							src || ( copy.length != null ? [ ] : { } )
						, copy );
					}
					// Don't bring in undefined values
					else if ( copy !== undefined ) {
						target[ name ] = copy;
					}

				}
			}
		}

		// Return the modified object
		return target;
	};

	// temporary crappy method to get the base path
	var getBasePath = function () {
		var nodes = document.getElementsByTagName('script'), i, base;

		for (i = 0; i < nodes.length; i = i + 1) {
			var src = nodes[i].src;
			var match = src.match(/^(.*)yui[\.-].*js(\?.*)?$/);

			if (match && (base = match[1])) {
				base = base.split(/[\/\\]/);

				// removing the last path level /yui/../
				base = base.splice(0, base.length - 2).concat(
					base.splice(base.length - 1, base.length)
				);

				break;
			}
		}

		return base.join('/');
	};

	/*!
	 * Alloy JavaScript Library v@VERSION
	 * http://alloyui.com/
	 *
	 * Copyright (c) 2009 Liferay Inc.
	 * Licensed under the MIT license.
	 * http://alloyui.com/License
	 *
	 * Nate Cavanaugh (nate.cavanaugh@liferay.com)
	 * Eduardo Lundgren (eduardo.lundgren@liferay.com)
	 *
	 * Date: @DATE
	 * Revision: @REVISION
	 */

	window.Alloy = window.Alloy || {};

	var defaults = {};
	var defaultModules = [ 'event', 'oop', 'widget' ];

	var errorCallback = function(instance, result) {
		if (!result.success) {
			throw result.msg;
		}
	};

	if ('defaults' in Alloy) {
		defaults = Alloy.defaults;
	}

	// get the base path in case the user has not specified
	if (!('base' in defaults)) {
		defaults.base = getBasePath();
	}

	var ALLOY = YUI( extend({}, defaults) );

	var originalConfig = ALLOY.config;

	// adding callback for .use()
	defaultModules.push(errorCallback);

	// loading default modules
	ALLOY.use.apply(ALLOY, defaultModules);

	Alloy = function(o) {
		var instance = this;

		ALLOY.config = ALLOY.merge(originalConfig, Alloy.defaults);

		if (o || instance instanceof Alloy) {
			// new Alloy() creates a new YUI sandbox
			return YUI( ALLOY.merge(ALLOY.config, o) );
		}

		// returns the cached YUI sandbox
		return ALLOY;
	};

	extend(Alloy, YUI, {
		__version: '@VERSION',

		extend: extend,

		defaults: defaults
	});

	Alloy.extend(Alloy.prototype, {
		ready: function() {
			var instance = this;
			var slice = Array.prototype.slice;
			var args = slice.call(arguments, 0), index = args.length - 1;

			// user callback
			var fn = args[index];

			// array with YUI modules to be loaded
			var modules = slice.call(arguments, 0, index);

			if (!modules.length) {
				modules.push('event');
			}

			// adding Alloy().use() callback
			modules.push(
				function(instance) {
					var args = arguments;
					instance.on('domready', function() {
					   fn.apply(this, args);
					});
				}
			);

			instance.use.apply(instance, modules);
		}
	});

})();<commit_msg>Optimizations to ready function<commit_after>;(function() {

	// Based on jQuery.extend
	var extend = function() {
		// copy reference to target object
		var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, toString = Object.prototype.toString;

		var isFunction = function( obj ) {
			return toString.call(obj) === "[object Function]";
		};

		// Handle a deep copy situation
		if ( typeof target === "boolean" ) {
			deep = target;
			target = arguments[1] || {};
			// skip the boolean and the target
			i = 2;
		}

		// Handle case when target is a string or something (possible in deep copy)
		if ( typeof target !== "object" && !isFunction(target) ) {
			target = {};
		}

		// extend Object itself if only one argument is passed
		if ( length == i ) {
			target = this;
			--i;
		}

		for ( ; i < length; i++ ) {
			// Only deal with non-null/undefined values
			if ( (options = arguments[ i ]) != null ) {
				// Extend the base object
				for ( var name in options ) {
					var src = target[ name ], copy = options[ name ];

					// Prevent never-ending loop
					if ( target === copy ) {
						continue;
					}

					// Recurse if we're merging object values
					if ( deep && copy && typeof copy === "object" && !copy.nodeType ) {
						target[ name ] = extend( deep,
							// Never move original objects, clone them
							src || ( copy.length != null ? [ ] : { } )
						, copy );
					}
					// Don't bring in undefined values
					else if ( copy !== undefined ) {
						target[ name ] = copy;
					}

				}
			}
		}

		// Return the modified object
		return target;
	};

	// temporary crappy method to get the base path
	var getBasePath = function () {
		var nodes = document.getElementsByTagName('script'), i, base;

		for (i = 0; i < nodes.length; i = i + 1) {
			var src = nodes[i].src;
			var match = src.match(/^(.*)yui[\.-].*js(\?.*)?$/);

			if (match && (base = match[1])) {
				base = base.split(/[\/\\]/);

				// removing the last path level /yui/../
				base = base.splice(0, base.length - 2).concat(
					base.splice(base.length - 1, base.length)
				);

				break;
			}
		}

		return base.join('/');
	};

	/*!
	 * Alloy JavaScript Library v@VERSION
	 * http://alloyui.com/
	 *
	 * Copyright (c) 2009 Liferay Inc.
	 * Licensed under the MIT license.
	 * http://alloyui.com/License
	 *
	 * Nate Cavanaugh (nate.cavanaugh@liferay.com)
	 * Eduardo Lundgren (eduardo.lundgren@liferay.com)
	 *
	 * Date: @DATE
	 * Revision: @REVISION
	 */

	window.Alloy = window.Alloy || {};

	var defaults = {};
	var defaultModules = [ 'event', 'oop', 'widget' ];

	var errorCallback = function(instance, result) {
		if (!result.success) {
			throw result.msg;
		}
	};

	if ('defaults' in Alloy) {
		defaults = Alloy.defaults;
	}

	// get the base path in case the user has not specified
	if (!('base' in defaults)) {
		defaults.base = getBasePath();
	}

	var ALLOY = YUI( extend({}, defaults) );

	var originalConfig = ALLOY.config;

	// adding callback for .use()
	defaultModules.push(errorCallback);

	// loading default modules
	ALLOY.use.apply(ALLOY, defaultModules);

	Alloy = function(o) {
		var instance = this;

		ALLOY.config = ALLOY.merge(originalConfig, Alloy.defaults);

		if (o || instance instanceof Alloy) {
			// new Alloy() creates a new YUI sandbox
			return YUI( ALLOY.merge(ALLOY.config, o) );
		}

		// returns the cached YUI sandbox
		return ALLOY;
	};

	extend(Alloy, YUI, {
		__version: '@VERSION',

		extend: extend,

		defaults: defaults
	});

	Alloy.extend(Alloy.prototype, {
		ready: function() {
			var instance = this;
			var args = Array.prototype.slice.call(arguments);

			// user callback
			var fn = args.pop();

			if (!args.length) {
				args.push('event');
			}

			// adding Alloy().use() callback
			args.push(
				function(instance) {
					var args = arguments;
					instance.on('domready', function() {
					   fn.apply(this, args);
					});
				}
			);

			instance.use.apply(instance, args);
		}
	});

})();<|endoftext|>