/*! jQuery v1.8.3 jquery.com | jquery.org/license */
(function(e,t){function _(e){var t=M[e]={};return v.each(e.split(y),function(e,n){t[n]=!0}),t}function H(e,n,r){if(r===t&&e.nodeType===1){var i="data-"+n.replace(P,"-$1").toLowerCase();r=e.getAttribute(i);if(typeof r=="string"){try{r=r==="true"?!0:r==="false"?!1:r==="null"?null:+r+""===r?+r:D.test(r)?v.parseJSON(r):r}catch(s){}v.data(e,n,r)}else r=t}return r}function B(e){var t;for(t in e){if(t==="data"&&v.isEmptyObject(e[t]))continue;if(t!=="toJSON")return!1}return!0}function et(){return!1}function tt(){return!0}function ut(e){return!e||!e.parentNode||e.parentNode.nodeType===11}function at(e,t){do e=e[t];while(e&&e.nodeType!==1);return e}function ft(e,t,n){t=t||0;if(v.isFunction(t))return v.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return v.grep(e,function(e,r){return e===t===n});if(typeof t=="string"){var r=v.grep(e,function(e){return e.nodeType===1});if(it.test(t))return v.filter(t,r,!n);t=v.filter(t,r)}return v.grep(e,function(e,r){return v.inArray(e,t)>=0===n})}function lt(e){var t=ct.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function At(e,t){if(t.nodeType!==1||!v.hasData(e))return;var n,r,i,s=v._data(e),o=v._data(t,s),u=s.events;if(u){delete o.handle,o.events={};for(n in u)for(r=0,i=u[n].length;r<i;r++)v.event.add(t,n,u[n][r])}o.data&&(o.data=v.extend({},o.data))}function Ot(e,t){var n;if(t.nodeType!==1)return;t.clearAttributes&&t.clearAttributes(),t.mergeAttributes&&t.mergeAttributes(e),n=t.nodeName.toLowerCase(),n==="object"?(t.parentNode&&(t.outerHTML=e.outerHTML),v.support.html5Clone&&e.innerHTML&&!v.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):n==="input"&&Et.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):n==="option"?t.selected=e.defaultSelected:n==="input"||n==="textarea"?t.defaultValue=e.defaultValue:n==="script"&&t.text!==e.text&&(t.text=e.text),t.removeAttribute(v.expando)}function Mt(e){return typeof e.getElementsByTagName!="undefined"?e.getElementsByTagName("*"):typeof e.querySelectorAll!="undefined"?e.querySelectorAll("*"):[]}function _t(e){Et.test(e.type)&&(e.defaultChecked=e.checked)}function Qt(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=Jt.length;while(i--){t=Jt[i]+n;if(t in e)return t}return r}function Gt(e,t){return e=t||e,v.css(e,"display")==="none"||!v.contains(e.ownerDocument,e)}function Yt(e,t){var n,r,i=[],s=0,o=e.length;for(;s<o;s++){n=e[s];if(!n.style)continue;i[s]=v._data(n,"olddisplay"),t?(!i[s]&&n.style.display==="none"&&(n.style.display=""),n.style.display===""&&Gt(n)&&(i[s]=v._data(n,"olddisplay",nn(n.nodeName)))):(r=Dt(n,"display"),!i[s]&&r!=="none"&&v._data(n,"olddisplay",r))}for(s=0;s<o;s++){n=e[s];if(!n.style)continue;if(!t||n.style.display==="none"||n.style.display==="")n.style.display=t?i[s]||"":"none"}return e}function Zt(e,t,n){var r=Rt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function en(e,t,n,r){var i=n===(r?"border":"content")?4:t==="width"?1:0,s=0;for(;i<4;i+=2)n==="margin"&&(s+=v.css(e,n+$t[i],!0)),r?(n==="content"&&(s-=parseFloat(Dt(e,"padding"+$t[i]))||0),n!=="margin"&&(s-=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0)):(s+=parseFloat(Dt(e,"padding"+$t[i]))||0,n!=="padding"&&(s+=parseFloat(Dt(e,"border"+$t[i]+"Width"))||0));return s}function tn(e,t,n){var r=t==="width"?e.offsetWidth:e.offsetHeight,i=!0,s=v.support.boxSizing&&v.css(e,"boxSizing")==="border-box";if(r<=0||r==null){r=Dt(e,t);if(r<0||r==null)r=e.style[t];if(Ut.test(r))return r;i=s&&(v.support.boxSizingReliable||r===e.style[t]),r=parseFloat(r)||0}return r+en(e,t,n||(s?"border":"content"),i)+"px"}function nn(e){if(Wt[e])return Wt[e];var t=v("<"+e+">").appendTo(i.body),n=t.css("display");t.remove();if(n==="none"||n===""){Pt=i.body.appendChild(Pt||v.extend(i.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!Ht||!Pt.createElement)Ht=(Pt.contentWindow||Pt.contentDocument).document,Ht.write("<!doctype html><html><body>"),Ht.close();t=Ht.body.appendChild(Ht.createElement(e)),n=Dt(t,"display"),i.body.removeChild(Pt)}return Wt[e]=n,n}function fn(e,t,n,r){var i;if(v.isArray(t))v.each(t,function(t,i){n||sn.test(e)?r(e,i):fn(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&v.type(t)==="object")for(i in t)fn(e+"["+i+"]",t[i],n,r);else r(e,t)}function Cn(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i,s,o=t.toLowerCase().split(y),u=0,a=o.length;if(v.isFunction(n))for(;u<a;u++)r=o[u],s=/^\+/.test(r),s&&(r=r.substr(1)||"*"),i=e[r]=e[r]||[],i[s?"unshift":"push"](n)}}function kn(e,n,r,i,s,o){s=s||n.dataTypes[0],o=o||{},o[s]=!0;var u,a=e[s],f=0,l=a?a.length:0,c=e===Sn;for(;f<l&&(c||!u);f++)u=a[f](n,r,i),typeof u=="string"&&(!c||o[u]?u=t:(n.dataTypes.unshift(u),u=kn(e,n,r,i,u,o)));return(c||!u)&&!o["*"]&&(u=kn(e,n,r,i,"*",o)),u}function Ln(e,n){var r,i,s=v.ajaxSettings.flatOptions||{};for(r in n)n[r]!==t&&((s[r]?e:i||(i={}))[r]=n[r]);i&&v.extend(!0,e,i)}function An(e,n,r){var i,s,o,u,a=e.contents,f=e.dataTypes,l=e.responseFields;for(s in l)s in r&&(n[l[s]]=r[s]);while(f[0]==="*")f.shift(),i===t&&(i=e.mimeType||n.getResponseHeader("content-type"));if(i)for(s in a)if(a[s]&&a[s].test(i)){f.unshift(s);break}if(f[0]in r)o=f[0];else{for(s in r){if(!f[0]||e.converters[s+" "+f[0]]){o=s;break}u||(u=s)}o=o||u}if(o)return o!==f[0]&&f.unshift(o),r[o]}function On(e,t){var n,r,i,s,o=e.dataTypes.slice(),u=o[0],a={},f=0;e.dataFilter&&(t=e.dataFilter(t,e.dataType));if(o[1])for(n in e.converters)a[n.toLowerCase()]=e.converters[n];for(;i=o[++f];)if(i!=="*"){if(u!=="*"&&u!==i){n=a[u+" "+i]||a["* "+i];if(!n)for(r in a){s=r.split(" ");if(s[1]===i){n=a[u+" "+s[0]]||a["* "+s[0]];if(n){n===!0?n=a[r]:a[r]!==!0&&(i=s[0],o.splice(f--,0,i));break}}}if(n!==!0)if(n&&e["throws"])t=n(t);else try{t=n(t)}catch(l){return{state:"parsererror",error:n?l:"No conversion from "+u+" to "+i}}}u=i}return{state:"success",data:t}}function Fn(){try{return new e.XMLHttpRequest}catch(t){}}function In(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function $n(){return setTimeout(function(){qn=t},0),qn=v.now()}function Jn(e,t){v.each(t,function(t,n){var r=(Vn[t]||[]).concat(Vn["*"]),i=0,s=r.length;for(;i<s;i++)if(r[i].call(e,t,n))return})}function Kn(e,t,n){var r,i=0,s=0,o=Xn.length,u=v.Deferred().always(function(){delete a.elem}),a=function(){var t=qn||$n(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,i=1-r,s=0,o=f.tweens.length;for(;s<o;s++)f.tweens[s].run(i);return u.notifyWith(e,[f,i,n]),i<1&&o?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:v.extend({},t),opts:v.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:qn||$n(),duration:n.duration,tweens:[],createTween:function(t,n,r){var i=v.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(i),i},stop:function(t){var n=0,r=t?f.tweens.length:0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;Qn(l,f.opts.specialEasing);for(;i<o;i++){r=Xn[i].call(f,e,l,f.opts);if(r)return r}return Jn(f,l),v.isFunction(f.opts.start)&&f.opts.start.call(e,f),v.fx.timer(v.extend(a,{anim:f,queue:f.opts.queue,elem:e})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function Qn(e,t){var n,r,i,s,o;for(n in e){r=v.camelCase(n),i=t[r],s=e[n],v.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=v.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Gn(e,t,n){var r,i,s,o,u,a,f,l,c,h=this,p=e.style,d={},m=[],g=e.nodeType&&Gt(e);n.queue||(l=v._queueHooks(e,"fx"),l.unqueued==null&&(l.unqueued=0,c=l.empty.fire,l.empty.fire=function(){l.unqueued||c()}),l.unqueued++,h.always(function(){h.always(function(){l.unqueued--,v.queue(e,"fx").length||l.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],v.css(e,"display")==="inline"&&v.css(e,"float")==="none"&&(!v.support.inlineBlockNeedsLayout||nn(e.nodeName)==="inline"?p.display="inline-block":p.zoom=1)),n.overflow&&(p.overflow="hidden",v.support.shrinkWrapBlocks||h.done(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t){s=t[r];if(Un.exec(s)){delete t[r],a=a||s==="toggle";if(s===(g?"hide":"show"))continue;m.push(r)}}o=m.length;if(o){u=v._data(e,"fxshow")||v._data(e,"fxshow",{}),"hidden"in u&&(g=u.hidden),a&&(u.hidden=!g),g?v(e).show():h.done(function(){v(e).hide()}),h.done(function(){var t;v.removeData(e,"fxshow",!0);for(t in d)v.style(e,t,d[t])});for(r=0;r<o;r++)i=m[r],f=h.createTween(i,g?u[i]:0),d[i]=u[i]||v.style(e,i),i in u||(u[i]=f.start,g&&(f.end=f.start,f.start=i==="width"||i==="height"?1:0))}}function Yn(e,t,n,r,i){return new Yn.prototype.init(e,t,n,r,i)}function Zn(e,t){var n,r={height:e},i=0;t=t?1:0;for(;i<4;i+=2-t)n=$t[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function tr(e){return v.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:!1}var n,r,i=e.document,s=e.location,o=e.navigator,u=e.jQuery,a=e.$,f=Array.prototype.push,l=Array.prototype.slice,c=Array.prototype.indexOf,h=Object.prototype.toString,p=Object.prototype.hasOwnProperty,d=String.prototype.trim,v=function(e,t){return new v.fn.init(e,t,n)},m=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,g=/\S/,y=/\s+/,b=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,w=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,E=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,S=/^[\],:{}\s]*$/,x=/(?:^|:|,)(?:\s*\[)+/g,T=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,N=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,C=/^-ms-/,k=/-([\da-z])/gi,L=function(e,t){return(t+"").toUpperCase()},A=function(){i.addEventListener?(i.removeEventListener("DOMContentLoaded",A,!1),v.ready()):i.readyState==="complete"&&(i.detachEvent("onreadystatechange",A),v.ready())},O={};v.fn=v.prototype={constructor:v,init:function(e,n,r){var s,o,u,a;if(!e)return this;if(e.nodeType)return this.context=this[0]=e,this.length=1,this;if(typeof e=="string"){e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3?s=[null,e,null]:s=w.exec(e);if(s&&(s[1]||!n)){if(s[1])return n=n instanceof v?n[0]:n,a=n&&n.nodeType?n.ownerDocument||n:i,e=v.parseHTML(s[1],a,!0),E.test(s[1])&&v.isPlainObject(n)&&this.attr.call(e,n,!0),v.merge(this,e);o=i.getElementById(s[2]);if(o&&o.parentNode){if(o.id!==s[2])return r.find(e);this.length=1,this[0]=o}return this.context=i,this.selector=e,this}return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e)}return v.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),v.makeArray(e,this))},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return l.call(this)},get:function(e){return e==null?this.toArray():e<0?this[this.length+e]:this[e]},pushStack:function(e,t,n){var r=v.merge(this.constructor(),e);return r.prevObject=this,r.context=this.context,t==="find"?r.selector=this.selector+(this.selector?" ":"")+n:t&&(r.selector=this.selector+"."+t+"("+n+")"),r},each:function(e,t){return v.each(this,e,t)},ready:function(e){return v.ready.promise().done(e),this},eq:function(e){return e=+e,e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(l.apply(this,arguments),"slice",l.call(arguments).join(","))},map:function(e){return this.pushStack(v.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:[].sort,splice:[].splice},v.fn.init.prototype=v.fn,v.extend=v.fn.extend=function(){var e,n,r,i,s,o,u=arguments[0]||{},a=1,f=arguments.length,l=!1;typeof u=="boolean"&&(l=u,u=arguments[1]||{},a=2),typeof u!="object"&&!v.isFunction(u)&&(u={}),f===a&&(u=this,--a);for(;a<f;a++)if((e=arguments[a])!=null)for(n in e){r=u[n],i=e[n];if(u===i)continue;l&&i&&(v.isPlainObject(i)||(s=v.isArray(i)))?(s?(s=!1,o=r&&v.isArray(r)?r:[]):o=r&&v.isPlainObject(r)?r:{},u[n]=v.extend(l,o,i)):i!==t&&(u[n]=i)}return u},v.extend({noConflict:function(t){return e.$===v&&(e.$=a),t&&e.jQuery===v&&(e.jQuery=u),v},isReady:!1,readyWait:1,holdReady:function(e){e?v.readyWait++:v.ready(!0)},ready:function(e){if(e===!0?--v.readyWait:v.isReady)return;if(!i.body)return setTimeout(v.ready,1);v.isReady=!0;if(e!==!0&&--v.readyWait>0)return;r.resolveWith(i,[v]),v.fn.trigger&&v(i).trigger("ready").off("ready")},isFunction:function(e){return v.type(e)==="function"},isArray:Array.isArray||function(e){return v.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):O[h.call(e)]||"object"},isPlainObject:function(e){if(!e||v.type(e)!=="object"||e.nodeType||v.isWindow(e))return!1;try{if(e.constructor&&!p.call(e,"constructor")&&!p.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||p.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw new Error(e)},parseHTML:function(e,t,n){var r;return!e||typeof e!="string"?null:(typeof t=="boolean"&&(n=t,t=0),t=t||i,(r=E.exec(e))?[t.createElement(r[1])]:(r=v.buildFragment([e],t,n?null:[]),v.merge([],(r.cacheable?v.clone(r.fragment):r.fragment).childNodes)))},parseJSON:function(t){if(!t||typeof t!="string")return null;t=v.trim(t);if(e.JSON&&e.JSON.parse)return e.JSON.parse(t);if(S.test(t.replace(T,"@").replace(N,"]").replace(x,"")))return(new Function("return "+t))();v.error("Invalid JSON: "+t)},parseXML:function(n){var r,i;if(!n||typeof n!="string")return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(s){r=t}return(!r||!r.documentElement||r.getElementsByTagName("parsererror").length)&&v.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&g.test(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(C,"ms-").replace(k,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,n,r){var i,s=0,o=e.length,u=o===t||v.isFunction(e);if(r){if(u){for(i in e)if(n.apply(e[i],r)===!1)break}else for(;s<o;)if(n.apply(e[s++],r)===!1)break}else if(u){for(i in e)if(n.call(e[i],i,e[i])===!1)break}else for(;s<o;)if(n.call(e[s],s,e[s++])===!1)break;return e},trim:d&&!d.call("\ufeff\u00a0")?function(e){return e==null?"":d.call(e)}:function(e){return e==null?"":(e+"").replace(b,"")},makeArray:function(e,t){var n,r=t||[];return e!=null&&(n=v.type(e),e.length==null||n==="string"||n==="function"||n==="regexp"||v.isWindow(e)?f.call(r,e):v.merge(r,e)),r},inArray:function(e,t,n){var r;if(t){if(c)return c.call(t,e,n);r=t.length,n=n?n<0?Math.max(0,r+n):n:0;for(;n<r;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,s=0;if(typeof r=="number")for(;s<r;s++)e[i++]=n[s];else while(n[s]!==t)e[i++]=n[s++];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length;n=!!n;for(;s<o;s++)r=!!t(e[s],s),n!==r&&i.push(e[s]);return i},map:function(e,n,r){var i,s,o=[],u=0,a=e.length,f=e instanceof v||a!==t&&typeof a=="number"&&(a>0&&e[0]&&e[a-1]||a===0||v.isArray(e));if(f)for(;u<a;u++)i=n(e[u],u,r),i!=null&&(o[o.length]=i);else for(s in e)i=n(e[s],s,r),i!=null&&(o[o.length]=i);return o.concat.apply([],o)},guid:1,proxy:function(e,n){var r,i,s;return typeof n=="string"&&(r=e[n],n=e,e=r),v.isFunction(e)?(i=l.call(arguments,2),s=function(){return e.apply(n,i.concat(l.call(arguments)))},s.guid=e.guid=e.guid||v.guid++,s):t},access:function(e,n,r,i,s,o,u){var a,f=r==null,l=0,c=e.length;if(r&&typeof r=="object"){for(l in r)v.access(e,n,l,r[l],1,o,i);s=1}else if(i!==t){a=u===t&&v.isFunction(i),f&&(a?(a=n,n=function(e,t,n){return a.call(v(e),n)}):(n.call(e,i),n=null));if(n)for(;l<c;l++)n(e[l],r,a?i.call(e[l],l,n(e[l],r)):i,u);s=1}return s?e:f?n.call(e):c?n(e[0],r):o},now:function(){return(new Date).getTime()}}),v.ready.promise=function(t){if(!r){r=v.Deferred();if(i.readyState==="complete")setTimeout(v.ready,1);else if(i.addEventListener)i.addEventListener("DOMContentLoaded",A,!1),e.addEventListener("load",v.ready,!1);else{i.attachEvent("onreadystatechange",A),e.attachEvent("onload",v.ready);var n=!1;try{n=e.frameElement==null&&i.documentElement}catch(s){}n&&n.doScroll&&function o(){if(!v.isReady){try{n.doScroll("left")}catch(e){return setTimeout(o,50)}v.ready()}}()}}return r.promise(t)},v.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(e,t){O["[object "+t+"]"]=t.toLowerCase()}),n=v(i);var M={};v.Callbacks=function(e){e=typeof e=="string"?M[e]||_(e):v.extend({},e);var n,r,i,s,o,u,a=[],f=!e.once&&[],l=function(t){n=e.memory&&t,r=!0,u=s||0,s=0,o=a.length,i=!0;for(;a&&u<o;u++)if(a[u].apply(t[0],t[1])===!1&&e.stopOnFalse){n=!1;break}i=!1,a&&(f?f.length&&l(f.shift()):n?a=[]:c.disable())},c={add:function(){if(a){var t=a.length;(function r(t){v.each(t,function(t,n){var i=v.type(n);i==="function"?(!e.unique||!c.has(n))&&a.push(n):n&&n.length&&i!=="string"&&r(n)})})(arguments),i?o=a.length:n&&(s=t,l(n))}return this},remove:function(){return a&&v.each(arguments,function(e,t){var n;while((n=v.inArray(t,a,n))>-1)a.splice(n,1),i&&(n<=o&&o--,n<=u&&u--)}),this},has:function(e){return v.inArray(e,a)>-1},empty:function(){return a=[],this},disable:function(){return a=f=n=t,this},disabled:function(){return!a},lock:function(){return f=t,n||c.disable(),this},locked:function(){return!f},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],a&&(!r||f)&&(i?f.push(t):l(t)),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},v.extend({Deferred:function(e){var t=[["resolve","done",v.Callbacks("once memory"),"resolved"],["reject","fail",v.Callbacks("once memory"),"rejected"],["notify","progress",v.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return v.Deferred(function(n){v.each(t,function(t,r){var s=r[0],o=e[t];i[r[1]](v.isFunction(o)?function(){var e=o.apply(this,arguments);e&&v.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s+"With"](this===i?n:this,[e])}:n[s])}),e=null}).promise()},promise:function(e){return e!=null?v.extend(e,r):r}},i={};return r.pipe=r.then,v.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=o.fire,i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=l.call(arguments),r=n.length,i=r!==1||e&&v.isFunction(e.promise)?r:0,s=i===1?e:v.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?l.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&v.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}}),v.support=function(){var t,n,r,s,o,u,a,f,l,c,h,p=i.createElement("div");p.setAttribute("className","t"),p.innerHTML="  <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=p.getElementsByTagName("*"),r=p.getElementsByTagName("a")[0];if(!n||!r||!n.length)return{};s=i.createElement("select"),o=s.appendChild(i.createElement("option")),u=p.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={leadingWhitespace:p.firstChild.nodeType===3,tbody:!p.getElementsByTagName("tbody").length,htmlSerialize:!!p.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:r.getAttribute("href")==="/a",opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:u.value==="on",optSelected:o.selected,getSetAttribute:p.className!=="t",enctype:!!i.createElement("form").enctype,html5Clone:i.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",boxModel:i.compatMode==="CSS1Compat",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},u.checked=!0,t.noCloneChecked=u.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!o.disabled;try{delete p.test}catch(d){t.deleteExpando=!1}!p.addEventListener&&p.attachEvent&&p.fireEvent&&(p.attachEvent("onclick",h=function(){t.noCloneEvent=!1}),p.cloneNode(!0).fireEvent("onclick"),p.detachEvent("onclick",h)),u=i.createElement("input"),u.value="t",u.setAttribute("type","radio"),t.radioValue=u.value==="t",u.setAttribute("checked","checked"),u.setAttribute("name","t"),p.appendChild(u),a=i.createDocumentFragment(),a.appendChild(p.lastChild),t.checkClone=a.cloneNode(!0).cloneNode(!0).lastChild.checked,t.appendChecked=u.checked,a.removeChild(u),a.appendChild(p);if(p.attachEvent)for(l in{submit:!0,change:!0,focusin:!0})f="on"+l,c=f in p,c||(p.setAttribute(f,"return;"),c=typeof p[f]=="function"),t[l+"Bubbles"]=c;return v(function(){var n,r,s,o,u="padding:0;margin:0;border:0;display:block;overflow:hidden;",a=i.getElementsByTagName("body")[0];if(!a)return;n=i.createElement("div"),n.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px",a.insertBefore(n,a.firstChild),r=i.createElement("div"),n.appendChild(r),r.innerHTML="<table><tr><td></td><td>t</td></tr></table>",s=r.getElementsByTagName("td"),s[0].style.cssText="padding:0;margin:0;border:0;display:none",c=s[0].offsetHeight===0,s[0].style.display="",s[1].style.display="none",t.reliableHiddenOffsets=c&&s[0].offsetHeight===0,r.innerHTML="",r.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=r.offsetWidth===4,t.doesNotIncludeMarginInBodyOffset=a.offsetTop!==1,e.getComputedStyle&&(t.pixelPosition=(e.getComputedStyle(r,null)||{}).top!=="1%",t.boxSizingReliable=(e.getComputedStyle(r,null)||{width:"4px"}).width==="4px",o=i.createElement("div"),o.style.cssText=r.style.cssText=u,o.style.marginRight=o.style.width="0",r.style.width="1px",r.appendChild(o),t.reliableMarginRight=!parseFloat((e.getComputedStyle(o,null)||{}).marginRight)),typeof r.style.zoom!="undefined"&&(r.innerHTML="",r.style.cssText=u+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=r.offsetWidth===3,r.style.display="block",r.style.overflow="visible",r.innerHTML="<div></div>",r.firstChild.style.width="5px",t.shrinkWrapBlocks=r.offsetWidth!==3,n.style.zoom=1),a.removeChild(n),n=r=s=o=null}),a.removeChild(p),n=r=s=o=u=a=p=null,t}();var D=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;v.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(v.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?v.cache[e[v.expando]]:e[v.expando],!!e&&!B(e)},data:function(e,n,r,i){if(!v.acceptData(e))return;var s,o,u=v.expando,a=typeof n=="string",f=e.nodeType,l=f?v.cache:e,c=f?e[u]:e[u]&&u;if((!c||!l[c]||!i&&!l[c].data)&&a&&r===t)return;c||(f?e[u]=c=v.deletedIds.pop()||v.guid++:c=u),l[c]||(l[c]={},f||(l[c].toJSON=v.noop));if(typeof n=="object"||typeof n=="function")i?l[c]=v.extend(l[c],n):l[c].data=v.extend(l[c].data,n);return s=l[c],i||(s.data||(s.data={}),s=s.data),r!==t&&(s[v.camelCase(n)]=r),a?(o=s[n],o==null&&(o=s[v.camelCase(n)])):o=s,o},removeData:function(e,t,n){if(!v.acceptData(e))return;var r,i,s,o=e.nodeType,u=o?v.cache:e,a=o?e[v.expando]:v.expando;if(!u[a])return;if(t){r=n?u[a]:u[a].data;if(r){v.isArray(t)||(t in r?t=[t]:(t=v.camelCase(t),t in r?t=[t]:t=t.split(" ")));for(i=0,s=t.length;i<s;i++)delete r[t[i]];if(!(n?B:v.isEmptyObject)(r))return}}if(!n){delete u[a].data;if(!B(u[a]))return}o?v.cleanData([e],!0):v.support.deleteExpando||u!=u.window?delete u[a]:u[a]=null},_data:function(e,t,n){return v.data(e,t,n,!0)},acceptData:function(e){var t=e.nodeName&&v.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),v.fn.extend({data:function(e,n){var r,i,s,o,u,a=this[0],f=0,l=null;if(e===t){if(this.length){l=v.data(a);if(a.nodeType===1&&!v._data(a,"parsedAttrs")){s=a.attributes;for(u=s.length;f<u;f++)o=s[f].name,o.indexOf("data-")||(o=v.camelCase(o.substring(5)),H(a,o,l[o]));v._data(a,"parsedAttrs",!0)}}return l}return typeof e=="object"?this.each(function(){v.data(this,e)}):(r=e.split(".",2),r[1]=r[1]?"."+r[1]:"",i=r[1]+"!",v.access(this,function(n){if(n===t)return l=this.triggerHandler("getData"+i,[r[0]]),l===t&&a&&(l=v.data(a,e),l=H(a,e,l)),l===t&&r[1]?this.data(r[0]):l;r[1]=n,this.each(function(){var t=v(this);t.triggerHandler("setData"+i,r),v.data(this,e,n),t.triggerHandler("changeData"+i,r)})},null,n,arguments.length>1,null,!1))},removeData:function(e){return this.each(function(){v.removeData(this,e)})}}),v.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=v._data(e,t),n&&(!r||v.isArray(n)?r=v._data(e,t,v.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=v.queue(e,t),r=n.length,i=n.shift(),s=v._queueHooks(e,t),o=function(){v.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return v._data(e,n)||v._data(e,n,{empty:v.Callbacks("once memory").add(function(){v.removeData(e,t+"queue",!0),v.removeData(e,n,!0)})})}}),v.fn.extend({queue:function(e,n){var r=2;return typeof e!="string"&&(n=e,e="fx",r--),arguments.length<r?v.queue(this[0],e):n===t?this:this.each(function(){var t=v.queue(this,e,n);v._queueHooks(this,e),e==="fx"&&t[0]!=="inprogress"&&v.dequeue(this,e)})},dequeue:function(e){return this.each(function(){v.dequeue(this,e)})},delay:function(e,t){return e=v.fx?v.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,s=v.Deferred(),o=this,u=this.length,a=function(){--i||s.resolveWith(o,[o])};typeof e!="string"&&(n=e,e=t),e=e||"fx";while(u--)r=v._data(o[u],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(a));return a(),s.promise(n)}});var j,F,I,q=/[\t\r\n]/g,R=/\r/g,U=/^(?:button|input)$/i,z=/^(?:button|input|object|select|textarea)$/i,W=/^a(?:rea|)$/i,X=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,V=v.support.getSetAttribute;v.fn.extend({attr:function(e,t){return v.access(this,v.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){v.removeAttr(this,e)})},prop:function(e,t){return v.access(this,v.prop,e,t,arguments.length>1)},removeProp:function(e){return e=v.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,s,o,u;if(v.isFunction(e))return this.each(function(t){v(this).addClass(e.call(this,t,this.className))});if(e&&typeof e=="string"){t=e.split(y);for(n=0,r=this.length;n<r;n++){i=this[n];if(i.nodeType===1)if(!i.className&&t.length===1)i.className=e;else{s=" "+i.className+" ";for(o=0,u=t.length;o<u;o++)s.indexOf(" "+t[o]+" ")<0&&(s+=t[o]+" ");i.className=v.trim(s)}}}return this},removeClass:function(e){var n,r,i,s,o,u,a;if(v.isFunction(e))return this.each(function(t){v(this).removeClass(e.call(this,t,this.className))});if(e&&typeof e=="string"||e===t){n=(e||"").split(y);for(u=0,a=this.length;u<a;u++){i=this[u];if(i.nodeType===1&&i.className){r=(" "+i.className+" ").replace(q," ");for(s=0,o=n.length;s<o;s++)while(r.indexOf(" "+n[s]+" ")>=0)r=r.replace(" "+n[s]+" "," ");i.className=e?v.trim(r):""}}}return this},toggleClass:function(e,t){var n=typeof e,r=typeof t=="boolean";return v.isFunction(e)?this.each(function(n){v(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var i,s=0,o=v(this),u=t,a=e.split(y);while(i=a[s++])u=r?u:!o.hasClass(i),o[u?"addClass":"removeClass"](i)}else if(n==="undefined"||n==="boolean")this.className&&v._data(this,"__className__",this.className),this.className=this.className||e===!1?"":v._data(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(q," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,s=this[0];if(!arguments.length){if(s)return n=v.valHooks[s.type]||v.valHooks[s.nodeName.toLowerCase()],n&&"get"in n&&(r=n.get(s,"value"))!==t?r:(r=s.value,typeof r=="string"?r.replace(R,""):r==null?"":r);return}return i=v.isFunction(e),this.each(function(r){var s,o=v(this);if(this.nodeType!==1)return;i?s=e.call(this,r,o.val()):s=e,s==null?s="":typeof s=="number"?s+="":v.isArray(s)&&(s=v.map(s,function(e){return e==null?"":e+""})),n=v.valHooks[this.type]||v.valHooks[this.nodeName.toLowerCase()];if(!n||!("set"in n)||n.set(this,s,"value")===t)this.value=s})}}),v.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(v.support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!v.nodeName(n.parentNode,"optgroup"))){t=v(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n=v.makeArray(t);return v(e).find("option").each(function(){this.selected=v.inArray(v(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attrFn:{},attr:function(e,n,r,i){var s,o,u,a=e.nodeType;if(!e||a===3||a===8||a===2)return;if(i&&v.isFunction(v.fn[n]))return v(e)[n](r);if(typeof e.getAttribute=="undefined")return v.prop(e,n,r);u=a!==1||!v.isXMLDoc(e),u&&(n=n.toLowerCase(),o=v.attrHooks[n]||(X.test(n)?F:j));if(r!==t){if(r===null){v.removeAttr(e,n);return}return o&&"set"in o&&u&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r)}return o&&"get"in o&&u&&(s=o.get(e,n))!==null?s:(s=e.getAttribute(n),s===null?t:s)},removeAttr:function(e,t){var n,r,i,s,o=0;if(t&&e.nodeType===1){r=t.split(y);for(;o<r.length;o++)i=r[o],i&&(n=v.propFix[i]||i,s=X.test(i),s||v.attr(e,i,""),e.removeAttribute(V?i:n),s&&n in e&&(e[n]=!1))}},attrHooks:{type:{set:function(e,t){if(U.test(e.nodeName)&&e.parentNode)v.error("type property can't be changed");else if(!v.support.radioValue&&t==="radio"&&v.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}},value:{get:function(e,t){return j&&v.nodeName(e,"button")?j.get(e,t):t in e?e.value:null},set:function(e,t,n){if(j&&v.nodeName(e,"button"))return j.set(e,t,n);e.value=t}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,s,o,u=e.nodeType;if(!e||u===3||u===8||u===2)return;return o=u!==1||!v.isXMLDoc(e),o&&(n=v.propFix[n]||n,s=v.propHooks[n]),r!==t?s&&"set"in s&&(i=s.set(e,r,n))!==t?i:e[n]=r:s&&"get"in s&&(i=s.get(e,n))!==null?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):z.test(e.nodeName)||W.test(e.nodeName)&&e.href?0:t}}}}),F={get:function(e,n){var r,i=v.prop(e,n);return i===!0||typeof i!="boolean"&&(r=e.getAttributeNode(n))&&r.nodeValue!==!1?n.toLowerCase():t},set:function(e,t,n){var r;return t===!1?v.removeAttr(e,n):(r=v.propFix[n]||n,r in e&&(e[r]=!0),e.setAttribute(n,n.toLowerCase())),n}},V||(I={name:!0,id:!0,coords:!0},j=v.valHooks.button={get:function(e,n){var r;return r=e.getAttributeNode(n),r&&(I[n]?r.value!=="":r.specified)?r.value:t},set:function(e,t,n){var r=e.getAttributeNode(n);return r||(r=i.createAttribute(n),e.setAttributeNode(r)),r.value=t+""}},v.each(["width","height"],function(e,t){v.attrHooks[t]=v.extend(v.attrHooks[t],{set:function(e,n){if(n==="")return e.setAttribute(t,"auto"),n}})}),v.attrHooks.contenteditable={get:j.get,set:function(e,t,n){t===""&&(t="false"),j.set(e,t,n)}}),v.support.hrefNormalized||v.each(["href","src","width","height"],function(e,n){v.attrHooks[n]=v.extend(v.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return r===null?t:r}})}),v.support.style||(v.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||t},set:function(e,t){return e.style.cssText=t+""}}),v.support.optSelected||(v.propHooks.selected=v.extend(v.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),v.support.enctype||(v.propFix.enctype="encoding"),v.support.checkOn||v.each(["radio","checkbox"],function(){v.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}}),v.each(["radio","checkbox"],function(){v.valHooks[this]=v.extend(v.valHooks[this],{set:function(e,t){if(v.isArray(t))return e.checked=v.inArray(v(e).val(),t)>=0}})});var $=/^(?:textarea|input|select)$/i,J=/^([^\.]*|)(?:\.(.+)|)$/,K=/(?:^|\s)hover(\.\S+|)\b/,Q=/^key/,G=/^(?:mouse|contextmenu)|click/,Y=/^(?:focusinfocus|focusoutblur)$/,Z=function(e){return v.event.special.hover?e:e.replace(K,"mouseenter$1 mouseleave$1")};v.event={add:function(e,n,r,i,s){var o,u,a,f,l,c,h,p,d,m,g;if(e.nodeType===3||e.nodeType===8||!n||!r||!(o=v._data(e)))return;r.handler&&(d=r,r=d.handler,s=d.selector),r.guid||(r.guid=v.guid++),a=o.events,a||(o.events=a={}),u=o.handle,u||(o.handle=u=function(e){return typeof v=="undefined"||!!e&&v.event.triggered===e.type?t:v.event.dispatch.apply(u.elem,arguments)},u.elem=e),n=v.trim(Z(n)).split(" ");for(f=0;f<n.length;f++){l=J.exec(n[f])||[],c=l[1],h=(l[2]||"").split(".").sort(),g=v.event.special[c]||{},c=(s?g.delegateType:g.bindType)||c,g=v.event.special[c]||{},p=v.extend({type:c,origType:l[1],data:i,handler:r,guid:r.guid,selector:s,needsContext:s&&v.expr.match.needsContext.test(s),namespace:h.join(".")},d),m=a[c];if(!m){m=a[c]=[],m.delegateCount=0;if(!g.setup||g.setup.call(e,i,h,u)===!1)e.addEventListener?e.addEventListener(c,u,!1):e.attachEvent&&e.attachEvent("on"+c,u)}g.add&&(g.add.call(e,p),p.handler.guid||(p.handler.guid=r.guid)),s?m.splice(m.delegateCount++,0,p):m.push(p),v.event.global[c]=!0}e=null},global:{},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,m,g=v.hasData(e)&&v._data(e);if(!g||!(h=g.events))return;t=v.trim(Z(t||"")).split(" ");for(s=0;s<t.length;s++){o=J.exec(t[s])||[],u=a=o[1],f=o[2];if(!u){for(u in h)v.event.remove(e,u+t[s],n,r,!0);continue}p=v.event.special[u]||{},u=(r?p.delegateType:p.bindType)||u,d=h[u]||[],l=d.length,f=f?new RegExp("(^|\\.)"+f.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(c=0;c<d.length;c++)m=d[c],(i||a===m.origType)&&(!n||n.guid===m.guid)&&(!f||f.test(m.namespace))&&(!r||r===m.selector||r==="**"&&m.selector)&&(d.splice(c--,1),m.selector&&d.delegateCount--,p.remove&&p.remove.call(e,m));d.length===0&&l!==d.length&&((!p.teardown||p.teardown.call(e,f,g.handle)===!1)&&v.removeEvent(e,u,g.handle),delete h[u])}v.isEmptyObject(h)&&(delete g.handle,v.removeData(e,"events",!0))},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(n,r,s,o){if(!s||s.nodeType!==3&&s.nodeType!==8){var u,a,f,l,c,h,p,d,m,g,y=n.type||n,b=[];if(Y.test(y+v.event.triggered))return;y.indexOf("!")>=0&&(y=y.slice(0,-1),a=!0),y.indexOf(".")>=0&&(b=y.split("."),y=b.shift(),b.sort());if((!s||v.event.customEvent[y])&&!v.event.global[y])return;n=typeof n=="object"?n[v.expando]?n:new v.Event(y,n):new v.Event(y),n.type=y,n.isTrigger=!0,n.exclusive=a,n.namespace=b.join("."),n.namespace_re=n.namespace?new RegExp("(^|\\.)"+b.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,h=y.indexOf(":")<0?"on"+y:"";if(!s){u=v.cache;for(f in u)u[f].events&&u[f].events[y]&&v.event.trigger(n,r,u[f].handle.elem,!0);return}n.result=t,n.target||(n.target=s),r=r!=null?v.makeArray(r):[],r.unshift(n),p=v.event.special[y]||{};if(p.trigger&&p.trigger.apply(s,r)===!1)return;m=[[s,p.bindType||y]];if(!o&&!p.noBubble&&!v.isWindow(s)){g=p.delegateType||y,l=Y.test(g+y)?s:s.parentNode;for(c=s;l;l=l.parentNode)m.push([l,g]),c=l;c===(s.ownerDocument||i)&&m.push([c.defaultView||c.parentWindow||e,g])}for(f=0;f<m.length&&!n.isPropagationStopped();f++)l=m[f][0],n.type=m[f][1],d=(v._data(l,"events")||{})[n.type]&&v._data(l,"handle"),d&&d.apply(l,r),d=h&&l[h],d&&v.acceptData(l)&&d.apply&&d.apply(l,r)===!1&&n.preventDefault();return n.type=y,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(s.ownerDocument,r)===!1)&&(y!=="click"||!v.nodeName(s,"a"))&&v.acceptData(s)&&h&&s[y]&&(y!=="focus"&&y!=="blur"||n.target.offsetWidth!==0)&&!v.isWindow(s)&&(c=s[h],c&&(s[h]=null),v.event.triggered=y,s[y](),v.event.triggered=t,c&&(s[h]=c)),n.result}return},dispatch:function(n){n=v.event.fix(n||e.event);var r,i,s,o,u,a,f,c,h,p,d=(v._data(this,"events")||{})[n.type]||[],m=d.delegateCount,g=l.call(arguments),y=!n.exclusive&&!n.namespace,b=v.event.special[n.type]||{},w=[];g[0]=n,n.delegateTarget=this;if(b.preDispatch&&b.preDispatch.call(this,n)===!1)return;if(m&&(!n.button||n.type!=="click"))for(s=n.target;s!=this;s=s.parentNode||this)if(s.disabled!==!0||n.type!=="click"){u={},f=[];for(r=0;r<m;r++)c=d[r],h=c.selector,u[h]===t&&(u[h]=c.needsContext?v(h,this).index(s)>=0:v.find(h,this,null,[s]).length),u[h]&&f.push(c);f.length&&w.push({elem:s,matches:f})}d.length>m&&w.push({elem:this,matches:d.slice(m)});for(r=0;r<w.length&&!n.isPropagationStopped();r++){a=w[r],n.currentTarget=a.elem;for(i=0;i<a.matches.length&&!n.isImmediatePropagationStopped();i++){c=a.matches[i];if(y||!n.namespace&&!c.namespace||n.namespace_re&&n.namespace_re.test(c.namespace))n.data=c.data,n.handleObj=c,o=((v.event.special[c.origType]||{}).handle||c.handler).apply(a.elem,g),o!==t&&(n.result=o,o===!1&&(n.preventDefault(),n.stopPropagation()))}}return b.postDispatch&&b.postDispatch.call(this,n),n.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,s,o,u=n.button,a=n.fromElement;return e.pageX==null&&n.clientX!=null&&(r=e.target.ownerDocument||i,s=r.documentElement,o=r.body,e.pageX=n.clientX+(s&&s.scrollLeft||o&&o.scrollLeft||0)-(s&&s.clientLeft||o&&o.clientLeft||0),e.pageY=n.clientY+(s&&s.scrollTop||o&&o.scrollTop||0)-(s&&s.clientTop||o&&o.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?n.toElement:a),!e.which&&u!==t&&(e.which=u&1?1:u&2?3:u&4?2:0),e}},fix:function(e){if(e[v.expando])return e;var t,n,r=e,s=v.event.fixHooks[e.type]||{},o=s.props?this.props.concat(s.props):this.props;e=v.Event(r);for(t=o.length;t;)n=o[--t],e[n]=r[n];return e.target||(e.target=r.srcElement||i),e.target.nodeType===3&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,r):e},special:{load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(e,t,n){v.isWindow(this)&&(this.onbeforeunload=n)},teardown:function(e,t){this.onbeforeunload===t&&(this.onbeforeunload=null)}}},simulate:function(e,t,n,r){var i=v.extend(new v.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?v.event.trigger(i,null,t):v.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},v.event.handle=v.event.dispatch,v.removeEvent=i.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]=="undefined"&&(e[r]=null),e.detachEvent(r,n))},v.Event=function(e,t){if(!(this instanceof v.Event))return new v.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?tt:et):this.type=e,t&&v.extend(this,t),this.timeStamp=e&&e.timeStamp||v.now(),this[v.expando]=!0},v.Event.prototype={preventDefault:function(){this.isDefaultPrevented=tt;var e=this.originalEvent;if(!e)return;e.preventDefault?e.preventDefault():e.returnValue=!1},stopPropagation:function(){this.isPropagationStopped=tt;var e=this.originalEvent;if(!e)return;e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=tt,this.stopPropagation()},isDefaultPrevented:et,isPropagationStopped:et,isImmediatePropagationStopped:et},v.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){v.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj,o=s.selector;if(!i||i!==r&&!v.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),v.support.submitBubbles||(v.event.special.submit={setup:function(){if(v.nodeName(this,"form"))return!1;v.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=v.nodeName(n,"input")||v.nodeName(n,"button")?n.form:t;r&&!v._data(r,"_submit_attached")&&(v.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),v._data(r,"_submit_attached",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&v.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){if(v.nodeName(this,"form"))return!1;v.event.remove(this,"._submit")}}),v.support.changeBubbles||(v.event.special.change={setup:function(){if($.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")v.event.add(this,"propertychange._change",function(e){e.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),v.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),v.event.simulate("change",this,e,!0)});return!1}v.event.add(this,"beforeactivate._change",function(e){var t=e.target;$.test(t.nodeName)&&!v._data(t,"_change_attached")&&(v.event.add(t,"change._change",function(e){this.parentNode&&!e.isSimulated&&!e.isTrigger&&v.event.simulate("change",this.parentNode,e,!0)}),v._data(t,"_change_attached",!0))})},handle:function(e){var t=e.target;if(this!==t||e.isSimulated||e.isTrigger||t.type!=="radio"&&t.type!=="checkbox")return e.handleObj.handler.apply(this,arguments)},teardown:function(){return v.event.remove(this,"._change"),!$.test(this.nodeName)}}),v.support.focusinBubbles||v.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){v.event.simulate(t,e.target,v.event.fix(e),!0)};v.event.special[t]={setup:function(){n++===0&&i.addEventListener(e,r,!0)},teardown:function(){--n===0&&i.removeEventListener(e,r,!0)}}}),v.fn.extend({on:function(e,n,r,i,s){var o,u;if(typeof e=="object"){typeof n!="string"&&(r=r||n,n=t);for(u in e)this.on(u,n,r,e[u],s);return this}r==null&&i==null?(i=n,r=n=t):i==null&&(typeof n=="string"?(i=r,r=t):(i=r,r=n,n=t));if(i===!1)i=et;else if(!i)return this;return s===1&&(o=i,i=function(e){return v().off(e),o.apply(this,arguments)},i.guid=o.guid||(o.guid=v.guid++)),this.each(function(){v.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,s;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,v(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if(typeof e=="object"){for(s in e)this.off(s,n,e[s]);return this}if(n===!1||typeof n=="function")r=n,n=t;return r===!1&&(r=et),this.each(function(){v.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},live:function(e,t,n){return v(this.context).on(e,this.selector,t,n),this},die:function(e,t){return v(this.context).off(e,this.selector||"**",t),this},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){v.event.trigger(e,t,this)})},triggerHandler:function(e,t){if(this[0])return v.event.trigger(e,t,this[0],!0)},toggle:function(e){var t=arguments,n=e.guid||v.guid++,r=0,i=function(n){var i=(v._data(this,"lastToggle"+e.guid)||0)%r;return v._data(this,"lastToggle"+e.guid,i+1),n.preventDefault(),t[i].apply(this,arguments)||!1};i.guid=n;while(r<t.length)t[r++].guid=n;return this.click(i)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),v.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){v.fn[t]=function(e,n){return n==null&&(n=e,e=null),arguments.length>0?this.on(t,null,e,n):this.trigger(t)},Q.test(t)&&(v.event.fixHooks[t]=v.event.keyHooks),G.test(t)&&(v.event.fixHooks[t]=v.event.mouseHooks)}),function(e,t){function nt(e,t,n,r){n=n||[],t=t||g;var i,s,a,f,l=t.nodeType;if(!e||typeof e!="string")return n;if(l!==1&&l!==9)return[];a=o(t);if(!a&&!r)if(i=R.exec(e))if(f=i[1]){if(l===9){s=t.getElementById(f);if(!s||!s.parentNode)return n;if(s.id===f)return n.push(s),n}else if(t.ownerDocument&&(s=t.ownerDocument.getElementById(f))&&u(t,s)&&s.id===f)return n.push(s),n}else{if(i[2])return S.apply(n,x.call(t.getElementsByTagName(e),0)),n;if((f=i[3])&&Z&&t.getElementsByClassName)return S.apply(n,x.call(t.getElementsByClassName(f),0)),n}return vt(e.replace(j,"$1"),t,n,r,a)}function rt(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function it(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function st(e){return N(function(t){return t=+t,N(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ot(e,t,n){if(e===t)return n;var r=e.nextSibling;while(r){if(r===t)return-1;r=r.nextSibling}return 1}function ut(e,t){var n,r,s,o,u,a,f,l=L[d][e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=i.preFilter;while(u){if(!n||(r=F.exec(u)))r&&(u=u.slice(r[0].length)||u),a.push(s=[]);n=!1;if(r=I.exec(u))s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=r[0].replace(j," ");for(o in i.filter)(r=J[o].exec(u))&&(!f[o]||(r=f[o](r)))&&(s.push(n=new m(r.shift())),u=u.slice(n.length),n.type=o,n.matches=r);if(!n)break}return t?u.length:u?nt.error(e):L(e,a).slice(0)}function at(e,t,r){var i=t.dir,s=r&&t.dir==="parentNode",o=w++;return t.first?function(t,n,r){while(t=t[i])if(s||t.nodeType===1)return e(t,n,r)}:function(t,r,u){if(!u){var a,f=b+" "+o+" ",l=f+n;while(t=t[i])if(s||t.nodeType===1){if((a=t[d])===l)return t.sizset;if(typeof a=="string"&&a.indexOf(f)===0){if(t.sizset)return t}else{t[d]=l;if(e(t,r,u))return t.sizset=!0,t;t.sizset=!1}}}else while(t=t[i])if(s||t.nodeType===1)if(e(t,r,u))return t}}function ft(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function lt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function ct(e,t,n,r,i,s){return r&&!r[d]&&(r=ct(r)),i&&!i[d]&&(i=ct(i,s)),N(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||dt(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?lt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=lt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?T.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=lt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):S.apply(o,g)})}function ht(e){var t,n,r,s=e.length,o=i.relative[e[0].type],u=o||i.relative[" "],a=o?1:0,f=at(function(e){return e===t},u,!0),l=at(function(e){return T.call(t,e)>-1},u,!0),h=[function(e,n,r){return!o&&(r||n!==c)||((t=n).nodeType?f(e,n,r):l(e,n,r))}];for(;a<s;a++)if(n=i.relative[e[a].type])h=[at(ft(h),n)];else{n=i.filter[e[a].type].apply(null,e[a].matches);if(n[d]){r=++a;for(;r<s;r++)if(i.relative[e[r].type])break;return ct(a>1&&ft(h),a>1&&e.slice(0,a-1).join("").replace(j,"$1"),n,a<r&&ht(e.slice(a,r)),r<s&&ht(e=e.slice(r)),r<s&&e.join(""))}h.push(n)}return ft(h)}function pt(e,t){var r=t.length>0,s=e.length>0,o=function(u,a,f,l,h){var p,d,v,m=[],y=0,w="0",x=u&&[],T=h!=null,N=c,C=u||s&&i.find.TAG("*",h&&a.parentNode||a),k=b+=N==null?1:Math.E;T&&(c=a!==g&&a,n=o.el);for(;(p=C[w])!=null;w++){if(s&&p){for(d=0;v=e[d];d++)if(v(p,a,f)){l.push(p);break}T&&(b=k,n=++o.el)}r&&((p=!v&&p)&&y--,u&&x.push(p))}y+=w;if(r&&w!==y){for(d=0;v=t[d];d++)v(x,m,a,f);if(u){if(y>0)while(w--)!x[w]&&!m[w]&&(m[w]=E.call(l));m=lt(m)}S.apply(l,m),T&&!u&&m.length>0&&y+t.length>1&&nt.uniqueSort(l)}return T&&(b=k,c=N),x};return o.el=0,r?N(o):o}function dt(e,t,n){var r=0,i=t.length;for(;r<i;r++)nt(e,t[r],n);return n}function vt(e,t,n,r,s){var o,u,f,l,c,h=ut(e),p=h.length;if(!r&&h.length===1){u=h[0]=h[0].slice(0);if(u.length>2&&(f=u[0]).type==="ID"&&t.nodeType===9&&!s&&i.relative[u[1].type]){t=i.find.ID(f.matches[0].replace($,""),t,s)[0];if(!t)return n;e=e.slice(u.shift().length)}for(o=J.POS.test(e)?-1:u.length-1;o>=0;o--){f=u[o];if(i.relative[l=f.type])break;if(c=i.find[l])if(r=c(f.matches[0].replace($,""),z.test(u[0].type)&&t.parentNode||t,s)){u.splice(o,1),e=r.length&&u.join("");if(!e)return S.apply(n,x.call(r,0)),n;break}}}return a(e,h)(r,t,s,n,z.test(e)),n}function mt(){}var n,r,i,s,o,u,a,f,l,c,h=!0,p="undefined",d=("sizcache"+Math.random()).replace(".",""),m=String,g=e.document,y=g.documentElement,b=0,w=0,E=[].pop,S=[].push,x=[].slice,T=[].indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},N=function(e,t){return e[d]=t==null||t,e},C=function(){var e={},t=[];return N(function(n,r){return t.push(n)>i.cacheLength&&delete e[t.shift()],e[n+" "]=r},e)},k=C(),L=C(),A=C(),O="[\\x20\\t\\r\\n\\f]",M="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",_=M.replace("w","w#"),D="([*^$|!~]?=)",P="\\["+O+"*("+M+")"+O+"*(?:"+D+O+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+_+")|)|)"+O+"*\\]",H=":("+M+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+P+")|[^:]|\\\\.)*|.*))\\)|)",B=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+O+"*((?:-\\d)?\\d*)"+O+"*\\)|)(?=[^-]|$)",j=new RegExp("^"+O+"+|((?:^|[^\\\\])(?:\\\\.)*)"+O+"+$","g"),F=new RegExp("^"+O+"*,"+O+"*"),I=new RegExp("^"+O+"*([\\x20\\t\\r\\n\\f>+~])"+O+"*"),q=new RegExp(H),R=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,U=/^:not/,z=/[\x20\t\r\n\f]*[+~]/,W=/:not\($/,X=/h\d/i,V=/input|select|textarea|button/i,$=/\\(?!\\)/g,J={ID:new RegExp("^#("+M+")"),CLASS:new RegExp("^\\.("+M+")"),NAME:new RegExp("^\\[name=['\"]?("+M+")['\"]?\\]"),TAG:new RegExp("^("+M.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+H),POS:new RegExp(B,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+O+"*(even|odd|(([+-]|)(\\d*)n|)"+O+"*(?:([+-]|)"+O+"*(\\d+)|))"+O+"*\\)|)","i"),needsContext:new RegExp("^"+O+"*[>+~]|"+B,"i")},K=function(e){var t=g.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}},Q=K(function(e){return e.appendChild(g.createComment("")),!e.getElementsByTagName("*").length}),G=K(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==p&&e.firstChild.getAttribute("href")==="#"}),Y=K(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return t!=="boolean"&&t!=="string"}),Z=K(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!e.getElementsByClassName||!e.getElementsByClassName("e").length?!1:(e.lastChild.className="e",e.getElementsByClassName("e").length===2)}),et=K(function(e){e.id=d+0,e.innerHTML="<a name='"+d+"'></a><div name='"+d+"'></div>",y.insertBefore(e,y.firstChild);var t=g.getElementsByName&&g.getElementsByName(d).length===2+g.getElementsByName(d+0).length;return r=!g.getElementById(d),y.removeChild(e),t});try{x.call(y.childNodes,0)[0].nodeType}catch(tt){x=function(e){var t,n=[];for(;t=this[e];e++)n.push(t);return n}}nt.matches=function(e,t){return nt(e,null,null,t)},nt.matchesSelector=function(e,t){return nt(t,null,null,[e]).length>0},s=nt.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(i===1||i===9||i===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=s(e)}else if(i===3||i===4)return e.nodeValue}else for(;t=e[r];r++)n+=s(t);return n},o=nt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},u=nt.contains=y.contains?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!(r&&r.nodeType===1&&n.contains&&n.contains(r))}:y.compareDocumentPosition?function(e,t){return t&&!!(e.compareDocumentPosition(t)&16)}:function(e,t){while(t=t.parentNode)if(t===e)return!0;return!1},nt.attr=function(e,t){var n,r=o(e);return r||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):r||Y?e.getAttribute(t):(n=e.getAttributeNode(t),n?typeof e[t]=="boolean"?e[t]?t:null:n.specified?n.value:null:null)},i=nt.selectors={cacheLength:50,createPseudo:N,match:J,attrHandle:G?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:r?function(e,t,n){if(typeof t.getElementById!==p&&!n){var r=t.getElementById(e);return r&&r.parentNode?[r]:[]}}:function(e,n,r){if(typeof n.getElementById!==p&&!r){var i=n.getElementById(e);return i?i.id===e||typeof i.getAttributeNode!==p&&i.getAttributeNode("id").value===e?[i]:t:[]}},TAG:Q?function(e,t){if(typeof t.getElementsByTagName!==p)return t.getElementsByTagName(e)}:function(e,t){var n=t.getElementsByTagName(e);if(e==="*"){var r,i=[],s=0;for(;r=n[s];s++)r.nodeType===1&&i.push(r);return i}return n},NAME:et&&function(e,t){if(typeof t.getElementsByName!==p)return t.getElementsByName(name)},CLASS:Z&&function(e,t,n){if(typeof t.getElementsByClassName!==p&&!n)return t.getElementsByClassName(e)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace($,""),e[3]=(e[4]||e[5]||"").replace($,""),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1]==="nth"?(e[2]||nt.error(e[0]),e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd")),e[4]=+(e[6]+e[7]||e[2]==="odd")):e[2]&&nt.error(e[0]),e},PSEUDO:function(e){var t,n;if(J.CHILD.test(e[0]))return null;if(e[3])e[2]=e[3];else if(t=e[4])q.test(t)&&(n=ut(t,!0))&&(n=t.indexOf(")",t.length-n)-t.length)&&(t=t.slice(0,n),e[0]=e[0].slice(0,n)),e[2]=t;return e.slice(0,3)}},filter:{ID:r?function(e){return e=e.replace($,""),function(t){return t.getAttribute("id")===e}}:function(e){return e=e.replace($,""),function(t){var n=typeof t.getAttributeNode!==p&&t.getAttributeNode("id");return n&&n.value===e}},TAG:function(e){return e==="*"?function(){return!0}:(e=e.replace($,"").toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[d][e+" "];return t||(t=new RegExp("(^|"+O+")"+e+"("+O+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==p&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r,i){var s=nt.attr(r,e);return s==null?t==="!=":t?(s+="",t==="="?s===n:t==="!="?s!==n:t==="^="?n&&s.indexOf(n)===0:t==="*="?n&&s.indexOf(n)>-1:t==="$="?n&&s.substr(s.length-n.length)===n:t==="~="?(" "+s+" ").indexOf(n)>-1:t==="|="?s===n||s.substr(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r){return e==="nth"?function(e){var t,i,s=e.parentNode;if(n===1&&r===0)return!0;if(s){i=0;for(t=s.firstChild;t;t=t.nextSibling)if(t.nodeType===1){i++;if(e===t)break}}return i-=r,i===n||i%n===0&&i/n>=0}:function(t){var n=t;switch(e){case"only":case"first":while(n=n.previousSibling)if(n.nodeType===1)return!1;if(e==="first")return!0;n=t;case"last":while(n=n.nextSibling)if(n.nodeType===1)return!1;return!0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||nt.error("unsupported pseudo: "+e);return r[d]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?N(function(e,n){var i,s=r(e,t),o=s.length;while(o--)i=T.call(e,s[o]),e[i]=!(n[i]=s[o])}):function(e){return r(e,0,n)}):r}},pseudos:{not:N(function(e){var t=[],n=[],r=a(e.replace(j,"$1"));return r[d]?N(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:N(function(e){return function(t){return nt(e,t).length>0}}),contains:N(function(e){return function(t){return(t.textContent||t.innerText||s(t)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},parent:function(e){return!i.pseudos.empty(e)},empty:function(e){var t;e=e.firstChild;while(e){if(e.nodeName>"@"||(t=e.nodeType)===3||t===4)return!1;e=e.nextSibling}return!0},header:function(e){return X.test(e.nodeName)},text:function(e){var t,n;return e.nodeName.toLowerCase()==="input"&&(t=e.type)==="text"&&((n=e.getAttribute("type"))==null||n.toLowerCase()===t)},radio:rt("radio"),checkbox:rt("checkbox"),file:rt("file"),password:rt("password"),image:rt("image"),submit:it("submit"),reset:it("reset"),button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},input:function(e){return V.test(e.nodeName)},focus:function(e){var t=e.ownerDocument;return e===t.activeElement&&(!t.hasFocus||t.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:st(function(){return[0]}),last:st(function(e,t){return[t-1]}),eq:st(function(e,t,n){return[n<0?n+t:n]}),even:st(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:st(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:st(function(e,t,n){for(var r=n<0?n+t:n;--r>=0;)e.push(r);return e}),gt:st(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}},f=y.compareDocumentPosition?function(e,t){return e===t?(l=!0,0):(!e.compareDocumentPosition||!t.compareDocumentPosition?e.compareDocumentPosition:e.compareDocumentPosition(t)&4)?-1:1}:function(e,t){if(e===t)return l=!0,0;if(e.sourceIndex&&t.sourceIndex)return e.sourceIndex-t.sourceIndex;var n,r,i=[],s=[],o=e.parentNode,u=t.parentNode,a=o;if(o===u)return ot(e,t);if(!o)return-1;if(!u)return 1;while(a)i.unshift(a),a=a.parentNode;a=u;while(a)s.unshift(a),a=a.parentNode;n=i.length,r=s.length;for(var f=0;f<n&&f<r;f++)if(i[f]!==s[f])return ot(i[f],s[f]);return f===n?ot(e,s[f],-1):ot(i[f],t,1)},[0,0].sort(f),h=!l,nt.uniqueSort=function(e){var t,n=[],r=1,i=0;l=h,e.sort(f);if(l){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e},nt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},a=nt.compile=function(e,t){var n,r=[],i=[],s=A[d][e+" "];if(!s){t||(t=ut(e)),n=t.length;while(n--)s=ht(t[n]),s[d]?r.push(s):i.push(s);s=A(e,pt(i,r))}return s},g.querySelectorAll&&function(){var e,t=vt,n=/'|\\/g,r=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,i=[":focus"],s=[":active"],u=y.matchesSelector||y.mozMatchesSelector||y.webkitMatchesSelector||y.oMatchesSelector||y.msMatchesSelector;K(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||i.push("\\["+O+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||i.push(":checked")}),K(function(e){e.innerHTML="<p test=''></p>",e.querySelectorAll("[test^='']").length&&i.push("[*^$]="+O+"*(?:\"\"|'')"),e.innerHTML="<input type='hidden'/>",e.querySelectorAll(":enabled").length||i.push(":enabled",":disabled")}),i=new RegExp(i.join("|")),vt=function(e,r,s,o,u){if(!o&&!u&&!i.test(e)){var a,f,l=!0,c=d,h=r,p=r.nodeType===9&&e;if(r.nodeType===1&&r.nodeName.toLowerCase()!=="object"){a=ut(e),(l=r.getAttribute("id"))?c=l.replace(n,"\\$&"):r.setAttribute("id",c),c="[id='"+c+"'] ",f=a.length;while(f--)a[f]=c+a[f].join("");h=z.test(e)&&r.parentNode||r,p=a.join(",")}if(p)try{return S.apply(s,x.call(h.querySelectorAll(p),0)),s}catch(v){}finally{l||r.removeAttribute("id")}}return t(e,r,s,o,u)},u&&(K(function(t){e=u.call(t,"div");try{u.call(t,"[test!='']:sizzle"),s.push("!=",H)}catch(n){}}),s=new RegExp(s.join("|")),nt.matchesSelector=function(t,n){n=n.replace(r,"='$1']");if(!o(t)&&!s.test(n)&&!i.test(n))try{var a=u.call(t,n);if(a||e||t.document&&t.document.nodeType!==11)return a}catch(f){}return nt(n,null,null,[t]).length>0})}(),i.pseudos.nth=i.pseudos.eq,i.filters=mt.prototype=i.pseudos,i.setFilters=new mt,nt.attr=v.attr,v.find=nt,v.expr=nt.selectors,v.expr[":"]=v.expr.pseudos,v.unique=nt.uniqueSort,v.text=nt.getText,v.isXMLDoc=nt.isXML,v.contains=nt.contains}(e);var nt=/Until$/,rt=/^(?:parents|prev(?:Until|All))/,it=/^.[^:#\[\.,]*$/,st=v.expr.match.needsContext,ot={children:!0,contents:!0,next:!0,prev:!0};v.fn.extend({find:function(e){var t,n,r,i,s,o,u=this;if(typeof e!="string")return v(e).filter(function(){for(t=0,n=u.length;t<n;t++)if(v.contains(u[t],this))return!0});o=this.pushStack("","find",e);for(t=0,n=this.length;t<n;t++){r=o.length,v.find(e,this[t],o);if(t>0)for(i=r;i<o.length;i++)for(s=0;s<r;s++)if(o[s]===o[i]){o.splice(i--,1);break}}return o},has:function(e){var t,n=v(e,this),r=n.length;return this.filter(function(){for(t=0;t<r;t++)if(v.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1),"not",e)},filter:function(e){return this.pushStack(ft(this,e,!0),"filter",e)},is:function(e){return!!e&&(typeof e=="string"?st.test(e)?v(e,this.context).index(this[0])>=0:v.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,s=[],o=st.test(e)||typeof e!="string"?v(e,t||this.context):0;for(;r<i;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&n.nodeType!==11){if(o?o.index(n)>-1:v.find.matchesSelector(n,e)){s.push(n);break}n=n.parentNode}}return s=s.length>1?v.unique(s):s,this.pushStack(s,"closest",e)},index:function(e){return e?typeof e=="string"?v.inArray(this[0],v(e)):v.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.prevAll().length:-1},add:function(e,t){var n=typeof e=="string"?v(e,t):v.makeArray(e&&e.nodeType?[e]:e),r=v.merge(this.get(),n);return this.pushStack(ut(n[0])||ut(r[0])?r:v.unique(r))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),v.fn.andSelf=v.fn.addBack,v.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return v.dir(e,"parentNode")},parentsUntil:function(e,t,n){return v.dir(e,"parentNode",n)},next:function(e){return at(e,"nextSibling")},prev:function(e){return at(e,"previousSibling")},nextAll:function(e){return v.dir(e,"nextSibling")},prevAll:function(e){return v.dir(e,"previousSibling")},nextUntil:function(e,t,n){return v.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return v.dir(e,"previousSibling",n)},siblings:function(e){return v.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return v.sibling(e.firstChild)},contents:function(e){return v.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:v.merge([],e.childNodes)}},function(e,t){v.fn[e]=function(n,r){var i=v.map(this,t,n);return nt.test(e)||(r=n),r&&typeof r=="string"&&(i=v.filter(r,i)),i=this.length>1&&!ot[e]?v.unique(i):i,this.length>1&&rt.test(e)&&(i=i.reverse()),this.pushStack(i,e,l.call(arguments).join(","))}}),v.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),t.length===1?v.find.matchesSelector(t[0],e)?[t[0]]:[]:v.find.matches(e,t)},dir:function(e,n,r){var i=[],s=e[n];while(s&&s.nodeType!==9&&(r===t||s.nodeType!==1||!v(s).is(r)))s.nodeType===1&&i.push(s),s=s[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}});var ct="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",ht=/ jQuery\d+="(?:null|\d+)"/g,pt=/^\s+/,dt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,vt=/<([\w:]+)/,mt=/<tbody/i,gt=/<|&#?\w+;/,yt=/<(?:script|style|link)/i,bt=/<(?:script|object|embed|option|style)/i,wt=new RegExp("<(?:"+ct+")[\\s/>]","i"),Et=/^(?:checkbox|radio)$/,St=/checked\s*(?:[^=]|=\s*.checked.)/i,xt=/\/(java|ecma)script/i,Tt=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,Nt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},Ct=lt(i),kt=Ct.appendChild(i.createElement("div"));Nt.optgroup=Nt.option,Nt.tbody=Nt.tfoot=Nt.colgroup=Nt.caption=Nt.thead,Nt.th=Nt.td,v.support.htmlSerialize||(Nt._default=[1,"X<div>","</div>"]),v.fn.extend({text:function(e){return v.access(this,function(e){return e===t?v.text(this):this.empty().append((this[0]&&this[0].ownerDocument||i).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(v.isFunction(e))return this.each(function(t){v(this).wrapAll(e.call(this,t))});if(this[0]){var t=v(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&e.firstChild.nodeType===1)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return v.isFunction(e)?this.each(function(t){v(this).wrapInner(e.call(this,t))}):this.each(function(){var t=v(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=v.isFunction(e);return this.each(function(n){v(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){v.nodeName(this,"body")||v(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(this.nodeType===1||this.nodeType===11)&&this.insertBefore(e,this.firstChild)})},before:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(e,this),"before",this.selector)}},after:function(){if(!ut(this[0]))return this.domManip(arguments,!1,function(e){this.parentNode.insertBefore(e,this.nextSibling)});if(arguments.length){var e=v.clean(arguments);return this.pushStack(v.merge(this,e),"after",this.selector)}},remove:function(e,t){var n,r=0;for(;(n=this[r])!=null;r++)if(!e||v.filter(e,[n]).length)!t&&n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),v.cleanData([n])),n.parentNode&&n.parentNode.removeChild(n);return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++){e.nodeType===1&&v.cleanData(e.getElementsByTagName("*"));while(e.firstChild)e.removeChild(e.firstChild)}return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return v.clone(this,e,t)})},html:function(e){return v.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return n.nodeType===1?n.innerHTML.replace(ht,""):t;if(typeof e=="string"&&!yt.test(e)&&(v.support.htmlSerialize||!wt.test(e))&&(v.support.leadingWhitespace||!pt.test(e))&&!Nt[(vt.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(dt,"<$1></$2>");try{for(;r<i;r++)n=this[r]||{},n.nodeType===1&&(v.cleanData(n.getElementsByTagName("*")),n.innerHTML=e);n=0}catch(s){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){return ut(this[0])?this.length?this.pushStack(v(v.isFunction(e)?e():e),"replaceWith",e):this:v.isFunction(e)?this.each(function(t){var n=v(this),r=n.html();n.replaceWith(e.call(this,t,r))}):(typeof e!="string"&&(e=v(e).detach()),this.each(function(){var t=this.nextSibling,n=this.parentNode;v(this).remove(),t?v(t).before(e):v(n).append(e)}))},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=[].concat.apply([],e);var i,s,o,u,a=0,f=e[0],l=[],c=this.length;if(!v.support.checkClone&&c>1&&typeof f=="string"&&St.test(f))return this.each(function(){v(this).domManip(e,n,r)});if(v.isFunction(f))return this.each(function(i){var s=v(this);e[0]=f.call(this,i,n?s.html():t),s.domManip(e,n,r)});if(this[0]){i=v.buildFragment(e,this,l),o=i.fragment,s=o.firstChild,o.childNodes.length===1&&(o=s);if(s){n=n&&v.nodeName(s,"tr");for(u=i.cacheable||c-1;a<c;a++)r.call(n&&v.nodeName(this[a],"table")?Lt(this[a],"tbody"):this[a],a===u?o:v.clone(o,!0,!0))}o=s=null,l.length&&v.each(l,function(e,t){t.src?v.ajax?v.ajax({url:t.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):v.error("no ajax"):v.globalEval((t.text||t.textContent||t.innerHTML||"").replace(Tt,"")),t.parentNode&&t.parentNode.removeChild(t)})}return this}}),v.buildFragment=function(e,n,r){var s,o,u,a=e[0];return n=n||i,n=!n.nodeType&&n[0]||n,n=n.ownerDocument||n,e.length===1&&typeof a=="string"&&a.length<512&&n===i&&a.charAt(0)==="<"&&!bt.test(a)&&(v.support.checkClone||!St.test(a))&&(v.support.html5Clone||!wt.test(a))&&(o=!0,s=v.fragments[a],u=s!==t),s||(s=n.createDocumentFragment(),v.clean(e,n,s,r),o&&(v.fragments[a]=u&&s)),{fragment:s,cacheable:o}},v.fragments={},v.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){v.fn[e]=function(n){var r,i=0,s=[],o=v(n),u=o.length,a=this.length===1&&this[0].parentNode;if((a==null||a&&a.nodeType===11&&a.childNodes.length===1)&&u===1)return o[t](this[0]),this;for(;i<u;i++)r=(i>0?this.clone(!0):this).get(),v(o[i])[t](r),s=s.concat(r);return this.pushStack(s,e,o.selector)}}),v.extend({clone:function(e,t,n){var r,i,s,o;v.support.html5Clone||v.isXMLDoc(e)||!wt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(kt.innerHTML=e.outerHTML,kt.removeChild(o=kt.firstChild));if((!v.support.noCloneEvent||!v.support.noCloneChecked)&&(e.nodeType===1||e.nodeType===11)&&!v.isXMLDoc(e)){Ot(e,o),r=Mt(e),i=Mt(o);for(s=0;r[s];++s)i[s]&&Ot(r[s],i[s])}if(t){At(e,o);if(n){r=Mt(e),i=Mt(o);for(s=0;r[s];++s)At(r[s],i[s])}}return r=i=null,o},clean:function(e,t,n,r){var s,o,u,a,f,l,c,h,p,d,m,g,y=t===i&&Ct,b=[];if(!t||typeof t.createDocumentFragment=="undefined")t=i;for(s=0;(u=e[s])!=null;s++){typeof u=="number"&&(u+="");if(!u)continue;if(typeof u=="string")if(!gt.test(u))u=t.createTextNode(u);else{y=y||lt(t),c=t.createElement("div"),y.appendChild(c),u=u.replace(dt,"<$1></$2>"),a=(vt.exec(u)||["",""])[1].toLowerCase(),f=Nt[a]||Nt._default,l=f[0],c.innerHTML=f[1]+u+f[2];while(l--)c=c.lastChild;if(!v.support.tbody){h=mt.test(u),p=a==="table"&&!h?c.firstChild&&c.firstChild.childNodes:f[1]==="<table>"&&!h?c.childNodes:[];for(o=p.length-1;o>=0;--o)v.nodeName(p[o],"tbody")&&!p[o].childNodes.length&&p[o].parentNode.removeChild(p[o])}!v.support.leadingWhitespace&&pt.test(u)&&c.insertBefore(t.createTextNode(pt.exec(u)[0]),c.firstChild),u=c.childNodes,c.parentNode.removeChild(c)}u.nodeType?b.push(u):v.merge(b,u)}c&&(u=c=y=null);if(!v.support.appendChecked)for(s=0;(u=b[s])!=null;s++)v.nodeName(u,"input")?_t(u):typeof u.getElementsByTagName!="undefined"&&v.grep(u.getElementsByTagName("input"),_t);if(n){m=function(e){if(!e.type||xt.test(e.type))return r?r.push(e.parentNode?e.parentNode.removeChild(e):e):n.appendChild(e)};for(s=0;(u=b[s])!=null;s++)if(!v.nodeName(u,"script")||!m(u))n.appendChild(u),typeof u.getElementsByTagName!="undefined"&&(g=v.grep(v.merge([],u.getElementsByTagName("script")),m),b.splice.apply(b,[s+1,0].concat(g)),s+=g.length)}return b},cleanData:function(e,t){var n,r,i,s,o=0,u=v.expando,a=v.cache,f=v.support.deleteExpando,l=v.event.special;for(;(i=e[o])!=null;o++)if(t||v.acceptData(i)){r=i[u],n=r&&a[r];if(n){if(n.events)for(s in n.events)l[s]?v.event.remove(i,s):v.removeEvent(i,s,n.handle);a[r]&&(delete a[r],f?delete i[u]:i.removeAttribute?i.removeAttribute(u):i[u]=null,v.deletedIds.push(r))}}}}),function(){var e,t;v.uaMatch=function(e){e=e.toLowerCase();var t=/(chrome)[ \/]([\w.]+)/.exec(e)||/(webkit)[ \/]([\w.]+)/.exec(e)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(e)||/(msie) ([\w.]+)/.exec(e)||e.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(e)||[];return{browser:t[1]||"",version:t[2]||"0"}},e=v.uaMatch(o.userAgent),t={},e.browser&&(t[e.browser]=!0,t.version=e.version),t.chrome?t.webkit=!0:t.webkit&&(t.safari=!0),v.browser=t,v.sub=function(){function e(t,n){return new e.fn.init(t,n)}v.extend(!0,e,this),e.superclass=this,e.fn=e.prototype=this(),e.fn.constructor=e,e.sub=this.sub,e.fn.init=function(r,i){return i&&i instanceof v&&!(i instanceof e)&&(i=e(i)),v.fn.init.call(this,r,i,t)},e.fn.init.prototype=e.fn;var t=e(i);return e}}();var Dt,Pt,Ht,Bt=/alpha\([^)]*\)/i,jt=/opacity=([^)]*)/,Ft=/^(top|right|bottom|left)$/,It=/^(none|table(?!-c[ea]).+)/,qt=/^margin/,Rt=new RegExp("^("+m+")(.*)$","i"),Ut=new RegExp("^("+m+")(?!px)[a-z%]+$","i"),zt=new RegExp("^([-+])=("+m+")","i"),Wt={BODY:"block"},Xt={position:"absolute",visibility:"hidden",display:"block"},Vt={letterSpacing:0,fontWeight:400},$t=["Top","Right","Bottom","Left"],Jt=["Webkit","O","Moz","ms"],Kt=v.fn.toggle;v.fn.extend({css:function(e,n){return v.access(this,function(e,n,r){return r!==t?v.style(e,n,r):v.css(e,n)},e,n,arguments.length>1)},show:function(){return Yt(this,!0)},hide:function(){return Yt(this)},toggle:function(e,t){var n=typeof e=="boolean";return v.isFunction(e)&&v.isFunction(t)?Kt.apply(this,arguments):this.each(function(){(n?e:Gt(this))?v(this).show():v(this).hide()})}}),v.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Dt(e,"opacity");return n===""?"1":n}}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":v.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var s,o,u,a=v.camelCase(n),f=e.style;n=v.cssProps[a]||(v.cssProps[a]=Qt(f,a)),u=v.cssHooks[n]||v.cssHooks[a];if(r===t)return u&&"get"in u&&(s=u.get(e,!1,i))!==t?s:f[n];o=typeof r,o==="string"&&(s=zt.exec(r))&&(r=(s[1]+1)*s[2]+parseFloat(v.css(e,n)),o="number");if(r==null||o==="number"&&isNaN(r))return;o==="number"&&!v.cssNumber[a]&&(r+="px");if(!u||!("set"in u)||(r=u.set(e,r,i))!==t)try{f[n]=r}catch(l){}},css:function(e,n,r,i){var s,o,u,a=v.camelCase(n);return n=v.cssProps[a]||(v.cssProps[a]=Qt(e.style,a)),u=v.cssHooks[n]||v.cssHooks[a],u&&"get"in u&&(s=u.get(e,!0,i)),s===t&&(s=Dt(e,n)),s==="normal"&&n in Vt&&(s=Vt[n]),r||i!==t?(o=parseFloat(s),r||v.isNumeric(o)?o||0:s):s},swap:function(e,t,n){var r,i,s={};for(i in t)s[i]=e.style[i],e.style[i]=t[i];r=n.call(e);for(i in t)e.style[i]=s[i];return r}}),e.getComputedStyle?Dt=function(t,n){var r,i,s,o,u=e.getComputedStyle(t,null),a=t.style;return u&&(r=u.getPropertyValue(n)||u[n],r===""&&!v.contains(t.ownerDocument,t)&&(r=v.style(t,n)),Ut.test(r)&&qt.test(n)&&(i=a.width,s=a.minWidth,o=a.maxWidth,a.minWidth=a.maxWidth=a.width=r,r=u.width,a.width=i,a.minWidth=s,a.maxWidth=o)),r}:i.documentElement.currentStyle&&(Dt=function(e,t){var n,r,i=e.currentStyle&&e.currentStyle[t],s=e.style;return i==null&&s&&s[t]&&(i=s[t]),Ut.test(i)&&!Ft.test(t)&&(n=s.left,r=e.runtimeStyle&&e.runtimeStyle.left,r&&(e.runtimeStyle.left=e.currentStyle.left),s.left=t==="fontSize"?"1em":i,i=s.pixelLeft+"px",s.left=n,r&&(e.runtimeStyle.left=r)),i===""?"auto":i}),v.each(["height","width"],function(e,t){v.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&It.test(Dt(e,"display"))?v.swap(e,Xt,function(){return tn(e,t,r)}):tn(e,t,r)},set:function(e,n,r){return Zt(e,n,r?en(e,t,r,v.support.boxSizing&&v.css(e,"boxSizing")==="border-box"):0)}}}),v.support.opacity||(v.cssHooks.opacity={get:function(e,t){return jt.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=v.isNumeric(t)?"alpha(opacity="+t*100+")":"",s=r&&r.filter||n.filter||"";n.zoom=1;if(t>=1&&v.trim(s.replace(Bt,""))===""&&n.removeAttribute){n.removeAttribute("filter");if(r&&!r.filter)return}n.filter=Bt.test(s)?s.replace(Bt,i):s+" "+i}}),v(function(){v.support.reliableMarginRight||(v.cssHooks.marginRight={get:function(e,t){return v.swap(e,{display:"inline-block"},function(){if(t)return Dt(e,"marginRight")})}}),!v.support.pixelPosition&&v.fn.position&&v.each(["top","left"],function(e,t){v.cssHooks[t]={get:function(e,n){if(n){var r=Dt(e,t);return Ut.test(r)?v(e).position()[t]+"px":r}}}})}),v.expr&&v.expr.filters&&(v.expr.filters.hidden=function(e){return e.offsetWidth===0&&e.offsetHeight===0||!v.support.reliableHiddenOffsets&&(e.style&&e.style.display||Dt(e,"display"))==="none"},v.expr.filters.visible=function(e){return!v.expr.filters.hidden(e)}),v.each({margin:"",padding:"",border:"Width"},function(e,t){v.cssHooks[e+t]={expand:function(n){var r,i=typeof n=="string"?n.split(" "):[n],s={};for(r=0;r<4;r++)s[e+$t[r]+t]=i[r]||i[r-2]||i[0];return s}},qt.test(e)||(v.cssHooks[e+t].set=Zt)});var rn=/%20/g,sn=/\[\]$/,on=/\r?\n/g,un=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,an=/^(?:select|textarea)/i;v.fn.extend({serialize:function(){return v.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?v.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||an.test(this.nodeName)||un.test(this.type))}).map(function(e,t){var n=v(this).val();return n==null?null:v.isArray(n)?v.map(n,function(e,n){return{name:t.name,value:e.replace(on,"\r\n")}}):{name:t.name,value:n.replace(on,"\r\n")}}).get()}}),v.param=function(e,n){var r,i=[],s=function(e,t){t=v.isFunction(t)?t():t==null?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};n===t&&(n=v.ajaxSettings&&v.ajaxSettings.traditional);if(v.isArray(e)||e.jquery&&!v.isPlainObject(e))v.each(e,function(){s(this.name,this.value)});else for(r in e)fn(r,e[r],n,s);return i.join("&").replace(rn,"+")};var ln,cn,hn=/#.*$/,pn=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,dn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,vn=/^(?:GET|HEAD)$/,mn=/^\/\//,gn=/\?/,yn=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bn=/([?&])_=[^&]*/,wn=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,En=v.fn.load,Sn={},xn={},Tn=["*/"]+["*"];try{cn=s.href}catch(Nn){cn=i.createElement("a"),cn.href="",cn=cn.href}ln=wn.exec(cn.toLowerCase())||[],v.fn.load=function(e,n,r){if(typeof e!="string"&&En)return En.apply(this,arguments);if(!this.length)return this;var i,s,o,u=this,a=e.indexOf(" ");return a>=0&&(i=e.slice(a,e.length),e=e.slice(0,a)),v.isFunction(n)?(r=n,n=t):n&&typeof n=="object"&&(s="POST"),v.ajax({url:e,type:s,dataType:"html",data:n,complete:function(e,t){r&&u.each(r,o||[e.responseText,t,e])}}).done(function(e){o=arguments,u.html(i?v("<div>").append(e.replace(yn,"")).find(i):e)}),this},v.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,t){v.fn[t]=function(e){return this.on(t,e)}}),v.each(["get","post"],function(e,n){v[n]=function(e,r,i,s){return v.isFunction(r)&&(s=s||i,i=r,r=t),v.ajax({type:n,url:e,data:r,success:i,dataType:s})}}),v.extend({getScript:function(e,n){return v.get(e,t,n,"script")},getJSON:function(e,t,n){return v.get(e,t,n,"json")},ajaxSetup:function(e,t){return t?Ln(e,v.ajaxSettings):(t=e,e=v.ajaxSettings),Ln(e,t),e},ajaxSettings:{url:cn,isLocal:dn.test(ln[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":Tn},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":v.parseJSON,"text xml":v.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:Cn(Sn),ajaxTransport:Cn(xn),ajax:function(e,n){function T(e,n,s,a){var l,y,b,w,S,T=n;if(E===2)return;E=2,u&&clearTimeout(u),o=t,i=a||"",x.readyState=e>0?4:0,s&&(w=An(c,x,s));if(e>=200&&e<300||e===304)c.ifModified&&(S=x.getResponseHeader("Last-Modified"),S&&(v.lastModified[r]=S),S=x.getResponseHeader("Etag"),S&&(v.etag[r]=S)),e===304?(T="notmodified",l=!0):(l=On(c,w),T=l.state,y=l.data,b=l.error,l=!b);else{b=T;if(!T||e)T="error",e<0&&(e=0)}x.status=e,x.statusText=(n||T)+"",l?d.resolveWith(h,[y,T,x]):d.rejectWith(h,[x,T,b]),x.statusCode(g),g=t,f&&p.trigger("ajax"+(l?"Success":"Error"),[x,c,l?y:b]),m.fireWith(h,[x,T]),f&&(p.trigger("ajaxComplete",[x,c]),--v.active||v.event.trigger("ajaxStop"))}typeof e=="object"&&(n=e,e=t),n=n||{};var r,i,s,o,u,a,f,l,c=v.ajaxSetup({},n),h=c.context||c,p=h!==c&&(h.nodeType||h instanceof v)?v(h):v.event,d=v.Deferred(),m=v.Callbacks("once memory"),g=c.statusCode||{},b={},w={},E=0,S="canceled",x={readyState:0,setRequestHeader:function(e,t){if(!E){var n=e.toLowerCase();e=w[n]=w[n]||e,b[e]=t}return this},getAllResponseHeaders:function(){return E===2?i:null},getResponseHeader:function(e){var n;if(E===2){if(!s){s={};while(n=pn.exec(i))s[n[1].toLowerCase()]=n[2]}n=s[e.toLowerCase()]}return n===t?null:n},overrideMimeType:function(e){return E||(c.mimeType=e),this},abort:function(e){return e=e||S,o&&o.abort(e),T(0,e),this}};d.promise(x),x.success=x.done,x.error=x.fail,x.complete=m.add,x.statusCode=function(e){if(e){var t;if(E<2)for(t in e)g[t]=[g[t],e[t]];else t=e[x.status],x.always(t)}return this},c.url=((e||c.url)+"").replace(hn,"").replace(mn,ln[1]+"//"),c.dataTypes=v.trim(c.dataType||"*").toLowerCase().split(y),c.crossDomain==null&&(a=wn.exec(c.url.toLowerCase()),c.crossDomain=!(!a||a[1]===ln[1]&&a[2]===ln[2]&&(a[3]||(a[1]==="http:"?80:443))==(ln[3]||(ln[1]==="http:"?80:443)))),c.data&&c.processData&&typeof c.data!="string"&&(c.data=v.param(c.data,c.traditional)),kn(Sn,c,n,x);if(E===2)return x;f=c.global,c.type=c.type.toUpperCase(),c.hasContent=!vn.test(c.type),f&&v.active++===0&&v.event.trigger("ajaxStart");if(!c.hasContent){c.data&&(c.url+=(gn.test(c.url)?"&":"?")+c.data,delete c.data),r=c.url;if(c.cache===!1){var N=v.now(),C=c.url.replace(bn,"$1_="+N);c.url=C+(C===c.url?(gn.test(c.url)?"&":"?")+"_="+N:"")}}(c.data&&c.hasContent&&c.contentType!==!1||n.contentType)&&x.setRequestHeader("Content-Type",c.contentType),c.ifModified&&(r=r||c.url,v.lastModified[r]&&x.setRequestHeader("If-Modified-Since",v.lastModified[r]),v.etag[r]&&x.setRequestHeader("If-None-Match",v.etag[r])),x.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+(c.dataTypes[0]!=="*"?", "+Tn+"; q=0.01":""):c.accepts["*"]);for(l in c.headers)x.setRequestHeader(l,c.headers[l]);if(!c.beforeSend||c.beforeSend.call(h,x,c)!==!1&&E!==2){S="abort";for(l in{success:1,error:1,complete:1})x[l](c[l]);o=kn(xn,c,n,x);if(!o)T(-1,"No Transport");else{x.readyState=1,f&&p.trigger("ajaxSend",[x,c]),c.async&&c.timeout>0&&(u=setTimeout(function(){x.abort("timeout")},c.timeout));try{E=1,o.send(b,T)}catch(k){if(!(E<2))throw k;T(-1,k)}}return x}return x.abort()},active:0,lastModified:{},etag:{}});var Mn=[],_n=/\?/,Dn=/(=)\?(?=&|$)|\?\?/,Pn=v.now();v.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Mn.pop()||v.expando+"_"+Pn++;return this[e]=!0,e}}),v.ajaxPrefilter("json jsonp",function(n,r,i){var s,o,u,a=n.data,f=n.url,l=n.jsonp!==!1,c=l&&Dn.test(f),h=l&&!c&&typeof a=="string"&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Dn.test(a);if(n.dataTypes[0]==="jsonp"||c||h)return s=n.jsonpCallback=v.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,o=e[s],c?n.url=f.replace(Dn,"$1"+s):h?n.data=a.replace(Dn,"$1"+s):l&&(n.url+=(_n.test(f)?"&":"?")+n.jsonp+"="+s),n.converters["script json"]=function(){return u||v.error(s+" was not called"),u[0]},n.dataTypes[0]="json",e[s]=function(){u=arguments},i.always(function(){e[s]=o,n[s]&&(n.jsonpCallback=r.jsonpCallback,Mn.push(s)),u&&v.isFunction(o)&&o(u[0]),u=o=t}),"script"}),v.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){return v.globalEval(e),e}}}),v.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),v.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=i.head||i.getElementsByTagName("head")[0]||i.documentElement;return{send:function(s,o){n=i.createElement("script"),n.async="async",e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,i){if(i||!n.readyState||/loaded|complete/.test(n.readyState))n.onload=n.onreadystatechange=null,r&&n.parentNode&&r.removeChild(n),n=t,i||o(200,"success")},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(0,1)}}}});var Hn,Bn=e.ActiveXObject?function(){for(var e in Hn)Hn[e](0,1)}:!1,jn=0;v.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&Fn()||In()}:Fn,function(e){v.extend(v.support,{ajax:!!e,cors:!!e&&"withCredentials"in e})}(v.ajaxSettings.xhr()),v.support.ajax&&v.ajaxTransport(function(n){if(!n.crossDomain||v.support.cors){var r;return{send:function(i,s){var o,u,a=n.xhr();n.username?a.open(n.type,n.url,n.async,n.username,n.password):a.open(n.type,n.url,n.async);if(n.xhrFields)for(u in n.xhrFields)a[u]=n.xhrFields[u];n.mimeType&&a.overrideMimeType&&a.overrideMimeType(n.mimeType),!n.crossDomain&&!i["X-Requested-With"]&&(i["X-Requested-With"]="XMLHttpRequest");try{for(u in i)a.setRequestHeader(u,i[u])}catch(f){}a.send(n.hasContent&&n.data||null),r=function(e,i){var u,f,l,c,h;try{if(r&&(i||a.readyState===4)){r=t,o&&(a.onreadystatechange=v.noop,Bn&&delete Hn[o]);if(i)a.readyState!==4&&a.abort();else{u=a.status,l=a.getAllResponseHeaders(),c={},h=a.responseXML,h&&h.documentElement&&(c.xml=h);try{c.text=a.responseText}catch(p){}try{f=a.statusText}catch(p){f=""}!u&&n.isLocal&&!n.crossDomain?u=c.text?200:404:u===1223&&(u=204)}}}catch(d){i||s(-1,d)}c&&s(u,f,c,l)},n.async?a.readyState===4?setTimeout(r,0):(o=++jn,Bn&&(Hn||(Hn={},v(e).unload(Bn)),Hn[o]=r),a.onreadystatechange=r):r()},abort:function(){r&&r(0,1)}}}});var qn,Rn,Un=/^(?:toggle|show|hide)$/,zn=new RegExp("^(?:([-+])=|)("+m+")([a-z%]*)$","i"),Wn=/queueHooks$/,Xn=[Gn],Vn={"*":[function(e,t){var n,r,i=this.createTween(e,t),s=zn.exec(t),o=i.cur(),u=+o||0,a=1,f=20;if(s){n=+s[2],r=s[3]||(v.cssNumber[e]?"":"px");if(r!=="px"&&u){u=v.css(i.elem,e,!0)||n||1;do a=a||".5",u/=a,v.style(i.elem,e,u+r);while(a!==(a=i.cur()/o)&&a!==1&&--f)}i.unit=r,i.start=u,i.end=s[1]?u+(s[1]+1)*n:n}return i}]};v.Animation=v.extend(Kn,{tweener:function(e,t){v.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],Vn[n]=Vn[n]||[],Vn[n].unshift(t)},prefilter:function(e,t){t?Xn.unshift(e):Xn.push(e)}}),v.Tween=Yn,Yn.prototype={constructor:Yn,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(v.cssNumber[n]?"":"px")},cur:function(){var e=Yn.propHooks[this.prop];return e&&e.get?e.get(this):Yn.propHooks._default.get(this)},run:function(e){var t,n=Yn.propHooks[this.prop];return this.options.duration?this.pos=t=v.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Yn.propHooks._default.set(this),this}},Yn.prototype.init.prototype=Yn.prototype,Yn.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=v.css(e.elem,e.prop,!1,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){v.fx.step[e.prop]?v.fx.step[e.prop](e):e.elem.style&&(e.elem.style[v.cssProps[e.prop]]!=null||v.cssHooks[e.prop])?v.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Yn.propHooks.scrollTop=Yn.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},v.each(["toggle","show","hide"],function(e,t){var n=v.fn[t];v.fn[t]=function(r,i,s){return r==null||typeof r=="boolean"||!e&&v.isFunction(r)&&v.isFunction(i)?n.apply(this,arguments):this.animate(Zn(t,!0),r,i,s)}}),v.fn.extend({fadeTo:function(e,t,n,r){return this.filter(Gt).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=v.isEmptyObject(e),s=v.speed(t,n,r),o=function(){var t=Kn(this,v.extend({},e),s);i&&t.stop(!0)};return i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return typeof e!="string"&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=e!=null&&e+"queueHooks",s=v.timers,o=v._data(this);if(n)o[n]&&o[n].stop&&i(o[n]);else for(n in o)o[n]&&o[n].stop&&Wn.test(n)&&i(o[n]);for(n=s.length;n--;)s[n].elem===this&&(e==null||s[n].queue===e)&&(s[n].anim.stop(r),t=!1,s.splice(n,1));(t||!r)&&v.dequeue(this,e)})}}),v.each({slideDown:Zn("show"),slideUp:Zn("hide"),slideToggle:Zn("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){v.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),v.speed=function(e,t,n){var r=e&&typeof e=="object"?v.extend({},e):{complete:n||!n&&t||v.isFunction(e)&&e,duration:e,easing:n&&t||t&&!v.isFunction(t)&&t};r.duration=v.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in v.fx.speeds?v.fx.speeds[r.duration]:v.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){v.isFunction(r.old)&&r.old.call(this),r.queue&&v.dequeue(this,r.queue)},r},v.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},v.timers=[],v.fx=Yn.prototype.init,v.fx.tick=function(){var e,n=v.timers,r=0;qn=v.now();for(;r<n.length;r++)e=n[r],!e()&&n[r]===e&&n.splice(r--,1);n.length||v.fx.stop(),qn=t},v.fx.timer=function(e){e()&&v.timers.push(e)&&!Rn&&(Rn=setInterval(v.fx.tick,v.fx.interval))},v.fx.interval=13,v.fx.stop=function(){clearInterval(Rn),Rn=null},v.fx.speeds={slow:600,fast:200,_default:400},v.fx.step={},v.expr&&v.expr.filters&&(v.expr.filters.animated=function(e){return v.grep(v.timers,function(t){return e===t.elem}).length});var er=/^(?:body|html)$/i;v.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){v.offset.setOffset(this,e,t)});var n,r,i,s,o,u,a,f={top:0,left:0},l=this[0],c=l&&l.ownerDocument;if(!c)return;return(r=c.body)===l?v.offset.bodyOffset(l):(n=c.documentElement,v.contains(n,l)?(typeof l.getBoundingClientRect!="undefined"&&(f=l.getBoundingClientRect()),i=tr(c),s=n.clientTop||r.clientTop||0,o=n.clientLeft||r.clientLeft||0,u=i.pageYOffset||n.scrollTop,a=i.pageXOffset||n.scrollLeft,{top:f.top+u-s,left:f.left+a-o}):f)},v.offset={bodyOffset:function(e){var t=e.offsetTop,n=e.offsetLeft;return v.support.doesNotIncludeMarginInBodyOffset&&(t+=parseFloat(v.css(e,"marginTop"))||0,n+=parseFloat(v.css(e,"marginLeft"))||0),{top:t,left:n}},setOffset:function(e,t,n){var r=v.css(e,"position");r==="static"&&(e.style.position="relative");var i=v(e),s=i.offset(),o=v.css(e,"top"),u=v.css(e,"left"),a=(r==="absolute"||r==="fixed")&&v.inArray("auto",[o,u])>-1,f={},l={},c,h;a?(l=i.position(),c=l.top,h=l.left):(c=parseFloat(o)||0,h=parseFloat(u)||0),v.isFunction(t)&&(t=t.call(e,n,s)),t.top!=null&&(f.top=t.top-s.top+c),t.left!=null&&(f.left=t.left-s.left+h),"using"in t?t.using.call(e,f):i.css(f)}},v.fn.extend({position:function(){if(!this[0])return;var e=this[0],t=this.offsetParent(),n=this.offset(),r=er.test(t[0].nodeName)?{top:0,left:0}:t.offset();return n.top-=parseFloat(v.css(e,"marginTop"))||0,n.left-=parseFloat(v.css(e,"marginLeft"))||0,r.top+=parseFloat(v.css(t[0],"borderTopWidth"))||0,r.left+=parseFloat(v.css(t[0],"borderLeftWidth"))||0,{top:n.top-r.top,left:n.left-r.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||i.body;while(e&&!er.test(e.nodeName)&&v.css(e,"position")==="static")e=e.offsetParent;return e||i.body})}}),v.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);v.fn[e]=function(i){return v.access(this,function(e,i,s){var o=tr(e);if(s===t)return o?n in o?o[n]:o.document.documentElement[i]:e[i];o?o.scrollTo(r?v(o).scrollLeft():s,r?s:v(o).scrollTop()):e[i]=s},e,i,arguments.length,null)}}),v.each({Height:"height",Width:"width"},function(e,n){v.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){v.fn[i]=function(i,s){var o=arguments.length&&(r||typeof i!="boolean"),u=r||(i===!0||s===!0?"margin":"border");return v.access(this,function(n,r,i){var s;return v.isWindow(n)?n.document.documentElement["client"+e]:n.nodeType===9?(s=n.documentElement,Math.max(n.body["scroll"+e],s["scroll"+e],n.body["offset"+e],s["offset"+e],s["client"+e])):i===t?v.css(n,r,i,u):v.style(n,r,i,u)},n,o?i:t,o,null)}})}),e.jQuery=e.$=v,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return v})})(window);
// for jQuery
$.event.special.touchstart = {
    setup: function( _, ns, handle ) {
        this.addEventListener("touchstart", handle, { passive: !ns.includes("noPreventDefault") });
    }
};
$.event.special.touchmove = {
    setup: function( _, ns, handle ) {
        this.addEventListener("touchmove", handle, { passive: !ns.includes("noPreventDefault") });
    }
};

// avoid conflict
var jQueryChamo = jQuery.noConflict(true);

// for IE7 or former , add JSON object
if(typeof JSON!=='object'){JSON={}}(function(){'use strict';function f(n){return n<10?'0'+n:n}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key)}if(typeof rep==='function'){value=rep.call(holder,key,value)}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null'}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null'}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==='string'){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' '}}else if(typeof space==='string'){indent=space}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}return str('',{'':value})}}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j}throw new SyntaxError('JSON.parse');}}}());

// Add some ES5 functions
if(!Array.isArray){Array.isArray=function(vArg){return Object.prototype.toString.call(vArg)==="[object Array]"}}
if(!Array.prototype.forEach){Array.prototype.forEach=function(callback,thisArg){var T,k;if(this==null){throw new TypeError(" this is null or not defined")}var O=Object(this);var len=O.length>>>0;if({}.toString.call(callback)!="[object Function]"){throw new TypeError(callback+" is not a function")}if(thisArg){T=thisArg}k=0;while(k<len){var kValue;if(k in O){kValue=O[k];callback.call(T,kValue,k,O)}k++}}};
if(!Array.prototype.indexOf){Array.prototype.indexOf=function(searchElement){"use strict";if(this==null){throw new TypeError();}var t=Object(this);var len=t.length>>>0;if(len===0){return-1}var n=0;if(arguments.length>0){n=Number(arguments[1]);if(n!=n){n=0}else if(n!=0&&n!=Infinity&&n!=-Infinity){n=(n>0||-1)*Math.floor(Math.abs(n))}}if(n>=len){return-1}var k=n>=0?n:Math.max(len-Math.abs(n),0);for(;k<len;k++){if(k in t&&t[k]===searchElement){return k}}return-1}}

// for IE7/8/9 use XDomainRequest instead of XMLHttpRequest
(function( jQuery ) { var appVersion = window.navigator.appVersion.toLowerCase(); if ((appVersion.indexOf("msie 7.") != -1) || (appVersion.indexOf("msie 8.") != -1) || (appVersion.indexOf("msie 9.") != -1)) {jQuery.ajaxTransport(function( s ) {if ( s.crossDomain && s.async ) {if ( s.timeout ) {s.xdrTimeout = s.timeout;delete s.timeout;}var xdr;return {send: function( _, complete ) {function callback( status, statusText, responses, responseHeaders ) {xdr.onload = xdr.onerror = xdr.ontimeout = xdr.onprogress = jQuery.noop;xdr = undefined;complete( status, statusText, responses, responseHeaders );}xdr = new XDomainRequest();xdr.open( s.type, s.url );xdr.onload = function() {callback( 200, "OK", { text: xdr.responseText }, "Content-Type: " + xdr.contentType );};xdr.onerror = function() {callback( 404, "Not Found" );};xdr.onprogress = function() {};if ( s.xdrTimeout ) {xdr.ontimeout = function() {callback( 0, "timeout" );};xdr.timeout = s.xdrTimeout;}xdr.send( ( s.hasContent && s.data ) || null );},abort: function() {if ( xdr ) {xdr.onerror = jQuery.noop();xdr.abort();}}};}});}})( jQueryChamo );


// MD5 http://www.onicos.com/staff/iz/amuse/javascript/expert/
var MD5_T=new Array(0x00000000,0xd76aa478,0xe8c7b756,0x242070db,0xc1bdceee,0xf57c0faf,0x4787c62a,0xa8304613,0xfd469501,0x698098d8,0x8b44f7af,0xffff5bb1,0x895cd7be,0x6b901122,0xfd987193,0xa679438e,0x49b40821,0xf61e2562,0xc040b340,0x265e5a51,0xe9b6c7aa,0xd62f105d,0x02441453,0xd8a1e681,0xe7d3fbc8,0x21e1cde6,0xc33707d6,0xf4d50d87,0x455a14ed,0xa9e3e905,0xfcefa3f8,0x676f02d9,0x8d2a4c8a,0xfffa3942,0x8771f681,0x6d9d6122,0xfde5380c,0xa4beea44,0x4bdecfa9,0xf6bb4b60,0xbebfbc70,0x289b7ec6,0xeaa127fa,0xd4ef3085,0x04881d05,0xd9d4d039,0xe6db99e5,0x1fa27cf8,0xc4ac5665,0xf4292244,0x432aff97,0xab9423a7,0xfc93a039,0x655b59c3,0x8f0ccc92,0xffeff47d,0x85845dd1,0x6fa87e4f,0xfe2ce6e0,0xa3014314,0x4e0811a1,0xf7537e82,0xbd3af235,0x2ad7d2bb,0xeb86d391);var MD5_round1=new Array(new Array(0,7,1),new Array(1,12,2),new Array(2,17,3),new Array(3,22,4),new Array(4,7,5),new Array(5,12,6),new Array(6,17,7),new Array(7,22,8),new Array(8,7,9),new Array(9,12,10),new Array(10,17,11),new Array(11,22,12),new Array(12,7,13),new Array(13,12,14),new Array(14,17,15),new Array(15,22,16));var MD5_round2=new Array(new Array(1,5,17),new Array(6,9,18),new Array(11,14,19),new Array(0,20,20),new Array(5,5,21),new Array(10,9,22),new Array(15,14,23),new Array(4,20,24),new Array(9,5,25),new Array(14,9,26),new Array(3,14,27),new Array(8,20,28),new Array(13,5,29),new Array(2,9,30),new Array(7,14,31),new Array(12,20,32));var MD5_round3=new Array(new Array(5,4,33),new Array(8,11,34),new Array(11,16,35),new Array(14,23,36),new Array(1,4,37),new Array(4,11,38),new Array(7,16,39),new Array(10,23,40),new Array(13,4,41),new Array(0,11,42),new Array(3,16,43),new Array(6,23,44),new Array(9,4,45),new Array(12,11,46),new Array(15,16,47),new Array(2,23,48));var MD5_round4=new Array(new Array(0,6,49),new Array(7,10,50),new Array(14,15,51),new Array(5,21,52),new Array(12,6,53),new Array(3,10,54),new Array(10,15,55),new Array(1,21,56),new Array(8,6,57),new Array(15,10,58),new Array(6,15,59),new Array(13,21,60),new Array(4,6,61),new Array(11,10,62),new Array(2,15,63),new Array(9,21,64));function MD5_F(x,y,z){return(x&y)|(~x&z)}function MD5_G(x,y,z){return(x&z)|(y&~z)}function MD5_H(x,y,z){return x^y^z}function MD5_I(x,y,z){return y^(x|~z)}var MD5_round=new Array(new Array(MD5_F,MD5_round1),new Array(MD5_G,MD5_round2),new Array(MD5_H,MD5_round3),new Array(MD5_I,MD5_round4));function MD5_pack(n32){return String.fromCharCode(n32&0xff)+String.fromCharCode((n32>>>8)&0xff)+String.fromCharCode((n32>>>16)&0xff)+String.fromCharCode((n32>>>24)&0xff)}function MD5_unpack(s4){return s4.charCodeAt(0)|(s4.charCodeAt(1)<<8)|(s4.charCodeAt(2)<<16)|(s4.charCodeAt(3)<<24)}function MD5_number(n){while(n<0)n+=4294967296;while(n>4294967295)n-=4294967296;return n}function MD5_apply_round(x,s,f,abcd,r){var a,b,c,d;var kk,ss,ii;var t,u;a=abcd[0];b=abcd[1];c=abcd[2];d=abcd[3];kk=r[0];ss=r[1];ii=r[2];u=f(s[b],s[c],s[d]);t=s[a]+u+x[kk]+MD5_T[ii];t=MD5_number(t);t=((t<<ss)|(t>>>(32-ss)));t+=s[b];s[a]=MD5_number(t)}function MD5_hash(data){var abcd,x,state,s;var len,index,padLen,f,r;var i,j,k;var tmp;state=new Array(0x67452301,0xefcdab89,0x98badcfe,0x10325476);len=data.length;index=len&0x3f;padLen=(index<56)?(56-index):(120-index);if(padLen>0){data+="\x80";for(i=0;i<padLen-1;i++)data+="\x00"}data+=MD5_pack(len*8);data+=MD5_pack(0);len+=padLen+8;abcd=new Array(0,1,2,3);x=new Array(16);s=new Array(4);for(k=0;k<len;k+=64){for(i=0,j=k;i<16;i++,j+=4){x[i]=data.charCodeAt(j)|(data.charCodeAt(j+1)<<8)|(data.charCodeAt(j+2)<<16)|(data.charCodeAt(j+3)<<24)}for(i=0;i<4;i++)s[i]=state[i];for(i=0;i<4;i++){f=MD5_round[i][0];r=MD5_round[i][1];for(j=0;j<16;j++){MD5_apply_round(x,s,f,abcd,r[j]);tmp=abcd[0];abcd[0]=abcd[3];abcd[3]=abcd[2];abcd[2]=abcd[1];abcd[1]=tmp}}for(i=0;i<4;i++){state[i]+=s[i];state[i]=MD5_number(state[i])}}return MD5_pack(state[0])+MD5_pack(state[1])+MD5_pack(state[2])+MD5_pack(state[3])}function MD5_hexhash(data){var i,out,c;var bit128;bit128=MD5_hash(data);out="";for(i=0;i<16;i++){c=bit128.charCodeAt(i);out+="0123456789abcdef".charAt((c>>4)&0xf);out+="0123456789abcdef".charAt(c&0xf)}return out}
/* Asynchronously write javascript, even with document.write., v1.4.0 https://krux.github.io/postscribe
Copyright (c) 2015 Derek Brans, MIT license https://github.com/krux/postscribe/blob/master/LICENSE */!function(){function a(a,h){a=a||"",h=h||{};for(var i in b)b.hasOwnProperty(i)&&(h.autoFix&&(h["fix_"+i]=!0),h.fix=h.fix||h["fix_"+i]);var j=[],k=document.createElement("div"),l=function(a){return"string"==typeof a&&-1!==a.indexOf("&")?(k.innerHTML=a,k.textContent||k.innerText||a):a},m=function(b){a+=b},n=function(b){a=b+a},o={comment:/^<!--/,endTag:/^<\//,atomicTag:/^<\s*(script|style|noscript|iframe|textarea)[\s\/>]/i,startTag:/^</,chars:/^[^<]/},p={comment:function(){var b=a.indexOf("-->");return b>=0?{content:a.substr(4,b),length:b+3}:void 0},endTag:function(){var b=a.match(d);return b?{tagName:b[1],length:b[0].length}:void 0},atomicTag:function(){var b=p.startTag();if(b){var c=a.slice(b.length);if(c.match(new RegExp("</\\s*"+b.tagName+"\\s*>","i"))){var d=c.match(new RegExp("([\\s\\S]*?)</\\s*"+b.tagName+"\\s*>","i"));if(d)return{tagName:b.tagName,attrs:b.attrs,content:d[1],length:d[0].length+b.length}}}},startTag:function(){var b=a.indexOf(">");if(-1===b)return null;var d=a.match(c);if(d){var g={},h={},i=d[2];return d[2].replace(e,function(a,b){if(arguments[2]||arguments[3]||arguments[4]||arguments[5])if(arguments[5])g[arguments[5]]="",h[b]=!0;else{var c=arguments[2]||arguments[3]||arguments[4]||f.test(b)&&b||"";g[b]=l(c)}else g[b]=null;i=i.replace(a,"")}),{tagName:d[1],attrs:g,booleanAttrs:h,rest:i,unary:!!d[3],length:d[0].length}}},chars:function(){var b=a.indexOf("<");return{length:b>=0?b:a.length}}},q=function(){for(var b in o)if(o[b].test(a)){g&&console.log("suspected "+b);var c=p[b]();return c?(g&&console.log("parsed "+b,c),c.type=c.type||b,c.text=a.substr(0,c.length),a=a.slice(c.length),c):null}},r=function(a){for(var b;b=q();)if(a[b.type]&&a[b.type](b)===!1)return},s=function(){var b=a;return a="",b},t=function(){return a};return h.fix&&!function(){var b=/^(AREA|BASE|BASEFONT|BR|COL|FRAME|HR|IMG|INPUT|ISINDEX|LINK|META|PARAM|EMBED)$/i,c=/^(COLGROUP|DD|DT|LI|OPTIONS|P|TD|TFOOT|TH|THEAD|TR)$/i,d=[];d.last=function(){return this[this.length-1]},d.lastTagNameEq=function(a){var b=this.last();return b&&b.tagName&&b.tagName.toUpperCase()===a.toUpperCase()},d.containsTagName=function(a){for(var b,c=0;b=this[c];c++)if(b.tagName===a)return!0;return!1};var e=function(a){return a&&"startTag"===a.type&&(a.unary=b.test(a.tagName)||a.unary,a.html5Unary=!/\/>$/.test(a.text)),a},f=q,g=function(){var b=a,c=e(f());return a=b,c},i=function(){var a=d.pop();n("</"+a.tagName+">")},j={startTag:function(a){var b=a.tagName;"TR"===b.toUpperCase()&&d.lastTagNameEq("TABLE")?(n("<TBODY>"),l()):h.fix_selfClose&&c.test(b)&&d.containsTagName(b)?d.lastTagNameEq(b)?i():(n("</"+a.tagName+">"),l()):a.unary||d.push(a)},endTag:function(a){var b=d.last();b?h.fix_tagSoup&&!d.lastTagNameEq(a.tagName)?i():d.pop():h.fix_tagSoup&&k()}},k=function(){f(),l()},l=function(){var a=g();a&&j[a.type]&&j[a.type](a)};q=function(){return l(),e(f())}}(),{append:m,readToken:q,readTokens:r,clear:s,rest:t,stack:j}}var b=function(){var a,b={},c=this.document.createElement("div");return a="<P><I></P></I>",c.innerHTML=a,b.tagSoup=c.innerHTML!==a,c.innerHTML="<P><i><P></P></i></P>",b.selfClose=2===c.childNodes.length,b}(),c=/^<([\-A-Za-z0-9_]+)((?:\s+[\w\-]+(?:\s*=?\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>/,d=/^<\/([\-A-Za-z0-9_]+)[^>]*>/,e=/(?:([\-A-Za-z0-9_]+)\s*=\s*(?:(?:"((?:\\.|[^"])*)")|(?:'((?:\\.|[^'])*)')|([^>\s]+)))|(?:([\-A-Za-z0-9_]+)(\s|$)+)/g,f=/^(checked|compact|declare|defer|disabled|ismap|multiple|nohref|noresize|noshade|nowrap|readonly|selected)$/i,g=!1;a.supports=b,a.tokenToString=function(a){var b={comment:function(a){return"<!--"+a.content},endTag:function(a){return"</"+a.tagName+">"},atomicTag:function(a){return g&&console.log(a),b.startTag(a)+a.content+b.endTag(a)},startTag:function(a){var b="<"+a.tagName;for(var c in a.attrs){b+=" "+c;var d=a.attrs[c];("undefined"==typeof a.booleanAttrs||"undefined"==typeof a.booleanAttrs[c])&&(b+='="'+(d?d.replace(/(^|[^\\])"/g,'$1\\"'):"")+'"')}return a.rest&&(b+=a.rest),b+(a.unary&&!a.html5Unary?"/>":">")},chars:function(a){return a.text}};return b[a.type](a)},a.escapeAttributes=function(a){var b={};for(var c in a){var d=a[c];b[c]=d&&d.replace(/(^|[^\\])"/g,'$1\\"')}return b};for(var h in b)a.browserHasFlaw=a.browserHasFlaw||!b[h]&&h;this.htmlParser=a}(),function(){function a(){}function b(a){return a!==m&&null!==a}function c(a){return"function"==typeof a}function d(a,b,c){var d,e=a&&a.length||0;for(d=0;e>d;d++)b.call(c,a[d],d)}function e(a,b,c){var d;for(d in a)a.hasOwnProperty(d)&&b.call(c,d,a[d])}function f(a,b){return e(b,function(b,c){a[b]=c}),a}function g(a,c){return a=a||{},e(c,function(c,d){b(a[c])||(a[c]=d)}),a}function h(a){try{return o.call(a)}catch(b){var c=[];return d(a,function(a){c.push(a)}),c}}function i(a){return a&&"tagName"in a?!!~a.tagName.toLowerCase().indexOf("script"):!1}function j(a){return a&&"tagName"in a?!!~a.tagName.toLowerCase().indexOf("style"):!1}var k={afterAsync:a,afterDequeue:a,afterStreamStart:a,afterWrite:a,autoFix:!0,beforeEnqueue:a,beforeWriteToken:function(a){return a},beforeWrite:function(a){return a},done:a,error:function(a){throw a},releaseAsync:!1},l=this,m=void 0;if(!l.postscribe){var n=!1,o=Array.prototype.slice,p=function(a){return a[a.length-1]},q=function(){function a(a,c,d){var e=k+c;if(2===arguments.length){var f=a.getAttribute(e);return b(f)?String(f):f}b(d)&&""!==d?a.setAttribute(e,d):a.removeAttribute(e)}function g(b,c){var d=b.ownerDocument;f(this,{root:b,options:c,win:d.defaultView||d.parentWindow,doc:d,parser:htmlParser("",{autoFix:c.autoFix}),actuals:[b],proxyHistory:"",proxyRoot:d.createElement(b.nodeName),scriptStack:[],writeQueue:[]}),a(this.proxyRoot,"proxyof",0)}var k="data-ps-";return g.prototype.write=function(){[].push.apply(this.writeQueue,arguments);for(var a;!this.deferredRemote&&this.writeQueue.length;)a=this.writeQueue.shift(),c(a)?this.callFunction(a):this.writeImpl(a)},g.prototype.callFunction=function(a){var b={type:"function",value:a.name||a.toString()};this.onScriptStart(b),a.call(this.win,this.doc),this.onScriptDone(b)},g.prototype.writeImpl=function(a){this.parser.append(a);for(var b,c,d,e=[];(b=this.parser.readToken())&&!(c=i(b))&&!(d=j(b));)b=this.options.beforeWriteToken(b),b&&e.push(b);this.writeStaticTokens(e),c&&this.handleScriptToken(b),d&&this.handleStyleToken(b)},g.prototype.writeStaticTokens=function(a){var b=this.buildChunk(a);if(b.actual)return b.html=this.proxyHistory+b.actual,this.proxyHistory+=b.proxy,this.proxyRoot.innerHTML=b.html,n&&(b.proxyInnerHTML=this.proxyRoot.innerHTML),this.walkChunk(),n&&(b.actualInnerHTML=this.root.innerHTML),b},g.prototype.buildChunk=function(a){var b=this.actuals.length,c=[],e=[],f=[];return d(a,function(a){var d=htmlParser.tokenToString(a);if(c.push(d),a.attrs){if(!/^noscript$/i.test(a.tagName)){var g=b++;e.push(d.replace(/(\/?>)/," "+k+"id="+g+" $1")),"ps-script"!==a.attrs.id&&"ps-style"!==a.attrs.id&&f.push("atomicTag"===a.type?"":"<"+a.tagName+" "+k+"proxyof="+g+(a.unary?" />":">"))}}else e.push(d),f.push("endTag"===a.type?d:"")}),{tokens:a,raw:c.join(""),actual:e.join(""),proxy:f.join("")}},g.prototype.walkChunk=function(){for(var c,d=[this.proxyRoot];b(c=d.shift());){var e=1===c.nodeType,f=e&&a(c,"proxyof");if(!f){e&&(this.actuals[a(c,"id")]=c,a(c,"id",null));var g=c.parentNode&&a(c.parentNode,"proxyof");g&&this.actuals[g].appendChild(c)}d.unshift.apply(d,h(c.childNodes))}},g.prototype.handleScriptToken=function(a){var b=this.parser.clear();if(b&&this.writeQueue.unshift(b),a.src=a.attrs.src||a.attrs.SRC,a=this.options.beforeWriteToken(a)){a.src&&this.scriptStack.length?this.deferredRemote=a:this.onScriptStart(a);var c=this;this.writeScriptToken(a,function(){c.onScriptDone(a)})}},g.prototype.handleStyleToken=function(a){var b=this.parser.clear();b&&this.writeQueue.unshift(b),a.type=a.attrs.type||a.attrs.TYPE||"text/css",a=this.options.beforeWriteToken(a),a&&this.writeStyleToken(a),b&&this.write()},g.prototype.writeStyleToken=function(a){var b=this.buildStyle(a);this.insertStyle(b),a.content&&(b.styleSheet&&!b.sheet?b.styleSheet.cssText=a.content:b.appendChild(this.doc.createTextNode(a.content)))},g.prototype.buildStyle=function(a){var b=this.doc.createElement(a.tagName);return b.setAttribute("type",a.type),e(a.attrs,function(a,c){b.setAttribute(a,c)}),b},g.prototype.insertStyle=function(a){this.writeImpl('<span id="ps-style"/>');var b=this.doc.getElementById("ps-style");b.parentNode.replaceChild(a,b)},g.prototype.onScriptStart=function(a){a.outerWrites=this.writeQueue,this.writeQueue=[],this.scriptStack.unshift(a)},g.prototype.onScriptDone=function(a){return a!==this.scriptStack[0]?void this.options.error({message:"Bad script nesting or script finished twice"}):(this.scriptStack.shift(),this.write.apply(this,a.outerWrites),void(!this.scriptStack.length&&this.deferredRemote&&(this.onScriptStart(this.deferredRemote),this.deferredRemote=null)))},g.prototype.writeScriptToken=function(a,b){var c=this.buildScript(a),d=this.shouldRelease(c),e=this.options.afterAsync;a.src&&(c.src=a.src,this.scriptLoadHandler(c,d?e:function(){b(),e()}));try{this.insertScript(c),(!a.src||d)&&b()}catch(f){this.options.error(f),b()}},g.prototype.buildScript=function(a){var b=this.doc.createElement(a.tagName);return e(a.attrs,function(a,c){b.setAttribute(a,c)}),a.content&&(b.text=a.content),b},g.prototype.insertScript=function(a){this.writeImpl('<span id="ps-script"/>');var b=this.doc.getElementById("ps-script");b.parentNode.replaceChild(a,b)},g.prototype.scriptLoadHandler=function(a,b){function c(){a=a.onload=a.onreadystatechange=a.onerror=null}function d(){c(),b()}function e(a){c(),g(a),b()}var g=this.options.error;f(a,{onload:function(){d()},onreadystatechange:function(){/^(loaded|complete)$/.test(a.readyState)&&d()},onerror:function(){e({message:"remote script failed "+a.src})}})},g.prototype.shouldRelease=function(a){var b=/^script$/i.test(a.nodeName);return!b||!!(this.options.releaseAsync&&a.src&&a.hasAttribute("async"))},g}();l.postscribe=function(){function b(){var a,b=j.shift();b&&(a=p(b),a.afterDequeue(),b.stream=d.apply(null,b),a.afterStreamStart())}function d(c,d,g){function j(a){a=g.beforeWrite(a),m.write(a),g.afterWrite(a)}m=new q(c,g),m.id=i++,m.name=g.name||m.id,e.streams[m.name]=m;var k=c.ownerDocument,l={close:k.close,open:k.open,write:k.write,writeln:k.writeln};f(k,{close:a,open:a,write:function(){return j(h(arguments).join(""))},writeln:function(){return j(h(arguments).join("")+"\n")}});var n=m.win.onerror||a;return m.win.onerror=function(a,b,c){g.error({msg:a+" - "+b+":"+c}),n.apply(m.win,arguments)},m.write(d,function(){f(k,l),m.win.onerror=n,g.done(),m=null,b()}),m}function e(d,e,f){c(f)&&(f={done:f}),f=g(f,k),d=/^#/.test(d)?l.document.getElementById(d.substr(1)):d.jquery?d[0]:d;var h=[d,e,f];return d.postscribe={cancel:function(){h.stream?h.stream.abort():h[1]=a}},f.beforeEnqueue(h),j.push(h),m||b(),d.postscribe}var i=0,j=[],m=null;return f(e,{streams:{},queue:j,WriteStream:q})}()}}();(function($){
  // Add show/hide event
  $.each(['show', 'hide'], function (i, ev) {
        var el = $.fn[ev];
        $.fn[ev] = function () {
          this.trigger(ev);
          return el.apply(this, arguments);
        };
      });  /*** Constant ***/
  var CHAT_SERVICENAME = 'chamovps';
  var CHAMO_SERVICE_NAME = 'Chamo';

  var CHAMO_STATE_HIDE = -11;
  var CHAMO_STATE_OFFLINE = -1;
  var CHAMO_STATE_UNKNOWN = 0;
  var CHAMO_STATE_ONLINE = 1;
  var CHAMO_STATE_INPUT = 2;

  var CHAMO_INPUT_START = 101;
  var CHAMO_INPUT_END = -101;

  var CHAMO_DISPLAY_WAITING = 0;    // 待機状態
  var CHAMO_DISPLAY_OPEN = 1;    // 開いた状態
  var CHAMO_DISPLAY_MAXIMUM = 2;    // 最大化状態

  var CHAMO_DEVICE_PC = 1;
  var CHAMO_DEVICE_IPHONE = 11;
  var CHAMO_DEVICE_IPAD = 21;
  var CHAMO_DEVICE_ANDROID = 31;

  var FLAG_OPERATOR_SPOKE = '_chamo_operator_spoke';
  var FLAG_USER_SPOKE = '_chamo_user_spoke';

  var CHAMO_NOOPERATOR_BEHAVIOR_FORM = 0;
  var CHAMO_NOOPERATOR_BEHAVIOR_ONLINE = 1;
  var CHAMO_NOOPERATOR_BEHAVIOR_INVISIBLE = 2;


  var accountID = _chaq["_accountID"];
  var loginhash = _chaq['_loginhash'] || null;
  var colormodel = [
    ['#7FBA00', '#72A700', '#FFFFFF', '#72A700','#FFFFFF']
  ];
  var protocol = 'https://';
  var hostname = 'ch.chamo-chat.com';
  var hostname1 = 'ch.chamo-chat.com';
  var hostname2 = 'ch.chamo-chat.com';
  if (($.inArray(accountID, [1009,1961]) != -1) || accountID >= 2590) {
    hostname = 'ch2.chamo-chat.com';
    hostname2 = 'ch2.chamo-chat.com';
  }
  var hosturl = protocol + hostname + '/';
  var staticfilehost = protocol + _chaq['host'] + '/';
  var refferel= hosturl + 'link.php?from=' + accountID;
  if ('LinQ' == CHAMO_SERVICE_NAME) {
    refferel = 'http://www.linq.asia/';
  }
  var nodejs_port = 443;
  var websocket_url = 'https://ws2.chamo-chat.com:443';
  // ローカルテスト用
  if ('local' == CHAT_SERVICENAME) {
    hostname = 'localhost';
    hosturl = 'http://localhost/www/chamo-node/';
  }

  // program uri
  var chamo_host = hosturl + 'req.php';
  var chamo_offline_mail = hosturl + 'receive_mail.php';
  var chamo_file_download = hosturl + 'download.php';
  // static file uri
  var chamo_css = staticfilehost + 'chamo.' + _chaq['device'] + '.css?ver=20170216';
  var chamo_audio_operator_post = staticfilehost + 'common/audio/button01';
  var chamo_email_imgurl= staticfilehost + 'common/img/email50.gif';
  var chamo_sm_imgurl = new Image(), chamo_sm_unread_imgurl = new Image(), chamo_sm_read_imgurl = new Image(), chamo_sm_offline_imgurl = new Image();
  var chamo_loading_imgurl = new Image();
  chamo_loading_imgurl.src = staticfilehost + 'common/img/loader.gif';     // ローディング画像
     chamo_sm_imgurl.src = staticfilehost + 'common/img/chamo_sm.gif';       // 待機時
   chamo_sm_unread_imgurl.src= staticfilehost + 'common/img/chamo_sm.gif';// 未読あり
   chamo_sm_read_imgurl.src = staticfilehost + 'common/img/chamo_sm.gif';// 未読なし
   chamo_sm_offline_imgurl.src = staticfilehost + 'common/img/chamo_sm_offline.gif';   // オフライン
    /*** Settings (ms) ***/
  var TimerInterval = 10 * 1000;
  var TimerIntervalMax = 30 * 1000;
  var TimerIntervalBlur = 20 * 1000;
  var TimerIntervalBlurMax = 60 * 1000;
  var TimerIntervalOffline = 150 * 1000;
  var TimerExtendNext = 10;
  var TimerExtendMagni = 2;

  var bot_useragents = ['Y!J-SRD','Y!J-MBS1.0','Yahoo! Slurp','Yahoo! DE Slurp','Googlebot','adsence-Google','Mediapartners','msnbot','bingbot','Hatena','MicroAd','Baidu','MJ12bo','Steeler','YodaoBot','OutfoxBot','Pockey','psbot','Yeti','Websi','Wget','NaverBot','BecomeBot','heritr','DotBot','Twiceler','ichiro','archive.org_bot','YandexBot','ICC-Crawler','SiteBot','TurnitinBot','Purebot','BingPreview'];
;  // jQuery Ajax Setup //
  $.ajaxSetup({
    timeout: 3000
  });

  //////// Class : ChatMessage ////////
  var ChatMessage = function(id, code, subcode, info, date, speaker, roomid) {
    this.id = id;
    this.code = code;
    this.subcode = subcode;
    this.info = info;
    this.date = date;
    this.speaker = speaker;
    this.roomid = roomid;
  };
  ChatMessage.prototype.toArray = function() {
    return {
      'id': this.id,
      'code': this.code,
      'subcode': this.subcode,
      'info': this.info,
      'date': this.date,
      'speaker': this.speaker,
      'roomid': this.roomid,
    };
  };

  //////// Model ////////
  var cm = {
    socket: null,
    userID: null,
    userhash: null,
    roomid: null,
    isUserScalable: 'undefined',
    isLogLoaded: false,
    viewportWidth: 0,
    originalViewport: [],
    init: function() {
      // initialize properties
      disp_setting = settingVersionAbsorber(disp_setting);
      cm.timers = {};
      cm.triggerManager = null;
      cm.account = {};
      cm.status = {
        roomid: null,
        isHide: false,
        isOfflineform: false,
        window: CHAMO_DISPLAY_WAITING,
        display: null,
        isExitTriggerCalled: false,
        num_unread: 0,
        hide_end: 0,
        inbusiness: true
      };
      cm.user = {};
      cm.operators = {};
      cm.lastUpdate = 0;
      cm.lastmessageid = 0;
      cm.user_viewed_msgid = 0;
      cm.op_viewed_msgid = 0;
      cm.log = [];
      cm.device = null;
      cm.browser = null;
      cm.onExitTriggers = [];
      cm.isWindowFocus = true;
      cm.isPosting = false;
      cm.isCVsent = false;
      cm.isLocalStorageOK = null;
      cm.isShown = false;
      cm.isXdr = ((window.XDomainRequest) ? 1 : 0); // IE8,9;
      cm.roominfo = {
        time_start: 0,
        time_inpage: 0,
        time_user_first_spoke: 0,
        time_user_last_spoke: 0,
        triggered: [],
        visitno: 0,
        flag: {},
        referer: null
      };
      cm.chatlog_offset = 0;
      cm.isAndroid2x = null;
      cm.isAndroid3x = null;

      // if called in iframe, return false;
      // ToDo 特別対応
      if (accountID != 1002 && accountID != 1003 && accountID != 1787 && accountID != 1882 && accountID != 2113) { 
        if (window != parent) { return false; }
      }
      //if (window != parent) return false;
      cm.device = cm.getDevice();
      cm.browser = cm.getBrowser();
      cm.user.state = CHAMO_STATE_ONLINE;
      cm.userID = cm.dataGet('userid');
      cm.userhash = cm.dataGet('userhash');
      cm.operators = (cm.dataGet('operators')) || {};
      //cm.log = (cm.dataGet('log')) ? cm.dataGet('log') : [];

      cm.isAndroid2x = (navigator.userAgent.search(/Android 2.[123]/) != -1);
      cm.isAndroid3x = (navigator.userAgent.search(/Android 3.[123]/) != -1);

      // 古いAndroidではLinQを動作させない
      if (cm.isAndroid2x || cm.isAndroid3x) {
        myconsolelog('not supported device');
        return false;
      }

      // クローラの場合はアクセスさせない
      var isBot = (function(str, needles) {
        var inString = false;
        $.each(needles, function(_index, needle) {
          if (str.indexOf(needle) != -1) {
            inString = true;
          }
        });
        return inString;
      })(navigator.userAgent, bot_useragents);
      if (isBot) return false;

      // googleweblight経由の場合はアクセスさせない
      if (navigator.userAgent.indexOf('googleweblight') != -1) {
        return false;
      }

      cm.triggerManager = new TriggerManager();

      // 拡大が可能かどうかの判定
      if (cm.isUserScalable == 'undefined') {
        cm.isUserScalable = true;
        $('meta').filter(function() {
          return (this.name.toLowerCase().indexOf('viewport') != -1);
        }).each(function() {
          if (!$(this).attr('content')) return;
          var content = $(this).attr('content').toLowerCase();
          cm.originalViewport[cm.originalViewport.length] = content;
          //if (content.indexOf('initial-scale=1') != -1) {
          //  cm.isUserScalable = false;
          //  return false;
          //}
          if (content.indexOf('user-scalable=0') != -1) {
            cm.isUserScalable = false;
          }
          if (content.indexOf('user-scalable=no') != -1) {
            cm.isUserScalable = false;
          }
          if (content.indexOf('maximum-scale') != -1 &&
              content.indexOf('minimum-scale') != -1) {
            // なぜAndroidだけ例外？？
            //if (cm.device != CHAMO_DEVICE_ANDROID) {
                content.match(/maximum-scale=([0-9\.]+)/i);
                var maximum = RegExp.$1;
                content.match(/minimum-scale=([0-9\.]+)/i);
                var minimum = RegExp.$1;
                if (maximum == minimum) {
                    cm.isUserScalable = false;
                }
            //}
            if (content.indexOf('maximum-scale=0.5') != -1 &&
                content.indexOf('minimum-scale=0.5') != -1) {
              // ai-amore用
              cm.isUserScalable = false;
            }
          }
          //if (content.indexOf('maximum-scale=1') != -1 &&
          //    content.indexOf('minimum-scale=1') != -1) {
          //  cm.isUserScalable = false;
          //  return false;
          //}
          if (content.indexOf('width') != -1) {
            if (content.indexOf('device-width') != -1) {
              cm.viewportWidth = 'device-width';
            } else {
              content.match(/width=([0-9]+)/i);
              cm.viewportWidth = parseInt(RegExp.$1);
            }
          }
        });
      }

      cm.roomid = cm.dataGet('roomid');
      timeline.push({
        code: 'system',
        subcode: 'user_inroom',
        info: {
          'title': document.title,
          'url': document.URL,
          'lang': navigator.language,
          'appv': navigator.appVersion,
          'swidth': screen.width,
          'sheight': screen.height,
          'referer': document.referrer
        }
      });
      cm.addStylesheet();
      timeline.start();
      $(window).on('blur', function() {
        cm.isWindowFocus = false;
        timeline.initTimerInterval();
      });
      $(window).on('focus', function() {
        if (!cm.isWindowFocus) {
          cm.isWindowFocus = true;
          cm.updateChat();
        }
      });
    }, // init終わり
    isStorageSupported: function() {
      return window.localStorage ? (function() {
        try {
          var checkKey = '__CHAMO_WEB_STORAGE_CHECK__';
          window.localStorage.setItem(checkKey, 1);
          window.localStorage.getItem(checkKey);
          return true;
        } catch (e) {
          return false;
        }
      })() : false;
    },
    dataSet: function(key, value) {
      if (cm.isLocalStorageOK == null) {
       cm.isLocalStorageOK = cm.isStorageSupported();
      }
      if (cm.isLocalStorageOK) {
        localStorage.setItem(key, JSON.stringify(value));
      } else {
        setCookie(key, JSON.stringify(value));
      }
      return;
    },
    dataGet: function(key) {
      if (cm.isLocalStorageOK == null) {
        cm.isLocalStorageOK = cm.isStorageSupported();
      }
      if (cm.isLocalStorageOK) {
        return JSON.parse(localStorage.getItem(key));
      } else {
        var cook = getCookie(key);
        if (cook) {
          return JSON.parse(cook);
        } else {
          return null;
        }
      }
    },
    saveState: function() {
      cm.status.roomid = cm.roomid;
      cm.status.user_viewed_msgid = cm.user_viewed_msgid;
      cm.dataSet('status', cm.status);
    },
    loadState: function() {
      var status = cm.dataGet('status');
      if (status) {
        if (status.roomid == cm.roomid) {
          cm.status = status;
          //cm.user_viewed_msgid = status.user_viewed_msgid;
          cm.status.num_unread = 0;
        }
      }
    },
    callBeforeFirstSend: function(type) {
      if (!cm.isCVsent) {
        // Analytics
        if (type === 'chat') {
          googleAnalyticsEventPush(CHAMO_SERVICE_NAME,
              'チャット問い合わせ', document.title, 1);
        } else if (type === 'form') {
          googleAnalyticsEventPush(CHAMO_SERVICE_NAME + '-Mail',
              'メール問い合わせ', document.title, 1);
        }
        // Microad Blade
        if (extra_options && extra_options.microadBlade) {
          microadBladeCV(extra_options.microadBlade);
        }
      }

      // Original Function
      if (typeof window.chamoEventCall === 'function') {
        var options = {
          type: type,
          isSent: cm.isCVsent
        };
        window.chamoEventCall(options);
      }

      cm.isCVsent = true;
    },
    analytics: function() {
      if (!cm.isCVsent) {
        if (typeof _gaq !== 'undefined') {
          _gaq.push(['_trackEvent', CHAMO_SERVICE_NAME,
              'チャット問い合わせ', document.title, 1]);
        } else if (typeof ga !== 'undefined') {
          ga('send', 'event', CHAMO_SERVICE_NAME,
              'チャット問い合わせ', document.title, 1);
        }
        cm.isCVsent = true;
      }
    },
    isChatting: function() {
      try {
       if (cm.isWindowFocus &&
           (cm.account.state == CHAMO_STATE_ONLINE) &&
           (cm.status.window == CHAMO_DISPLAY_OPEN)) {
         return true;
       }
      } catch (e) {
         return false;
      }
      return false;
    },
    setOperatorInfo: function(operatorid, operator) {
      this.operators[operatorid] = operator;
      this.dataSet('operators', this.operators);
    },
    displayChat: function(name) {
      cv.hideChat(cm.status.display, cm.device);
      cm.status.display = name;
      if (!cm.status.isHide) {
        cm.saveState();
        cv.showChat(name, cm.device);
      }
      // trigger scroll event for IE quirks mode to change the pos
      $(window).triggerHandler('scroll');
    },
    updateChat: function(forceUpdate) {
      var new_display = cm.getDisplayname();

      //myconsolelog('updateChat: ' + new_display);
      // If display is updated or first view, change the view
      if (forceUpdate || cm.status.display != new_display || !cm.isShown) {
        cm.displayChat(new_display);
        timeline.initTimerInterval();
        cm.isShown = true;
      } else if (new_display === 'invisible') {
        cm.isShown = false;
      }
        // ユーザーがどのメッセージまで見たかをサーバーに送る
      if (((cm.status.display == 'chatting') ||
          (cm.status.display == 'chatting_maximum')) &&
          cm.lastmessageid > cm.user_viewed_msgid && cm.isWindowFocus) {
        clearTimeout(cm.timers.user_viewed_msgid);
        cm.timers.user_viewed_msgid = window.setTimeout(function() {
          if (cm.user_viewed_msgid > cm.lastmessageid) return;
          cm.user_viewed_msgid = cm.lastmessageid;
          timeline.push({
            code: 'system',
            subcode: 'user_viewed_msgid',
            info: cm.user_viewed_msgid
          });
        }, 100);
      }
      if (new_display == 'chatting' || new_display == 'chatting_maximum') {
        cm.status.num_unread = 0;
      }
      cm.saveState();
      cv.updateDOM();
      inputStateObserver.notify();
    },
    getDisplayname: function() {
      if (cm.account.state == CHAMO_STATE_ONLINE) {
        switch (cm.status.window) {
          case CHAMO_DISPLAY_WAITING:
          default:
            return 'waiting';
            break;
          case CHAMO_DISPLAY_OPEN:
            return 'chatting';
            break;
          case CHAMO_DISPLAY_MAXIMUM:
            return 'chatting_maximum';
            break;
        }
      } else if (cm.account.state == CHAMO_STATE_OFFLINE) {
        $(window).off('beforeunload');
        if (cm.account.operator_num == 0 &&
            cm.account['nooperator_behavior'] === CHAMO_NOOPERATOR_BEHAVIOR_INVISIBLE) {
          return 'invisible';
        }
        switch (cm.status.window) {
          case CHAMO_DISPLAY_WAITING:
          default:
            return 'offline_waiting';
            break;
          case CHAMO_DISPLAY_OPEN:
            return 'offline_message';
            break;
          case CHAMO_DISPLAY_MAXIMUM:
            //return 'offline_message_maximum';
            return 'offline_message';
            break;
        }
      }
    },
    chatState: function(state) {
      if (cm.account.state != state) {
        /*
        if (state == CHAMO_STATE_ONLINE) {
          // オペレータがオンラインになった時
          cm.displayChat('chatting');
        } else {
          // オペレータがオフラインになった時
          cm.displayChat('offline_waiting');
        }
        */
        cm.account.state = state;
        cm.updateChat();
      }
    },
    getDevice: function() {
      var agent = navigator.userAgent.toLowerCase();
      if (agent.search(/iphone/) != -1) {
        return CHAMO_DEVICE_IPHONE;
      } else if (agent.search(/ipod/) != -1) {
        return CHAMO_DEVICE_IPHONE;
      } else if (agent.search(/ipad/) != -1) {
        return CHAMO_DEVICE_IPAD;
      } else if (agent.search(/android/) != -1) {
        return CHAMO_DEVICE_ANDROID;
      } else {
        return CHAMO_DEVICE_PC;
      }
    },
    getBrowser: function() {
      var name = 'unknown';
      var ua = navigator.userAgent.toLowerCase();
      if (ua.indexOf('chrome') != -1) {
        name = 'Chrome';
      } else if (ua.indexOf('safari') != -1) {
        name = 'Safari';
      } else if (ua.indexOf('opera') != -1) {
        name = 'Opera';
      } else if (ua.indexOf('firefox') != -1) {
        name = 'Firefox';
      } else if (ua.indexOf('msie') != -1) {
        if (ua.indexOf('msie 6.') != -1) {
          name = 'IE 6';
        } else if (ua.indexOf('msie 7.') != -1) {
          name = 'IE 7';
        } else if (ua.indexOf('msie 8.') != -1) {
          name = 'IE 8';
        } else if (ua.indexOf('msie 9.') != -1) {
          name = 'IE 9';
        } else if (ua.indexOf('msie 10.') != -1) {
          name = 'IE 10';
        } else {
          name = 'IE';
        }
      } else if (ua.indexOf('trident/7') != -1) {
        name = 'IE 11';
      }
      return name;
    },
    addStylesheet: function() {
      $('<link>', {
        'href': chamo_css,
        'rel': 'stylesheet',
        'type': 'text/css'
      }).appendTo('head');
    },
    setExitTrigger: function(data) {
      if (cm.onExitTriggers.length == 0 && !cm.status.isExitTriggerCalled) {
        $('input[type=image],input[type=submit]').one('click', function() {
          $(window).off('beforeunload');
        });
        $(window).on('beforeunload', function() {
          cm.status.window = CHAMO_DISPLAY_OPEN;
          cm.updateChat();
          // Set status to trigger called state
          cm.status.isExitTriggerCalled = true;
          cm.saveState();
          // Disable beforeunload
          $(window).off('beforeunload');
          // Set the dialog message
          var msg = '';
          var len = cm.onExitTriggers.length;
          for (var i = 0; i < len; i++) {
            var data = cm.onExitTriggers[i];
            if (data.subcode == 'message') {
              msg = data.info;
              break;
            }
          }
          if (!msg) msg = Localizer.getValue('trigger-exit-default');
          return msg;
        });
      }
      data.code = 'trigger';
      cm.onExitTriggers[cm.onExitTriggers.length] = data;
    },
    // 投稿をサーバーに送る
    post: function(data) {
      if ($.trim(data) === '') { return false; }
      cm.roominfo.flag[FLAG_USER_SPOKE] = true;
      var genkey = correctedDate().getTime();
      var msg = new ChatMessage(
          null, 'user_post', genkey, data, 0, cm.userID, cm.roomid
      );
      //cm.log[cm.log.length] = msg;
      //cv.show_message(msg);
      cm.user.state = CHAMO_STATE_ONLINE;
      timeline.push(msg.toArray());
    },
    // 選択肢を選んだことをサーバーに送る
    post_selected: function(_name, _val) {
      cm.roominfo.flag[FLAG_USER_SPOKE] = true;
      var msg = new ChatMessage(
          0, 'option_selected', _name, _val, 0, cm.userID, cm.roomid
      );
      cm.user.state = CHAMO_STATE_ONLINE;
      timeline.push(msg.toArray());
    },
    department_selected: function(_name, _val, _text) {
      //cm.roominfo.flag[FLAG_USER_SPOKE] = true;
      // infoにdepartmentidをセット
      var msg = new ChatMessage(
          0, 'department_selected', _name, _val, 0, cm.userID, cm.roomid
      );
      cm.user.state = CHAMO_STATE_ONLINE;
      timeline.push(msg.toArray());
    },
    getPreviousChat: function() {
      var msg = new ChatMessage(
          0, 'past_chatlog', '', cm.chatlog_offset, 0, cm.userID, cm.roomid
      );
      timeline.push(msg.toArray());
    },
    /***
     // ドキュメントを書き換えたら削除
    chat_input_start: function() {
      cm.changeInputState(CHAMO_INPUT_START);
    },
    chat_input_end: function() {
      cm.changeInputState(CHAMO_INPUT_END);
    },
    changeInputState : function(state) {
      clearTimeout(cm.timers.change_input_state);
      cm.timers.change_input_state = window.setTimeout(function() {
        if (cm.user.input_state == state) return;
        cm.user.input_state = state;
        timeline.push({
          code: 'system',
          subcode: 'user_input_state',
          info: state
        });
      }, 500);
    }
    ***/
    sendUserInput: function(inputText) {
      timeline.push({
        code: 'system',
        subcode: 'user_input',
        info: (inputText === CHAMO_INPUT_END) ? CHAMO_INPUT_END : inputText
      });
    },
    // 営業時間外は非表示にする
    checkBusinessHours: function() {
      // 最初に祝日・指定日判定は除く
      if (!cm.account.only_business_hours &&
         (cm.account.bs_merged_holidays !== undefined && cm.account.bs_merged_holidays.count > 0)) return;
      if (!cm.account.bs) return;
      var inBusiness = inBusinessHours(cm.account);
      if (!inBusiness && cm.account.inbusiness_behavior === 'form') {
        cm.account.state = CHAMO_STATE_OFFLINE;
      }
      if (cm.status.inbusiness !== inBusiness) {
        // 営業時間内・外が変わった場合
        cm.status.inbusiness = inBusiness;
        if (inBusiness) {
          // 営業開始したら表示
          cm.show('connect');
          cm.sioStart();
        } else {
          // 営業終了したら非表示
          if (cm.account.inbusiness_behavior === 'form') {
            cm.status.isOfflineform = true;
          } else {
            var blinkDom = cv.getBlinkDom();
            // タイトルを元に戻してから消す
            if (blinkDom) {
              $(blinkDom.waiting_title).html(cm.account.title_mini);
              $(blinkDom.chatting_title).html(cm.account.title);
            }
            cm.hide();
          }
          // 「チャットを隠す」タイマーも削除
          if (cm.timers['hide_button_timer']) {
            clearTimeout(cm.timers['hide_button_timer']);
            cm.timers['hide_button_timer'] = null;
          }
          // 終了時間タイマーも削除
          if (cm.timers['blink_message_timer']) {
            clearTimeout(cm.timers['blink_message_timer']);
            cm.timers['blink_message_timer'] = null;
          }
        }
      }
      // 終了時間タイマーを設定
      if (!cm.timers['blink_message_timer']) {
        var day = correctedDate().getDay() || 7;
        for (var i = 0; i < cm.account.bs[day - 1].length; i++) {
          var left = whatMoreMinutes(cm.account.bs[day - 1][i].hour2,
              cm.account.bs[day - 1][i].min2 + 1);
          if (left > 0 && left <= 5) {
            if (!inBusinessHours(cm.account, 5)) {
              cm.startBlinkMessage();
            }
            break;
          }
        }
      }
    },
    startBlinkMessage: function() {
      var blinkDom = cv.getBlinkDom();

      if (!blinkDom) {
        return;
      }
      var $waiting_dom = $(blinkDom.waiting_title),
          $chatting_dom = $(blinkDom.chatting_title),
          waiting_title = $waiting_dom.html(),
          chatting_title = $chatting_dom.html();

      var blink1 = function() {
        var blinkMes = '';
        var day = correctedDate().getDay() || 7;
        for (var i = 0; i < cm.account.bs[day - 1].length; i++) {
          var left = whatMoreMinutes(cm.account.bs[day - 1][i].hour2,
              cm.account.bs[day - 1][i].min2 + 1);
          if (left > 0 && left <= 5) {
            blinkMes = Localizer.sprintf('widget-chatend-x-minute', left);
            break;
          }
        }
        $waiting_dom.html(blinkMes);
        $chatting_dom.html(blinkMes);
        cm.timers['blink_message_timer'] = window.setTimeout(blink2, 2000);
      };
      var blink2 = function() {
        $waiting_dom.html(waiting_title);
        $chatting_dom.html(chatting_title);
        cm.timers['blink_message_timer'] = window.setTimeout(blink1, 4000);
      };
      blink1();
    },
    // ウィジェットを表示する
    show: function(options) {
      var options_array = (options) ? options.split(' ') : [];
      cm.status.isHide = false;
      cm.status.hide_end = 0;
      cm.updateChat(true);
      if (options_array.indexOf('connect') !== -1) {
        timeline.valid = true;
        if (!cm.account.nochat) {
          cm.sioStart();
        }
      }
    },
    // ウィジェットを非表示にする
    hide: function(options) {
      var options_array = (options) ? options.split(' ') : [];
      cm.status.isHide = true;
      cm.updateChat(true);
      if (options_array.indexOf('disconnect') !== -1) {
        timeline.valid = false;
      }
    },
    // 「隠す」機能の初期化
    hide_init: function() {
      var _now = correctedDate().getTime();
      if (cm.status.hide_end == 'endless') {
        // 完全に非表示
        cm.hide('disconnect');
        //timeline.valid = false;
      } else if (cm.status.hide_end > _now) {
        // 非表示時間が残っている場合
        cm.hide();
        cm.timers['hide_button_timer'] = window.setTimeout(function() {
          cm.show();
          //cm.status.isHide = false;
          //cm.updateChat(true);
        }, (cm.status.hide_end - _now));
      } else if (cm.status.hide_end) {
        // 「隠す」機能が使われていて、かつ非表示時間が過ぎている場合
        cm.show();
        //cm.status.isHide = false;
        //cm.updateChat(true);
      }
    },
    // ユーザーが「隠す」ボタンを押した場合
    hide_set: function(hide_time) {
      //cm.status.isHide = true;
      if (hide_time > 0) {
        cm.status.hide_end = correctedDate().getTime() + (hide_time * 60 * 1000);
        cm.timers['hide_button_timer'] = window.setTimeout(function() {
          cm.show();
          //cm.status.isHide = false;
          //cm.updateChat(true);
        }, (hide_time * 60 * 1000));
      } else {
        cm.status.hide_end = 'endless';
      }
      cm.hide();
      //cm.updateChat(true);
    },
    // ユーザーの状態を変更
    userStatus: function(status) {
      cm.user.state = status;
      timeline.push({
        code: 'system',
        subcode: 'status',
        state: cm.user.state
      });
    },
    // Ajax通信完了時
    update: function(data_array) {
      if (cm.status.isExitTriggerCalled && cm.onExitTriggers.length) {
        // on exit triggers
        data_array = data_array.concat(cm.onExitTriggers);
        cm.onExitTriggers = [];
      }
      // debug
      //myconsolelog(data_array);
      //myconsolelog(cm.roominfo.flag);
      var isMesform = false;
      var isNewPost = false;
      var isWelcome = false;
      var isExpired = false;
      var isOffline = false;
      var isChatlog = false;
      var isBanned = false;
      var isFirstPost = false;
      $.each(data_array, function(_index, data) {
        if ((!!data.date) && (data.date > cm.lastUpdate)) {
          cm.lastUpdate = data.date;
        }
        if ((!!data.id) && (data.id > cm.lastmessageid)) {
          cm.lastmessageid = data.id;
        }
        switch (data.code) {
          case 'operator_post':
          case 'operator post':
            if (cm.log.length == 0) { isFirstPost = true; }
            var msg = new ChatMessage(
                data.id, 'operator_post', null, data.info,
                data.date, data.operatorid, data.roomid
            );
            cm.log[cm.log.length] = msg;
            //cm.dataSet('log', cm.log);
            cv.show_message(msg);
            // 状態をオンラインに
            cm.account.state = CHAMO_STATE_ONLINE;
            isNewPost = true;
            cm.roominfo.flag[FLAG_OPERATOR_SPOKE] = true;
            if (msg.id > cm.user_viewed_msgid) {
              cm.status.num_unread++;
            }
            if (!isChatlog && $chamo.api && $chamo.api.event) {
              $chamo.api.event.trigger('operator_send', data.info.message);
            }
            break;
          case 'operator_file':
          case 'operator file':
            if (cm.log.length == 0) { isFirstPost = true; }
            var msg = new ChatMessage(
                data.id, data.code, data.subcode, data.info,
                data.date, data.operatorid, data.roomid
            );
            cm.log[cm.log.length] = msg;
            //cm.dataSet('log', cm.log);
            cv.show_message(msg);
            // 状態をオンラインに
            cm.account.state = CHAMO_STATE_ONLINE;
            isNewPost = true;
            cm.roominfo.flag[FLAG_OPERATOR_SPOKE] = true;
            if (msg.id > cm.user_viewed_msgid) {
              cm.status.num_unread++;
            }

            info = JSON.parse(data.info);

            // 画像thumbnail取得
            switch (info.type) {
              case 'image/jpeg':
              case 'image/png':
              case 'image/gif':
                timeline.push({
                  code: 'user_getfile',
                  subcode: info.fileId,
                  info: info.type,
                });
                break;
            }
            break;
          case 'user_getfile':
            // 画像thumbnail取得
            if (data.info) {
              cv.set_image_data(data);
            }
            break;
          case 'user_post':
          case 'user post':
          case 'option_selected':
          case 'option selected':
            //if (isWelcome) {
              if (cm.log.length == 0) { isFirstPost = true; }
              var msg = new ChatMessage(
                  data.id, data.code, data.subcode, data.info,
                  data.date, data.userid, data.roomid
              );
              cm.log[cm.log.length] = msg;
              //cm.dataSet('log', cm.log);
              cv.show_message(msg);
              if (!cm.roominfo.time_user_first_spoke) {
                cm.roominfo.time_user_first_spoke = data.date;
              }
              cm.roominfo.time_user_last_spoke = data.date;
            //}
            if (!cm.isLogLoaded) {
              cm.isCVsent = true;
            }
            break;
          case 'department_selected':
          case 'department_selected_log':
            var attrs = data.subcode.split(':');
            var isPastchat = cm.roomid != data.roomid;
            cv.disable_options(attrs[0], data.subcode, isPastchat);
            break;
          case 'system':
            switch (data.subcode) {
              case 'welcome':
                correctedDate.initialize(data.date);
                cm.userID = data.userid;
                cm.userhash = data.userhash;
                // loginhashユーザーで書き込んでしまうと通常ページでも
                // loginページになってしまう。
                if (!loginhash) {
                  cm.dataSet('userid', data.userid);
                  cm.dataSet('userhash', data.userhash);
                }
                cm.roomid = data.roomid;
                cm.dataSet('roomid', cm.roomid);
                //cm.account = data.info;
                // アカウント情報の読み込み
                $.extend(true, cm.account, disp_setting);
                // 営業時間の変換
                cm.account.state = data.info;
                cm.account.language = cm.account.language || 'ja';
                Localizer.setLanguage(cm.account.language);
                cv.init();//cm.updateChat();
                if (cm.account.nochat) {
                  if (_chaq['device'] == 'pc') {
                    var poweredby = $('.chamo_footer .chamo-poweredby').
                        parent().css({'left': 'auto', 'right': '20px'});
                    $('#chamo-chatting').append(poweredby);
                  } else if (_chaq['device'] == 'android') {
                    var poweredby = $('<div style="position: absolute; bottom: 0; left: 10px;"><a href="' +
                        refferel +
                        '" target="_blank" style="font-size:0.6em !important;text-decoration:none; color:#888;">powered by Chamo</a></div>');
                    //$('#chamo-chatting').append(poweredby.clone());
                    cv.chamo.chatting_maximum.append(poweredby.clone());
                  } else {
                    var poweredby = $('<div style="position: absolute; bottom: 0; left: 10px;"><a href="' +
                        refferel +
                        '" target="_blank" style="font-size:0.6em !important;text-decoration:none; color:#888;">powered by Chamo</a></div>');
                    //$('#chamo-chatting').append(poweredby.clone());
                    cv.chamo.chatting_maximum.css({
                      top: 'auto', bottom: 0
                    }).append(poweredby.clone());
                  }
                  cv.chamo.chatting.find('.chamo_footer, .-chamo-chat-footer, #chamo-chatting-footer').hide();
                  if (cv.chamo.chatting_maximum) {
                    cv.chamo.chatting_maximum.find('.chamo_footer, .-chamo-chat-footer, #chamo-chatting-footer').hide();
                  }
                  cv.chamo.statusbar.hide();
                }

                cm.status.inbusiness = inBusinessHours(cm.account);
                cm.account.visibility = checkVisibility(cm.account);
                if (cm.account.visibility == 'invisible') {
                  cm.status.isHide = true;
                } else {
                  cm.loadState();
                  cm.hide_init();
                  if (cm.status.window == CHAMO_DISPLAY_MAXIMUM) {
                    cm.status.window = CHAMO_DISPLAY_OPEN;
                  }
                  if (cm.account.nochat) {
                    // チャットしない場合はsocket.io接続しない
                    timeline.push({
                      code: 'system',
                      subcode: 'requestlog',
                      info: cm.lastmessageid
                    });
                  } else {
                    // Socket.io開始
                    // 負荷対策　とりあえずオフライン時はWebSocket接続しない
                    if (cm.account.state != CHAMO_STATE_OFFLINE) {
                      cm.sioStart();
                    }
                  }
                }
                isWelcome = true;
                cm.checkBusinessHours();
                break;
              case 'chatlog':
                isChatlog = true;
                break;
              case 'past_chatlog':
                isNewPost = false;
                if (data.info) { // data.info => room.start
                  cv.flush_past_chatlog_buffer(data.info);
                } else {
                  // 過去チャットルームが見つからなかった場合
                  cv.hidePastChatLink();
                }
                break;
              case 'refresh_room':
              case 'refresh room':
                timeline.valid = true;
                timeline.sending = false;
                cm.userID = data.userid;
                cm.userhash = data.userhash;
                cm.roomid = data.roomid;
                cm.dataSet('userid', data.userid);
                cm.dataSet('userhash', data.userhash);
                cm.dataSet('roomid', cm.roomid);
                cm.init();
                //myconsolelog('refresh room : ' + cm.roomid);
                //cm.status.window = CHAMO_DISPLAY_OPEN;
                if (cm.socket) {
                  cm.socket.emit('user inroom', {
                    userid: cm.userID,
                    userhash: cm.userhash,
                    roomid: cm.roomid,
                    accountid: accountID
                  });
                } else {
                  if (cm.account.nochat) {
                    // チャットしない場合はsocket.io接続しない
                    timeline.push({
                      code: 'system',
                      subcode: 'requestlog',
                      info: cm.lastmessageid
                    });
                  } else {
                    // Socket.io開始
                    cm.sioStart();
                  }
                }
                /*
                cm.log  = [];
                cm.roomid  = data.roomid;
                timeline.push({
                  code: 'system',
                  subcode: 'user_inroom',
                  info: {
                    'title': document.title,
                    'url': document.URL,
                    'lang': navigator.language,
                    'appv': navigator.appVersion,
                    'swidth': screen.width,
                    'sheight': screen.height
                  }
                });
                */
                break;
              /*
              case 'roominfo':
                cm.roominfo = data.info;
                cm.user_viewed_msgid = data.info.user_viewed_msgid;
                if (display_past_chatlog) {
                  cv.addPastChatLink();
                }
                break;
              case 'roomflag':
                cm.roominfo.flag = data.info;
                break;
                */
              case 'roominfo':
                cm.user_viewed_msgid = data.info.user_viewed_msgid;
                var isOperatorSpoke = !!cm.roominfo.flag[FLAG_OPERATOR_SPOKE];
                var isUserSpoke = !!cm.roominfo.flag[FLAG_USER_SPOKE];
                cm.roominfo = data.info;
                cm.roominfo.flag[FLAG_OPERATOR_SPOKE] = cm.roominfo.flag[FLAG_OPERATOR_SPOKE] || isOperatorSpoke;
                cm.roominfo.flag[FLAG_USER_SPOKE] = cm.roominfo.flag[FLAG_USER_SPOKE] || isUserSpoke;
                if (display_past_chatlog) {
                  cv.addPastChatLink();
                }
                break;
              case 'roomflag':
                var isOperatorSpoke = !!cm.roominfo.flag[FLAG_OPERATOR_SPOKE];
                var isUserSpoke = !!cm.roominfo.flag[FLAG_USER_SPOKE];
                cm.roominfo.flag = data.info;
                cm.roominfo.flag[FLAG_OPERATOR_SPOKE] = cm.roominfo.flag[FLAG_OPERATOR_SPOKE] || isOperatorSpoke;
                cm.roominfo.flag[FLAG_USER_SPOKE] = cm.roominfo.flag[FLAG_USER_SPOKE] || isUserSpoke;
                break;
              case 'operator_inroom':
              case 'operator inroom':
                cm.setOperatorInfo(data.operatorid, data.info);
                break;
              case 'bulletin':
                if (cm.account.state === -1 && data.info.state === 1) {
                  cm.sioStart();
                }
                //cm.userID = data.userid;
                cm.account.state = data.info.state;
                cm.account.operator_num = data.info.operator_num;
                if (data.info.op_viewed_msgid > cm.op_viewed_msgid) {
                  cm.op_viewed_msgid = data.info.op_viewed_msgid;
                  if (!cm.account.not_readnotif) {
                    cv.update_op_viewed();
                  }
                }
                cm.checkBusinessHours();
                //cm.updateChat();//cm.chatState(data.info.state);
                break;
              case 'operator_state':
              case 'operator state':
                cm.account.state = data.info.state;
                cm.account.operator_num = data.info.operator_num;
                if (cm.account.state == CHAMO_STATE_ONLINE) {
                  timeline.push({
                    code: 'system',
                    subcode: 'requestlog',
                    info: cm.lastmessageid
                  });
                }
                break;
              case 'operator_input_state':
              case 'operator input state':
                cm.account.operator_inputting = data.info;
                break;
              case 'op_viewed_msgid':
              case 'op viewed msgid':
                if (data.info > cm.op_viewed_msgid) {
                  cm.op_viewed_msgid = data.info;
                  if (!cm.account.not_readnotif) {
                    cv.update_op_viewed();
                  }
                }
                break;
              case 'receive':
                cm.account.state = data.info.state;
                cm.roominfo.time_user_last_spoke = data.date;
                cv.chat_receive(data);
                cm.callBeforeFirstSend('chat');
                cm.triggerManager.onSend();
                if ($chamo.api && $chamo.api.event) {
                  $chamo.api.event.trigger('user_send', data.info.message);
                }
                break;
              case 'expired':
                isExpired = true;
                break;
              case 'banned':
                cm.status.isHide = true;
                isBanned = true;
                break;
              case 'unbanned':
                cm.status.isHide = false;
                cm.account.state = CHAMO_STATE_ONLINE;
                timeline.valid = true;
                isBanned = false;
                break;
              case 'triggers':
                //setTimeout(function() {
                //  cm.triggerManager.setTriggers(data.info);
                //}, 1000);
                //cm.triggerManager.setTriggers(data.info);
                myconsolelog('code: triggers');
                break;
              case 'reconnect_success':
                cm.reconnectSuccess();
                break;
            } // end system
            break;
          case 'trigger':
            switch (data.subcode) {
              case 'showform':
                // お問い合わせフォームを表示
                cm.status.isOfflineform = true;
                break;
              /*
              case 'chamo_hide':
              case 'chamo hide':
                // チャモを非表示にする
                cm.status.isHide = true;
                cm.displayChat();
                break;
              case 'chamo_show':
              case 'chamo show':
                // チャモを表示（非表示時のみ）
                cm.status.isHide = false;
                cm.displayChat();
                break;
              */
              case 'offline':
                // お問い合わせフォームを表示
                isOffline = true;
                break;
              case 'message':
                if (cm.log.length == 0) { isFirstPost = true; }
                // ToDoオンライン時・オフライン時それぞれの処理
                var msg = new ChatMessage(
                    data.id, 'trigger', null, data.info,
                    null, null, data.roomid
                );
                cm.log[cm.log.length] = msg;
                cv.show_message(msg);
                isNewPost = true;
                if (msg.id > cm.user_viewed_msgid) {
                  cm.status.num_unread++;
                }
                if (!isChatlog && $chamo.api && $chamo.api.event) {
                  $chamo.api.event.trigger('trigger_message', data.info.message);
                }
                break;
              case 'script':
                cm.addConversionTag(data.info);
                break;
              case 'department_list':
                if (cm.log.length == 0) { isFirstPost = true; }
                // ToDoオンライン時・オフライン時それぞれの処理
                var msg = new ChatMessage(
                    data.id, 'trigger', 'department_list', data.info,
                    null, null, data.roomid
                );
                cm.log[cm.log.length] = msg;
                cv.show_message(msg);
                isNewPost = true;
                if (msg.id > cm.user_viewed_msgid) {
                  cm.status.num_unread++;
                }
                break;
            }
            break; // end trigger
            /*
            case 'on_exit_trigger':
              cm.setExitTrigger(data);
              break;
            */
          case 'api':
            switch (data.subcode) {
              case 'operator_message':
              case 'operator message':
                if (cm.log.length == 0) { isFirstPost = true; }
                // ToDoオンライン時・オフライン時それぞれの処理
                var msg = new ChatMessage(
                    data.id, 'api', 'operator_message', data.info,
                    null, null, data.roomid
                );
                cm.log[cm.log.length] = msg;
                cv.show_message(msg);
                isNewPost = true;
                if (msg.id > cm.user_viewed_msgid) {
                  cm.status.num_unread++;
                }
                break;
              case 'department_list':
                break;
              default:
                break;
            }
            break;
          case 'sendmail':
            break;
          case 'error':    // ToDoエラー時処理
          default:
            myconsolelog('Server Error:');
            myconsolelog(data);
            break;
        } // end switch
      }); // end $.each
      if (isChatlog) {
        cv.unsetLoader();
        cm.triggerManager.setTriggers(account_triggers);
        cm.isLogLoaded = true;
      }
      if (isBanned) {
        cm.account.state = CHAMO_STATE_OFFLINE;
        cm.status.window = CHAMO_DISPLAY_WAITING;
        timeline.valid = false;
        cm.updateChat();
        cm.hide();
        cm.saveState();
      } else if (isExpired || isOffline) {
        cm.account.state = CHAMO_STATE_OFFLINE;
        cm.status.window = CHAMO_DISPLAY_WAITING;
        cm.status.isOfflineform = true;
        timeline.valid = false;
        cm.updateChat();
        cm.saveState();
      } else if (cm.status.isOfflineform) {
        // お問い合わせフォームを表示
        timeline.valid = false;
        cm.account.state = CHAMO_STATE_OFFLINE;
        cm.status.window = CHAMO_DISPLAY_OPEN;
        //cm.updateChat();
        //cm.chatState(CHAMO_STATE_OFFLINE);
        //cm.displayChat('offline_message');
        var tmp_userposts = [];
        $.each(cm.log, function(_index, msg) {
          //cm.log.forEach(function(msg){
          if (msg.code == 'user_post') {
            tmp_userposts[tmp_userposts.length] = msg.info;
          }
        });
        cv.set_messageform({'message': tmp_userposts.join("\n")});
        cm.saveState();
      } else if ((!isWelcome) && (!isChatlog) && isNewPost && cm.account && cm.account.state != CHAMO_STATE_OFFLINE) {
        // メッセージ受信時の通知処理（ウィンドウオープン）
        if ((cm.account.not_open_window == 2 && isFirstPost) ||   // 初回メッセージのみチャットウィンドウを開く
          (!cm.account.not_open_window)) {                  // 常にチャットウィンドウを開く(0) または undefined（デフォルト）
          // 最小化状態なら開く
          if (cm.status.window == CHAMO_DISPLAY_WAITING) {
            cm.status.window = CHAMO_DISPLAY_OPEN;
          }
        }
        // メッセージ受信時の通知処理（音）
        if (cm.account.beepnotif || typeof cm.account.beepnotif === 'undefined') {
          if (!cm.status.isHide && !isWelcome) {
            cv.play_audio(isWelcome);
          }
        }
      }
      if (isWelcome) {
        if (cm.status.isOfflineform) {
          cm.status.window = CHAMO_DISPLAY_WAITING;
        }
        // PCの初回はメッセージフォームを開く
        //if (cm.account.state == CHAMO_STATE_OFFLINE && cm.getDevice() == CHAMO_DEVICE_PC && !cm.dataGet('isFormOpened')) {
        //  cm.status.window = CHAMO_DISPLAY_OPEN;
        //  cm.dataSet('isFormOpened', 1);
        //}

        cm.lastmessageid = 0;
        // Loading
        cv.setLoader();
        /*
        var sio_success_func = function() {
          myconsolelog('check connection');
          if (cm.socket && cm.socket.connected_roomid == cm.roomid) {
            timeline.push({
              code: 'system',
              subcode: 'requestlog',
              info: 0
            });
          } else {
            setTimeout(sio_success_func, 500);
          }
        }
        sio_success_func();
        */
        cm.onChamoLoad();
      }
      cm.updateChat();
    }, // end update()
    sendError: function(data_array) {
      timeline.valid = false;
      cv.chat_send_error(data_array);
    },
    addConversionTag: function(tag) {
      var el = document.createElement('div');
      el.style.display = 'none';
      el.style.visibility = 'hidden';
      document.body.appendChild(el);
      postscribe(el, tag);
    },
    reconnect: function() {
      timeline.reconnect();
    },
    reconnectSuccess: function() {
      timeline.valid = true;
      timeline.sending = false;
      cv.clearStatusbar();
      cv.chat_reconnect_success();
    },
    send_offline_mail: function() {
      var $form = $('#chamo_offline_mail_form');
      // Check Required
      var isError = false;
      $form.find('.chamo-error-required').remove();
      $form.find('.chamo-required').each(function() {
        if (!$(this).val() || ($(this).hasClass('checkbox') &&
            !$(this).attr('checked'))) {
          $(this).addClass('chamo-error-form').on('focus', function() {
            $(this).removeClass('chamo-error-form');
          }).prev().before($('<span class="chamo-error-required">' +
              Localizer.getValue('messageform-required') + '</span>'));
          isError = true;
        }
      });
      // Check email validation
      // target: id="message[email]"
      $form.find('#message\\[email\\]').each(function() {
        var validateTargetValue = $(this).val();
        // see: https://www.w3resource.com/javascript/form/email-validation.php
        // 必須項目として扱われているので、未入力の場合バリデーション処理する
        // →未入力の場合は未入力ですと言う警告だけ表示する
        if (!isError && !/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/.test(validateTargetValue)) {
          $(this).addClass('chamo-error-form').on('focus', function() {
            $(this).removeClass('chamo-error-form');
          }).prev().before($('<span class="chamo-error-required">' +
              Localizer.getValue('messageform-email') + '</span>'));
          isError = true;
        }
      });
      if (isError) return false;
      var postdata = {
        'accountid': accountID,
        'userid': cm.userID,
        'userhash': cm.userhash,
        'roomid': cm.roomid,
        'form': $form.serializeArray(),
        'pagetitle': document.title,
        'pageurl': document.URL,
        'isXdr': cm.isXdr,
      };
      $submit = $form.find('input[type=submit]');
      $.ajax({
        // IEキャッシュ対策
        url: chamo_offline_mail + '?' + parseInt(correctedDate() / 1000),
        cache: false,
        data: postdata,
        beforeSend: function() {
          $submit.attr('disabled', 'disabled');
          $submit.val(Localizer.getValue('messageform-sending'));
        },
        success: function(data) {
          if (!(data instanceof Object)) {
            try {
              data = $.parseJSON(data);
            } catch (e) {
              myconsolelog('Error: invalid response');
              myconsolelog(e);
              myconsolelog(data);
            }
          }
          switch (data.code) {
            case 'success':
              $form.find('input:not(.checkbox), textarea').val('');
              $form.find('.checkbox').attr('checked', false);
              $submit.val(Localizer.getValue('messageform-send-success'));
              cv.show_offline_message_submitted();
              // Send event to Analytics
              cm.callBeforeFirstSend('form');
              break;
            case 'error':
            default:
              $submit.val(Localizer.getValue('messageform-failed'));
              myconsolelog(data.info);
              break;
          }
        },
        error: function(data) {
          // ToDo エラー処理
          $submit.val(Localizer.getValue('messageform-failed'));
          myconsolelog('Ajax Error: Cannot send Mail.');
          myconsolelog(data);
        }, complete: function(data) {
          $submit.removeAttr('disabled');
        }
      });
    },
    // called on chamo widget is loaded
    onChamoLoad: function() {
      if ($.isFunction(_chaq.onChamoLoad)) {
        _chaq.onChamoLoad();
      } else if ($.isArray(_chaq.onChamoLoad)) {
        $.each(_chaq.onChamoLoad, function(index, fn) {
          fn();
        });
      }
    },
    // socket.io
    sioStart: function() {
      if (!cm.socket) {
        //var sockethost = (hostname.indexOf('/') == -1) ?
        //    hostname : (hostname.split('/')[0]);
        //cm.socket = io(_chaq['protocol'] + sockethost + ':' +
        //    nodejs_port, {'forceNew': true });
        cm.socket = io(websocket_url, {
          'forceNew': true,
          'reconnection': true,
          'reconnectionDelay': 2000,
          'reconnectionDelayMax': 50000,
          'reconnectionAttempts': 2
        });
        cm.socket.on('enter room', function(data) {
          cm.socket.emit('user inroom', {
            userid: cm.userID,
            userhash: cm.userhash,
            roomid: cm.roomid,
            accountid: accountID
          });
        }).on('connect success', function(connected_roomid) {
          cm.socket.connected_roomid = connected_roomid;
          connected_roomid = null;
          timeline.push({
            code: 'system',
            subcode: 'requestlog',
            info: cm.lastmessageid
          });
        }).on('disconnect', function(data) {
          cm.socket.connected_roomid = null;
        }).on('message', function(data) {
          cm.update(data);
          data = null;
        }).on('ping', function(data) {
          cm.socket.emit('pong', 'pong');
        });
        // メモリリーク対策のため、定期的に接続し直す
        window.setTimeout(function() {
          cm.socket.disconnect();
          cm.socket = null;
          cm.sioStart();
        }, 100 * 1000);
      }
    }
  }; // cmモデル終わり

  ////// Timeline /////
  var timeline = {
    stack: [],
    backupstack: [],
    timer: null,
    timerInterval: TimerInterval,
    timerExtendCnt: 0,
    lastUpdate: 0,
    valid: true,
    sending: false,
    maxRetry: 4,
    //maxRetry: 2,
    retry: 0,
    start: function() {
      //myconsolelog('timeline start');
      timeline.initTimerInterval();
      //timeline.bulletin();
    },
    push: function(data) {
      this.stack[this.stack.length] = data;
      timeline.bulletin();
    },
    // タイマーの時間間隔を初期化
    initTimerInterval: function() {
      if (cm.isWindowFocus) {
        timeline.timerInterval = TimerInterval;
      } else {
        timeline.timerInterval = TimerIntervalBlur;
      }
      timeline.bulletin();
    },
    // タイマーの時間間隔を徐々に長くする
    extendTimerInterval: function() {
      if (cm.isChatting()) return false;
      if (cm.account && cm.account.state == CHAMO_STATE_OFFLINE) {
        timeline.timerInterval = TimerIntervalOffline;
        return;
      }
      timeline.timerExtendCnt++;
      if (timeline.timerExtendCnt >= TimerExtendNext) {
        timeline.timerExtendCnt = 0;    // initialize count
        var intervalMax = (cm.isWindowFocus) ?
            TimerIntervalMax : TimerIntervalBlurMax;
        timeline.timerInterval = timeline.timerInterval * TimerExtendMagni;
        if (timeline.timerInterval > intervalMax)
          timeline.timerInterval = intervalMax;
      }
    },
    // 定期的にサーバーに状態を送信
    bulletin: function() {
      if (timeline.sending) {
        // 送信中の場合は0.5秒後にリトライ
        clearTimeout(timeline.timer);
        timeline.timer = setTimeout(timeline.bulletin, 500);
      } else {
        // 送信中でなければ即時送信
        if (timeline.stack.length > 0) {
          //timeline.ajax({data_array: timeline.stack});
          timeline.ajax();
          timeline.stack = [];
        } else {
          // roomidが設定されずに大量のbulletinが飛ぶ現象があるので、その対策
          if (cm.roomid) {
            timeline.stack[timeline.stack.length] = {
              code: 'system',
              subcode: 'bulletin'
            };
          }
          timeline.ajax();
          timeline.stack = [];
        }
        timeline.extendTimerInterval();
        clearTimeout(timeline.timer);
        timeline.timer = setTimeout(timeline.bulletin, timeline.timerInterval);
      }
    },
    reconnect: function() {
      this.ajax(true);
    },
    ajax: function(reconnect) {
      var postdata = {};
      if (reconnect) {
        postdata.data_array = [{'code': 'system', 'subcode': 'reconnect'}];
      } else {
        if (!timeline.valid) {
          cv.setStatusbar(Localizer.getValue('error-disconnect'),
              'chamo-statusbar-error');
          return false;
        }
        postdata.data_array = timeline.stack;
      }
      if (postdata.data_array.length == 0) {
        return false;
      }
      postdata.accountid = accountID;
      postdata.userid = cm.userID;
      postdata.userhash = cm.userhash;
      postdata.roomid = cm.roomid;
      postdata.lastmessageid = cm.lastmessageid - 0;
      postdata.state = cm.user.state;
      postdata.isXdr = cm.isXdr;
      postdata.nochat = cm.account.nochat;

      postdata.loginhash = loginhash;
      // debug
      myconsolelog('---post_data---');
      myconsolelog(postdata);

      // requestを構築
      var request = {
        url: chamo_host + '?' + parseInt(correctedDate() / 1000),
        cache: false,
        data: postdata,
        crossDomain: true,
        beforeSend: function() {
          //myconsolelog('---beforeSend start---');
          timeline.sending = true;
          timeline.backupstack = postdata.data_array;
          //myconsolelog('---beforeSend---');
        },
        complete: function(data) {
          // 下記処理は、リトライ失敗時もつど呼ばれないといけない
          timeline.sending = false;
        }
      };
      //var self = this;
      connectAjax(request).done(function(data_array){
        // リトライ含めた接続成功時
        // debug
        myconsolelog('---ajax success---');
        myconsolelog(data_array);
        if (data_array instanceof Array) {
        } else {
          try {
            var data_array2 = $.parseJSON(data_array);
            data_array = data_array2;
          } catch (e) {
            cv.setStatusbar(Localizer.getValue('error-invaliddata'),
                'chamo-statusbar-error');
            myconsolelog('Error: invalid data_array');
            myconsolelog(e);
            myconsolelog(data_array);

            // log error
            var err_log = {
              code: 'user: resend invalid data_array',
              ua: navigator.userAgent,
              accountid: accountID,
              roomid: cm.roomid,
              userid: cm.userID,
              data_array: data_array,
              isXdr: cm.isXdr,
              error: e
            };
            $.ajax({
              url: hosturl + 'error.php',
              cache: false,
              data: err_log
            });
            return;
          }
        }
        cm.update(data_array);
        // トリガー再評価
        cm.triggerManager.evaluate();
        // エラー表示を消す
        cv.clearStatusbar('chamo-statusbar-error');
      })
      .fail(function(jqXHR, textStatus, errorThrown){
        // リトライ全てに失敗した時
        // デバッグコンソールに表示しつつエラーログに記載する。
        myconsolelog('Chamo: Data Receiving Error');
        myconsolelog('Timeline Ajax Error:');

        // 全てのリトライが失敗したらエラー記録を試みる。
        // これにはリトライを仕掛けない。
        var err_log = {
          code: 'user: resend ajax error',
          ua: navigator.userAgent,
          accountid: accountID,
          roomid: cm.roomid,
          userid: cm.userID,
          isXdr: cm.isXdr,
          responseText: jqXHR.responseText,
          status: jqXHR.status,
          textStatus: textStatus,
          errorThrown: errorThrown.message,
          stack: timeline.backupstack
        };
        $.ajax({
          url: hosturl + 'error.php',
          cache: false,
          data: err_log
        });
        myconsolelog(postdata);
        myconsolelog(jqXHR.responseText);

        // 切断エラー表示する
        cm.sendError(timeline.backupstack);
      })
    } // ajax
  };

  // 以下aibis_operator.jsより。
  // 一部設定数値は変更している。
  // また、bulletinのみの通信のリトライもさせない修正を加えてある。
  /**
   * connect Ajax
   *
   * @param object request
   */
  function connectAjax(request)
  {
    var maxRetries = 4; // 最大リトライ回数

    var retries = 0; // 現在のリトライ回数
    var retryTime = 1000; // リトライの間隔 ミリ秒

    var defer = $.Deferred();

    request.timeout = retryTime;
    request.success = defer.resolve;
    request.error = function(jqXHR, textStatus, errorThrown){
      // サーバーへの負荷を減らすため、infoのない単純なbulletinはリトライしない
      // 理由：当該bulletinは定期的に行われるから
      var skipBulletinOnly = false;
      var data_array = request.data.data_array;
      if (data_array !== undefined) {
        if (data_array.length == 1
           && data_array[0].subcode == 'bulletin'
           && data_array[0].info === undefined) {
          skipBulletinOnly = true;
        }
      }
      if (!skipBulletinOnly && retries < maxRetries){
        // 単純なbulletin以外かつ最大リトライ数以下
        var _request = request;
        retryTime = retryTime * 2; // リトライを繰り返すごとにリトライ間隔を延長します
        _request.timeout = retryTime;
        console.warn("Connection Failed. Retry After " + retryTime + " (ms)");
        console.warn("---- Failed Requst ----");
        console.warn(data_array);
        retries++;
        _request.data.retries = retries; // アクセスログにリトライ回数を記録するための措置
        setTimeout(function(){ $.ajax(_request) }, retryTime); // retry begin
      }
      else {
        if (skipBulletinOnly) {
          // bulleinのみの通信失敗情報をコンソールログに残し、正常系に戻す。
          console.warn("Connection Failed. (Not Retry noinfo bulletin)");
          return defer.promise();
        } else {
          console.warn("Connection Timeout.");
        }
        console.warn(jqXHR.status + " " + jqXHR.statusText);
        console.warn(showException(jqXHR.status, textStatus));

        defer.reject(jqXHR, textStatus, errorThrown); // retry end
      }
    };
    $.ajax(request);
    return defer.promise();
  }

  function responseMessages()
  {
    return {
      '400' : "Server understood the request, but request content was invalid.",
      '401' : "Unauthorized access.",
      '403' : "Forbidden resource can't be accessed.",
      '500' : "Internal server error.",
      '503' : "Service unavailable."
    };
  }

  function exceptionMessages()
  {
    return {
      'parsererror' : "Parsing JSON Request failed.",
      'timeout'     : "Request Time out.",
      'abort'       : "Request was aborted by the server",
    };
  }

  function responseMessage(responseCode)
  {
    var resMsgs = responseMessages();

    var msg = responseCode + " : ";
    var resMsg = resMsgs[responseCode];

    resMsg = (resMsg !== undefined) ? resMsg : "An Unknown Error Occurred.";

    return msg + resMsg;
  }

  function exceptionMessage(textStatus)
  {
    var exMsgs = exceptionMessages();

    var msg = textStatus + " : ";
    var exMsg = exMsgs[textStatus];

    exMsg = (exMsg !== undefined) ? exMsg : "An Unknown Error Occurred.";

    return msg + exMsg;
  }

  function showException(responseCode, textStatus)
  {
    var resMsg = responseMessage(responseCode);
    var exMsg = exceptionMessage(textStatus);

    return resMsg + "\n" + exMsg;
  }
  // ここまでaibis_oprator.jsから

  // functions
  function checkVisibility(settings) {
    if (settings.visibility == 'invisible') return 'invisible';

    // マージされたカレンダー
    if (settings.bs_merged_holidays !== undefined && settings.inbusiness_behavior === 'invisible') {
      if (!isInBusinessDayNow(settings.bs_merged_holidays)) {
        return 'invisible';
      }
    }

    if (settings.only_business_hours && settings.inbusiness_behavior === 'invisible') {
      if (isBetweenTimeOnDayNow(settings.bs)) {
        return 'visible';
      } else {
        return 'invisible';
      }
    }
    return 'visible';
  }

  function inBusinessHours(settings, offsetMinute) {
    // マージされたカレンダー
    if (settings.bs_merged_holidays !== undefined) {
      //settings.bs_merged_holidays = ['2018-06-21', '2018-06-22'];
      if (!isInBusinessDayNow(settings.bs_merged_holidays)) {
        return false;
      }
    }

    if (!settings.only_business_hours) {
      return true;
    }
    if (isBetweenTimeOnDayNow(settings.bs, offsetMinute)) {
      return true;
    } else {
      return false;
    }
  }

;!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.io=e()}}(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}({1:[function(_dereq_,module,exports){module.exports=_dereq_("./lib/")},{"./lib/":2}],2:[function(_dereq_,module,exports){var url=_dereq_("./url");var parser=_dereq_("socket.io-parser");var Manager=_dereq_("./manager");var debug=_dereq_("debug")("socket.io-client");module.exports=exports=lookup;var cache=exports.managers={};function lookup(uri,opts){if(typeof uri=="object"){opts=uri;uri=undefined}opts=opts||{};var parsed=url(uri);var source=parsed.source;var id=parsed.id;var io;if(opts.forceNew||opts["force new connection"]||false===opts.multiplex){debug("ignoring socket cache for %s",source);io=Manager(source,opts)}else{if(!cache[id]){debug("new io instance for %s",source);cache[id]=Manager(source,opts)}io=cache[id]}return io.socket(parsed.path)}exports.protocol=parser.protocol;exports.connect=lookup;exports.Manager=_dereq_("./manager");exports.Socket=_dereq_("./socket")},{"./manager":3,"./socket":5,"./url":6,debug:10,"socket.io-parser":44}],3:[function(_dereq_,module,exports){var url=_dereq_("./url");var eio=_dereq_("engine.io-client");var Socket=_dereq_("./socket");var Emitter=_dereq_("component-emitter");var parser=_dereq_("socket.io-parser");var on=_dereq_("./on");var bind=_dereq_("component-bind");var object=_dereq_("object-component");var debug=_dereq_("debug")("socket.io-client:manager");var indexOf=_dereq_("indexof");var Backoff=_dereq_("backo2");module.exports=Manager;function Manager(uri,opts){if(!(this instanceof Manager))return new Manager(uri,opts);if(uri&&"object"==typeof uri){opts=uri;uri=undefined}opts=opts||{};opts.path=opts.path||"/socket.io";this.nsps={};this.subs=[];this.opts=opts;this.reconnection(opts.reconnection!==false);this.reconnectionAttempts(opts.reconnectionAttempts||Infinity);this.reconnectionDelay(opts.reconnectionDelay||1e3);this.reconnectionDelayMax(opts.reconnectionDelayMax||5e3);this.randomizationFactor(opts.randomizationFactor||.5);this.backoff=new Backoff({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()});this.timeout(null==opts.timeout?2e4:opts.timeout);this.readyState="closed";this.uri=uri;this.connected=[];this.encoding=false;this.packetBuffer=[];this.encoder=new parser.Encoder;this.decoder=new parser.Decoder;this.autoConnect=opts.autoConnect!==false;if(this.autoConnect)this.open()}Manager.prototype.emitAll=function(){this.emit.apply(this,arguments);for(var nsp in this.nsps){this.nsps[nsp].emit.apply(this.nsps[nsp],arguments)}};Manager.prototype.updateSocketIds=function(){for(var nsp in this.nsps){this.nsps[nsp].id=this.engine.id}};Emitter(Manager.prototype);Manager.prototype.reconnection=function(v){if(!arguments.length)return this._reconnection;this._reconnection=!!v;return this};Manager.prototype.reconnectionAttempts=function(v){if(!arguments.length)return this._reconnectionAttempts;this._reconnectionAttempts=v;return this};Manager.prototype.reconnectionDelay=function(v){if(!arguments.length)return this._reconnectionDelay;this._reconnectionDelay=v;this.backoff&&this.backoff.setMin(v);return this};Manager.prototype.randomizationFactor=function(v){if(!arguments.length)return this._randomizationFactor;this._randomizationFactor=v;this.backoff&&this.backoff.setJitter(v);return this};Manager.prototype.reconnectionDelayMax=function(v){if(!arguments.length)return this._reconnectionDelayMax;this._reconnectionDelayMax=v;this.backoff&&this.backoff.setMax(v);return this};Manager.prototype.timeout=function(v){if(!arguments.length)return this._timeout;this._timeout=v;return this};Manager.prototype.maybeReconnectOnOpen=function(){if(!this.reconnecting&&this._reconnection&&this.backoff.attempts===0){this.reconnect()}};Manager.prototype.open=Manager.prototype.connect=function(fn){debug("readyState %s",this.readyState);if(~this.readyState.indexOf("open"))return this;debug("opening %s",this.uri);this.engine=eio(this.uri,this.opts);var socket=this.engine;var self=this;this.readyState="opening";this.skipReconnect=false;var openSub=on(socket,"open",function(){self.onopen();fn&&fn()});var errorSub=on(socket,"error",function(data){debug("connect_error");self.cleanup();self.readyState="closed";self.emitAll("connect_error",data);if(fn){var err=new Error("Connection error");err.data=data;fn(err)}else{self.maybeReconnectOnOpen()}});if(false!==this._timeout){var timeout=this._timeout;debug("connect attempt will timeout after %d",timeout);var timer=setTimeout(function(){debug("connect attempt timed out after %d",timeout);openSub.destroy();socket.close();socket.emit("error","timeout");self.emitAll("connect_timeout",timeout)},timeout);this.subs.push({destroy:function(){clearTimeout(timer)}})}this.subs.push(openSub);this.subs.push(errorSub);return this};Manager.prototype.onopen=function(){debug("open");this.cleanup();this.readyState="open";this.emit("open");var socket=this.engine;this.subs.push(on(socket,"data",bind(this,"ondata")));this.subs.push(on(this.decoder,"decoded",bind(this,"ondecoded")));this.subs.push(on(socket,"error",bind(this,"onerror")));this.subs.push(on(socket,"close",bind(this,"onclose")))};Manager.prototype.ondata=function(data){this.decoder.add(data)};Manager.prototype.ondecoded=function(packet){this.emit("packet",packet)};Manager.prototype.onerror=function(err){debug("error",err);this.emitAll("error",err)};Manager.prototype.socket=function(nsp){var socket=this.nsps[nsp];if(!socket){socket=new Socket(this,nsp);this.nsps[nsp]=socket;var self=this;socket.on("connect",function(){socket.id=self.engine.id;if(!~indexOf(self.connected,socket)){self.connected.push(socket)}})}return socket};Manager.prototype.destroy=function(socket){var index=indexOf(this.connected,socket);if(~index)this.connected.splice(index,1);if(this.connected.length)return;this.close()};Manager.prototype.packet=function(packet){debug("writing packet %j",packet);var self=this;if(!self.encoding){self.encoding=true;this.encoder.encode(packet,function(encodedPackets){for(var i=0;i<encodedPackets.length;i++){self.engine.write(encodedPackets[i])}self.encoding=false;self.processPacketQueue()})}else{self.packetBuffer.push(packet)}};Manager.prototype.processPacketQueue=function(){if(this.packetBuffer.length>0&&!this.encoding){var pack=this.packetBuffer.shift();this.packet(pack)}};Manager.prototype.cleanup=function(){var sub;while(sub=this.subs.shift())sub.destroy();this.packetBuffer=[];this.encoding=false;this.decoder.destroy()};Manager.prototype.close=Manager.prototype.disconnect=function(){this.skipReconnect=true;this.backoff.reset();this.readyState="closed";this.engine&&this.engine.close()};Manager.prototype.onclose=function(reason){debug("close");this.cleanup();this.backoff.reset();this.readyState="closed";this.emit("close",reason);if(this._reconnection&&!this.skipReconnect){this.reconnect()}};Manager.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var self=this;if(this.backoff.attempts>=this._reconnectionAttempts){debug("reconnect failed");this.backoff.reset();this.emitAll("reconnect_failed");this.reconnecting=false}else{var delay=this.backoff.duration();debug("will wait %dms before reconnect attempt",delay);this.reconnecting=true;var timer=setTimeout(function(){if(self.skipReconnect)return;debug("attempting reconnect");self.emitAll("reconnect_attempt",self.backoff.attempts);self.emitAll("reconnecting",self.backoff.attempts);if(self.skipReconnect)return;self.open(function(err){if(err){debug("reconnect attempt error");self.reconnecting=false;self.reconnect();self.emitAll("reconnect_error",err.data)}else{debug("reconnect success");self.onreconnect()}})},delay);this.subs.push({destroy:function(){clearTimeout(timer)}})}};Manager.prototype.onreconnect=function(){var attempt=this.backoff.attempts;this.reconnecting=false;this.backoff.reset();this.updateSocketIds();this.emitAll("reconnect",attempt)}},{"./on":4,"./socket":5,"./url":6,backo2:7,"component-bind":8,"component-emitter":9,debug:10,"engine.io-client":11,indexof:40,"object-component":41,"socket.io-parser":44}],4:[function(_dereq_,module,exports){module.exports=on;function on(obj,ev,fn){obj.on(ev,fn);return{destroy:function(){obj.removeListener(ev,fn)}}}},{}],5:[function(_dereq_,module,exports){var parser=_dereq_("socket.io-parser");var Emitter=_dereq_("component-emitter");var toArray=_dereq_("to-array");var on=_dereq_("./on");var bind=_dereq_("component-bind");var debug=_dereq_("debug")("socket.io-client:socket");var hasBin=_dereq_("has-binary");module.exports=exports=Socket;var events={connect:1,connect_error:1,connect_timeout:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1};var emit=Emitter.prototype.emit;function Socket(io,nsp){this.io=io;this.nsp=nsp;this.json=this;this.ids=0;this.acks={};if(this.io.autoConnect)this.open();this.receiveBuffer=[];this.sendBuffer=[];this.connected=false;this.disconnected=true}Emitter(Socket.prototype);Socket.prototype.subEvents=function(){if(this.subs)return;var io=this.io;this.subs=[on(io,"open",bind(this,"onopen")),on(io,"packet",bind(this,"onpacket")),on(io,"close",bind(this,"onclose"))]};Socket.prototype.open=Socket.prototype.connect=function(){if(this.connected)return this;this.subEvents();this.io.open();if("open"==this.io.readyState)this.onopen();return this};Socket.prototype.send=function(){var args=toArray(arguments);args.unshift("message");this.emit.apply(this,args);return this};Socket.prototype.emit=function(ev){if(events.hasOwnProperty(ev)){emit.apply(this,arguments);return this}var args=toArray(arguments);var parserType=parser.EVENT;if(hasBin(args)){parserType=parser.BINARY_EVENT}var packet={type:parserType,data:args};if("function"==typeof args[args.length-1]){debug("emitting packet with ack id %d",this.ids);this.acks[this.ids]=args.pop();packet.id=this.ids++}if(this.connected){this.packet(packet)}else{this.sendBuffer.push(packet)}return this};Socket.prototype.packet=function(packet){packet.nsp=this.nsp;this.io.packet(packet)};Socket.prototype.onopen=function(){debug("transport is open - connecting");if("/"!=this.nsp){this.packet({type:parser.CONNECT})}};Socket.prototype.onclose=function(reason){debug("close (%s)",reason);this.connected=false;this.disconnected=true;delete this.id;this.emit("disconnect",reason)};Socket.prototype.onpacket=function(packet){if(packet.nsp!=this.nsp)return;switch(packet.type){case parser.CONNECT:this.onconnect();break;case parser.EVENT:this.onevent(packet);break;case parser.BINARY_EVENT:this.onevent(packet);break;case parser.ACK:this.onack(packet);break;case parser.BINARY_ACK:this.onack(packet);break;case parser.DISCONNECT:this.ondisconnect();break;case parser.ERROR:this.emit("error",packet.data);break}};Socket.prototype.onevent=function(packet){var args=packet.data||[];debug("emitting event %j",args);if(null!=packet.id){debug("attaching ack callback to event");args.push(this.ack(packet.id))}if(this.connected){emit.apply(this,args)}else{this.receiveBuffer.push(args)}};Socket.prototype.ack=function(id){var self=this;var sent=false;return function(){if(sent)return;sent=true;var args=toArray(arguments);debug("sending ack %j",args);var type=hasBin(args)?parser.BINARY_ACK:parser.ACK;self.packet({type:type,id:id,data:args})}};Socket.prototype.onack=function(packet){debug("calling ack %s with %j",packet.id,packet.data);var fn=this.acks[packet.id];fn.apply(this,packet.data);delete this.acks[packet.id]};Socket.prototype.onconnect=function(){this.connected=true;this.disconnected=false;this.emit("connect");this.emitBuffered()};Socket.prototype.emitBuffered=function(){var i;for(i=0;i<this.receiveBuffer.length;i++){emit.apply(this,this.receiveBuffer[i])}this.receiveBuffer=[];for(i=0;i<this.sendBuffer.length;i++){this.packet(this.sendBuffer[i])}this.sendBuffer=[]};Socket.prototype.ondisconnect=function(){debug("server disconnect (%s)",this.nsp);this.destroy();this.onclose("io server disconnect")};Socket.prototype.destroy=function(){if(this.subs){for(var i=0;i<this.subs.length;i++){this.subs[i].destroy()}this.subs=null}this.io.destroy(this)};Socket.prototype.close=Socket.prototype.disconnect=function(){if(this.connected){debug("performing disconnect (%s)",this.nsp);this.packet({type:parser.DISCONNECT})}this.destroy();if(this.connected){this.onclose("io client disconnect")}return this}},{"./on":4,"component-bind":8,"component-emitter":9,debug:10,"has-binary":36,"socket.io-parser":44,"to-array":48}],6:[function(_dereq_,module,exports){(function(global){var parseuri=_dereq_("parseuri");var debug=_dereq_("debug")("socket.io-client:url");module.exports=url;function url(uri,loc){var obj=uri;var loc=loc||global.location;if(null==uri)uri=loc.protocol+"//"+loc.host;if("string"==typeof uri){if("/"==uri.charAt(0)){if("/"==uri.charAt(1)){uri=loc.protocol+uri}else{uri=loc.hostname+uri}}if(!/^(https?|wss?):\/\//.test(uri)){debug("protocol-less url %s",uri);if("undefined"!=typeof loc){uri=loc.protocol+"//"+uri}else{uri="https://"+uri}}debug("parse %s",uri);obj=parseuri(uri)}if(!obj.port){if(/^(http|ws)$/.test(obj.protocol)){obj.port="80"}else if(/^(http|ws)s$/.test(obj.protocol)){obj.port="443"}}obj.path=obj.path||"/";obj.id=obj.protocol+"://"+obj.host+":"+obj.port;obj.href=obj.protocol+"://"+obj.host+(loc&&loc.port==obj.port?"":":"+obj.port);return obj}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{debug:10,parseuri:42}],7:[function(_dereq_,module,exports){module.exports=Backoff;function Backoff(opts){opts=opts||{};this.ms=opts.min||100;this.max=opts.max||1e4;this.factor=opts.factor||2;this.jitter=opts.jitter>0&&opts.jitter<=1?opts.jitter:0;this.attempts=0}Backoff.prototype.duration=function(){var ms=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.jitter*ms);ms=(Math.floor(rand*10)&1)==0?ms-deviation:ms+deviation}return Math.min(ms,this.max)|0};Backoff.prototype.reset=function(){this.attempts=0};Backoff.prototype.setMin=function(min){this.ms=min};Backoff.prototype.setMax=function(max){this.max=max};Backoff.prototype.setJitter=function(jitter){this.jitter=jitter}},{}],8:[function(_dereq_,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],9:[function(_dereq_,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}on.fn=fn;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var cb;for(var i=0;i<callbacks.length;i++){cb=callbacks[i];if(cb===fn||cb.fn===fn){callbacks.splice(i,1);break}}return this};Emitter.prototype.emit=function(event){this._callbacks=this._callbacks||{};var args=[].slice.call(arguments,1),callbacks=this._callbacks[event];if(callbacks){callbacks=callbacks.slice(0);for(var i=0,len=callbacks.length;i<len;++i){callbacks[i].apply(this,args)}}return this};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],10:[function(_dereq_,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],11:[function(_dereq_,module,exports){module.exports=_dereq_("./lib/")},{"./lib/":12}],12:[function(_dereq_,module,exports){module.exports=_dereq_("./socket");module.exports.parser=_dereq_("engine.io-parser")},{"./socket":13,"engine.io-parser":25}],13:[function(_dereq_,module,exports){(function(global){var transports=_dereq_("./transports");var Emitter=_dereq_("component-emitter");var debug=_dereq_("debug")("engine.io-client:socket");var index=_dereq_("indexof");var parser=_dereq_("engine.io-parser");var parseuri=_dereq_("parseuri");var parsejson=_dereq_("parsejson");var parseqs=_dereq_("parseqs");module.exports=Socket;function noop(){}function Socket(uri,opts){if(!(this instanceof Socket))return new Socket(uri,opts);opts=opts||{};if(uri&&"object"==typeof uri){opts=uri;uri=null}if(uri){uri=parseuri(uri);opts.host=uri.host;opts.secure=uri.protocol=="https"||uri.protocol=="wss";opts.port=uri.port;if(uri.query)opts.query=uri.query}this.secure=null!=opts.secure?opts.secure:global.location&&"https:"==location.protocol;if(opts.host){var pieces=opts.host.split(":");opts.hostname=pieces.shift();if(pieces.length){opts.port=pieces.pop()}else if(!opts.port){opts.port=this.secure?"443":"80"}}this.agent=opts.agent||false;this.hostname=opts.hostname||(global.location?location.hostname:"localhost");this.port=opts.port||(global.location&&location.port?location.port:this.secure?443:80);this.query=opts.query||{};if("string"==typeof this.query)this.query=parseqs.decode(this.query);this.upgrade=false!==opts.upgrade;this.path=(opts.path||"/engine.io").replace(/\/$/,"")+"/";this.forceJSONP=!!opts.forceJSONP;this.jsonp=false!==opts.jsonp;this.forceBase64=!!opts.forceBase64;this.enablesXDR=!!opts.enablesXDR;this.timestampParam=opts.timestampParam||"t";this.timestampRequests=opts.timestampRequests;this.transports=opts.transports||["polling","websocket"];this.readyState="";this.writeBuffer=[];this.callbackBuffer=[];this.policyPort=opts.policyPort||843;this.rememberUpgrade=opts.rememberUpgrade||false;this.binaryType=null;this.onlyBinaryUpgrades=opts.onlyBinaryUpgrades;this.pfx=opts.pfx||null;this.key=opts.key||null;this.passphrase=opts.passphrase||null;this.cert=opts.cert||null;this.ca=opts.ca||null;this.ciphers=opts.ciphers||null;this.rejectUnauthorized=opts.rejectUnauthorized||null;this.open()}Socket.priorWebsocketSuccess=false;Emitter(Socket.prototype);Socket.protocol=parser.protocol;Socket.Socket=Socket;Socket.Transport=_dereq_("./transport");Socket.transports=_dereq_("./transports");Socket.parser=_dereq_("engine.io-parser");Socket.prototype.createTransport=function(name){debug('creating transport "%s"',name);var query=clone(this.query);query.EIO=parser.protocol;query.transport=name;if(this.id)query.sid=this.id;var transport=new transports[name]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:query,forceJSONP:this.forceJSONP,jsonp:this.jsonp,forceBase64:this.forceBase64,enablesXDR:this.enablesXDR,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this,pfx:this.pfx,key:this.key,passphrase:this.passphrase,cert:this.cert,ca:this.ca,ciphers:this.ciphers,rejectUnauthorized:this.rejectUnauthorized});return transport};function clone(obj){var o={};for(var i in obj){if(obj.hasOwnProperty(i)){o[i]=obj[i]}}return o}Socket.prototype.open=function(){var transport;if(this.rememberUpgrade&&Socket.priorWebsocketSuccess&&this.transports.indexOf("websocket")!=-1){transport="websocket"}else if(0==this.transports.length){var self=this;setTimeout(function(){self.emit("error","No transports available")},0);return}else{transport=this.transports[0]}this.readyState="opening";var transport;try{transport=this.createTransport(transport)}catch(e){this.transports.shift();this.open();return}transport.open();this.setTransport(transport)};Socket.prototype.setTransport=function(transport){debug("setting transport %s",transport.name);var self=this;if(this.transport){debug("clearing existing transport %s",this.transport.name);this.transport.removeAllListeners()}this.transport=transport;transport.on("drain",function(){self.onDrain()}).on("packet",function(packet){self.onPacket(packet)}).on("error",function(e){self.onError(e)}).on("close",function(){self.onClose("transport close")})};Socket.prototype.probe=function(name){debug('probing transport "%s"',name);var transport=this.createTransport(name,{probe:1}),failed=false,self=this;Socket.priorWebsocketSuccess=false;function onTransportOpen(){if(self.onlyBinaryUpgrades){var upgradeLosesBinary=!this.supportsBinary&&self.transport.supportsBinary;failed=failed||upgradeLosesBinary}if(failed)return;debug('probe transport "%s" opened',name);transport.send([{type:"ping",data:"probe"}]);transport.once("packet",function(msg){if(failed)return;if("pong"==msg.type&&"probe"==msg.data){debug('probe transport "%s" pong',name);self.upgrading=true;self.emit("upgrading",transport);if(!transport)return;Socket.priorWebsocketSuccess="websocket"==transport.name;debug('pausing current transport "%s"',self.transport.name);self.transport.pause(function(){if(failed)return;if("closed"==self.readyState)return;debug("changing transport and sending upgrade packet");cleanup();self.setTransport(transport);transport.send([{type:"upgrade"}]);self.emit("upgrade",transport);transport=null;self.upgrading=false;self.flush()})}else{debug('probe transport "%s" failed',name);var err=new Error("probe error");err.transport=transport.name;self.emit("upgradeError",err)}})}function freezeTransport(){if(failed)return;failed=true;cleanup();transport.close();transport=null}function onerror(err){var error=new Error("probe error: "+err);error.transport=transport.name;freezeTransport();debug('probe transport "%s" failed because of error: %s',name,err);self.emit("upgradeError",error)}function onTransportClose(){onerror("transport closed")}function onclose(){onerror("socket closed")}function onupgrade(to){if(transport&&to.name!=transport.name){debug('"%s" works - aborting "%s"',to.name,transport.name);freezeTransport()}}function cleanup(){transport.removeListener("open",onTransportOpen);transport.removeListener("error",onerror);transport.removeListener("close",onTransportClose);self.removeListener("close",onclose);self.removeListener("upgrading",onupgrade)}transport.once("open",onTransportOpen);transport.once("error",onerror);transport.once("close",onTransportClose);this.once("close",onclose);this.once("upgrading",onupgrade);transport.open()};Socket.prototype.onOpen=function(){debug("socket open");this.readyState="open";Socket.priorWebsocketSuccess="websocket"==this.transport.name;this.emit("open");this.flush();if("open"==this.readyState&&this.upgrade&&this.transport.pause){debug("starting upgrade probes");for(var i=0,l=this.upgrades.length;i<l;i++){this.probe(this.upgrades[i])}}};Socket.prototype.onPacket=function(packet){if("opening"==this.readyState||"open"==this.readyState){debug('socket receive: type "%s", data "%s"',packet.type,packet.data);this.emit("packet",packet);this.emit("heartbeat");switch(packet.type){case"open":this.onHandshake(parsejson(packet.data));break;case"pong":this.setPing();break;case"error":var err=new Error("server error");err.code=packet.data;this.emit("error",err);break;case"message":this.emit("data",packet.data);this.emit("message",packet.data);break}}else{debug('packet received with socket readyState "%s"',this.readyState)}};Socket.prototype.onHandshake=function(data){this.emit("handshake",data);this.id=data.sid;this.transport.query.sid=data.sid;this.upgrades=this.filterUpgrades(data.upgrades);this.pingInterval=data.pingInterval;this.pingTimeout=data.pingTimeout;this.onOpen();if("closed"==this.readyState)return;this.setPing();this.removeListener("heartbeat",this.onHeartbeat);this.on("heartbeat",this.onHeartbeat)};Socket.prototype.onHeartbeat=function(timeout){clearTimeout(this.pingTimeoutTimer);var self=this;self.pingTimeoutTimer=setTimeout(function(){if("closed"==self.readyState)return;self.onClose("ping timeout")},timeout||self.pingInterval+self.pingTimeout)};Socket.prototype.setPing=function(){var self=this;clearTimeout(self.pingIntervalTimer);self.pingIntervalTimer=setTimeout(function(){debug("writing ping packet - expecting pong within %sms",self.pingTimeout);self.ping();self.onHeartbeat(self.pingTimeout)},self.pingInterval)};Socket.prototype.ping=function(){this.sendPacket("ping")};Socket.prototype.onDrain=function(){for(var i=0;i<this.prevBufferLen;i++){if(this.callbackBuffer[i]){this.callbackBuffer[i]()}}this.writeBuffer.splice(0,this.prevBufferLen);this.callbackBuffer.splice(0,this.prevBufferLen);this.prevBufferLen=0;if(this.writeBuffer.length==0){this.emit("drain")}else{this.flush()}};Socket.prototype.flush=function(){if("closed"!=this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){debug("flushing %d packets in socket",this.writeBuffer.length);this.transport.send(this.writeBuffer);this.prevBufferLen=this.writeBuffer.length;this.emit("flush")}};Socket.prototype.write=Socket.prototype.send=function(msg,fn){this.sendPacket("message",msg,fn);return this};Socket.prototype.sendPacket=function(type,data,fn){if("closing"==this.readyState||"closed"==this.readyState){return}var packet={type:type,data:data};this.emit("packetCreate",packet);this.writeBuffer.push(packet);this.callbackBuffer.push(fn);this.flush()};Socket.prototype.close=function(){if("opening"==this.readyState||"open"==this.readyState){this.readyState="closing";var self=this;function close(){self.onClose("forced close");debug("socket closing - telling transport to close");self.transport.close()}function cleanupAndClose(){self.removeListener("upgrade",cleanupAndClose);self.removeListener("upgradeError",cleanupAndClose);close()}function waitForUpgrade(){self.once("upgrade",cleanupAndClose);self.once("upgradeError",cleanupAndClose)}if(this.writeBuffer.length){this.once("drain",function(){if(this.upgrading){waitForUpgrade()}else{close()}})}else if(this.upgrading){waitForUpgrade()}else{close()}}return this};Socket.prototype.onError=function(err){debug("socket error %j",err);Socket.priorWebsocketSuccess=false;this.emit("error",err);this.onClose("transport error",err)};Socket.prototype.onClose=function(reason,desc){if("opening"==this.readyState||"open"==this.readyState||"closing"==this.readyState){debug('socket close with reason: "%s"',reason);var self=this;clearTimeout(this.pingIntervalTimer);clearTimeout(this.pingTimeoutTimer);setTimeout(function(){self.writeBuffer=[];self.callbackBuffer=[];self.prevBufferLen=0},0);this.transport.removeAllListeners("close");this.transport.close();this.transport.removeAllListeners();this.readyState="closed";this.id=null;this.emit("close",reason,desc)}};Socket.prototype.filterUpgrades=function(upgrades){var filteredUpgrades=[];for(var i=0,j=upgrades.length;i<j;i++){if(~index(this.transports,upgrades[i]))filteredUpgrades.push(upgrades[i])}return filteredUpgrades}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./transport":14,"./transports":15,"component-emitter":9,debug:22,"engine.io-parser":25,indexof:40,parsejson:32,parseqs:33,parseuri:34}],14:[function(_dereq_,module,exports){var parser=_dereq_("engine.io-parser");var Emitter=_dereq_("component-emitter");module.exports=Transport;function Transport(opts){this.path=opts.path;this.hostname=opts.hostname;this.port=opts.port;this.secure=opts.secure;this.query=opts.query;this.timestampParam=opts.timestampParam;this.timestampRequests=opts.timestampRequests;this.readyState="";this.agent=opts.agent||false;this.socket=opts.socket;this.enablesXDR=opts.enablesXDR;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized}Emitter(Transport.prototype);Transport.timestamps=0;Transport.prototype.onError=function(msg,desc){var err=new Error(msg);err.type="TransportError";err.description=desc;this.emit("error",err);return this};Transport.prototype.open=function(){if("closed"==this.readyState||""==this.readyState){this.readyState="opening";this.doOpen()}return this};Transport.prototype.close=function(){if("opening"==this.readyState||"open"==this.readyState){this.doClose();this.onClose()}return this};Transport.prototype.send=function(packets){if("open"==this.readyState){this.write(packets)}else{throw new Error("Transport not open")}};Transport.prototype.onOpen=function(){this.readyState="open";this.writable=true;this.emit("open")};Transport.prototype.onData=function(data){var packet=parser.decodePacket(data,this.socket.binaryType);this.onPacket(packet)};Transport.prototype.onPacket=function(packet){this.emit("packet",packet)};Transport.prototype.onClose=function(){this.readyState="closed";this.emit("close")}},{"component-emitter":9,"engine.io-parser":25}],15:[function(_dereq_,module,exports){(function(global){var XMLHttpRequest=_dereq_("xmlhttprequest");var XHR=_dereq_("./polling-xhr");var JSONP=_dereq_("./polling-jsonp");var websocket=_dereq_("./websocket");exports.polling=polling;exports.websocket=websocket;function polling(opts){var xhr;var xd=false;var xs=false;var jsonp=false!==opts.jsonp;if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}xd=opts.hostname!=location.hostname||port!=opts.port;xs=opts.secure!=isSSL}opts.xdomain=xd;opts.xscheme=xs;xhr=new XMLHttpRequest(opts);if("open"in xhr&&!opts.forceJSONP){return new XHR(opts)}else{if(!jsonp)throw new Error("JSONP disabled");return new JSONP(opts)}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling-jsonp":16,"./polling-xhr":17,"./websocket":19,xmlhttprequest:20}],16:[function(_dereq_,module,exports){(function(global){var Polling=_dereq_("./polling");var inherit=_dereq_("component-inherit");module.exports=JSONPPolling;var rNewline=/\n/g;var rEscapedNewline=/\\n/g;var callbacks;var index=0;function empty(){}function JSONPPolling(opts){Polling.call(this,opts);
this.query=this.query||{};if(!callbacks){if(!global.___eio)global.___eio=[];callbacks=global.___eio}this.index=callbacks.length;var self=this;callbacks.push(function(msg){self.onData(msg)});this.query.j=this.index;if(global.document&&global.addEventListener){global.addEventListener("beforeunload",function(){if(self.script)self.script.onerror=empty},false)}}inherit(JSONPPolling,Polling);JSONPPolling.prototype.supportsBinary=false;JSONPPolling.prototype.doClose=function(){if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}if(this.form){this.form.parentNode.removeChild(this.form);this.form=null;this.iframe=null}Polling.prototype.doClose.call(this)};JSONPPolling.prototype.doPoll=function(){var self=this;var script=document.createElement("script");if(this.script){this.script.parentNode.removeChild(this.script);this.script=null}script.async=true;script.src=this.uri();script.onerror=function(e){self.onError("jsonp poll error",e)};var insertAt=document.getElementsByTagName("script")[0];insertAt.parentNode.insertBefore(script,insertAt);this.script=script;var isUAgecko="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);if(isUAgecko){setTimeout(function(){var iframe=document.createElement("iframe");document.body.appendChild(iframe);document.body.removeChild(iframe)},100)}};JSONPPolling.prototype.doWrite=function(data,fn){var self=this;if(!this.form){var form=document.createElement("form");var area=document.createElement("textarea");var id=this.iframeId="eio_iframe_"+this.index;var iframe;form.className="socketio";form.style.position="absolute";form.style.top="-1000px";form.style.left="-1000px";form.target=id;form.method="POST";form.setAttribute("accept-charset","utf-8");area.name="d";form.appendChild(area);document.body.appendChild(form);this.form=form;this.area=area}this.form.action=this.uri();function complete(){initIframe();fn()}function initIframe(){if(self.iframe){try{self.form.removeChild(self.iframe)}catch(e){self.onError("jsonp polling iframe removal error",e)}}try{var html='<iframe src="javascript:0" name="'+self.iframeId+'">';iframe=document.createElement(html)}catch(e){iframe=document.createElement("iframe");iframe.name=self.iframeId;iframe.src="javascript:0"}iframe.id=self.iframeId;self.form.appendChild(iframe);self.iframe=iframe}initIframe();data=data.replace(rEscapedNewline,"\\\n");this.area.value=data.replace(rNewline,"\\n");try{this.form.submit()}catch(e){}if(this.iframe.attachEvent){this.iframe.onreadystatechange=function(){if(self.iframe.readyState=="complete"){complete()}}}else{this.iframe.onload=complete}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling":18,"component-inherit":21}],17:[function(_dereq_,module,exports){(function(global){var XMLHttpRequest=_dereq_("xmlhttprequest");var Polling=_dereq_("./polling");var Emitter=_dereq_("component-emitter");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:polling-xhr");module.exports=XHR;module.exports.Request=Request;function empty(){}function XHR(opts){Polling.call(this,opts);if(global.location){var isSSL="https:"==location.protocol;var port=location.port;if(!port){port=isSSL?443:80}this.xd=opts.hostname!=global.location.hostname||port!=opts.port;this.xs=opts.secure!=isSSL}}inherit(XHR,Polling);XHR.prototype.supportsBinary=true;XHR.prototype.request=function(opts){opts=opts||{};opts.uri=this.uri();opts.xd=this.xd;opts.xs=this.xs;opts.agent=this.agent||false;opts.supportsBinary=this.supportsBinary;opts.enablesXDR=this.enablesXDR;opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;return new Request(opts)};XHR.prototype.doWrite=function(data,fn){var isBinary=typeof data!=="string"&&data!==undefined;var req=this.request({method:"POST",data:data,isBinary:isBinary});var self=this;req.on("success",fn);req.on("error",function(err){self.onError("xhr post error",err)});this.sendXhr=req};XHR.prototype.doPoll=function(){debug("xhr poll");var req=this.request();var self=this;req.on("data",function(data){self.onData(data)});req.on("error",function(err){self.onError("xhr poll error",err)});this.pollXhr=req};function Request(opts){this.method=opts.method||"GET";this.uri=opts.uri;this.xd=!!opts.xd;this.xs=!!opts.xs;this.async=false!==opts.async;this.data=undefined!=opts.data?opts.data:null;this.agent=opts.agent;this.isBinary=opts.isBinary;this.supportsBinary=opts.supportsBinary;this.enablesXDR=opts.enablesXDR;this.pfx=opts.pfx;this.key=opts.key;this.passphrase=opts.passphrase;this.cert=opts.cert;this.ca=opts.ca;this.ciphers=opts.ciphers;this.rejectUnauthorized=opts.rejectUnauthorized;this.create()}Emitter(Request.prototype);Request.prototype.create=function(){var opts={agent:this.agent,xdomain:this.xd,xscheme:this.xs,enablesXDR:this.enablesXDR};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;var xhr=this.xhr=new XMLHttpRequest(opts);var self=this;try{debug("xhr open %s: %s",this.method,this.uri);xhr.open(this.method,this.uri,this.async);if(this.supportsBinary){xhr.responseType="arraybuffer"}if("POST"==this.method){try{if(this.isBinary){xhr.setRequestHeader("Content-type","application/octet-stream")}else{xhr.setRequestHeader("Content-type","text/plain;charset=UTF-8")}}catch(e){}}if("withCredentials"in xhr){xhr.withCredentials=true}if(this.hasXDR()){xhr.onload=function(){self.onLoad()};xhr.onerror=function(){self.onError(xhr.responseText)}}else{xhr.onreadystatechange=function(){if(4!=xhr.readyState)return;if(200==xhr.status||1223==xhr.status){self.onLoad()}else{setTimeout(function(){self.onError(xhr.status)},0)}}}debug("xhr data %s",this.data);xhr.send(this.data)}catch(e){setTimeout(function(){self.onError(e)},0);return}if(global.document){this.index=Request.requestsCount++;Request.requests[this.index]=this}};Request.prototype.onSuccess=function(){this.emit("success");this.cleanup()};Request.prototype.onData=function(data){this.emit("data",data);this.onSuccess()};Request.prototype.onError=function(err){this.emit("error",err);this.cleanup(true)};Request.prototype.cleanup=function(fromError){if("undefined"==typeof this.xhr||null===this.xhr){return}if(this.hasXDR()){this.xhr.onload=this.xhr.onerror=empty}else{this.xhr.onreadystatechange=empty}if(fromError){try{this.xhr.abort()}catch(e){}}if(global.document){delete Request.requests[this.index]}this.xhr=null};Request.prototype.onLoad=function(){var data;try{var contentType;try{contentType=this.xhr.getResponseHeader("Content-Type").split(";")[0]}catch(e){}if(contentType==="application/octet-stream"){data=this.xhr.response}else{if(!this.supportsBinary){data=this.xhr.responseText}else{data="ok"}}}catch(e){this.onError(e)}if(null!=data){this.onData(data)}};Request.prototype.hasXDR=function(){return"undefined"!==typeof global.XDomainRequest&&!this.xs&&this.enablesXDR};Request.prototype.abort=function(){this.cleanup()};if(global.document){Request.requestsCount=0;Request.requests={};if(global.attachEvent){global.attachEvent("onunload",unloadHandler)}else if(global.addEventListener){global.addEventListener("beforeunload",unloadHandler,false)}}function unloadHandler(){for(var i in Request.requests){if(Request.requests.hasOwnProperty(i)){Request.requests[i].abort()}}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./polling":18,"component-emitter":9,"component-inherit":21,debug:22,xmlhttprequest:20}],18:[function(_dereq_,module,exports){var Transport=_dereq_("../transport");var parseqs=_dereq_("parseqs");var parser=_dereq_("engine.io-parser");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:polling");module.exports=Polling;var hasXHR2=function(){var XMLHttpRequest=_dereq_("xmlhttprequest");var xhr=new XMLHttpRequest({xdomain:false});return null!=xhr.responseType}();function Polling(opts){var forceBase64=opts&&opts.forceBase64;if(!hasXHR2||forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(Polling,Transport);Polling.prototype.name="polling";Polling.prototype.doOpen=function(){this.poll()};Polling.prototype.pause=function(onPause){var pending=0;var self=this;this.readyState="pausing";function pause(){debug("paused");self.readyState="paused";onPause()}if(this.polling||!this.writable){var total=0;if(this.polling){debug("we are currently polling - waiting to pause");total++;this.once("pollComplete",function(){debug("pre-pause polling complete");--total||pause()})}if(!this.writable){debug("we are currently writing - waiting to pause");total++;this.once("drain",function(){debug("pre-pause writing complete");--total||pause()})}}else{pause()}};Polling.prototype.poll=function(){debug("polling");this.polling=true;this.doPoll();this.emit("poll")};Polling.prototype.onData=function(data){var self=this;debug("polling got data %s",data);var callback=function(packet,index,total){if("opening"==self.readyState){self.onOpen()}if("close"==packet.type){self.onClose();return false}self.onPacket(packet)};parser.decodePayload(data,this.socket.binaryType,callback);if("closed"!=this.readyState){this.polling=false;this.emit("pollComplete");if("open"==this.readyState){this.poll()}else{debug('ignoring poll - transport state "%s"',this.readyState)}}};Polling.prototype.doClose=function(){var self=this;function close(){debug("writing close packet");self.write([{type:"close"}])}if("open"==this.readyState){debug("transport open - closing");close()}else{debug("transport not open - deferring close");this.once("open",close)}};Polling.prototype.write=function(packets){var self=this;this.writable=false;var callbackfn=function(){self.writable=true;self.emit("drain")};var self=this;parser.encodePayload(packets,this.supportsBinary,function(data){self.doWrite(data,callbackfn)})};Polling.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"https":"http";var port="";if(false!==this.timestampRequests){query[this.timestampParam]=+new Date+"-"+Transport.timestamps++}if(!this.supportsBinary&&!query.sid){query.b64=1}query=parseqs.encode(query);if(this.port&&("https"==schema&&this.port!=443||"http"==schema&&this.port!=80)){port=":"+this.port}if(query.length){query="?"+query}return schema+"://"+this.hostname+port+this.path+query}},{"../transport":14,"component-inherit":21,debug:22,"engine.io-parser":25,parseqs:33,xmlhttprequest:20}],19:[function(_dereq_,module,exports){var Transport=_dereq_("../transport");var parser=_dereq_("engine.io-parser");var parseqs=_dereq_("parseqs");var inherit=_dereq_("component-inherit");var debug=_dereq_("debug")("engine.io-client:websocket");var WebSocket=_dereq_("ws");module.exports=WS;function WS(opts){var forceBase64=opts&&opts.forceBase64;if(forceBase64){this.supportsBinary=false}Transport.call(this,opts)}inherit(WS,Transport);WS.prototype.name="websocket";WS.prototype.supportsBinary=true;WS.prototype.doOpen=function(){if(!this.check()){return}var self=this;var uri=this.uri();var protocols=void 0;var opts={agent:this.agent};opts.pfx=this.pfx;opts.key=this.key;opts.passphrase=this.passphrase;opts.cert=this.cert;opts.ca=this.ca;opts.ciphers=this.ciphers;opts.rejectUnauthorized=this.rejectUnauthorized;this.ws=new WebSocket(uri,protocols,opts);if(this.ws.binaryType===undefined){this.supportsBinary=false}this.ws.binaryType="arraybuffer";this.addEventListeners()};WS.prototype.addEventListeners=function(){var self=this;this.ws.onopen=function(){self.onOpen()};this.ws.onclose=function(){self.onClose()};this.ws.onmessage=function(ev){self.onData(ev.data)};this.ws.onerror=function(e){self.onError("websocket error",e)}};if("undefined"!=typeof navigator&&/iPad|iPhone|iPod/i.test(navigator.userAgent)){WS.prototype.onData=function(data){var self=this;setTimeout(function(){Transport.prototype.onData.call(self,data)},0)}}WS.prototype.write=function(packets){var self=this;this.writable=false;for(var i=0,l=packets.length;i<l;i++){parser.encodePacket(packets[i],this.supportsBinary,function(data){try{self.ws.send(data)}catch(e){debug("websocket closed before onclose event")}})}function ondrain(){self.writable=true;self.emit("drain")}setTimeout(ondrain,0)};WS.prototype.onClose=function(){Transport.prototype.onClose.call(this)};WS.prototype.doClose=function(){if(typeof this.ws!=="undefined"){this.ws.close()}};WS.prototype.uri=function(){var query=this.query||{};var schema=this.secure?"wss":"ws";var port="";if(this.port&&("wss"==schema&&this.port!=443||"ws"==schema&&this.port!=80)){port=":"+this.port}if(this.timestampRequests){query[this.timestampParam]=+new Date}if(!this.supportsBinary){query.b64=1}query=parseqs.encode(query);if(query.length){query="?"+query}return schema+"://"+this.hostname+port+this.path+query};WS.prototype.check=function(){return!!WebSocket&&!("__initialize"in WebSocket&&this.name===WS.prototype.name)}},{"../transport":14,"component-inherit":21,debug:22,"engine.io-parser":25,parseqs:33,ws:35}],20:[function(_dereq_,module,exports){var hasCORS=_dereq_("has-cors");module.exports=function(opts){var xdomain=opts.xdomain;var xscheme=opts.xscheme;var enablesXDR=opts.enablesXDR;try{if("undefined"!=typeof XMLHttpRequest&&(!xdomain||hasCORS)){return new XMLHttpRequest}}catch(e){}try{if("undefined"!=typeof XDomainRequest&&!xscheme&&enablesXDR){return new XDomainRequest}}catch(e){}if(!xdomain){try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}}},{"has-cors":38}],21:[function(_dereq_,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],22:[function(_dereq_,module,exports){exports=module.exports=_dereq_("./debug");exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"];function useColors(){return"WebkitAppearance"in document.documentElement.style||window.console&&(console.firebug||console.exception&&console.table)||navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31}exports.formatters.j=function(v){return JSON.stringify(v)};function formatArgs(){var args=arguments;var useColors=this.useColors;args[0]=(useColors?"%c":"")+this.namespace+(useColors?" %c":" ")+args[0]+(useColors?"%c ":" ")+"+"+exports.humanize(this.diff);if(!useColors)return args;var c="color: "+this.color;args=[args[0],c,"color: inherit"].concat(Array.prototype.slice.call(args,1));var index=0;var lastC=0;args[0].replace(/%[a-z%]/g,function(match){if("%"===match)return;index++;if("%c"===match){lastC=index}});args.splice(lastC,0,c);return args}function log(){return"object"==typeof console&&"function"==typeof console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{if(null==namespaces){localStorage.removeItem("debug")}else{localStorage.debug=namespaces}}catch(e){}}function load(){var r;try{r=localStorage.debug}catch(e){}return r}exports.enable(load())},{"./debug":23}],23:[function(_dereq_,module,exports){exports=module.exports=debug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=_dereq_("ms");exports.names=[];exports.skips=[];exports.formatters={};var prevColor=0;var prevTime;function selectColor(){return exports.colors[prevColor++%exports.colors.length]}function debug(namespace){function disabled(){}disabled.enabled=false;function enabled(){var self=enabled;var curr=+new Date;var ms=curr-(prevTime||curr);self.diff=ms;self.prev=prevTime;self.curr=curr;prevTime=curr;if(null==self.useColors)self.useColors=exports.useColors();if(null==self.color&&self.useColors)self.color=selectColor();var args=Array.prototype.slice.call(arguments);args[0]=exports.coerce(args[0]);if("string"!==typeof args[0]){args=["%o"].concat(args)}var index=0;args[0]=args[0].replace(/%([a-z%])/g,function(match,format){if(match==="%")return match;index++;var formatter=exports.formatters[format];if("function"===typeof formatter){var val=args[index];match=formatter.call(self,val);args.splice(index,1);index--}return match});if("function"===typeof exports.formatArgs){args=exports.formatArgs.apply(self,args)}var logFn=enabled.log||exports.log||console.log.bind(console);logFn.apply(self,args)}enabled.enabled=true;var fn=exports.enabled(namespace)?enabled:disabled;fn.namespace=namespace;return fn}function enable(namespaces){exports.save(namespaces);var split=(namespaces||"").split(/[\s,]+/);var len=split.length;for(var i=0;i<len;i++){if(!split[i])continue;namespaces=split[i].replace(/\*/g,".*?");if(namespaces[0]==="-"){exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$"))}else{exports.names.push(new RegExp("^"+namespaces+"$"))}}}function disable(){exports.enable("")}function enabled(name){var i,len;for(i=0,len=exports.skips.length;i<len;i++){if(exports.skips[i].test(name)){return false}}for(i=0,len=exports.names.length;i<len;i++){if(exports.names[i].test(name)){return true}}return false}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{ms:24}],24:[function(_dereq_,module,exports){var s=1e3;var m=s*60;var h=m*60;var d=h*24;var y=d*365.25;module.exports=function(val,options){options=options||{};if("string"==typeof val)return parse(val);return options.long?long(val):short(val)};function parse(str){var match=/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);if(!match)return;var n=parseFloat(match[1]);var type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"h":return n*h;case"minutes":case"minute":case"m":return n*m;case"seconds":case"second":case"s":return n*s;case"ms":return n}}function short(ms){if(ms>=d)return Math.round(ms/d)+"d";if(ms>=h)return Math.round(ms/h)+"h";if(ms>=m)return Math.round(ms/m)+"m";if(ms>=s)return Math.round(ms/s)+"s";return ms+"ms"}function long(ms){return plural(ms,d,"day")||plural(ms,h,"hour")||plural(ms,m,"minute")||plural(ms,s,"second")||ms+" ms"}function plural(ms,n,name){if(ms<n)return;if(ms<n*1.5)return Math.floor(ms/n)+" "+name;return Math.ceil(ms/n)+" "+name+"s"}},{}],25:[function(_dereq_,module,exports){(function(global){var keys=_dereq_("./keys");var hasBinary=_dereq_("has-binary");var sliceBuffer=_dereq_("arraybuffer.slice");var base64encoder=_dereq_("base64-arraybuffer");var after=_dereq_("after");var utf8=_dereq_("utf8");var isAndroid=navigator.userAgent.match(/Android/i);var isPhantomJS=/PhantomJS/i.test(navigator.userAgent);var dontSendBlobs=isAndroid||isPhantomJS;exports.protocol=3;var packets=exports.packets={open:0,close:1,ping:2,pong:3,message:4,upgrade:5,noop:6};var packetslist=keys(packets);var err={type:"error",data:"parser error"};var Blob=_dereq_("blob");exports.encodePacket=function(packet,supportsBinary,utf8encode,callback){if("function"==typeof supportsBinary){callback=supportsBinary;supportsBinary=false}if("function"==typeof utf8encode){callback=utf8encode;utf8encode=null}var data=packet.data===undefined?undefined:packet.data.buffer||packet.data;if(global.ArrayBuffer&&data instanceof ArrayBuffer){return encodeArrayBuffer(packet,supportsBinary,callback)}else if(Blob&&data instanceof global.Blob){return encodeBlob(packet,supportsBinary,callback)}if(data&&data.base64){return encodeBase64Object(packet,callback)}var encoded=packets[packet.type];if(undefined!==packet.data){encoded+=utf8encode?utf8.encode(String(packet.data)):String(packet.data)}return callback(""+encoded)};function encodeBase64Object(packet,callback){var message="b"+exports.packets[packet.type]+packet.data.data;return callback(message)}function encodeArrayBuffer(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}var data=packet.data;var contentArray=new Uint8Array(data);var resultBuffer=new Uint8Array(1+data.byteLength);resultBuffer[0]=packets[packet.type];for(var i=0;i<contentArray.length;i++){resultBuffer[i+1]=contentArray[i]}return callback(resultBuffer.buffer)}function encodeBlobAsArrayBuffer(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}var fr=new FileReader;fr.onload=function(){packet.data=fr.result;exports.encodePacket(packet,supportsBinary,true,callback)};return fr.readAsArrayBuffer(packet.data)}function encodeBlob(packet,supportsBinary,callback){if(!supportsBinary){return exports.encodeBase64Packet(packet,callback)}if(dontSendBlobs){return encodeBlobAsArrayBuffer(packet,supportsBinary,callback)}var length=new Uint8Array(1);length[0]=packets[packet.type];var blob=new Blob([length.buffer,packet.data]);return callback(blob)}exports.encodeBase64Packet=function(packet,callback){var message="b"+exports.packets[packet.type];if(Blob&&packet.data instanceof Blob){var fr=new FileReader;fr.onload=function(){var b64=fr.result.split(",")[1];callback(message+b64)};return fr.readAsDataURL(packet.data)}var b64data;try{b64data=String.fromCharCode.apply(null,new Uint8Array(packet.data))}catch(e){var typed=new Uint8Array(packet.data);var basic=new Array(typed.length);for(var i=0;i<typed.length;i++){basic[i]=typed[i]}b64data=String.fromCharCode.apply(null,basic)}message+=global.btoa(b64data);return callback(message)};exports.decodePacket=function(data,binaryType,utf8decode){if(typeof data=="string"||data===undefined){if(data.charAt(0)=="b"){return exports.decodeBase64Packet(data.substr(1),binaryType)}if(utf8decode){try{data=utf8.decode(data)}catch(e){return err}}var type=data.charAt(0);if(Number(type)!=type||!packetslist[type]){return err}if(data.length>1){return{type:packetslist[type],data:data.substring(1)}}else{return{type:packetslist[type]}}}var asArray=new Uint8Array(data);var type=asArray[0];var rest=sliceBuffer(data,1);if(Blob&&binaryType==="blob"){rest=new Blob([rest])}return{type:packetslist[type],data:rest}};exports.decodeBase64Packet=function(msg,binaryType){var type=packetslist[msg.charAt(0)];if(!global.ArrayBuffer){return{type:type,data:{base64:true,data:msg.substr(1)}}}var data=base64encoder.decode(msg.substr(1));if(binaryType==="blob"&&Blob){data=new Blob([data])}return{type:type,data:data}};exports.encodePayload=function(packets,supportsBinary,callback){if(typeof supportsBinary=="function"){callback=supportsBinary;supportsBinary=null}var isBinary=hasBinary(packets);if(supportsBinary&&isBinary){if(Blob&&!dontSendBlobs){return exports.encodePayloadAsBlob(packets,callback)}return exports.encodePayloadAsArrayBuffer(packets,callback)}if(!packets.length){return callback("0:")}function setLengthHeader(message){return message.length+":"+message}function encodeOne(packet,doneCallback){exports.encodePacket(packet,!isBinary?false:supportsBinary,true,function(message){doneCallback(null,setLengthHeader(message))})}map(packets,encodeOne,function(err,results){return callback(results.join(""))})};function map(ary,each,done){var result=new Array(ary.length);var next=after(ary.length,done);var eachWithIndex=function(i,el,cb){each(el,function(error,msg){result[i]=msg;cb(error,result)})};for(var i=0;i<ary.length;i++){eachWithIndex(i,ary[i],next)}}exports.decodePayload=function(data,binaryType,callback){if(typeof data!="string"){return exports.decodePayloadAsBinary(data,binaryType,callback)}if(typeof binaryType==="function"){callback=binaryType;binaryType=null}var packet;if(data==""){return callback(err,0,1)}var length="",n,msg;for(var i=0,l=data.length;i<l;i++){var chr=data.charAt(i);if(":"!=chr){length+=chr}else{if(""==length||length!=(n=Number(length))){return callback(err,0,1)}msg=data.substr(i+1,n);if(length!=msg.length){return callback(err,0,1)}if(msg.length){packet=exports.decodePacket(msg,binaryType,true);if(err.type==packet.type&&err.data==packet.data){return callback(err,0,1)}var ret=callback(packet,i+n,l);if(false===ret)return}i+=n;length=""}}if(length!=""){return callback(err,0,1)}};exports.encodePayloadAsArrayBuffer=function(packets,callback){if(!packets.length){return callback(new ArrayBuffer(0))}function encodeOne(packet,doneCallback){exports.encodePacket(packet,true,true,function(data){return doneCallback(null,data)})}map(packets,encodeOne,function(err,encodedPackets){var totalLength=encodedPackets.reduce(function(acc,p){var len;if(typeof p==="string"){len=p.length}else{len=p.byteLength}return acc+len.toString().length+len+2},0);var resultArray=new Uint8Array(totalLength);var bufferIndex=0;encodedPackets.forEach(function(p){var isString=typeof p==="string";var ab=p;if(isString){var view=new Uint8Array(p.length);for(var i=0;i<p.length;i++){view[i]=p.charCodeAt(i)}ab=view.buffer}if(isString){resultArray[bufferIndex++]=0}else{resultArray[bufferIndex++]=1}var lenStr=ab.byteLength.toString();for(var i=0;i<lenStr.length;i++){resultArray[bufferIndex++]=parseInt(lenStr[i])}resultArray[bufferIndex++]=255;var view=new Uint8Array(ab);for(var i=0;i<view.length;i++){resultArray[bufferIndex++]=view[i]}});return callback(resultArray.buffer)})};exports.encodePayloadAsBlob=function(packets,callback){function encodeOne(packet,doneCallback){exports.encodePacket(packet,true,true,function(encoded){var binaryIdentifier=new Uint8Array(1);binaryIdentifier[0]=1;if(typeof encoded==="string"){var view=new Uint8Array(encoded.length);for(var i=0;i<encoded.length;i++){view[i]=encoded.charCodeAt(i)}encoded=view.buffer;binaryIdentifier[0]=0}var len=encoded instanceof ArrayBuffer?encoded.byteLength:encoded.size;var lenStr=len.toString();var lengthAry=new Uint8Array(lenStr.length+1);for(var i=0;i<lenStr.length;i++){lengthAry[i]=parseInt(lenStr[i])}lengthAry[lenStr.length]=255;if(Blob){var blob=new Blob([binaryIdentifier.buffer,lengthAry.buffer,encoded]);doneCallback(null,blob)}})}map(packets,encodeOne,function(err,results){return callback(new Blob(results))})};exports.decodePayloadAsBinary=function(data,binaryType,callback){if(typeof binaryType==="function"){callback=binaryType;binaryType=null}var bufferTail=data;var buffers=[];var numberTooLong=false;while(bufferTail.byteLength>0){var tailArray=new Uint8Array(bufferTail);var isString=tailArray[0]===0;var msgLength="";for(var i=1;;i++){if(tailArray[i]==255)break;if(msgLength.length>310){numberTooLong=true;break}msgLength+=tailArray[i]}if(numberTooLong)return callback(err,0,1);bufferTail=sliceBuffer(bufferTail,2+msgLength.length);msgLength=parseInt(msgLength);var msg=sliceBuffer(bufferTail,0,msgLength);if(isString){try{msg=String.fromCharCode.apply(null,new Uint8Array(msg))}catch(e){var typed=new Uint8Array(msg);msg="";for(var i=0;i<typed.length;i++){msg+=String.fromCharCode(typed[i])}}}buffers.push(msg);bufferTail=sliceBuffer(bufferTail,msgLength)}var total=buffers.length;buffers.forEach(function(buffer,i){callback(exports.decodePacket(buffer,binaryType,true),i,total)})}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./keys":26,after:27,"arraybuffer.slice":28,"base64-arraybuffer":29,blob:30,"has-binary":36,utf8:31}],26:[function(_dereq_,module,exports){module.exports=Object.keys||function keys(obj){var arr=[];var has=Object.prototype.hasOwnProperty;for(var i in obj){if(has.call(obj,i)){arr.push(i)}}return arr}},{}],27:[function(_dereq_,module,exports){module.exports=after;function after(count,callback,err_cb){var bail=false;err_cb=err_cb||noop;proxy.count=count;return count===0?callback():proxy;function proxy(err,result){if(proxy.count<=0){throw new Error("after called too many times")}--proxy.count;if(err){bail=true;callback(err);callback=err_cb}else if(proxy.count===0&&!bail){callback(null,result)}}}function noop(){}},{}],28:[function(_dereq_,module,exports){module.exports=function(arraybuffer,start,end){var bytes=arraybuffer.byteLength;start=start||0;end=end||bytes;if(arraybuffer.slice){return arraybuffer.slice(start,end)}if(start<0){start+=bytes}if(end<0){end+=bytes}if(end>bytes){end=bytes}if(start>=bytes||start>=end||bytes===0){return new ArrayBuffer(0)}var abv=new Uint8Array(arraybuffer);var result=new Uint8Array(end-start);for(var i=start,ii=0;i<end;i++,ii++){result[ii]=abv[i]}return result.buffer}},{}],29:[function(_dereq_,module,exports){(function(chars){"use strict";exports.encode=function(arraybuffer){var bytes=new Uint8Array(arraybuffer),i,len=bytes.length,base64="";for(i=0;i<len;i+=3){base64+=chars[bytes[i]>>2];base64+=chars[(bytes[i]&3)<<4|bytes[i+1]>>4];base64+=chars[(bytes[i+1]&15)<<2|bytes[i+2]>>6];base64+=chars[bytes[i+2]&63]}if(len%3===2){base64=base64.substring(0,base64.length-1)+"="}else if(len%3===1){base64=base64.substring(0,base64.length-2)+"=="}return base64};exports.decode=function(base64){var bufferLength=base64.length*.75,len=base64.length,i,p=0,encoded1,encoded2,encoded3,encoded4;if(base64[base64.length-1]==="="){bufferLength--;if(base64[base64.length-2]==="="){bufferLength--}}var arraybuffer=new ArrayBuffer(bufferLength),bytes=new Uint8Array(arraybuffer);for(i=0;i<len;i+=4){encoded1=chars.indexOf(base64[i]);encoded2=chars.indexOf(base64[i+1]);encoded3=chars.indexOf(base64[i+2]);encoded4=chars.indexOf(base64[i+3]);bytes[p++]=encoded1<<2|encoded2>>4;bytes[p++]=(encoded2&15)<<4|encoded3>>2;bytes[p++]=(encoded3&3)<<6|encoded4&63}return arraybuffer}})("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")},{}],30:[function(_dereq_,module,exports){(function(global){var BlobBuilder=global.BlobBuilder||global.WebKitBlobBuilder||global.MSBlobBuilder||global.MozBlobBuilder;var blobSupported=function(){try{var b=new Blob(["hi"]);return b.size==2}catch(e){return false}}();var blobBuilderSupported=BlobBuilder&&BlobBuilder.prototype.append&&BlobBuilder.prototype.getBlob;function BlobBuilderConstructor(ary,options){options=options||{};var bb=new BlobBuilder;for(var i=0;i<ary.length;i++){bb.append(ary[i])}return options.type?bb.getBlob(options.type):bb.getBlob()}module.exports=function(){if(blobSupported){return global.Blob}else if(blobBuilderSupported){return BlobBuilderConstructor}else{return undefined}}()}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],31:[function(_dereq_,module,exports){(function(global){(function(root){var freeExports=typeof exports=="object"&&exports;var freeModule=typeof module=="object"&&module&&module.exports==freeExports&&module;var freeGlobal=typeof global=="object"&&global;if(freeGlobal.global===freeGlobal||freeGlobal.window===freeGlobal){root=freeGlobal}var stringFromCharCode=String.fromCharCode;function ucs2decode(string){var output=[];var counter=0;var length=string.length;var value;var extra;while(counter<length){value=string.charCodeAt(counter++);if(value>=55296&&value<=56319&&counter<length){extra=string.charCodeAt(counter++);if((extra&64512)==56320){output.push(((value&1023)<<10)+(extra&1023)+65536)}else{output.push(value);counter--}}else{output.push(value)}}return output}function ucs2encode(array){var length=array.length;var index=-1;var value;var output="";while(++index<length){value=array[index];if(value>65535){value-=65536;output+=stringFromCharCode(value>>>10&1023|55296);value=56320|value&1023}output+=stringFromCharCode(value)}return output}function createByte(codePoint,shift){return stringFromCharCode(codePoint>>shift&63|128)}function encodeCodePoint(codePoint){if((codePoint&4294967168)==0){return stringFromCharCode(codePoint)}var symbol="";if((codePoint&4294965248)==0){symbol=stringFromCharCode(codePoint>>6&31|192)}else if((codePoint&4294901760)==0){symbol=stringFromCharCode(codePoint>>12&15|224);symbol+=createByte(codePoint,6)}else if((codePoint&4292870144)==0){symbol=stringFromCharCode(codePoint>>18&7|240);symbol+=createByte(codePoint,12);symbol+=createByte(codePoint,6)}symbol+=stringFromCharCode(codePoint&63|128);return symbol}function utf8encode(string){var codePoints=ucs2decode(string);var length=codePoints.length;var index=-1;var codePoint;var byteString="";while(++index<length){codePoint=codePoints[index];
byteString+=encodeCodePoint(codePoint)}return byteString}function readContinuationByte(){if(byteIndex>=byteCount){throw Error("Invalid byte index")}var continuationByte=byteArray[byteIndex]&255;byteIndex++;if((continuationByte&192)==128){return continuationByte&63}throw Error("Invalid continuation byte")}function decodeSymbol(){var byte1;var byte2;var byte3;var byte4;var codePoint;if(byteIndex>byteCount){throw Error("Invalid byte index")}if(byteIndex==byteCount){return false}byte1=byteArray[byteIndex]&255;byteIndex++;if((byte1&128)==0){return byte1}if((byte1&224)==192){var byte2=readContinuationByte();codePoint=(byte1&31)<<6|byte2;if(codePoint>=128){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&240)==224){byte2=readContinuationByte();byte3=readContinuationByte();codePoint=(byte1&15)<<12|byte2<<6|byte3;if(codePoint>=2048){return codePoint}else{throw Error("Invalid continuation byte")}}if((byte1&248)==240){byte2=readContinuationByte();byte3=readContinuationByte();byte4=readContinuationByte();codePoint=(byte1&15)<<18|byte2<<12|byte3<<6|byte4;if(codePoint>=65536&&codePoint<=1114111){return codePoint}}throw Error("Invalid UTF-8 detected")}var byteArray;var byteCount;var byteIndex;function utf8decode(byteString){byteArray=ucs2decode(byteString);byteCount=byteArray.length;byteIndex=0;var codePoints=[];var tmp;while((tmp=decodeSymbol())!==false){codePoints.push(tmp)}return ucs2encode(codePoints)}var utf8={version:"2.0.0",encode:utf8encode,decode:utf8decode};if(typeof define=="function"&&typeof define.amd=="object"&&define.amd){define(function(){return utf8})}else if(freeExports&&!freeExports.nodeType){if(freeModule){freeModule.exports=utf8}else{var object={};var hasOwnProperty=object.hasOwnProperty;for(var key in utf8){hasOwnProperty.call(utf8,key)&&(freeExports[key]=utf8[key])}}}else{root.utf8=utf8}})(this)}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],32:[function(_dereq_,module,exports){(function(global){var rvalidchars=/^[\],:{}\s]*$/;var rvalidescape=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;var rvalidtokens=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;var rvalidbraces=/(?:^|:|,)(?:\s*\[)+/g;var rtrimLeft=/^\s+/;var rtrimRight=/\s+$/;module.exports=function parsejson(data){if("string"!=typeof data||!data){return null}data=data.replace(rtrimLeft,"").replace(rtrimRight,"");if(global.JSON&&JSON.parse){return JSON.parse(data)}if(rvalidchars.test(data.replace(rvalidescape,"@").replace(rvalidtokens,"]").replace(rvalidbraces,""))){return new Function("return "+data)()}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],33:[function(_dereq_,module,exports){exports.encode=function(obj){var str="";for(var i in obj){if(obj.hasOwnProperty(i)){if(str.length)str+="&";str+=encodeURIComponent(i)+"="+encodeURIComponent(obj[i])}}return str};exports.decode=function(qs){var qry={};var pairs=qs.split("&");for(var i=0,l=pairs.length;i<l;i++){var pair=pairs[i].split("=");qry[decodeURIComponent(pair[0])]=decodeURIComponent(pair[1])}return qry}},{}],34:[function(_dereq_,module,exports){var re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;var parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];module.exports=function parseuri(str){var src=str,b=str.indexOf("["),e=str.indexOf("]");if(b!=-1&&e!=-1){str=str.substring(0,b)+str.substring(b,e).replace(/:/g,";")+str.substring(e,str.length)}var m=re.exec(str||""),uri={},i=14;while(i--){uri[parts[i]]=m[i]||""}if(b!=-1&&e!=-1){uri.source=src;uri.host=uri.host.substring(1,uri.host.length-1).replace(/;/g,":");uri.authority=uri.authority.replace("[","").replace("]","").replace(/;/g,":");uri.ipv6uri=true}return uri}},{}],35:[function(_dereq_,module,exports){var global=function(){return this}();var WebSocket=global.WebSocket||global.MozWebSocket;module.exports=WebSocket?ws:null;function ws(uri,protocols,opts){var instance;if(protocols){instance=new WebSocket(uri,protocols)}else{instance=new WebSocket(uri)}return instance}if(WebSocket)ws.prototype=WebSocket.prototype},{}],36:[function(_dereq_,module,exports){(function(global){var isArray=_dereq_("isarray");module.exports=hasBinary;function hasBinary(data){function _hasBinary(obj){if(!obj)return false;if(global.Buffer&&global.Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer||global.Blob&&obj instanceof Blob||global.File&&obj instanceof File){return true}if(isArray(obj)){for(var i=0;i<obj.length;i++){if(_hasBinary(obj[i])){return true}}}else if(obj&&"object"==typeof obj){if(obj.toJSON){obj=obj.toJSON()}for(var key in obj){if(obj.hasOwnProperty(key)&&_hasBinary(obj[key])){return true}}}return false}return _hasBinary(data)}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{isarray:37}],37:[function(_dereq_,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],38:[function(_dereq_,module,exports){var global=_dereq_("global");try{module.exports="XMLHttpRequest"in global&&"withCredentials"in new global.XMLHttpRequest}catch(err){module.exports=false}},{global:39}],39:[function(_dereq_,module,exports){module.exports=function(){return this}()},{}],40:[function(_dereq_,module,exports){var indexOf=[].indexOf;module.exports=function(arr,obj){if(indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],41:[function(_dereq_,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],42:[function(_dereq_,module,exports){var re=/^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;var parts=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];module.exports=function parseuri(str){var m=re.exec(str||""),uri={},i=14;while(i--){uri[parts[i]]=m[i]||""}return uri}},{}],43:[function(_dereq_,module,exports){(function(global){var isArray=_dereq_("isarray");var isBuf=_dereq_("./is-buffer");exports.deconstructPacket=function(packet){var buffers=[];var packetData=packet.data;function _deconstructPacket(data){if(!data)return data;if(isBuf(data)){var placeholder={_placeholder:true,num:buffers.length};buffers.push(data);return placeholder}else if(isArray(data)){var newData=new Array(data.length);for(var i=0;i<data.length;i++){newData[i]=_deconstructPacket(data[i])}return newData}else if("object"==typeof data&&!(data instanceof Date)){var newData={};for(var key in data){newData[key]=_deconstructPacket(data[key])}return newData}return data}var pack=packet;pack.data=_deconstructPacket(packetData);pack.attachments=buffers.length;return{packet:pack,buffers:buffers}};exports.reconstructPacket=function(packet,buffers){var curPlaceHolder=0;function _reconstructPacket(data){if(data&&data._placeholder){var buf=buffers[data.num];return buf}else if(isArray(data)){for(var i=0;i<data.length;i++){data[i]=_reconstructPacket(data[i])}return data}else if(data&&"object"==typeof data){for(var key in data){data[key]=_reconstructPacket(data[key])}return data}return data}packet.data=_reconstructPacket(packet.data);packet.attachments=undefined;return packet};exports.removeBlobs=function(data,callback){function _removeBlobs(obj,curKey,containingObject){if(!obj)return obj;if(global.Blob&&obj instanceof Blob||global.File&&obj instanceof File){pendingBlobs++;var fileReader=new FileReader;fileReader.onload=function(){if(containingObject){containingObject[curKey]=this.result}else{bloblessData=this.result}if(!--pendingBlobs){callback(bloblessData)}};fileReader.readAsArrayBuffer(obj)}else if(isArray(obj)){for(var i=0;i<obj.length;i++){_removeBlobs(obj[i],i,obj)}}else if(obj&&"object"==typeof obj&&!isBuf(obj)){for(var key in obj){_removeBlobs(obj[key],key,obj)}}}var pendingBlobs=0;var bloblessData=data;_removeBlobs(bloblessData);if(!pendingBlobs){callback(bloblessData)}}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{"./is-buffer":45,isarray:46}],44:[function(_dereq_,module,exports){var debug=_dereq_("debug")("socket.io-parser");var json=_dereq_("json3");var isArray=_dereq_("isarray");var Emitter=_dereq_("component-emitter");var binary=_dereq_("./binary");var isBuf=_dereq_("./is-buffer");exports.protocol=4;exports.types=["CONNECT","DISCONNECT","EVENT","BINARY_EVENT","ACK","BINARY_ACK","ERROR"];exports.CONNECT=0;exports.DISCONNECT=1;exports.EVENT=2;exports.ACK=3;exports.ERROR=4;exports.BINARY_EVENT=5;exports.BINARY_ACK=6;exports.Encoder=Encoder;exports.Decoder=Decoder;function Encoder(){}Encoder.prototype.encode=function(obj,callback){debug("encoding packet %j",obj);if(exports.BINARY_EVENT==obj.type||exports.BINARY_ACK==obj.type){encodeAsBinary(obj,callback)}else{var encoding=encodeAsString(obj);callback([encoding])}};function encodeAsString(obj){var str="";var nsp=false;str+=obj.type;if(exports.BINARY_EVENT==obj.type||exports.BINARY_ACK==obj.type){str+=obj.attachments;str+="-"}if(obj.nsp&&"/"!=obj.nsp){nsp=true;str+=obj.nsp}if(null!=obj.id){if(nsp){str+=",";nsp=false}str+=obj.id}if(null!=obj.data){if(nsp)str+=",";str+=json.stringify(obj.data)}debug("encoded %j as %s",obj,str);return str}function encodeAsBinary(obj,callback){function writeEncoding(bloblessData){var deconstruction=binary.deconstructPacket(bloblessData);var pack=encodeAsString(deconstruction.packet);var buffers=deconstruction.buffers;buffers.unshift(pack);callback(buffers)}binary.removeBlobs(obj,writeEncoding)}function Decoder(){this.reconstructor=null}Emitter(Decoder.prototype);Decoder.prototype.add=function(obj){var packet;if("string"==typeof obj){packet=decodeString(obj);if(exports.BINARY_EVENT==packet.type||exports.BINARY_ACK==packet.type){this.reconstructor=new BinaryReconstructor(packet);if(this.reconstructor.reconPack.attachments==0){this.emit("decoded",packet)}}else{this.emit("decoded",packet)}}else if(isBuf(obj)||obj.base64){if(!this.reconstructor){throw new Error("got binary data when not reconstructing a packet")}else{packet=this.reconstructor.takeBinaryData(obj);if(packet){this.reconstructor=null;this.emit("decoded",packet)}}}else{throw new Error("Unknown type: "+obj)}};function decodeString(str){var p={};var i=0;p.type=Number(str.charAt(0));if(null==exports.types[p.type])return error();if(exports.BINARY_EVENT==p.type||exports.BINARY_ACK==p.type){p.attachments="";while(str.charAt(++i)!="-"){p.attachments+=str.charAt(i)}p.attachments=Number(p.attachments)}if("/"==str.charAt(i+1)){p.nsp="";while(++i){var c=str.charAt(i);if(","==c)break;p.nsp+=c;if(i+1==str.length)break}}else{p.nsp="/"}var next=str.charAt(i+1);if(""!=next&&Number(next)==next){p.id="";while(++i){var c=str.charAt(i);if(null==c||Number(c)!=c){--i;break}p.id+=str.charAt(i);if(i+1==str.length)break}p.id=Number(p.id)}if(str.charAt(++i)){try{p.data=json.parse(str.substr(i))}catch(e){return error()}}debug("decoded %s as %j",str,p);return p}Decoder.prototype.destroy=function(){if(this.reconstructor){this.reconstructor.finishedReconstruction()}};function BinaryReconstructor(packet){this.reconPack=packet;this.buffers=[]}BinaryReconstructor.prototype.takeBinaryData=function(binData){this.buffers.push(binData);if(this.buffers.length==this.reconPack.attachments){var packet=binary.reconstructPacket(this.reconPack,this.buffers);this.finishedReconstruction();return packet}return null};BinaryReconstructor.prototype.finishedReconstruction=function(){this.reconPack=null;this.buffers=[]};function error(data){return{type:exports.ERROR,data:"parser error"}}},{"./binary":43,"./is-buffer":45,"component-emitter":9,debug:10,isarray:46,json3:47}],45:[function(_dereq_,module,exports){(function(global){module.exports=isBuf;function isBuf(obj){return global.Buffer&&global.Buffer.isBuffer(obj)||global.ArrayBuffer&&obj instanceof ArrayBuffer}}).call(this,typeof self!=="undefined"?self:typeof window!=="undefined"?window:{})},{}],46:[function(_dereq_,module,exports){module.exports=_dereq_(37)},{}],47:[function(_dereq_,module,exports){(function(window){var getClass={}.toString,isProperty,forEach,undef;var isLoader=typeof define==="function"&&define.amd;var nativeJSON=typeof JSON=="object"&&JSON;var JSON3=typeof exports=="object"&&exports&&!exports.nodeType&&exports;if(JSON3&&nativeJSON){JSON3.stringify=nativeJSON.stringify;JSON3.parse=nativeJSON.parse}else{JSON3=window.JSON=nativeJSON||{}}var isExtended=new Date(-0xc782b5b800cec);try{isExtended=isExtended.getUTCFullYear()==-109252&&isExtended.getUTCMonth()===0&&isExtended.getUTCDate()===1&&isExtended.getUTCHours()==10&&isExtended.getUTCMinutes()==37&&isExtended.getUTCSeconds()==6&&isExtended.getUTCMilliseconds()==708}catch(exception){}function has(name){if(has[name]!==undef){return has[name]}var isSupported;if(name=="bug-string-char-index"){isSupported="a"[0]!="a"}else if(name=="json"){isSupported=has("json-stringify")&&has("json-parse")}else{var value,serialized='{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';if(name=="json-stringify"){var stringify=JSON3.stringify,stringifySupported=typeof stringify=="function"&&isExtended;if(stringifySupported){(value=function(){return 1}).toJSON=value;try{stringifySupported=stringify(0)==="0"&&stringify(new Number)==="0"&&stringify(new String)=='""'&&stringify(getClass)===undef&&stringify(undef)===undef&&stringify()===undef&&stringify(value)==="1"&&stringify([value])=="[1]"&&stringify([undef])=="[null]"&&stringify(null)=="null"&&stringify([undef,getClass,null])=="[null,null,null]"&&stringify({a:[value,true,false,null,"\x00\b\n\f\r	"]})==serialized&&stringify(null,value)==="1"&&stringify([1,2],null,1)=="[\n 1,\n 2\n]"&&stringify(new Date(-864e13))=='"-271821-04-20T00:00:00.000Z"'&&stringify(new Date(864e13))=='"+275760-09-13T00:00:00.000Z"'&&stringify(new Date(-621987552e5))=='"-000001-01-01T00:00:00.000Z"'&&stringify(new Date(-1))=='"1969-12-31T23:59:59.999Z"'}catch(exception){stringifySupported=false}}isSupported=stringifySupported}if(name=="json-parse"){var parse=JSON3.parse;if(typeof parse=="function"){try{if(parse("0")===0&&!parse(false)){value=parse(serialized);var parseSupported=value["a"].length==5&&value["a"][0]===1;if(parseSupported){try{parseSupported=!parse('"	"')}catch(exception){}if(parseSupported){try{parseSupported=parse("01")!==1}catch(exception){}}if(parseSupported){try{parseSupported=parse("1.")!==1}catch(exception){}}}}}catch(exception){parseSupported=false}}isSupported=parseSupported}}return has[name]=!!isSupported}if(!has("json")){var functionClass="[object Function]";var dateClass="[object Date]";var numberClass="[object Number]";var stringClass="[object String]";var arrayClass="[object Array]";var booleanClass="[object Boolean]";var charIndexBuggy=has("bug-string-char-index");if(!isExtended){var floor=Math.floor;var Months=[0,31,59,90,120,151,181,212,243,273,304,334];var getDay=function(year,month){return Months[month]+365*(year-1970)+floor((year-1969+(month=+(month>1)))/4)-floor((year-1901+month)/100)+floor((year-1601+month)/400)}}if(!(isProperty={}.hasOwnProperty)){isProperty=function(property){var members={},constructor;if((members.__proto__=null,members.__proto__={toString:1},members).toString!=getClass){isProperty=function(property){var original=this.__proto__,result=property in(this.__proto__=null,this);this.__proto__=original;return result}}else{constructor=members.constructor;isProperty=function(property){var parent=(this.constructor||constructor).prototype;return property in this&&!(property in parent&&this[property]===parent[property])}}members=null;return isProperty.call(this,property)}}var PrimitiveTypes={"boolean":1,number:1,string:1,undefined:1};var isHostType=function(object,property){var type=typeof object[property];return type=="object"?!!object[property]:!PrimitiveTypes[type]};forEach=function(object,callback){var size=0,Properties,members,property;(Properties=function(){this.valueOf=0}).prototype.valueOf=0;members=new Properties;for(property in members){if(isProperty.call(members,property)){size++}}Properties=members=null;if(!size){members=["valueOf","toString","toLocaleString","propertyIsEnumerable","isPrototypeOf","hasOwnProperty","constructor"];forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,length;var hasProperty=!isFunction&&typeof object.constructor!="function"&&isHostType(object,"hasOwnProperty")?object.hasOwnProperty:isProperty;for(property in object){if(!(isFunction&&property=="prototype")&&hasProperty.call(object,property)){callback(property)}}for(length=members.length;property=members[--length];hasProperty.call(object,property)&&callback(property));}}else if(size==2){forEach=function(object,callback){var members={},isFunction=getClass.call(object)==functionClass,property;for(property in object){if(!(isFunction&&property=="prototype")&&!isProperty.call(members,property)&&(members[property]=1)&&isProperty.call(object,property)){callback(property)}}}}else{forEach=function(object,callback){var isFunction=getClass.call(object)==functionClass,property,isConstructor;for(property in object){if(!(isFunction&&property=="prototype")&&isProperty.call(object,property)&&!(isConstructor=property==="constructor")){callback(property)}}if(isConstructor||isProperty.call(object,property="constructor")){callback(property)}}}return forEach(object,callback)};if(!has("json-stringify")){var Escapes={92:"\\\\",34:'\\"',8:"\\b",12:"\\f",10:"\\n",13:"\\r",9:"\\t"};var leadingZeroes="000000";var toPaddedString=function(width,value){return(leadingZeroes+(value||0)).slice(-width)};var unicodePrefix="\\u00";var quote=function(value){var result='"',index=0,length=value.length,isLarge=length>10&&charIndexBuggy,symbols;if(isLarge){symbols=value.split("")}for(;index<length;index++){var charCode=value.charCodeAt(index);switch(charCode){case 8:case 9:case 10:case 12:case 13:case 34:case 92:result+=Escapes[charCode];break;default:if(charCode<32){result+=unicodePrefix+toPaddedString(2,charCode.toString(16));break}result+=isLarge?symbols[index]:charIndexBuggy?value.charAt(index):value[index]}}return result+'"'};var serialize=function(property,object,callback,properties,whitespace,indentation,stack){var value,className,year,month,date,time,hours,minutes,seconds,milliseconds,results,element,index,length,prefix,result;try{value=object[property]}catch(exception){}if(typeof value=="object"&&value){className=getClass.call(value);if(className==dateClass&&!isProperty.call(value,"toJSON")){if(value>-1/0&&value<1/0){if(getDay){date=floor(value/864e5);for(year=floor(date/365.2425)+1970-1;getDay(year+1,0)<=date;year++);for(month=floor((date-getDay(year,0))/30.42);getDay(year,month+1)<=date;month++);date=1+date-getDay(year,month);time=(value%864e5+864e5)%864e5;hours=floor(time/36e5)%24;minutes=floor(time/6e4)%60;seconds=floor(time/1e3)%60;milliseconds=time%1e3}else{year=value.getUTCFullYear();month=value.getUTCMonth();date=value.getUTCDate();hours=value.getUTCHours();minutes=value.getUTCMinutes();seconds=value.getUTCSeconds();milliseconds=value.getUTCMilliseconds()}value=(year<=0||year>=1e4?(year<0?"-":"+")+toPaddedString(6,year<0?-year:year):toPaddedString(4,year))+"-"+toPaddedString(2,month+1)+"-"+toPaddedString(2,date)+"T"+toPaddedString(2,hours)+":"+toPaddedString(2,minutes)+":"+toPaddedString(2,seconds)+"."+toPaddedString(3,milliseconds)+"Z"}else{value=null}}else if(typeof value.toJSON=="function"&&(className!=numberClass&&className!=stringClass&&className!=arrayClass||isProperty.call(value,"toJSON"))){value=value.toJSON(property)}}if(callback){value=callback.call(object,property,value)}if(value===null){return"null"}className=getClass.call(value);if(className==booleanClass){return""+value}else if(className==numberClass){return value>-1/0&&value<1/0?""+value:"null"}else if(className==stringClass){return quote(""+value)}if(typeof value=="object"){for(length=stack.length;length--;){if(stack[length]===value){throw TypeError()}}stack.push(value);results=[];prefix=indentation;indentation+=whitespace;if(className==arrayClass){for(index=0,length=value.length;index<length;index++){element=serialize(index,value,callback,properties,whitespace,indentation,stack);results.push(element===undef?"null":element)}result=results.length?whitespace?"[\n"+indentation+results.join(",\n"+indentation)+"\n"+prefix+"]":"["+results.join(",")+"]":"[]"}else{forEach(properties||value,function(property){var element=serialize(property,value,callback,properties,whitespace,indentation,stack);if(element!==undef){results.push(quote(property)+":"+(whitespace?" ":"")+element)}});result=results.length?whitespace?"{\n"+indentation+results.join(",\n"+indentation)+"\n"+prefix+"}":"{"+results.join(",")+"}":"{}"}stack.pop();return result}};JSON3.stringify=function(source,filter,width){var whitespace,callback,properties,className;if(typeof filter=="function"||typeof filter=="object"&&filter){if((className=getClass.call(filter))==functionClass){callback=filter}else if(className==arrayClass){properties={};for(var index=0,length=filter.length,value;index<length;value=filter[index++],(className=getClass.call(value),className==stringClass||className==numberClass)&&(properties[value]=1));}}if(width){if((className=getClass.call(width))==numberClass){if((width-=width%1)>0){for(whitespace="",width>10&&(width=10);whitespace.length<width;whitespace+=" ");}}else if(className==stringClass){whitespace=width.length<=10?width:width.slice(0,10)}}return serialize("",(value={},value[""]=source,value),callback,properties,whitespace,"",[])}}if(!has("json-parse")){var fromCharCode=String.fromCharCode;var Unescapes={92:"\\",34:'"',47:"/",98:"\b",116:"	",110:"\n",102:"\f",114:"\r"};var Index,Source;var abort=function(){Index=Source=null;throw SyntaxError()};var lex=function(){var source=Source,length=source.length,value,begin,position,isSigned,charCode;while(Index<length){charCode=source.charCodeAt(Index);switch(charCode){case 9:case 10:case 13:case 32:Index++;break;case 123:case 125:case 91:case 93:case 58:case 44:value=charIndexBuggy?source.charAt(Index):source[Index];Index++;return value;case 34:for(value="@",Index++;Index<length;){charCode=source.charCodeAt(Index);if(charCode<32){abort()}else if(charCode==92){charCode=source.charCodeAt(++Index);switch(charCode){case 92:case 34:case 47:case 98:case 116:case 110:case 102:case 114:value+=Unescapes[charCode];Index++;break;case 117:begin=++Index;for(position=Index+4;Index<position;Index++){charCode=source.charCodeAt(Index);if(!(charCode>=48&&charCode<=57||charCode>=97&&charCode<=102||charCode>=65&&charCode<=70)){abort()}}value+=fromCharCode("0x"+source.slice(begin,Index));break;default:abort()}}else{if(charCode==34){break}charCode=source.charCodeAt(Index);begin=Index;while(charCode>=32&&charCode!=92&&charCode!=34){charCode=source.charCodeAt(++Index)}value+=source.slice(begin,Index)}}if(source.charCodeAt(Index)==34){Index++;return value}abort();default:begin=Index;if(charCode==45){isSigned=true;charCode=source.charCodeAt(++Index)}if(charCode>=48&&charCode<=57){if(charCode==48&&(charCode=source.charCodeAt(Index+1),charCode>=48&&charCode<=57)){abort()}isSigned=false;for(;Index<length&&(charCode=source.charCodeAt(Index),charCode>=48&&charCode<=57);Index++);if(source.charCodeAt(Index)==46){position=++Index;for(;position<length&&(charCode=source.charCodeAt(position),charCode>=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}charCode=source.charCodeAt(Index);if(charCode==101||charCode==69){charCode=source.charCodeAt(++Index);if(charCode==43||charCode==45){Index++}for(position=Index;position<length&&(charCode=source.charCodeAt(position),charCode>=48&&charCode<=57);position++);if(position==Index){abort()}Index=position}return+source.slice(begin,Index)}if(isSigned){abort()}if(source.slice(Index,Index+4)=="true"){Index+=4;return true}else if(source.slice(Index,Index+5)=="false"){Index+=5;return false}else if(source.slice(Index,Index+4)=="null"){Index+=4;return null}abort()}}return"$"};var get=function(value){var results,hasMembers;if(value=="$"){abort()}if(typeof value=="string"){if((charIndexBuggy?value.charAt(0):value[0])=="@"){return value.slice(1)}if(value=="["){results=[];for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="]"){break}if(hasMembers){if(value==","){value=lex();if(value=="]"){abort()}}else{abort()}}if(value==","){abort()}results.push(get(value))}return results}else if(value=="{"){results={};for(;;hasMembers||(hasMembers=true)){value=lex();if(value=="}"){break}if(hasMembers){if(value==","){value=lex();if(value=="}"){abort()}}else{abort()}}if(value==","||typeof value!="string"||(charIndexBuggy?value.charAt(0):value[0])!="@"||lex()!=":"){abort()}results[value.slice(1)]=get(lex())}return results}abort()}return value};var update=function(source,property,callback){var element=walk(source,property,callback);if(element===undef){delete source[property]}else{source[property]=element}};var walk=function(source,property,callback){var value=source[property],length;if(typeof value=="object"&&value){if(getClass.call(value)==arrayClass){for(length=value.length;length--;){update(value,length,callback)}}else{forEach(value,function(property){update(value,property,callback)})}}return callback.call(source,property,value)};JSON3.parse=function(source,callback){var result,value;Index=0;Source=""+source;result=get(lex());if(lex()!="$"){abort()}Index=Source=null;return callback&&getClass.call(callback)==functionClass?walk((value={},value[""]=result,value),"",callback):result}}}if(isLoader){define(function(){return JSON3})}})(this)},{}],48:[function(_dereq_,module,exports){module.exports=toArray;function toArray(list,index){var array=[];index=index||0;for(var i=index||0;i<list.length;i++){array[i-index]=list[i]}return array}},{}]},{},[1])(1)});var disp_setting={"imgurl":"https://cp.chamo-chat.com/common/default/default1.png","place":"right","colormodel":{"main1":"#BA1CAF","bg":"#FFFFFF","balloon":"#BEF18C","font1":"#5D5967","font2":"#AAAAAA","font3":"#FFFFFF"},"name":"東洋堂チャットオペレーター","title":"チャット受付中","desc":"お気軽にご質問ください＾＾","title_mini":"ご質問はチャットでどうぞ♪","placeholder_mini":"チャット受付中！","sm_waiting_mode":0,"offline_title":"メッセージ受付","offline_body":"ご訪問ありがとうございます。\r\nこちらからお問い合わせいただけます。\r\n後ほど担当者よりご連絡さしあげます。\r\n\r\nメッセージ\r\n{textarea:required}\r\nメールアドレス*\r\n{email:required}\r\nお名前（ニックネーム可）\r\n{name}\r\n\r\n","auto_response":1,"offline_title_mini":"メッセージ受付中","offline_desc_mini":"お問い合わせはこちらから","always_online":1};var display_past_chatlog = 0;var account_triggers=[{"id":2179,"timing":{"account_state":"WITH_OPERATOR","on":"IN_SITE","time":10},"info":{"selector":"AND","conditions":[{"on":"NONE"}],"actions":[{"do":"SEND_MESSAGE","detail":"ご訪問ありがとうございます。ご不明な点がございましたら、こちらからチャットにてご質問いただけます。"}]}},{"id":2180,"timing":{"account_state":"WITH_OPERATOR","on":"IN_SITE","time":66},"info":{"selector":"AND","conditions":[{"on":"OPERATOR_NOSPOKE"}],"actions":[{"do":"SEND_MESSAGE","detail":"お聞きになりたいことなどございませんでしょうか？チャットにてお気軽にお尋ねください。"}]}},{"id":2182,"timing":{"account_state":"NO_OPERATOR","on":"AFTER_MESSAGE","time":0},"info":{"selector":"AND","conditions":[{"on":"NONE"}],"actions":[{"do":"SEND_MESSAGE","detail":"お問い合わせありがとうございます。こちらからメッセージを残していただけますか？"}]}}];var extra_options={};var USE_API = 0;  //////// View ////////
  var cv = {
    chamo: {},
    isForbidUserscalable: false,
    isInputFocused: false,
    innerWidth: 0,
    innerHeight: 1,
    zoom: -1,
    scrollHeight: 0,
    orientation: null,
    timers: {},
    scroll: {top: 0, left: 0},
    init: function() {
      $.each(cv.timers, function(name, timer) {clearTimeout(timer);});
      $('div.-chamo-toplevel-container').remove();
      // 古いIEにおいて、埋め込み動画でz-indexが反映されない問題
      var browser = cm.getBrowser();
      if (browser == 'IE 6' || browser == 'IE 7' || browser == 'IE 8' || browser == 'IE 9') {
        $('iframe').each(function() {
          if (!$(this).attr('src') ||
            $(this).attr('src').indexOf('youtube.com') == -1 ||
            $(this).attr('src').indexOf('wmode=transparent') != -1 ) {
            return;
          }
          if ($(this).attr('src').indexOf('?') != -1) {
            $(this).attr('src', $(this).attr('src') + '&wmode=transparent');
          } else {
            $(this).attr('src', $(this).attr('src') + '?wmode=transparent');
          }
        });
      }

      cv.createDOM();
      cv.setEvent();
      // Resize
      var resizeTimer = function(isForcely) {
        cv.resize(isForcely);
        cv.timers.resize = window.setTimeout(resizeTimer, 300);
      };
      resizeTimer(true);
    },
    createDOM: function() {
      // 画像URLをプロトコルにあわせる
      //var account_img_url = cm.account["imgurl"].replace("https://","").replace("http://","").replace(hostname + "/","");
      //cm.account["imgurl"] = hosturl + account_img_url;
      // 表示位置の調整
      var pc_bottom = '';
      if (cm.account.placeDetail &&
          isFinite(cm.account.placeDetail.pc_bottom) &&
          cm.account.placeDetail.pc_bottom_unit) {
        pc_bottom = (cm.account.placeDetail.pc_bottom - 0) +
            ((cm.account.placeDetail.pc_bottom_unit == 'percent') ? '%' : 'px');
        addStyleRule('#chamo-window, #chamo-window #chamo-waiting,' +
            ' #chamo-window #chamo-chatting,' +
            ' #chamo-window #chamo-offline-waiting,' +
            ' #chamo-window #chamo_offline_mail_form',
                'bottom:' + pc_bottom + ' !important;');
      } else {
        pc_bottom = '0px';
      }
      // オフライン時メッセージを整形する関数
      var format_html = function(text) {
        var pos1, pos2;
        var parBefore, parIn, parAfter;
        var options, no_css3;
        while (text.indexOf('{') != -1) {
          // 文字列を {} の前後で分解
          pos1 = text.indexOf('{');
          parBefore = text.substring(0, pos1);
          parAfter = text.substring(pos1 + 1);
          pos2 = parAfter.indexOf('}');
          parIn = parAfter.substring(0, pos2);
          parAfter = parAfter.substring(pos2 + 2);
          // inputを挿入
          text = parBefore;
          options = parIn.split(':');
          var element_class = 'chamo_offline_message_element' +
              (($.inArray('required', options) >= 0) ? ' chamo-required' : '');
          switch (options[0]) {
            case 'name':
              text += '<input type="text" placeholder="' +
                  Localizer.getValue('form-name') +
                  '" id="message[name]" name="NAME" class="' +
                  element_class + '">';
              break;
            case 'email':
              text += '<input type="email" placeholder="' +
                  Localizer.getValue('form-email') +
                  '" id="message[email]" name="EMAIL" class="' +
                  element_class + '">';
              break;
            case 'textarea':
              text += '<textarea placeholder="' +
                  Localizer.getValue('form-message') +
                  '" id="message[textarea]" name="MESSAGE" class="' +
                  element_class + '"></textarea>';
              break;
            case 'checkbox':
              element_class += ' checkbox';
              text += '<input type="checkbox" id="message[' + options[1] +
                  ']" name="' + options[1] + '" class="' + element_class +
                  '" value="check" style="display:inline-block;">';
              break;
            case 'link':
              var linkto = options[2] + ':' + options[3];
              var target = (options[4]) ? options[4] : '_self';
              text += '<a href="' + linkto + '" target="' + target + '">' +
                  options[1] + '</a>';
              break;
            case 'label':
              text += '<label for="message[' + options[1] + ']">' +
                  options[2] + '</label>';
              break;
            default:
              options[0] = options[0].replace('{', '');
              text += '<input type="text" id="message[' + options[0] +
                  ']" name="' + options[0] + '" class="' + element_class + '">';
              break;
          }
          text += parAfter;
        }
        text = text.replace(/\r?\n/g, '<br />');
        return text;
      };

      // parameters
      var chatWidth, chatHeight, chatWaitingWidth,
          chatFontSize, chatLineHeight;
      var chamoTextMinimize;
      chatWaitingWidth = 240;
      chatWidth = 288;
      chatHeight = 400;
      chamoTextMinimize = '×';
      chatFontSize = 13;
      chatLineHeight = 24;
      chatTitlebarHeight = 24;
      chatDescbarHeight = 36;
      chatFooterHeight = 72;
      chatImageSize = 50;
      var appVersion = window.navigator.appVersion.toLowerCase();
      no_css3 = ((appVersion.indexOf('msie 6.') != -1) ||
          (appVersion.indexOf('msie 7.') != -1) ||
          (appVersion.indexOf('msie 8.') != -1));

      function getFrameBase(title) {
        return $('<div>', {
          'class': 'chamo_frame chamo_pc chamo_pcif' +
              ((no_css3) ? ' no_css3' : '')
        }).css({
          'background-color': cm.account.colormodel['bg']
        }).append($('<div>', {
          'class': 'chamo-titlebar'
        }).css({
          'background-color': cm.account.colormodel['main1'],
          'height': chatTitlebarHeight + 'px',
          'position': 'relative'
        }).append($('<div>').css({
          'line-height': chatTitlebarHeight + 'px',
          'text-align': 'left',
          'color': cm.account.colormodel['font3']
        }).html(title)));
      }
      function getMinimumFrame(title) {
        return $('<div>', {
          'class': 'chamo_frame scroll_and_transparent chamo_pc chamo_pcif' +
              ((no_css3) ? ' no_css3' : '')
        }).append($('<img src="' + chamo_sm_imgurl + '">').css({
          'width': chatImageSize + 'px',
          'height': chatImageSize + 'px'
        })).css({
          'position': 'fixed',
          'bottom': '4px',
          'right': '4px',
          'opacity': 0.5,
          'width': chatImageSize + 'px',
          'height': chatImageSize + 'px',
        });
      }
      function getSmallFrame(title, desc, imgurl) {
        var base = getFrameBase(title);
        base.find('.chamo-titlebar div').css('margin-left',
            (chatImageSize + 15) + 'px');
        return base.css({
          'width': chatWaitingWidth + 'px',
          'cursor': 'pointer'
        }).append($('<div>', {
          'class': 'chamo_descbar'
        }).css({
          'width': '100%',
          'height': chatDescbarHeight + 'px',
          'background-color': cm.account.colormodel['bg']
        }).append($('<div>').css({
          'margin-left': (chatImageSize + 15) + 'px',
          'line-height': chatTitlebarHeight + 'px',
          'padding-top': (chatDescbarHeight - chatTitlebarHeight) / 2 + 'px',
          'text-align': 'left',
          'color': cm.account.colormodel['font1'],
        }).html(desc))).append($('<img>', {
          'src': imgurl, 'class': 'image_border'
        }).css({
          'position': 'absolute',
          'left': '5px',
          'bottom': '5px',
          'width': chatImageSize + 'px',
          'height': chatImageSize + 'px',
        //'border-color': cm.account.colormodel['font2'],
          'border-radius': '3px',
        }));
      }
      function getMediumFrame(title) {
        var base = getFrameBase(title);
        base.find('.chamo-titlebar div').css('text-align', 'center');
        if (!cm.isSmartInterface) {
          if (location.hostname.indexOf('rakuten') != -1) {
            var chamo_link = "<span style='color:" +
              cm.account.colormodel['font2'] +
              ";font-size:10px;' class='chamo_link chamo-poweredby'>powered by " +
              CHAMO_SERVICE_NAME + '</span>';
          } else if ($.inArray(accountID, [3407]) != -1) {
            var chamo_link = "<span style='color:" +
              cm.account.colormodel['font2'] +
              ";font-size:10px;' class='chamo_link chamo-poweredby'>powered by " +
              CHAMO_SERVICE_NAME + '</span>';
          } else if ($.inArray(accountID, [1973, 1961, 3842]) == -1) {
            var chamo_link = "<a onclick='return window.confirm(\"" + Localizer.getValue("confirm-move-chamo") +
              "\");'  href='" + refferel + "' style='color:" +
              cm.account.colormodel['font2'] +
              ";font-size:10px;text-decoration:underline;' target='_blank' class='chamo_link chamo-poweredby'>No.1チャットシステム" +
              CHAMO_SERVICE_NAME + '</a>';
          } else {
            var chamo_link = "<a onclick='return window.confirm(\"" + Localizer.getValue("confirm-move-chamo") +
                "\");'  href='" + refferel + "' style='color:" +
                cm.account.colormodel['font2'] +
                ";font-size:10px;text-decoration:none;' target='_blank' class='chamo_link chamo-poweredby'>powered by " +
                CHAMO_SERVICE_NAME + '</a>';
          }
        }
        var _frame = base.css({
          'width': chatWidth + 'px',
          //'height': chatHeight + 'px'
        }).append($('<div>', {
          'class': 'chamo_main'
        }).css({
          'height': (chatHeight - chatTitlebarHeight - chatFooterHeight) + 'px',
          'width': (chatWidth - 2) + 'px',
          'position': 'relative',
          'color': cm.account.colormodel['font1'],
          'background-color': cm.account.colormodel['bg']
        })).append($('<div>', {
          'class': 'chamo_footer'
        }).css({
          'height': chatFooterHeight + 'px',
          'width': (chatWidth - 2) + 'px',
        //'box-shadow': '0 4px 4px #ccc inset',
          'border-top': '1px solid #ccc',
          'position': 'relative',
          'background-color': cm.account.colormodel['bg'],
        }).append($('<div>').css({
          'position': 'absolute',
          'left': '10px',
          'bottom': '4px'
        }).html(chamo_link)));
        if (cm.account.allow_hide) {
          _frame.find('.chamo_footer').append($('<a>', {
            'class': 'hide_by_user chamo_link', 'href': '#'
          }).css({
            'position': 'absolute',
            'right': '6px',
            'bottom': '4px',
            'color': cm.account.colormodel['font2'],
            'font-size': '0.85em !important',
            'text-decoration': 'none',
          }).text(Localizer.getValue('widget-hidechat')));
        }
        return _frame;
      }


      // Set Audio
      $('body:first').append($('<div>').append($('<audio>').attr({
        id: 'chamo-audio-operatorpost',
        preload: 'auto'
      }).append($('<source>', {
        src: chamo_audio_operator_post + '.mp3',
        type: 'audio/mp3'
      })).append($('<source>', {
        src: chamo_audio_operator_post + '.ogg',
        type: 'audio/ogg'
      }))));
      this.chamo.audio_operator_post = document.getElementById('chamo-audio-operatorpost');

      this.chamo.base = $('<div>', {id: 'chamo-window'});

      // 待機中
      this.chamo.mini_input = $('<input>', {
        'type': 'text',
        'value': cm.account.placeholder_mini,
        'id': 'chamo-chatting-input'
      }).css({
        width: (chatWaitingWidth - chatImageSize - 35) + 'px',
        height: chatLineHeight + 'px'
      });

      this.chamo.waiting =
          getSmallFrame(
              cm.account.title_mini,
              $('<div>').append(this.chamo.mini_input).html(),
              cm.account['imgurl']
          ).
          attr('id', 'chamo-waiting').
          css(cm.account.place, '20px').
          append($('<span id="chamo-mesmes">').hide());

      // チャットフォーム
      this.chamo.chatting = getMediumFrame(cm.account['title']).
          attr('id', 'chamo-chatting').
          css(cm.account.place, '20px');
      this.chamo.chatting.find('.chamo-titlebar').
          //append(
          //    $('<div>',{'title':'最大化', 'class':'chamo-titlebar-leftbutton'}).
          //    html("<img src='"+hosturl+"common/img/buttons_maximize.gif' class='chamo-image-buttonsize'>").
          //    addClass('chamo-button-maximize')
          //).
          append($('<div>', {
            'title': Localizer.getValue('widget-minimize'),
            'class': 'chamo-titlebar-rightbutton'
          }).html('&times;').addClass('chamo-button-minimize'));
      var chamo_main_row = (function() {
        var cnt = 0;
        cnt += (cm.account['name']) ? 1 : 0;
        cnt += Math.ceil(strip_tags(cm.account['desc']).length / 18);
        return cnt;
      })();
      // 過去チャット用プロパティ
      this.chamo.past_chat_buffer = $('<div>');
      this.chamo.past_chatlog_link = $('<a>', {
        'class': 'chamo-chatlog-link',
      }).css({
        'display': 'none',
        'margin-top': '10px',
        'text-align': 'center',
        'color': '#0092C4',
        'text-decoration': 'none',
        'cursor': 'pointer',
      }).html('過去のチャット履歴を取得');
      this.chamo.chatlog_wrapper = $('<div>', {
        'class': 'chamo-chatlog-wrapper'
      }).css({
        'height': (chatHeight - chatTitlebarHeight -
            chatLineHeight * chamo_main_row - chatFooterHeight - 1) + 'px'
      });
      this.chamo.chatlog = $('<div>');
      this.chamo.chatlog_wrapper.
          append($('<div>').//css({ margin: '1em 0.4em' }).
              append(this.chamo.past_chatlog_link).
              append(this.chamo.chatlog));
      this.chamo.statusbar = $('<div>', {
        'class': 'chamo-statusbar'
      }).css({
        'color': cm.account.colormodel['font2'],
        'text-align': 'center',
        'line-height': chatLineHeight + 'px'
      }).appendTo(this.chamo.chatlog_wrapper);
      this.chamo.chatting.append($('<img>', {
        'src': cm.account['imgurl'],
        'id': 'chamo-image',
        'class': 'image_border'
      }).css({
        'position': 'absolute',
        'left': '10px',
        'top': '10px',
        'width': chatImageSize + 'px',
        'height': chatImageSize + 'px',
        //'border-color': cm.account.colormodel['font2'],
        'border-radius': '3px',
      }));
      this.chamo.chatting.find('.chamo_main').append($('<div>').css({
        'margin-left': (chatImageSize + 20) + 'px',
        'line-height': chatLineHeight + 'px',
        'height': (chatLineHeight * chamo_main_row) + 'px',
        'text-align': 'left',
        'padding-right': '5px',
      }).html(((cm.account['name']) ?
          ("<span style='color:" + cm.account.colormodel['main1'] + ";'>" + cm.account['name'] + '</span><br>') : '') +
              "<span style='color:" + cm.account.colormodel['font2'] + ";'>" + cm.account['desc'] + '</span>')).
          append(this.chamo.chatlog_wrapper);
      this.chamo.textarea = $('<textarea>', {
        'id': 'chamo-chat-textarea',
        'placeholder': Localizer.getValue('widget-sendenter')
      }).css({
        'width': (chatWidth - (chatFontSize * 2)) + 'px',
        'height': chatFontSize * 2.5 + 'px',
      //'margin': '14px auto 0 auto',
        'margin': 0,
        'position': 'absolute',
        'top': (chatFontSize) + 'px',
        'left': (chatFontSize) + 'px',
      });
      this.chamo.sendbutton = $('<div>');
      this.chamo.chatting.find('.chamo_footer').
          append(this.chamo.textarea).
          append(this.chamo.sendbutton);
      // 送信失敗
      this.chamo.send_error_message = $('<div id="send_error_message">').css({
        color: '#FFFFFF',
        background: '#999999'
      }).appendTo(cv.chamo.chatting);

      // 最大化状態
      this.chamo.chatlog_maximum = $('<div>');
      this.chamo.chatlog_wrapper_maximum = $('<div>');

      // オフライン時待機中
      this.chamo.offline_waiting =
          getSmallFrame(cm.account.offline_title_mini, cm.account.offline_desc_mini, chamo_email_imgurl).
          attr('id', 'chamo-offline-waiting').
          css(cm.account.place, '20px');

      // オフライン時のメッセージ受付フォーム
      this.chamo.offline_message = $('<form>', {
        'id': 'chamo_offline_mail_form'
      }).append(getMediumFrame(cm.account.offline_title)).
          css(cm.account.place, '20px');
      this.chamo.offline_message.find('.chamo-titlebar').append($('<div>', {
        'title': Localizer.getValue('widget-minimize'),
        'class': 'chamo-titlebar-rightbutton'
      }).html('&times;').addClass('chamo-button-minimize'));
      this.chamo.offline_message.find('.chamo_main').
          attr('id', 'chamo_offline_message_form').css({
            'background-color': cm.account.colormodel['bg']
          }).append(
              $('<div id="chamo-offline-message-body">').
              html(format_html(cm.account.offline_body))
          );
      this.chamo.offline_message.find('.chamo_footer').prepend($('<input>', {
        type: 'submit',
        value: Localizer.getValue('messageform-send'),
        id: 'offline-message-sendbutton'
      }).css({
        'background-color': cm.account.colormodel['main1'],
        'color': cm.account.colormodel['font3']
      }));

      // オフライン時メッセージ送信完了
      this.chamo.offline_message_submitted = $('<div id="offline_message_submitted">').
          html(Localizer.getValue('messageform-success')).
          css({
            color: cm.account.colormodel['font3'],
            background: cm.account.colormodel['main1']
          }).
          appendTo(cv.chamo.offline_message);

      // 吹き出しの色をセット
      var hexPlusDecimal = function(hex, plus) {
        var res = parseInt(hex, 16) + plus;
        if (res > 255) res = 255;
        if (res < 0) res = 0;
        return res.toString(16);
      };
      var ballooncolor1 = '#' +
          hexPlusDecimal(cm.account.colormodel['balloon'].substring(1, 3), -2) +
          hexPlusDecimal(cm.account.colormodel['balloon'].substring(3, 5), -2) +
          hexPlusDecimal(cm.account.colormodel['balloon'].substring(5, 7), -2);
      var ballooncolor2 = '#' +
          hexPlusDecimal(cm.account.colormodel['balloon'].substring(1, 3), 2) +
          hexPlusDecimal(cm.account.colormodel['balloon'].substring(3, 5), 2) +
          hexPlusDecimal(cm.account.colormodel['balloon'].substring(5, 7), 2);
      addStyleRule('.chamo_frame .user_message',
          'background-color:' + cm.account.colormodel['balloon'] +
              ' !important;background:linear-gradient(' +
              ballooncolor1 + ',' + ballooncolor2 + ') !important;');
      addStyleRule('.chamo_frame .user_message:after',
          'border-left-color:' + cm.account.colormodel['balloon'] +
              ' !important;' + 'border-bottom-color:' +
              cm.account.colormodel['balloon'] + ' !important;');

      this.chamo.base.
          addClass('-chamo-toplevel-container').
          append(this.chamo.waiting).
          append(this.chamo.chatting).
          //append(this.chamo.chatting_maximum).
          append(this.chamo.offline_waiting).
          append(this.chamo.offline_message);
          //append(this.chamo.offline_message_maximum);

      this.chamo.base.children().hide();
      if ($.inArray(accountID,[2242, 3298, 3516, 3842]) != -1) {
        addStyleRule('.chamo-poweredby', 'display:none !important;');
      }
      this.chamo.base.appendTo($('body:first'));

      //  IE quirks mode
      if (document.documentMode == 5 && document.compatMode == 'BackCompat') {
        var pc_bottom_fixed = 0;
        if (pc_bottom != '0px') {
          if (cm.account.placeDetail.pc_bottom_unit == 'percent') {
            pc_bottom_fixed = parseInt(
                (document.documentElement.clientHeight || document.body.clientHeight) *
                    cm.account.placeDetail.pc_bottom / 100);
          } else {
            pc_bottom_fixed = cm.account.placeDetail.pc_bottom;
          }
        }
        // overwrite CSS rules
        addStyleRule('.chamo_frame .operator_image', 'position:relative !important; top:32px !important; left:-40px !important');
        addStyleRule('#chamo-chat-textarea', 'position:relative !important; top:13px !important; left:13px !important');
        addStyleRule('.chamo_footer input', 'position:relative !important; left:13px !important');
        addStyleRule('.chamo_frame .user_message', 'background-color:' +
            cm.account.colormodel['balloon'] +
            ' !important; border:1px solid #999 !important; padding: 3px !important;');
        addStyleRule('.chamo_frame .operator_message', 'background-color:#f0f0f0 !important;');
        addStyleRule('#chamo-window .operator_post', 'margin: 0 0.3em !important;');
        addStyleRule('#chamo-window .user_post', 'margin-top: 2em !important;');
        // set position via javascript since quriks cannot use 'position:fixed'
        cv.chamo.base.css({
          'position': 'absolute',
          'top': ((document.documentElement.scrollTop || document.body.scrollTop) +
              (document.documentElement.clientHeight || document.body.clientHeight) -
              document.getElementById('chamo-window').offsetHeight + pc_bottom_fixed) + 'px'
        });
        cv.chamo.base.children().css('position', 'absolute');
        $(window).on('scroll', function() {
          cv.chamo.base.css({
            'top': ((document.documentElement.scrollTop || document.body.scrollTop) +
                (document.documentElement.clientHeight || document.body.clientHeight) -
                document.getElementById('chamo-window').offsetHeight + pc_bottom_fixed) + 'px'
          });
        });
      }
    }, // End of createDOM
    updateDOM: function() {
      if (!cv.chamo.base) return;
      var _titlebar = '';
      if (cm.status.num_unread > 0) {
        _titlebar = '<img src="' + hosturl +
            'common/img/chat_balloon_mini.gif" width="17" height="14">' +
            Localizer.getValue('widget-unread');
        $('#chamo-mesmes').html(cm.status.num_unread).show();
      } else {
        _titlebar = cm.account.title_mini;
        $('#chamo-mesmes').html(cm.status.num_unread).hide();
      }
      var _dom = cv.chamo.waiting.find('.chamo-titlebar div');
      if (_dom.html() != _titlebar) {
        _dom.html(_titlebar);
      }
    },
    getBlinkDom: function() {
      return {
        'waiting_title': '#chamo-waiting .chamo-titlebar > div:first-child',
        'chatting_title': '#chamo-chatting .chamo-titlebar > div:first-child'
      };
    },
    hideChat: function(display, device) {
      if (cv.chamo[display]) {
        if (device == CHAMO_DEVICE_PC || device == CHAMO_DEVICE_IPAD) {
          cv.chamo[display].hide();
        } else {
          cv.chamo[display].trigger('chamo-hidden');
        }
      }
      $('#chamo-window .chamo_link').css({ 'visibility': 'hidden' });
      $('#chamo-window .chamo_footer input[type=submit]').
          attr('disabled', 'disabled');
    },
    showChat: function(display, device) {
      var _target = null;
      switch (display) {
        case 'waiting':
           _target = cv.chamo.waiting;//.show();
          break;
        case 'offline_waiting':
           _target = cv.chamo.offline_waiting;
          //cv.chamo.offline_waiting.show();
          break;
        case 'chatting':
           _target = cv.chamo.chatting;
          //cv.chamo.chatting.show();
          setTimeout(function() {
            $('#chamo-window .chamo_link').css({ 'visibility': 'visible' });
          }, 1500);
          break;
        case 'offline_message':
           _target = cv.chamo.offline_message;
          //cv.chamo.offline_message.show();
          setTimeout(function() {
            $('#chamo-window .chamo_link').css({ 'visibility': 'visible' });
            $('#chamo-window .chamo_footer input[type=submit]').removeAttr('disabled');
          }, 1500);
          break;
        case 'chatting_maximum':
           _target = cv.chamo.chatting_maximum;
          //cv.chamo.chatting_maximum.show();
          setTimeout(function() {
            $('#chamo-window .chamo_link').css({ 'visibility': 'visible' });
          }, 1500);
          break;
        case 'offline_message_maximum':
           _target = cv.chamo.offline_message_maximum;
          //cv.chamo.offline_message_maximum.show();
          setTimeout(function() {
            $('#chamo-window .chamo_link').css({ 'visibility': 'visible' });
            $('#chamo-window .chamo_footer input[type=submit]').
                removeAttr('disabled');
          }, 1500);
          break;
      }
      if (_target) {
        if (device == CHAMO_DEVICE_PC || device == CHAMO_DEVICE_IPAD) {
          cv.chamo[display].show();
        } else {
          cv.chamo[display].trigger('chamo-visible');
        }
      }
    },
    resize: function(isForced) {
    },
    isFocusOnTextarea: function() {
      return cv.chamo.textarea && cv.chamo.textarea.is(':focus');
    },
    getInputtingText: function() {
      return cv.chamo.textarea ? $.trim(cv.chamo.textarea.val()) : null;
    },
    addPastChatLink: function() {
      cv.chamo.chatlog_wrapper.find('.chamo-chatlog-link').css({
        'display': 'block'
      });
      cv.chamo.past_chatlog_link.on('click', function(e) {
        cm.getPreviousChat();
        cm.chatlog_offset++;
      });
    },
    hidePastChatLink: function() {
      cv.chamo.past_chatlog_link.css({
        'display': 'none'
      });
      cv.chamo.past_chatlog_link.off('click');
    },
    setEvent: function() {
      cv.chamo.base.find(':input').
          on('focus', function() { cv.isInputFocused = true; }).
          on('blur', function() { cv.isInputFocused = false; });
      // Waiting
      cv.chamo.waiting.on('click', function(e) {
        cm.status.window = CHAMO_DISPLAY_OPEN;
        cm.updateChat();
      });
      // Chatting
      cv.chamo.chatting.on('show', function() {
        cv.scrollToViewedMsg();
        //cv.forbidUserscalable();
      });
      cv.chamo.chatting.find('.chamo-button-minimize').
          on('mousedown touchend', function() {
            cm.status.window = CHAMO_DISPLAY_WAITING;
            cm.updateChat();
          });
      cv.chamo.chatting.find('.chamo-button-maximize, .chamo-titlebar-title').
          on('mousedown touchend', function() {
            cm.status.window = CHAMO_DISPLAY_MAXIMUM;
            cm.updateChat();
          });
      cv.chamo.textarea.on('keydown', function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
          if (!e.shiftKey) {
            cv.chat_submit();
            e.preventDefault();
            //cm.chat_input_end();
          }
        } else {
          //cm.chat_input_start();
        }
        inputStateObserver.notify();
      }).on('blur', function(e) {
        inputStateObserver.notify();
        //cm.chat_input_end();
      });
      /*
      // Chatting Maximum
      cv.chamo.chatting_maximum
          .on('show',function(){
              cv.forbidUserscalable();
          })
          .on('hide',function(){
              cv.allowUserscalable();
          });
      cv.chamo.chatting_maximum
          .find('.chamo-button-minimize')
                .on('mousedown touchend', function(){
                    //cv.allowUserscalable();
                      cm.status.window = CHAMO_DISPLAY_WAITING;
                cm.updateChat();
                });
      cv.chamo.chatting_maximum
          .find('.chamo-button-normalize, .chamo-titlebar-title')
                .on('mousedown touchend', function(){
                    //cv.allowUserscalable();
                      cm.status.window = CHAMO_DISPLAY_OPEN;
                cm.updateChat();
                });
          cv.chamo.sendbutton
                .on('click touchend',function (e) {
                      cv.chat_submit();
              });
          */
      // Offline Waiting
      cv.chamo.offline_waiting.on('mousedown touchend', function() {
        cm.status.window = CHAMO_DISPLAY_OPEN;
        cm.updateChat();
      });
      // Offline Message
      cv.chamo.offline_message.
          find('.chamo-button-minimize').
          on('mousedown touchend', function() {
            //cv.allowUserscalable();
            cm.status.window = CHAMO_DISPLAY_WAITING;
            cm.updateChat();
          });
      cv.chamo.offline_message.
          on('submit', function(e) {
            cm.send_offline_mail();
            e.preventDefault();
          }).
          on('show', function() {
            cv.forbidUserscalable();
          }).
          on('hide', function() {
            cv.allowUserscalable();
          });

      $(document).on('change', 'input.chamo-question-option', function() {
        $this = $(this);
        if ($this.attr('disabled')) return;
        if ($this.parent().siblings().find('input.chamo-question-option').attr('disabled')) return;
        // disabledにして送信
        $this.attr('disabled', 'disabled');
        cm.post_selected($this.attr('id'), $this.val());
      });

      $(document).on('change', 'input.chamo-department-option', function() {
        $this = $(this);
        if ($this.attr('disabled')) {
          return;
        } else {
          $this.attr('disabled', 'disabled');
        }
        if ($this.parent().siblings().find('input.chamo-department-option').
            attr('disabled')) {
          return;
        } else {
          $this.parent().siblings().find('input.chamo-department-option').
              attr('disabled', 'disabled');
        }
        // disabledにして送信
        cm.department_selected($this.attr('id'), $this.val(), $this.next().text());
      });

      if (cm.account.allow_hide) {
        cv.chamo.base.find('a.hide_by_user').on('click', function(e) {
          e.preventDefault();
          var confirm_text = '';
          if (cm.account.allow_hide_time > 0) {
            confirm_text = Localizer.sprintf('widget-hidechat-minute', cm.account.allow_hide_time);
          } else {
            confirm_text = Localizer.getValue('widget-hidechat-eternal');
          }
          if (window.confirm(confirm_text)) {
            cm.hide_set(cm.account.allow_hide_time);
          }
        });
      }
    },
    forbidUserscalable: function(_isForcely) {
      return; // for PC, no action is need
      if (!cm.isUserScalable) return;

      var isForcely = (_isForcely === undefined) ? false : _isForcely;
      if (!isForcely && cm.device == CHAMO_DEVICE_ANDROID) return;
      //forbidUserscalable  : function() {
      //  if(cm.device == CHAMO_DEVICE_ANDROID) return;

      $('meta[title=chamoAllowUserscalable]').remove();
      $('head:first').append(
          '<meta title="chamoForbidUserscalable" name="viewport" content="user-scalable=no" />'
      );

      /*
      $('meta[title=chamoAllowUserscalable]').remove();
      if (cm.device == CHAMO_DEVICE_ANDROID) {
        var zoom_now = document.body.clientWidth / window.innerWidth;
      $('head:first')
      .append(
          '<meta title="chamoForbidUserscalable" name="viewport" content="user-scalable=no,minimum-scale='+zoom_now+',maximum-scale='+(zoom_now+0.01)+'" />'
      );
      } else {
      $('head:first')
      .append(
          '<meta title="chamoForbidUserscalable" name="viewport" content="user-scalable=no" />'
      );
      }
      */
      cv.isForbidUserscalable = true;
    },
    allowUserscalable: function() {
      return; // for PC, no action is need
      if (!cm.isUserScalable) return;

      if (!cv.isForbidUserscalable) return;

      $('meta[title=chamoForbidUserscalable]').remove();
      $('head:first').append(
          '<meta title="chamoAllowUserscalable" name="viewport" content="user-scalable=yes" />'
      );
      cv.isForbidUserscalable = false;
    },
    setStatusbar: function(value, opt_class) {
      if (cv.chamo && cv.chamo.statusbar) {
        if (opt_class) {
          cv.chamo.statusbar.html('<span class="' + opt_class + '">' +
              value + '</span>');
        } else {
          cv.chamo.statusbar.html(value);
        }
      }
    },
    clearStatusbar: function(opt_class) {
      if (cv.chamo && cv.chamo.statusbar) {
        if (opt_class) {
          cv.chamo.statusbar.find('.' + opt_class).remove();
        } else {
          cv.chamo.statusbar.html('');
        }
      }
    },
    setLoader: function() {
      var _loading = '<img src="' + chamo_loading_imgurl.src + '">';
      cv.setStatusbar(_loading);
      cv.chamo.textarea.attr('disabled', 'disabled');
    },
    unsetLoader: function() {
      if (cv.chamo && cv.chamo.statusbar) cv.chamo.statusbar.html('');
      cv.chamo.textarea.removeAttr('disabled');
    },
    chat_receive: function(data) {
      cv.chamo.statusbar.html(Localizer.getValue('status-send'));
    },
    play_audio: function() {
      if (cv.chamo.audio_operator_post && cv.chamo.audio_operator_post.play) {
        if (cv.chamo.audio_operator_post.currentTime == 0 ||
            cv.chamo.audio_operator_post.ended) {
          if (CHAMO_SERVICE_NAME != 'LinQ') {
            cv.chamo.audio_operator_post.play();
          }
        }
      }
    },
    show_operator_inputting: function() {
      if (cm.account.operator_inputting == CHAMO_INPUT_START) {
        cv.chamo.statusbar.html('<span class="operator_input_state">' +
            Localizer.getValue('status-operatorinput') + '</span>');
        //cv.scrollToViewedMsg();
      } else {
        cv.chamo.statusbar.find('.operator_input_state').remove();
      }
    },
    chat_send_error: function(data_array) {
      cv.chamo.statusbar.html('');
      cv.chamo.send_error_message.
          html(Localizer.getValue('status-disconnect')).
          one('click', function(e) {
            cv.chamo.send_error_message.html(Localizer.getValue('status-reconnect'));
            e.preventDefault();
            cm.reconnect();
          }).fadeIn(1000);
      // 送信ボタンをdisabled
      // data-msgidが未セットのものに「エラー」文字を追加
      //cv.chamo.chatlog.find("div.user_post").not('[data-msgid]').prepend('<div class="chamo_send_error">エラー</div>');
      cv.chamo.chatlog.find("div[data-msgid='null']").
          prepend('<div class="chamo_send_error">' + Localizer.getValue('error') + '</div>');
    },
    chat_reconnect_success: function() {
      cv.chamo.send_error_message.
          html(Localizer.getValue('status-reconnect-success')).
          delay(2000).
          fadeOut(1000);
    },
    update_op_viewed: function() {
      cv.chamo.chatlog.find('div.user_post[data-opviewed!=1]').each(function() {
        if ($(this).attr('data-msgid') <= cm.op_viewed_msgid) {
          $(this).attr('data-opviewed', 1);
          $(this).prepend('<div class="opviewed">' +
              Localizer.getValue('widget-viewed') + '</div>');
        }
      });
      cv.chamo.chatlog_maximum.find('div.user_post[data-opviewed!=1]').each(function() {
        if ($(this).attr('data-msgid') <= cm.op_viewed_msgid) {
          $(this).attr('data-opviewed', 1);
          $(this).prepend('<div class="opviewed">' +
              Localizer.getValue('widget-viewed') + '</div>');
        }
      });
    },
    show_offline_message_submitted: function() {
      cv.chamo.offline_message_submitted.
          fadeIn(1000).delay(4000).fadeOut(1500);
    },
    set_image_data: function(data) {
      if (cv.chamo.chatting_maximum) {
        cv.chamo.chatting_maximum.
            find('[data-fileid=' + data.subcode + '] img').
            attr('src', data.info);
      }
      if (cv.chamo.chatting) {
        cv.chamo.chatting.
            find('[data-fileid=' + data.subcode + '] img').
            attr('src', data.info);
      }
    },
    disable_options: function(name, checked_id, isPastchat) {
      if (isPastchat) {
        if (cv.chamo.past_chat_buffer) {
          cv.chamo.past_chat_buffer.find("input.chamo-option[id='" +
              checked_id + "']").attr('checked', true);
          cv.chamo.past_chat_buffer.find("input.chamo-option[name='" +
              name + "']").attr('disabled', 'disabled');
        }
      } else {
        $("input.chamo-option[id='" + checked_id + "']").
            attr('checked', true);
        $("input.chamo-option[name='" + name + "']").
            attr('disabled', 'disabled');
      }
    },
    show_message: function(chatMessage) {
      var html = [];
      var date = new Date(chatMessage.date * 1000);
      //var additionalClass = (cm.isLogLoaded) ? '-chamo-new-post' : '';
      var additionalClass = '';
      switch (chatMessage.code) {
        case 'user_post':
          html[html.length] = '<div class="user_post ' + additionalClass +
              '" data-msgid="' + chatMessage.id +
              '" data-genkey="' + chatMessage.subcode + '">';
          html[html.length] = '<div class="user_message">' +
              autolinker(chatMessage.info) + '</div>';
          html[html.length] = '</div>';
          break;
        case 'option_selected':
          var attrs = chatMessage.subcode.split(':');
          html[html.length] = '<div class="user_post option_selected ' +
              additionalClass + '" data-msgid="' + chatMessage.id +
              '" data-genkey="' + chatMessage.subcode + '">';
          html[html.length] = '<div class="user_message">' +
              chatMessage.info + '</div>';
          html[html.length] = '</div>';
          var isPastchat = cm.roomid != chatMessage.roomid;
          cv.disable_options(attrs[0], chatMessage.subcode, isPastchat);
          break;
        case 'operator_post':
          var _imgurl = (cm.operators[chatMessage.speaker]) ?
              cm.operators[chatMessage.speaker]['imgurl'] : chamo_sm_imgurl;
          html[html.length] = '<div class="operator_post ' + additionalClass +
              '" data-msgid="' + chatMessage.id + '">';
          html[html.length] = '<img src="' + _imgurl +
              '" width="25" height="25" style="width:25px;height:25px;" class="operator_image">';
          html[html.length] = '<div class="operator_message">';
          if (cm.operators[chatMessage.speaker]['name']) {
            html[html.length] = '<div class="operator_name" style="color:' +
                cm.account.colormodel['main1'] + ';">';
            html[html.length] = cm.operators[chatMessage.speaker]['name'];
            html[html.length] = '</div>';
          }
          html[html.length] = parseOperatorMessage(chatMessage.info, chatMessage.id, true) + '</div>';
          html[html.length] = '</div>';
          break;
        case 'operator_file':
          var _imgurl = (cm.operators[chatMessage.speaker]) ?
              cm.operators[chatMessage.speaker]['imgurl'] : chamo_sm_imgurl;
          html[html.length] = '<div class="operator_post ' + additionalClass +
              '" data-msgid="' + chatMessage.id + '">';
          html[html.length] = '<img src="' + _imgurl +
              '" width="25" height="25" style="width:25px;height:25px;" class="operator_image">';
          html[html.length] = '<div class="operator_message">';
          if (cm.operators[chatMessage.speaker]['name']) {
            html[html.length] = '<div class="operator_name" style="color:' +
                cm.account.colormodel['main1'] + ';">';
            html[html.length] = cm.operators[chatMessage.speaker]['name'];
            html[html.length] = '</div>';
          }
          html[html.length] = createFileView(chatMessage, '_self') + '</div>';
          html[html.length] = '</div>';
          break;
        case 'trigger':
          html[html.length] = '<div class="operator_post trigger ' +
              additionalClass + '" data-msgid="' + chatMessage.id + '">';
          html[html.length] = '<img src="' + cm.account['imgurl'] +
              '" width="25" height="25" style="width:25px;height:25px;" class="operator_image">';
          html[html.length] = '<div class="operator_message">';
          if (cm.account.name) {
            html[html.length] = '<div class="operator_name" style="color:' +
                cm.account.colormodel['main1'] + ';">';
            html[html.length] = cm.account.name;
            html[html.length] = '</div>';
          }
          switch (chatMessage.subcode) {
            case 'department_list':
              html[html.length] = parseDepartmentList(chatMessage, true) + '</div>';
              break;
            default:
              html[html.length] = parseOperatorMessage(chatMessage.info, chatMessage.id, true) + '</div>';
              break;
          }
          html[html.length] = '</div>';
          break;
        case 'api':
          if (chatMessage.subcode == 'operator_message') {
            html[html.length] = '<div class="operator_post trigger ' +
                additionalClass + '" data-msgid="' + chatMessage.id + '">';
            html[html.length] = '<img src="' + cm.account['imgurl'] +
                '" width="25" height="25" style="width:25px;height:25px;" class="operator_image">';
            html[html.length] = '<div class="operator_message">';
            if (cm.account.name) {
              html[html.length] = '<div class="operator_name" style="color:' +
                  cm.account.colormodel['main1'] + ';">';
              html[html.length] = cm.account.name;
              html[html.length] = '</div>';
            }
            html[html.length] = parseOperatorMessage(chatMessage.info, chatMessage.id, true) + '</div>';
            html[html.length] = '</div>';
          }
          break;
      }

      var joined_html = html.join('');
      if (cm.roomid == chatMessage.roomid) {
        cv.chamo.chatlog.append($('<div>', {
          'class': 'chamo-message'
        }).html(joined_html));
        cv.chamo.chatlog_maximum.append($('<div>', {
          'class': 'chamo-message'
        }).html(joined_html));
        cv.scrollToViewedMsg();
      } else {
        // 過去チャット
        cv.chamo.past_chat_buffer.append($('<div>', {
          'class': 'chamo-message'
        }).html(joined_html));
      }

      /*
      // 最新の投稿までスクロール
      // DOMが更新される前にスクロールすると中途半端な位置で止まるため、
      // スリープを入れている
      window.setTimeout(function() {
        cv.chamo.chatlog_wrapper.
            scrollTop(cv.chamo.chatlog_wrapper[0].scrollHeight);
        //cv.chamo.chatlog_wrapper_maximum.
            scrollTop(cv.chamo.chatlog_wrapper_maximum[0].scrollHeight);
      }, 100);
      */
    },
    flush_past_chatlog_buffer: function(start) {
      if (cv.chamo.past_chat_buffer) {
        cv.chamo.past_chat_buffer.find('input.chamo-option').
            attr('disabled', 'disabled');
        var line = '------------';
        if (cm.chatlog_offset === 1) {
          cv.chamo.past_chat_buffer.append($('<div>', {
            'class': 'chamo-separater',
          }).css({
            'text-align': 'center',
          }).html(line + ' 現在のチャット ' + line));
        }
        cv.chamo.past_chat_buffer.prepend($('<div>', {
          'class': 'chamo-separater',
        }).css({
          'text-align': 'center',
        }).html(line + ' ' + dateTimeText(start) + ' ' + line));

        cv.chamo.chatlog.prepend(cv.chamo.past_chat_buffer);
        cv.chamo.chatlog_maximum.prepend(cv.chamo.past_chat_buffer.clone());
        cv.chamo.past_chat_buffer = $('<div>');
      }
    },
    chat_submit: function() {
      if (!timeline.valid) {
        cv.chamo.statusbar.html(Localizer.getValue('status-invalidconnect'));
        return;
      }
      if ($.trim(cv.chamo.textarea.val())) {
        var _val = cv.chamo.textarea.val();
        cv.chamo.textarea.val('');
        cv.chamo.statusbar.html(Localizer.getValue('status-sending'));
        cv.scrollToViewedMsg();
        cm.post(_val);
      }
    },
    set_messageform: function(data_array) {
      cv.chamo.offline_message.find('input.chamo_offline_message_element').
          each(function() {
            var key = $(this).attr('name').toLowerCase();
            if (data_array[key]) $(this).val(data_array[key]);
          });
      cv.chamo.offline_message.find('textarea.chamo_offline_message_element').
          each(function() {
            var key = $(this).attr('name').toLowerCase();
            if (data_array[key]) $(this).text(data_array[key]);
          });
    },
    scrollToViewedMsg: function() {
      // DOMが更新される前にスクロールすると中途半端な位置で止まるため、
      // スリープを入れている
      clearTimeout(cv.timers['scrollToBottom1']);
      cv.timers['scrollToBottom1'] = window.setTimeout(function() {
        if (cm.user_viewed_msgid == 0) return;
        $sc = cv.chamo.chatlog_wrapper;
        var dd = $sc.find('[data-msgid=' + cm.user_viewed_msgid + ']').
            parent().next('.chamo-message');
        if (dd.length == 0) {
          $sc.scrollTop($sc[0].scrollHeight);
        } else {
          //$sc.scrollTop($sc.scrollTop()+dd.offset().top);
          var scrTop = dd.offset().top + $sc.scrollTop() - $sc.offset().top;
          $sc.scrollTop(scrTop);
        }
      }, 100);
    }
  }; // cv

;  // Microad BLADE CV tag
  /*
  param = {
    'co_account_id': co_account_id,
    'group_id': group_id,
    'country_id': country_id,
    'ver': ver
  };
  */
  function microadBladeCV(param) {
    if (!param) {
      return false;
    }

    window.microad_blade_jp = window.microad_blade_jp || {
      'params': new Array(),
      'complete_map': new Object()
    };

    window.microad_blade_jp.params.push(param);

    var src = (location.protocol == 'https:') ?
        'https://d-track.send.microad.jp/js/blade_track_jp.js' :
        'http://d-cache.microad.jp/js/blade_track_jp.js';

    var bs = document.createElement('script');
    bs.type = 'text/javascript';
    bs.async = true;
    bs.charset = 'utf-8';
    bs.src = src;

    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(bs, s);

    return true;
  }

  // Google Analytics event push
  function googleAnalyticsEventPush(category, action, label, val) {
    if (typeof _gaq !== 'undefined') {
      _gaq.push(['_trackEvent', category, action, label, val]);
    } else if (typeof ga !== 'undefined') {
      ga('send', 'event', category, action, label, val);
    }
    return true;
  }


  // サーバー時間と、デバイスの時間のずれを調整したDateを返す
  var correctedDate = (function(spec) {
    var diff = 0;
    var correctedDate = function() {
      return new Date((new Date()).getTime() + diff);
    };
    var initialize = function(serverTime) {
      var deviceTime = correctedDate().getTime();
      serverTime = serverTime || deviceTime;
      if (serverTime < 20000000000) {
        // 秒の場合は、ミリ秒に直す
        serverTime *= 1000;
      }
      diff = serverTime - deviceTime;
    };
    correctedDate.initialize = initialize;
    return correctedDate;
  })();

  var dateTimeText = function(date) {
    var d = new Date(date * 1000);
    var dateText = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate();
    var hour = d.getHours();
    var min = d.getMinutes();

    return dateText + ' ' +
        (hour < 10 ? '0' + hour : hour) + ':' +
        (min < 10 ? '0' + min : min);
  };

  // Dateオブジェクトに昨日のDateを返すメソッドを追加
  Date.prototype.previousday = function() {
    return new Date(this - (3600 * 24 * 1000));
  };

  // 現在時刻が hour:min の何分前かをチェック
  // たとえば現在時刻が 10:15:39 ならば、whatMoreMinutes(10,21) = 6
  function whatMoreMinutes(hour, min) {
    var d = correctedDate();
    var now = d.getHours() * 3600 + d.getMinutes() * 60 + d.getSeconds();
    var target = (hour % 24) * 3600 + min * 60 + 59;
    if (target < now) { target += 24 * 3600; }
    var left = target - now;
    return Math.floor(left / 60);
  }

  function isBetweenTimeOnDayNow(obj, offsetMinute) {
    var date = correctedDate();
    if (typeof offsetMinute !== 'undefined') {
      date.setMinutes(date.getMinutes() + offsetMinute);
    }
    var dayOfTheWeek = date.getDay() || 7;
    var obj2 = {};
    for (var entry = 0; entry < obj[dayOfTheWeek - 1].length; entry++) {
      obj2 = {
        hour1: obj[dayOfTheWeek - 1][entry].hour1,
        min1: obj[dayOfTheWeek - 1][entry].min1,
        hour2: obj[dayOfTheWeek - 1][entry].hour2,
        min2: obj[dayOfTheWeek - 1][entry].min2,
      };
      if (isBetweenTimeNow(obj2, offsetMinute)) return true;
    }
    return false;
  }

  function isBetweenTimeNow(obj, offsetMinute) {
    // 現在時刻が hour1:min1 ～ hour2:min2 の中かどうかをチェック
    var hour1 = obj.hour1,
        min1 = obj.min1,
        hour2 = obj.hour2,
        min2 = obj.min2;
    var d = correctedDate();
    if (typeof offsetMinute !== 'undefined') {
      d.setMinutes(d.getMinutes() + offsetMinute);
    }
    var hour = d.getHours();
    var min = d.getMinutes();
    if (hour2 < 24) {
      if (hour < hour1) return false;
      if (hour == hour1 && min < min1) return false;
      if (hour > hour2) return false;
      if (hour == hour2 && min > min2) return false;
    } else {
      // eg. 22:00 ～ 27:00 <=> 22:00～23:59 or 0:00～3:00
      return ((isBetweenTimeNow({
        hour1: obj.hour1,
        min1: obj.min1,
        hour2: 23,
        min2: 59
      }, offsetMinute)) || (isBetweenTimeNow({
        hour1: 0,
        min1: 0,
        hour2: (obj.hour2 - 24),
        min2: obj.min2
      }, offsetMinute)));
    }
    return true;
  }

  /**
   * 営業日かどうかの判定
   * 例）7-20 or 7/20 → 今年の同月同日に変換。
   */
  function isInBusinessDayNow(days) {
    const delim = '-';
    var thisDate = new Date();
    var thisYear = thisDate.getFullYear();
    var thisMonth = thisDate.getMonth() + 1;
    var thisDay = thisDate.getDate();
    var targetYear = thisYear;
    var targetMonth = thisMonth;
    var targetDay = thisDay;
    //console.log(days);
    for (var entry = 0; entry < days.length; entry++) {
      var day = days[entry];
      day = day.replace('/', delim);// / -> - だけする。
      var dayArr = day.split(delim);
      if (dayArr.length === 2) {
        // 比定：7-20
        targetMonth = dayArr[0];
        targetDay = dayArr[1];
      } else if (dayArr.length === 3) {
        // 比定：2015-7-20
        targetYear = dayArr[0];
        targetMonth = dayArr[1];
        targetDay = dayArr[2];
      } else {
        // 謎のフォーマット
        continue;
      }
      // 妥当な日付ならば、比較をする。
      targetYear = parseInt(targetYear, 10);
      targetMonth = parseInt(targetMonth, 10);
      targetDay = parseInt(targetDay, 10);
      //console.log(isValidDate(targetYear, targetMonth, targetDay));
      if (isValidDate(targetYear, targetMonth, targetDay) && targetYear === thisYear && targetMonth === thisMonth && targetDay === thisDay) {
        return false;
      }
    }
    return true;
  }

  /**
   * 正しい日付かどうか
   * @returns
   */
  function isValidDate(y, m, d) {
    var dt = new Date(y, m - 1, d);
    return (dt.getFullYear() === y && dt.getMonth() === m - 1 && dt.getDate() === d);
  }

  var _orientation_zero, _orientation_90;
  function getOrientation() {
    var _orientation = window.orientation;
    // デバイスによる、縦長・横長のどちらが window.orientation=0 に対応するかの違いを吸収
    if (!_orientation_zero) {
      // 初めてウィンドウを開いたとき
      if (window.innerHeight > window.innerWidth) {
        if (_orientation == 0 || _orientation == 180) {
          _orientation_zero = 'portrait';
          _orientation_90 = 'landscape';
        } else {
          _orientation_zero = 'landscape';
          _orientation_90 = 'portrait';
        }
      } else {
        if (_orientation == 0 || _orientation == 180) {
          _orientation_zero = 'landscape';
          _orientation_90 = 'portrait';
        } else {
          _orientation_zero = 'portrait';
          _orientation_90 = 'landscape';
        }
      }
    }

    if (_orientation == 0 || _orientation == 180) {
      return _orientation_zero;
    } else {
      return _orientation_90;
    }
  }

  /* スタイルの追加 */
  function addStyleRule(selector, declaration) {
    var isMSIE = /*@cc_on!@*/false;
    var sheet, selectors;
    // StyleSheetを作成
    if (isMSIE) {  // for IE8, Sleipnir
      sheet = document.createStyleSheet();
    } else {  // for FireFox, Opera, Safari, Crome
      var head = document.getElementsByTagName('head')[0];
      if (head == null) { return; }
      var style = document.createElement('style');
      style.type = 'text/css';
      head.appendChild(style);
      sheet = style.sheet;
    }
    // 複数のセレクタが指定されている場合は、分解して一つ一つsheetに挿入する
    if (selector.indexOf(',') != -1) {
      selectors = selector.split(',');
    } else {
      selectors = [selector];
    }
    selectors.forEach(function(sel) {
      if (isMSIE) {  // for IE8, Sleipnir
        sheet.addRule(sel, declaration);
      } else {  // for FireFox, Opera, Safari, Crome
        sheet.insertRule(sel + '{' + declaration + '}',
            (sheet.cssRules) ? sheet.cssRules.length : 0);
      }
    });
  }
  /* スタイルの変更 */
  function changeStyleRule(title, selector, declaration) {
    var isMSIE = /*@cc_on!@*/false;
    var sheet, selectors;
    var prefix = 'css-';

    sheet = (function(sheet_title) {
      var css_list = document.styleSheets;
      for (i = css_list.length - 1; i >= 0; --i)
        if (css_list[i].id == prefix + sheet_title)
          return css_list[i];

      return null;
    })(title);

    if (sheet) {
      // Delete All Rules
      rule_list = sheet.cssRules;
      for (i = rule_list.length - 1; i >= 0; --i)
        sheet.deleteRule(i);
    } else {
      // StyleSheetを作成
      if (isMSIE) {  // for IE8, Sleipnir
        sheet = document.createStyleSheet();
      } else {  // for FireFox, Opera, Safari, Crome
        var head = document.getElementsByTagName('head')[0];
        if (head == null) { return; }
        var style = document.createElement('style');
        style.type = 'text/css';
        style.id = prefix + title;
        head.appendChild(style);
        sheet = style.sheet;
      }
    }
    // 複数のセレクタが指定されている場合は、分解して一つ一つsheetに挿入する
    if (selector.indexOf(',') != -1) {
      selectors = selector.split(',');
    } else {
      selectors = [selector];
    }
    selectors.forEach(function(sel) {
      if (isMSIE) {  // for IE8, Sleipnir
        sheet.addRule(sel, declaration);
      } else {  // for FireFox, Opera, Safari, Crome
        sheet.insertRule(sel + '{' + declaration + '}',
            (sheet.cssRules) ? sheet.cssRules.length : 0);
      }
    });
  }

  function settingVersionAbsorber(setting) {
    // placeDetail
    if (typeof setting.placeDetail === 'undefined') {
      setting.placeDetail = {
        pc_bottom: 0,
        pc_bottom_unit: 'px',
        sm_bottom: 0,
        sm_bottom_unit: 'px'
      };
    } else {
      setting.placeDetail = {
        pc_bottom: setting.placeDetail.pc_bottom || 0,
        pc_bottom_unit: setting.placeDetail.pc_bottom_unit || 'px',
        sm_bottom: setting.placeDetail.sm_bottom || 0,
        sm_bottom_unit: setting.placeDetail.sm_bottom_unit || 'px'
      };
    }

    // colormodel
    if (typeof setting.colormodel === 'undefined') {
      setting.colormodel = {
        main1: '#7FBA00',
        bg: '#FFFFFF',
        balloon: '#BEF18C',
        font1: '#5d5967',
        font2: '#AAAAAA',
        font3: '#FFFFFF'
      };
    } else {
      setting.colormodel = {
        main1: setting.colormodel.main1 || '#7FBA00',
        bg: setting.colormodel.bg || '#FFFFFF',
        balloon: setting.colormodel.balloon || '#BEF18C',
        font1: setting.colormodel.font1 || '#5d5967',
        font2: setting.colormodel.font2 || '#AAAAAA',
        font3: setting.colormodel.font3 || '#FFFFFF'
      };
    }

    // nochat
    setting.nochat = setting.nochat ? 1 : 0;

    // sm_waiting_mode
    setting.sm_waiting_mode = setting.sm_waiting_mode ? 1 : 0;

    setting.auto_response = setting.auto_response ? 1 : 0;

    setting.nooperator_behavior = setting.nooperator_behavior || 0;

    // not_open_window setting
    setting.not_open_window = setting.not_open_window || 0;

    setting.not_readnotif = setting.not_readnotif ? 1 : 0;

    setting.allow_hide = setting.allow_hide ? 1 : 0;
    setting.allow_hide_time = typeof setting.allow_hide_time !== 'undefined' ?
        setting.allow_hide_time : 5;

    // beepnotif setting
    if (typeof setting.beepnotif === 'undefined') {
      switch (setting.not_open_window) {
        case 0:
          setting.beepnotif = 1;
          break;
        case 1:
        case 2:
        default:
          setting.beepnotif = 0;
          break;
      }
    }

    setting.language = setting.language || 'ja';

    setting.visibility = setting.visibility || 'visible';
    setting.inbusiness_behavior = setting.inbusiness_behavior || 'invisible';
    setting.only_business_hours = setting.only_business_hours ? 1 : 0;

    // business hours setting
    // 日をまたいだ営業時間設定を再編
    // bs may be undefined or an object or an array.
    // This function assures you to have bs of the array type.
    var newBs = [[], [], [], [], [], [], []];
    var bs = setting.bs
    if (!bs) {
      for (var i = 0; i < 7; i++) {
        newBs[i].push({
          hour1: 0, min1: 0,
          hour2: 23, min2: 59,
        });
      }
    } else if (!$.isArray(bs)) {
      if (bs.hour2 < 24) {
        for (var i = 0; i < 7; i++) {
          newBs[i].push(bs);
        }
      } else {
        for (var i = 0; i < 7; i++) {
          newBs[i].push({
            hour1: bs.hour1, min1: bs.min1,
            hour2: 23, min2: 59,
          });
          var indexTomorrow = (i + 1) % 7;
          newBs[indexTomorrow].push({
            hour1: 0, min1: 0,
            hour2: bs.hour2 - 24, min2: bs.min2,
          });
        }
      }
    } else {
      for (var i = 0; i < 7; i++) {
        $.each(bs[i], function(index, entry) {
          if (entry.hour2 < 24) {
            newBs[i].push(entry);
          } else {
            newBs[i].push({
              hour1: entry.hour1, min1: entry.min1,
              hour2: 23, min2: 59,
            });
            var indexTomorrow = (i + 1) % 7;
            newBs[indexTomorrow].push({
              hour1: 0, min1: 0,
              hour2: entry.hour2 - 24, min2: entry.min2,
            });
          }
        });
      }
    }
    setting.bs = newBs;
    return setting;
  }

  /*** オペレータのメッセージをパース ***/
  function parseOperatorMessage(str, msgid, label) {
    str = '' + str;
    if (str.indexOf('[+]') == -1) {
      return autolinker(str);
    } else {
      //var options = autolinker(str, true).replace(/\r\n|\n|\r/g, '').
      //    split('[+]');
      var options = str.split('[+]');
      options[0] = autolinker(options[0], false);
      var _name = MD5_hexhash(strip_tags(options[0])) + '-' + msgid;
      var ret = options[0];
      for (var i = 1; i < options.length; i++) {
        options[i] = autolinker(options[i], false);
        options[i] = $.trim(options[i]).replace(/<br \/>/g, '');
        ret += '<div class="chamo-question-option-wrapper"><input type="radio" class="chamo-option chamo-question-option" name="' +
            _name + '" id="' + _name + ':' + i +
            '" value="' + strip_tags(options[i]) + '">';
        if (label) {
          ret += '<label onclick="" for="' + _name + ':' + i + '">' +
              options[i] + '</label>';
        } else {
          ret += options[i];
        }
        ret += '</div>';
      }
      return ret;
    }
  }

  function parseOperatorMessage2(str, msgid, isPastchat) {
    str = '' + str;
    if (str.indexOf('[+]') == -1) {
      return {
        info: autolinker(str, true)
      }
    } else {
      // ハッシュ用に一度falseにして取り出す.
      var options = autolinker(str, false).split('[+]',1);
      var _name = MD5_hexhash(strip_tags(options[0])) + '-' + msgid;
      options = autolinker(str, true).split('[+]');
      var options2 = [];
      for (var i = 1; i < options.length; i++) {
        //options[i] = $.trim(options[i]).replace(/<br \/>/g, '');
        options2.push({
          name: _name,
          id: _name + ':' + i,
          label: options[i],
          value: strip_tags(options[i]),
          checked: false,
          disabled: isPastchat,
        });
      }
      return {
        info: options[0],
        options: options2,
      };
    }
  }

  /*** 部署選択のメッセージをパース ***/
  function parseDepartmentList(message, label) {
    var info = JSON.parse(message.info);
    var ret = info.detail;
    var _name = MD5_hexhash(strip_tags(info.detail) + message.roomid) +
        '-' + message.id;
    for (var i = 0; i < info.departments.length; i++) {
      info.departments[i].name = $.trim(info.departments[i].name).
          replace(/<br \/>/g, '');
      ret += '<div class="chamo-question-option-wrapper"><input type="radio" class="chamo-option chamo-department-option" name="' +
          _name + '" id="' + _name + ':' + i +
          '" value="' + info.departments[i].id + '">';
      if (label) {
        ret += '<label onclick="" for="' + _name + ':' + i + '">' +
        info.departments[i].name + '</label>';
      } else {
        ret += info.departments[i].name;
      }
      ret += '</div>';
    }
    return ret;
  }

  function createFileView(message, opt_target) {
    opt_target = (typeof opt_target !== 'undefined') ? opt_target : '_self';
    info = JSON.parse(message.info);
    var ret = '';
    switch (info.type) {
      case 'image/jpeg':
      case 'image/png':
      case 'image/gif':
        ret += '<a data-fileid="' + info.fileId +
            '" href="' + chamo_file_download + '?fileId=' + info.fileId +
            '&token=' + message.subcode +
            '"><img class="chamo-uploaded-image" alt="' + info.fileName + '" src="">' + '</a>';
        break;
      default:
        ret += '【 ' + Localizer.getValue('message-file') + ': <a data-fileid="' + info.fileId +
            '" href="' + chamo_file_download + '?fileId=' + info.fileId +
            '&token=' + message.subcode + '" target="' + opt_target + '">' +
            info.fileName + '</a> 】';
    }
    return ret;
  }

  function autolinker(str, nobr) {
    str = new String(str);

    // 文字装飾
    var colonString = '_colonString_';    // http(s)の置換を防ぐためのバッドノウハウ的処理
    var parser = new DecorationParser('[[[',']]]',':');
    parser.addParseTemplate( 'link', '<a href="%%2%%' + colonString + '%%3%%">%%1%%</a>');
    parser.addParseTemplate( 'externalLink', '<a href="%%2%%' + colonString + '%%3%%" target="_blank">%%1%%</a>');
    parser.addParseTemplate( 'color', '<span style="color:%%2%%;">%%1%%</span>');
    parser.addParseTemplate( 'image', '<img src="%%1%%' + colonString + '%%2%%" style="width: 80%; margin-left: 10px; margin-top: 10px; margin-bottom: 10px; object-fit: contain;">');
    str = parser.format(str);

    // URL
    //str = str.replace(/(http:\/\/[\x21-\x7e]+)/gi,
    //    "<a href='$1' onclick=''>$1</a>");
    str = str.replace(/(http(s?):\/\/[\x21-\x7e]+(:?[a-z]*))/gi, function(match) {
      if (match.toLowerCase().indexOf(':blank') !== -1) {
        match = match.replace(':blank', '');
        return "<a href='" + match + "' onclick='' target='_blank'>" +
            match + '</a>';
      } else {
        return "<a href='" + match + "' onclick=''>" + match + '</a>';
      }
    });
    // Tel
    str = str.replace(/\d+\-\d+\-\d+/g, function(match) {
      return '<a href="tel:' + match.replace(/\-/g, '') + '" onclick="">' +
          match + '</a>';
    });
    // Email
    str = str.replace(/([!#-9A-~]+@+[a-z0-9]+.+[a-z])/ig,
        "<a onclick='' href='mailto:$1'>$1</a>");

    // LineBreak
    if (!nobr) str = str.replace(/\r\n|\n|\r/g, '<br />');

    // colonStringをコロンに戻す
    str = str.replace(new RegExp(colonString, 'g'), ':');

    return str;
  }


  function strip_tags(str) {
    return str.replace(/(<([^>]+)>)/ig, '');
  }

  function nl2br(str) {
    return str.replace(/\r\n|\n|\r/g, '<br />');
  }

  function h(str) {
    return str ? htmlspecialchars(str, 'ENT_QUOTES') : '';
  }

  function h_decode(str) {
    return str ? htmlspecialchars_decode(str, 'ENT_QUOTES') : '';
  }

  // discuss at: http://phpjs.org/functions/htmlspecialchars/
  function htmlspecialchars(string,quote_style,charset,double_encode){var optTemp=0,i=0,noquotes=false;if(typeof quote_style==='undefined'||quote_style===null){quote_style=2}string=string.toString();if(double_encode!==false){string=string.replace(/&/g,'&amp;')}string=string.replace(/</g,'&lt;').replace(/>/g,'&gt;');var OPTS={'ENT_NOQUOTES':0,'ENT_HTML_QUOTE_SINGLE':1,'ENT_HTML_QUOTE_DOUBLE':2,'ENT_COMPAT':2,'ENT_QUOTES':3,'ENT_IGNORE':4};if(quote_style===0){noquotes=true}if(typeof quote_style!=='number'){quote_style=[].concat(quote_style);for(i=0;i<quote_style.length;i++){if(OPTS[quote_style[i]]===0){noquotes=true}else if(OPTS[quote_style[i]]){optTemp=optTemp|OPTS[quote_style[i]]}}quote_style=optTemp}if(quote_style&OPTS.ENT_HTML_QUOTE_SINGLE){string=string.replace(/'/g,'&#039;')}if(!noquotes){string=string.replace(/"/g,'&quot;')}return string}

  // discuss at: http://phpjs.org/functions/htmlspecialchars_decode/
  function htmlspecialchars_decode(string,quote_style){var optTemp=0,i=0,noquotes=false;if(typeof quote_style==='undefined'){quote_style=2}string=string.toString().replace(/&lt;/g,'<').replace(/&gt;/g,'>');var OPTS={'ENT_NOQUOTES':0,'ENT_HTML_QUOTE_SINGLE':1,'ENT_HTML_QUOTE_DOUBLE':2,'ENT_COMPAT':2,'ENT_QUOTES':3,'ENT_IGNORE':4};if(quote_style===0){noquotes=true}if(typeof quote_style!=='number'){quote_style=[].concat(quote_style);for(i=0;i<quote_style.length;i++){if(OPTS[quote_style[i]]===0){noquotes=true}else if(OPTS[quote_style[i]]){optTemp=optTemp|OPTS[quote_style[i]]}}quote_style=optTemp}if(quote_style&OPTS.ENT_HTML_QUOTE_SINGLE){string=string.replace(/&#0*39;/g,"'")}if(!noquotes){string=string.replace(/&quot;/g,'"')}string=string.replace(/&amp;/g,'&');return string}

  /*** localStorage非対応ブラウザ用に CookieによるデータI/Oも用意 ***/
  function setCookie(c_name, value, expiredays) {
    // pathの指定
    var path = location.pathname;
    // pathをフォルダ毎に指定する場合のIE対策
    var paths = new Array();
    paths = path.split('/');
    if (paths[paths.length - 1] != '') {
      paths[paths.length - 1] = '';
      path = paths.join('/');
    }
    // 有効期限の日付
    var extime = new Date().getTime();
    var cltime = new Date(extime + (60 * 60 * 24 * 1000 * expiredays));
    var exdate = cltime.toUTCString();
    // クッキーに保存する文字列を生成
    var s = '';
    s += c_name + '=' + escape(value);// 値はエンコードしておく
    s += '; path=' + path;
    if (expiredays) {
      s += '; expires=' + exdate + '; ';
    } else {
      s += '; ';
    }
    // クッキーに保存
    document.cookie = s;
  }
  function getCookie(c_name) {
    var st = '';
    var ed = '';
    if (document.cookie.length > 0) {
      // クッキーの値を取り出す
      st = document.cookie.indexOf(c_name + '=');
      if (st != -1) {
        st = st + c_name.length + 1;
        ed = document.cookie.indexOf(';', st);
        if (ed == -1) ed = document.cookie.length;
        // 値をデコードして返す
        return unescape(document.cookie.substring(st, ed));
      }
    }
    return '';
  }
  /*** デバッグ用 ***/
  function debugObject(obj) {
    myconsolelog('--- Debug Object ---');
    for (var key in obj) {
      myconsolelog(key + ' => ' + obj[key]);
    }
  }
  /*** IE7/8対応用 http://www.netagent-blog.jp/archives/51509761.html ***/
  function hookXhr() {
    return undefined;
    if (!window.XDomainRequest) return undefined;

    var xhr = function() {
      this.readyState = 0; // uninitialized
      this.responseText = '';
      this.status = '';
      this.onreadstatechange = undefined;
      var xdr = new XDomainRequest();

      xdr.onprogress = function() {
        var f;
        this.xhr.readyState = 2; // loaded
        if (this.xhr && (f = this.xhr.onreadystatechange)) {
          f.apply(this.xhr);
        }
      };

      xdr.onload = function() {
        var f;
        this.xhr.readyState = 3;    // interactive
        if (this.xhr && (f = this.xhr.onreadystatechange)) {
          f.apply(this.xhr);
        }
        this.xhr.responseText = xdr.responseText;
        this.xhr.readyState = 4;    // complete
        this.xhr.status = '200';
        if (f) {
          f.apply(this.xhr);
        }
      };

      this.open = function(method, url, async) {
        return xdr.open(method, url, async);
        readyState = 1;
      };
      this.send = function(body) {
        xdr.send(body);
      };
      this.setRequestHeader = function(headerName, headerValue) {
        myconsolelog('setRequestHeader is not supported.');
      };

      this.getResponseHeader = function(headerName) {
        if (headerName.match(/^Content\-Type$/i)) {
          return xdr.contentType;
        } else {
          myconsolelog('getResponseType not supported');
          return '';
        }
      };
      xdr.xhr = this;
      return this;
    };
    return new xhr();
  }

  function replaceAll(expression, org, dest) {
    return expression.split(org).join(dest);
  }

  function myconsolelog(mylog) {
    if (location.href.indexOf('chat_debug') != -1) {
      if (typeof console != 'undefined') { console.log(mylog); }
    }
  }


/*!
 * verge 1.9.1+201402130803
 * https://github.com/ryanve/verge
 * MIT License 2013 Ryan Van Etten
 */
(function(root, name, make) {
  if (typeof module != 'undefined' && module['exports'])
    module['exports'] = make();
  else root[name] = make();
}(this, 'verge', function() {

  var xports = {},
      win = typeof window != 'undefined' && window,
      doc = typeof document != 'undefined' && document,
      docElem = doc && doc.documentElement,
      matchMedia = win['matchMedia'] || win['msMatchMedia'];
  var mq = matchMedia ? function(q) {
        return !!matchMedia.call(win, q).matches;
      } : function() {
        return false;
      };
  var viewportW = xports['viewportW'] = function() {
        var a = docElem['clientWidth'], b = win['innerWidth'];
        return a < b ? b : a;
      };
  var viewportH = xports['viewportH'] = function() {
        var a = docElem['clientHeight'], b = win['innerHeight'];
        return a < b ? b : a;
      };

  /**
   * Test if a media query is active. Like Modernizr.mq
   * @since 1.6.0
   * @return {boolean}
   */
  xports['mq'] = mq;

  /**
   * Normalized matchMedia
   * @since 1.6.0
   * @return {MediaQueryList|Object}
   */
  xports['matchMedia'] = matchMedia ? function() {
    // matchMedia must be binded to window
    return matchMedia.apply(win, arguments);
  } : function() {
    // Gracefully degrade to plain object
    return {};
  };

  /**
   * @since 1.8.0
   * @return {{width:number, height:number}}
   */
  function viewport() {
    return {'width': viewportW(), 'height': viewportH()};
  }
  xports['viewport'] = viewport;

  /**
   * Cross-browser window.scrollX
   * @since 1.0.0
   * @return {number}
   */
  xports['scrollX'] = function() {
    return win.pageXOffset || docElem.scrollLeft;
  };

  /**
   * Cross-browser window.scrollY
   * @since 1.0.0
   * @return {number}
   */
  xports['scrollY'] = function() {
    return win.pageYOffset || docElem.scrollTop;
  };

  /**
   * @param {{top:number, right:number, bottom:number, left:number}} coords
   * @param {number=} cushion adjustment
   * @return {Object}
   */
  function calibrate(coords, cushion) {
    var o = {};
    cushion = +cushion || 0;
    o['width'] = (o['right'] = coords['right'] + cushion) -
        (o['left'] = coords['left'] - cushion);
    o['height'] = (o['bottom'] = coords['bottom'] + cushion) -
        (o['top'] = coords['top'] - cushion);
    return o;
  }

  /**
   * Cross-browser element.getBoundingClientRect plus optional cushion.
   * Coords are relative to the top-left corner of the viewport.
   * @since 1.0.0
   * @param {Element|Object} el element or stack (uses first item)
   * @param {number=} cushion +/- pixel adjustment amount
   * @return {Object|boolean}
   */
  function rectangle(el, cushion) {
    el = el && !el.nodeType ? el[0] : el;
    if (!el || 1 !== el.nodeType) return false;
    return calibrate(el.getBoundingClientRect(), cushion);
  }
  xports['rectangle'] = rectangle;

  /**
   * Get the viewport aspect ratio (or the aspect ratio of an object or element)
   * @since 1.7.0
   * @param {(Element|Object)=} o optional object with
   *     width/height props or methods
   * @return {number}
   * @link http://w3.org/TR/css3-mediaqueries/#orientation
   */
  function aspect(o) {
    o = null == o ? viewport() : 1 === o.nodeType ? rectangle(o) : o;
    var h = o['height'], w = o['width'];
    h = typeof h == 'function' ? h.call(o) : h;
    w = typeof w == 'function' ? w.call(o) : w;
    return w / h;
  }
  xports['aspect'] = aspect;

  /**
   * Test if an element is in the same x-axis section as the viewport.
   * @since 1.0.0
   * @param {Element|Object} el
   * @param {number=} cushion
   * @return {boolean}
   */
  xports['inX'] = function(el, cushion) {
    var r = rectangle(el, cushion);
    return !!r && r.right >= 0 && r.left <= viewportW();
  };

  /**
   * Test if an element is in the same y-axis section as the viewport.
   * @since 1.0.0
   * @param {Element|Object} el
   * @param {number=} cushion
   * @return {boolean}
   */
  xports['inY'] = function(el, cushion) {
    var r = rectangle(el, cushion);
    return !!r && r.bottom >= 0 && r.top <= viewportH();
  };

  /**
   * Test if an element is in the viewport.
   * @since 1.0.0
   * @param {Element|Object} el
   * @param {number=} cushion
   * @return {boolean}
   */
  xports['inViewport'] = function(el, cushion) {
    // Equiv to `inX(el, cushion) && inY(el, cushion)` but just manually do both
    // to avoid calling rectangle() twice. It gzips just as small like this.
    var r = rectangle(el, cushion);
    return !!r && r.bottom >= 0 && r.right >= 0 &&
        r.top <= viewportH() && r.left <= viewportW();
  };

  return xports;
}));

;  // トリガーを解釈
  var TriggerManager = (function() {
    var TRIGGER_UNSET = 0;
    var TRIGGER_SET = 2;
    var TRIGGER_CALLED = 4;
    var TriggerManager = function(arg_triggers) {
      var self = this;
      self.triggerTimer = null;
      //self.triggers = (!!arg_triggers) ? arg_triggers : [];
      self.onSendTriggers = [];
      self.onExitTriggers = [];
      self.afterSendTriggers = [];
      self.afterSendTriggerTimers = [];
      //if (!!arg_triggers) self.evaluate();
      self.setTriggers(arg_triggers);
    };
    /*
    // トリガー評価タイマーをスタート
    TriggerManager.prototype.timerStart   = function() {
      var self = this;
      if (!self.triggerTimer) {
        self.triggerTimer = setInterval(function(){
          myconsolelog('trigger' + correctedDate());
          self.evaluate();
        }, 1000);
      }
    }
    */
    // トリガーをセット
    TriggerManager.prototype.setTriggers = function(arg_triggers) {
      if (!$.isArray(arg_triggers)) return false;
      var self = this;
      // このページ内では決して発動しないトリガーは最初から除いておく
      var setTriggers = $.map(arg_triggers, function(trigger) {
        if ($.inArray(trigger.id, cm.roominfo.triggered) != -1)
          return null;
        var isCondition = true;
        if ('AND' == trigger.info.selector || 1 == trigger.info.conditions.length) {
          trigger.info.conditions.forEach(function(condition) {
            switch (condition.on) {
              case 'IN_PAGEURL':
              case 'NOT_IN_PAGEURL':
              case 'COINCIDE_PAGEURL':
              case 'NOT_COINCIDE_PAGEURL':
              case 'IN_PAGETITLE':
              case 'NOT_IN_PAGETITLE':
              case 'COINCIDE_PAGETITLE':
              case 'NOT_COINCIDE_PAGETITLE':
              case 'VISIT_NUM_EQUAL':
              case 'VISIT_NUM_LESS':
              case 'VISIT_NUM_GREATER':
              case 'OPERATOR_NOSPOKE':
              case 'USER_NOSPOKE':
              case 'DEVICE_IPHONE':
              case 'DEVICE_ANDROID':
              case 'DEVICE_IPAD':
              case 'DEVICE_PC':
              case 'DEVICE_SMARTPHONE':
                if (!self._checkCondition(condition)) {
                  isCondition = false;
                }
                break;
              default:
                break;
            }
          });
          if (!isCondition) {
            return null;
          }
        }
        trigger.state = TRIGGER_UNSET;
        return trigger;
      });
      //myconsolelog('set triggers');
      //myconsolelog(cm.roominfo.triggered);
      //myconsolelog(arg_triggers);
      //myconsolelog(setTriggers);
      //myconsolelog(this.sortTriggers(setTriggers));
      //this.triggers = setTriggers;
      this.triggers = this.sortTriggers(setTriggers);
      this.evaluate();
      if (cm.roominfo.flag[FLAG_USER_SPOKE]) {
        self.onSend();
      }
    };
    // トリガー発動情報を更新
    TriggerManager.prototype.update = function() {
      var _triggered = [];
      if ($.isArray(cm.roominfo.triggered))
        _triggered = cm.roominfo.triggered;
      if (!this.triggers) return;
      this.triggers.forEach(function(trigger, index) {
        if ($.inArray(trigger.id, _triggered) != -1)
          this.triggers[index].state = TRIGGER_CALLED;
      }, this);
    };
    TriggerManager.prototype.evaluate = function() {
      var self = this;
      this.update();
      // setTimeoutなどを設定
      var timestamp_sec = Math.round(correctedDate().getTime() / 1000);
      if (!this.triggers) return;
      this.triggers.forEach(function(trigger, index) {
          if (trigger.state >= TRIGGER_SET) return;
          // アカウントの状態をチェック
          if (!self.isAccountOK(trigger)) return;
          // 発動条件をチェック
          if (!self.isCondition(trigger)) return;
          // タイミングをチェック
          self.triggers[index].state = TRIGGER_SET;
          switch (trigger.timing.on) {
            case 'IN_PAGE':
              var time_second = trigger.timing.time -
                  (timestamp_sec - cm.roominfo.time_inpage);
              if (time_second <= 0) {
                self.action(trigger);
              } else {
                setTimeout(function() {
                  self.action(trigger);
                }, time_second * 1000);
              }
              break;
            case 'IN_SITE':
              var time_second = trigger.timing.time -
                  (timestamp_sec - cm.roominfo.time_start);
              if (time_second <= 0) {
                self.action(trigger);
              } else {
                setTimeout(function() {
                  self.action(trigger);
                }, time_second * 1000);
              }
              break;
            case 'AFTER_MESSAGE':
              self.registerOnSendTrigger(trigger);
              if (!!cm.roominfo.flag[FLAG_USER_SPOKE]) {
                self.onSend();
              }
              break;
            case 'AFTER_LASTMESSAGE':
              self.registerAfterSendTriggers(trigger);
              if (!!cm.roominfo.flag[FLAG_USER_SPOKE]) {
                self.onSend();
              }
              break;
            case 'ON_EXIT':
              self.registerOnExitTrigger(trigger);
              break;
            default:
              break;
          }
      });
    };
    TriggerManager.prototype.isAccountOK = function(trigger) {
      switch (trigger.timing.account_state) {
        case 'ONLINE_ONLY':
          if (cm.account.state == CHAMO_STATE_ONLINE)
            return true;
          break;
        case 'WITH_OPERATOR':
          if (cm.account.state == CHAMO_STATE_ONLINE &&
              cm.account.operator_num > 0)
            return true;
          break;
        case 'NO_OPERATOR':
          if (cm.account.state == CHAMO_STATE_ONLINE &&
              cm.account.operator_num == 0)
            return true;
          break;
      }
      return false;
    };
    TriggerManager.prototype.isCondition = function(trigger) {
      var self = this;
      var isCondition = null;
      switch (trigger.info.selector) {
        case 'AND':
          isCondition = true;
          trigger.info.conditions.forEach(function(condition) {
            if (!self._checkCondition(condition)) {
              isCondition = false;
            }
          });
          break;
        case 'OR':
          isCondition = false;
          trigger.info.conditions.forEach(function(condition) {
            if (self._checkCondition(condition)) {
              isCondition = true;
            }
          });
          break;
      }
      return isCondition;
    };
    TriggerManager.prototype._checkCondition = function(condition) {
      switch (condition.on) {
        /**** ページ情報 ****/
        case 'IN_PAGEURL':
          return (location.href.indexOf(condition.detail) != -1) ? true : false;
          break;
        case 'NOT_IN_PAGEURL':
          return (location.href.indexOf(condition.detail) == -1) ? true : false;
          break;
        case 'COINCIDE_PAGEURL':
          return (location.href == condition.detail) ? true : false;
          break;
        case 'NOT_COINCIDE_PAGEURL':
          return (location.href != condition.detail) ? true : false;
          break;
        case 'IN_PAGETITLE':
          return (document.title.indexOf(condition.detail) != -1) ? true : false;
          break;
        case 'NOT_IN_PAGETITLE':
          return (document.title.indexOf(condition.detail) == -1) ? true : false;
          break;
        case 'COINCIDE_PAGETITLE':
          return (document.title == condition.detail) ? true : false;
          break;
        case 'NOT_COINCIDE_PAGETITLE':
          return (document.title != condition.detail) ? true : false;
          break;
        /**** リファラー情報 ****/
        case 'IN_REFERERURL':
          return (cm.roominfo.referer.indexOf(condition.detail) != -1) ?
              true : false;
          break;
        case 'NOT_IN_REFERERURL':
          return (cm.roominfo.referer.indexOf(condition.detail) == -1) ?
              true : false;
          break;
        case 'COINCIDE_REFERERURL':
          return (cm.roominfo.referer == condition.detail) ? true : false;
          break;
        case 'NOT_COINCIDE_REFERERURL':
          return (cm.roominfo.referer != condition.detail) ? true : false;
          break;
        /**** 訪問回数　****/
        case 'VISIT_NUM_EQUAL':
          return (cm.roominfo.visitno == condition.detail) ? true : false;
          break;
        case 'VISIT_NUM_LESS':
          return (cm.roominfo.visitno <= condition.detail) ? true : false;
          break;
        case 'VISIT_NUM_GREATER':
          return (cm.roominfo.visitno >= condition.detail) ? true : false;
          break;
        /**** 時間指定 ****/
        case 'TIME_IN':
          return isBetweenTimeNow(condition.detail);
          break;
        case 'TIME_OUT':
          return !isBetweenTimeNow(condition.detail);
          break;
        case 'DAY_OF_THE_WEEK':
          if (!$.isArray(condition.detail)) { return false; }
          if ($.inArray(7, condition.detail) != -1) {
            // 日曜日
            condition.detail[condition.detail.length] = 0;
          }
          return ($.inArray(correctedDate().getDay(), condition.detail) != -1) ?
              true : false;
          break;
        case 'DAY_OF_THE_WEEK_WITH_TIME':
          var dayOfTheWeek = correctedDate().getDay() || 7;    // 日曜日は7に直す
          var dayOfTheWeek_yesterday = (dayOfTheWeek - 1) || 7;  // 月曜の前日は7
          if (condition.detail[dayOfTheWeek] &&
              condition.detail[dayOfTheWeek].checked &&
              isBetweenTimeNow({
                hour1: condition.detail[dayOfTheWeek].hour1,
                min1: condition.detail[dayOfTheWeek].min1,
                hour2: (condition.detail[dayOfTheWeek].hour2 <= 23) ?
                    condition.detail[dayOfTheWeek].hour2 : 23,
                min2: (condition.detail[dayOfTheWeek].hour2 <= 23) ?
                    condition.detail[dayOfTheWeek].min2 : 59,
              })) {
            return true;
          } else if (condition.detail[dayOfTheWeek_yesterday] &&
              condition.detail[dayOfTheWeek_yesterday].checked &&
              condition.detail[dayOfTheWeek_yesterday].hour2 > 23 &&
              isBetweenTimeNow({
                hour1: 0,
                min1: 0,
                hour2: condition.detail[dayOfTheWeek_yesterday].hour2 - 24,
                min2: condition.detail[dayOfTheWeek_yesterday].min2,
              })) {
            return true;
          }
          return false;
          break;
        case 'SPECIFIC_DATE':
          return (correctedDate().getDate() == condition.detail) ? true : false;
          break;
        case 'SPECIFIC_DATE_WITH_TIME':
          if (correctedDate().getDate() == condition.detail.day &&
              isBetweenTimeNow({
                hour1: condition.detail.hour1,
                min1: condition.detail.min1,
                hour2: (condition.detail.hour2 <= 23) ?
                    condition.detail.hour2 : 23,
                min2: (condition.detail.hour2 <= 23) ?
                    condition.detail.min2 : 59,
              })) {
            return true;
          } else if (correctedDate().previousday().getDate() == condition.detail.day &&
              condition.detail.hour2 > 23 &&
              isBetweenTimeNow({
                hour1: 0,
                min1: 0,
                hour2: condition.detail.hour2 - 24,
                min2: condition.detail.min2,
              })) {
            return true;
          }
          return false;
          break;
        /**** オペレーターの行動を指定 ****/
        case 'OPERATOR_SPOKE':
          return (!!cm.roominfo.flag[FLAG_OPERATOR_SPOKE]);
          break;
        case 'OPERATOR_NOSPOKE':
          return (!cm.roominfo.flag[FLAG_OPERATOR_SPOKE]);
          break;
        /**** ユーザーの行動を指定 ****/
        case 'USER_SPOKE':
          return (!!cm.roominfo.flag[FLAG_USER_SPOKE]);
          break;
        case 'USER_NOSPOKE':
          return (!cm.roominfo.flag[FLAG_USER_SPOKE]);
          break;
        /**** ユーザーのフラグ条件 ****/
        case 'USER_FLAGGED':
          if (!condition.detail) return false;
          return (!!cm.roominfo.flag[condition.detail]);
          break;
        case 'USER_NOFLAGGED':
          if (!condition.detail) return false;
          return (!cm.roominfo.flag[condition.detail]);
          break;
        /**** ユーザーの利用デバイス ****/
        case 'DEVICE_IPHONE':
          return (cm.device === CHAMO_DEVICE_IPHONE);
          break;
        case 'DEVICE_ANDROID':
          return (cm.device === CHAMO_DEVICE_ANDROID);
          break;
        case 'DEVICE_IPAD':
          return (cm.device === CHAMO_DEVICE_IPAD);
          break;
        case 'DEVICE_PC':
          return (cm.device === CHAMO_DEVICE_PC);
          break;
        case 'DEVICE_SMARTPHONE':
          return (cm.device === CHAMO_DEVICE_IPHONE ||
              cm.device === CHAMO_DEVICE_ANDROID);
          break;
        /**** 発言内容をチェック ****/
        case 'USER_POST_COINCIDE':
          if (!condition.detail) return false;
          var isOK = false;
          $.each(cm.log, function(index, msg) {
            if ((msg.code == 'user_post' || msg.code == 'option_selected') &&
                $.trim(msg.info) == $.trim(condition.detail)) {
              isOK = true;
              return false;
            }
          });
          return isOK;
          break;
        case 'USER_POST_IN':
          if (!condition.detail) return false;
          var isOK = false;
          $.each(cm.log, function(index, msg) {
            if ((msg.code == 'user_post' || msg.code == 'option_selected') &&
                msg.info.indexOf(condition.detail) != -1) {
              isOK = true;
              return false;
            }
          });
          return isOK;
          break;
        /**** 条件なし ****/
        case 'NONE':
          return true;
          break;
        default:
          return false;
          break;
      }
      return false;
    };
    TriggerManager.prototype.action = function(trigger) {
      if (!this.isCondition(trigger) || !this.isAccountOK(trigger)) {
        // 発動条件を満たしていなければ再度 unset に
        var self = this;
        this.triggers.forEach(function(mytrigger, index) {
          if (mytrigger.id == trigger.id)
            self.triggers[index].state = TRIGGER_UNSET;
        });
        return false;
      }
      if (trigger.state == TRIGGER_CALLED) {
        return false;
      }
      var action_array = [];
      trigger.info.actions.forEach(function(action) {
        switch (action['do']) {
          case 'SEND_MESSAGE':
            //action_array[action_array.length] = {
            //  code: 'trigger',
            //  subcode: 'message',
            //  info:action.detail
            //};
            break;
          case 'SEND_SCRIPT':
            break;
          case 'SHOW_FORM':
            action_array[action_array.length] = {
              code: 'trigger',
              subcode: 'showform'
            };
            break;
          case 'SHOW_DEPARTMENT_LIST':
            //action_array[action_array.length] = {
            //  code: 'trigger',
            //  subcode: 'department_list'
            //};
            break;
          /*
          case 'CHAMO_HIDE':
            action_array[action_array.length] = {
              code: 'trigger',
              subcode: 'chamo_hide'
            };
            break;
          case 'CHAMO_SHOW':
            action_array[action_array.length] = {
              code:'trigger',
              subcode:'chamo_show'
            };
            break;
          */
          case 'SET_FLAG_TO_USER':
            //action_array[action_array.length] = {
            //  code:'trigger',
            //  subcode:'set_flag',
            //  info:action.detail
            //};
            break;
          case 'UNSET_FLAG_TO_USER':
            //action_array[action_array.length] = {
            //  code:'trigger',
            //  subcode:'unset_flag',
            //  info:action.detail
            //};
            break;
          case 'SET_OPERATOR_ANSWERED':
            break;
          case 'OFFLINE':
            action_array[action_array.length] = {
              code: 'trigger',
              subcode: 'offline'
            };
            break;
          default:
            return null;
            break;
        }
      });
      cm.update(action_array);
      // trigger called
      cm.roominfo.triggered[cm.roominfo.triggered.length] = trigger.id;
      timeline.push({
        code: 'system',
        subcode: 'trigger_called',
        info: trigger.id
      });
    };
    TriggerManager.prototype.registerOnSendTrigger = function(trigger) {
      this.onSendTriggers[this.onSendTriggers.length] = trigger;
    };
    TriggerManager.prototype.registerAfterSendTriggers = function(trigger) {
      this.afterSendTriggers[this.afterSendTriggers.length] = trigger;
    };
    TriggerManager.prototype.registerOnExitTrigger = function(trigger) {
      var self = this;
      if (this.onExitTriggers.length == 0 && !cm.status.isExitTriggerCalled) {
        $('input[type=image],input[type=submit]').one('click', function() {
          $(window).off('beforeunload.chamoOnExit');
        });
        $(window).on('beforeunload.chamoOnExit', function() {
          // 離脱時
          cm.status.window = CHAMO_DISPLAY_OPEN;
          cm.updateChat();
          // Set status to trigger called state
          cm.status.isExitTriggerCalled = true;
          cm.saveState();
          // Disable beforeunload
          $(window).off('beforeunload.chamoOnExit');
          // Set the dialog message
          var msg = '';
          var len = self.onExitTriggers.length;
          for (var i = 0; i < len; i++) {
            var trigger = self.onExitTriggers[i];
            if (self.isCondition(trigger) && self.isAccountOK(trigger)) {
              trigger.info.actions.forEach(function(action) {
                if (action['do'] == 'SEND_MESSAGE') {
                  msg = action.detail;
                  cm.onExitTriggers[cm.onExitTriggers.length] = {
                    code: 'trigger',
                    subcode: 'message',
                    info: action.detail
                  };
                }
              });
            }
          }
          if (!msg) msg = Localizer.getValue('trigger-exit-default');
          return msg;
        });
      }
      this.onExitTriggers[this.onExitTriggers.length] = trigger;
    };
    // ユーザーがメッセージを送信したときに呼ばれる。メッセージ送信後トリガーをセット
    TriggerManager.prototype.onSend = function() {
      if (!cm.roominfo.time_user_first_spoke) {
        return;
      }
      var self = this;
      var timestamp_sec = Math.round(correctedDate().getTime() / 1000);

      // ユーザーが最初に送信したメッセージからX秒後に発動するトリガー
      this.onSendTriggers.forEach(function(trigger) {
        var time_second = trigger.timing.time -
            (timestamp_sec - cm.roominfo.time_user_first_spoke);
        if (time_second <= 0) {
          self.action(trigger);
        } else {
          setTimeout(function() {
            self.action(trigger);
          }, time_second * 1000);
        }
      });
      this.onSendTriggers = [];

      // ユーザーが最後に送信したメッセージからX秒後に発動するトリガー
      this.afterSendTriggerTimers.forEach(function(timerID) {
        clearTimeout(timerID);
      });
      this.afterSendTriggerTimers = [];
      this.afterSendTriggers.forEach(function(trigger) {
        if (trigger.state == TRIGGER_CALLED) return;
        var time_second = trigger.timing.time -
            (timestamp_sec - cm.roominfo.time_user_last_spoke);
        if (time_second <= 0) {
          self.action(trigger);
        } else {
          self.afterSendTriggerTimers[self.afterSendTriggerTimers.length] =
              setTimeout(function() {
                self.action(trigger);
              }, time_second * 1000);
        }
      });
    };
    /*
    TriggerManager.prototype.isBetweenTimeNow = function(obj) {
      // 現在時刻が hour1:min1 ～ hour2:min2 の中かどうかをチェック
      var hour1 = obj.hour1,
          min1 = obj.min1,
          hour2 = obj.hour2,
          min2 = obj.min2;
      var d = correctedDate();
      var hour= d.getHours();
      var min = d.getMinutes();
      if (hour < hour1) return false;
      if (hour == hour1 && min < min1) return false;
      if (hour > hour2) return false;
      if (hour == hour2 && min > min2) return false;
      return true;
    };
    */
    TriggerManager.prototype.sortTriggers = function(triggers) {
      triggers.sort(function(a, b) {
        timingA = a.timing || {};
        timingB = b.timing || {};
        if (timingA.on < timingB.on) {
          return -1;
        } else if (timingA.on > timingB.on) {
          return 1;
        } else {
          return timingA.time - timingB.time;
        }
      });
      return triggers;
    };
    return TriggerManager;
  })();

;
// https://github.com/jes-sherborne/javascript-localizer
var Localizer={currentLanguage:null,fallbackLanguage:null,languages:{},languageRegEx:new RegExp("^([a-z]+)(-[a-z]+)?$")};Localizer.setLanguage=function(languageName){languageName=Localizer.validateLanguageName(languageName);if(languageName){Localizer.currentLanguage=Localizer.getOrCreateLanguage(languageName)}else{Localizer.currentLanguage=null}};Localizer.getLanguage=function(){if(Localizer.currentLanguage){return Localizer.currentLanguage.name}else{return null}};Localizer.setFallbackLanguage=function(languageName){languageName=Localizer.validateLanguageName(languageName);if(languageName){Localizer.fallbackLanguage=Localizer.getOrCreateLanguage(languageName)}else{Localizer.fallbackLanguage=null}};Localizer.getFallbackLanguage=function(){if(Localizer.fallbackLanguage){return Localizer.fallbackLanguage.name}else{return null}};Localizer.getValue=function(key){var targetValue;if(Localizer.currentLanguage){targetValue=Localizer.currentLanguage.getValue(key);if(targetValue!==null){return targetValue}}if(Localizer.fallbackLanguage){return Localizer.fallbackLanguage.getValue(key)}return null};Localizer.setValues=function(values){var iLanguageSet,thisLanguage,thisLanguageName,iTranslation,thisTranslationSet;for(iLanguageSet=0;iLanguageSet<values.length;iLanguageSet++){thisLanguageName=Localizer.validateLanguageName(values[iLanguageSet].language);thisLanguage=Localizer.getOrCreateLanguage(thisLanguageName);thisTranslationSet=values[iLanguageSet].translation;for(iTranslation=0;iTranslation<thisTranslationSet.length;iTranslation++){thisLanguage.setValue(thisTranslationSet[iTranslation][0],thisTranslationSet[iTranslation][1])}}};Localizer.getOrCreateLanguage=function(languageName){var result,baseLanguage,languageNameSplit;result=Localizer.languages[languageName];if(result){return result}languageNameSplit=languageName.split("-");baseLanguage=Localizer.languages[languageNameSplit[0]];if(!baseLanguage){baseLanguage=new Localizer.TranslationSet(languageNameSplit[0],languageNameSplit[0],"",null);Localizer.languages[languageNameSplit[0]]=baseLanguage}if(languageNameSplit.length===1){return baseLanguage}result=new Localizer.TranslationSet(languageName,languageNameSplit[0],languageNameSplit[1],baseLanguage);Localizer.languages[languageName]=result;return result};Localizer.validateLanguageName=function(name){var splitName;if(typeof name==="string"){if(name.length===0){return null}splitName=name.toLowerCase().match(Localizer.languageRegEx);if(splitName){return splitName[0]}}else if(name==null){return null}throw new Error("Invalid language name");};Localizer.TranslationSet=function(name,language,culture,parent){this.name=name;this.language=language;this.culture=culture;this.parent=parent;this.values={}};Localizer.TranslationSet.prototype.getValue=function(key){if(this.values[key]!=null){return this.values[key]}else if(this.parent){return this.parent.getValue(key)}return null};Localizer.TranslationSet.prototype.setValue=function(key,value){this.values[key]=value;if(value!==null&&this.parent){if(this.parent.values[key]==null){this.parent.setValue(key,value)}}};
// sprintf
Localizer.sprintf = function(key) {
  var str = this.getValue(key);
  for (var i = 1; i < arguments.length; i++) {
    str = str.replace(/%s|%d/, arguments[i]);
  }
  return str;
};

Localizer.setFallbackLanguage("ja");

Localizer.setValues([
    // Japanese
    {language: "ja", translation: [
      ["form-name",         "お名前"],
      ["form-email",        "メールアドレス"],
      ["form-message",      "メッセージをご入力ください。"],
      ["widget-hidechat",  　"チャットを隠す"],
      ["widget-hidechat-minute",  "%d分間、チャットウィンドウが非表示になります。"],
      ["widget-hidechat-eternal",  "今回のアクセス中、チャットウィンドウが非表示になります。"],
      ["widget-minimize",   "最小化"],
      ["widget-maximize",   "最大化"],
      ["widget-sendenter",  "メッセージ入力後、Enterキーで送信\n（Shift+Enterで改行）"],
      ["widget-unread",     "未読メッセージ "],
      ["widget-unread-unit","件"],
      ["widget-viewed",     "既読"],
      ["widget-send",       "送信"],
      ["widget-input",      "メッセージを入力..."],
      ["widget-chatend-x-minute", "チャット受付終了 %d分前"],
      ["message-file",    "ファイル"],
      ["messageform-send",    "メッセージを送信"],
      ["messageform-success", "お問い合わせありがとうございます。<br>後ほど担当者よりご連絡いたします。"],
      ["messageform-required","必須項目です。"],
      ["messageform-email","正しいメールアドレスを入力してください。"],
      ["messageform-sending", "メッセージ送信中..."],
      ["messageform-send-success",    "送信完了"],
      ["messageform-failed",  "送信に失敗しました"],
      ["status-send",       "送信しました"],
      ["status-sending",    "送信中..."],
      ["status-invalidconnect", "接続が無効です"],
      ["status-operatorinput",  "オペレータが入力しています..."],
      ["status-disconnect", "接続が切断されました。<br>インターネット接続を確認してください。<br><br>タップして再接続"],
      ["status-reconnect",  "再接続中です..."],
      ["status-reconnect-success",  "接続しました"],
      ["trigger-exit-default",  "ご質問はありませんか？"],
      ["error",   "エラー"],
      ["error-senderror",   "接続エラー<br>インターネット接続を確認の上、ページを再読み込みしてください。"],
      ["error-invaliddata",   "不正なデータを受信しました"],
      ["error-disconnect",   "通信が切断されました。<br>再読み込みしてください。"],
      ["confirm-move-chamo", "Chamo公式サイトへ移動します。よろしいでしょうか？"]
    ]},
    // Chinese
    {language: "cn", translation: [
      ["form-name",         "姓名"],
      ["form-email",        "电子邮箱"],
      ["form-message",      "请输入您的信息。"],
      ["widget-hidechat",  　"隐藏对话"],
      ["widget-hidechat-minute",  "%d 分钟，对话窗口变示为非表示。"],
      ["widget-hidechat-eternal",  "正在访问中，对话窗口变为非表示。"],
      ["widget-minimize",   "最小化"],
      ["widget-maximize",   "最大化"],
      ["widget-sendenter",  "信息输入后，请按 Enter 键发送"],
      ["widget-unread",     "未读信息 "],
      ["widget-unread-unit","件"],
      ["widget-viewed",     "已读"],
      ["widget-send",       "送信"],
      ["widget-input",      "请在这里输入信息..."],
      ["widget-chatend-x-minute", "对话处理结束  %d 分钟前"],
      ["message-file",    "档"],
      ["messageform-send",    "发送信息"],
      ["messageform-success", "感谢您的咨询。<br>稍后担当人员将会和您进行联系。"],
      ["messageform-required","必要项目。"],
      ["messageform-email","请输入正确的电子邮件地址。"],
      ["messageform-sending", "信息发送中..."],
      ["messageform-send-success",    "发送完成"],
      ["messageform-failed",  "发送失败"],
      ["status-send",       "已发送"],
      ["status-sending",    "发送中..."],
      ["status-invalidconnect", "连接无效"],
      ["status-operatorinput",  "操作人员正在输入中..."],
      ["status-disconnect", "连接已被切断。<br>请确认网络连接。<br><br>点击再次连接"],
      ["status-reconnect",  "再次连接中..."],
      ["status-reconnect-success",  "已连接"],
      ["trigger-exit-default",  "您有问题吗？"],
      ["error",   "错误"],
      ["error-senderror",   "连接错误。<br>确认网络连接之后，请再次读取网页"],
      ["error-invaliddata",   "已接受不良数据"],
      ["error-disconnect",   "通信被切断。<br>请再次读取。"],
      ["confirm-move-chamo", "Go to Chamo Official Website."]
    ]},
    // Korean
    {language: "kr", translation: [
      ["form-name",         "이름"],
      ["form-email",        "이메일 주소"],
      ["form-message",      "메시지를 입력해 주세요."],
      ["widget-hidechat",  　"채팅 숨기기"],
      ["widget-hidechat-minute",  "%d분 동안 채팅 창을 숨길 수 있습니다."],
      ["widget-hidechat-eternal",  "이번 액세스 동안, 채팅 창을 숨길 수 있습니다. "],
      ["widget-minimize",   "최소화"],
      ["widget-maximize",   "최대화"],
      ["widget-sendenter",  "메시지 입력 후, Enter 키로 전송"],
      ["widget-unread",     "읽지 않은 메시지 X"],
      ["widget-unread-unit","건"],
      ["widget-viewed",     "읽음"],
      ["widget-send",       "전송"],
      ["widget-input",      "여기에 메시지를 입력..."],
      ["widget-chatend-x-minute", "채팅 접수 마감 %d분전"],
      ["message-file",    "파일"],
      ["messageform-send",    "메시지 전송"],
      ["messageform-success", "문의해 주셔서 감사합니다.<br>나중에 담당자가 연락 드리겠습니다."],
      ["messageform-required","필수 항목입니다."],
      ["messageform-email","올바른 이메일 주소를 입력하십시오."],
      ["messageform-sending", "메시지 전송 중..."],
      ["messageform-send-success",    "전송 완료"],
      ["messageform-failed",  "전송에 실패했습니다"],
      ["status-send",       "전송했습니다"],
      ["status-sending",    "전송 중..."],
      ["status-invalidconnect", "연결이 잘못되었습니다"],
      ["status-operatorinput",  "담당자가 입력하고 있습니다..."],
      ["status-disconnect", "연결이 끊어졌습니다.<br>인터넷 연결을 확인하세요.<br><br>탭하여 다시 연결"],
      ["status-reconnect",  "다시 연결 중입니다..."],
      ["status-reconnect-success",  "연결되었습니다"],
      ["trigger-exit-default",  "문의 사항은 없습니까?"],
      ["error",   "오류"],
      ["error-senderror",   "연결 오류.<br>인터넷 연결을 확인 후, 페이지를 다시 로드하시기 바랍니다"],
      ["error-invaliddata",   "잘못된 데이터를 수신하였습니다"],
      ["error-disconnect",   "통신이 중단되었습니다.<br>다시 로드하시기 바랍니다. "],
      ["confirm-move-chamo", "Go to Chamo Official Website."]
    ]},
    // English
    {language: "en", translation: [
      ["form-name",         "Your Name"],
      ["form-email",        "Your Email"],
      ["form-message",      "Please type your message."],
      ["widget-hidechat",  　"Hide"],
      ["widget-hidechat-minute",  "The Chat Window will be hidden for the next %d minutes."],
      ["widget-hidechat-eternal",  "The Chat Widget will be hidden for this access."],
      ["widget-minimize",   "minimize window"],
      ["widget-maximize",   "maximize window"],
      ["widget-sendenter",  " Press <Enter> to send"],
      ["widget-unread",     "Unread message "],
      ["widget-unread-unit",""],
      ["widget-viewed",     "Read"],
      ["widget-send",       "Send"],
      ["widget-input",      "Type your message here"],
      ["widget-chatend-x-minute", "%d minutes until chat ends"],
      ["message-file",    "File"],
      ["messageform-send",    "Send"],
      ["messageform-success", "Thank you for your Mail.<br>We will reply soon."],
      ["messageform-required","Required"],
      ["messageform-email","Please enter a valid email address"],
      ["messageform-sending", "Sending..."],
      ["messageform-send-success",    "Sent"],
      ["messageform-failed",  "Failed to send your message"],
      ["status-send",       "Sent"],
      ["status-sending",    "sending..."],
      ["status-invalidconnect", "Invalid Connection"],
      ["status-operatorinput",  "Operator typing..."],
      ["status-disconnect", "Disconnected<br>Please check your network connection.<br><br>Tap here to reconnect."],
      ["status-reconnect",  "reconnecting..."],
      ["status-reconnect-success",  "Connection succeeded"],
      ["trigger-exit-default",  "May I help you?"],
      ["error",   "Error"],
      ["error-senderror",   "Connection failed<br>Check your network, and reload the page."],
      ["error-invaliddata",   "Invalid data received"],
      ["error-disconnect",   "Disconnected<br>Please reload the page."],
      ["confirm-move-chamo", "Go to Chamo Official Website."]
    ]}
  ]);

;var InputStateObserver = (function() {
  var InputStateObserver = function() {
    this.inputText_ = '';
    this.isInput_ = true;     // trueにしておくことで、ページ更新時にまずCHAMO_INPUT_ENDを投げる
    this.timer_ = null;
  };
  InputStateObserver.prototype.notify = function() {
    var self = this;
    clearTimeout(this.timer_);
    this.timer_ = window.setTimeout(function() {
      var isFocusOnTextarea = self.isFocusOnTextarea_();
      var inputtingText = self.getInputtingText_();
      // フォーカス　→　非フォーカス
      // 内容あり　→　内容削除
      if ((self.isInput_ && (!isFocusOnTextarea)) ||
          (self.inputText_ && (!inputtingText))) {
        self.isInput_ = false;
        self.inputText_ = '';
        cm.sendUserInput(CHAMO_INPUT_END);
        return;
      }
      // フォーカス　&&　内容変更
      if (isFocusOnTextarea && (inputtingText !== self.inputText_)) {
        self.isInput_ = true;
        self.inputText_ = inputtingText;
        cm.sendUserInput(self.inputText_);
        return;
      }
    }, 500);
  };
  /**
   * 現在、ユーザーがチャット入力中状態かどうか
   */
  InputStateObserver.prototype.isFocusOnTextarea_ = function() {
    return cv.isFocusOnTextarea();
  };
  /**
   * 現在、ユーザーがチャット入力中の文面を取得
   */
  InputStateObserver.prototype.getInputtingText_ = function() {
    return cv.getInputtingText();
  };

  return InputStateObserver;
}());

var inputStateObserver = new InputStateObserver();

;
var chamoAPI = (function() {
  var timers = {};
  var stacks = {};
  //var callbacks = {};

  /** @constructor */
  var chamoAPI = function() {
  };

  /*****************************
   *        User API
   *****************************/
  /**
   * ユーザー名を設定
   * @param {string} name - ユーザー名
   */
  var setName = function(name) {
    set({visitorName: name});
  };

  /**
   * メールアドレスを設定
   * @param {string} email - メールアドレス
   */
  var setEmail = function(email) {
    set({visitorEmail: email});
  };

  /**
   * 電話番号を設定
   * @param {string} tel - 電話番号
   */
  var setTel = function(tel) {
    set({visitorTel: tel});
  };

  /**
   * 顧客IDを設定
   * @param {string} customerid - 顧客ID
   */
  var setCustomerid = function(customerid) {
    set({visitorCustomerid: customerid});
  };

  /**
   * メモを設定
   * @param {string} memo - メモ
   */
  var setMemo = function(memo) {
    set({visitorMemo: memo});
  };

  /**
   * 既存のメモに内容を追加
   * @param {string} memo - メモ
   */
  var appendMemo = function(memo) {
    set({appendMemo: memo});
  };

  /**
   * ユーザー情報を設定
   * @param {object} info - ユーザー情報
   */
  var set = function(info) {
    if (!$.isPlainObject(info)) {
      console.log('Parameter must be object.');
      return false;
    }

    stacks['set'] = $.extend({}, stacks['set'], info);

    clearTimeout(timers['set']);
    timers['set'] = window.setTimeout(function() {
      timeline.push({
        code: 'api',
        subcode: 'set_userinfo',
        info: stacks['set']
      });
      stacks['set'] = {};
    }, 100);
  };

  chamoAPI.prototype.user = {
    setName: setName,
    setEmail: setEmail,
    setTel: setTel,
    setCustomerid: setCustomerid,
    setMemo: setMemo,
    appendMemo: appendMemo,
    set: set
  };


  /*****************************
   *        Chat API
   *****************************/
  /**
   * 現在設定されているタグを取得
   */
  var getRoomTags = function() {
    var tags = $.map((cm.roominfo.flag || []), function(val, name) {
      if (val && name.substring(0, 7) != '_chamo_') {
        return name;
      }
      return null;
    });
    return tags;
  };

  /**
   * タグを設定
   * @param {string|array} tags - タグ
   */
  var addRoomTags = function(tags) {
    if (!Array.isArray(tags)) {
      tags = [tags];
    }
    timeline.push({
      code: 'api',
      subcode: 'add_roomtag',
      info: tags
    });
  };

  /**
   * タグを削除
   * @param {string|array} tags - タグ
   */
  var removeRoomTags = function(tags) {
    if (!Array.isArray(tags)) {
      tags = [tags];
    }
    timeline.push({
      code: 'api',
      subcode: 'remove_roomtag',
      info: tags
    });
  };

  /**
   * アカウントの状態を取得
   * @return {string} state - 'online' または 'offline'
   */
  var getAccountState = function() {
    return (cm.account.state == CHAMO_STATE_ONLINE) ? 
        'online' : 'offline';
  }

  /**
   * ユーザーが未読のメッセージ件数を取得
   * @return {int} num - ユーザーが未読のメッセージ件数
   */
  var getUnreadNum = function() {
    return cm.status.num_unread - 0;
  }

  /**
   * ユーザーメッセージの送信
   * @param {string} message - 送信するメッセージ
   */
  var post = function(message) {
    return cm.post(message);
  }

  chamoAPI.prototype.chat = {
    addTags: addRoomTags,
    removeTags: removeRoomTags,
    getTags: getRoomTags,
    getState: getAccountState,
    getUnreadNum: getUnreadNum,
    post: post
  };


  /*****************************
   *        Widget API
   *****************************/
  /**
   * チャモを非表示にする
   */
  var widgetHide = function() {
    cm.hide();
  };

  /**
   * チャモを表示する
   */
  var widgetShow = function() {
    cm.show('connect');
  };

  /**
   * チャモを拡大する、非表示になっている場合は表示もする
   */
  var widgetExpand = function() {
    cm.show('connect');
    cm.status.window = CHAMO_DISPLAY_OPEN;
    cm.updateChat(true);
  };

  /**
   * チャモを最大化（スマホの場合）する、非表示になっている場合は表示もする
   */
  var widgetMaximize = function() {
    cm.show('connect');
    if (_chaq['device'] == 'ios' || _chaq['device'] == 'android') {
        cm.status.window = CHAMO_DISPLAY_MAXIMUM;    
    } else {
        cm.status.window = CHAMO_DISPLAY_OPEN;            
    }
    cm.updateChat(true);
  };

  /**
   * チャモを最小化する、非表示になっている場合は表示もする
   */
  var widgetMinimize = function() {
    cm.show('connect');
    cm.status.window = CHAMO_DISPLAY_WAITING;
    cm.updateChat(true);
  };

  chamoAPI.prototype.widget = {
    hide: widgetHide,
    show: widgetShow,
    expand: widgetExpand,
    maximize: widgetMaximize,
    minimize: widgetMinimize
  };


  /*****************************
   *        Operator API
   *****************************/
  /**
   * オペレータからのメッセージ送信する
   * 管理画面上では「ＡＰＩ送信」と表示されます。
   * @param {string} message - メッセージ内容
   */
  var operatorSendMessage = function(message) {
    if (!message) {
      return false;
    }
    timeline.push({
      code: 'api',
      subcode: 'operator_message',
      info: message
    });
    return true;
  };

  chamoAPI.prototype.operator = {
    sendMessage: operatorSendMessage
  };

  /*****************************
   *        Department
   *****************************/

  //var getDepartments = function() {
  //  timeline.push({
  //    code: 'api',
  //    subcode: 'department_list'
  //  });
  //  console.log('inside api');
  //};

  //chamoAPI.prototype.department = {
  //  getDepartments: getDepartments
  //};


  /*****************************
   *        Event API
   *****************************/

  var callbacks = {};

  /**
   * コールバック関数を追加する
   * @param {string} type - イベントタイプ
   * @param {function} fn - コールバック関数
   * @param {string} [name] - 名称
   */
  var addCallback = function(type, fn, name) {
    if (typeof type !== 'string') {
      return false;
    }
    callbacks[type] = callbacks[type] || {};

    if (name == null || typeof name !== 'string') {
      name = Object.keys(callbacks[type]).length;
    }

    callbacks[type][name] = fn;
    return true;
  };

  /**
   * 指定した名称のコールバックを削除する
   * @param {string} type - イベントタイプ
   * @param {string} name - 名称
   */
  var removeCallback = function(type, name) {
    if (type == null || name == null ||
        typeof type !== 'string' || typeof name !== 'string') {
      return false;
    }
    if (!callbacks[type]) {
      return false;
    }

    delete callbacks[type][name];
    return true;
  };

  /**
   * 指定したイベントタイプに設定されたコールバックを実行する
   * @param {string} type - イベントタイプ
   * @param {Object} [args] - コールバック関数に渡す引数
   */
  var trigger = function(type, args) {
    if (type == null || typeof type !== 'string') {
      return false;
    }
    if (!callbacks[type]) {
      return false;
    }

    Object.keys(callbacks[type]).forEach(function(key) {
      if (callbacks[type][key] && callbacks[type][key].apply) {
        callbacks[type][key](args);
      }
    });

    delete callbacks[type][name];
    return true;
  };

  chamoAPI.prototype.event = {
    onUserSend: function(fn, name) {
      addCallback('user_send', fn, name);
    },
    onOperatorSend: function(fn, name) {
      addCallback('operator_send', fn, name);
    },
    onTriggerMessage: function(fn, name) {
      addCallback('trigger_message', fn, name);
    },
    addCallback: addCallback,
    removeCallback: removeCallback,
    trigger: trigger
  };


  return chamoAPI;
}());

window.$chamo = window.$chamo || {};
if (USE_API || (location.href.indexOf(hostname1) != -1) || (location.href.indexOf(hostname2) != -1)) {
  window.$chamo.api = new chamoAPI();
}
;﻿
var DecorationParser = (function(){
    /**
     * @param   delimiter1 {String} - 装飾要素を判別する接頭辞
     * @param   delimiter2 {String} - 装飾要素を判別する接尾辞
     * @param   subdelimiter {String} - 装飾要素内の区切り文字
    */
    var parser = function( delimiter1, delimiter2, subdelimiter) {
        this.delimiter1 = delimiter1;
        this.delimiter2 = delimiter2;
        this.subdelimiter = subdelimiter;
        this.parseTemplates = {};
    }

    /**
     * 次の装飾要素を読込
     * @param   text   {String} - 解析対象文字列
     * @returns {Object} - { found: boolean(要素が見つかったらtrue), textBefore: {String}(要素までのtext), textAfter: {String}, type: {String}, name: {String} options: {Array} }
     */
    parser.prototype.parseNext_ = function(text) {
        var pos1, pos2, parBefore, parIn, parAfter;
        var options, type;

        // delimiter1 が見つからない場合は終了
        if (text.indexOf(this.delimiter1) == -1) {
            return {
                found: false
            };
        }

        // 文字列を分解
        pos1 = text.indexOf(this.delimiter1);
        parBefore = text.substring(0, pos1);
        parAfter = text.substring(pos1 + this.delimiter1.length);
        pos2 = parAfter.indexOf(this.delimiter2);
        parIn = parAfter.substring(0, pos2);
        parAfter = parAfter.substring(pos2 + this.delimiter2.length);

        // オプションを抽出
        options = parIn.split(this.subdelimiter);        
        type = options.shift();

        return {
            found:      true,
            textBefore: parBefore,
            textAfter:  parAfter,
            type:       type,
            options:    options
        };
    }

    /**
     * parse時のルールを追加する
     * @param type {String} - タイプ
     * @param template {String} - parse後のルール（例）<a href="($2):($3)">($1)</a>
     * @return {boolean} - 成功したらtrue
     */
    parser.prototype.addParseTemplate= function(type, template) {
        this.parseTemplates[type] = template;
        return true;
    }

    /**
     * 解析する
     * @param text {String} - 解析対象の文字列
     */
    parser.prototype.format = function(text) {
        var result;
        while (result = this.parseNext_(text)) {
            if (!result.found) {
                break;
            }

            if (this.parseTemplates[result.type]) {
                text = result.textBefore + this.formatTemplate_(result.options, this.parseTemplates[result.type]) + result.textAfter;
            } else {
                text = result.textBefore + result.type + result.textAfter;
            }
        }
        return text;
    }

    /**
     * 解析する
     * @param options {Array} - 置換文字列の配列
     * @param template {String} - テンプレート文字列
     */
    parser.prototype.formatTemplate_ = function( options, template) {
        var result = template + '';
        for (var i = 0; i < options.length; i++) {
            result = result.replace( new RegExp("%%" + (i+1) + "%%", "g"), options[i]);
        }
        return result;
    }

    return parser;
})();

;    // Onload
    $(cm.init);
    // Turbolinks
    $(document).bind("page:load", cm.init);
    $(document).bind("page:restore", cm.init);

})(jQueryChamo);