PageRenderTime 102ms CodeModel.GetById 15ms app.highlight 72ms RepoModel.GetById 1ms app.codeStats 0ms

/Game/Socket.IO/socket.io.js

https://bitbucket.org/larchange/game
JavaScript | 3787 lines | 2850 code | 327 blank | 610 comment | 225 complexity | d097f31a9a340c75ea9ccd782187ca2c MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1/*! Socket.IO.js build:0.9.5, development. Copyright(c) 2011 LearnBoost <dev@learnboost.com> MIT Licensed */
   2
   3/**
   4 * socket.io
   5 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
   6 * MIT Licensed
   7 */
   8
   9(function (exports, global) {
  10
  11  /**
  12   * IO namespace.
  13   *
  14   * @namespace
  15   */
  16
  17  var io = exports;
  18
  19  /**
  20   * Socket.IO version
  21   *
  22   * @api public
  23   */
  24
  25  io.version = '0.9.5';
  26
  27  /**
  28   * Protocol implemented.
  29   *
  30   * @api public
  31   */
  32
  33  io.protocol = 1;
  34
  35  /**
  36   * Available transports, these will be populated with the available transports
  37   *
  38   * @api public
  39   */
  40
  41  io.transports = [];
  42
  43  /**
  44   * Keep track of jsonp callbacks.
  45   *
  46   * @api private
  47   */
  48
  49  io.j = [];
  50
  51  /**
  52   * Keep track of our io.Sockets
  53   *
  54   * @api private
  55   */
  56  io.sockets = {};
  57
  58
  59  /**
  60   * Manages connections to hosts.
  61   *
  62   * @param {String} uri
  63   * @Param {Boolean} force creation of new socket (defaults to false)
  64   * @api public
  65   */
  66
  67  io.connect = function (host, details) {
  68    var uri = io.util.parseUri(host)
  69      , uuri
  70      , socket;
  71
  72    if (global && global.location) {
  73      uri.protocol = uri.protocol || global.location.protocol.slice(0, -1);
  74      uri.host = uri.host || (global.document
  75        ? global.document.domain : global.location.hostname);
  76      uri.port = uri.port || global.location.port;
  77    }
  78
  79    uuri = io.util.uniqueUri(uri);
  80
  81    var options = {
  82        host: uri.host
  83      , secure: 'https' == uri.protocol
  84      , port: uri.port || ('https' == uri.protocol ? 443 : 80)
  85      , query: uri.query || ''
  86    };
  87
  88    io.util.merge(options, details);
  89
  90    if (options['force new connection'] || !io.sockets[uuri]) {
  91      socket = new io.Socket(options);
  92    }
  93
  94    if (!options['force new connection'] && socket) {
  95      io.sockets[uuri] = socket;
  96    }
  97
  98    socket = socket || io.sockets[uuri];
  99
 100    // if path is different from '' or /
 101    return socket.of(uri.path.length > 1 ? uri.path : '');
 102  };
 103
 104})('object' === typeof module ? module.exports : (this.io = {}), this);
 105/**
 106 * socket.io
 107 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 108 * MIT Licensed
 109 */
 110
 111(function (exports, global) {
 112
 113  /**
 114   * Utilities namespace.
 115   *
 116   * @namespace
 117   */
 118
 119  var util = exports.util = {};
 120
 121  /**
 122   * Parses an URI
 123   *
 124   * @author Steven Levithan <stevenlevithan.com> (MIT license)
 125   * @api public
 126   */
 127
 128  var re = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
 129
 130  var parts = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password',
 131               'host', 'port', 'relative', 'path', 'directory', 'file', 'query',
 132               'anchor'];
 133
 134  util.parseUri = function (str) {
 135    var m = re.exec(str || '')
 136      , uri = {}
 137      , i = 14;
 138
 139    while (i--) {
 140      uri[parts[i]] = m[i] || '';
 141    }
 142
 143    return uri;
 144  };
 145
 146  /**
 147   * Produces a unique url that identifies a Socket.IO connection.
 148   *
 149   * @param {Object} uri
 150   * @api public
 151   */
 152
 153  util.uniqueUri = function (uri) {
 154    var protocol = uri.protocol
 155      , host = uri.host
 156      , port = uri.port;
 157
 158    if ('document' in global) {
 159      host = host || document.domain;
 160      port = port || (protocol == 'https'
 161        && document.location.protocol !== 'https:' ? 443 : document.location.port);
 162    } else {
 163      host = host || 'localhost';
 164
 165      if (!port && protocol == 'https') {
 166        port = 443;
 167      }
 168    }
 169
 170    return (protocol || 'http') + '://' + host + ':' + (port || 80);
 171  };
 172
 173  /**
 174   * Mergest 2 query strings in to once unique query string
 175   *
 176   * @param {String} base
 177   * @param {String} addition
 178   * @api public
 179   */
 180
 181  util.query = function (base, addition) {
 182    var query = util.chunkQuery(base || '')
 183      , components = [];
 184
 185    util.merge(query, util.chunkQuery(addition || ''));
 186    for (var part in query) {
 187      if (query.hasOwnProperty(part)) {
 188        components.push(part + '=' + query[part]);
 189      }
 190    }
 191
 192    return components.length ? '?' + components.join('&') : '';
 193  };
 194
 195  /**
 196   * Transforms a querystring in to an object
 197   *
 198   * @param {String} qs
 199   * @api public
 200   */
 201
 202  util.chunkQuery = function (qs) {
 203    var query = {}
 204      , params = qs.split('&')
 205      , i = 0
 206      , l = params.length
 207      , kv;
 208
 209    for (; i < l; ++i) {
 210      kv = params[i].split('=');
 211      if (kv[0]) {
 212        query[kv[0]] = kv[1];
 213      }
 214    }
 215
 216    return query;
 217  };
 218
 219  /**
 220   * Executes the given function when the page is loaded.
 221   *
 222   *     io.util.load(function () { console.log('page loaded'); });
 223   *
 224   * @param {Function} fn
 225   * @api public
 226   */
 227
 228  var pageLoaded = false;
 229
 230  util.load = function (fn) {
 231    if ('document' in global && document.readyState === 'complete' || pageLoaded) {
 232      return fn();
 233    }
 234
 235    util.on(global, 'load', fn, false);
 236  };
 237
 238  /**
 239   * Adds an event.
 240   *
 241   * @api private
 242   */
 243
 244  util.on = function (element, event, fn, capture) {
 245    if (element.attachEvent) {
 246      element.attachEvent('on' + event, fn);
 247    } else if (element.addEventListener) {
 248      element.addEventListener(event, fn, capture);
 249    }
 250  };
 251
 252  /**
 253   * Generates the correct `XMLHttpRequest` for regular and cross domain requests.
 254   *
 255   * @param {Boolean} [xdomain] Create a request that can be used cross domain.
 256   * @returns {XMLHttpRequest|false} If we can create a XMLHttpRequest.
 257   * @api private
 258   */
 259
 260  util.request = function (xdomain) {
 261
 262    if (xdomain && 'undefined' != typeof XDomainRequest) {
 263      return new XDomainRequest();
 264    }
 265
 266    if ('undefined' != typeof XMLHttpRequest && (!xdomain || util.ua.hasCORS)) {
 267      return new XMLHttpRequest();
 268    }
 269
 270    if (!xdomain) {
 271      try {
 272        return new window[(['Active'].concat('Object').join('X'))]('Microsoft.XMLHTTP');
 273      } catch(e) { }
 274    }
 275
 276    return null;
 277  };
 278
 279  /**
 280   * XHR based transport constructor.
 281   *
 282   * @constructor
 283   * @api public
 284   */
 285
 286  /**
 287   * Change the internal pageLoaded value.
 288   */
 289
 290  if ('undefined' != typeof window) {
 291    util.load(function () {
 292      pageLoaded = true;
 293    });
 294  }
 295
 296  /**
 297   * Defers a function to ensure a spinner is not displayed by the browser
 298   *
 299   * @param {Function} fn
 300   * @api public
 301   */
 302
 303  util.defer = function (fn) {
 304    if (!util.ua.webkit || 'undefined' != typeof importScripts) {
 305      return fn();
 306    }
 307
 308    util.load(function () {
 309      setTimeout(fn, 100);
 310    });
 311  };
 312
 313  /**
 314   * Merges two objects.
 315   *
 316   * @api public
 317   */
 318  
 319  util.merge = function merge (target, additional, deep, lastseen) {
 320    var seen = lastseen || []
 321      , depth = typeof deep == 'undefined' ? 2 : deep
 322      , prop;
 323
 324    for (prop in additional) {
 325      if (additional.hasOwnProperty(prop) && util.indexOf(seen, prop) < 0) {
 326        if (typeof target[prop] !== 'object' || !depth) {
 327          target[prop] = additional[prop];
 328          seen.push(additional[prop]);
 329        } else {
 330          util.merge(target[prop], additional[prop], depth - 1, seen);
 331        }
 332      }
 333    }
 334
 335    return target;
 336  };
 337
 338  /**
 339   * Merges prototypes from objects
 340   *
 341   * @api public
 342   */
 343  
 344  util.mixin = function (ctor, ctor2) {
 345    util.merge(ctor.prototype, ctor2.prototype);
 346  };
 347
 348  /**
 349   * Shortcut for prototypical and static inheritance.
 350   *
 351   * @api private
 352   */
 353
 354  util.inherit = function (ctor, ctor2) {
 355    function f() {};
 356    f.prototype = ctor2.prototype;
 357    ctor.prototype = new f;
 358  };
 359
 360  /**
 361   * Checks if the given object is an Array.
 362   *
 363   *     io.util.isArray([]); // true
 364   *     io.util.isArray({}); // false
 365   *
 366   * @param Object obj
 367   * @api public
 368   */
 369
 370  util.isArray = Array.isArray || function (obj) {
 371    return Object.prototype.toString.call(obj) === '[object Array]';
 372  };
 373
 374  /**
 375   * Intersects values of two arrays into a third
 376   *
 377   * @api public
 378   */
 379
 380  util.intersect = function (arr, arr2) {
 381    var ret = []
 382      , longest = arr.length > arr2.length ? arr : arr2
 383      , shortest = arr.length > arr2.length ? arr2 : arr;
 384
 385    for (var i = 0, l = shortest.length; i < l; i++) {
 386      if (~util.indexOf(longest, shortest[i]))
 387        ret.push(shortest[i]);
 388    }
 389
 390    return ret;
 391  }
 392
 393  /**
 394   * Array indexOf compatibility.
 395   *
 396   * @see bit.ly/a5Dxa2
 397   * @api public
 398   */
 399
 400  util.indexOf = function (arr, o, i) {
 401    
 402    for (var j = arr.length, i = i < 0 ? i + j < 0 ? 0 : i + j : i || 0; 
 403         i < j && arr[i] !== o; i++) {}
 404
 405    return j <= i ? -1 : i;
 406  };
 407
 408  /**
 409   * Converts enumerables to array.
 410   *
 411   * @api public
 412   */
 413
 414  util.toArray = function (enu) {
 415    var arr = [];
 416
 417    for (var i = 0, l = enu.length; i < l; i++)
 418      arr.push(enu[i]);
 419
 420    return arr;
 421  };
 422
 423  /**
 424   * UA / engines detection namespace.
 425   *
 426   * @namespace
 427   */
 428
 429  util.ua = {};
 430
 431  /**
 432   * Whether the UA supports CORS for XHR.
 433   *
 434   * @api public
 435   */
 436
 437  util.ua.hasCORS = 'undefined' != typeof XMLHttpRequest && (function () {
 438    try {
 439      var a = new XMLHttpRequest();
 440    } catch (e) {
 441      return false;
 442    }
 443
 444    return a.withCredentials != undefined;
 445  })();
 446
 447  /**
 448   * Detect webkit.
 449   *
 450   * @api public
 451   */
 452
 453  util.ua.webkit = 'undefined' != typeof navigator
 454    && /webkit/i.test(navigator.userAgent);
 455
 456})('undefined' != typeof io ? io : module.exports, this);
 457
 458/**
 459 * socket.io
 460 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 461 * MIT Licensed
 462 */
 463
 464(function (exports, io) {
 465
 466  /**
 467   * Expose constructor.
 468   */
 469
 470  exports.EventEmitter = EventEmitter;
 471
 472  /**
 473   * Event emitter constructor.
 474   *
 475   * @api public.
 476   */
 477
 478  function EventEmitter () {};
 479
 480  /**
 481   * Adds a listener
 482   *
 483   * @api public
 484   */
 485
 486  EventEmitter.prototype.on = function (name, fn) {
 487    if (!this.$events) {
 488      this.$events = {};
 489    }
 490
 491    if (!this.$events[name]) {
 492      this.$events[name] = fn;
 493    } else if (io.util.isArray(this.$events[name])) {
 494      this.$events[name].push(fn);
 495    } else {
 496      this.$events[name] = [this.$events[name], fn];
 497    }
 498
 499    return this;
 500  };
 501
 502  EventEmitter.prototype.addListener = EventEmitter.prototype.on;
 503
 504  /**
 505   * Adds a volatile listener.
 506   *
 507   * @api public
 508   */
 509
 510  EventEmitter.prototype.once = function (name, fn) {
 511    var self = this;
 512
 513    function on () {
 514      self.removeListener(name, on);
 515      fn.apply(this, arguments);
 516    };
 517
 518    on.listener = fn;
 519    this.on(name, on);
 520
 521    return this;
 522  };
 523
 524  /**
 525   * Removes a listener.
 526   *
 527   * @api public
 528   */
 529
 530  EventEmitter.prototype.removeListener = function (name, fn) {
 531    if (this.$events && this.$events[name]) {
 532      var list = this.$events[name];
 533
 534      if (io.util.isArray(list)) {
 535        var pos = -1;
 536
 537        for (var i = 0, l = list.length; i < l; i++) {
 538          if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
 539            pos = i;
 540            break;
 541          }
 542        }
 543
 544        if (pos < 0) {
 545          return this;
 546        }
 547
 548        list.splice(pos, 1);
 549
 550        if (!list.length) {
 551          delete this.$events[name];
 552        }
 553      } else if (list === fn || (list.listener && list.listener === fn)) {
 554        delete this.$events[name];
 555      }
 556    }
 557
 558    return this;
 559  };
 560
 561  /**
 562   * Removes all listeners for an event.
 563   *
 564   * @api public
 565   */
 566
 567  EventEmitter.prototype.removeAllListeners = function (name) {
 568    // TODO: enable this when node 0.5 is stable
 569    //if (name === undefined) {
 570      //this.$events = {};
 571      //return this;
 572    //}
 573
 574    if (this.$events && this.$events[name]) {
 575      this.$events[name] = null;
 576    }
 577
 578    return this;
 579  };
 580
 581  /**
 582   * Gets all listeners for a certain event.
 583   *
 584   * @api publci
 585   */
 586
 587  EventEmitter.prototype.listeners = function (name) {
 588    if (!this.$events) {
 589      this.$events = {};
 590    }
 591
 592    if (!this.$events[name]) {
 593      this.$events[name] = [];
 594    }
 595
 596    if (!io.util.isArray(this.$events[name])) {
 597      this.$events[name] = [this.$events[name]];
 598    }
 599
 600    return this.$events[name];
 601  };
 602
 603  /**
 604   * Emits an event.
 605   *
 606   * @api public
 607   */
 608
 609  EventEmitter.prototype.emit = function (name) {
 610    if (!this.$events) {
 611      return false;
 612    }
 613
 614    var handler = this.$events[name];
 615
 616    if (!handler) {
 617      return false;
 618    }
 619
 620    var args = Array.prototype.slice.call(arguments, 1);
 621
 622    if ('function' == typeof handler) {
 623      handler.apply(this, args);
 624    } else if (io.util.isArray(handler)) {
 625      var listeners = handler.slice();
 626
 627      for (var i = 0, l = listeners.length; i < l; i++) {
 628        listeners[i].apply(this, args);
 629      }
 630    } else {
 631      return false;
 632    }
 633
 634    return true;
 635  };
 636
 637})(
 638    'undefined' != typeof io ? io : module.exports
 639  , 'undefined' != typeof io ? io : module.parent.exports
 640);
 641
 642/**
 643 * socket.io
 644 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 645 * MIT Licensed
 646 */
 647
 648/**
 649 * Based on JSON2 (http://www.JSON.org/js.html).
 650 */
 651
 652(function (exports, nativeJSON) {
 653  "use strict";
 654
 655  // use native JSON if it's available
 656  if (nativeJSON && nativeJSON.parse){
 657    return exports.JSON = {
 658      parse: nativeJSON.parse
 659    , stringify: nativeJSON.stringify
 660    }
 661  }
 662
 663  var JSON = exports.JSON = {};
 664
 665  function f(n) {
 666      // Format integers to have at least two digits.
 667      return n < 10 ? '0' + n : n;
 668  }
 669
 670  function date(d, key) {
 671    return isFinite(d.valueOf()) ?
 672        d.getUTCFullYear()     + '-' +
 673        f(d.getUTCMonth() + 1) + '-' +
 674        f(d.getUTCDate())      + 'T' +
 675        f(d.getUTCHours())     + ':' +
 676        f(d.getUTCMinutes())   + ':' +
 677        f(d.getUTCSeconds())   + 'Z' : null;
 678  };
 679
 680  var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
 681      escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
 682      gap,
 683      indent,
 684      meta = {    // table of character substitutions
 685          '\b': '\\b',
 686          '\t': '\\t',
 687          '\n': '\\n',
 688          '\f': '\\f',
 689          '\r': '\\r',
 690          '"' : '\\"',
 691          '\\': '\\\\'
 692      },
 693      rep;
 694
 695
 696  function quote(string) {
 697
 698// If the string contains no control characters, no quote characters, and no
 699// backslash characters, then we can safely slap some quotes around it.
 700// Otherwise we must also replace the offending characters with safe escape
 701// sequences.
 702
 703      escapable.lastIndex = 0;
 704      return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
 705          var c = meta[a];
 706          return typeof c === 'string' ? c :
 707              '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
 708      }) + '"' : '"' + string + '"';
 709  }
 710
 711
 712  function str(key, holder) {
 713
 714// Produce a string from holder[key].
 715
 716      var i,          // The loop counter.
 717          k,          // The member key.
 718          v,          // The member value.
 719          length,
 720          mind = gap,
 721          partial,
 722          value = holder[key];
 723
 724// If the value has a toJSON method, call it to obtain a replacement value.
 725
 726      if (value instanceof Date) {
 727          value = date(key);
 728      }
 729
 730// If we were called with a replacer function, then call the replacer to
 731// obtain a replacement value.
 732
 733      if (typeof rep === 'function') {
 734          value = rep.call(holder, key, value);
 735      }
 736
 737// What happens next depends on the value's type.
 738
 739      switch (typeof value) {
 740      case 'string':
 741          return quote(value);
 742
 743      case 'number':
 744
 745// JSON numbers must be finite. Encode non-finite numbers as null.
 746
 747          return isFinite(value) ? String(value) : 'null';
 748
 749      case 'boolean':
 750      case 'null':
 751
 752// If the value is a boolean or null, convert it to a string. Note:
 753// typeof null does not produce 'null'. The case is included here in
 754// the remote chance that this gets fixed someday.
 755
 756          return String(value);
 757
 758// If the type is 'object', we might be dealing with an object or an array or
 759// null.
 760
 761      case 'object':
 762
 763// Due to a specification blunder in ECMAScript, typeof null is 'object',
 764// so watch out for that case.
 765
 766          if (!value) {
 767              return 'null';
 768          }
 769
 770// Make an array to hold the partial results of stringifying this object value.
 771
 772          gap += indent;
 773          partial = [];
 774
 775// Is the value an array?
 776
 777          if (Object.prototype.toString.apply(value) === '[object Array]') {
 778
 779// The value is an array. Stringify every element. Use null as a placeholder
 780// for non-JSON values.
 781
 782              length = value.length;
 783              for (i = 0; i < length; i += 1) {
 784                  partial[i] = str(i, value) || 'null';
 785              }
 786
 787// Join all of the elements together, separated with commas, and wrap them in
 788// brackets.
 789
 790              v = partial.length === 0 ? '[]' : gap ?
 791                  '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
 792                  '[' + partial.join(',') + ']';
 793              gap = mind;
 794              return v;
 795          }
 796
 797// If the replacer is an array, use it to select the members to be stringified.
 798
 799          if (rep && typeof rep === 'object') {
 800              length = rep.length;
 801              for (i = 0; i < length; i += 1) {
 802                  if (typeof rep[i] === 'string') {
 803                      k = rep[i];
 804                      v = str(k, value);
 805                      if (v) {
 806                          partial.push(quote(k) + (gap ? ': ' : ':') + v);
 807                      }
 808                  }
 809              }
 810          } else {
 811
 812// Otherwise, iterate through all of the keys in the object.
 813
 814              for (k in value) {
 815                  if (Object.prototype.hasOwnProperty.call(value, k)) {
 816                      v = str(k, value);
 817                      if (v) {
 818                          partial.push(quote(k) + (gap ? ': ' : ':') + v);
 819                      }
 820                  }
 821              }
 822          }
 823
 824// Join all of the member texts together, separated with commas,
 825// and wrap them in braces.
 826
 827          v = partial.length === 0 ? '{}' : gap ?
 828              '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
 829              '{' + partial.join(',') + '}';
 830          gap = mind;
 831          return v;
 832      }
 833  }
 834
 835// If the JSON object does not yet have a stringify method, give it one.
 836
 837  JSON.stringify = function (value, replacer, space) {
 838
 839// The stringify method takes a value and an optional replacer, and an optional
 840// space parameter, and returns a JSON text. The replacer can be a function
 841// that can replace values, or an array of strings that will select the keys.
 842// A default replacer method can be provided. Use of the space parameter can
 843// produce text that is more easily readable.
 844
 845      var i;
 846      gap = '';
 847      indent = '';
 848
 849// If the space parameter is a number, make an indent string containing that
 850// many spaces.
 851
 852      if (typeof space === 'number') {
 853          for (i = 0; i < space; i += 1) {
 854              indent += ' ';
 855          }
 856
 857// If the space parameter is a string, it will be used as the indent string.
 858
 859      } else if (typeof space === 'string') {
 860          indent = space;
 861      }
 862
 863// If there is a replacer, it must be a function or an array.
 864// Otherwise, throw an error.
 865
 866      rep = replacer;
 867      if (replacer && typeof replacer !== 'function' &&
 868              (typeof replacer !== 'object' ||
 869              typeof replacer.length !== 'number')) {
 870          throw new Error('JSON.stringify');
 871      }
 872
 873// Make a fake root object containing our value under the key of ''.
 874// Return the result of stringifying the value.
 875
 876      return str('', {'': value});
 877  };
 878
 879// If the JSON object does not yet have a parse method, give it one.
 880
 881  JSON.parse = function (text, reviver) {
 882  // The parse method takes a text and an optional reviver function, and returns
 883  // a JavaScript value if the text is a valid JSON text.
 884
 885      var j;
 886
 887      function walk(holder, key) {
 888
 889  // The walk method is used to recursively walk the resulting structure so
 890  // that modifications can be made.
 891
 892          var k, v, value = holder[key];
 893          if (value && typeof value === 'object') {
 894              for (k in value) {
 895                  if (Object.prototype.hasOwnProperty.call(value, k)) {
 896                      v = walk(value, k);
 897                      if (v !== undefined) {
 898                          value[k] = v;
 899                      } else {
 900                          delete value[k];
 901                      }
 902                  }
 903              }
 904          }
 905          return reviver.call(holder, key, value);
 906      }
 907
 908
 909  // Parsing happens in four stages. In the first stage, we replace certain
 910  // Unicode characters with escape sequences. JavaScript handles many characters
 911  // incorrectly, either silently deleting them, or treating them as line endings.
 912
 913      text = String(text);
 914      cx.lastIndex = 0;
 915      if (cx.test(text)) {
 916          text = text.replace(cx, function (a) {
 917              return '\\u' +
 918                  ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
 919          });
 920      }
 921
 922  // In the second stage, we run the text against regular expressions that look
 923  // for non-JSON patterns. We are especially concerned with '()' and 'new'
 924  // because they can cause invocation, and '=' because it can cause mutation.
 925  // But just to be safe, we want to reject all unexpected forms.
 926
 927  // We split the second stage into 4 regexp operations in order to work around
 928  // crippling inefficiencies in IE's and Safari's regexp engines. First we
 929  // replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
 930  // replace all simple value tokens with ']' characters. Third, we delete all
 931  // open brackets that follow a colon or comma or that begin the text. Finally,
 932  // we look to see that the remaining characters are only whitespace or ']' or
 933  // ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.
 934
 935      if (/^[\],:{}\s]*$/
 936              .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
 937                  .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
 938                  .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
 939
 940  // In the third stage we use the eval function to compile the text into a
 941  // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
 942  // in JavaScript: it can begin a block or an object literal. We wrap the text
 943  // in parens to eliminate the ambiguity.
 944
 945          j = eval('(' + text + ')');
 946
 947  // In the optional fourth stage, we recursively walk the new structure, passing
 948  // each name/value pair to a reviver function for possible transformation.
 949
 950          return typeof reviver === 'function' ?
 951              walk({'': j}, '') : j;
 952      }
 953
 954  // If the text is not JSON parseable, then a SyntaxError is thrown.
 955
 956      throw new SyntaxError('JSON.parse');
 957  };
 958
 959})(
 960    'undefined' != typeof io ? io : module.exports
 961  , typeof JSON !== 'undefined' ? JSON : undefined
 962);
 963
 964/**
 965 * socket.io
 966 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 967 * MIT Licensed
 968 */
 969
 970(function (exports, io) {
 971
 972  /**
 973   * Parser namespace.
 974   *
 975   * @namespace
 976   */
 977
 978  var parser = exports.parser = {};
 979
 980  /**
 981   * Packet types.
 982   */
 983
 984  var packets = parser.packets = [
 985      'disconnect'
 986    , 'connect'
 987    , 'heartbeat'
 988    , 'message'
 989    , 'json'
 990    , 'event'
 991    , 'ack'
 992    , 'error'
 993    , 'noop'
 994  ];
 995
 996  /**
 997   * Errors reasons.
 998   */
 999
1000  var reasons = parser.reasons = [
1001      'transport not supported'
1002    , 'client not handshaken'
1003    , 'unauthorized'
1004  ];
1005
1006  /**
1007   * Errors advice.
1008   */
1009
1010  var advice = parser.advice = [
1011      'reconnect'
1012  ];
1013
1014  /**
1015   * Shortcuts.
1016   */
1017
1018  var JSON = io.JSON
1019    , indexOf = io.util.indexOf;
1020
1021  /**
1022   * Encodes a packet.
1023   *
1024   * @api private
1025   */
1026
1027  parser.encodePacket = function (packet) {
1028    var type = indexOf(packets, packet.type)
1029      , id = packet.id || ''
1030      , endpoint = packet.endpoint || ''
1031      , ack = packet.ack
1032      , data = null;
1033
1034    switch (packet.type) {
1035      case 'error':
1036        var reason = packet.reason ? indexOf(reasons, packet.reason) : ''
1037          , adv = packet.advice ? indexOf(advice, packet.advice) : '';
1038
1039        if (reason !== '' || adv !== '')
1040          data = reason + (adv !== '' ? ('+' + adv) : '');
1041
1042        break;
1043
1044      case 'message':
1045        if (packet.data !== '')
1046          data = packet.data;
1047        break;
1048
1049      case 'event':
1050        var ev = { name: packet.name };
1051
1052        if (packet.args && packet.args.length) {
1053          ev.args = packet.args;
1054        }
1055
1056        data = JSON.stringify(ev);
1057        break;
1058
1059      case 'json':
1060        data = JSON.stringify(packet.data);
1061        break;
1062
1063      case 'connect':
1064        if (packet.qs)
1065          data = packet.qs;
1066        break;
1067
1068      case 'ack':
1069        data = packet.ackId
1070          + (packet.args && packet.args.length
1071              ? '+' + JSON.stringify(packet.args) : '');
1072        break;
1073    }
1074
1075    // construct packet with required fragments
1076    var encoded = [
1077        type
1078      , id + (ack == 'data' ? '+' : '')
1079      , endpoint
1080    ];
1081
1082    // data fragment is optional
1083    if (data !== null && data !== undefined)
1084      encoded.push(data);
1085
1086    return encoded.join(':');
1087  };
1088
1089  /**
1090   * Encodes multiple messages (payload).
1091   *
1092   * @param {Array} messages
1093   * @api private
1094   */
1095
1096  parser.encodePayload = function (packets) {
1097    var decoded = '';
1098
1099    if (packets.length == 1)
1100      return packets[0];
1101
1102    for (var i = 0, l = packets.length; i < l; i++) {
1103      var packet = packets[i];
1104      decoded += '\ufffd' + packet.length + '\ufffd' + packets[i];
1105    }
1106
1107    return decoded;
1108  };
1109
1110  /**
1111   * Decodes a packet
1112   *
1113   * @api private
1114   */
1115
1116  var regexp = /([^:]+):([0-9]+)?(\+)?:([^:]+)?:?([\s\S]*)?/;
1117
1118  parser.decodePacket = function (data) {
1119    var pieces = data.match(regexp);
1120
1121    if (!pieces) return {};
1122
1123    var id = pieces[2] || ''
1124      , data = pieces[5] || ''
1125      , packet = {
1126            type: packets[pieces[1]]
1127          , endpoint: pieces[4] || ''
1128        };
1129
1130    // whether we need to acknowledge the packet
1131    if (id) {
1132      packet.id = id;
1133      if (pieces[3])
1134        packet.ack = 'data';
1135      else
1136        packet.ack = true;
1137    }
1138
1139    // handle different packet types
1140    switch (packet.type) {
1141      case 'error':
1142        var pieces = data.split('+');
1143        packet.reason = reasons[pieces[0]] || '';
1144        packet.advice = advice[pieces[1]] || '';
1145        break;
1146
1147      case 'message':
1148        packet.data = data || '';
1149        break;
1150
1151      case 'event':
1152        try {
1153          var opts = JSON.parse(data);
1154          packet.name = opts.name;
1155          packet.args = opts.args;
1156        } catch (e) { }
1157
1158        packet.args = packet.args || [];
1159        break;
1160
1161      case 'json':
1162        try {
1163          packet.data = JSON.parse(data);
1164        } catch (e) { }
1165        break;
1166
1167      case 'connect':
1168        packet.qs = data || '';
1169        break;
1170
1171      case 'ack':
1172        var pieces = data.match(/^([0-9]+)(\+)?(.*)/);
1173        if (pieces) {
1174          packet.ackId = pieces[1];
1175          packet.args = [];
1176
1177          if (pieces[3]) {
1178            try {
1179              packet.args = pieces[3] ? JSON.parse(pieces[3]) : [];
1180            } catch (e) { }
1181          }
1182        }
1183        break;
1184
1185      case 'disconnect':
1186      case 'heartbeat':
1187        break;
1188    };
1189
1190    return packet;
1191  };
1192
1193  /**
1194   * Decodes data payload. Detects multiple messages
1195   *
1196   * @return {Array} messages
1197   * @api public
1198   */
1199
1200  parser.decodePayload = function (data) {
1201    // IE doesn't like data[i] for unicode chars, charAt works fine
1202    if (data.charAt(0) == '\ufffd') {
1203      var ret = [];
1204
1205      for (var i = 1, length = ''; i < data.length; i++) {
1206        if (data.charAt(i) == '\ufffd') {
1207          ret.push(parser.decodePacket(data.substr(i + 1).substr(0, length)));
1208          i += Number(length) + 1;
1209          length = '';
1210        } else {
1211          length += data.charAt(i);
1212        }
1213      }
1214
1215      return ret;
1216    } else {
1217      return [parser.decodePacket(data)];
1218    }
1219  };
1220
1221})(
1222    'undefined' != typeof io ? io : module.exports
1223  , 'undefined' != typeof io ? io : module.parent.exports
1224);
1225/**
1226 * socket.io
1227 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
1228 * MIT Licensed
1229 */
1230
1231(function (exports, io) {
1232
1233  /**
1234   * Expose constructor.
1235   */
1236
1237  exports.Transport = Transport;
1238
1239  /**
1240   * This is the transport template for all supported transport methods.
1241   *
1242   * @constructor
1243   * @api public
1244   */
1245
1246  function Transport (socket, sessid) {
1247    this.socket = socket;
1248    this.sessid = sessid;
1249  };
1250
1251  /**
1252   * Apply EventEmitter mixin.
1253   */
1254
1255  io.util.mixin(Transport, io.EventEmitter);
1256
1257  /**
1258   * Handles the response from the server. When a new response is received
1259   * it will automatically update the timeout, decode the message and
1260   * forwards the response to the onMessage function for further processing.
1261   *
1262   * @param {String} data Response from the server.
1263   * @api private
1264   */
1265
1266  Transport.prototype.onData = function (data) {
1267    this.clearCloseTimeout();
1268    
1269    // If the connection in currently open (or in a reopening state) reset the close 
1270    // timeout since we have just received data. This check is necessary so
1271    // that we don't reset the timeout on an explicitly disconnected connection.
1272    if (this.socket.connected || this.socket.connecting || this.socket.reconnecting) {
1273      this.setCloseTimeout();
1274    }
1275
1276    if (data !== '') {
1277      // todo: we should only do decodePayload for xhr transports
1278      var msgs = io.parser.decodePayload(data);
1279
1280      if (msgs && msgs.length) {
1281        for (var i = 0, l = msgs.length; i < l; i++) {
1282          this.onPacket(msgs[i]);
1283        }
1284      }
1285    }
1286
1287    return this;
1288  };
1289
1290  /**
1291   * Handles packets.
1292   *
1293   * @api private
1294   */
1295
1296  Transport.prototype.onPacket = function (packet) {
1297    this.socket.setHeartbeatTimeout();
1298
1299    if (packet.type == 'heartbeat') {
1300      return this.onHeartbeat();
1301    }
1302
1303    if (packet.type == 'connect' && packet.endpoint == '') {
1304      this.onConnect();
1305    }
1306
1307    if (packet.type == 'error' && packet.advice == 'reconnect') {
1308      this.open = false;
1309    }
1310
1311    this.socket.onPacket(packet);
1312
1313    return this;
1314  };
1315
1316  /**
1317   * Sets close timeout
1318   *
1319   * @api private
1320   */
1321  
1322  Transport.prototype.setCloseTimeout = function () {
1323    if (!this.closeTimeout) {
1324      var self = this;
1325
1326      this.closeTimeout = setTimeout(function () {
1327        self.onDisconnect();
1328      }, this.socket.closeTimeout);
1329    }
1330  };
1331
1332  /**
1333   * Called when transport disconnects.
1334   *
1335   * @api private
1336   */
1337
1338  Transport.prototype.onDisconnect = function () {
1339    if (this.close && this.open) this.close();
1340    this.clearTimeouts();
1341    this.socket.onDisconnect();
1342    return this;
1343  };
1344
1345  /**
1346   * Called when transport connects
1347   *
1348   * @api private
1349   */
1350
1351  Transport.prototype.onConnect = function () {
1352    this.socket.onConnect();
1353    return this;
1354  }
1355
1356  /**
1357   * Clears close timeout
1358   *
1359   * @api private
1360   */
1361
1362  Transport.prototype.clearCloseTimeout = function () {
1363    if (this.closeTimeout) {
1364      clearTimeout(this.closeTimeout);
1365      this.closeTimeout = null;
1366    }
1367  };
1368
1369  /**
1370   * Clear timeouts
1371   *
1372   * @api private
1373   */
1374
1375  Transport.prototype.clearTimeouts = function () {
1376    this.clearCloseTimeout();
1377
1378    if (this.reopenTimeout) {
1379      clearTimeout(this.reopenTimeout);
1380    }
1381  };
1382
1383  /**
1384   * Sends a packet
1385   *
1386   * @param {Object} packet object.
1387   * @api private
1388   */
1389
1390  Transport.prototype.packet = function (packet) {
1391    this.send(io.parser.encodePacket(packet));
1392  };
1393
1394  /**
1395   * Send the received heartbeat message back to server. So the server
1396   * knows we are still connected.
1397   *
1398   * @param {String} heartbeat Heartbeat response from the server.
1399   * @api private
1400   */
1401
1402  Transport.prototype.onHeartbeat = function (heartbeat) {
1403    this.packet({ type: 'heartbeat' });
1404  };
1405 
1406  /**
1407   * Called when the transport opens.
1408   *
1409   * @api private
1410   */
1411
1412  Transport.prototype.onOpen = function () {
1413    this.open = true;
1414    this.clearCloseTimeout();
1415    this.socket.onOpen();
1416  };
1417
1418  /**
1419   * Notifies the base when the connection with the Socket.IO server
1420   * has been disconnected.
1421   *
1422   * @api private
1423   */
1424
1425  Transport.prototype.onClose = function () {
1426    var self = this;
1427
1428    /* FIXME: reopen delay causing a infinit loop
1429    this.reopenTimeout = setTimeout(function () {
1430      self.open();
1431    }, this.socket.options['reopen delay']);*/
1432
1433    this.open = false;
1434    this.socket.onClose();
1435    this.onDisconnect();
1436  };
1437
1438  /**
1439   * Generates a connection url based on the Socket.IO URL Protocol.
1440   * See <https://github.com/learnboost/socket.io-node/> for more details.
1441   *
1442   * @returns {String} Connection url
1443   * @api private
1444   */
1445
1446  Transport.prototype.prepareUrl = function () {
1447    var options = this.socket.options;
1448
1449    return this.scheme() + '://'
1450      + options.host + ':' + options.port + '/'
1451      + options.resource + '/' + io.protocol
1452      + '/' + this.name + '/' + this.sessid;
1453  };
1454
1455  /**
1456   * Checks if the transport is ready to start a connection.
1457   *
1458   * @param {Socket} socket The socket instance that needs a transport
1459   * @param {Function} fn The callback
1460   * @api private
1461   */
1462
1463  Transport.prototype.ready = function (socket, fn) {
1464    fn.call(this);
1465  };
1466})(
1467    'undefined' != typeof io ? io : module.exports
1468  , 'undefined' != typeof io ? io : module.parent.exports
1469);
1470/**
1471 * socket.io
1472 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
1473 * MIT Licensed
1474 */
1475
1476(function (exports, io, global) {
1477
1478  /**
1479   * Expose constructor.
1480   */
1481
1482  exports.Socket = Socket;
1483
1484  /**
1485   * Create a new `Socket.IO client` which can establish a persistent
1486   * connection with a Socket.IO enabled server.
1487   *
1488   * @api public
1489   */
1490
1491  function Socket (options) {
1492    this.options = {
1493        port: 80
1494      , secure: false
1495      , document: 'document' in global ? document : false
1496      , resource: 'socket.io'
1497      , transports: io.transports
1498      , 'connect timeout': 10000
1499      , 'try multiple transports': true
1500      , 'reconnect': true
1501      , 'reconnection delay': 500
1502      , 'reconnection limit': Infinity
1503      , 'reopen delay': 3000
1504      , 'max reconnection attempts': 10
1505      , 'sync disconnect on unload': true
1506      , 'auto connect': true
1507      , 'flash policy port': 10843
1508    };
1509
1510    io.util.merge(this.options, options);
1511
1512    this.connected = false;
1513    this.open = false;
1514    this.connecting = false;
1515    this.reconnecting = false;
1516    this.namespaces = {};
1517    this.buffer = [];
1518    this.doBuffer = false;
1519
1520    if (this.options['sync disconnect on unload'] &&
1521        (!this.isXDomain() || io.util.ua.hasCORS)) {
1522      var self = this;
1523
1524      io.util.on(global, 'unload', function () {
1525        self.disconnectSync();
1526      }, false);
1527    }
1528
1529    if (this.options['auto connect']) {
1530      this.connect();
1531    }
1532};
1533
1534  /**
1535   * Apply EventEmitter mixin.
1536   */
1537
1538  io.util.mixin(Socket, io.EventEmitter);
1539
1540  /**
1541   * Returns a namespace listener/emitter for this socket
1542   *
1543   * @api public
1544   */
1545
1546  Socket.prototype.of = function (name) {
1547    if (!this.namespaces[name]) {
1548      this.namespaces[name] = new io.SocketNamespace(this, name);
1549
1550      if (name !== '') {
1551        this.namespaces[name].packet({ type: 'connect' });
1552      }
1553    }
1554
1555    return this.namespaces[name];
1556  };
1557
1558  /**
1559   * Emits the given event to the Socket and all namespaces
1560   *
1561   * @api private
1562   */
1563
1564  Socket.prototype.publish = function () {
1565    this.emit.apply(this, arguments);
1566
1567    var nsp;
1568
1569    for (var i in this.namespaces) {
1570      if (this.namespaces.hasOwnProperty(i)) {
1571        nsp = this.of(i);
1572        nsp.$emit.apply(nsp, arguments);
1573      }
1574    }
1575  };
1576
1577  /**
1578   * Performs the handshake
1579   *
1580   * @api private
1581   */
1582
1583  function empty () { };
1584
1585  Socket.prototype.handshake = function (fn) {
1586    var self = this
1587      , options = this.options;
1588
1589    function complete (data) {
1590      if (data instanceof Error) {
1591        self.onError(data.message);
1592      } else {
1593        fn.apply(null, data.split(':'));
1594      }
1595    };
1596
1597    var url = [
1598          'http' + (options.secure ? 's' : '') + ':/'
1599        , options.host + ':' + options.port
1600        , options.resource
1601        , io.protocol
1602        , io.util.query(this.options.query, 't=' + +new Date)
1603      ].join('/');
1604
1605    if (this.isXDomain() && !io.util.ua.hasCORS) {
1606      var insertAt = document.getElementsByTagName('script')[0]
1607        , script = document.createElement('script');
1608
1609      script.src = url + '&jsonp=' + io.j.length;
1610      insertAt.parentNode.insertBefore(script, insertAt);
1611
1612      io.j.push(function (data) {
1613        complete(data);
1614        script.parentNode.removeChild(script);
1615      });
1616    } else {
1617      var xhr = io.util.request();
1618
1619      xhr.open('GET', url, true);
1620      xhr.withCredentials = true;
1621      xhr.onreadystatechange = function () {
1622        if (xhr.readyState == 4) {
1623          xhr.onreadystatechange = empty;
1624
1625          if (xhr.status == 200) {
1626            complete(xhr.responseText);
1627          } else {
1628            !self.reconnecting && self.onError(xhr.responseText);
1629          }
1630        }
1631      };
1632      xhr.send(null);
1633    }
1634  };
1635
1636  /**
1637   * Find an available transport based on the options supplied in the constructor.
1638   *
1639   * @api private
1640   */
1641
1642  Socket.prototype.getTransport = function (override) {
1643    var transports = override || this.transports, match;
1644
1645    for (var i = 0, transport; transport = transports[i]; i++) {
1646      if (io.Transport[transport]
1647        && io.Transport[transport].check(this)
1648        && (!this.isXDomain() || io.Transport[transport].xdomainCheck())) {
1649        return new io.Transport[transport](this, this.sessionid);
1650      }
1651    }
1652
1653    return null;
1654  };
1655
1656  /**
1657   * Connects to the server.
1658   *
1659   * @param {Function} [fn] Callback.
1660   * @returns {io.Socket}
1661   * @api public
1662   */
1663
1664  Socket.prototype.connect = function (fn) {
1665    if (this.connecting) {
1666      return this;
1667    }
1668
1669    var self = this;
1670
1671    this.handshake(function (sid, heartbeat, close, transports) {
1672      self.sessionid = sid;
1673      self.closeTimeout = close * 1000;
1674      self.heartbeatTimeout = heartbeat * 1000;
1675      self.transports = transports ? io.util.intersect(
1676          transports.split(',')
1677        , self.options.transports
1678      ) : self.options.transports;
1679
1680      self.setHeartbeatTimeout();
1681
1682      function connect (transports){
1683        if (self.transport) self.transport.clearTimeouts();
1684
1685        self.transport = self.getTransport(transports);
1686        if (!self.transport) return self.publish('connect_failed');
1687
1688        // once the transport is ready
1689        self.transport.ready(self, function () {
1690          self.connecting = true;
1691          self.publish('connecting', self.transport.name);
1692          self.transport.open();
1693
1694          if (self.options['connect timeout']) {
1695            self.connectTimeoutTimer = setTimeout(function () {
1696              if (!self.connected) {
1697                self.connecting = false;
1698
1699                if (self.options['try multiple transports']) {
1700                  if (!self.remainingTransports) {
1701                    self.remainingTransports = self.transports.slice(0);
1702                  }
1703
1704                  var remaining = self.remainingTransports;
1705
1706                  while (remaining.length > 0 && remaining.splice(0,1)[0] !=
1707                         self.transport.name) {}
1708
1709                    if (remaining.length){
1710                      connect(remaining);
1711                    } else {
1712                      self.publish('connect_failed');
1713                    }
1714                }
1715              }
1716            }, self.options['connect timeout']);
1717          }
1718        });
1719      }
1720
1721      connect(self.transports);
1722
1723      self.once('connect', function (){
1724        clearTimeout(self.connectTimeoutTimer);
1725
1726        fn && typeof fn == 'function' && fn();
1727      });
1728    });
1729
1730    return this;
1731  };
1732
1733  /**
1734   * Clears and sets a new heartbeat timeout using the value given by the
1735   * server during the handshake.
1736   *
1737   * @api private
1738   */
1739
1740  Socket.prototype.setHeartbeatTimeout = function () {
1741    clearTimeout(this.heartbeatTimeoutTimer);
1742
1743    var self = this;
1744    this.heartbeatTimeoutTimer = setTimeout(function () {
1745      self.transport.onClose();
1746    }, this.heartbeatTimeout);
1747  };
1748
1749  /**
1750   * Sends a message.
1751   *
1752   * @param {Object} data packet.
1753   * @returns {io.Socket}
1754   * @api public
1755   */
1756
1757  Socket.prototype.packet = function (data) {
1758    if (this.connected && !this.doBuffer) {
1759      this.transport.packet(data);
1760    } else {
1761      this.buffer.push(data);
1762    }
1763
1764    return this;
1765  };
1766
1767  /**
1768   * Sets buffer state
1769   *
1770   * @api private
1771   */
1772
1773  Socket.prototype.setBuffer = function (v) {
1774    this.doBuffer = v;
1775
1776    if (!v && this.connected && this.buffer.length) {
1777      this.transport.payload(this.buffer);
1778      this.buffer = [];
1779    }
1780  };
1781
1782  /**
1783   * Disconnect the established connect.
1784   *
1785   * @returns {io.Socket}
1786   * @api public
1787   */
1788
1789  Socket.prototype.disconnect = function () {
1790    if (this.connected || this.connecting) {
1791      if (this.open) {
1792        this.of('').packet({ type: 'disconnect' });
1793      }
1794
1795      // handle disconnection immediately
1796      this.onDisconnect('booted');
1797    }
1798
1799    return this;
1800  };
1801
1802  /**
1803   * Disconnects the socket with a sync XHR.
1804   *
1805   * @api private
1806   */
1807
1808  Socket.prototype.disconnectSync = function () {
1809    // ensure disconnection
1810    var xhr = io.util.request()
1811      , uri = this.resource + '/' + io.protocol + '/' + this.sessionid;
1812
1813    xhr.open('GET', uri, true);
1814
1815    // handle disconnection immediately
1816    this.onDisconnect('booted');
1817  };
1818
1819  /**
1820   * Check if we need to use cross domain enabled transports. Cross domain would
1821   * be a different port or different domain name.
1822   *
1823   * @returns {Boolean}
1824   * @api private
1825   */
1826
1827  Socket.prototype.isXDomain = function () {
1828
1829    var port = global.location.port ||
1830      ('https:' == global.location.protocol ? 443 : 80);
1831
1832    return this.options.host !== global.location.hostname 
1833      || this.options.port != port;
1834  };
1835
1836  /**
1837   * Called upon handshake.
1838   *
1839   * @api private
1840   */
1841
1842  Socket.prototype.onConnect = function () {
1843    if (!this.connected) {
1844      this.connected = true;
1845      this.connecting = false;
1846      if (!this.doBuffer) {
1847        // make sure to flush the buffer
1848        this.setBuffer(false);
1849      }
1850      this.emit('connect');
1851    }
1852  };
1853
1854  /**
1855   * Called when the transport opens
1856   *
1857   * @api private
1858   */
1859
1860  Socket.prototype.onOpen = function () {
1861    this.open = true;
1862  };
1863
1864  /**
1865   * Called when the transport closes.
1866   *
1867   * @api private
1868   */
1869
1870  Socket.prototype.onClose = function () {
1871    this.open = false;
1872    clearTimeout(this.heartbeatTimeoutTimer);
1873  };
1874
1875  /**
1876   * Called when the transport first opens a connection
1877   *
1878   * @param text
1879   */
1880
1881  Socket.prototype.onPacket = function (packet) {
1882    this.of(packet.endpoint).onPacket(packet);
1883  };
1884
1885  /**
1886   * Handles an error.
1887   *
1888   * @api private
1889   */
1890
1891  Socket.prototype.onError = function (err) {
1892    if (err && err.advice) {
1893      if (err.advice === 'reconnect' && (this.connected || this.connecting)) {
1894        this.disconnect();
1895        if (this.options.reconnect) {
1896          this.reconnect();
1897        }
1898      }
1899    }
1900
1901    this.publish('error', err && err.reason ? err.reason : err);
1902  };
1903
1904  /**
1905   * Called when the transport disconnects.
1906   *
1907   * @api private
1908   */
1909
1910  Socket.prototype.onDisconnect = function (reason) {
1911    var wasConnected = this.connected
1912      , wasConnecting = this.connecting;
1913
1914    this.connected = false;
1915    this.connecting = false;
1916    this.open = false;
1917
1918    if (wasConnected || wasConnecting) {
1919      this.transport.close();
1920      this.transport.clearTimeouts();
1921      if (wasConnected) {
1922        this.publish('disconnect', reason);
1923
1924        if ('booted' != reason && this.options.reconnect && !this.reconnecting) {
1925          this.reconnect();
1926        }
1927      }
1928    }
1929  };
1930
1931  /**
1932   * Called upon reconnection.
1933   *
1934   * @api private
1935   */
1936
1937  Socket.prototype.reconnect = function () {
1938    this.reconnecting = true;
1939    this.reconnectionAttempts = 0;
1940    this.reconnectionDelay = this.options['reconnection delay'];
1941
1942    var self = this
1943      , maxAttempts = this.options['max reconnection attempts']
1944      , tryMultiple = this.options['try multiple transports']
1945      , limit = this.options['reconnection limit'];
1946
1947    function reset () {
1948      if (self.connected) {
1949        for (var i in self.namespaces) {
1950          if (self.namespaces.hasOwnProperty(i) && '' !== i) {
1951              self.namespaces[i].packet({ type: 'connect' });
1952          }
1953        }
1954        self.publish('reconnect', self.transport.name, self.reconnectionAttempts);
1955      }
1956
1957      clearTimeout(self.reconnectionTimer);
1958
1959      self.removeListener('connect_failed', maybeReconnect);
1960      self.removeListener('connect', maybeReconnect);
1961
1962      self.reconnecting = false;
1963
1964      delete self.reconnectionAttempts;
1965      delete self.reconnectionDelay;
1966      delete self.reconnectionTimer;
1967      delete self.redoTransports;
1968
1969      self.options['try multiple transports'] = tryMultiple;
1970    };
1971
1972    function maybeReconnect () {
1973      if (!self.reconnecting) {
1974        return;
1975      }
1976
1977      if (self.connected) {
1978        return reset();
1979      };
1980
1981      if (self.connecting && self.reconnecting) {
1982        return self.reconnectionTimer = setTimeout(maybeReconnect, 1000);
1983      }
1984
1985      if (self.reconnectionAttempts++ >= maxAttempts) {
1986        if (!self.redoTransports) {
1987          self.on('connect_failed', maybeReconnect);
1988          self.options['try multiple transports'] = true;
1989          self.transport = self.getTransport();
1990          self.redoTransports = true;
1991          self.connect();
1992        } else {
1993          self.publish('reconnect_failed');
1994          reset();
1995        }
1996      } else {
1997        if (self.reconnectionDelay < limit) {
1998          self.reconnectionDelay *= 2; // exponential back off
1999        }
2000
2001        self.connect();
2002        self.publish('reconnecting', self.reconnectionDelay, self.reconnectionAttempts);
2003        self.reconnectionTimer = setTimeout(maybeReconnect, self.reconnectionDelay);
2004      }
2005    };
2006
2007    this.options['try multiple transports'] = false;
2008    this.reconnectionTimer = setTimeout(maybeReconnect, this.reconnectionDelay);
2009
2010    this.on('connect', maybeReconnect);
2011  };
2012
2013})(
2014    'undefined' != typeof io ? io : module.exports
2015  , 'undefined' != typeof io ? io : module.parent.exports
2016  , this
2017);
2018/**
2019 * socket.io
2020 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
2021 * MIT Licensed
2022 */
2023
2024(function (exports, io) {
2025
2026  /**
2027   * Expose constructor.
2028   */
2029
2030  exports.SocketNamespace = SocketNamespace;
2031
2032  /**
2033   * Socket namespace constructor.
2034   *
2035   * @constructor
2036   * @api public
2037   */
2038
2039  function SocketNamespace (socket, name) {
2040    this.socket = socket;
2041    this.name = name || '';
2042    this.flags = {};
2043    this.json = new Flag(this, 'json');
2044    this.ackPackets = 0;
2045    this.acks = {};
2046  };
2047
2048  /**
2049   * Apply EventEmitter mixin.
2050   */
2051
2052  io.util.mixin(SocketNamespace, io.EventEmitter);
2053
2054  /**
2055   * Copies emit since we override it
2056   *
2057   * @api private
2058   */
2059
2060  SocketNamespace.prototype.$emit = io.EventEmitter.prototype.emit;
2061
2062  /**
2063   * Creates a new namespace, by proxying the request to the socket. This
2064   * allows us to use the synax as we do on the server.
2065   *
2066   * @api public
2067   */
2068
2069  SocketNamespace.prototype.of = function () {
2070    return this.socket.of.apply(this.socket, arguments);
2071  };
2072
2073  /**
2074   * Sends a packet.
2075   *
2076   * @api private
2077   */
2078
2079  SocketNamespace.prototype.packet = function (packet) {
2080    packet.endpoint = this.name;
2081    this.socket.packet(packet);
2082    this.flags = {};
2083    return this;
2084  };
2085
2086  /**
2087   * Sends a message
2088   *
2089   * @api public
2090   */
2091
2092  SocketNamespace.prototype.send = function (data, fn) {
2093    var packet = {
2094        type: this.flags.json ? 'json' : 'message'
2095      , data: data
2096    };
2097
2098    if ('function' == typeof fn) {
2099      packet.id = ++this.ackPackets;
2100      packet.ack = true;
2101      this.acks[packet.id] = fn;
2102    }
2103
2104    return this.packet(packet);
2105  };
2106
2107  /**
2108   * Emits an event
2109   *
2110   * @api public
2111   */
2112  
2113  SocketNamespace.prototype.emit = function (name) {
2114    var args = Array.prototype.slice.call(arguments, 1)
2115      , lastArg = args[args.length - 1]
2116      , packet = {
2117            type: 'event'
2118          , name: name
2119        };
2120
2121    if ('function' == typeof lastArg) {
2122      packet.id = ++this.ackPackets;
2123      packet.ack = 'data';
2124      this.acks[packet.id] = lastArg;
2125      args = args.slice(0, args.length - 1);
2126    }
2127
2128    packet.args = args;
2129
2130    return this.packet(packet);
2131  };
2132
2133  /**
2134   * Disconnects the namespace
2135   *
2136   * @api private
2137   */
2138
2139  SocketNamespace.prototype.disconnect = function () {
2140    if (this.name === '') {
2141      this.socket.disconnect();
2142    } else {
2143      this.packet({ type: 'disconnect' });
2144      this.$emit('disconnect');
2145    }
2146
2147    return this;
2148  };
2149
2150  /**
2151   * Handles a packet
2152   *
2153   * @api private
2154   */
2155
2156  SocketNamespace.prototype.onPacket = function (packet) {
2157    var self = this;
2158
2159    function ack () {
2160      self.packet({
2161          type: 'ack'
2162        , args: io.util.toArray(arguments)
2163        , ackId: packet.id
2164      });
2165    };
2166
2167    switch (packet.type) {
2168      case 'connect':
2169        this.$emit('connect');
2170        break;
2171
2172      case 'disconnect':
2173        if (this.name === '') {
2174          this.socket.onDisconnect(packet.reason || 'booted');
2175        } else {
2176          this.$emit('disconnect', packet.reason);
2177        }
2178        break;
2179
2180      case 'message':
2181      case 'json':
2182        var params = ['message', packet.data];
2183
2184        if (packet.ack == 'data') {
2185          params.push(ack);
2186        } else if (packet.ack) {
2187          this.packet({ type: 'ack', ackId: packet.id });
2188        }
2189
2190        this.$emit.apply(this, params);
2191        break;
2192
2193      case 'event':
2194        var params = [packet.name].concat(packet.args);
2195
2196        if (packet.ack == 'data')
2197          params.push(ack);
2198
2199        this

Large files files are truncated, but you can click here to view the full file