<commit_before>// pump.js
//
// Entrypoint for the pump.io client UI
//
// Copyright 2011-2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Make sure this exists

if (!window.Pump) {
    window.Pump = {};
}

(function(_, $, Backbone, Pump) {

    // This is overwritten by inline script in layout.utml

    Pump.config = {};

    // Main entry point

    $(document).ready(function() {

        // XXX: set up initial models

        // Set up router

        Pump.router   = new Pump.Router();

        // Set up initial view

        Pump.body     = new Pump.BodyView({el: $("body")});
        Pump.body.nav = new Pump.AnonymousNav({el: ".navbar-inner .container"});

        // XXX: Make this more complete

        if ($("#content #login").length > 0) {
            Pump.body.content = new Pump.LoginContent();
        } else if ($("#content #registration").length > 0) {
            Pump.body.content = new Pump.RegisterContent();
        } else if ($("#content #user").length > 0) {
            Pump.body.content = new Pump.UserPageContent({});
        } else if ($("#content #inbox").length > 0) {
            Pump.body.content = new Pump.InboxContent({});
        }

        $("abbr.easydate").easydate();

        Backbone.history.start({pushState: true, silent: true});

        Pump.setupWysiHTML5();

        // Refresh the streams automatically every 60 seconds
        // This is a fallback in case something gets lost in the
        // SockJS conversation

        Pump.refreshStreamsID = setInterval(Pump.refreshStreams, 60000);

        // Connect to current server

        if (Pump.config.sockjs) {
            Pump.setupSocket();
        }

        // Check if we have stored OAuth credentials

        Pump.ensureCred(function(err, cred) {

            var user, nickname, pair, major, minor;

            if (err) {
                Pump.error(err.message);
                return;
            }

            nickname = Pump.getNickname();

            if (nickname) {

                user = new Pump.User({nickname: nickname});
                major = user.majorDirectInbox;
                minor = user.minorDirectInbox;

                Pump.fetchObjects([user, major, minor], function(objs) {
                    var sp, continueTo;

                    Pump.currentUser = user;

                    Pump.body.nav = new Pump.UserNav({el: ".navbar-inner .container",
                                                      model: user,
                                                      data: {
                                                          messages: major,
                                                          notifications: minor
                                                      }});
                    Pump.body.nav.render();

                    // If we're on the login page, and there's a current
                    // user, redirect to the actual page

                    switch (window.location.pathname) {
                    case "/main/login":
                        Pump.body.content = new Pump.LoginContent();
                        continueTo = Pump.getContinueTo();
                        Pump.router.navigate(continueTo, true);
                        break;
                    case "/":
                        Pump.router.home();
                        break;
                    }
                });
            }
        });
    });

    // When errors happen, and you don't know what to do with them,
    // send them here and I'll figure it out.

    Pump.error = function(err) {
        console.log(err);
    };

    // Given a relative URL like /main/register, make a fully-qualified
    // URL on the current server

    Pump.fullURL = function(url) {

        var here = window.location;

        if (url.indexOf(':') == -1) {
            if (url.substr(0, 1) == '/') {
                url = here.protocol + '//' + here.host + url;
            } else {
                url = here.href.substr(0, here.href.lastIndexOf('/') + 1) + url;
            }
        }

        return url;
    };

    // Add some OAuth magic to the arguments for a $.ajax() call

    Pump.oauthify = function(options) {

        options.url = Pump.fullURL(options.url);

        var message = {action: options.url,
                       method: options.type,
                       parameters: [["oauth_version", "1.0"],
                                    ["oauth_consumer_key", options.consumerKey]]};

        if (options.token) {
            message.parameters.push(["oauth_token", options.token]);
        }

        OAuth.setTimestampAndNonce(message);
        OAuth.SignatureMethod.sign(message,
                                   {consumerSecret: options.consumerSecret,
                                    tokenSecret: options.tokenSecret});

        var header =  OAuth.getAuthorizationHeader("OAuth", message.parameters);

        options.headers = {Authorization: header};

        return options;
    };

    Pump.fetchObjects = function(orig, callback) {
        var fetched = 0,
            objs = (orig.length) > 0 ? orig.slice(0) : [], // make a dupe in case arg is changed
            count = objs.length,
            done = false,
            onSuccess = function() {
                if (!done) {
                    fetched++;
                    if (fetched >= count) {
                        done = true;
                        callback(objs);
                    }
                }
            },
            onError = function() {
                if (!done) {
                    done = true;
                    callback(null);
                }
            };

        _.each(objs, function(obj) {
            try {
                obj.fetch({success: onSuccess,
                           error: onError});
            } catch (e) {
                Pump.error(e.message);
                onError();
            }
        });
    };

    // Not the most lovely, but it works
    // XXX: change this to use UTML templating instead

    Pump.wysihtml5Tmpl = {
        "emphasis": function(locale) {
            return "
" +
                "
" +
                "" +
                "" +
                "_" +
                "
" +
                "
";
        }
    };

    // Most long-form descriptions and notes use this lib for editing

    Pump.setupWysiHTML5 = function() {

        // Set wysiwyg defaults

        $.fn.wysihtml5.defaultOptions["font-styles"] = false;
        $.fn.wysihtml5.defaultOptions["image"] = false;
        $.fn.wysihtml5.defaultOptions["customTemplates"] = Pump.wysihtml5Tmpl;
    };

    // Turn the querystring into an object

    Pump.searchParams = function(str) {
        var params = {},
            pl     = /\+/g,
            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
            pairs;

        if (!str) {
            str = window.location.search;
        }

        pairs = str.substr(1).split("&");

        _.each(pairs, function(pairStr) {
            var pair = pairStr.split("=", 2),
                key = decode(pair[0]),
                value = (pair.length > 1) ? decode(pair[1]) : null;

            params[key] = value;
        });

        return params;
    };

    // Get the "continue" param

    Pump.getContinueTo = function() {
        var sp = Pump.searchParams(),
            continueTo = (_.has(sp, "continue")) ? sp["continue"] : null;
        if (continueTo && continueTo.length > 0 && continueTo[0] == "/") {
            return continueTo;
        } else {
            return "";
        }
    };

    // We clear out cached stuff when login state changes

    Pump.clearCaches = function() {
        Pump.Model.clearCache();
        Pump.Collection.clearCache();
        Pump.User.clearCache();
    };

    Pump.ajax = function(options) {
        Pump.ensureCred(function(err, cred) {
            var pair;
            if (err) {
                Pump.error("Couldn't get OAuth credentials. :(");
            } else {
                options.consumerKey = cred.clientID;
                options.consumerSecret = cred.clientSecret;
                pair = Pump.getUserCred();

                if (pair) {
                    options.token = pair.token;
                    options.tokenSecret = pair.secret;
                }

                options = Pump.oauthify(options);
                $.ajax(options);
            }
        });
    };
})(window._, window.$, window.Backbone, window.Pump);
<commit_msg>Add infinite scroll<commit_after>// pump.js
//
// Entrypoint for the pump.io client UI
//
// Copyright 2011-2012, StatusNet Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Make sure this exists

if (!window.Pump) {
    window.Pump = {};
}

(function(_, $, Backbone, Pump) {

    // This is overwritten by inline script in layout.utml

    Pump.config = {};

    // Main entry point

    $(document).ready(function() {

        // XXX: set up initial models

        // Set up router

        Pump.router   = new Pump.Router();

        // Set up initial view

        Pump.body     = new Pump.BodyView({el: $("body")});
        Pump.body.nav = new Pump.AnonymousNav({el: ".navbar-inner .container"});

        // XXX: Make this more complete

        if ($("#content #login").length > 0) {
            Pump.body.content = new Pump.LoginContent();
        } else if ($("#content #registration").length > 0) {
            Pump.body.content = new Pump.RegisterContent();
        } else if ($("#content #user").length > 0) {
            Pump.body.content = new Pump.UserPageContent({});
        } else if ($("#content #inbox").length > 0) {
            Pump.body.content = new Pump.InboxContent({});
        }

        $("abbr.easydate").easydate();

        Backbone.history.start({pushState: true, silent: true});

        Pump.setupWysiHTML5();

        // Refresh the streams automatically every 60 seconds
        // This is a fallback in case something gets lost in the
        // SockJS conversation

        Pump.refreshStreamsID = setInterval(Pump.refreshStreams, 60000);

        // Connect to current server

        if (Pump.config.sockjs) {
            Pump.setupSocket();
        }

        Pump.setupInfiniteScroll();

        // Check if we have stored OAuth credentials

        Pump.ensureCred(function(err, cred) {

            var user, nickname, pair, major, minor;

            if (err) {
                Pump.error(err.message);
                return;
            }

            nickname = Pump.getNickname();

            if (nickname) {

                user = new Pump.User({nickname: nickname});
                major = user.majorDirectInbox;
                minor = user.minorDirectInbox;

                Pump.fetchObjects([user, major, minor], function(objs) {
                    var sp, continueTo;

                    Pump.currentUser = user;

                    Pump.body.nav = new Pump.UserNav({el: ".navbar-inner .container",
                                                      model: user,
                                                      data: {
                                                          messages: major,
                                                          notifications: minor
                                                      }});
                    Pump.body.nav.render();

                    // If we're on the login page, and there's a current
                    // user, redirect to the actual page

                    switch (window.location.pathname) {
                    case "/main/login":
                        Pump.body.content = new Pump.LoginContent();
                        continueTo = Pump.getContinueTo();
                        Pump.router.navigate(continueTo, true);
                        break;
                    case "/":
                        Pump.router.home();
                        break;
                    }
                });
            }
        });
    });

    // When errors happen, and you don't know what to do with them,
    // send them here and I'll figure it out.

    Pump.error = function(err) {
        console.log(err);
    };

    // Given a relative URL like /main/register, make a fully-qualified
    // URL on the current server

    Pump.fullURL = function(url) {

        var here = window.location;

        if (url.indexOf(':') == -1) {
            if (url.substr(0, 1) == '/') {
                url = here.protocol + '//' + here.host + url;
            } else {
                url = here.href.substr(0, here.href.lastIndexOf('/') + 1) + url;
            }
        }

        return url;
    };

    // Add some OAuth magic to the arguments for a $.ajax() call

    Pump.oauthify = function(options) {

        options.url = Pump.fullURL(options.url);

        var message = {action: options.url,
                       method: options.type,
                       parameters: [["oauth_version", "1.0"],
                                    ["oauth_consumer_key", options.consumerKey]]};

        if (options.token) {
            message.parameters.push(["oauth_token", options.token]);
        }

        OAuth.setTimestampAndNonce(message);
        OAuth.SignatureMethod.sign(message,
                                   {consumerSecret: options.consumerSecret,
                                    tokenSecret: options.tokenSecret});

        var header =  OAuth.getAuthorizationHeader("OAuth", message.parameters);

        options.headers = {Authorization: header};

        return options;
    };

    Pump.fetchObjects = function(orig, callback) {
        var fetched = 0,
            objs = (orig.length) > 0 ? orig.slice(0) : [], // make a dupe in case arg is changed
            count = objs.length,
            done = false,
            onSuccess = function() {
                if (!done) {
                    fetched++;
                    if (fetched >= count) {
                        done = true;
                        callback(objs);
                    }
                }
            },
            onError = function() {
                if (!done) {
                    done = true;
                    callback(null);
                }
            };

        _.each(objs, function(obj) {
            try {
                obj.fetch({success: onSuccess,
                           error: onError});
            } catch (e) {
                Pump.error(e.message);
                onError();
            }
        });
    };

    // Not the most lovely, but it works
    // XXX: change this to use UTML templating instead

    Pump.wysihtml5Tmpl = {
        "emphasis": function(locale) {
            return "
" +
                "
" +
                "" +
                "" +
                "_" +
                "
" +
                "
";
        }
    };

    // Most long-form descriptions and notes use this lib for editing

    Pump.setupWysiHTML5 = function() {

        // Set wysiwyg defaults

        $.fn.wysihtml5.defaultOptions["font-styles"] = false;
        $.fn.wysihtml5.defaultOptions["image"] = false;
        $.fn.wysihtml5.defaultOptions["customTemplates"] = Pump.wysihtml5Tmpl;
    };

    // Turn the querystring into an object

    Pump.searchParams = function(str) {
        var params = {},
            pl     = /\+/g,
            decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
            pairs;

        if (!str) {
            str = window.location.search;
        }

        pairs = str.substr(1).split("&");

        _.each(pairs, function(pairStr) {
            var pair = pairStr.split("=", 2),
                key = decode(pair[0]),
                value = (pair.length > 1) ? decode(pair[1]) : null;

            params[key] = value;
        });

        return params;
    };

    // Get the "continue" param

    Pump.getContinueTo = function() {
        var sp = Pump.searchParams(),
            continueTo = (_.has(sp, "continue")) ? sp["continue"] : null;
        if (continueTo && continueTo.length > 0 && continueTo[0] == "/") {
            return continueTo;
        } else {
            return "";
        }
    };

    // We clear out cached stuff when login state changes

    Pump.clearCaches = function() {
        Pump.Model.clearCache();
        Pump.Collection.clearCache();
        Pump.User.clearCache();
    };

    Pump.ajax = function(options) {
        Pump.ensureCred(function(err, cred) {
            var pair;
            if (err) {
                Pump.error("Couldn't get OAuth credentials. :(");
            } else {
                options.consumerKey = cred.clientID;
                options.consumerSecret = cred.clientSecret;
                pair = Pump.getUserCred();

                if (pair) {
                    options.token = pair.token;
                    options.tokenSecret = pair.secret;
                }

                options = Pump.oauthify(options);
                $.ajax(options);
            }
        });
    };

    Pump.setupInfiniteScroll = function() {

        var didScroll = false;

        // scroll fires too fast, so just use the handler
        // to set a flag, and check that flag with an interval

        // From http://ejohn.org/blog/learning-from-twitter/

        $(window).scroll(function() {
            didScroll = true;
        });

        setInterval(function() {
            var streams;
            if (didScroll) {
                didScroll = false;
                if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
                    streams = Pump.getStreams();
                    if (streams.major && streams.major.nextLink) {
                        streams.major.getNext();
                    }
                }
            }
        }, 250);
    };

})(window._, window.$, window.Backbone, window.Pump);
<|endoftext|>


<commit_before>'use strict';

/**
 * "Coup de Grace" is a cooldown action that does 1000 potency damage to a
 * target whos health is at 30% or less.
 * @author Ryan Sandor Richards
 */
Commands.addCooldown('coup', {
  displayName: 'coup de grace',
  cooldownDuration: 120,
  initiatesCombat: true,
  basePotency: 1000,
  spCost: 10,
  run: function (player, target, level, cooldown) {
    return cooldown.executeAttack(target);
  },
  checkValidTarget: function (target) {
    if (target.getHp() / target.getMaxHp() >= 0.3) {
      throw new Error(
        'Coup de grace can only be used on targets with less than 30% health.'
      );
    }
  }
});
<commit_msg>Fixed coup de grace<commit_after>'use strict';

/**
 * "Coup de Grace" is a cooldown action that does 1000 potency damage to a
 * target whos health is at 30% or less.
 * @author Ryan Sandor Richards
 */
Commands.addCooldown('coup', {
  displayName: 'coup de grace',
  cooldownDuration: 120,
  initiatesCombat: true,
  basePotency: 1000,
  spCost: 10,
  run: function (player, target, level, cooldown) {
    return cooldown.executeAttack(player, target);
  },
  checkValidTarget: function (target) {
    if (target.getHp() / target.getMaxHp() >= 0.3) {
      throw new Error(
        'Coup de grace can only be used on targets with less than 30% health.'
      );
    }
  }
});
<|endoftext|>


<commit_before>  //setup offline storage
  var marks_store = new Lawnchair({name:'marks', adaptor:'dom indexed-db webkit-sqlite window-name'}, function(marks) {});
  var mark_count = 0;
  var longest_streak = 0;
  var logged_in = false;
  if(typeof userMarks !== "undefined" && userMarks) {
      displayClear = false;
  } else {
      displayClear = true;
  }

  $(function(){
    //display calendar
    $("#calendar").calendarWidget({});
    setTimeout(function() { window.scrollTo(0, 1) }, 1000);

    if(typeof userMarks !== "undefined" && userMarks) {
      restoreUserMarks();
    } else {
      auth();
      restore_marks();
      //oddly this blows up rails 3 locally on my machine
      //jQuery.ajaxSetup({
      //	'beforeSend': function(xhr) {
      //	  xhr.setRequestHeader("Accept", "text/javascript")
      //	    }
      //  });
      sync();
      //if we reconnect to the net sync again
      $(window).bind("online", reconnected);
    }
  });

  var restoreUserMarks = function() {
    mark_count = 0;
    var data = userMarks.data
    $.each(data, function(index, item) {
        if(item.key!="last_updated") {
	  mark_count += 1;
          console.log('cached-mark: '+item.key);
          $("#"+item.key.replace(/ /g,'.')).addClass('xmarksthespot');
        } else {
          console.log('last updated: '+item.key+' : '+item.val);
        }
      });
    $("#total-marks").html(mark_count);
    streaks();
  }

  var update_links = function() {
    $(".date-item").click( function(){
      if($(this).hasClass('xmarksthespot')) {
        $(this).toggleClass('xmarksthespot');
        marks_store.remove($(this).attr('id'), function() {});
        mark_count -= 1;
      } else {
        marks_store.save({key:$(this).attr('id'),val:true});
        $(this).toggleClass('xmarksthespot');
        mark_count += 1;
      }
      marks_store.save({key:'last_updated',val:new Date()});
      $("#total-marks").html(mark_count);
      streaks();
      sync();
      return false;
    });

    $('#next-month').click( function() {
      var next_month = month + 1;
      if(next_month >= 12) {
        year = year + 1;
        next_month = 0;
      }
      $("#calendar").calendarWidget({
        month: next_month,
	year: year
      });
      restore_marks();
      return false;
    });

    $('#prev-month').click( function() {
      var prev_month = month - 1;
      if(prev_month < 0) {
        year = year - 1;
        prev_month = 11;
      }
      $("#calendar").calendarWidget({
        month: prev_month,
	year: year
      });
      restore_marks();
      return false;
    });

    $('#clear-all').click( function() {
      marks_store.nuke();
      mark_count = 0;
      $("#calendar").calendarWidget({
        month: month,
	year: year
      });
      restore_marks();
      displayNotice("Local Marks cleared");
      return false;
    });

    $('#logout').click( function() {
      marks_store.nuke();
      logged_in = false;
      mark_count = 0;
      $("#calendar").calendarWidget({
        month: month,
	      year: year
      });
      restore_marks();
      displayNotice("You are now logged out!");
      return true;
    });

  }

  var reconnected = function() {
    auth();
    sync();
  }

  var auth = function() {
    if (window.navigator.onLine) {
    console.log("check auth");
    $.get("/site/auth", function (data) {
	  console.log('auth resp');
	  console.log(data);
    if(data['email']) {
	      $("#auth-state").html("Logged in as "+data['email']+"
Not you? Sign out");
        logged_in = true;
	  } else {
	      $("#auth-state").html("Sign In or Sign Up");
        logged_in = false;
	  }
      });
    } else {
      console.log("offline try later");
      $("#auth-state").html("offline mode, syncing disabled");
    }
  }

  var sync = function() {
    if (window.navigator.onLine) {
        if(logged_in==true) {
            console.log("start sync");
            sync_data = [];
            marks_store.all(function(items) { sync_data = items });
            sync_data = {'data':JSON.stringify(sync_data)}
            console.log('sync data: '+sync_data);
            $.post("/marks/sync", sync_data, function (data) {
                console.log('results: '+data['force_update']);
                if(data['force_update']) {
	                  marks_store.nuke();
	                  restore_marks();
                    marks_data = data['data'];
	                  $.each(marks_data, function(index, record) {
	                      console.log('item: '+index+': '+record['key']+':'+record['val']);
	                      marks_store.save({key:record['key'],val:record['val']});
	                      restore_marks();
	                  });
                }
            });
        } else {
          displayNotice("No syncing occurs unless logged in");
        }
    } else {
      console.log("offline try later");
      displaError("No syncing occurs during offline mode");
    }
  }

  var displayNotice = function(message) {
    $("#messages .notice").html("");
    $("#messages .error").html("");
    $("#messages .notice").html(message);
    $("#messages").slideDown();
    setTimeout("$('#messages').slideUp();", 15000)
  }

  var displaError = function(message) {
    $("#messages .notice").html("");
    $("#messages .error").html("");
    $("#messages .error").html(message);
    $("#messages").slideDown();
    setTimeout("$('#messages').slideUp();", 15000)
  }

  var restore_marks = function() {
    update_links();
    mark_count = 0;
    marks_store.all(function(items) {
      items.forEach(function(item) {
        if(item.key!="last_updated") {
	        mark_count += 1;
          console.log('cached-mark: '+item.key);
          $("#"+item.key.replace(/ /g,'.')).addClass('xmarksthespot');
        } else {
          console.log('last updated: '+item.key+' : '+item.val);
        }
      });
    });
    $("#total-marks").html(mark_count);
    streaks();
  }

  var dateFormatted = function(d) {
    var curr_date  = zeroPad(d.getDate(),2);
    var curr_month = zeroPad(d.getMonth() + 1,2); //months are zero based
    var curr_year  = zeroPad(d.getFullYear(),2);
    return (curr_month + "-" + curr_date + "-" + curr_year);
  }

  var zeroPad = function (num,count) {
    var numZeropad = num + '';
    while(numZeropad.length < count) {
      numZeropad = "0" + numZeropad;
    }
    return numZeropad;
  }

  //todo refactor this
  var streaks = function() {
    longest_streak = 0;
    var streak_count = 0;
    var current_streak = [];
    var current_streak_count = 0;
    var today = new Date();
    var yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);

    var loopIteration = function(record, index) {
	//seriously jquery loop and lawnchair loop have record and index in opposite fields
	//TODO find a better way to swap or make more explicit with mehtod call
	//TODO only swap when they are backwards
	item = index
	index = record
	record = item

        if(record.key!='last_updated') {

        if(current_streak.length==0) {
          //console.log('first: '+record.key);
          current_streak.push(record.key)
          streak_count = current_streak.length;
          if(streak_count > longest_streak) {
            longest_streak = streak_count;
          }

        } else if(current_streak.length>0) {
          //console.log('more than one');
          var tomorrow = new Date();
          var parts = current_streak[current_streak.length-1].split('-');
          tomorrow.setFullYear(parts[2], parts[0]-1, parts[1]); // year, month (0-based), day
          tomorrow.setTime(tomorrow.getTime() + 86400000);
          //console.log('tomorrow: '+dateFormatted(tomorrow));
          //console.log('matching: '+record.key);
          if(dateFormatted(tomorrow)==record.key) {
            //console.log('hit single');
            current_streak.push(record.key);
            streak_count = current_streak.length;
            if(streak_count > longest_streak) {
              longest_streak = streak_count;
            }
          } else {
            //update current streak
            $.each(current_streak, function(index, value) {
              //console.log('today:'+dateFormatted(today));
              //console.log('match:'+value);
              if(dateFormatted(today)==value) {
                current_streak_count = current_streak.length;
              }
            });

            current_streak = [];
            current_streak.push(record.key)
            if(dateFormatted(today)==record.key || dateFormatted(yesterday)==record.key) {
              current_streak_count = current_streak.length;
            }
          }

        }
      }
    };

    if(typeof userMarks !== "undefined" && userMarks) {
      var data = userMarks.data
      console.log('data: '+data);
      $.each(data, loopIteration);
    } else {
    marks_store.where('record.val==true').asc('key', function(){
      this.each( loopIteration );
      });
    }

    //update current streak, which didn't hit the next streak case
    $.each(current_streak, function(index, value) {
      //console.log('today:'+dateFormatted(today));
      //console.log('match:'+value);
      if(dateFormatted(today)==value || dateFormatted(yesterday)==value) {
        current_streak_count = current_streak.length;
      }
    });

    $("#longest-streak").html(longest_streak);
    $("#current-streak").html(current_streak_count);
  }
<commit_msg>fix loop function variable order<commit_after>  //setup offline storage
  var marks_store = new Lawnchair({name:'marks', adaptor:'dom indexed-db webkit-sqlite window-name'}, function(marks) {});
  var mark_count = 0;
  var longest_streak = 0;
  var logged_in = false;
  if(typeof userMarks !== "undefined" && userMarks) {
      displayClear = false;
  } else {
      displayClear = true;
  }

  $(function(){
    //display calendar
    $("#calendar").calendarWidget({});
    setTimeout(function() { window.scrollTo(0, 1) }, 1000);

    if(typeof userMarks !== "undefined" && userMarks) {
      restoreUserMarks();
    } else {
      auth();
      restore_marks();
      //oddly this blows up rails 3 locally on my machine
      //jQuery.ajaxSetup({
      //	'beforeSend': function(xhr) {
      //	  xhr.setRequestHeader("Accept", "text/javascript")
      //	    }
      //  });
      sync();
      //if we reconnect to the net sync again
      $(window).bind("online", reconnected);
    }
  });

  var restoreUserMarks = function() {
    mark_count = 0;
    var data = userMarks.data
    $.each(data, function(index, item) {
        if(item.key!="last_updated") {
	  mark_count += 1;
          console.log('cached-mark: '+item.key);
          $("#"+item.key.replace(/ /g,'.')).addClass('xmarksthespot');
        } else {
          console.log('last updated: '+item.key+' : '+item.val);
        }
      });
    $("#total-marks").html(mark_count);
    streaks();
  }

  var update_links = function() {
    $(".date-item").click( function(){
      if($(this).hasClass('xmarksthespot')) {
        $(this).toggleClass('xmarksthespot');
        marks_store.remove($(this).attr('id'), function() {});
        mark_count -= 1;
      } else {
        marks_store.save({key:$(this).attr('id'),val:true});
        $(this).toggleClass('xmarksthespot');
        mark_count += 1;
      }
      marks_store.save({key:'last_updated',val:new Date()});
      $("#total-marks").html(mark_count);
      streaks();
      sync();
      return false;
    });

    $('#next-month').click( function() {
      var next_month = month + 1;
      if(next_month >= 12) {
        year = year + 1;
        next_month = 0;
      }
      $("#calendar").calendarWidget({
        month: next_month,
	year: year
      });
      restore_marks();
      return false;
    });

    $('#prev-month').click( function() {
      var prev_month = month - 1;
      if(prev_month < 0) {
        year = year - 1;
        prev_month = 11;
      }
      $("#calendar").calendarWidget({
        month: prev_month,
	year: year
      });
      restore_marks();
      return false;
    });

    $('#clear-all').click( function() {
      marks_store.nuke();
      mark_count = 0;
      $("#calendar").calendarWidget({
        month: month,
	year: year
      });
      restore_marks();
      displayNotice("Local Marks cleared");
      return false;
    });

    $('#logout').click( function() {
      marks_store.nuke();
      logged_in = false;
      mark_count = 0;
      $("#calendar").calendarWidget({
        month: month,
	      year: year
      });
      restore_marks();
      displayNotice("You are now logged out!");
      return true;
    });

  }

  var reconnected = function() {
    auth();
    sync();
  }

  var auth = function() {
    if (window.navigator.onLine) {
    console.log("check auth");
    $.get("/site/auth", function (data) {
	  console.log('auth resp');
	  console.log(data);
    if(data['email']) {
	      $("#auth-state").html("Logged in as "+data['email']+"
Not you? Sign out");
        logged_in = true;
	  } else {
	      $("#auth-state").html("Sign In or Sign Up");
        logged_in = false;
	  }
      });
    } else {
      console.log("offline try later");
      $("#auth-state").html("offline mode, syncing disabled");
    }
  }

  var sync = function() {
    if (window.navigator.onLine) {
        if(logged_in==true) {
            console.log("start sync");
            sync_data = [];
            marks_store.all(function(items) { sync_data = items });
            sync_data = {'data':JSON.stringify(sync_data)}
            console.log('sync data: '+sync_data);
            $.post("/marks/sync", sync_data, function (data) {
                console.log('results: '+data['force_update']);
                if(data['force_update']) {
	                  marks_store.nuke();
	                  restore_marks();
                    marks_data = data['data'];
	                  $.each(marks_data, function(index, record) {
	                      console.log('item: '+index+': '+record['key']+':'+record['val']);
	                      marks_store.save({key:record['key'],val:record['val']});
	                      restore_marks();
	                  });
                }
            });
        } else {
          displayNotice("No syncing occurs unless logged in");
        }
    } else {
      console.log("offline try later");
      displaError("No syncing occurs during offline mode");
    }
  }

  var displayNotice = function(message) {
    $("#messages .notice").html("");
    $("#messages .error").html("");
    $("#messages .notice").html(message);
    $("#messages").slideDown();
    setTimeout("$('#messages').slideUp();", 15000)
  }

  var displaError = function(message) {
    $("#messages .notice").html("");
    $("#messages .error").html("");
    $("#messages .error").html(message);
    $("#messages").slideDown();
    setTimeout("$('#messages').slideUp();", 15000)
  }

  var restore_marks = function() {
    update_links();
    mark_count = 0;
    marks_store.all(function(items) {
      items.forEach(function(item) {
        if(item.key!="last_updated") {
	        mark_count += 1;
          console.log('cached-mark: '+item.key);
          $("#"+item.key.replace(/ /g,'.')).addClass('xmarksthespot');
        } else {
          console.log('last updated: '+item.key+' : '+item.val);
        }
      });
    });
    $("#total-marks").html(mark_count);
    streaks();
  }

  var dateFormatted = function(d) {
    var curr_date  = zeroPad(d.getDate(),2);
    var curr_month = zeroPad(d.getMonth() + 1,2); //months are zero based
    var curr_year  = zeroPad(d.getFullYear(),2);
    return (curr_month + "-" + curr_date + "-" + curr_year);
  }

  var zeroPad = function (num,count) {
    var numZeropad = num + '';
    while(numZeropad.length < count) {
      numZeropad = "0" + numZeropad;
    }
    return numZeropad;
  }

  //todo refactor this
  var streaks = function() {
    longest_streak = 0;
    var streak_count = 0;
    var current_streak = [];
    var current_streak_count = 0;
    var today = new Date();
    var yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);

    var loopIteration = function(record, index) {
        if(typeof record.key==='undefined') {
	  // Seriously jquery loop and lawnchair loop function
          // have record and index in opposite fields
	  // TODO find a better way to swap or make more explicit with mehtod call
	  item = index
	  index = record
	  record = item
	}

        if(record.key!='last_updated') {

        if(current_streak.length==0) {
          //console.log('first: '+record.key);
          current_streak.push(record.key)
          streak_count = current_streak.length;
          if(streak_count > longest_streak) {
            longest_streak = streak_count;
          }

        } else if(current_streak.length>0) {
          //console.log('more than one');
          var tomorrow = new Date();
          var parts = current_streak[current_streak.length-1].split('-');
          tomorrow.setFullYear(parts[2], parts[0]-1, parts[1]); // year, month (0-based), day
          tomorrow.setTime(tomorrow.getTime() + 86400000);
          //console.log('tomorrow: '+dateFormatted(tomorrow));
          //console.log('matching: '+record.key);
          if(dateFormatted(tomorrow)==record.key) {
            //console.log('hit single');
            current_streak.push(record.key);
            streak_count = current_streak.length;
            if(streak_count > longest_streak) {
              longest_streak = streak_count;
            }
          } else {
            //update current streak
            $.each(current_streak, function(index, value) {
              //console.log('today:'+dateFormatted(today));
              //console.log('match:'+value);
              if(dateFormatted(today)==value) {
                current_streak_count = current_streak.length;
              }
            });

            current_streak = [];
            current_streak.push(record.key)
            if(dateFormatted(today)==record.key || dateFormatted(yesterday)==record.key) {
              current_streak_count = current_streak.length;
            }
          }

        }
      }
    };

    if(typeof userMarks !== "undefined" && userMarks) {
      var data = userMarks.data
      console.log('data: '+data);
      $.each(data, loopIteration);
    } else {
    marks_store.where('record.val==true').asc('key', function(){
      this.each( loopIteration );
      });
    }

    //update current streak, which didn't hit the next streak case
    $.each(current_streak, function(index, value) {
      //console.log('today:'+dateFormatted(today));
      //console.log('match:'+value);
      if(dateFormatted(today)==value || dateFormatted(yesterday)==value) {
        current_streak_count = current_streak.length;
      }
    });

    $("#longest-streak").html(longest_streak);
    $("#current-streak").html(current_streak_count);
  }
<|endoftext|>


<commit_before>(function($) {
	$().ready(function() {
		var ANIMATION_SPEED = 250;

		$('body').addClass('js');

		// DMs on the Settings page
		$('#user_enable_dms').click(function(event) {
			$('#dm-priority-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_enable_dms:checked').length == 1)
			$('#dm-priority-container').show();

		// Mentions on the Settings page
		$('#user_enable_mentions').click(function(event) {
			$('#mention-priority-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_enable_mentions:checked').length == 1)
			$('#mention-priority-container').show();

		// Retweets on the Settings page
		$('#user_disable_retweets').click(function(event) {
			$('#retweet-priority-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_disable_retweets:checked').length == 1)
			$('#retweet-priority-container').show();

		// Lists on the Settings page
		$('#user_enable_list').click(function(event) {
			$('#list-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_enable_list:checked').length == 1)
			$('#list-container').show();

		// If the account switcher is available we'll setup some JS to handle it.
		if ($('#account-controls').length) {
			// Reveal account switcher form
			$('#account-controls-link').click(function(event) {
				$(this).blur();
				$('#account-controls').slideToggle(ANIMATION_SPEED);

				event.preventDefault();
			});

			// Automatic form submission whenever a radio account
			// switcher is clicked.
			var currentUserAccount = $('#account-switcher input.radio-button:checked').val();
			$('#account-switcher input.radio-button').click(function(event) {
				if ($(this).val() != currentUserAccount) {
					$('#account-switcher').submit();
				}
			});
		}

	});
})(jQuery);
<commit_msg>Add JS for favourites settings<commit_after>(function($) {
	$().ready(function() {
		var ANIMATION_SPEED = 250;

		$('body').addClass('js');

		// DMs on the Settings page
		$('#user_enable_dms').click(function(event) {
			$('#dm-priority-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_enable_dms:checked').length == 1)
			$('#dm-priority-container').show();

		// Mentions on the Settings page
		$('#user_enable_mentions').click(function(event) {
			$('#mention-priority-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_enable_mentions:checked').length == 1)
			$('#mention-priority-container').show();

		// Retweets on the Settings page
		$('#user_disable_retweets').click(function(event) {
			$('#retweet-priority-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_disable_retweets:checked').length == 1)
			$('#retweet-priority-container').show();

		// Favorites on the Settings page
		$('#user_enable_favorites').click(function(event) {
			$('#favorites-priority-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_enable_favorites:checked').length == 1)
			$('#favorites-priority-container').show();

		// Lists on the Settings page
		$('#user_enable_list').click(function(event) {
			$('#list-container').slideToggle(ANIMATION_SPEED);
		});
		if ($('#user_enable_list:checked').length == 1)
			$('#list-container').show();

		// If the account switcher is available we'll setup some JS to handle it.
		if ($('#account-controls').length) {
			// Reveal account switcher form
			$('#account-controls-link').click(function(event) {
				$(this).blur();
				$('#account-controls').slideToggle(ANIMATION_SPEED);

				event.preventDefault();
			});

			// Automatic form submission whenever a radio account
			// switcher is clicked.
			var currentUserAccount = $('#account-switcher input.radio-button:checked').val();
			$('#account-switcher input.radio-button').click(function(event) {
				if ($(this).val() != currentUserAccount) {
					$('#account-switcher').submit();
				}
			});
		}

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


<commit_before>function CheckLogin(success, failed) {
	$.getJSON("https://api.tnyu.org/v1.0/people/me", function(data) {
		return success(data);
	})
	.fail(function() {
		return failed();
	});
}

function GetNextEvent() {
	$.getJSON("https://api.tnyu.org/v1.0/events/upcoming", function(data) {
		var todaysDate = new Date();
		var eventDate = moment().format(data["events"]["startDateTime"]);
		if(!moment(eventDate).isSame(moment(), 'day')){
			$('#no-event-happening').html('
No event happening today!
');
			$('#next-event-happening').html('Next Event: ' + data["events"]["title"] + "")
			$('#no-event-happening').show();
			$('#next-event-happening').show();
		} else {
			window.location.replace(document.URL+data["events"]["id"]);
		}
	});
}

function Get10NextEvents() {
	$.getJSON("https://api.tnyu.org/v1.0/events", function(data) {

	});
}

function GetUpcomingEvents() {
	$.getJSON("https://api.tnyu.org/v1.0/events", function(data) {

	});
}

CheckLogin(function(data) {
	$('#login').html('Edit Profile');
}, function(){
	$('#login').html('Login');
});

GetNextEvent();<commit_msg>Fixing redirect URL<commit_after>function CheckLogin(success, failed) {
	$.getJSON("https://api.tnyu.org/v1.0/people/me", function(data) {
		return success(data);
	})
	.fail(function() {
		return failed();
	});
}

function GetNextEvent() {
	$.getJSON("https://api.tnyu.org/v1.0/events/upcoming", function(data) {
		var todaysDate = new Date();
		var eventDate = moment().format(data["events"]["startDateTime"]);
		if(!moment(eventDate).isSame(moment(), 'day')){
			$('#no-event-happening').html('
No event happening today!
');
			$('#next-event-happening').html('Next Event: ' + data["events"]["title"] + "")
			$('#no-event-happening').show();
			$('#next-event-happening').show();
		} else {
			window.location.replace(document.URL+data["events"]["id"]);
		}
	});
}

function Get10NextEvents() {
	$.getJSON("https://api.tnyu.org/v1.0/events", function(data) {

	});
}

function GetUpcomingEvents() {
	$.getJSON("https://api.tnyu.org/v1.0/events", function(data) {

	});
}

CheckLogin(function(data) {
	$('#login').html('Edit Profile');
}, function(){
	$('#login').html('Login');
});

GetNextEvent();<|endoftext|>


<commit_before>$(function() {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "positionClass": "toast-bottom-right",
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    // Save shortcut
    Mousetrap.bind('mod+s', function(event) {
        event.preventDefault();
        if ($('.editor')) {
            $('.editor-form').submit();
        }
    });

    // Fork shorcut
    Mousetrap.bind('f', function() {
        if ($('.button.fork')) {
            $('.button.fork')[0].click();
        }
        return false;
    });

    // New shorcut
    Mousetrap.bind('n', function() {
        if ($('.button.new')) {
            $('.button.new')[0].click();
        }
        return false;
    });

    // Fork shorcut
    Mousetrap.bind('r', function() {
        if ($('.button.raw')) {
            $('.button.raw')[0].click();
        }
        return false;
    });

    Mousetrap.bind('mod+c', function() {
        if (window.getSelection().toString() == '') {
            if ($('.button.copy')) {
                $('#copy-data').val(location.toString()).select();
                toastr.info('Copied URL to clipboard! ' + $('#copy-data').val());
            }
        }
    });

    // Setup tabby
    var tabbyOptions = { tabString:'    '};
    $('.editor').focus().tabby(tabbyOptions);

    // Setup copy
    $(document).on('copy', function (event) {
        if (window.getSelection().toString() == '') {
            event.preventDefault();
            var url = $('#copy-data').val();
            event.originalEvent.clipboardData.setData('text/plain', url);
        }
    });

    $('.button.copy').zclip({
        path: '/javascripts/vendor/ZeroClipboard.swf',
        copy: location.toString(),
        afterCopy: function() {
            toastr.info('Copied URL to clipboard! ' + location.toString());
        }
    });

    (function($){

        var defaults = {
            $list: $('.list'),
            selectedClass: 'selected',
            preventTextSelectionClass: 'prevent-user-select'
        },
        _lines, options, $lastLineToggled;

        // Call this public method like $.myMethod();
        $.handleLines = function(options){
            defaults = $.extend(defaults, options);
            defaults.$lines = defaults.$list.find('li');

            _lines = expandLines(window.location.hash);
            highlight();
            events();
        };

        function highlight() {
            for(var i = 0; i < _lines.length; i++) {
                defaults.$lines.eq(_lines[i] - 1).addClass(defaults.selectedClass);
            }
        }

        function events() {
            defaults.$list.on('click', 'li', function (e) {
                var $line = $(this);
                if ($lastLineToggled && e.shiftKey) {
                    var $range,
                        lineIndex = $line.index(),
                        lastLineIndex = $lastLineToggled.index() + 1;

                    $range = (lineIndex > lastLineIndex) ? defaults.$lines.slice(lastLineIndex, lineIndex + 1) : defaults.$lines.slice(lineIndex, lastLineIndex - 1);

                    if ($line.hasClass(defaults.selectedClass)) {
                        $range.removeClass(defaults.selectedClass);
                    } else {
                        $range.addClass(defaults.selectedClass);
                    }
                    manage($range);
                } else {
                    $line.toggleClass(defaults.selectedClass);
                    manage($line);
                }
                $lastLineToggled = $line;
            });

            $(document).mousedown(function (e) {
                if (e.shiftKey) e.preventDefault();
            });
        }

        /* expand #1-7,12,20 into [1,2,3,4,5,6,7,12,20] */
        function expandLines(lines) {
            if(lines == '') return [];
            lines = lines.replace(/#/g, '').split(',');
            var linesExpanded = [];
            for(var i in lines) {
                if(lines.hasOwnProperty(i)) {
                    linesExpanded = linesExpanded.concat(expand(lines[i]));
                }
            }

            return sanitize(linesExpanded)
        }

        function expand(item) {
            return (item.indexOf('-') > 0) ? generateRange(item.split('-')) : [parseInt(item, 10)];
        }

        function generateRange(values) {
            var range = [];
            for (var i = parseInt(values[0], 10); i <= parseInt(values[1], 10); i++) {
                range.push(i);
            }
            return range;
        }

        /* sort linesnumbers array and remove duplicate numbers */
        function sanitize(lines) {
            lines = lines.sort(function(a, b) { return a-b; });
            uniqueLines = [];
            for(var i = 0; i < lines.length; i++) {
                if(uniqueLines.indexOf(lines[i]) === -1) uniqueLines.push(lines[i]);
            }
            return uniqueLines;
        }

        /* collapse [1,2,3,4,5,6,7,12,20] into #1-7,12,20 */
        function collapser() {
            lines = sanitize(_lines);
            var ranges = [], rstart, rend;
            for (var i = 0; i < lines.length; i++) {
                rstart = lines[i];
                rend = rstart;
                while (lines[i + 1] - lines[i] == 1) {
                    rend = lines[i + 1];
                    i++;
                }
                ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend);
            }
            return '#' + ranges.join(',');
        }

        /* update lines array */
        function manage(items) {
            items.each(function() {
                var indexOfLine = $(this).index() + 1,
                    indexInLinesArray = _lines.indexOf(indexOfLine);

                if(indexInLinesArray < 0) {
                    _lines.push(indexOfLine);
                } else {
                    _lines.splice(indexInLinesArray, 1);
                }
            });
            window.location.hash = collapser();
        }

    })(jQuery);

    prettyPrint(function() {
        $.handleLines({
            $list: $('ol.linenums'),
            selectClass: 'selected',
            preventTextSelectionClass: 'prevent-user-select'
        });
    });

});

// // drag and drop file api stuff
// function handleFileSelect(e) {
//   e.stopPropagation();
//   e.preventDefault();

//   var files = e.dataTransfer.files;

//   $.each(files, function() {
//     var file = this;

//     // if ( ! file.type.match('text.*')) {
//     //   continue;
//     // }

//     var reader = new FileReader();

//     reader.onload = (function() {
//       return function(e) {
//         addFile(file.name, e.target.result);
//       };
//     })(file);

//     reader.readAsText(file);
//   });
// }

// function handleDragOver(e) {
//   e.stopPropagation();
//   e.preventDefault();
//   e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
// }

// function bindDragAndDrop() {
//   var dropZone = document.getElementById('drop_zone');
//   dropZone.addEventListener('dragover', handleDragOver, false);
//   dropZone.addEventListener('drop', handleFileSelect, false);
// }

// //
// function addFile(name, contents) {
//   var template = $('._file_template').html();

//   template = template.replace(/\|filename\|/g, name);
//   template = template.replace(/\|contents\|/g, contents);

//   $('._files').append(template);
// }

// // go
// $(function() {
//   bindDragAndDrop();
// });<commit_msg>Fixed a bug where backwards selection caused inconsistencies<commit_after>$(function() {
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "positionClass": "toast-bottom-right",
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "5000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    }

    // Save shortcut
    Mousetrap.bind('mod+s', function(event) {
        event.preventDefault();
        if ($('.editor')) {
            $('.editor-form').submit();
        }
    });

    // Fork shorcut
    Mousetrap.bind('f', function() {
        if ($('.button.fork')) {
            $('.button.fork')[0].click();
        }
        return false;
    });

    // New shorcut
    Mousetrap.bind('n', function() {
        if ($('.button.new')) {
            $('.button.new')[0].click();
        }
        return false;
    });

    // Fork shorcut
    Mousetrap.bind('r', function() {
        if ($('.button.raw')) {
            $('.button.raw')[0].click();
        }
        return false;
    });

    Mousetrap.bind('mod+c', function() {
        if (window.getSelection().toString() == '') {
            if ($('.button.copy')) {
                $('#copy-data').val(location.toString()).select();
                toastr.info('Copied URL to clipboard! ' + $('#copy-data').val());
            }
        }
    });

    // Setup tabby
    var tabbyOptions = { tabString:'    '};
    $('.editor').focus().tabby(tabbyOptions);

    // Setup copy
    $(document).on('copy', function (event) {
        if (window.getSelection().toString() == '') {
            event.preventDefault();
            var url = $('#copy-data').val();
            event.originalEvent.clipboardData.setData('text/plain', url);
        }
    });

    $('.button.copy').zclip({
        path: '/javascripts/vendor/ZeroClipboard.swf',
        copy: location.toString(),
        afterCopy: function() {
            toastr.info('Copied URL to clipboard! ' + location.toString());
        }
    });

    (function($){

        var defaults = {
            $list: $('.list'),
            selectedClass: 'selected',
            preventTextSelectionClass: 'prevent-user-select'
        },
        _lines, options, $lastLineToggled;

        // Call this public method like $.myMethod();
        $.handleLines = function(options){
            defaults = $.extend(defaults, options);
            defaults.$lines = defaults.$list.find('li');

            _lines = expandLines(window.location.hash);
            highlight();
            events();
        };

        function highlight() {
            for(var i = 0; i < _lines.length; i++) {
                defaults.$lines.eq(_lines[i] - 1).addClass(defaults.selectedClass);
            }
        }

        function events() {
            defaults.$list.on('click', 'li', function (e) {
                var $line = $(this);
                if ($lastLineToggled && e.shiftKey) {
                    var $range,
                        lineIndex = $line.index(),
                        lastLineIndex = $lastLineToggled.index() + 1;

                    $range = (lineIndex > lastLineIndex) ? defaults.$lines.slice(lastLineIndex, lineIndex + 1) : defaults.$lines.slice(lineIndex, lastLineIndex - 1);
                    $range.toggleClass(defaults.selectedClass);
                    manage($range);
                } else {
                    $line.toggleClass(defaults.selectedClass);
                    manage($line);
                }
                $lastLineToggled = $line;
            });

            $(document).mousedown(function (e) {
                if (e.shiftKey) e.preventDefault();
            });
        }

        /* expand #1-7,12,20 into [1,2,3,4,5,6,7,12,20] */
        function expandLines(lines) {
            if(lines == '') return [];
            lines = lines.replace(/#/g, '').split(',');
            var linesExpanded = [];
            for(var i in lines) {
                if(lines.hasOwnProperty(i)) {
                    linesExpanded = linesExpanded.concat(expand(lines[i]));
                }
            }

            return sanitize(linesExpanded)
        }

        function expand(item) {
            return (item.indexOf('-') > 0) ? generateRange(item.split('-')) : [parseInt(item, 10)];
        }

        function generateRange(values) {
            var range = [];
            for (var i = parseInt(values[0], 10); i <= parseInt(values[1], 10); i++) {
                range.push(i);
            }
            return range;
        }

        /* sort linesnumbers array and remove duplicate numbers */
        function sanitize(lines) {
            lines = lines.sort(function(a, b) { return a-b; });
            uniqueLines = [];
            for(var i = 0; i < lines.length; i++) {
                if(uniqueLines.indexOf(lines[i]) === -1) uniqueLines.push(lines[i]);
            }
            return uniqueLines;
        }

        /* collapse [1,2,3,4,5,6,7,12,20] into #1-7,12,20 */
        function collapser() {
            lines = sanitize(_lines);
            var ranges = [], rstart, rend;
            for (var i = 0; i < lines.length; i++) {
                rstart = lines[i];
                rend = rstart;
                while (lines[i + 1] - lines[i] == 1) {
                    rend = lines[i + 1];
                    i++;
                }
                ranges.push(rstart == rend ? rstart+'' : rstart + '-' + rend);
            }
            return '#' + ranges.join(',');
        }

        /* update lines array */
        function manage(items) {
            items.each(function() {
                var indexOfLine = $(this).index() + 1,
                    indexInLinesArray = _lines.indexOf(indexOfLine);

                if(indexInLinesArray < 0) {
                    _lines.push(indexOfLine);
                } else {
                    _lines.splice(indexInLinesArray, 1);
                }
            });
            window.location.hash = collapser();
        }

    })(jQuery);

    prettyPrint(function() {
        $.handleLines({
            $list: $('ol.linenums'),
            selectClass: 'selected',
            preventTextSelectionClass: 'prevent-user-select'
        });
    });

});

// // drag and drop file api stuff
// function handleFileSelect(e) {
//   e.stopPropagation();
//   e.preventDefault();

//   var files = e.dataTransfer.files;

//   $.each(files, function() {
//     var file = this;

//     // if ( ! file.type.match('text.*')) {
//     //   continue;
//     // }

//     var reader = new FileReader();

//     reader.onload = (function() {
//       return function(e) {
//         addFile(file.name, e.target.result);
//       };
//     })(file);

//     reader.readAsText(file);
//   });
// }

// function handleDragOver(e) {
//   e.stopPropagation();
//   e.preventDefault();
//   e.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
// }

// function bindDragAndDrop() {
//   var dropZone = document.getElementById('drop_zone');
//   dropZone.addEventListener('dragover', handleDragOver, false);
//   dropZone.addEventListener('drop', handleFileSelect, false);
// }

// //
// function addFile(name, contents) {
//   var template = $('._file_template').html();

//   template = template.replace(/\|filename\|/g, name);
//   template = template.replace(/\|contents\|/g, contents);

//   $('._files').append(template);
// }

// // go
// $(function() {
//   bindDragAndDrop();
// });<|endoftext|>


<commit_before>var map;
var markers;
var popup;

function createMap(divName) {
   OpenLayers.Util.onImageLoadError = function() {
      this.src = OpenLayers.Util.getImagesLocation() + "404.png";
   }

   map = new OpenLayers.Map(divName,
                            { maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
                              numZoomLevels: 19,
                              maxResolution: 156543,
                              units: 'm',
                              projection: "EPSG:41001" });

   var mapnik = new OpenLayers.Layer.TMS("Mapnik",
                                         ["http://a.tile.openstreetmap.org/","http://b.tile.openstreetmap.org/","http://c.tile.openstreetmap.org/"],
                                         { type: 'png', getURL: getTileURL, displayOutsideMaxExtent: true });
   map.addLayer(mapnik);

   var osmarender = new OpenLayers.Layer.TMS("Osmarender",
                                             "http://tah.openstreetmap.org/Tiles/tile.php/",
                                             { type: 'png', getURL: getTileURL, displayOutsideMaxExtent: true });
   map.addLayer(osmarender);

   markers = new OpenLayers.Layer.Markers("markers", { visibility: false });
   map.addLayer(markers);

   map.addControl(new OpenLayers.Control.LayerSwitcher());

   return map;
}

function getTileURL(bounds) {
   var res = this.map.getResolution();
   var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
   var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
   var z = this.map.getZoom();
   var limit = Math.pow(2, z);

   if (y < 0 || y >= limit)
   {
     return OpenLayers.Util.getImagesLocation() + "404.png";
   }
   else
   {
     x = ((x % limit) + limit) % limit;

     var url = this.url;
     var path = z + "/" + x + "/" + y + "." + this.type;

     if (url instanceof Array)
     {
        url = this.selectUrl(path, url);
     }

     return url + path;
   }
}

function getArrowIcon() {
   var size = new OpenLayers.Size(25, 22);
   var offset = new OpenLayers.Pixel(-30, -27);
   var icon = new OpenLayers.Icon("/images/arrow.png", size, offset);

   return icon;
}

function addMarkerToMap(position, icon, description) {
   var marker = new OpenLayers.Marker(position, icon);

   markers.addMarker(marker);
   markers.setVisibility(true);

   if (description) {
      marker.events.register("click", marker, function() { openMapPopup(marker, description) });
   }

   return marker;
}

function openMapPopup(marker, description) {
   closeMapPopup();

   popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat,
                                               sizeMapPopup(description),
                                               "
" + description + "
",
                                               marker.icon, true);
   popup.setBackgroundColor("#E3FFC5");
   map.addPopup(popup);

   return popup;
}

function closeMapPopup() {
   if (popup) {
      map.removePopup(popup);
      delete popup;
   }
}

function sizeMapPopup(text) {
   var box = document.createElement("div");

   box.innerHTML = text;
   box.style.visibility = "hidden";
   box.style.position = "absolute";
   box.style.top = "0px";
   box.style.left = "0px";
   box.style.width = "200px";
   box.style.height = "auto";

   document.body.appendChild(box);

   var width = box.offsetWidth;
   var height = box.offsetHeight;

   document.body.removeChild(box);

   return new OpenLayers.Size(width + 30, height + 24);
}

function removeMarkerFromMap(marker){
   markers.removeMarker(marker);
}

function getMapLayers() {
   var layers = "";

   for (var i=0; i< this.map.layers.length; i++) {
      var layer = this.map.layers[i];

      if (layer.isBaseLayer) {
         layers += (layer == this.map.baseLayer) ? "B" : "0";
      } else {
         layers += (layer.getVisibility()) ? "T" : "F";
      }
   }

   return layers;
}

function setMapLayers(layers) {
   for (var i=0; i < layers.length; i++) {
      var layer = map.layers[i];
      var c = layers.charAt(i);

      if (c == "B") {
         map.setBaseLayer(layer);
      } else if ( (c == "T") || (c == "F") ) {
         layer.setVisibility(c == "T");
      }
   }
}

function mercatorToLonLat(merc) {
   var lon = (merc.lon / 20037508.34) * 180;
   var lat = (merc.lat / 20037508.34) * 180;

   lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

   return new OpenLayers.LonLat(lon, lat);
}

function lonLatToMercator(ll) {
   var lon = ll.lon * 20037508.34 / 180;
   var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180);

   lat = lat * 20037508.34 / 180;

   return new OpenLayers.LonLat(lon, lat);
}

function scaleToZoom(scale) {
   return Math.log(360.0/(scale * 512.0)) / Math.log(2.0);
}
<commit_msg>Spread T@H over three host names.<commit_after>var map;
var markers;
var popup;

function createMap(divName) {
   OpenLayers.Util.onImageLoadError = function() {
      this.src = OpenLayers.Util.getImagesLocation() + "404.png";
   }

   map = new OpenLayers.Map(divName,
                            { maxExtent: new OpenLayers.Bounds(-20037508,-20037508,20037508,20037508),
                              numZoomLevels: 19,
                              maxResolution: 156543,
                              units: 'm',
                              projection: "EPSG:41001" });

   var mapnik = new OpenLayers.Layer.TMS("Mapnik",
                                         ["http://a.tile.openstreetmap.org/","http://b.tile.openstreetmap.org/","http://c.tile.openstreetmap.org/"],
                                         { type: 'png', getURL: getTileURL, displayOutsideMaxExtent: true });
   map.addLayer(mapnik);

   var osmarender = new OpenLayers.Layer.TMS("Osmarender",
                                             ["http://a.tah.openstreetmap.org/Tiles/tile.php/","http://b.tah.openstreetmap.org/Tiles/tile.php/","http://c.tah.openstreetmap.org/Tiles/tile.php/"],
                                             { type: 'png', getURL: getTileURL, displayOutsideMaxExtent: true });
   map.addLayer(osmarender);

   markers = new OpenLayers.Layer.Markers("markers", { visibility: false });
   map.addLayer(markers);

   map.addControl(new OpenLayers.Control.LayerSwitcher());

   return map;
}

function getTileURL(bounds) {
   var res = this.map.getResolution();
   var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
   var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
   var z = this.map.getZoom();
   var limit = Math.pow(2, z);

   if (y < 0 || y >= limit)
   {
     return OpenLayers.Util.getImagesLocation() + "404.png";
   }
   else
   {
     x = ((x % limit) + limit) % limit;

     var url = this.url;
     var path = z + "/" + x + "/" + y + "." + this.type;

     if (url instanceof Array)
     {
        url = this.selectUrl(path, url);
     }

     return url + path;
   }
}

function getArrowIcon() {
   var size = new OpenLayers.Size(25, 22);
   var offset = new OpenLayers.Pixel(-30, -27);
   var icon = new OpenLayers.Icon("/images/arrow.png", size, offset);

   return icon;
}

function addMarkerToMap(position, icon, description) {
   var marker = new OpenLayers.Marker(position, icon);

   markers.addMarker(marker);
   markers.setVisibility(true);

   if (description) {
      marker.events.register("click", marker, function() { openMapPopup(marker, description) });
   }

   return marker;
}

function openMapPopup(marker, description) {
   closeMapPopup();

   popup = new OpenLayers.Popup.AnchoredBubble("popup", marker.lonlat,
                                               sizeMapPopup(description),
                                               "
" + description + "
",
                                               marker.icon, true);
   popup.setBackgroundColor("#E3FFC5");
   map.addPopup(popup);

   return popup;
}

function closeMapPopup() {
   if (popup) {
      map.removePopup(popup);
      delete popup;
   }
}

function sizeMapPopup(text) {
   var box = document.createElement("div");

   box.innerHTML = text;
   box.style.visibility = "hidden";
   box.style.position = "absolute";
   box.style.top = "0px";
   box.style.left = "0px";
   box.style.width = "200px";
   box.style.height = "auto";

   document.body.appendChild(box);

   var width = box.offsetWidth;
   var height = box.offsetHeight;

   document.body.removeChild(box);

   return new OpenLayers.Size(width + 30, height + 24);
}

function removeMarkerFromMap(marker){
   markers.removeMarker(marker);
}

function getMapLayers() {
   var layers = "";

   for (var i=0; i< this.map.layers.length; i++) {
      var layer = this.map.layers[i];

      if (layer.isBaseLayer) {
         layers += (layer == this.map.baseLayer) ? "B" : "0";
      } else {
         layers += (layer.getVisibility()) ? "T" : "F";
      }
   }

   return layers;
}

function setMapLayers(layers) {
   for (var i=0; i < layers.length; i++) {
      var layer = map.layers[i];
      var c = layers.charAt(i);

      if (c == "B") {
         map.setBaseLayer(layer);
      } else if ( (c == "T") || (c == "F") ) {
         layer.setVisibility(c == "T");
      }
   }
}

function mercatorToLonLat(merc) {
   var lon = (merc.lon / 20037508.34) * 180;
   var lat = (merc.lat / 20037508.34) * 180;

   lat = 180/Math.PI * (2 * Math.atan(Math.exp(lat * Math.PI / 180)) - Math.PI / 2);

   return new OpenLayers.LonLat(lon, lat);
}

function lonLatToMercator(ll) {
   var lon = ll.lon * 20037508.34 / 180;
   var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180);

   lat = lat * 20037508.34 / 180;

   return new OpenLayers.LonLat(lon, lat);
}

function scaleToZoom(scale) {
   return Math.log(360.0/(scale * 512.0)) / Math.log(2.0);
}
<|endoftext|>


<commit_before>/**
 * # WaitRoomView widget for nodeGame
 * Copyright(c) 2019 Stefano Balietti
 * MIT Licensed
 *
 * Shows requirements settings
 *
 * www.nodegame.org
 * ---
 */

(function(node) {
  ("use strict");

  node.widgets.register("WaitRoomView", WaitRoomView);

  var JSUS = node.JSUS;

  // ## Meta-data

  WaitRoomView.version = "0.0.1";
  WaitRoomView.description = "Displays a waitroom settings.";

  WaitRoomView.title = "WaitRoom Settings";
  WaitRoomView.className = "waitroomview";

  // ## Dependencies
  WaitRoomView.dependencies = {
    JSUS: {},
    Table: {}
  };

  var originalTable = {};

  function WaitRoomView(options) {
    var that = this;
    this.table = new W.Table({
      className: "table table-striped viewer",
      id: "settingsTable",
      render: {
        pipeline: function(item) {
          //x = 0 y = 0 first row first column
          //x = 0 y = 1 first row second column
          if (originalTable[item.x] === undefined) {
            originalTable[item.x] = {};
          }
          if (item.y % 2 === 0) {
            originalTable[item.x]["content"] = item.content;
            return document.createTextNode(item.content + ": ");
          } else if (item.y % 2 === 1) {
            originalTable[item.x]["value"] = item.content;

            var inp = document.createElement("input");
            inp.placeholder = originalTable[item.x].value;
            inp.disabled = true;
            inp.id = originalTable[item.x].content;
            return inp;
          }
        }
      }
    });
    this.editSaveButton = document.createElement("button");
    this.editSaveButton.className = "btn btn-primary";
    this.editSaveButton.innerHTML = "Edit";

    this.span = document.createElement("span");
    this.span.className = "origContent";
    this.table.setHeader(["Setting", "Value"]);
    // Creates table.table.
    this.table.parse();
  }

  WaitRoomView.prototype.append = function() {
    var that = this;

    this.bodyDiv.appendChild(this.table.table);
    this.span.appendChild(this.editSaveButton);
    this.bodyDiv.appendChild(this.span);
  };

  WaitRoomView.prototype.listeners = function() {
    var that;
    that = this;
    node.on("CHANNEL_SELECTED", function() {
      that.displayData();
    });
  };

  WaitRoomView.prototype.displayData = function() {
    var i, t, s, tmp;
    var that = this;

    // Not ready yet.
    if (!node.game.gamesInfo) return;
    s = node.game.gamesInfo[node.game.channelInUse].waitroom;
    t = this.table;
    t.clear();

    //LEVELS in case later use
    node.game.gamesInfo[node.game.channelInUse].levels;

    //my settings
    var mySettings =
      node.game.gamesInfo[node.game.channelInUse].settings.standard;

    //remove unnecessary settings
    delete mySettings.SESSION_ID;
    delete mySettings.TIMER;
    delete mySettings.treatmentName;
    delete mySettings.name;

    //I dont think deleting them from a copy object affects anything
    delete s.EXECUTION_MODE;
    delete s.CHOSEN_TREATMENT;
    delete s.TEXTS;
    delete s.SOUND;

    var combinedSettings = mergeObjects(s, mySettings);

    console.log("WAITROOM S: " + JSON.stringify(s));
    console.log("MY SETTINGS: " + JSON.stringify(mySettings));
    console.log("COMBINED " + JSON.stringify(combinedSettings));

    this.editSaveButton.onclick = function() {
      var listOfSettings = [
        (repeat = W.gid("REPEAT")),
        (imageDir = W.gid("IMG_DIR")),
        (nOfNeighbors = W.gid("N_OF_NEIGHBORS")),
        (userDataFolder = W.gid("USER_DATA_FOLDER")),
        (botDataFolder = W.gid("BOT_DATA_FOLDER")),
        (maleNamesPath = W.gid("MALE_NAMES_FILE")),
        (femaleNamesPath = W.gid("FEMALE_NAMES_FILE")),
        (group_size = W.gid("GROUP_SIZE")),
        (playWithBots = W.gid("ALLOW_PLAY_WITH_BOTS"))
      ];

      if (that.editSaveButton.innerHTML == "Edit") {
        that.editSaveButton.innerHTML = "Save";
        for (let x = 0; x < listOfSettings.length; x++) {
          var currentSetting = listOfSettings[x];
          var currentContent = originalTable[x + 1].content;
          var originalValue = originalTable[x + 1].value;

          if (
            currentSetting.value === "" ||
            currentSetting.placeholder == originalValue
          ) {
            //do nothing
          } else {
            currentSetting.placeholder = currentSetting.value;

            //update table structure for prev value
            originalTable[x + 1].value = currentSetting.value;
          }

          currentSetting.disabled = false;
        }
      } else if (that.editSaveButton.innerHTML == "Save") {
        that.editSaveButton.innerHTML = "Edit";

        var changes = {};
        changes["s"] = {};
        changes["mySettings"] = {};
        //disable the field
        for (let x = 0; x < listOfSettings.length; x++) {
          var currentSetting = listOfSettings[x];
          var currentContent = originalTable[x + 1].content;
          var originalValue = originalTable[x + 1].value;
          var currentValue = currentSetting.value;

          //not changed
          if (
            currentSetting.value === "" ||
            currentSetting.value == originalValue
          ) {
          } else {
            //SAVE IN A OBJECT AS STATED

            //waitroom s settings
            if (currentContent == "GROUP_SIZE") {
              changes["s"][currentContent] = parseInt(currentValue);
              changes["s"]["POOL_SIZE"] = parseInt(currentValue);
            } else if (currentContent == "ALLOW_PLAY_WITH_BOTS") {
              changes["s"][currentContent] = currentValue == "true";
            } else if (currentContent == "REPEAT") {
              changes["mySettings"][currentContent] = parseInt(currentValue);
            } else if (currentContent == "IMG_DIR") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "N_OF_NEIGHBORS") {
              changes["mySettings"][currentContent] = parseInt(currentValue);
            } else if (currentContent == "MALE_NAMES_FILE") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "FEMALE_NAMES_FILE") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "USER_DATA_FOLDER") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "BOT_DATA_FOLDER") {
              changes["mySettings"][currentContent] = currentValue;
            }
            //mySettings

            //update original table if any of the inputs is not empty
            originalTable[x + 1].value = currentValue;
          }

          currentSetting.disabled = true;
        }

        console.log("CHANGES: " + JSON.stringify(changes));

        //send changes in waitingroom
        if (!isEmptyObject(changes.s)) {
          node.socket.send(
            node.msg.create({
              target: "SERVERCOMMAND",
              text: "UPDATE_SETTINGS",
              data: {
                type: "waitroom", // or requirements or settings, etc.
                update: changes.s
              },
              levels: true
            })
          );
        }

        //send changes in settings
        if (!isEmptyObject(changes.mySettings)) {
          node.socket.send(
            node.msg.create({
              target: "SERVERCOMMAND",
              text: "UPDATE_SETTINGS",
              data: {
                type: "settings", // or requirements or settings, etc.
                update: changes.mySettings
              },
              levels: true
            })
          );
        }

        //send the new data back to server
      }
    };

    for (let setting in mySettings) {
      if (mySettings.hasOwnProperty(setting)) {
        t.addRow([setting, mySettings[setting]]);
      }
    }

    //standard properties
    for (i in s) {
      if (s.hasOwnProperty(i)) {
        t.addRow([i, s[i]]);
      }
    }

    t.parse();
  };

  //check if object is empty or not (utility function)
  function isEmptyObject(obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) return false;
    }
    return true;
  }

  function mergeObjects(obj1, obj2) {
    var obj3 = {};
    for (var attrname in obj1) {
      obj3[attrname] = obj1[attrname];
    }
    for (var attrname in obj2) {
      obj3[attrname] = obj2[attrname];
    }
    return obj3;
  }
})(node);
<commit_msg>final<commit_after>/**
 * # WaitRoomView widget for nodeGame
 * Copyright(c) 2019 Stefano Balietti
 * MIT Licensed
 *
 * Shows requirements settings
 *
 * www.nodegame.org
 * ---
 */

(function(node) {
  ("use strict");

  node.widgets.register("WaitRoomView", WaitRoomView);

  var JSUS = node.JSUS;

  // ## Meta-data

  WaitRoomView.version = "0.0.1";
  WaitRoomView.description = "Displays a waitroom settings.";

  WaitRoomView.title = "WaitRoom Settings";
  WaitRoomView.className = "waitroomview";

  // ## Dependencies
  WaitRoomView.dependencies = {
    JSUS: {},
    Table: {}
  };

  var originalTable = {};

  function WaitRoomView(options) {
    var that = this;
    this.table = new W.Table({
      className: "table table-striped viewer",
      id: "settingsTable",
      render: {
        pipeline: function(item) {
          //x = 0 y = 0 first row first column
          //x = 0 y = 1 first row second column
          if (originalTable[item.x] === undefined) {
            originalTable[item.x] = {};
          }
          if (item.y % 2 === 0) {
            originalTable[item.x]["content"] = item.content;
            return document.createTextNode(item.content + ": ");
          } else if (item.y % 2 === 1) {
            originalTable[item.x]["value"] = item.content;

            var inp = document.createElement("input");
            inp.placeholder = originalTable[item.x].value;
            inp.disabled = true;
            inp.id = originalTable[item.x].content;
            return inp;
          }
        }
      }
    });
    this.editSaveButton = document.createElement("button");
    this.editSaveButton.className = "btn btn-primary";
    this.editSaveButton.innerHTML = "Edit";

    this.span = document.createElement("span");
    this.span.className = "origContent";
    this.table.setHeader(["Setting", "Value"]);
    // Creates table.table.
    this.table.parse();
  }

  WaitRoomView.prototype.append = function() {
    var that = this;

    this.bodyDiv.appendChild(this.table.table);
    this.span.appendChild(this.editSaveButton);
    this.bodyDiv.appendChild(this.span);
  };

  WaitRoomView.prototype.listeners = function() {
    var that;
    that = this;
    node.on("CHANNEL_SELECTED", function() {
      that.displayData();
    });
  };

  WaitRoomView.prototype.displayData = function() {
    var i, t, s, tmp;
    var that = this;

    // Not ready yet.
    if (!node.game.gamesInfo) return;
    s = node.game.gamesInfo[node.game.channelInUse].waitroom;
    t = this.table;
    t.clear();

    //LEVELS in case later use
    node.game.gamesInfo[node.game.channelInUse].levels;

    //my settings
    var mySettings =
      node.game.gamesInfo[node.game.channelInUse].settings.standard;

    //remove unnecessary settings
    delete mySettings.SESSION_ID;
    delete mySettings.TIMER;
    delete mySettings.treatmentName;
    delete mySettings.name;

    //I dont think deleting them from a copy object affects anything
    delete s.EXECUTION_MODE;
    delete s.CHOSEN_TREATMENT;
    delete s.TEXTS;
    delete s.SOUND;

    var combinedSettings = mergeObjects(s, mySettings);

    console.log("WAITROOM S: " + JSON.stringify(s));
    console.log("MY SETTINGS: " + JSON.stringify(mySettings));
    console.log("COMBINED " + JSON.stringify(combinedSettings));

    this.editSaveButton.onclick = function() {
      var listOfSettings = [
        (repeat = W.gid("REPEAT")),
        (imageDir = W.gid("IMG_DIR")),
        (nOfNeighbors = W.gid("N_OF_NEIGHBORS")),
        (userDataFolder = W.gid("USER_DATA_FOLDER")),
        (botDataFolder = W.gid("BOT_DATA_FOLDER")),
        (maleNamesPath = W.gid("MALE_NAMES_FILE")),
        (femaleNamesPath = W.gid("FEMALE_NAMES_FILE")),
        (group_size = W.gid("GROUP_SIZE")),
        (playWithBots = W.gid("ALLOW_PLAY_WITH_BOTS"))
      ];

      if (that.editSaveButton.innerHTML == "Edit") {
        that.editSaveButton.innerHTML = "Save";
        for (let x = 0; x < listOfSettings.length; x++) {
          var currentSetting = listOfSettings[x];
          var currentContent = originalTable[x + 1].content;
          var originalValue = originalTable[x + 1].value;

          if (
            currentSetting.value === "" ||
            currentSetting.placeholder == originalValue
          ) {
            //do nothing
          } else {
            currentSetting.placeholder = currentSetting.value;

            //update table structure for prev value
            originalTable[x + 1].value = currentSetting.value;
          }

          currentSetting.disabled = false;
        }
      } else if (that.editSaveButton.innerHTML == "Save") {
        that.editSaveButton.innerHTML = "Edit";

        var changes = {};
        changes["s"] = {};
        changes["mySettings"] = {};
        //disable the field
        for (let x = 0; x < listOfSettings.length; x++) {
          var currentSetting = listOfSettings[x];
          var currentContent = originalTable[x + 1].content;
          var originalValue = originalTable[x + 1].value;
          var currentValue = currentSetting.value;

          //not changed
          if (
            currentSetting.value === "" ||
            currentSetting.value == originalValue
          ) {
          } else {
            //SAVE IN A OBJECT AS STATED

            //waitroom s settings
            if (currentContent == "GROUP_SIZE") {
              changes["s"][currentContent] = parseInt(currentValue);
              changes["s"]["POOL_SIZE"] = parseInt(currentValue);
            } else if (currentContent == "ALLOW_PLAY_WITH_BOTS") {
              changes["s"][currentContent] = currentValue == "true";
            } else if (currentContent == "REPEAT") {
              changes["mySettings"][currentContent] = parseInt(currentValue);
            } else if (currentContent == "IMG_DIR") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "N_OF_NEIGHBORS") {
              changes["mySettings"][currentContent] = parseInt(currentValue);
            } else if (currentContent == "MALE_NAMES_FILE") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "FEMALE_NAMES_FILE") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "USER_DATA_FOLDER") {
              changes["mySettings"][currentContent] = currentValue;
            } else if (currentContent == "BOT_DATA_FOLDER") {
              changes["mySettings"][currentContent] = currentValue;
            }
            //mySettings

            //update original table if any of the inputs is not empty
            originalTable[x + 1].value = currentValue;
          }

          currentSetting.disabled = true;
        }

        console.log("CHANGES: " + JSON.stringify(changes));

        //send changes in waitingroom
        if (!isEmptyObject(changes.s)) {
          node.socket.send(
            node.msg.create({
              target: "SERVERCOMMAND",
              text: "UPDATE_SETTINGS",
              data: {
                type: "waitroom", // or requirements or settings, etc.
                update: changes.s,
                levels: true
              }
            })
          );
        }

        //send changes in settings
        if (!isEmptyObject(changes.mySettings)) {
          node.socket.send(
            node.msg.create({
              target: "SERVERCOMMAND",
              text: "UPDATE_SETTINGS",
              data: {
                type: "settings", // or requirements or settings, etc.
                update: changes.mySettings,
                levels: true
              }
            })
          );
        }

        //send the new data back to server
      }
    };

    for (let setting in mySettings) {
      if (mySettings.hasOwnProperty(setting)) {
        t.addRow([setting, mySettings[setting]]);
      }
    }

    //standard properties
    for (i in s) {
      if (s.hasOwnProperty(i)) {
        t.addRow([i, s[i]]);
      }
    }

    t.parse();
  };

  //check if object is empty or not (utility function)
  function isEmptyObject(obj) {
    for (var key in obj) {
      if (obj.hasOwnProperty(key)) return false;
    }
    return true;
  }

  function mergeObjects(obj1, obj2) {
    var obj3 = {};
    for (var attrname in obj1) {
      obj3[attrname] = obj1[attrname];
    }
    for (var attrname in obj2) {
      obj3[attrname] = obj2[attrname];
    }
    return obj3;
  }
})(node);
<|endoftext|>


<commit_before>(function () {
  'use strict';

  /*globals $, jsbin, CodeMirror, template, ternDefinitions, ternBasicDefs */
  if (!jsbin.settings.addons.tern || jsbin.embed) {
    return;
  }

  var ternServer;
  var ternLoaded = {};

  var initTern = function(editor, defs){
    var keyMap = {
      'Ctrl-Q': function(cm) { ternServer.selectName(cm); },
      'Ctrl-I': function(cm) { ternServer.showType(cm); },
      'Ctrl-Space': function(cm) { ternServer.complete(cm); }
    };
    if (typeof defs === 'undefined') {
      defs = [];
    }
    ternServer = new CodeMirror.TernServer({
      defs: defs,
      useWorker: false,
      cm: editor
    });
    editor.addKeyMap(keyMap);
    editor.on('cursorActivity', function(cm) { ternServer.updateArgHints(cm); });
  };

  var addTernDefinition = function(def) {
    if (typeof ternServer === 'object') {
      ternServer.options.defs.push(def);
      ternServer = new CodeMirror.TernServer({
        defs: ternServer.options.defs,
        useWorker: ternServer.options.useWorker,
        tooltipType: ternServer.options.tooltipType,
        cm: ternServer.options.cm
      });
    }
  };

  // Load the json defition of the library
  var loadTernDefinition = function(name, file) {
    if (!ternLoaded[name]) {
      $.ajax({
        url: file,
        dataType: 'json',
        success: function(data) {
          addTernDefinition(data);
          ternLoaded[name] = true;
        }
      });
    }
  };

  // Load the actual js library
  var loadTernFile = function(name, file) {
    if (!ternLoaded[name]) {
      $.ajax({
        url: file,
        dataType: 'script',
        success: function(data) {
          ternServer.server.addFile(name, data);
          ternLoaded[name] = true;
        }
      });
    }
  };

  var loadTern = function(editor) {
    initTern(editor, ternBasicDefs);
    ternLoaded.ecma5 = true;
    ternLoaded.browser = true;
  };

  var searchTernDefinition = function(htmlCode) {
    for (var i = 0; i < ternDefinitions.length; i++) {
      if (ternDefinitions[i].match.test(htmlCode)) {
        if (ternDefinitions[i].type === 'def') {
          loadTernDefinition(ternDefinitions[i].name, ternDefinitions[i].file);
        } else {
          loadTernFile(ternDefinitions[i].name, ternDefinitions[i].file);
        }
      }
    }
  };

  // Overwrite the autocomplete function to use tern
  CodeMirror.commands.autocomplete = function(cm) {
    if (CodeMirror.snippets(cm) === CodeMirror.Pass) {
      var pos = cm.getCursor();
      var tok = cm.getTokenAt(pos);
      var indent = '';
      if (cm.options.indentWithTabs) {
        indent = '\t';
      } else {
        indent = new Array(cm.options.indentUnit * 1 + 1).join(' ');
      }

      // I don't like this - feel like we shouldnt be pseudo parsing the code around the cursor. - FO
      // the && here is in the correct place, if the token type is null, but the token string is '.'
      // then we're probably at the end of an object lookup so let's use tern for autocomplete
      if (tok.string === ';' || tok.type === 'string' || tok.type === null && tok.string !== '.') {
        return cm.replaceRange(indent, pos);
      }
      if (tok.string.trim() !== '') {
        return ternServer.complete(cm);
      }
      return cm.replaceRange(indent, pos);
    }
  };

  CodeMirror.startTern = function() {
    loadTern(jsbin.panels.panels.javascript.editor);
    searchTernDefinition(template.html);

    $('#library').bind('change', function () {
      searchTernDefinition(jsbin.panels.panels.html.getCode());
    });
  };

})();<commit_msg>Remove check for addon - tern is loaded conditionally<commit_after>(function () {
  'use strict';
  /*globals $, jsbin, CodeMirror, template, ternDefinitions, ternBasicDefs */

  if (jsbin.embed) {
    return;
  }

  var ternServer;
  var ternLoaded = {};

  var initTern = function(editor, defs){
    var keyMap = {
      'Ctrl-Q': function(cm) { ternServer.selectName(cm); },
      'Ctrl-I': function(cm) { ternServer.showType(cm); },
      'Ctrl-Space': function(cm) { ternServer.complete(cm); }
    };
    if (typeof defs === 'undefined') {
      defs = [];
    }
    ternServer = new CodeMirror.TernServer({
      defs: defs,
      useWorker: false,
      cm: editor
    });
    editor.addKeyMap(keyMap);
    editor.on('cursorActivity', function(cm) { ternServer.updateArgHints(cm); });
  };

  var addTernDefinition = function(def) {
    if (typeof ternServer === 'object') {
      ternServer.options.defs.push(def);
      ternServer = new CodeMirror.TernServer({
        defs: ternServer.options.defs,
        useWorker: ternServer.options.useWorker,
        tooltipType: ternServer.options.tooltipType,
        cm: ternServer.options.cm
      });
    }
  };

  // Load the json defition of the library
  var loadTernDefinition = function(name, file) {
    if (!ternLoaded[name]) {
      $.ajax({
        url: file,
        dataType: 'json',
        success: function(data) {
          addTernDefinition(data);
          ternLoaded[name] = true;
        }
      });
    }
  };

  // Load the actual js library
  var loadTernFile = function(name, file) {
    if (!ternLoaded[name]) {
      $.ajax({
        url: file,
        dataType: 'script',
        success: function(data) {
          ternServer.server.addFile(name, data);
          ternLoaded[name] = true;
        }
      });
    }
  };

  var loadTern = function(editor) {
    initTern(editor, ternBasicDefs);
    ternLoaded.ecma5 = true;
    ternLoaded.browser = true;
  };

  var searchTernDefinition = function(htmlCode) {
    for (var i = 0; i < ternDefinitions.length; i++) {
      if (ternDefinitions[i].match.test(htmlCode)) {
        if (ternDefinitions[i].type === 'def') {
          loadTernDefinition(ternDefinitions[i].name, ternDefinitions[i].file);
        } else {
          loadTernFile(ternDefinitions[i].name, ternDefinitions[i].file);
        }
      }
    }
  };

  // Overwrite the autocomplete function to use tern
  CodeMirror.commands.autocomplete = function(cm) {
    if (CodeMirror.snippets(cm) === CodeMirror.Pass) {
      var pos = cm.getCursor();
      var tok = cm.getTokenAt(pos);
      var indent = '';
      if (cm.options.indentWithTabs) {
        indent = '\t';
      } else {
        indent = new Array(cm.options.indentUnit * 1 + 1).join(' ');
      }

      // I don't like this - feel like we shouldnt be pseudo parsing the code around the cursor. - FO
      // the && here is in the correct place, if the token type is null, but the token string is '.'
      // then we're probably at the end of an object lookup so let's use tern for autocomplete
      if (tok.string === ';' || tok.type === 'string' || tok.type === null && tok.string !== '.') {
        return cm.replaceRange(indent, pos);
      }
      if (tok.string.trim() !== '') {
        return ternServer.complete(cm);
      }
      return cm.replaceRange(indent, pos);
    }
  };

  CodeMirror.startTern = function() {
    loadTern(jsbin.panels.panels.javascript.editor);
    searchTernDefinition(template.html);

    $('#library').bind('change', function () {
      searchTernDefinition(jsbin.panels.panels.html.getCode());
    });
  };

})();<|endoftext|>


<commit_before>"use strict";
module.exports = function jekyll(renderDocsProcessor) {
  return {
    name: 'jekyll',
    description: 'Create jekyll includes',
    $runAfter: ['paths-computed'],
    $runBefore: ['rendering-docs'],
    $process: docs => {

      // pretty up and sort the docs object for menu generation
      docs = docs.filter(doc => (!!doc.name && !!doc.outputPath) || doc.docType === 'index-page');

      docs.sort((a, b) => {
        const textA = a.name ? a.name.toUpperCase() : '',
          textB = b.name ? b.name.toUpperCase() : '';

        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
      });

      docs.forEach(doc => {
        doc.outputPath = doc.outputPath.toLowerCase().replace(/\s/g, '-');
        doc.URL = doc.outputPath.replace('docs//', 'docs/')
          .replace('/index.md', '')
          .replace('content/', '');
        doc.URL = doc.URL+'/'; // add trailing slash
      });

      const betaDocs = [];

      docs = docs.filter(doc => {
        if (doc.beta === true) {
          betaDocs.push(doc);
          return false;
        }
        return true;
      });

      docs = docs.concat(betaDocs);

      // add side menu
      docs.push({
        docType: 'nativeMenu',
        id: 'native_menu',
        template: 'native_menu.template.html',
        outputPath: 'content/_includes/fluid/native_menu.html'
      });

      return docs;
    }
  };
};
<commit_msg>only add trailing slash on plugin pages<commit_after>"use strict";
module.exports = function jekyll(renderDocsProcessor) {
  return {
    name: 'jekyll',
    description: 'Create jekyll includes',
    $runAfter: ['paths-computed'],
    $runBefore: ['rendering-docs'],
    $process: docs => {

      // pretty up and sort the docs object for menu generation
      docs = docs.filter(doc => (!!doc.name && !!doc.outputPath) || doc.docType === 'index-page');

      docs.sort((a, b) => {
        const textA = a.name ? a.name.toUpperCase() : '',
          textB = b.name ? b.name.toUpperCase() : '';

        return (textA < textB) ? -1 : (textA > textB) ? 1 : 0;
      });

      docs.forEach(doc => {
        doc.outputPath = doc.outputPath.toLowerCase().replace(/\s/g, '-');
        doc.URL = doc.outputPath.replace('docs//', 'docs/')
          .replace('/index.md', '')
          .replace('content/', '');
        // add trailing slash to plugin pages
        if(!doc.URL.endsWith("/") && !doc.URL.endsWith(".html")) {
          doc.URL = doc.URL+'/';
        }
      });

      const betaDocs = [];

      docs = docs.filter(doc => {
        if (doc.beta === true) {
          betaDocs.push(doc);
          return false;
        }
        return true;
      });

      docs = docs.concat(betaDocs);

      // add side menu
      docs.push({
        docType: 'nativeMenu',
        id: 'native_menu',
        template: 'native_menu.template.html',
        outputPath: 'content/_includes/fluid/native_menu.html'
      });

      return docs;
    }
  };
};
<|endoftext|>