"use strict";var Base=require("./base"),Draft75=require("./draft75"),crypto=require("crypto"),util=require("util"),numberFromKey=function(e){return parseInt(e.match(/[0-9]/g).join(""),10)},spacesInKey=function(e){return e.match(/ /g).length},Draft76=function(e,t,s){Draft75.apply(this,arguments),this._stage=-1,this._body=[],this.version="hixie-76",this._headers.clear(),this._headers.set("Upgrade","WebSocket"),this._headers.set("Connection","Upgrade"),this._headers.set("Sec-WebSocket-Origin",this._request.headers.origin),this._headers.set("Sec-WebSocket-Location",this.url)};util.inherits(Draft76,Draft75);var instance={BODY_SIZE:8,start:function(){return!!Draft75.prototype.start.call(this)&&(this._started=!0,this._sendHandshakeBody(),!0)},close:function(){return 3!==this.readyState&&(this._write(new Buffer([255,0])),this.readyState=3,this.emit("close",new Base.CloseEvent(null,null)),!0)},_handshakeResponse:function(){var e=(a=this._request.headers)["sec-websocket-key1"],t=numberFromKey(e),s=spacesInKey(e),r=a["sec-websocket-key2"],i=numberFromKey(r),n=spacesInKey(r);if(t%s!=0||i%n!=0)return this.emit("error",new Error("Client sent invalid Sec-WebSocket-Key headers")),this.close(),null;this._keyValues=[t/s,i/n];var a=["HTTP/1.1 101 WebSocket Protocol Handshake",this._headers.toString(),""];return new Buffer(a.join("\r\n"),"binary")},_handshakeSignature:function(){if(this._body.length<this.BODY_SIZE)return null;var e=crypto.createHash("md5"),t=new Buffer(8+this.BODY_SIZE);return t.writeUInt32BE(this._keyValues[0],0),t.writeUInt32BE(this._keyValues[1],4),new Buffer(this._body).copy(t,8,0,this.BODY_SIZE),e.update(t),new Buffer(e.digest("binary"),"binary")},_sendHandshakeBody:function(){if(this._started){var e=this._handshakeSignature();e&&(this._write(e),this._stage=0,this._open(),this._body.length>this.BODY_SIZE&&this.parse(this._body.slice(this.BODY_SIZE)))}},_parseLeadingByte:function(e){if(255!==e)return Draft75.prototype._parseLeadingByte.call(this,e);this._closing=!0,this._length=0,this._stage=1}};for(var key in instance)Draft76.prototype[key]=instance[key];module.exports=Draft76;