var COMPILED=true;var goog=goog||{};goog.global=this;goog.global.CLOSURE_UNCOMPILED_DEFINES;goog.global.CLOSURE_DEFINES;goog.isDef=function(val){return val!==void 0;};goog.exportPath_=function(name,opt_object,opt_objectToExportTo){var parts=name.split('.');var cur=opt_objectToExportTo||goog.global;if(!(parts[0]in cur)&&cur.execScript){cur.execScript('var '+parts[0]);}
for(var part;parts.length&&(part=parts.shift());){if(!parts.length&&goog.isDef(opt_object)){cur[part]=opt_object;}else if(cur[part]){cur=cur[part];}else{cur=cur[part]={};}}};goog.define=function(name,defaultValue){var value=defaultValue;if(!COMPILED){if(goog.global.CLOSURE_UNCOMPILED_DEFINES&&Object.prototype.hasOwnProperty.call(goog.global.CLOSURE_UNCOMPILED_DEFINES,name)){value=goog.global.CLOSURE_UNCOMPILED_DEFINES[name];}else if(goog.global.CLOSURE_DEFINES&&Object.prototype.hasOwnProperty.call(goog.global.CLOSURE_DEFINES,name)){value=goog.global.CLOSURE_DEFINES[name];}}
goog.exportPath_(name,value);};goog.DEBUG=true;goog.define('goog.LOCALE','en');goog.define('goog.TRUSTED_SITE',true);goog.define('goog.STRICT_MODE_COMPATIBLE',false);goog.provide=function(name){if(!COMPILED){if(goog.isProvided_(name)){throw Error('Namespace "'+name+'" already declared.');}
delete goog.implicitNamespaces_[name];var namespace=name;while((namespace=namespace.substring(0,namespace.lastIndexOf('.')))){if(goog.getObjectByName(namespace)){break;}
goog.implicitNamespaces_[namespace]=true;}}
goog.exportPath_(name);};goog.setTestOnly=function(opt_message){if(COMPILED&&!goog.DEBUG){opt_message=opt_message||'';throw Error('Importing test-only code into non-debug environment'+
opt_message?': '+opt_message:'.');}};goog.forwardDeclare=function(name){};if(!COMPILED){goog.isProvided_=function(name){return!goog.implicitNamespaces_[name]&&goog.isDefAndNotNull(goog.getObjectByName(name));};goog.implicitNamespaces_={};}
goog.getObjectByName=function(name,opt_obj){var parts=name.split('.');var cur=opt_obj||goog.global;for(var part;part=parts.shift();){if(goog.isDefAndNotNull(cur[part])){cur=cur[part];}else{return null;}}
return cur;};goog.globalize=function(obj,opt_global){var global=opt_global||goog.global;for(var x in obj){global[x]=obj[x];}};goog.addDependency=function(relPath,provides,requires){if(goog.DEPENDENCIES_ENABLED){var provide,require;var path=relPath.replace(/\\/g,'/');var deps=goog.dependencies_;for(var i=0;provide=provides[i];i++){deps.nameToPath[provide]=path;if(!(path in deps.pathToNames)){deps.pathToNames[path]={};}
deps.pathToNames[path][provide]=true;}
for(var j=0;require=requires[j];j++){if(!(path in deps.requires)){deps.requires[path]={};}
deps.requires[path][require]=true;}}};goog.define('goog.ENABLE_DEBUG_LOADER',true);goog.require=function(name){if(!COMPILED){if(goog.isProvided_(name)){return;}
if(goog.ENABLE_DEBUG_LOADER){var path=goog.getPathFromDeps_(name);if(path){goog.included_[path]=true;goog.writeScripts_();return;}}
var errorMessage='goog.require could not find: '+name;if(goog.global.console){goog.global.console['error'](errorMessage);}
throw Error(errorMessage);}};goog.basePath='';goog.global.CLOSURE_BASE_PATH;goog.global.CLOSURE_NO_DEPS=true;goog.global.CLOSURE_IMPORT_SCRIPT;goog.nullFunction=function(){};goog.identityFunction=function(opt_returnValue,var_args){return opt_returnValue;};goog.abstractMethod=function(){throw Error('unimplemented abstract method');};goog.addSingletonGetter=function(ctor){ctor.getInstance=function(){if(ctor.instance_){return ctor.instance_;}
if(goog.DEBUG){goog.instantiatedSingletons_[goog.instantiatedSingletons_.length]=ctor;}
return ctor.instance_=new ctor;};};goog.instantiatedSingletons_=[];goog.DEPENDENCIES_ENABLED=!COMPILED&&goog.ENABLE_DEBUG_LOADER;if(goog.DEPENDENCIES_ENABLED){goog.included_={};goog.dependencies_={pathToNames:{},nameToPath:{},requires:{},visited:{},written:{}};goog.inHtmlDocument_=function(){var doc=goog.global.document;return typeof doc!='undefined'&&'write'in doc;};goog.findBasePath_=function(){if(goog.global.CLOSURE_BASE_PATH){goog.basePath=goog.global.CLOSURE_BASE_PATH;return;}else if(!goog.inHtmlDocument_()){return;}
var doc=goog.global.document;var scripts=doc.getElementsByTagName('script');for(var i=scripts.length-1;i>=0;--i){var src=scripts[i].src;var qmark=src.lastIndexOf('?');var l=qmark==-1?src.length:qmark;if(src.substr(l-7,7)=='base.js'){goog.basePath=src.substr(0,l-7);return;}}};goog.importScript_=function(src){var importScript=goog.global.CLOSURE_IMPORT_SCRIPT||goog.writeScriptTag_;if(!goog.dependencies_.written[src]&&importScript(src)){goog.dependencies_.written[src]=true;}};goog.writeScriptTag_=function(src){if(goog.inHtmlDocument_()){var doc=goog.global.document;if(doc.readyState=='complete'){var isDeps=/\bdeps.js$/.test(src);if(isDeps){return false;}else{throw Error('Cannot write "'+src+'" after document load');}}
doc.write('<script type="text/javascript" src="'+src+'"></'+'script>');return true;}else{return false;}};goog.writeScripts_=function(){var scripts=[];var seenScript={};var deps=goog.dependencies_;function visitNode(path){if(path in deps.written){return;}
if(path in deps.visited){if(!(path in seenScript)){seenScript[path]=true;scripts.push(path);}
return;}
deps.visited[path]=true;if(path in deps.requires){for(var requireName in deps.requires[path]){if(!goog.isProvided_(requireName)){if(requireName in deps.nameToPath){visitNode(deps.nameToPath[requireName]);}else{throw Error('Undefined nameToPath for '+requireName);}}}}
if(!(path in seenScript)){seenScript[path]=true;scripts.push(path);}}
for(var path in goog.included_){if(!deps.written[path]){visitNode(path);}}
for(var i=0;i<scripts.length;i++){if(scripts[i]){goog.importScript_(goog.basePath+scripts[i]);}else{throw Error('Undefined script input');}}};goog.getPathFromDeps_=function(rule){if(rule in goog.dependencies_.nameToPath){return goog.dependencies_.nameToPath[rule];}else{return null;}};goog.findBasePath_();if(!goog.global.CLOSURE_NO_DEPS){goog.importScript_(goog.basePath+'deps.js');}}
goog.typeOf=function(value){var s=typeof value;if(s=='object'){if(value){if(value instanceof Array){return'array';}else if(value instanceof Object){return s;}
var className=Object.prototype.toString.call((value));if(className=='[object Window]'){return'object';}
if((className=='[object Array]'||typeof value.length=='number'&&typeof value.splice!='undefined'&&typeof value.propertyIsEnumerable!='undefined'&&!value.propertyIsEnumerable('splice'))){return'array';}
if((className=='[object Function]'||typeof value.call!='undefined'&&typeof value.propertyIsEnumerable!='undefined'&&!value.propertyIsEnumerable('call'))){return'function';}}else{return'null';}}else if(s=='function'&&typeof value.call=='undefined'){return'object';}
return s;};goog.isNull=function(val){return val===null;};goog.isDefAndNotNull=function(val){return val!=null;};goog.isArray=function(val){return goog.typeOf(val)=='array';};goog.isArrayLike=function(val){var type=goog.typeOf(val);return type=='array'||type=='object'&&typeof val.length=='number';};goog.isDateLike=function(val){return goog.isObject(val)&&typeof val.getFullYear=='function';};goog.isString=function(val){return typeof val=='string';};goog.isBoolean=function(val){return typeof val=='boolean';};goog.isNumber=function(val){return typeof val=='number';};goog.isFunction=function(val){return goog.typeOf(val)=='function';};goog.isObject=function(val){var type=typeof val;return type=='object'&&val!=null||type=='function';};goog.getUid=function(obj){return obj[goog.UID_PROPERTY_]||(obj[goog.UID_PROPERTY_]=++goog.uidCounter_);};goog.hasUid=function(obj){return!!obj[goog.UID_PROPERTY_];};goog.removeUid=function(obj){if('removeAttribute'in obj){obj.removeAttribute(goog.UID_PROPERTY_);}
try{delete obj[goog.UID_PROPERTY_];}catch(ex){}};goog.UID_PROPERTY_='closure_uid_'+((Math.random()*1e9)>>>0);goog.uidCounter_=0;goog.getHashCode=goog.getUid;goog.removeHashCode=goog.removeUid;goog.cloneObject=function(obj){var type=goog.typeOf(obj);if(type=='object'||type=='array'){if(obj.clone){return obj.clone();}
var clone=type=='array'?[]:{};for(var key in obj){clone[key]=goog.cloneObject(obj[key]);}
return clone;}
return obj;};goog.bindNative_=function(fn,selfObj,var_args){return(fn.call.apply(fn.bind,arguments));};goog.bindJs_=function(fn,selfObj,var_args){if(!fn){throw new Error();}
if(arguments.length>2){var boundArgs=Array.prototype.slice.call(arguments,2);return function(){var newArgs=Array.prototype.slice.call(arguments);Array.prototype.unshift.apply(newArgs,boundArgs);return fn.apply(selfObj,newArgs);};}else{return function(){return fn.apply(selfObj,arguments);};}};goog.bind=function(fn,selfObj,var_args){if(Function.prototype.bind&&Function.prototype.bind.toString().indexOf('native code')!=-1){goog.bind=goog.bindNative_;}else{goog.bind=goog.bindJs_;}
return goog.bind.apply(null,arguments);};goog.partial=function(fn,var_args){var args=Array.prototype.slice.call(arguments,1);return function(){var newArgs=args.slice();newArgs.push.apply(newArgs,arguments);return fn.apply(this,newArgs);};};goog.mixin=function(target,source){for(var x in source){target[x]=source[x];}};goog.now=(goog.TRUSTED_SITE&&Date.now)||(function(){return+new Date();});goog.globalEval=function(script){if(goog.global.execScript){goog.global.execScript(script,'JavaScript');}else if(goog.global.eval){if(goog.evalWorksForGlobals_==null){goog.global.eval('var _et_ = 1;');if(typeof goog.global['_et_']!='undefined'){delete goog.global['_et_'];goog.evalWorksForGlobals_=true;}else{goog.evalWorksForGlobals_=false;}}
if(goog.evalWorksForGlobals_){goog.global.eval(script);}else{var doc=goog.global.document;var scriptElt=doc.createElement('script');scriptElt.type='text/javascript';scriptElt.defer=false;scriptElt.appendChild(doc.createTextNode(script));doc.body.appendChild(scriptElt);doc.body.removeChild(scriptElt);}}else{throw Error('goog.globalEval not available');}};goog.evalWorksForGlobals_=null;goog.cssNameMapping_;goog.cssNameMappingStyle_;goog.getCssName=function(className,opt_modifier){var getMapping=function(cssName){return goog.cssNameMapping_[cssName]||cssName;};var renameByParts=function(cssName){var parts=cssName.split('-');var mapped=[];for(var i=0;i<parts.length;i++){mapped.push(getMapping(parts[i]));}
return mapped.join('-');};var rename;if(goog.cssNameMapping_){rename=goog.cssNameMappingStyle_=='BY_WHOLE'?getMapping:renameByParts;}else{rename=function(a){return a;};}
if(opt_modifier){return className+'-'+rename(opt_modifier);}else{return rename(className);}};goog.setCssNameMapping=function(mapping,opt_style){goog.cssNameMapping_=mapping;goog.cssNameMappingStyle_=opt_style;};goog.global.CLOSURE_CSS_NAME_MAPPING;if(!COMPILED&&goog.global.CLOSURE_CSS_NAME_MAPPING){goog.cssNameMapping_=goog.global.CLOSURE_CSS_NAME_MAPPING;}
goog.getMsg=function(str,opt_values){var values=opt_values||{};for(var key in values){var value=(''+values[key]).replace(/\$/g,'$$$$');str=str.replace(new RegExp('\\{\\$'+key+'\\}','gi'),value);}
return str;};goog.getMsgWithFallback=function(a,b){return a;};goog.exportSymbol=function(publicPath,object,opt_objectToExportTo){goog.exportPath_(publicPath,object,opt_objectToExportTo);};goog.exportProperty=function(object,publicName,symbol){object[publicName]=symbol;};goog.inherits=function(childCtor,parentCtor){function tempCtor(){};tempCtor.prototype=parentCtor.prototype;childCtor.superClass_=parentCtor.prototype;childCtor.prototype=new tempCtor();childCtor.prototype.constructor=childCtor;childCtor.base=function(me,methodName,var_args){var args=Array.prototype.slice.call(arguments,2);return parentCtor.prototype[methodName].apply(me,args);};};goog.base=function(me,opt_methodName,var_args){var caller=arguments.callee.caller;if(goog.STRICT_MODE_COMPATIBLE||(goog.DEBUG&&!caller)){throw Error('arguments.caller not defined.  goog.base() cannot be used '+'with strict mode code. See '+'http://www.ecma-international.org/ecma-262/5.1/#sec-C');}
if(caller.superClass_){return caller.superClass_.constructor.apply(me,Array.prototype.slice.call(arguments,1));}
var args=Array.prototype.slice.call(arguments,2);var foundCaller=false;for(var ctor=me.constructor;ctor;ctor=ctor.superClass_&&ctor.superClass_.constructor){if(ctor.prototype[opt_methodName]===caller){foundCaller=true;}else if(foundCaller){return ctor.prototype[opt_methodName].apply(me,args);}}
if(me[opt_methodName]===caller){return me.constructor.prototype[opt_methodName].apply(me,args);}else{throw Error('goog.base called from a method of one name '+'to a method of a different name');}};goog.scope=function(fn){fn.call(goog.global);};if(!COMPILED){goog.global['COMPILED']=COMPILED;}
goog.provide('cvox.AbstractEarcons');goog.provide('cvox.Earcon');cvox.Earcon={ALERT_MODAL:'alert_modal',ALERT_NONMODAL:'alert_nonmodal',BUTTON:'button',CHECK_OFF:'check_off',CHECK_ON:'check_on',EDITABLE_TEXT:'editable_text',INVALID_KEYPRESS:'invalid_keypress',LINK:'link',LISTBOX:'listbox',LIST_ITEM:'list_item',LONG_DESC:'long_desc',MATH:'math',OBJECT_CLOSE:'object_close',OBJECT_ENTER:'object_enter',OBJECT_EXIT:'object_exit',OBJECT_OPEN:'object_open',OBJECT_SELECT:'object_select',PAGE_FINISH_LOADING:'page_finish_loading',PAGE_START_LOADING:'page_start_loading',POP_UP_BUTTON:'pop_up_button',RECOVER_FOCUS:'recover_focus',SELECTION:'selection',SELECTION_REVERSE:'selection_reverse',SKIP:'skip',SLIDER:'slider',WRAP:'wrap',WRAP_EDGE:'wrap_edge',};cvox.AbstractEarcons=function(){};cvox.AbstractEarcons.enabled=true;cvox.AbstractEarcons.prototype.playEarcon=function(earcon){};cvox.AbstractEarcons.prototype.cancelEarcon=function(earcon){};cvox.AbstractEarcons.prototype.earconsAvailable=function(){return true;};cvox.AbstractEarcons.prototype.toggle=function(){cvox.AbstractEarcons.enabled=!cvox.AbstractEarcons.enabled;return cvox.AbstractEarcons.enabled;};goog.provide('Msgs');Msgs=function(){};Msgs.NAMESPACE_='chromevox_';Msgs.localeNameDict_=null;Msgs.getLocale=function(){return chrome.i18n.getMessage('locale');};Msgs.getMsg=function(messageId,opt_subs){var message=Msgs.Untranslated[messageId.toUpperCase()];if(message!==undefined)
return Msgs.applySubstitutions_(message,opt_subs);message=chrome.i18n.getMessage(Msgs.NAMESPACE_+messageId,opt_subs);if(message==undefined||message==''){throw new Error('Invalid ChromeVox message id: '+messageId);}
return message;};Msgs.addTranslatedMessagesToDom=function(root){var elts=root.querySelectorAll('.i18n');for(var i=0;i<elts.length;i++){var msgid=elts[i].getAttribute('msgid');if(!msgid){throw new Error('Element has no msgid attribute: '+elts[i]);}
var val=this.getMsg(msgid);if(elts[i].tagName=='INPUT'){elts[i].setAttribute('placeholder',val);}else{elts[i].textContent=val;}
elts[i].classList.add('i18n-processed');}};Msgs.getNumber=function(num){return''+num;};Msgs.getLocaleDisplayName=function(locale){if(!Msgs.localeNameDict_){Msgs.localeNameDict_=(JSON.parse(this.getMsg('locale_dict')));}
var name=Msgs.localeNameDict_[locale];if(!name){throw Error('Unsupported locale identifier: '+locale);}
return name;};Msgs.applySubstitutions_=function(message,opt_subs){if(opt_subs){for(var i=0;i<opt_subs.length;i++){message=message.replace('$'+(i+1),opt_subs[i]);}}
return message;};Msgs.Untranslated={CHECKBOX_UNCHECKED_STATE_BRL:'( )',CHECKBOX_CHECKED_STATE_BRL:'(x)',RADIO_UNSELECTED_STATE_BRL:'( )',RADIO_SELECTED_STATE_BRL:'(x)',ARIA_HAS_SUBMENU_BRL:'->',ROLE_OPTION:' ',ROLE_OPTION_BRL:' ',ARIA_CHECKED_TRUE_BRL:'(x)',ARIA_CHECKED_FALSE_BRL:'( )',ARIA_CHECKED_MIXED_BRL:'(-)',ARIA_DISABLED_TRUE_BRL:'xx',ARIA_EXPANDED_TRUE_BRL:'-',ARIA_EXPANDED_FALSE_BRL:'+',ARIA_INVALID_TRUE_BRL:'!',ARIA_PRESSED_TRUE_BRL:'=',ARIA_PRESSED_FALSE_BRL:' ',ARIA_PRESSED_MIXED_BRL:'-',ARIA_SELECTED_TRUE_BRL:'(x)',ARIA_SELECTED_FALSE_BRL:'( )',HAS_SUBMENU_BRL:'->',TAG_TIME_BRL:' ',ARIA_VALUE_NOW:'$1',ARIA_VALUE_NOW_BRL:'$1',ARIA_VALUE_TEXT:'$1',ARIA_VALUE_TEXT_BRL:'$1',};goog.provide('cvox.NodeState');goog.provide('cvox.NodeStateUtil');goog.require('Msgs');cvox.NodeState;cvox.NodeStateUtil.expand=function(state){try{return state.map(function(s){if(s.length<1){throw new Error('cvox.NodeState must have at least one entry');}
var args=s.slice(1).map(function(a){if(typeof a=='number'){return Msgs.getNumber(a);}
return a;});return Msgs.getMsg((s[0]),args);}).join(' ');}catch(e){throw new Error('error: '+e+' state: '+state);}};goog.provide('cvox.XpathUtil');cvox.XpathUtil=function(){};cvox.XpathUtil.nameSpaces_={'xhtml':'http://www.w3.org/1999/xhtml','mathml':'http://www.w3.org/1998/Math/MathML'};cvox.XpathUtil.resolveNameSpace=function(prefix){return cvox.XpathUtil.nameSpaces_[prefix]||null;};cvox.XpathUtil.evalXPath=function(expression,rootNode){try{var xpathIterator=rootNode.ownerDocument.evaluate(expression,rootNode,cvox.XpathUtil.resolveNameSpace,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);}catch(err){return[];}
var results=[];for(var xpathNode=xpathIterator.iterateNext();xpathNode;xpathNode=xpathIterator.iterateNext()){results.push(xpathNode);}
return results;};cvox.XpathUtil.getLeafNodes=function(rootNode){try{var xpathIterator=rootNode.ownerDocument.evaluate('.//*[count(*)=0]',rootNode,null,XPathResult.ORDERED_NODE_ITERATOR_TYPE,null);}catch(err){return[];}
var results=[];for(var xpathNode=xpathIterator.iterateNext();xpathNode;xpathNode=xpathIterator.iterateNext()){results.push(xpathNode);}
return results;};cvox.XpathUtil.xpathSupported=function(){if(typeof(XPathResult)=='undefined'){return false;}
return true;};cvox.XpathUtil.evaluateBoolean=function(expression,rootNode){try{var xpathResult=rootNode.ownerDocument.evaluate(expression,rootNode,cvox.XpathUtil.resolveNameSpace,XPathResult.BOOLEAN_TYPE,null);}catch(err){return false;}
return xpathResult.booleanValue;};cvox.XpathUtil.evaluateString=function(expression,rootNode){try{var xpathResult=rootNode.ownerDocument.evaluate(expression,rootNode,cvox.XpathUtil.resolveNameSpace,XPathResult.STRING_TYPE,null);}catch(err){return'';}
return xpathResult.stringValue;};goog.provide('cvox.QueueMode');goog.provide('cvox.TtsCapturingEventListener');goog.provide('cvox.TtsCategory');goog.provide('cvox.TtsInterface');cvox.TtsCategory={LIVE:'live',NAV:'nav'};cvox.QueueMode={FLUSH:0,QUEUE:1,CATEGORY_FLUSH:2};cvox.TtsCapturingEventListener=function(){};cvox.TtsCapturingEventListener.prototype.onTtsStart=function(){};cvox.TtsCapturingEventListener.prototype.onTtsEnd=function(){};cvox.TtsInterface=function(){};cvox.TtsInterface.prototype.speak=function(textString,queueMode,properties){};cvox.TtsInterface.prototype.isSpeaking=function(){};cvox.TtsInterface.prototype.stop=function(){};cvox.TtsInterface.prototype.addCapturingEventListener=function(listener){};cvox.TtsInterface.prototype.increaseOrDecreaseProperty=function(propertyName,increase){};cvox.TtsInterface.prototype.propertyToPercentage=function(property){};cvox.TtsInterface.prototype.getDefaultProperty=function(property){};goog.provide('goog.dom.NodeType');goog.dom.NodeType={ELEMENT:1,ATTRIBUTE:2,TEXT:3,CDATA_SECTION:4,ENTITY_REFERENCE:5,ENTITY:6,PROCESSING_INSTRUCTION:7,COMMENT:8,DOCUMENT:9,DOCUMENT_TYPE:10,DOCUMENT_FRAGMENT:11,NOTATION:12};goog.provide('goog.debug.Error');goog.debug.Error=function(opt_msg){if(Error.captureStackTrace){Error.captureStackTrace(this,goog.debug.Error);}else{var stack=new Error().stack;if(stack){this.stack=stack;}}
if(opt_msg){this.message=String(opt_msg);}};goog.inherits(goog.debug.Error,Error);goog.debug.Error.prototype.name='CustomError';goog.provide('goog.string');goog.string.subs=function(str,var_args){var splitParts=str.split('%s');var returnString='';var subsArguments=Array.prototype.slice.call(arguments,1);while(subsArguments.length&&splitParts.length>1){returnString+=splitParts.shift()+subsArguments.shift();}
return returnString+splitParts.join('%s');};goog.provide('goog.asserts');goog.provide('goog.asserts.AssertionError');goog.require('goog.debug.Error');goog.require('goog.dom.NodeType');goog.require('goog.string');goog.define('goog.asserts.ENABLE_ASSERTS',goog.DEBUG);goog.asserts.AssertionError=function(messagePattern,messageArgs){messageArgs.unshift(messagePattern);goog.debug.Error.call(this,goog.string.subs.apply(null,messageArgs));messageArgs.shift();this.messagePattern=messagePattern;};goog.inherits(goog.asserts.AssertionError,goog.debug.Error);goog.asserts.AssertionError.prototype.name='AssertionError';goog.asserts.doAssertFailure_=function(defaultMessage,defaultArgs,givenMessage,givenArgs){var message='Assertion failed';if(givenMessage){message+=': '+givenMessage;var args=givenArgs;}else if(defaultMessage){message+=': '+defaultMessage;args=defaultArgs;}
throw new goog.asserts.AssertionError(''+message,args||[]);};goog.asserts.assert=function(condition,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&!condition){goog.asserts.doAssertFailure_('',null,opt_message,Array.prototype.slice.call(arguments,2));}
return condition;};goog.asserts.fail=function(opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS){throw new goog.asserts.AssertionError('Failure'+(opt_message?': '+opt_message:''),Array.prototype.slice.call(arguments,1));}};goog.asserts.assertNumber=function(value,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&!goog.isNumber(value)){goog.asserts.doAssertFailure_('Expected number but got %s: %s.',[goog.typeOf(value),value],opt_message,Array.prototype.slice.call(arguments,2));}
return(value);};goog.asserts.assertString=function(value,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&!goog.isString(value)){goog.asserts.doAssertFailure_('Expected string but got %s: %s.',[goog.typeOf(value),value],opt_message,Array.prototype.slice.call(arguments,2));}
return(value);};goog.asserts.assertFunction=function(value,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&!goog.isFunction(value)){goog.asserts.doAssertFailure_('Expected function but got %s: %s.',[goog.typeOf(value),value],opt_message,Array.prototype.slice.call(arguments,2));}
return(value);};goog.asserts.assertObject=function(value,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&!goog.isObject(value)){goog.asserts.doAssertFailure_('Expected object but got %s: %s.',[goog.typeOf(value),value],opt_message,Array.prototype.slice.call(arguments,2));}
return(value);};goog.asserts.assertArray=function(value,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&!goog.isArray(value)){goog.asserts.doAssertFailure_('Expected array but got %s: %s.',[goog.typeOf(value),value],opt_message,Array.prototype.slice.call(arguments,2));}
return(value);};goog.asserts.assertBoolean=function(value,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&!goog.isBoolean(value)){goog.asserts.doAssertFailure_('Expected boolean but got %s: %s.',[goog.typeOf(value),value],opt_message,Array.prototype.slice.call(arguments,2));}
return(value);};goog.asserts.assertElement=function(value,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&(!goog.isObject(value)||value.nodeType!=goog.dom.NodeType.ELEMENT)){goog.asserts.doAssertFailure_('Expected Element but got %s: %s.',[goog.typeOf(value),value],opt_message,Array.prototype.slice.call(arguments,2));}
return(value);};goog.asserts.assertInstanceof=function(value,type,opt_message,var_args){if(goog.asserts.ENABLE_ASSERTS&&!(value instanceof type)){goog.asserts.doAssertFailure_('instanceof check failed.',null,opt_message,Array.prototype.slice.call(arguments,3));}
return value;};goog.asserts.assertObjectPrototypeIsIntact=function(){for(var key in Object.prototype){goog.asserts.fail(key+' should not be enumerable in Object.prototype.');}};goog.provide('goog.i18n.pluralRules');goog.i18n.pluralRules.Keyword={ZERO:'zero',ONE:'one',TWO:'two',FEW:'few',MANY:'many',OTHER:'other'};goog.i18n.pluralRules.defaultSelect_=function(n,opt_precision){return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.decimals_=function(n){var str=n+'';var result=str.indexOf('.');return(result==-1)?0:str.length-result-1;};goog.i18n.pluralRules.get_vf_=function(n,opt_precision){var DEFAULT_DIGITS=3;if(undefined===opt_precision){var v=Math.min(goog.i18n.pluralRules.decimals_(n),DEFAULT_DIGITS);}else{var v=opt_precision;}
var base=Math.pow(10,v);var f=((n*base)|0)%base;return{v:v,f:f};};goog.i18n.pluralRules.get_wt_=function(v,f){if(f===0){return{w:0,t:0};}
while((f%10)===0){f/=10;v--;}
return{w:v,t:f};};goog.i18n.pluralRules.gaSelect_=function(n,opt_precision){if(n==1){return goog.i18n.pluralRules.Keyword.ONE;}
if(n==2){return goog.i18n.pluralRules.Keyword.TWO;}
if(n>=3&&n<=6){return goog.i18n.pluralRules.Keyword.FEW;}
if(n>=7&&n<=10){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.roSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(i==1&&vf.v==0){return goog.i18n.pluralRules.Keyword.ONE;}
if(vf.v!=0||n==0||n!=1&&n%100>=1&&n%100<=19){return goog.i18n.pluralRules.Keyword.FEW;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.filSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(vf.v==0&&(i==1||i==2||i==3)||vf.v==0&&i%10!=4&&i%10!=6&&i%10!=9||vf.v!=0&&vf.f%10!=4&&vf.f%10!=6&&vf.f%10!=9){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.frSelect_=function(n,opt_precision){var i=n|0;if(i==0||i==1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.enSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(i==1&&vf.v==0){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.mtSelect_=function(n,opt_precision){if(n==1){return goog.i18n.pluralRules.Keyword.ONE;}
if(n==0||n%100>=2&&n%100<=10){return goog.i18n.pluralRules.Keyword.FEW;}
if(n%100>=11&&n%100<=19){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.daSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);var wt=goog.i18n.pluralRules.get_wt_(vf.v,vf.f);if(n==1||wt.t!=0&&(i==0||i==1)){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.gvSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(vf.v==0&&i%10==1){return goog.i18n.pluralRules.Keyword.ONE;}
if(vf.v==0&&i%10==2){return goog.i18n.pluralRules.Keyword.TWO;}
if(vf.v==0&&(i%100==0||i%100==20||i%100==40||i%100==60||i%100==80)){return goog.i18n.pluralRules.Keyword.FEW;}
if(vf.v!=0){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.cySelect_=function(n,opt_precision){if(n==0){return goog.i18n.pluralRules.Keyword.ZERO;}
if(n==1){return goog.i18n.pluralRules.Keyword.ONE;}
if(n==2){return goog.i18n.pluralRules.Keyword.TWO;}
if(n==3){return goog.i18n.pluralRules.Keyword.FEW;}
if(n==6){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.brSelect_=function(n,opt_precision){if(n%10==1&&n%100!=11&&n%100!=71&&n%100!=91){return goog.i18n.pluralRules.Keyword.ONE;}
if(n%10==2&&n%100!=12&&n%100!=72&&n%100!=92){return goog.i18n.pluralRules.Keyword.TWO;}
if((n%10>=3&&n%10<=4||n%10==9)&&(n%100<10||n%100>19)&&(n%100<70||n%100>79)&&(n%100<90||n%100>99)){return goog.i18n.pluralRules.Keyword.FEW;}
if(n!=0&&n%1000000==0){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.esSelect_=function(n,opt_precision){if(n==1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.siSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if((n==0||n==1)||i==0&&vf.f==1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.slSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(vf.v==0&&i%100==1){return goog.i18n.pluralRules.Keyword.ONE;}
if(vf.v==0&&i%100==2){return goog.i18n.pluralRules.Keyword.TWO;}
if(vf.v==0&&i%100>=3&&i%100<=4||vf.v!=0){return goog.i18n.pluralRules.Keyword.FEW;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.tzmSelect_=function(n,opt_precision){if(n>=0&&n<=1||n>=11&&n<=99){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.srSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(vf.v==0&&i%10==1&&i%100!=11||vf.f%10==1&&vf.f%100!=11){return goog.i18n.pluralRules.Keyword.ONE;}
if(vf.v==0&&i%10>=2&&i%10<=4&&(i%100<12||i%100>14)||vf.f%10>=2&&vf.f%10<=4&&(vf.f%100<12||vf.f%100>14)){return goog.i18n.pluralRules.Keyword.FEW;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.hiSelect_=function(n,opt_precision){var i=n|0;if(i==0||n==1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.mkSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(vf.v==0&&i%10==1||vf.f%10==1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.arSelect_=function(n,opt_precision){if(n==0){return goog.i18n.pluralRules.Keyword.ZERO;}
if(n==1){return goog.i18n.pluralRules.Keyword.ONE;}
if(n==2){return goog.i18n.pluralRules.Keyword.TWO;}
if(n%100>=3&&n%100<=10){return goog.i18n.pluralRules.Keyword.FEW;}
if(n%100>=11&&n%100<=99){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.iuSelect_=function(n,opt_precision){if(n==1){return goog.i18n.pluralRules.Keyword.ONE;}
if(n==2){return goog.i18n.pluralRules.Keyword.TWO;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.csSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(i==1&&vf.v==0){return goog.i18n.pluralRules.Keyword.ONE;}
if(i>=2&&i<=4&&vf.v==0){return goog.i18n.pluralRules.Keyword.FEW;}
if(vf.v!=0){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.pt_PTSelect_=function(n,opt_precision){var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(n==1&&vf.v==0){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.beSelect_=function(n,opt_precision){if(n%10==1&&n%100!=11){return goog.i18n.pluralRules.Keyword.ONE;}
if(n%10>=2&&n%10<=4&&(n%100<12||n%100>14)){return goog.i18n.pluralRules.Keyword.FEW;}
if(n%10==0||n%10>=5&&n%10<=9||n%100>=11&&n%100<=14){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.akSelect_=function(n,opt_precision){if(n>=0&&n<=1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.ptSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);var wt=goog.i18n.pluralRules.get_wt_(vf.v,vf.f);if(i==1&&vf.v==0||i==0&&wt.t==1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.plSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(i==1&&vf.v==0){return goog.i18n.pluralRules.Keyword.ONE;}
if(vf.v==0&&i%10>=2&&i%10<=4&&(i%100<12||i%100>14)){return goog.i18n.pluralRules.Keyword.FEW;}
if(vf.v==0&&i!=1&&i%10>=0&&i%10<=1||vf.v==0&&i%10>=5&&i%10<=9||vf.v==0&&i%100>=12&&i%100<=14){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.ruSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(vf.v==0&&i%10==1&&i%100!=11){return goog.i18n.pluralRules.Keyword.ONE;}
if(vf.v==0&&i%10>=2&&i%10<=4&&(i%100<12||i%100>14)){return goog.i18n.pluralRules.Keyword.FEW;}
if(vf.v==0&&i%10==0||vf.v==0&&i%10>=5&&i%10<=9||vf.v==0&&i%100>=11&&i%100<=14){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.lagSelect_=function(n,opt_precision){var i=n|0;if(n==0){return goog.i18n.pluralRules.Keyword.ZERO;}
if((i==0||i==1)&&n!=0){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.shiSelect_=function(n,opt_precision){var i=n|0;if(i==0||n==1){return goog.i18n.pluralRules.Keyword.ONE;}
if(n>=2&&n<=10){return goog.i18n.pluralRules.Keyword.FEW;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.heSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(i==1&&vf.v==0){return goog.i18n.pluralRules.Keyword.ONE;}
if(i==2&&vf.v==0){return goog.i18n.pluralRules.Keyword.TWO;}
if(vf.v==0&&(n<0||n>10)&&n%10==0){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.isSelect_=function(n,opt_precision){var i=n|0;var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);var wt=goog.i18n.pluralRules.get_wt_(vf.v,vf.f);if(wt.t==0&&i%10==1&&i%100!=11||wt.t!=0){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.ltSelect_=function(n,opt_precision){var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(n%10==1&&(n%100<11||n%100>19)){return goog.i18n.pluralRules.Keyword.ONE;}
if(n%10>=2&&n%10<=9&&(n%100<11||n%100>19)){return goog.i18n.pluralRules.Keyword.FEW;}
if(vf.f!=0){return goog.i18n.pluralRules.Keyword.MANY;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.gdSelect_=function(n,opt_precision){if(n==1||n==11){return goog.i18n.pluralRules.Keyword.ONE;}
if(n==2||n==12){return goog.i18n.pluralRules.Keyword.TWO;}
if(n>=3&&n<=10||n>=13&&n<=19){return goog.i18n.pluralRules.Keyword.FEW;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.lvSelect_=function(n,opt_precision){var vf=goog.i18n.pluralRules.get_vf_(n,opt_precision);if(n%10==0||n%100>=11&&n%100<=19||vf.v==2&&vf.f%100>=11&&vf.f%100<=19){return goog.i18n.pluralRules.Keyword.ZERO;}
if(n%10==1&&n%100!=11||vf.v==2&&vf.f%10==1&&vf.f%100!=11||vf.v!=2&&vf.f%10==1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.kshSelect_=function(n,opt_precision){if(n==0){return goog.i18n.pluralRules.Keyword.ZERO;}
if(n==1){return goog.i18n.pluralRules.Keyword.ONE;}
return goog.i18n.pluralRules.Keyword.OTHER;};goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;if(goog.LOCALE=='af'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='am'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.hiSelect_;}
if(goog.LOCALE=='ar'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.arSelect_;}
if(goog.LOCALE=='az'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='bg'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='bn'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.hiSelect_;}
if(goog.LOCALE=='br'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.brSelect_;}
if(goog.LOCALE=='ca'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='chr'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='cs'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.csSelect_;}
if(goog.LOCALE=='cy'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.cySelect_;}
if(goog.LOCALE=='da'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.daSelect_;}
if(goog.LOCALE=='de'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='de_AT'||goog.LOCALE=='de-AT'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='de_CH'||goog.LOCALE=='de-CH'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='el'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='en'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='en_AU'||goog.LOCALE=='en-AU'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='en_GB'||goog.LOCALE=='en-GB'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='en_IE'||goog.LOCALE=='en-IE'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='en_IN'||goog.LOCALE=='en-IN'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='en_ISO'||goog.LOCALE=='en-ISO'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='en_SG'||goog.LOCALE=='en-SG'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='en_US'||goog.LOCALE=='en-US'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='en_ZA'||goog.LOCALE=='en-ZA'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='es'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='es_419'||goog.LOCALE=='es-419'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='es_ES'||goog.LOCALE=='es-ES'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='et'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='eu'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='fa'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.hiSelect_;}
if(goog.LOCALE=='fi'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='fil'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.filSelect_;}
if(goog.LOCALE=='fr'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.frSelect_;}
if(goog.LOCALE=='fr_CA'||goog.LOCALE=='fr-CA'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.frSelect_;}
if(goog.LOCALE=='gl'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='gsw'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='gu'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.hiSelect_;}
if(goog.LOCALE=='haw'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='he'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.heSelect_;}
if(goog.LOCALE=='hi'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.hiSelect_;}
if(goog.LOCALE=='hr'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.srSelect_;}
if(goog.LOCALE=='hu'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='hy'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.frSelect_;}
if(goog.LOCALE=='id'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='in'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='is'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.isSelect_;}
if(goog.LOCALE=='it'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='iw'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.heSelect_;}
if(goog.LOCALE=='ja'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='ka'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='kk'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='km'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='kn'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.hiSelect_;}
if(goog.LOCALE=='ko'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='ky'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='ln'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.akSelect_;}
if(goog.LOCALE=='lo'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='lt'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.ltSelect_;}
if(goog.LOCALE=='lv'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.lvSelect_;}
if(goog.LOCALE=='mk'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.mkSelect_;}
if(goog.LOCALE=='ml'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='mn'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='mo'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.roSelect_;}
if(goog.LOCALE=='mr'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.hiSelect_;}
if(goog.LOCALE=='ms'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='mt'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.mtSelect_;}
if(goog.LOCALE=='my'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='nb'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='ne'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='nl'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='no'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='no_NO'||goog.LOCALE=='no-NO'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='or'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='pa'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.akSelect_;}
if(goog.LOCALE=='pl'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.plSelect_;}
if(goog.LOCALE=='pt'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.ptSelect_;}
if(goog.LOCALE=='pt_BR'||goog.LOCALE=='pt-BR'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.ptSelect_;}
if(goog.LOCALE=='pt_PT'||goog.LOCALE=='pt-PT'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.pt_PTSelect_;}
if(goog.LOCALE=='ro'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.roSelect_;}
if(goog.LOCALE=='ru'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.ruSelect_;}
if(goog.LOCALE=='sh'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.srSelect_;}
if(goog.LOCALE=='si'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.siSelect_;}
if(goog.LOCALE=='sk'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.csSelect_;}
if(goog.LOCALE=='sl'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.slSelect_;}
if(goog.LOCALE=='sq'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='sr'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.srSelect_;}
if(goog.LOCALE=='sv'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='sw'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='ta'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='te'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='th'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='tl'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.filSelect_;}
if(goog.LOCALE=='tr'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='uk'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.ruSelect_;}
if(goog.LOCALE=='ur'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.enSelect_;}
if(goog.LOCALE=='uz'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.esSelect_;}
if(goog.LOCALE=='vi'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='zh'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='zh_CN'||goog.LOCALE=='zh-CN'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='zh_HK'||goog.LOCALE=='zh-HK'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='zh_TW'||goog.LOCALE=='zh-TW'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.defaultSelect_;}
if(goog.LOCALE=='zu'){goog.i18n.pluralRules.select=goog.i18n.pluralRules.hiSelect_;}
goog.provide('goog.i18n.ordinalRules');goog.i18n.ordinalRules.Keyword={ZERO:'zero',ONE:'one',TWO:'two',FEW:'few',MANY:'many',OTHER:'other'};goog.i18n.ordinalRules.defaultSelect_=function(n,opt_precision){return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.decimals_=function(n){var str=n+'';var result=str.indexOf('.');return(result==-1)?0:str.length-result-1;};goog.i18n.ordinalRules.get_vf_=function(n,opt_precision){var DEFAULT_DIGITS=3;if(undefined===opt_precision){var v=Math.min(goog.i18n.ordinalRules.decimals_(n),DEFAULT_DIGITS);}else{var v=opt_precision;}
var base=Math.pow(10,v);var f=((n*base)|0)%base;return{v:v,f:f};};goog.i18n.ordinalRules.get_wt_=function(v,f){if(f===0){return{w:0,t:0};}
while((f%10)===0){f/=10;v--;}
return{w:v,t:f};};goog.i18n.ordinalRules.enSelect_=function(n,opt_precision){if(n%10==1&&n%100!=11){return goog.i18n.ordinalRules.Keyword.ONE;}
if(n%10==2&&n%100!=12){return goog.i18n.ordinalRules.Keyword.TWO;}
if(n%10==3&&n%100!=13){return goog.i18n.ordinalRules.Keyword.FEW;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.svSelect_=function(n,opt_precision){if((n%10==1||n%10==2)&&n%100!=11&&n%100!=12){return goog.i18n.ordinalRules.Keyword.ONE;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.huSelect_=function(n,opt_precision){if(n==1||n==5){return goog.i18n.ordinalRules.Keyword.ONE;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.kkSelect_=function(n,opt_precision){if(n%10==6||n%10==9||n%10==0&&n!=0){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.mrSelect_=function(n,opt_precision){if(n==1){return goog.i18n.ordinalRules.Keyword.ONE;}
if(n==2||n==3){return goog.i18n.ordinalRules.Keyword.TWO;}
if(n==4){return goog.i18n.ordinalRules.Keyword.FEW;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.sqSelect_=function(n,opt_precision){if(n==1){return goog.i18n.ordinalRules.Keyword.ONE;}
if(n%10==4&&n%100!=14){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.bnSelect_=function(n,opt_precision){if(n==1||n==5||n==7||n==8||n==9||n==10){return goog.i18n.ordinalRules.Keyword.ONE;}
if(n==2||n==3){return goog.i18n.ordinalRules.Keyword.TWO;}
if(n==4){return goog.i18n.ordinalRules.Keyword.FEW;}
if(n==6){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.guSelect_=function(n,opt_precision){if(n==1){return goog.i18n.ordinalRules.Keyword.ONE;}
if(n==2||n==3){return goog.i18n.ordinalRules.Keyword.TWO;}
if(n==4){return goog.i18n.ordinalRules.Keyword.FEW;}
if(n==6){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.kaSelect_=function(n,opt_precision){var i=n|0;if(i==1){return goog.i18n.ordinalRules.Keyword.ONE;}
if(i==0||(i%100>=2&&i%100<=20||i%100==40||i%100==60||i%100==80)){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.frSelect_=function(n,opt_precision){if(n==1){return goog.i18n.ordinalRules.Keyword.ONE;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.neSelect_=function(n,opt_precision){if(n>=1&&n<=4){return goog.i18n.ordinalRules.Keyword.ONE;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.cySelect_=function(n,opt_precision){if(n==0||n==7||n==8||n==9){return goog.i18n.ordinalRules.Keyword.ZERO;}
if(n==1){return goog.i18n.ordinalRules.Keyword.ONE;}
if(n==2){return goog.i18n.ordinalRules.Keyword.TWO;}
if(n==3||n==4){return goog.i18n.ordinalRules.Keyword.FEW;}
if(n==5||n==6){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.azSelect_=function(n,opt_precision){var i=n|0;if((i%10==1||i%10==2||i%10==5||i%10==7||i%10==8)||(i%100==20||i%100==50||i%100==70||i%100==80)){return goog.i18n.ordinalRules.Keyword.ONE;}
if((i%10==3||i%10==4)||(i%1000==100||i%1000==200||i%1000==300||i%1000==400||i%1000==500||i%1000==600||i%1000==700||i%1000==800||i%1000==900)){return goog.i18n.ordinalRules.Keyword.FEW;}
if(i==0||i%10==6||(i%100==40||i%100==60||i%100==90)){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.caSelect_=function(n,opt_precision){if(n==1||n==3){return goog.i18n.ordinalRules.Keyword.ONE;}
if(n==2){return goog.i18n.ordinalRules.Keyword.TWO;}
if(n==4){return goog.i18n.ordinalRules.Keyword.FEW;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.itSelect_=function(n,opt_precision){if(n==11||n==8||n==80||n==800){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.mkSelect_=function(n,opt_precision){var i=n|0;if(i%10==1&&i%100!=11){return goog.i18n.ordinalRules.Keyword.ONE;}
if(i%10==2&&i%100!=12){return goog.i18n.ordinalRules.Keyword.TWO;}
if((i%10==7||i%10==8)&&i%100!=17&&i%100!=18){return goog.i18n.ordinalRules.Keyword.MANY;}
return goog.i18n.ordinalRules.Keyword.OTHER;};goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;if(goog.LOCALE=='af'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='am'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ar'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='az'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.azSelect_;}
if(goog.LOCALE=='bg'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='bn'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.bnSelect_;}
if(goog.LOCALE=='br'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ca'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.caSelect_;}
if(goog.LOCALE=='chr'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='cs'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='cy'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.cySelect_;}
if(goog.LOCALE=='da'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='de'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='de_AT'||goog.LOCALE=='de-AT'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='de_CH'||goog.LOCALE=='de-CH'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='el'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='en'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='en_AU'||goog.LOCALE=='en-AU'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='en_GB'||goog.LOCALE=='en-GB'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='en_IE'||goog.LOCALE=='en-IE'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='en_IN'||goog.LOCALE=='en-IN'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='en_ISO'||goog.LOCALE=='en-ISO'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='en_SG'||goog.LOCALE=='en-SG'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='en_US'||goog.LOCALE=='en-US'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='en_ZA'||goog.LOCALE=='en-ZA'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.enSelect_;}
if(goog.LOCALE=='es'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='es_419'||goog.LOCALE=='es-419'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='es_ES'||goog.LOCALE=='es-ES'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='et'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='eu'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='fa'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='fi'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='fil'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='fr'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='fr_CA'||goog.LOCALE=='fr-CA'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='gl'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='gsw'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='gu'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.guSelect_;}
if(goog.LOCALE=='haw'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='he'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='hi'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.guSelect_;}
if(goog.LOCALE=='hr'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='hu'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.huSelect_;}
if(goog.LOCALE=='hy'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='id'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='in'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='is'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='it'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.itSelect_;}
if(goog.LOCALE=='iw'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ja'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ka'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.kaSelect_;}
if(goog.LOCALE=='kk'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.kkSelect_;}
if(goog.LOCALE=='km'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='kn'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ko'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ky'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ln'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='lo'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='lt'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='lv'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='mk'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.mkSelect_;}
if(goog.LOCALE=='ml'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='mn'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='mo'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='mr'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.mrSelect_;}
if(goog.LOCALE=='ms'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='mt'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='my'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='nb'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ne'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.neSelect_;}
if(goog.LOCALE=='nl'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='no'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='no_NO'||goog.LOCALE=='no-NO'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='or'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='pa'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='pl'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='pt'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='pt_BR'||goog.LOCALE=='pt-BR'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='pt_PT'||goog.LOCALE=='pt-PT'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ro'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='ru'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='sh'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='si'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='sk'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='sl'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='sq'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.sqSelect_;}
if(goog.LOCALE=='sr'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='sv'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.svSelect_;}
if(goog.LOCALE=='sw'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ta'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='te'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='th'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='tl'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='tr'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='uk'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='ur'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='uz'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='vi'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.frSelect_;}
if(goog.LOCALE=='zh'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='zh_CN'||goog.LOCALE=='zh-CN'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='zh_HK'||goog.LOCALE=='zh-HK'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='zh_TW'||goog.LOCALE=='zh-TW'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
if(goog.LOCALE=='zu'){goog.i18n.ordinalRules.select=goog.i18n.ordinalRules.defaultSelect_;}
goog.provide('goog.i18n.MessageFormat');goog.require('goog.asserts');goog.require('goog.i18n.ordinalRules');goog.require('goog.i18n.pluralRules');goog.i18n.MessageFormat=function(pattern){this.literals_=[];this.parsedPattern_=[];this.parsePattern_(pattern);};goog.i18n.MessageFormat.LITERAL_PLACEHOLDER_='\uFDDF_';goog.i18n.MessageFormat.Element_={STRING:0,BLOCK:1};goog.i18n.MessageFormat.BlockType_={PLURAL:0,ORDINAL:1,SELECT:2,SIMPLE:3,STRING:4,UNKNOWN:5};goog.i18n.MessageFormat.OTHER_='other';goog.i18n.MessageFormat.REGEX_LITERAL_=new RegExp("'([{}#].*?)'",'g');goog.i18n.MessageFormat.REGEX_DOUBLE_APOSTROPHE_=new RegExp("''",'g');goog.i18n.MessageFormat.prototype.format=function(namedParameters){return this.format_(namedParameters,false);};goog.i18n.MessageFormat.prototype.formatIgnoringPound=function(namedParameters){return this.format_(namedParameters,true);};goog.i18n.MessageFormat.prototype.format_=function(namedParameters,ignorePound){if(this.parsedPattern_.length==0){return'';}
var result=[];this.formatBlock_(this.parsedPattern_,namedParameters,ignorePound,result);var message=result.join('');if(!ignorePound){goog.asserts.assert(message.search('#')==-1,'Not all # were replaced.');}
while(this.literals_.length>0){message=message.replace(this.buildPlaceholder_(this.literals_),this.literals_.pop());}
return message;};goog.i18n.MessageFormat.prototype.formatBlock_=function(parsedPattern,namedParameters,ignorePound,result){for(var i=0;i<parsedPattern.length;i++){switch(parsedPattern[i].type){case goog.i18n.MessageFormat.BlockType_.STRING:result.push(parsedPattern[i].value);break;case goog.i18n.MessageFormat.BlockType_.SIMPLE:var pattern=parsedPattern[i].value;this.formatSimplePlaceholder_(pattern,namedParameters,result);break;case goog.i18n.MessageFormat.BlockType_.SELECT:var pattern=parsedPattern[i].value;this.formatSelectBlock_(pattern,namedParameters,ignorePound,result);break;case goog.i18n.MessageFormat.BlockType_.PLURAL:var pattern=parsedPattern[i].value;this.formatPluralOrdinalBlock_(pattern,namedParameters,goog.i18n.pluralRules.select,ignorePound,result);break;case goog.i18n.MessageFormat.BlockType_.ORDINAL:var pattern=parsedPattern[i].value;this.formatPluralOrdinalBlock_(pattern,namedParameters,goog.i18n.ordinalRules.select,ignorePound,result);break;default:goog.asserts.fail('Unrecognized block type.');}}};goog.i18n.MessageFormat.prototype.formatSimplePlaceholder_=function(parsedPattern,namedParameters,result){var value=namedParameters[parsedPattern];if(!goog.isDef(value)){result.push('Undefined parameter - '+parsedPattern);return;}
this.literals_.push(value);result.push(this.buildPlaceholder_(this.literals_));};goog.i18n.MessageFormat.prototype.formatSelectBlock_=function(parsedPattern,namedParameters,ignorePound,result){var argumentIndex=parsedPattern.argumentIndex;if(!goog.isDef(namedParameters[argumentIndex])){result.push('Undefined parameter - '+argumentIndex);return;}
var option=parsedPattern[namedParameters[argumentIndex]];if(!goog.isDef(option)){option=parsedPattern[goog.i18n.MessageFormat.OTHER_];goog.asserts.assertArray(option,'Invalid option or missing other option for select block.');}
this.formatBlock_(option,namedParameters,ignorePound,result);};goog.i18n.MessageFormat.prototype.formatPluralOrdinalBlock_=function(parsedPattern,namedParameters,pluralSelector,ignorePound,result){var argumentIndex=parsedPattern.argumentIndex;var argumentOffset=parsedPattern.argumentOffset;var pluralValue=+namedParameters[argumentIndex];if(isNaN(pluralValue)){result.push('Undefined or invalid parameter - '+argumentIndex);return;}
var diff=pluralValue-argumentOffset;var option=parsedPattern[namedParameters[argumentIndex]];if(!goog.isDef(option)){goog.asserts.assert(diff>=0,'Argument index smaller than offset.');var item;item=pluralSelector(diff);goog.asserts.assertString(item,'Invalid plural key.');option=parsedPattern[item];if(!goog.isDef(option)){option=parsedPattern[goog.i18n.MessageFormat.OTHER_];}
goog.asserts.assertArray(option,'Invalid option or missing other option for plural block.');}
var pluralResult=[];this.formatBlock_(option,namedParameters,ignorePound,pluralResult);var plural=pluralResult.join('');goog.asserts.assertString(plural,'Empty block in plural.');if(ignorePound){result.push(plural);}else{var localeAwareDiff=diff.toLocaleString();result.push(plural.replace(/#/g,localeAwareDiff));}};goog.i18n.MessageFormat.prototype.parsePattern_=function(pattern){if(pattern){pattern=this.insertPlaceholders_(pattern);this.parsedPattern_=this.parseBlock_(pattern);}};goog.i18n.MessageFormat.prototype.insertPlaceholders_=function(pattern){var literals=this.literals_;var buildPlaceholder=goog.bind(this.buildPlaceholder_,this);pattern=pattern.replace(goog.i18n.MessageFormat.REGEX_DOUBLE_APOSTROPHE_,function(){literals.push("'");return buildPlaceholder(literals);});pattern=pattern.replace(goog.i18n.MessageFormat.REGEX_LITERAL_,function(match,text){literals.push(text);return buildPlaceholder(literals);});return pattern;};goog.i18n.MessageFormat.prototype.extractParts_=function(pattern){var prevPos=0;var inBlock=false;var braceStack=[];var results=[];var braces=/[{}]/g;braces.lastIndex=0;var match;while(match=braces.exec(pattern)){var pos=match.index;if(match[0]=='}'){var brace=braceStack.pop();goog.asserts.assert(goog.isDef(brace)&&brace=='{','No matching { for }.');if(braceStack.length==0){var part={};part.type=goog.i18n.MessageFormat.Element_.BLOCK;part.value=pattern.substring(prevPos,pos);results.push(part);prevPos=pos+1;inBlock=false;}}else{if(braceStack.length==0){inBlock=true;var substring=pattern.substring(prevPos,pos);if(substring!=''){results.push({type:goog.i18n.MessageFormat.Element_.STRING,value:substring});}
prevPos=pos+1;}
braceStack.push('{');}}
goog.asserts.assert(braceStack.length==0,'There are mismatched { or } in the pattern.');var substring=pattern.substring(prevPos);if(substring!=''){results.push({type:goog.i18n.MessageFormat.Element_.STRING,value:substring});}
return results;};goog.i18n.MessageFormat.PLURAL_BLOCK_RE_=/^\s*(\w+)\s*,\s*plural\s*,(?:\s*offset:(\d+))?/;goog.i18n.MessageFormat.ORDINAL_BLOCK_RE_=/^\s*(\w+)\s*,\s*selectordinal\s*,/;goog.i18n.MessageFormat.SELECT_BLOCK_RE_=/^\s*(\w+)\s*,\s*select\s*,/;goog.i18n.MessageFormat.prototype.parseBlockType_=function(pattern){if(goog.i18n.MessageFormat.PLURAL_BLOCK_RE_.test(pattern)){return goog.i18n.MessageFormat.BlockType_.PLURAL;}
if(goog.i18n.MessageFormat.ORDINAL_BLOCK_RE_.test(pattern)){return goog.i18n.MessageFormat.BlockType_.ORDINAL;}
if(goog.i18n.MessageFormat.SELECT_BLOCK_RE_.test(pattern)){return goog.i18n.MessageFormat.BlockType_.SELECT;}
if(/^\s*\w+\s*/.test(pattern)){return goog.i18n.MessageFormat.BlockType_.SIMPLE;}
return goog.i18n.MessageFormat.BlockType_.UNKNOWN;};goog.i18n.MessageFormat.prototype.parseBlock_=function(pattern){var result=[];var parts=this.extractParts_(pattern);for(var i=0;i<parts.length;i++){var block={};if(goog.i18n.MessageFormat.Element_.STRING==parts[i].type){block.type=goog.i18n.MessageFormat.BlockType_.STRING;block.value=parts[i].value;}else if(goog.i18n.MessageFormat.Element_.BLOCK==parts[i].type){var blockType=this.parseBlockType_(parts[i].value);switch(blockType){case goog.i18n.MessageFormat.BlockType_.SELECT:block.type=goog.i18n.MessageFormat.BlockType_.SELECT;block.value=this.parseSelectBlock_(parts[i].value);break;case goog.i18n.MessageFormat.BlockType_.PLURAL:block.type=goog.i18n.MessageFormat.BlockType_.PLURAL;block.value=this.parsePluralBlock_(parts[i].value);break;case goog.i18n.MessageFormat.BlockType_.ORDINAL:block.type=goog.i18n.MessageFormat.BlockType_.ORDINAL;block.value=this.parseOrdinalBlock_(parts[i].value);break;case goog.i18n.MessageFormat.BlockType_.SIMPLE:block.type=goog.i18n.MessageFormat.BlockType_.SIMPLE;block.value=parts[i].value;break;default:goog.asserts.fail('Unknown block type.');}}else{goog.asserts.fail('Unknown part of the pattern.');}
result.push(block);}
return result;};goog.i18n.MessageFormat.prototype.parseSelectBlock_=function(pattern){var argumentIndex='';var replaceRegex=goog.i18n.MessageFormat.SELECT_BLOCK_RE_;pattern=pattern.replace(replaceRegex,function(string,name){argumentIndex=name;return'';});var result={};result.argumentIndex=argumentIndex;var parts=this.extractParts_(pattern);var pos=0;while(pos<parts.length){var key=parts[pos].value;goog.asserts.assertString(key,'Missing select key element.');pos++;goog.asserts.assert(pos<parts.length,'Missing or invalid select value element.');if(goog.i18n.MessageFormat.Element_.BLOCK==parts[pos].type){var value=this.parseBlock_(parts[pos].value);}else{goog.asserts.fail('Expected block type.');}
result[key.replace(/\s/g,'')]=value;pos++;}
goog.asserts.assertArray(result[goog.i18n.MessageFormat.OTHER_],'Missing other key in select statement.');return result;};goog.i18n.MessageFormat.prototype.parsePluralBlock_=function(pattern){var argumentIndex='';var argumentOffset=0;var replaceRegex=goog.i18n.MessageFormat.PLURAL_BLOCK_RE_;pattern=pattern.replace(replaceRegex,function(string,name,offset){argumentIndex=name;if(offset){argumentOffset=parseInt(offset,10);}
return'';});var result={};result.argumentIndex=argumentIndex;result.argumentOffset=argumentOffset;var parts=this.extractParts_(pattern);var pos=0;while(pos<parts.length){var key=parts[pos].value;goog.asserts.assertString(key,'Missing plural key element.');pos++;goog.asserts.assert(pos<parts.length,'Missing or invalid plural value element.');if(goog.i18n.MessageFormat.Element_.BLOCK==parts[pos].type){var value=this.parseBlock_(parts[pos].value);}else{goog.asserts.fail('Expected block type.');}
result[key.replace(/\s*(?:=)?(\w+)\s*/,'$1')]=value;pos++;}
goog.asserts.assertArray(result[goog.i18n.MessageFormat.OTHER_],'Missing other key in plural statement.');return result;};goog.i18n.MessageFormat.prototype.parseOrdinalBlock_=function(pattern){var argumentIndex='';var replaceRegex=goog.i18n.MessageFormat.ORDINAL_BLOCK_RE_;pattern=pattern.replace(replaceRegex,function(string,name){argumentIndex=name;return'';});var result={};result.argumentIndex=argumentIndex;result.argumentOffset=0;var parts=this.extractParts_(pattern);var pos=0;while(pos<parts.length){var key=parts[pos].value;goog.asserts.assertString(key,'Missing ordinal key element.');pos++;goog.asserts.assert(pos<parts.length,'Missing or invalid ordinal value element.');if(goog.i18n.MessageFormat.Element_.BLOCK==parts[pos].type){var value=this.parseBlock_(parts[pos].value);}else{goog.asserts.fail('Expected block type.');}
result[key.replace(/\s*(?:=)?(\w+)\s*/,'$1')]=value;pos++;}
goog.asserts.assertArray(result[goog.i18n.MessageFormat.OTHER_],'Missing other key in selectordinal statement.');return result;};goog.i18n.MessageFormat.prototype.buildPlaceholder_=function(literals){goog.asserts.assert(literals.length>0,'Literal array is empty.');var index=(literals.length-1).toString(10);return goog.i18n.MessageFormat.LITERAL_PLACEHOLDER_+index+'_';};goog.provide('cvox.AbstractTts');goog.require('Msgs');goog.require('cvox.TtsInterface');goog.require('goog.i18n.MessageFormat');cvox.AbstractTts=function(){this.ttsProperties=new Object();this.propertyDefault={'rate':0.5,'pitch':0.5,'volume':0.5};this.propertyMin={'rate':0.0,'pitch':0.0,'volume':0.0};this.propertyMax={'rate':1.0,'pitch':1.0,'volume':1.0};this.propertyStep={'rate':0.1,'pitch':0.1,'volume':0.1};if(cvox.AbstractTts.pronunciationDictionaryRegexp_==undefined){var words=[];for(var word in cvox.AbstractTts.PRONUNCIATION_DICTIONARY){words.push(word);}
var expr='\\b('+words.join('|')+')\\b';cvox.AbstractTts.pronunciationDictionaryRegexp_=new RegExp(expr,'ig');}
if(cvox.AbstractTts.substitutionDictionaryRegexp_==undefined){var symbols=[];for(var symbol in cvox.AbstractTts.SUBSTITUTION_DICTIONARY){symbols.push(symbol);}
var expr='('+symbols.join('|')+')';cvox.AbstractTts.substitutionDictionaryRegexp_=new RegExp(expr,'ig');}};cvox.AbstractTts.prototype.ttsProperties;cvox.AbstractTts.prototype.speak=function(textString,queueMode,properties){return this;};cvox.AbstractTts.prototype.isSpeaking=function(){return false;};cvox.AbstractTts.prototype.stop=function(){};cvox.AbstractTts.prototype.addCapturingEventListener=function(listener){};cvox.AbstractTts.prototype.increaseOrDecreaseProperty=function(propertyName,increase){var min=this.propertyMin[propertyName];var max=this.propertyMax[propertyName];var step=this.propertyStep[propertyName];var current=this.ttsProperties[propertyName];current=increase?current+step:current-step;this.ttsProperties[propertyName]=Math.max(Math.min(current,max),min);};cvox.AbstractTts.prototype.propertyToPercentage=function(property){return(this.ttsProperties[property]-this.propertyMin[property])/Math.abs(this.propertyMax[property]-this.propertyMin[property]);};cvox.AbstractTts.prototype.mergeProperties=function(properties){var mergedProperties=new Object();var p;if(this.ttsProperties){for(p in this.ttsProperties){mergedProperties[p]=this.ttsProperties[p];}}
if(properties){var tts=cvox.AbstractTts;if(typeof(properties[tts.VOLUME])=='number'){mergedProperties[tts.VOLUME]=properties[tts.VOLUME];}
if(typeof(properties[tts.PITCH])=='number'){mergedProperties[tts.PITCH]=properties[tts.PITCH];}
if(typeof(properties[tts.RATE])=='number'){mergedProperties[tts.RATE]=properties[tts.RATE];}
if(typeof(properties[tts.LANG])=='string'){mergedProperties[tts.LANG]=properties[tts.LANG];}
var context=this;var mergeRelativeProperty=function(abs,rel){if(typeof(properties[rel])=='number'&&typeof(mergedProperties[abs])=='number'){mergedProperties[abs]+=properties[rel];var min=context.propertyMin[abs];var max=context.propertyMax[abs];if(mergedProperties[abs]>max){mergedProperties[abs]=max;}else if(mergedProperties[abs]<min){mergedProperties[abs]=min;}}};mergeRelativeProperty(tts.VOLUME,tts.RELATIVE_VOLUME);mergeRelativeProperty(tts.PITCH,tts.RELATIVE_PITCH);mergeRelativeProperty(tts.RATE,tts.RELATIVE_RATE);}
for(p in properties){if(!mergedProperties.hasOwnProperty(p)){mergedProperties[p]=properties[p];}}
return mergedProperties;};cvox.AbstractTts.prototype.preprocess=function(text,properties){if(text.length==1&&text>='A'&&text<='Z'){for(var prop in cvox.AbstractTts.PERSONALITY_CAPITAL)
properties[prop]=cvox.AbstractTts.PERSONALITY_CAPITAL[prop];}
text=text.replace(cvox.AbstractTts.substitutionDictionaryRegexp_,function(symbol){return' '+cvox.AbstractTts.SUBSTITUTION_DICTIONARY[symbol]+' ';});if(text.length==1){return cvox.AbstractTts.CHARACTER_DICTIONARY[text]?(new goog.i18n.MessageFormat(Msgs.getMsg(cvox.AbstractTts.CHARACTER_DICTIONARY[text]))).format({'COUNT':1}):text.toUpperCase();}
text=text.replace(cvox.AbstractTts.pronunciationDictionaryRegexp_,function(word){return cvox.AbstractTts.PRONUNCIATION_DICTIONARY[word.toLowerCase()];});text=text.replace(cvox.AbstractTts.repetitionRegexp_,cvox.AbstractTts.repetitionReplace_);return text;};cvox.AbstractTts.RATE='rate';cvox.AbstractTts.PITCH='pitch';cvox.AbstractTts.VOLUME='volume';cvox.AbstractTts.LANG='lang';cvox.AbstractTts.RELATIVE_RATE='relativeRate';cvox.AbstractTts.RELATIVE_PITCH='relativePitch';cvox.AbstractTts.RELATIVE_VOLUME='relativeVolume';cvox.AbstractTts.COLOR='color';cvox.AbstractTts.FONT_WEIGHT='fontWeight';cvox.AbstractTts.PUNCTUATION_ECHO='punctuationEcho';cvox.AbstractTts.PAUSE='pause';cvox.AbstractTts.PERSONALITY_ANNOTATION={'relativePitch':-0.25,'color':'yellow','punctuationEcho':'none'};cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT={'punctuationEcho':'none'};cvox.AbstractTts.PERSONALITY_SYSTEM_ALERT={'punctuationEcho':'none','doNotInterrupt':true};cvox.AbstractTts.PERSONALITY_ASIDE={'relativePitch':-0.1,'color':'#669'};cvox.AbstractTts.PERSONALITY_CAPITAL={'relativePitch':0.6};cvox.AbstractTts.PERSONALITY_DELETED={'punctuationEcho':'none','relativePitch':-0.6};cvox.AbstractTts.PERSONALITY_QUOTE={'relativePitch':0.1,'color':'#b6b','fontWeight':'bold'};cvox.AbstractTts.PERSONALITY_STRONG={'relativePitch':0.1,'color':'#b66','fontWeight':'bold'};cvox.AbstractTts.PERSONALITY_EMPHASIS={'relativeVolume':0.1,'relativeRate':-0.1,'color':'#6bb','fontWeight':'bold'};cvox.AbstractTts.DEBUG=true;cvox.AbstractTts.CHARACTER_DICTIONARY={' ':'space','`':'backtick','~':'tilde','!':'exclamation','@':'at','#':'pound','$':'dollar','%':'percent','^':'caret','&':'ampersand','*':'asterisk','(':'open_paren',')':'close_paren','-':'dash','_':'underscore','=':'equals','+':'plus','[':'left_bracket',']':'right_bracket','{':'left_brace','}':'right_brace','|':'pipe',';':'semicolon',':':'colon',',':'comma','.':'dot','<':'less_than','>':'greater_than','/':'slash','?':'question_mark','"':'quote','\'':'apostrophe','\t':'tab','\r':'return','\n':'new_line','\\':'backslash','\u2022':'bullet'};cvox.AbstractTts.PRONUNCIATION_DICTIONARY={'admob':'ad-mob','adsense':'ad-sense','adwords':'ad-words','angularjs':'angular j s','bcc':'B C C','cc':'C C','chromevox':'chrome vox','cr48':'C R 48','ctrl':'control','doubleclick':'double-click','gmail':'gee mail','gtalk':'gee talk','http':'H T T P','https':'H T T P S','igoogle':'eye google','pagerank':'page-rank','username':'user-name','www':'W W W','youtube':'you tube'};cvox.AbstractTts.pronunciationDictionaryRegexp_;cvox.AbstractTts.SUBSTITUTION_DICTIONARY={'://':'colon slash slash','\u00bc':'one fourth','\u00bd':'one half','\u2190':'left arrow','\u2191':'up arrow','\u2192':'right arrow','\u2193':'down arrow','\u21d0':'left double arrow','\u21d1':'up double arrow','\u21d2':'right double  arrow','\u21d3':'down double arrow','\u21e6':'left arrow','\u21e7':'up arrow','\u21e8':'right arrow','\u21e9':'down arrow','\u2303':'control','\u2318':'command','\u2325':'option','\u25b2':'up triangle','\u25b3':'up triangle','\u25b4':'up triangle','\u25b5':'up triangle','\u25b6':'right triangle','\u25b7':'right triangle','\u25b8':'right triangle','\u25b9':'right triangle','\u25ba':'right pointer','\u25bb':'right pointer','\u25bc':'down triangle','\u25bd':'down triangle','\u25be':'down triangle','\u25bf':'down triangle','\u25c0':'left triangle','\u25c1':'left triangle','\u25c2':'left triangle','\u25c3':'left triangle','\u25c4':'left pointer','\u25c5':'left pointer','\uf8ff':'apple'};cvox.AbstractTts.substitutionDictionaryRegexp_;cvox.AbstractTts.repetitionRegexp_=/([-\/\\|!@#$%^&*\(\)=_+\[\]\{\}.?;'":<>\u2022])\1{1,}/g;cvox.AbstractTts.repetitionReplace_=function(match){var count=match.length;return' '+(new goog.i18n.MessageFormat(Msgs.getMsg(cvox.AbstractTts.CHARACTER_DICTIONARY[match[0]]))).format({'COUNT':count})+' ';};cvox.AbstractTts.prototype.getDefaultProperty=function(property){return this.propertyDefault[property];};goog.provide('cvox.ChromeVox');goog.addDependency('../host/interface/abstract_host.js',['cvox.AbstractHost'],[]);goog.addDependency('../host/interface/tts_interface.js',['cvox.TtsInterface'],[]);goog.addDependency('../host/interface/braille_interface.js',['cvox.BrailleInterface'],[]);goog.addDependency('../host/interface/mathjax_interface.js',['cvox.MathJaxInterface'],[]);goog.addDependency('../chromevox/messages/msgs.js',['Msgs'],[]);goog.addDependency('../host/interface/abstract_earcons.js',['cvox.AbstractEarcons'],[]);goog.addDependency('../chromevox/common/key_sequence.js',['cvox.KeySequence'],[]);goog.addDependency('../chromevox/injected/navigation_manager.js',['cvox.NavigationManager'],[]);goog.addDependency('../chromevox/injected/serializer.js',['cvox.Serializer'],[]);cvox.VERBOSITY_VERBOSE=0;cvox.VERBOSITY_BRIEF=1;cvox.ChromeVox=function(){};cvox.ChromeVox.host=null;cvox.ChromeVox.tts;cvox.ChromeVox.braille;cvox.ChromeVox.mathJax;cvox.ChromeVox.isActive=true;cvox.ChromeVox.version=null;cvox.ChromeVox.earcons=null;cvox.ChromeVox.navigationManager=null;cvox.ChromeVox.serializer=null;cvox.ChromeVox.isStickyPrefOn=false;cvox.ChromeVox.stickyOverride=null;cvox.ChromeVox.keyPrefixOn=false;cvox.ChromeVox.verbosity=cvox.VERBOSITY_VERBOSE;cvox.ChromeVox.typingEcho=0;cvox.ChromeVox.keyEcho={};cvox.Point;cvox.ChromeVox.position={};cvox.ChromeVox.isChromeOS=navigator.userAgent.indexOf('CrOS')!=-1;cvox.ChromeVox.isMac=navigator.platform.indexOf('Mac')!=-1;cvox.ChromeVox.modKeyStr;if(cvox.ChromeVox.isChromeOS){cvox.ChromeVox.modKeyStr='Shift+Search';}else if(cvox.ChromeVox.isMac){cvox.ChromeVox.modKeyStr='Ctrl+Cmd';}else{cvox.ChromeVox.modKeyStr='Shift+Alt';}
cvox.ChromeVox.sequenceSwitchKeyCodes=[];cvox.ChromeVox.visitedUrls={};cvox.ChromeVox.markInUserCommand=function(){};cvox.ChromeVox.syncToNode=function(targetNode,speakNode,opt_queueMode){};cvox.ChromeVox.speakNode=function(targetNode,queueMode,properties){};cvox.ChromeVox.executeUserCommand=function(commandName){};cvox.ChromeVox.entireDocumentIsHidden=false;cvox.ChromeVox.storeOn=function(store){store['isStickyPrefOn']=cvox.ChromeVox.isStickyPrefOn;cvox.ChromeVox.navigationManager.storeOn(store);};cvox.ChromeVox.readFrom=function(store){cvox.ChromeVox.isStickyPrefOn=store['isStickyPrefOn'];cvox.ChromeVox.navigationManager.readFrom(store);};cvox.ChromeVox.isStickyModeOn=function(){if(cvox.ChromeVox.stickyOverride!==null){return cvox.ChromeVox.stickyOverride;}else{return cvox.ChromeVox.isStickyPrefOn;}};function $(id){return document.getElementById(id);}
cvox.ChromeVox.injectChromeVoxIntoTabs=function(tabs){};cvox.ChromeVox.documentHasFocus=function(){if(!document.hasFocus()||document.hidden){return false;}
if(document.activeElement.tagName=='IFRAME'||document.activeElement.tagName=='WEBVIEW'){return false;}
return true;};goog.provide('cvox.DomPredicates');cvox.DomPredicates.checkboxPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='checkbox')||(nodes[i].tagName=='INPUT'&&nodes[i].type=='checkbox')){return nodes[i];}}
return null;};cvox.DomPredicates.radioPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='radio')||(nodes[i].tagName=='INPUT'&&nodes[i].type=='radio')){return nodes[i];}}
return null;};cvox.DomPredicates.sliderPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='slider')||(nodes[i].tagName=='INPUT'&&nodes[i].type=='range')){return nodes[i];}}
return null;};cvox.DomPredicates.graphicPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(nodes[i].tagName=='IMG'||(nodes[i].tagName=='INPUT'&&nodes[i].type=='img')){return nodes[i];}}
return null;};cvox.DomPredicates.buttonPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='button')||nodes[i].tagName=='BUTTON'||(nodes[i].tagName=='INPUT'&&nodes[i].type=='submit')||(nodes[i].tagName=='INPUT'&&nodes[i].type=='button')||(nodes[i].tagName=='INPUT'&&nodes[i].type=='reset')){return nodes[i];}}
return null;};cvox.DomPredicates.comboBoxPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='combobox')||nodes[i].tagName=='SELECT'){return nodes[i];}}
return null;};cvox.DomPredicates.editTextPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='textbox')||nodes[i].tagName=='TEXTAREA'||nodes[i].isContentEditable||(nodes[i].tagName=='INPUT'&&cvox.DomUtil.isInputTypeText(nodes[i]))){return nodes[i];}}
return null;};cvox.DomPredicates.headingPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(nodes[i].getAttribute&&nodes[i].getAttribute('role')=='heading'){return nodes[i];}
switch(nodes[i].tagName){case'H1':case'H2':case'H3':case'H4':case'H5':case'H6':return nodes[i];}}
return null;};cvox.DomPredicates.heading1Predicate=function(nodes){return cvox.DomPredicates.containsTagName_(nodes,'H1');};cvox.DomPredicates.heading2Predicate=function(nodes){return cvox.DomPredicates.containsTagName_(nodes,'H2');};cvox.DomPredicates.heading3Predicate=function(nodes){return cvox.DomPredicates.containsTagName_(nodes,'H3');};cvox.DomPredicates.heading4Predicate=function(nodes){return cvox.DomPredicates.containsTagName_(nodes,'H4');};cvox.DomPredicates.heading5Predicate=function(nodes){return cvox.DomPredicates.containsTagName_(nodes,'H5');};cvox.DomPredicates.heading6Predicate=function(nodes){return cvox.DomPredicates.containsTagName_(nodes,'H6');};cvox.DomPredicates.linkPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='link')||(nodes[i].tagName=='A'&&nodes[i].href)){return nodes[i];}}
return null;};cvox.DomPredicates.tablePredicate=function(nodes){var node=cvox.DomUtil.findTableNodeInList(nodes,{allowCaptions:true});if(node&&!cvox.DomUtil.isLayoutTable(node)){return node;}else{return null;}};cvox.DomPredicates.cellPredicate=function(nodes){for(var i=nodes.length-1;i>=0;--i){var node=nodes[i];if(node.tagName=='TD'||node.tagName=='TH'||(node.getAttribute&&node.getAttribute('role')=='gridcell')){return node;}}
return null;};cvox.DomPredicates.visitedLinkPredicate=function(nodes){for(var i=nodes.length-1;i>=0;--i){if(cvox.DomPredicates.linkPredicate([nodes[i]])&&cvox.ChromeVox.visitedUrls[nodes[i].href]){return nodes[i];}}
return null;};cvox.DomPredicates.listPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='list')||nodes[i].tagName=='UL'||nodes[i].tagName=='OL'){return nodes[i];}}
return null;};cvox.DomPredicates.listItemPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='listitem')||nodes[i].tagName=='LI'){return nodes[i];}}
return null;};cvox.DomPredicates.blockquotePredicate=function(nodes){return cvox.DomPredicates.containsTagName_(nodes,'BLOCKQUOTE');};cvox.DomPredicates.formFieldPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(cvox.DomUtil.isControl(nodes[i])){return nodes[i];}}
return null;};cvox.DomPredicates.landmarkPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(cvox.AriaUtil.isLandmark(nodes[i])){return nodes[i];}}
return null;};cvox.DomPredicates.containsTagName_=function(arr,tagName){var i=arr.length;while(i--){if(arr[i].tagName==tagName){return arr[i];}}
return null;};cvox.DomPredicates.mathPredicate=function(nodes){return cvox.DomUtil.findMathNodeInList(nodes);};cvox.DomPredicates.sectionPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(cvox.DomUtil.isSemanticElt(nodes[i])){return nodes[i];}
if(cvox.AriaUtil.isLandmark(nodes[i])){return nodes[i];}
if(nodes[i].getAttribute&&nodes[i].getAttribute('role')=='heading'){return nodes[i];}
switch(nodes[i].tagName){case'H1':case'H2':case'H3':case'H4':case'H5':case'H6':return nodes[i];}}
return null;};cvox.DomPredicates.controlPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(cvox.DomUtil.isControl(nodes[i])){return nodes[i];}
if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='link')||(nodes[i].tagName=='A'&&nodes[i].href)){return nodes[i];}}
return null;};cvox.DomPredicates.captionPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(nodes[i].tagName=='CAPTION'){return nodes[i];}}
return null;};cvox.DomPredicates.articlePredicate=function(nodes){for(var i=0;i<nodes.length;i++){if((nodes[i].getAttribute&&nodes[i].getAttribute('role')=='article')||nodes[i].tagName=='ARTICLE'){return nodes[i];}}
return null;};cvox.DomPredicates.mediaPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(nodes[i].tagName=='AUDIO'||nodes[i].tagName=='VIDEO'){return nodes[i];}}
return null;};cvox.DomPredicates.orderedListPredicate=function(nodes){for(var i=0;i<nodes.length;i++){if(nodes[i].tagName=='OL'){return nodes[i];}}
return null;};goog.provide('cvox.AriaUtil');goog.require('cvox.AbstractEarcons');goog.require('cvox.ChromeVox');goog.require('cvox.NodeState');goog.require('cvox.NodeStateUtil');cvox.AriaUtil=function(){};cvox.AriaUtil.WIDGET_ROLE_TO_NAME={'alert':'role_alert','alertdialog':'role_alertdialog','button':'role_button','checkbox':'role_checkbox','columnheader':'role_columnheader','combobox':'role_combobox','dialog':'role_dialog','grid':'role_grid','gridcell':'role_gridcell','link':'role_link','listbox':'role_listbox','log':'role_log','marquee':'role_marquee','menu':'role_menu','menubar':'role_menubar','menuitem':'role_menuitem','menuitemcheckbox':'role_menuitemcheckbox','menuitemradio':'role_menuitemradio','option':'role_option','progressbar':'role_progressbar','radio':'role_radio','radiogroup':'role_radiogroup','rowheader':'role_rowheader','scrollbar':'role_scrollbar','slider':'role_slider','spinbutton':'role_spinbutton','status':'role_status','tab':'role_tab','tablist':'role_tablist','tabpanel':'role_tabpanel','textbox':'role_textbox','timer':'role_timer','toolbar':'role_toolbar','tooltip':'role_tooltip','treeitem':'role_treeitem'};cvox.AriaUtil.STRUCTURE_ROLE_TO_NAME={'article':'role_article','application':'role_application','banner':'role_banner','columnheader':'role_columnheader','complementary':'role_complementary','contentinfo':'role_contentinfo','definition':'role_definition','directory':'role_directory','document':'role_document','form':'role_form','group':'role_group','heading':'role_heading','img':'role_img','list':'role_list','listitem':'role_listitem','main':'role_main','math':'role_math','navigation':'role_navigation','note':'role_note','region':'role_region','rowheader':'role_rowheader','search':'role_search','separator':'role_separator'};cvox.AriaUtil.ATTRIBUTE_VALUE_TO_STATUS=[{name:'aria-autocomplete',values:{'inline':'aria_autocomplete_inline','list':'aria_autocomplete_list','both':'aria_autocomplete_both'}},{name:'aria-checked',values:{'true':'aria_checked_true','false':'aria_checked_false','mixed':'aria_checked_mixed'}},{name:'aria-disabled',values:{'true':'aria_disabled_true'}},{name:'aria-expanded',values:{'true':'aria_expanded_true','false':'aria_expanded_false'}},{name:'aria-invalid',values:{'true':'aria_invalid_true','grammar':'aria_invalid_grammar','spelling':'aria_invalid_spelling'}},{name:'aria-multiline',values:{'true':'aria_multiline_true'}},{name:'aria-multiselectable',values:{'true':'aria_multiselectable_true'}},{name:'aria-pressed',values:{'true':'aria_pressed_true','false':'aria_pressed_false','mixed':'aria_pressed_mixed'}},{name:'aria-readonly',values:{'true':'aria_readonly_true'}},{name:'aria-required',values:{'true':'aria_required_true'}},{name:'aria-selected',values:{'true':'aria_selected_true','false':'aria_selected_false'}}];cvox.AriaUtil.isHiddenRecursive=function(targetNode){if(cvox.AriaUtil.isHidden(targetNode)){return true;}
var parent=targetNode.parentElement;while(parent){if((parent.getAttribute('aria-hidden')=='true')&&(parent.getAttribute('chromevoxignoreariahidden')!='true')){return true;}
parent=parent.parentElement;}
return false;};cvox.AriaUtil.isHidden=function(targetNode){if(!targetNode){return true;}
if(targetNode.getAttribute){if((targetNode.getAttribute('aria-hidden')=='true')&&(targetNode.getAttribute('chromevoxignoreariahidden')!='true')){return true;}}
return false;};cvox.AriaUtil.isForcedVisibleRecursive=function(targetNode){var node=targetNode;while(node){if(node.getAttribute){if(node.hasAttribute('aria-hidden')&&(node.getAttribute('chromevoxignoreariahidden')!='true')){return node.getAttribute('aria-hidden')=='false';}}
node=node.parentElement;}
return false;};cvox.AriaUtil.isLeafElement=function(targetElement){var role=targetElement.getAttribute('role');return role=='img'||role=='progressbar';};cvox.AriaUtil.isDescendantOfRole=function(node,roleName){while(node){if(roleName&&node&&(node.getAttribute('role')==roleName)){return true;}
node=node.parentNode;}
return false;};cvox.AriaUtil.getRoleNameMsgForRole_=function(role){var msgId=cvox.AriaUtil.WIDGET_ROLE_TO_NAME[role];if(!msgId){return null;}
return msgId;};cvox.AriaUtil.isButton=function(node){var role=cvox.AriaUtil.getRoleAttribute(node);if(role=='button'){return true;}
if(node.tagName=='BUTTON'){return true;}
if(node.tagName=='INPUT'){return(node.type=='submit'||node.type=='reset'||node.type=='button');}
return false;};cvox.AriaUtil.getRoleNameMsg=function(targetNode){var roleName;if(targetNode&&targetNode.getAttribute){var role=cvox.AriaUtil.getRoleAttribute(targetNode);if(targetNode.getAttribute('aria-haspopup')=='true'&&cvox.AriaUtil.isButton(targetNode)){return'role_popup_button';}
if(role){roleName=cvox.AriaUtil.getRoleNameMsgForRole_(role);if(!roleName){roleName=cvox.AriaUtil.STRUCTURE_ROLE_TO_NAME[role];}}
if(role=='menuitem'){var container=targetNode.parentElement;while(container){if(container.getAttribute&&(cvox.AriaUtil.getRoleAttribute(container)=='menu'||cvox.AriaUtil.getRoleAttribute(container)=='menubar')){break;}
container=container.parentElement;}
if(container&&cvox.AriaUtil.getRoleAttribute(container)=='menubar'){roleName=cvox.AriaUtil.getRoleNameMsgForRole_('menu');}}}
if(!roleName){roleName='';}
return roleName;};cvox.AriaUtil.getRoleName=function(targetNode){var roleMsg=cvox.AriaUtil.getRoleNameMsg(targetNode);var roleName=Msgs.getMsg(roleMsg);var role=cvox.AriaUtil.getRoleAttribute(targetNode);if((role=='heading')&&(targetNode.hasAttribute('aria-level'))){roleName+=' '+targetNode.getAttribute('aria-level');}
return roleName?roleName:'';};cvox.AriaUtil.getStateMsgs=function(targetNode,primary){var state=[];if(!targetNode||!targetNode.getAttribute){return state;}
for(var i=0,attr;attr=cvox.AriaUtil.ATTRIBUTE_VALUE_TO_STATUS[i];i++){var value=targetNode.getAttribute(attr.name);var msgId=attr.values[value];if(msgId){state.push([msgId]);}}
if(targetNode.getAttribute('role')=='grid'){return cvox.AriaUtil.getGridState_(targetNode,targetNode);}
var role=cvox.AriaUtil.getRoleAttribute(targetNode);if(targetNode.getAttribute('aria-haspopup')=='true'){if(role=='menuitem'){state.push(['has_submenu']);}else if(cvox.AriaUtil.isButton(targetNode)){}else{state.push(['has_popup']);}}
var valueText=targetNode.getAttribute('aria-valuetext');if(valueText){state.push(['aria_value_text',valueText]);return state;}
var valueNow=targetNode.getAttribute('aria-valuenow');var valueMin=targetNode.getAttribute('aria-valuemin');var valueMax=targetNode.getAttribute('aria-valuemax');if((valueNow!=null)&&(valueMin!=null)&&(valueMax!=null)){if((role=='scrollbar')||(role=='progressbar')){var percent=Math.round((valueNow/(valueMax-valueMin))*100);state.push(['state_percent',percent]);return state;}}
if(valueNow!=null){state.push(['aria_value_now',valueNow]);}
if(valueMin!=null){state.push(['aria_value_min',valueMin]);}
if(valueMax!=null){state.push(['aria_value_max',valueMax]);}
var parentControl=targetNode;var currentDescendant=null;if(cvox.AriaUtil.isCompositeControl(parentControl)&&primary){currentDescendant=cvox.AriaUtil.getActiveDescendant(parentControl);}else{role=cvox.AriaUtil.getRoleAttribute(targetNode);if(role=='option'||role=='menuitem'||role=='menuitemcheckbox'||role=='menuitemradio'||role=='radio'||role=='tab'||role=='treeitem'){currentDescendant=targetNode;parentControl=targetNode.parentElement;while(parentControl&&!cvox.AriaUtil.isCompositeControl(parentControl)){parentControl=parentControl.parentElement;if(parentControl&&cvox.AriaUtil.getRoleAttribute(parentControl)=='treeitem'){break;}}}}
if(parentControl&&(cvox.AriaUtil.isCompositeControl(parentControl)||cvox.AriaUtil.getRoleAttribute(parentControl)=='treeitem')&&currentDescendant){var parentRole=cvox.AriaUtil.getRoleAttribute(parentControl);var descendantRoleList;switch(parentRole){case'combobox':case'listbox':descendantRoleList=['option'];break;case'menu':descendantRoleList=['menuitem','menuitemcheckbox','menuitemradio'];break;case'radiogroup':descendantRoleList=['radio'];break;case'tablist':descendantRoleList=['tab'];break;case'tree':case'treegrid':case'treeitem':descendantRoleList=['treeitem'];break;}
if(descendantRoleList){var listLength;var currentIndex;var ariaLength=parseInt(currentDescendant.getAttribute('aria-setsize'),10);if(!isNaN(ariaLength)){listLength=ariaLength;}
var ariaIndex=parseInt(currentDescendant.getAttribute('aria-posinset'),10);if(!isNaN(ariaIndex)){currentIndex=ariaIndex;}
if(listLength==undefined||currentIndex==undefined){var descendants=cvox.AriaUtil.getNextLevel(parentControl,descendantRoleList);if(listLength==undefined){listLength=descendants.length;}
if(currentIndex==undefined){for(var j=0;j<descendants.length;j++){if(descendants[j]==currentDescendant){currentIndex=j+1;}}}}
if(currentIndex&&listLength){state.push(['list_position',currentIndex,listLength]);}}}
return state;};cvox.AriaUtil.getGridState_=function(targetNode,parentControl){var activeDescendant=cvox.AriaUtil.getActiveDescendant(parentControl);if(activeDescendant){var descendantSelector='*[role~="row"]';var rows=parentControl.querySelectorAll(descendantSelector);var currentIndex=null;for(var j=0;j<rows.length;j++){var gridcells=rows[j].querySelectorAll('*[role~="gridcell"]');for(var k=0;k<gridcells.length;k++){if(gridcells[k]==activeDescendant){return([['role_gridcell_pos',j+1,k+1]]);}}}}
return[];};cvox.AriaUtil.getActiveDescendantId_=function(targetNode){if(!targetNode.getAttribute){return null;}
var activeId=targetNode.getAttribute('aria-activedescendant');if(!activeId){return null;}
return activeId;};cvox.AriaUtil.getNextLevel=function(parentControl,role){var result=[];var children=parentControl.childNodes;var length=children.length;for(var i=0;i<children.length;i++){if(cvox.AriaUtil.isHidden(children[i])||!cvox.DomUtil.isVisible(children[i])){continue;}
var nextLevel=cvox.AriaUtil.getNextLevelItems(children[i],role);if(nextLevel.length>0){result=result.concat(nextLevel);}}
return result;};cvox.AriaUtil.getNextLevelItems=function(current,role){if(current.nodeType!=1){return[];}
if(role.indexOf(cvox.AriaUtil.getRoleAttribute(current))!=-1){return[current];}else{var children=current.childNodes;var length=children.length;if(length==0){return[];}else{var resultArray=[];for(var i=0;i<length;i++){var result=cvox.AriaUtil.getNextLevelItems(children[i],role);if(result.length>0){resultArray=resultArray.concat(result);}}
return resultArray;}}};cvox.AriaUtil.getActiveDescendant=function(targetNode){var seenIds={};var node=targetNode;while(node){var activeId=cvox.AriaUtil.getActiveDescendantId_(node);if(!activeId){break;}
if(activeId in seenIds){return null;}
seenIds[activeId]=true;node=document.getElementById(activeId);}
if(node==targetNode){return null;}
return node;};cvox.AriaUtil.isControlWidget=function(targetNode){if(targetNode&&targetNode.getAttribute){var role=cvox.AriaUtil.getRoleAttribute(targetNode);switch(role){case'button':case'checkbox':case'combobox':case'listbox':case'menu':case'menuitemcheckbox':case'menuitemradio':case'radio':case'slider':case'progressbar':case'scrollbar':case'spinbutton':case'tab':case'tablist':case'textbox':return true;}}
return false;};cvox.AriaUtil.isCompositeControl=function(targetNode){if(targetNode&&targetNode.getAttribute){var role=cvox.AriaUtil.getRoleAttribute(targetNode);switch(role){case'combobox':case'grid':case'listbox':case'menu':case'menubar':case'radiogroup':case'tablist':case'tree':case'treegrid':return true;}}
return false;};cvox.AriaUtil.getAriaLive=function(node){if(!node.hasAttribute)
return null;var value=node.getAttribute('aria-live');if(value=='off'){return null;}else if(value){return value;}
var role=cvox.AriaUtil.getRoleAttribute(node);switch(role){case'alert':return'assertive';case'log':case'status':return'polite';default:return null;}};cvox.AriaUtil.getAriaAtomic=function(node){if(!node.hasAttribute)
return false;var value=node.getAttribute('aria-atomic');if(value){return(value==='true');}
var role=cvox.AriaUtil.getRoleAttribute(node);if(role=='alert'){return true;}
return false;};cvox.AriaUtil.getAriaBusy=function(node){if(!node.hasAttribute)
return false;var value=node.getAttribute('aria-busy');if(value){return(value==='true');}
return false;};cvox.AriaUtil.getAriaRelevant=function(node,change){if(!node.hasAttribute)
return false;var value;if(node.hasAttribute('aria-relevant')){value=node.getAttribute('aria-relevant');}else{value='additions text';}
if(value=='all'){value='additions removals text';}
var tokens=value.replace(/\s+/g,' ').replace(/^\s+|\s+$/g,'').split(' ');if(change=='all'){return(tokens.indexOf('additions')>=0&&tokens.indexOf('text')>=0&&tokens.indexOf('removals')>=0);}else{return(tokens.indexOf(change)>=0);}};cvox.AriaUtil.getLiveRegions=function(node){var result=[];if(node.querySelectorAll){var nodes=node.querySelectorAll('[role="alert"], [role="log"],  [role="marquee"], '+'[role="status"], [role="timer"],  [aria-live]');if(nodes){for(var i=0;i<nodes.length;i++){result.push(nodes[i]);}}}
while(node){if(cvox.AriaUtil.getAriaLive(node)){result.push(node);return result;}
node=node.parentElement;}
return result;};cvox.AriaUtil.isLandmark=function(node){if(!node||!node.getAttribute){return false;}
var role=cvox.AriaUtil.getRoleAttribute(node);switch(role){case'application':case'banner':case'complementary':case'contentinfo':case'form':case'main':case'navigation':case'search':return true;}
return false;};cvox.AriaUtil.isGrid=function(node){if(!node||!node.getAttribute){return false;}
var role=cvox.AriaUtil.getRoleAttribute(node);switch(role){case'grid':case'treegrid':return true;}
return false;};cvox.AriaUtil.getEarcon=function(node){if(!node||!node.getAttribute){return null;}
var role=cvox.AriaUtil.getRoleAttribute(node);switch(role){case'button':return cvox.Earcon.BUTTON;case'checkbox':case'radio':case'menuitemcheckbox':case'menuitemradio':var checked=node.getAttribute('aria-checked');if(checked=='true'){return cvox.Earcon.CHECK_ON;}else{return cvox.Earcon.CHECK_OFF;}
case'combobox':case'listbox':return cvox.Earcon.LISTBOX;case'textbox':return cvox.Earcon.EDITABLE_TEXT;case'listitem':return cvox.Earcon.LIST_ITEM;case'link':return cvox.Earcon.LINK;}
return null;};cvox.AriaUtil.getRoleAttribute=function(targetNode){if(!targetNode.getAttribute){return'';}
var role=targetNode.getAttribute('role');if(targetNode.hasAttribute('chromevoxoriginalrole')){role=targetNode.getAttribute('chromevoxoriginalrole');}
return role;};cvox.AriaUtil.isMath=function(node){if(!node||!node.getAttribute){return false;}
var role=cvox.AriaUtil.getRoleAttribute(node);return role=='math';};goog.provide('cvox.Memoize');cvox.Memoize=function(){};cvox.Memoize.nodeMap_=null;cvox.Memoize.scopeCount_=0;cvox.Memoize.scope=function(functionScope){var result;try{cvox.Memoize.scopeCount_++;if(cvox.Memoize.scopeCount_==1){cvox.Memoize.nodeMap_={};}
result=functionScope();}finally{cvox.Memoize.scopeCount_--;if(cvox.Memoize.scopeCount_==0){cvox.Memoize.nodeMap_=null;}}
return result;};cvox.Memoize.memoize=function(functionClosure,functionName,node){if(cvox.Memoize.nodeMap_&&cvox.Memoize.nodeMap_[functionName]===undefined){cvox.Memoize.nodeMap_[functionName]=new WeakMap();}
if(!cvox.Memoize.nodeMap_){return functionClosure(node);}
var result=cvox.Memoize.nodeMap_[functionName].get(node);if(result===undefined){result=functionClosure(node);if(result===undefined){throw'A memoized function cannot return undefined.';}
cvox.Memoize.nodeMap_[functionName].set(node,result);}
return result;};goog.provide('cvox.DomUtil');goog.require('cvox.AbstractTts');goog.require('cvox.AriaUtil');goog.require('cvox.ChromeVox');goog.require('cvox.DomPredicates');goog.require('cvox.Memoize');goog.require('cvox.NodeState');goog.require('cvox.XpathUtil');cvox.DomUtil=function(){};cvox.DomUtil.INPUT_TYPE_TO_INFORMATION_TABLE_MSG={'button':'role_button','checkbox':'role_checkbox','color':'input_type_color','datetime':'input_type_datetime','datetime-local':'input_type_datetime_local','date':'input_type_date','email':'input_type_email','file':'input_type_file','image':'role_button','month':'input_type_month','number':'input_type_number','password':'input_type_password','radio':'role_radio','range':'role_slider','reset':'input_type_reset','search':'input_type_search','submit':'role_button','tel':'input_type_number','text':'input_type_text','url':'input_type_url','week':'input_type_week'};cvox.DomUtil.TAG_TO_INFORMATION_TABLE_VERBOSE_MSG={'A':'role_link','ARTICLE':'tag_article','ASIDE':'tag_aside','AUDIO':'tag_audio','BUTTON':'role_button','FOOTER':'tag_footer','H1':'tag_h1','H2':'tag_h2','H3':'tag_h3','H4':'tag_h4','H5':'tag_h5','H6':'tag_h6','HEADER':'tag_header','HGROUP':'tag_hgroup','LI':'tag_li','MARK':'tag_mark','NAV':'tag_nav','OL':'tag_ol','SECTION':'tag_section','SELECT':'tag_select','TABLE':'tag_table','TEXTAREA':'tag_textarea','TIME':'tag_time','UL':'tag_ul','VIDEO':'tag_video'};cvox.DomUtil.TAG_TO_INFORMATION_TABLE_BRIEF_MSG={'AUDIO':'tag_audio','BUTTON':'role_button','SELECT':'tag_select','TABLE':'tag_table','TEXTAREA':'tag_textarea','VIDEO':'tag_video'};cvox.DomUtil.FORMATTING_TAGS=['B','BIG','CITE','CODE','DFN','EM','I','KBD','SAMP','SMALL','SPAN','STRIKE','STRONG','SUB','SUP','U','VAR'];cvox.DomUtil.isVisible=function(node,opt_options){var checkAncestors=true;var checkDescendants=true;if(opt_options){if(opt_options.checkAncestors!==undefined){checkAncestors=opt_options.checkAncestors;}
if(opt_options.checkDescendants!==undefined){checkDescendants=opt_options.checkDescendants;}}
var fname='isVisible-'+checkAncestors+'-'+checkDescendants;return(cvox.Memoize.memoize(cvox.DomUtil.computeIsVisible_.bind(this,node,checkAncestors,checkDescendants),fname,node));};cvox.DomUtil.computeIsVisible_=function(node,checkAncestors,checkDescendants){if(node.tagName=='IFRAME'&&!node.src){return false;}
if(cvox.AriaUtil.isForcedVisibleRecursive(node)){return true;}
if(checkAncestors&&cvox.DomUtil.hasInvisibleAncestor_(node)){return false;}
if(cvox.DomUtil.hasVisibleNodeSubtree_(node,checkDescendants)){return true;}
return false;};cvox.DomUtil.hasInvisibleAncestor_=function(node){var ancestor=node;while(ancestor=ancestor.parentElement){var style=document.defaultView.getComputedStyle(ancestor,null);if(cvox.DomUtil.isInvisibleStyle(style,true)){return true;}
if(ancestor==document.documentElement){return false;}}
return true;};cvox.DomUtil.hasVisibleNodeSubtree_=function(root,recursive){if(!(root instanceof Element)){if(!root.parentElement){return false;}
var parentStyle=document.defaultView.getComputedStyle(root.parentElement,null);var isVisibleParent=!cvox.DomUtil.isInvisibleStyle(parentStyle);return isVisibleParent;}
var rootStyle=document.defaultView.getComputedStyle(root,null);var isRootVisible=!cvox.DomUtil.isInvisibleStyle(rootStyle);if(isRootVisible){return true;}
var isSubtreeInvisible=cvox.DomUtil.isInvisibleStyle(rootStyle,true);if(!recursive||isSubtreeInvisible){return false;}
var children=root.childNodes;for(var i=0;i<children.length;i++){var child=children[i];if(cvox.DomUtil.hasVisibleNodeSubtree_(child,recursive)){return true;}}
return false;};cvox.DomUtil.isInvisibleStyle=function(style,opt_strict){if(!style){return false;}
if(style.display=='none'){return true;}
if(parseFloat(style.opacity)==0){return true;}
if(!opt_strict&&(style.visibility=='hidden'||style.visibility=='collapse')){return true;}
return false;};cvox.DomUtil.isDisabled=function(node){if(node.disabled){return true;}
var ancestor=node;while(ancestor=ancestor.parentElement){if(ancestor.tagName=='FIELDSET'&&ancestor.disabled){return true;}}
return false;};cvox.DomUtil.isSemanticElt=function(node){if(node.tagName){var tag=node.tagName;if((tag=='SECTION')||(tag=='NAV')||(tag=='ARTICLE')||(tag=='ASIDE')||(tag=='HGROUP')||(tag=='HEADER')||(tag=='FOOTER')||(tag=='TIME')||(tag=='MARK')){return true;}}
return false;};cvox.DomUtil.isLeafNode=function(node,opt_allowHidden){if(!(node instanceof Element)){return(node.firstChild==null);}
var element=(node);if(!opt_allowHidden&&!cvox.DomUtil.isVisible(element,{checkAncestors:false})){return true;}
if(!opt_allowHidden&&cvox.AriaUtil.isHidden(element)){return true;}
if(cvox.AriaUtil.isLeafElement(element)){return true;}
switch(element.tagName){case'OBJECT':case'EMBED':case'VIDEO':case'AUDIO':case'IFRAME':case'FRAME':return true;}
if(!!cvox.DomPredicates.linkPredicate([element])){return!cvox.DomUtil.findNode(element,function(node){return!!cvox.DomPredicates.headingPredicate([node]);});}
if(cvox.DomUtil.isLeafLevelControl(element)){return true;}
if(!element.firstChild){return true;}
if(cvox.DomUtil.isMath(element)){return true;}
if(cvox.DomPredicates.headingPredicate([element])){return!cvox.DomUtil.findNode(element,function(n){return!!cvox.DomPredicates.controlPredicate([n]);});}
return false;};cvox.DomUtil.isDescendantOf=function(node,tagName,className){while(node){if(tagName&&className&&(node.tagName&&(node.tagName==tagName))&&(node.className&&(node.className==className))){return true;}else if(tagName&&!className&&(node.tagName&&(node.tagName==tagName))){return true;}else if(!tagName&&className&&(node.className&&(node.className==className))){return true;}
node=node.parentNode;}
return false;};cvox.DomUtil.isDescendantOfNode=function(node,ancestor){while(node&&ancestor){if(node.isSameNode(ancestor)){return true;}
node=node.parentNode;}
return false;};cvox.DomUtil.collapseWhitespace=function(str){return str.replace(/\s+/g,' ').replace(/^\s+|\s+$/g,'');};cvox.DomUtil.getBaseLabel_=function(node,recursive,includeControls){var label='';if(node.hasAttribute){if(node.hasAttribute('aria-labelledby')){var labelNodeIds=node.getAttribute('aria-labelledby').split(' ');for(var labelNodeId,i=0;labelNodeId=labelNodeIds[i];i++){var labelNode=document.getElementById(labelNodeId);if(labelNode){label+=' '+cvox.DomUtil.getName(labelNode,true,includeControls,true);}}}else if(node.hasAttribute('aria-label')){label=node.getAttribute('aria-label');}else if(node.constructor==HTMLImageElement){label=cvox.DomUtil.getImageTitle(node);}else if(node.tagName=='FIELDSET'){var legends=node.getElementsByTagName('LEGEND');label='';for(var legend,i=0;legend=legends[i];i++){label+=' '+cvox.DomUtil.getName(legend,true,includeControls);}}
if(label.length==0&&node&&node.id){var labelFor=document.querySelector('label[for="'+node.id+'"]');if(labelFor){label=cvox.DomUtil.getName(labelFor,recursive,includeControls);}}}
return cvox.DomUtil.collapseWhitespace(label);};cvox.DomUtil.getNearestAncestorLabel_=function(node){var label='';var enclosingLabel=node;while(enclosingLabel&&enclosingLabel.tagName!='LABEL'){enclosingLabel=enclosingLabel.parentElement;}
if(enclosingLabel&&!enclosingLabel.hasAttribute('for')){label=cvox.DomUtil.getName(enclosingLabel,true,false);}
return label;};cvox.DomUtil.getInputName_=function(node){var label='';if(node.type=='image'){label=cvox.DomUtil.getImageTitle(node);}else if(node.type=='submit'){if(node.hasAttribute('value')){label=node.getAttribute('value');}else{label='Submit';}}else if(node.type=='reset'){if(node.hasAttribute('value')){label=node.getAttribute('value');}else{label='Reset';}}else if(node.type=='button'){if(node.hasAttribute('value')){label=node.getAttribute('value');}}
return label;};cvox.DomUtil.getName=function(node,recursive,includeControls,opt_allowHidden){if(!node||node.cvoxGetNameMarked==true){return'';}
node.cvoxGetNameMarked=true;var ret=cvox.DomUtil.getName_(node,recursive,includeControls,opt_allowHidden);node.cvoxGetNameMarked=false;var prefix=cvox.DomUtil.getPrefixText(node);return prefix+ret;};cvox.DomUtil.hasChildrenBasedName_=function(node,opt_allowHidden){if(!!cvox.DomPredicates.linkPredicate([node])||!!cvox.DomPredicates.headingPredicate([node])||node.tagName=='BUTTON'||cvox.AriaUtil.isControlWidget(node)||!cvox.DomUtil.isLeafNode(node,opt_allowHidden)){return true;}else{return false;}};cvox.DomUtil.getName_=function(node,recursive,includeControls,opt_allowHidden){if(typeof(recursive)==='undefined'){recursive=true;}
if(typeof(includeControls)==='undefined'){includeControls=true;}
if(node.constructor==Text){return node.data;}
var label=cvox.DomUtil.getBaseLabel_(node,recursive,includeControls);if(label.length==0&&cvox.DomUtil.isControl(node)){label=cvox.DomUtil.getNearestAncestorLabel_(node);}
if(label.length==0&&node.constructor==HTMLInputElement){label=cvox.DomUtil.getInputName_(node);}
if(cvox.DomUtil.isInputTypeText(node)&&node.hasAttribute('placeholder')){var placeholder=node.getAttribute('placeholder');if(label.length>0){if(cvox.DomUtil.getValue(node).length>0){return label;}else{return label+' with hint '+placeholder;}}else{return placeholder;}}
if(label.length>0){return label;}
if(cvox.DomUtil.collapseWhitespace(node.textContent).length==0&&node.hasAttribute&&node.hasAttribute('title')){return node.getAttribute('title');}
if(!recursive){return'';}
if(cvox.AriaUtil.isCompositeControl(node)){return'';}
if(cvox.DomUtil.hasChildrenBasedName_(node,opt_allowHidden)){return cvox.DomUtil.getNameFromChildren(node,includeControls,opt_allowHidden);}
return'';};cvox.DomUtil.getNameFromChildren=function(node,includeControls,opt_allowHidden){if(includeControls==undefined){includeControls=true;}
var name='';var delimiter='';for(var i=0;i<node.childNodes.length;i++){var child=node.childNodes[i];var prevChild=node.childNodes[i-1]||child;if(!includeControls&&cvox.DomUtil.isControl(child)){continue;}
var isVisible=cvox.DomUtil.isVisible(child,{checkAncestors:false});if(opt_allowHidden||(isVisible&&!cvox.AriaUtil.isHidden(child))){delimiter=(prevChild.tagName=='SPAN'||child.tagName=='SPAN'||child.parentNode.tagName=='SPAN')?'':' ';name+=delimiter+cvox.DomUtil.getName(child,true,includeControls);}}
return name;};cvox.DomUtil.getPrefixText=function(node,opt_index){opt_index=opt_index||0;var ancestors=cvox.DomUtil.getAncestors(node);var prefix='';var firstListitem=cvox.DomPredicates.listItemPredicate(ancestors);var leftmost=firstListitem;while(leftmost&&leftmost.firstChild){leftmost=leftmost.firstChild;}
if(firstListitem&&firstListitem.parentNode&&opt_index==0&&firstListitem.parentNode.tagName=='OL'&&node==leftmost&&document.defaultView.getComputedStyle(firstListitem.parentNode).listStyleType!='none'){var items=cvox.DomUtil.toArray(firstListitem.parentNode.children).filter(function(li){return li.tagName=='LI';});var position=items.indexOf(firstListitem)+1;if(document.defaultView.getComputedStyle(firstListitem.parentNode).listStyleType.indexOf('latin')!=-1){position--;prefix=String.fromCharCode('A'.charCodeAt(0)+position%26);}else{prefix=position;}
prefix+='. ';}
return prefix;};cvox.DomUtil.getControlLabelHeuristics=function(node){if(node.hasAttribute&&((node.hasAttribute('aria-label')&&(node.getAttribute('aria-label')==''))||(node.hasAttribute('aria-title')&&(node.getAttribute('aria-title')=='')))){return'';}
var prevNode=cvox.DomUtil.previousLeafNode(node);var prevTraversalCount=0;while(prevNode&&(!cvox.DomUtil.hasContent(prevNode)||cvox.DomUtil.isControl(prevNode))){prevNode=cvox.DomUtil.previousLeafNode(prevNode);prevTraversalCount++;}
var nextNode=cvox.DomUtil.directedNextLeafNode(node);var nextTraversalCount=0;while(nextNode&&(!cvox.DomUtil.hasContent(nextNode)||cvox.DomUtil.isControl(nextNode))){nextNode=cvox.DomUtil.directedNextLeafNode(nextNode);nextTraversalCount++;}
var guessedLabelNode;if(prevNode&&nextNode){var parentNode=node;var prevCount=0;while(parentNode){if(cvox.DomUtil.isDescendantOfNode(prevNode,parentNode)){break;}
parentNode=parentNode.parentNode;prevCount++;}
parentNode=node;var nextCount=0;while(parentNode){if(cvox.DomUtil.isDescendantOfNode(nextNode,parentNode)){break;}
parentNode=parentNode.parentNode;nextCount++;}
guessedLabelNode=nextCount<prevCount?nextNode:prevNode;}else{guessedLabelNode=prevNode||nextNode;}
if(guessedLabelNode){return cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(guessedLabelNode)+' '+
cvox.DomUtil.getName(guessedLabelNode));}
return'';};cvox.DomUtil.getValue=function(node){var activeDescendant=cvox.AriaUtil.getActiveDescendant(node);if(activeDescendant){return cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(activeDescendant)+' '+
cvox.DomUtil.getName(activeDescendant));}
if(node.constructor==HTMLSelectElement){node=(node);var value='';var start=node.selectedOptions?node.selectedOptions[0]:null;var end=node.selectedOptions?node.selectedOptions[node.selectedOptions.length-1]:null;if(start&&end&&start!=end){value=Msgs.getMsg('selected_options_value',[start.text,end.text]);}else if(start){value=start.text+'';}
return value;}
if(node.constructor==HTMLTextAreaElement){return node.value;}
if(node.constructor==HTMLInputElement){switch(node.type){case'hidden':case'image':case'submit':case'reset':case'button':case'checkbox':case'radio':return'';case'password':return node.value.replace(/./g,'dot ');default:return node.value;}}
if(node.isContentEditable){return cvox.DomUtil.getNameFromChildren(node,true);}
return'';};cvox.DomUtil.getImageTitle=function(node){var text;if(node.hasAttribute('alt')){text=node.alt;}else if(node.hasAttribute('title')){text=node.title;}else{var url=node.src;if(url.substring(0,4)!='data'){var filename=url.substring(url.lastIndexOf('/')+1,url.lastIndexOf('.'));if(filename.length>=1&&filename.length<=16){text=filename+' Image';}else{text='Image';}}else{text='Image';}}
return text;};cvox.DomUtil.getLabelledByTargets=function(){if(cvox.labelledByTargets){return cvox.labelledByTargets;}
var labelledByElements=document.querySelectorAll('[aria-labelledby]');var labelledByTargets={};for(var i=0;i<labelledByElements.length;++i){var element=labelledByElements[i];var attrValue=element.getAttribute('aria-labelledby');var ids=attrValue.split(/ +/);for(var j=0;j<ids.length;j++){labelledByTargets[ids[j]]=true;}}
cvox.labelledByTargets=labelledByTargets;window.setTimeout(function(){cvox.labelledByTargets=null;},0);return labelledByTargets;};cvox.DomUtil.hasContent=function(node){return(cvox.Memoize.memoize(cvox.DomUtil.computeHasContent_.bind(this),'hasContent',node));};cvox.DomUtil.computeHasContent_=function(node){if(node.nodeType==8){return false;}
if(cvox.DomUtil.isDescendantOf(node,'HEAD')){return false;}
if(cvox.DomUtil.isDescendantOf(node,'SCRIPT')){return false;}
if(cvox.DomUtil.isDescendantOf(node,'NOSCRIPT')){return false;}
if(cvox.DomUtil.isDescendantOf(node,'NOEMBED')){return false;}
if(cvox.DomUtil.isDescendantOf(node,'STYLE')){return false;}
if(!cvox.DomUtil.isVisible(node)){return false;}
if(cvox.AriaUtil.isHidden(node)){return false;}
if(cvox.DomUtil.isControl(node)){return true;}
if(cvox.DomUtil.isDescendantOf(node,'VIDEO')){return true;}
if(cvox.DomUtil.isDescendantOf(node,'AUDIO')){return true;}
if((node.tagName=='IFRAME')&&(node.src)&&(!node.src.startsWith('javascript:'))){return true;}
var controlQuery='button,input,select,textarea';var enclosingLabel=node.parentElement;while(enclosingLabel&&enclosingLabel.tagName!='LABEL'){enclosingLabel=enclosingLabel.parentElement;}
if(enclosingLabel){var embeddedControl=enclosingLabel.querySelector(controlQuery);if(enclosingLabel.hasAttribute('for')){var targetId=enclosingLabel.getAttribute('for');var targetNode=document.getElementById(targetId);if(targetNode&&cvox.DomUtil.isControl(targetNode)&&!embeddedControl){return false;}}else if(embeddedControl){return false;}}
var enclosingLegend=node.parentElement;while(enclosingLegend&&enclosingLegend.tagName!='LEGEND'){enclosingLegend=enclosingLegend.parentElement;}
if(enclosingLegend){var legendAncestor=enclosingLegend.parentElement;while(legendAncestor&&legendAncestor.tagName!='FIELDSET'){legendAncestor=legendAncestor.parentElement;}
var embeddedControl=legendAncestor&&legendAncestor.querySelector(controlQuery);if(legendAncestor&&!embeddedControl){return false;}}
if(!!cvox.DomPredicates.linkPredicate([node])){return true;}
if(node.tagName=='TABLE'&&!cvox.DomUtil.isLayoutTable(node)){return true;}
if(cvox.DomUtil.isMath(node)){return true;}
if(cvox.DomPredicates.headingPredicate([node])){return true;}
if(cvox.DomUtil.isFocusable(node)){return true;}
var labelledByTargets=cvox.DomUtil.getLabelledByTargets();var enclosingNodeWithId=node;while(enclosingNodeWithId){if(enclosingNodeWithId.id&&labelledByTargets[enclosingNodeWithId.id]){var attrValue=enclosingNodeWithId.getAttribute('aria-labelledby');if(attrValue){var ids=attrValue.split(/ +/);if(ids.indexOf(enclosingNodeWithId.id)==-1){return false;}}else{return false;}}
enclosingNodeWithId=enclosingNodeWithId.parentElement;}
var text=cvox.DomUtil.getValue(node)+' '+cvox.DomUtil.getName(node);var state=cvox.DomUtil.getState(node,true);if(text.match(/^\s+$/)&&state===''){return false;}
return true;};cvox.DomUtil.getAncestors=function(targetNode){var ancestors=new Array();while(targetNode){ancestors.push(targetNode);targetNode=targetNode.parentNode;}
ancestors.reverse();while(ancestors.length&&!ancestors[0].tagName&&!ancestors[0].nodeValue){ancestors.shift();}
return ancestors;};cvox.DomUtil.compareAncestors=function(ancestorsA,ancestorsB){var i=0;while(ancestorsA[i]&&ancestorsB[i]&&(ancestorsA[i]==ancestorsB[i])){i++;}
if(!ancestorsA[i]&&!ancestorsB[i]){i=-1;}
return i;};cvox.DomUtil.getUniqueAncestors=function(previousNode,currentNode,opt_fallback){var prevAncestors=cvox.DomUtil.getAncestors(previousNode);var currentAncestors=cvox.DomUtil.getAncestors(currentNode);var divergence=cvox.DomUtil.compareAncestors(prevAncestors,currentAncestors);var diff=currentAncestors.slice(divergence);return(diff.length==0&&opt_fallback)?currentAncestors:diff;};cvox.DomUtil.getRoleMsg=function(targetNode,verbosity){var info;info=cvox.AriaUtil.getRoleNameMsg(targetNode);if(!info){if(targetNode.tagName=='INPUT'){info=cvox.DomUtil.INPUT_TYPE_TO_INFORMATION_TABLE_MSG[targetNode.type];}else if(targetNode.tagName=='A'&&cvox.DomUtil.isInternalLink(targetNode)){info='internal_link';}else if(targetNode.tagName=='A'&&targetNode.getAttribute('href')&&cvox.ChromeVox.visitedUrls[targetNode.href]){info='visited_link';}else if(targetNode.tagName=='A'&&targetNode.getAttribute('name')){info='';}else if(targetNode.isContentEditable){info='input_type_text';}else if(cvox.DomUtil.isMath(targetNode)){info='math_expr';}else if(targetNode.tagName=='TABLE'&&cvox.DomUtil.isLayoutTable(targetNode)){info='';}else{if(verbosity==cvox.VERBOSITY_BRIEF){info=cvox.DomUtil.TAG_TO_INFORMATION_TABLE_BRIEF_MSG[targetNode.tagName];}else{info=cvox.DomUtil.TAG_TO_INFORMATION_TABLE_VERBOSE_MSG[targetNode.tagName];if(cvox.DomUtil.hasLongDesc(targetNode)){info='image_with_long_desc';}
if(!info&&targetNode.onclick){info='clickable';}}}}
return info;};cvox.DomUtil.getRole=function(targetNode,verbosity){var roleMsg=cvox.DomUtil.getRoleMsg(targetNode,verbosity)||'';var role=roleMsg&&roleMsg!=' '?Msgs.getMsg(roleMsg):'';return role?role:roleMsg;};cvox.DomUtil.getListLength=function(targetNode){var count=0;for(var node=targetNode.firstChild;node;node=node.nextSibling){if(cvox.DomUtil.isVisible(node)&&(node.tagName=='LI'||(node.getAttribute&&node.getAttribute('role')=='listitem'))){if(node.hasAttribute('aria-setsize')){var ariaLength=parseInt(node.getAttribute('aria-setsize'),10);if(!isNaN(ariaLength)){return ariaLength;}}
count++;}}
return count;};cvox.DomUtil.getStateMsgs=function(targetNode,primary){var activeDescendant=cvox.AriaUtil.getActiveDescendant(targetNode);if(activeDescendant){return cvox.DomUtil.getStateMsgs(activeDescendant,primary);}
var info=[];var role=targetNode.getAttribute?targetNode.getAttribute('role'):'';info=cvox.AriaUtil.getStateMsgs(targetNode,primary);if(!info){info=[];}
if(targetNode.tagName=='INPUT'){if(!targetNode.hasAttribute('aria-checked')){var INPUT_MSGS={'checkbox-true':'checkbox_checked_state','checkbox-false':'checkbox_unchecked_state','radio-true':'radio_selected_state','radio-false':'radio_unselected_state'};var msgId=INPUT_MSGS[targetNode.type+'-'+!!targetNode.checked];if(msgId){info.push([msgId]);}}}else if(targetNode.tagName=='SELECT'){if(targetNode.selectedOptions&&targetNode.selectedOptions.length<=1){info.push(['list_position',Msgs.getNumber(targetNode.selectedIndex+1),Msgs.getNumber(targetNode.options.length)]);}else{info.push(['selected_options_state',Msgs.getNumber(targetNode.selectedOptions.length)]);}}else if(targetNode.tagName=='UL'||targetNode.tagName=='OL'||role=='list'){info.push(['list_with_items_not_pluralized',Msgs.getNumber(cvox.DomUtil.getListLength(targetNode))]);}
if(cvox.DomUtil.isDisabled(targetNode)){info.push(['aria_disabled_true']);}
if(targetNode.accessKey){info.push(['access_key',targetNode.accessKey]);}
return info;};cvox.DomUtil.getState=function(targetNode,primary){return cvox.NodeStateUtil.expand(cvox.DomUtil.getStateMsgs(targetNode,primary));};cvox.DomUtil.isFocusable=function(targetNode){if(!targetNode||typeof(targetNode.tabIndex)!='number'){return false;}
if((targetNode.tagName=='A')&&!targetNode.hasAttribute('href')&&!targetNode.hasAttribute('tabindex')){return false;}
if(targetNode.tabIndex>=0){return true;}
if(targetNode.hasAttribute&&targetNode.hasAttribute('tabindex')&&targetNode.getAttribute('tabindex')=='-1'){return true;}
return false;};cvox.DomUtil.findFocusableDescendant=function(targetNode){if(targetNode){var focusableNode=cvox.DomUtil.findNode(targetNode,cvox.DomUtil.isFocusable);if(focusableNode){return focusableNode;}}
return null;};cvox.DomUtil.countFocusableDescendants=function(targetNode){return targetNode?cvox.DomUtil.countNodes(targetNode,cvox.DomUtil.isFocusable):0;};cvox.DomUtil.isAttachedToDocument=function(targetNode){while(targetNode){if(targetNode.tagName&&(targetNode.tagName=='HTML')){return true;}
targetNode=targetNode.parentNode;}
return false;};cvox.DomUtil.clickElem=function(targetNode,shiftKey,callOnClickDirectly,opt_double,opt_handleOwnEvents){var activeDescendant=cvox.AriaUtil.getActiveDescendant(targetNode);if(activeDescendant){targetNode=activeDescendant;}
if(callOnClickDirectly){var onClickFunction=null;if(targetNode.onclick){onClickFunction=targetNode.onclick;}
if(!onClickFunction&&(targetNode.nodeType!=1)&&targetNode.parentNode&&targetNode.parentNode.onclick){onClickFunction=targetNode.parentNode.onclick;}
var keepGoing=true;if(onClickFunction){try{keepGoing=onClickFunction();}catch(exception){}}
if(!keepGoing){return;}}
var evt=document.createEvent('MouseEvents');var evtType=opt_double?'dblclick':'mousedown';evt.initMouseEvent(evtType,true,true,document.defaultView,1,0,0,0,0,false,false,shiftKey,false,0,null);evt.fromCvox=!opt_handleOwnEvents;try{targetNode.dispatchEvent(evt);}catch(e){}
evt=document.createEvent('MouseEvents');evt.initMouseEvent('mouseup',true,true,document.defaultView,1,0,0,0,0,false,false,shiftKey,false,0,null);evt.fromCvox=!opt_handleOwnEvents;try{targetNode.dispatchEvent(evt);}catch(e){}
evt=document.createEvent('MouseEvents');evt.initMouseEvent('click',true,true,document.defaultView,1,0,0,0,0,false,false,shiftKey,false,0,null);evt.fromCvox=!opt_handleOwnEvents;try{targetNode.dispatchEvent(evt);}catch(e){}
if(cvox.DomUtil.isInternalLink(targetNode)){cvox.DomUtil.syncInternalLink(targetNode);}};cvox.DomUtil.syncInternalLink=function(node){var targetNode;var targetId=node.href.split('#')[1];targetNode=document.getElementById(targetId);if(!targetNode){var nodes=document.getElementsByName(targetId);if(nodes.length>0){targetNode=nodes[0];}}
if(targetNode){var parent=targetNode.parentNode;var dummyNode=document.createElement('div');dummyNode.setAttribute('tabindex','-1');parent.insertBefore(dummyNode,targetNode);dummyNode.setAttribute('chromevoxignoreariahidden',1);dummyNode.focus();cvox.ChromeVox.syncToNode(targetNode,false);}};cvox.DomUtil.isInputTypeText=function(node){if(!node||node.constructor!=HTMLInputElement){return false;}
switch(node.type){case'email':case'number':case'password':case'search':case'text':case'tel':case'url':case'':return true;default:return false;}};cvox.DomUtil.isControl=function(node){if(cvox.AriaUtil.isControlWidget(node)&&cvox.DomUtil.isFocusable(node)){return true;}
if(node.tagName){switch(node.tagName){case'BUTTON':case'TEXTAREA':case'SELECT':return true;case'INPUT':return node.type!='hidden';}}
if(node.isContentEditable){return true;}
return false;};cvox.DomUtil.isLeafLevelControl=function(node){if(cvox.DomUtil.isControl(node)){return!(cvox.AriaUtil.isCompositeControl(node)&&cvox.DomUtil.findFocusableDescendant(node));}
return false;};cvox.DomUtil.getSurroundingControl=function(node){var surroundingControl=null;if(!cvox.DomUtil.isControl(node)&&node.hasAttribute&&node.hasAttribute('role')){surroundingControl=node.parentElement;while(surroundingControl&&!cvox.AriaUtil.isCompositeControl(surroundingControl)){surroundingControl=surroundingControl.parentElement;}}
return surroundingControl;};cvox.DomUtil.directedNextLeafLikeNode=function(node,r,isLeaf){if(node!=document.body){while(!cvox.DomUtil.directedNextSibling(node,r)){if(!node){return null;}
node=(node.parentNode);if(node==document.body){return null;}}
if(cvox.DomUtil.directedNextSibling(node,r)){node=(cvox.DomUtil.directedNextSibling(node,r));}}
while(cvox.DomUtil.directedFirstChild(node,r)&&!isLeaf(node)){node=(cvox.DomUtil.directedFirstChild(node,r));}
if(node==document.body){return null;}
return node;};cvox.DomUtil.directedNextLeafNode=function(node,reverse){reverse=!!reverse;return cvox.DomUtil.directedNextLeafLikeNode(node,reverse,cvox.DomUtil.isLeafNode);};cvox.DomUtil.previousLeafNode=function(node){return cvox.DomUtil.directedNextLeafNode(node,true);};cvox.DomUtil.directedFindFirstNode=function(node,r,pred){var child=cvox.DomUtil.directedFirstChild(node,r);while(child){if(pred(child)){return child;}else{var leaf=cvox.DomUtil.directedFindFirstNode(child,r,pred);if(leaf){return leaf;}}
child=cvox.DomUtil.directedNextSibling(child,r);}
return null;};cvox.DomUtil.directedFindDeepestNode=function(node,r,pred){var next=cvox.DomUtil.directedFindFirstNode(node,r,pred);if(!next){if(pred(node)){return node;}else{return null;}}else{return cvox.DomUtil.directedFindDeepestNode(next,r,pred);}};cvox.DomUtil.directedFindNextNode=function(node,ancestor,r,pred,above,deep){above=!!above;deep=!!deep;if(!cvox.DomUtil.isDescendantOfNode(node,ancestor)||node==ancestor){return null;}
var next=cvox.DomUtil.directedNextSibling(node,r);while(next){if(!deep&&pred(next)){return next;}
var leaf=(deep?cvox.DomUtil.directedFindDeepestNode:cvox.DomUtil.directedFindFirstNode)(next,r,pred);if(leaf){return leaf;}
if(deep&&pred(next)){return next;}
next=cvox.DomUtil.directedNextSibling(next,r);}
var parent=(node.parentNode);if(above&&pred(parent)){return parent;}
return cvox.DomUtil.directedFindNextNode(parent,ancestor,r,pred,above,deep);};cvox.DomUtil.getControlValueAndStateString=function(control){var parentControl=cvox.DomUtil.getSurroundingControl(control);if(parentControl){return cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(control)+' '+
cvox.DomUtil.getName(control)+' '+
cvox.DomUtil.getState(control,true));}else{return cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(control)+' '+
cvox.DomUtil.getState(control,true));}};cvox.DomUtil.isInternalLink=function(node){if(node.nodeType==1){var href=node.getAttribute('href');if(href&&href.indexOf('#')!=-1){var path=href.split('#')[0];return path==''||path==window.location.pathname;}}
return false;};cvox.DomUtil.getLinkURL=function(node){if(node.tagName=='A'){if(node.getAttribute('href')){if(cvox.DomUtil.isInternalLink(node)){return Msgs.getMsg('internal_link');}else{return node.getAttribute('href');}}else{return'';}}else if(cvox.AriaUtil.getRoleName(node)==Msgs.getMsg('role_link')){return Msgs.getMsg('unknown_link');}
return'';};cvox.DomUtil.getContainingTable=function(node,kwargs){var ancestors=cvox.DomUtil.getAncestors(node);return cvox.DomUtil.findTableNodeInList(ancestors,kwargs);};cvox.DomUtil.findTableNodeInList=function(nodes,kwargs){kwargs=kwargs||{allowCaptions:false};for(var i=nodes.length-1,node;node=nodes[i];i--){if(node.constructor!=Text){if(!kwargs.allowCaptions&&node.tagName=='CAPTION'){return null;}
if((node.tagName=='TABLE')||cvox.AriaUtil.isGrid(node)){return node;}}}
return null;};cvox.DomUtil.isLayoutTable=function(tableNode){if(tableNode.rows&&(tableNode.rows.length<=1||(tableNode.rows[0].childElementCount==1))){return true;}
if(cvox.AriaUtil.isGrid(tableNode)){return false;}
if(cvox.AriaUtil.isLandmark(tableNode)){return false;}
if(tableNode.caption||tableNode.summary){return false;}
if((cvox.XpathUtil.evalXPath('tbody/tr/th',tableNode).length>0)&&(cvox.XpathUtil.evalXPath('tbody/tr/td',tableNode).length>0)){return false;}
if(cvox.XpathUtil.evalXPath('colgroup',tableNode).length>0){return false;}
if((cvox.XpathUtil.evalXPath('thead',tableNode).length>0)||(cvox.XpathUtil.evalXPath('tfoot',tableNode).length>0)){return false;}
if((cvox.XpathUtil.evalXPath('tbody/tr/td/embed',tableNode).length>0)||(cvox.XpathUtil.evalXPath('tbody/tr/td/object',tableNode).length>0)||(cvox.XpathUtil.evalXPath('tbody/tr/td/iframe',tableNode).length>0)||(cvox.XpathUtil.evalXPath('tbody/tr/td/applet',tableNode).length>0)){return true;}
var points=0;if(!cvox.DomUtil.hasBorder(tableNode)){points++;}
if(tableNode.rows.length<=6){points++;}
if(cvox.DomUtil.countPreviousTags(tableNode)<=12){points++;}
if(cvox.XpathUtil.evalXPath('tbody/tr/td/table',tableNode).length>0){points++;}
return(points>=3);};cvox.DomUtil.countPreviousTags=function(node){var ancestors=cvox.DomUtil.getAncestors(node);return ancestors.length+cvox.DomUtil.countPreviousSiblings(node);};cvox.DomUtil.countPreviousSiblings=function(node){var count=0;var prev=node.previousSibling;while(prev!=null){if(prev.constructor!=Text){count++;}
prev=prev.previousSibling;}
return count;};cvox.DomUtil.hasBorder=function(tableNode){if(tableNode.frame){return(tableNode.frame.indexOf('void')==-1);}
if(tableNode.border){if(tableNode.border.length==1){return(tableNode.border!='0');}else{return(tableNode.border.slice(0,-2)!=0);}}
if(tableNode.style.borderStyle&&tableNode.style.borderStyle=='none'){return false;}
if(tableNode.style.borderWidth){return(tableNode.style.borderWidth.slice(0,-2)!=0);}
if(tableNode.style.borderColor){return true;}
return false;};cvox.DomUtil.getFirstLeafNode=function(){var node=document.body;while(node&&node.firstChild){node=node.firstChild;}
while(node&&!cvox.DomUtil.hasContent(node)){node=cvox.DomUtil.directedNextLeafNode(node);}
return node;};cvox.DomUtil.findNode=function(root,p){var rv=[];var found=cvox.DomUtil.findNodes_(root,p,rv,true,10000);return found?rv[0]:undefined;};cvox.DomUtil.countNodes=function(root,p){var rv=[];cvox.DomUtil.findNodes_(root,p,rv,false,10000);return rv.length;};cvox.DomUtil.findNodes_=function(root,p,rv,findOne,maxChildCount){if((root!=null)||(maxChildCount==0)){var child=root.firstChild;while(child){if(p(child)){rv.push(child);if(findOne){return true;}}
maxChildCount=maxChildCount-1;if(cvox.DomUtil.findNodes_(child,p,rv,findOne,maxChildCount)){return true;}
child=child.nextSibling;}}
return false;};cvox.DomUtil.toArray=function(nodeList){var nodeArray=[];for(var i=0;i<nodeList.length;i++){nodeArray.push(nodeList[i]);}
return nodeArray;};cvox.DomUtil.shallowChildlessClone=function(node,skipattrs){if(node.nodeName=='#text'){return document.createTextNode(node.nodeValue);}
if(node.nodeName=='#comment'){return document.createComment(node.nodeValue);}
var ret=document.createElement(node.nodeName);for(var i=0;i<node.attributes.length;++i){var attr=node.attributes[i];if(skipattrs&&skipattrs[attr.nodeName]){continue;}
ret.setAttribute(attr.nodeName,attr.nodeValue);}
return ret;};cvox.DomUtil.deepClone=function(node,skipattrs){var ret=cvox.DomUtil.shallowChildlessClone(node,skipattrs);for(var i=0;i<node.childNodes.length;++i){ret.appendChild(cvox.DomUtil.deepClone(node.childNodes[i],skipattrs));}
return ret;};cvox.DomUtil.directedFirstChild=function(node,reverse){if(reverse){return node.lastChild;}
return node.firstChild;};cvox.DomUtil.directedNextSibling=function(node,reverse){if(!node){return null;}
if(reverse){return node.previousSibling;}
return node.nextSibling;};cvox.DomUtil.createSimpleClickFunction=function(targetNode){var target=targetNode.cloneNode(true);return function(){cvox.DomUtil.clickElem(target,false,false);};};cvox.DomUtil.addNodeToHead=function(node,opt_id){if(opt_id&&document.getElementById(opt_id)){return;}
var p=document.head||document.body;p.appendChild(node);};cvox.DomUtil.getContainingMath=function(node){var ancestors=cvox.DomUtil.getAncestors(node);return cvox.DomUtil.findMathNodeInList(ancestors);};cvox.DomUtil.findMathNodeInList=function(nodes){for(var i=0,node;node=nodes[i];i++){if(cvox.DomUtil.isMath(node)){return node;}}
return null;};cvox.DomUtil.isMath=function(node){return cvox.DomUtil.isMathml(node)||cvox.DomUtil.isMathJax(node)||cvox.DomUtil.isMathImg(node)||cvox.AriaUtil.isMath(node);};cvox.DomUtil.ALT_MATH_CLASSES={tex:['tex','latex'],asciimath:['numberedequation','inlineformula','displayformula']};cvox.DomUtil.altMathQuerySelector=function(contentType){var classes=cvox.DomUtil.ALT_MATH_CLASSES[contentType];if(classes){return classes.map(function(x){return'img.'+x;}).join(', ');}
return'';};cvox.DomUtil.isMathImg=function(node){if(!node||!node.tagName||!node.className){return false;}
if(node.tagName!='IMG'){return false;}
for(var i=0,className;className=node.classList.item(i);i++){className=className.toLowerCase();if(cvox.DomUtil.ALT_MATH_CLASSES.tex.indexOf(className)!=-1||cvox.DomUtil.ALT_MATH_CLASSES.asciimath.indexOf(className)!=-1){return true;}}
return false;};cvox.DomUtil.isMathml=function(node){if(!node||!node.tagName){return false;}
return node.tagName.toLowerCase()=='math';};cvox.DomUtil.isMathJax=function(node){if(!node||!node.tagName||!node.className){return false;}
function isSpanWithClass(n,cl){return(n.tagName=='SPAN'&&n.className.split(' ').some(function(x){return x.toLowerCase()==cl;}));};if(isSpanWithClass(node,'math')){var ancestors=cvox.DomUtil.getAncestors(node);return ancestors.some(function(x){return isSpanWithClass(x,'mathjax');});}
return false;};cvox.DomUtil.getMathSpanId=function(jaxId){var node=document.getElementById(jaxId+'-Frame');if(node){var span=node.querySelector('span.math');if(span){return span.id;}}
return'';};cvox.DomUtil.hasLongDesc=function(node){if(node&&node.longDesc){return true;}
return false;};cvox.DomUtil.getNodeTagName=function(node){if(node.nodeType==Node.ELEMENT_NODE){return node.tagName;}
return'';};cvox.DomUtil.purgeNodes=function(nodes){return cvox.DomUtil.toArray(nodes).filter(function(node){return node.nodeType!=Node.TEXT_NODE||!node.textContent.match(/^\s+$/);});};cvox.DomUtil.elementToPoint=function(node){if(!node){return{x:0,y:0};}
if(node.constructor==Text){node=node.parentNode;}
var r=node.getBoundingClientRect();return{x:r.left+(r.width/2),y:r.top+(r.height/2)};};cvox.DomUtil.doesInputSupportSelection=function(node){return goog.isDef(node)&&node.tagName=='INPUT'&&node.type!='email'&&node.type!='number';};cvox.DomUtil.getHint=function(node){var desc='';if(node.hasAttribute){if(node.hasAttribute('aria-describedby')){var describedByIds=node.getAttribute('aria-describedby').split(' ');for(var describedById,i=0;describedById=describedByIds[i];i++){var describedNode=document.getElementById(describedById);if(describedNode){desc+=' '+cvox.DomUtil.getName(describedNode,true,true,true);}}}}
return desc;};goog.provide('cvox.ChromeVoxJSON');if(!cvox.ChromeVoxJSON){cvox.ChromeVoxJSON={};}
if(window.JSON&&window.JSON.toString()=='[object JSON]'){cvox.ChromeVoxJSON=window.JSON;}else{(function(){function f(n){return n<10?'0'+n:n;}
if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){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(key){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){k=rep[i];if(typeof k==='string'){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.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 cvox.ChromeVoxJSON.stringify!=='function'){cvox.ChromeVoxJSON.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 cvox.ChromeVoxJSON.parse!=='function'){cvox.ChromeVoxJSON.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.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');};}}());}
goog.provide('cvox.Interframe');goog.require('cvox.ChromeVoxJSON');goog.require('cvox.DomUtil');cvox.Interframe=function(){};cvox.Interframe.IF_MSG_PREFIX='cvox.INTERFRAME:';cvox.Interframe.SET_ID='cvox.INTERFRAME_SET_ID';cvox.Interframe.ACK_SET_ID='cvox.INTERFRAME_ACK_SET_ID';cvox.Interframe.id;cvox.Interframe.listeners=[];cvox.Interframe.idToCallback_={};cvox.Interframe.allowAccessToIframeContentWindow=true;cvox.Interframe.init=function(){cvox.Interframe.messageListener=function(event){if(typeof event.data==='string'&&event.data.startsWith(cvox.Interframe.IF_MSG_PREFIX)){var suffix=event.data.substr(cvox.Interframe.IF_MSG_PREFIX.length);var message=(cvox.ChromeVoxJSON.parse(suffix));if(message['command']==cvox.Interframe.SET_ID){cvox.Interframe.id=message['id'];message['command']=cvox.Interframe.ACK_SET_ID;cvox.Interframe.sendMessageToParentWindow(message);}else if(message['command']==cvox.Interframe.ACK_SET_ID){cvox.Interframe.id=message['id'];var callback=cvox.Interframe.idToCallback_[cvox.Interframe.id];callback();}
for(var i=0,listener;listener=cvox.Interframe.listeners[i];i++){listener(message);}}
return false;};window.addEventListener('message',cvox.Interframe.messageListener,true);};cvox.Interframe.shutdown=function(){window.removeEventListener('message',cvox.Interframe.messageListener,true);};cvox.Interframe.addListener=function(listener){cvox.Interframe.listeners.push(listener);};cvox.Interframe.sendMessageToWindow=function(message,window){var encodedMessage=cvox.Interframe.IF_MSG_PREFIX+
cvox.ChromeVoxJSON.stringify(message,null,null);window.postMessage(encodedMessage,'*');};cvox.Interframe.sendMessageToIFrame=function(message,iframe){if(cvox.Interframe.allowAccessToIframeContentWindow&&iframe.contentWindow){cvox.Interframe.sendMessageToWindow(message,iframe.contentWindow);return;}
var encodedMessage=cvox.Interframe.IF_MSG_PREFIX+
cvox.ChromeVoxJSON.stringify(message,null,null);var script=document.createElement('script');script.type='text/javascript';if(iframe.hasAttribute('id')&&document.getElementById(iframe.id)==iframe){script.innerHTML='document.getElementById(decodeURI(\''+
encodeURI(iframe.id)+'\')).contentWindow.postMessage(decodeURI(\''+
encodeURI(encodedMessage)+'\'), \'*\');';}else{var styleName='cvox_iframe'+message['id'];if(iframe.className===''){iframe.className=styleName;}else if(iframe.className.indexOf(styleName)==-1){iframe.className+=' '+styleName;}
script.innerHTML='document.getElementsByClassName(decodeURI(\''+
encodeURI(styleName)+'\'))[0].contentWindow.postMessage(decodeURI(\''+
encodeURI(encodedMessage)+'\'), \'*\');';}
document.head.appendChild(script);window.setTimeout(function(){document.head.removeChild(script);},1000);};cvox.Interframe.sendMessageToParentWindow=function(message){if(!cvox.Interframe.isIframe()){return;}
message['sourceId']=cvox.Interframe.id;if(window.parent){cvox.Interframe.sendMessageToWindow(message,window.parent);return;}
var encodedMessage=cvox.Interframe.IF_MSG_PREFIX+
cvox.ChromeVoxJSON.stringify(message,null,null);window.location.href='javascript:window.parent.postMessage(\''+
encodeURI(encodedMessage)+'\', \'*\');';};cvox.Interframe.sendIdToIFrame=function(id,iframe,opt_callback){if(opt_callback){cvox.Interframe.idToCallback_[id]=opt_callback;}
var message={'command':cvox.Interframe.SET_ID,'id':id};cvox.Interframe.sendMessageToIFrame(message,iframe);};cvox.Interframe.isIframe=function(){return(window!=window.parent);};cvox.Interframe.init();goog.provide('cvox.SelectionUtil');goog.require('cvox.DomUtil');goog.require('cvox.XpathUtil');cvox.SelectionUtil=function(){};cvox.SelectionUtil.cleanUpParagraphForward=function(sel){var expand=true;while(sel.focusNode.nodeType==3){var fnode=sel.focusNode;var foffset=sel.focusOffset;sel.modify('extend','forward','sentence');if((fnode==sel.focusNode)&&(foffset==sel.focusOffset)){return false;}}
return true;};cvox.SelectionUtil.cleanUpParagraphBack=function(sel){var expand=true;var fnode;var foffset;while(sel.focusNode.nodeType==3){fnode=sel.focusNode;foffset=sel.focusOffset;sel.modify('extend','backward','sentence');if((fnode==sel.focusNode)&&(foffset==sel.focusOffset)){return true;}}
return true;};cvox.SelectionUtil.cleanUpSentence=function(sel){var expand=true;var lastSelection;var lastSelectionOffset;while(expand){if(sel.focusNode.nodeType==3){var fnode=sel.focusNode;var foffset=sel.focusOffset;if(sel.rangeCount>0&&sel.getRangeAt(0).endOffset>0){if(fnode.substringData(sel.getRangeAt(0).endOffset-1,1)=='.'){return true;}else if(fnode.substringData(sel.getRangeAt(0).endOffset-1,1)==' '){return true;}else{sel.modify('extend','forward','sentence');if((fnode==sel.focusNode)&&(foffset==sel.focusOffset)){return false;}}}else{return true;}}else{return true;}}
return true;};cvox.SelectionUtil.findSelPosition=function(sel){if(sel.rangeCount==0){return[0,0];}
var clientRect=sel.getRangeAt(0).getBoundingClientRect();if(!clientRect){return[0,0];}
var top=window.pageYOffset+clientRect.top;var left=window.pageXOffset+clientRect.left;return[top,left];};cvox.SelectionUtil.findTopLeftPosition=function(targetNode){var left=0;var top=0;var obj=targetNode;if(obj.offsetParent){left=obj.offsetLeft;top=obj.offsetTop;obj=obj.offsetParent;while(obj!==null){left+=obj.offsetLeft;top+=obj.offsetTop;obj=obj.offsetParent;}}
return[top,left];};cvox.SelectionUtil.isSelectionValid=function(sel){var regExpWhiteSpace=new RegExp(/^\s+$/);return(!((regExpWhiteSpace.test(sel.toString()))||(sel.toString()=='')));};cvox.SelectionUtil.isRangeValid=function(range){var text=range.cloneContents().textContent;var regExpWhiteSpace=new RegExp(/^\s+$/);return(!((regExpWhiteSpace.test(text))||(text=='')));};cvox.SelectionUtil.findPos_=function(node){var curLeft=0;var curTop=0;if(node.offsetParent){do{curLeft+=node.offsetLeft;curTop+=node.offsetTop;}while(node=node.offsetParent);}
return[curLeft,curTop];};cvox.SelectionUtil.scrollElementsToView=function(focusNode){while(focusNode&&!focusNode.getBoundingClientRect){focusNode=focusNode.parentElement;}
if(!focusNode){return;}
var node=focusNode;var parentNode=node.parentElement;while(node!=document.body&&parentNode){node.scrollTop=node.offsetTop;node.scrollLeft=node.offsetLeft;node=parentNode;parentNode=node.parentElement;}
var pos=cvox.SelectionUtil.findPos_(focusNode);window.scrollTo(pos[0]-window.innerWidth/2,pos[1]-window.innerHeight/2);};cvox.SelectionUtil.scrollToSelection=function(sel){if(sel.rangeCount==0){return;}
cvox.SelectionUtil.scrollElementsToView(sel.focusNode);var pos=cvox.SelectionUtil.findSelPosition(sel);var top=pos[0];var left=pos[1];var scrolledVertically=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop;var pageHeight=window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight;var pageWidth=window.innerWidth||document.documentElement.innerWidth||document.body.clientWidth;if(left<pageWidth){left=0;}
if((scrolledVertically+pageHeight)<top){var diff=top-pageHeight;window.scroll(left,diff+100);}else if(top<scrolledVertically){window.scroll(left,top-100);}};cvox.SelectionUtil.isAllWs=function(node){return!(/[^\t\n\r ]/.test(node.data));};cvox.SelectionUtil.isIgnorable=function(node){return(node.nodeType==8)||((node.nodeType==3)&&cvox.SelectionUtil.isAllWs(node));};cvox.SelectionUtil.nodeBefore=function(sib){while((sib=sib.previousSibling)){if(!cvox.SelectionUtil.isIgnorable(sib)){return sib;}}
return null;};cvox.SelectionUtil.nodeAfter=function(sib){while((sib=sib.nextSibling)){if(!cvox.SelectionUtil.isIgnorable(sib)){return sib;}}
return null;};cvox.SelectionUtil.lastChildNode=function(par){var res=par.lastChild;while(res){if(!cvox.SelectionUtil.isIgnorable(res)){return res;}
res=res.previousSibling;}
return null;};cvox.SelectionUtil.firstChildNode=function(par){var res=par.firstChild;while(res){if(!cvox.SelectionUtil.isIgnorable(res)){return res;}
res=res.nextSibling;}
return null;};cvox.SelectionUtil.dataOf=function(txt){var data=txt.data;data=data.replace(/[\t\n\r ]+/g,' ');if(data.charAt(0)==' '){data=data.substring(1,data.length);}
if(data.charAt(data.length-1)==' '){data=data.substring(0,data.length-1);}
return data;};cvox.SelectionUtil.hasContentWithTag=function(sel,tagName){if(!sel||!sel.anchorNode||!sel.focusNode){return false;}
if(sel.anchorNode.tagName&&(sel.anchorNode.tagName==tagName)){return true;}
if(sel.focusNode.tagName&&(sel.focusNode.tagName==tagName)){return true;}
if(sel.anchorNode.parentNode.tagName&&(sel.anchorNode.parentNode.tagName==tagName)){return true;}
if(sel.focusNode.parentNode.tagName&&(sel.focusNode.parentNode.tagName==tagName)){return true;}
var docFrag=sel.getRangeAt(0).cloneContents();var span=document.createElement('span');span.appendChild(docFrag);return(span.getElementsByTagName(tagName).length>0);};cvox.SelectionUtil.selectText=function(textNode,start,end){var newRange=document.createRange();newRange.setStart(textNode,start);newRange.setEnd(textNode,end);var sel=window.getSelection();sel.removeAllRanges();sel.addRange(newRange);};cvox.SelectionUtil.selectAllTextInNode=function(node){var newRange=document.createRange();newRange.setStart(node,0);newRange.setEndAfter(node);var sel=window.getSelection();sel.removeAllRanges();sel.addRange(newRange);};cvox.SelectionUtil.collapseToStart=function(node){var sel=window.getSelection();var cursorNode=sel.anchorNode;var cursorOffset=sel.anchorOffset;if(cursorNode==null){cursorNode=node;cursorOffset=0;}
var newRange=document.createRange();newRange.setStart(cursorNode,cursorOffset);newRange.setEnd(cursorNode,cursorOffset);sel.removeAllRanges();sel.addRange(newRange);};cvox.SelectionUtil.collapseToEnd=function(node){var sel=window.getSelection();var cursorNode=sel.focusNode;var cursorOffset=sel.focusOffset;if(cursorNode==null){cursorNode=node;cursorOffset=0;}
var newRange=document.createRange();newRange.setStart(cursorNode,cursorOffset);newRange.setEnd(cursorNode,cursorOffset);sel.removeAllRanges();sel.addRange(newRange);};cvox.SelectionUtil.getText=function(){var sel=window.getSelection();if(cvox.SelectionUtil.hasContentWithTag(sel,'IMG')){var text='';var docFrag=sel.getRangeAt(0).cloneContents();var span=document.createElement('span');span.appendChild(docFrag);var leafNodes=cvox.XpathUtil.getLeafNodes(span);for(var i=0,node;node=leafNodes[i];i++){text=text+' '+cvox.DomUtil.getName(node);}
return text;}else{return this.getSelectionText_();}};cvox.SelectionUtil.getSelectionText_=function(){return''+window.getSelection();};cvox.SelectionUtil.getRangeText=function(range){if(range)
return range.cloneContents().textContent.replace(/\s+/g,' ');else
return'';};goog.provide('cvox.Cursor');cvox.Cursor=function(node,index,text){this.node=node;this.index=index;this.text=text;};cvox.Cursor.prototype.clone=function(){return new cvox.Cursor(this.node,this.index,this.text);};cvox.Cursor.prototype.copyFrom=function(otherCursor){this.node=otherCursor.node;this.index=otherCursor.index;this.text=otherCursor.text;};cvox.Cursor.prototype.equals=function(rhs){return this.node==rhs.node&&this.index==rhs.index&&this.text==rhs.text;};goog.provide('cvox.TraverseUtil');goog.require('cvox.Cursor');goog.require('cvox.DomPredicates');goog.require('cvox.DomUtil');cvox.TraverseUtil=function(){};cvox.TraverseUtil.getNodeText=function(node){if(node.constructor==Text){return node.data;}else{return'';}};cvox.TraverseUtil.treatAsLeafNode=function(node){return node.childNodes.length==0||node.nodeName=='SELECT'||node.getAttribute('role')=='listbox'||node.nodeName=='OBJECT';};cvox.TraverseUtil.isWhitespace=function(c){return(c==' '||c=='\n'||c=='\r'||c=='\t');};cvox.TraverseUtil.setSelection=function(start,end){var sel=window.getSelection();sel.removeAllRanges();var range=document.createRange();range.setStart(start.node,start.index);range.setEnd(end.node,end.index);sel.addRange(range);return sel;};cvox.TraverseUtil.isHidden=function(node){if(node instanceof HTMLElement&&node.getAttribute('aria-hidden')=='true'){return true;}
switch(node.tagName){case'SCRIPT':case'NOSCRIPT':return true;}
return false;};cvox.TraverseUtil.forwardsChar=function(cursor,elementsEntered,elementsLeft){while(true){var childNode=null;if(!cvox.TraverseUtil.treatAsLeafNode(cursor.node)){for(var i=cursor.index;i<cursor.node.childNodes.length;i++){var node=cursor.node.childNodes[i];if(cvox.TraverseUtil.isHidden(node)){if(node instanceof HTMLElement){elementsEntered.push(node);}
continue;}
if(cvox.DomUtil.isVisible(node,{checkAncestors:false})){childNode=node;break;}}}
if(childNode){cursor.node=childNode;cursor.index=0;cursor.text=cvox.TraverseUtil.getNodeText(cursor.node);if(cursor.node instanceof HTMLElement){elementsEntered.push(cursor.node);}
continue;}
if(cursor.index<cursor.text.length)
return cursor.text[cursor.index++];while(cursor.node!=null){var siblingNode=null;for(var node=cursor.node.nextSibling;node!=null;node=node.nextSibling){if(cvox.TraverseUtil.isHidden(node)){if(node instanceof HTMLElement){elementsEntered.push(node);}
continue;}
if(cvox.DomUtil.isVisible(node,{checkAncestors:false})){siblingNode=node;break;}}
if(siblingNode){if(cursor.node instanceof HTMLElement){elementsLeft.push(cursor.node);}
cursor.node=siblingNode;cursor.text=cvox.TraverseUtil.getNodeText(siblingNode);cursor.index=0;if(cursor.node instanceof HTMLElement){elementsEntered.push(cursor.node);}
break;}
if(cursor.node.parentNode&&cursor.node.parentNode.constructor!=HTMLBodyElement){if(cursor.node instanceof HTMLElement){elementsLeft.push(cursor.node);}
cursor.node=cursor.node.parentNode;cursor.text=null;cursor.index=0;}else{return null;}}}};cvox.TraverseUtil.backwardsChar=function(cursor,elementsEntered,elementsLeft){while(true){var childNode=null;if(!cvox.TraverseUtil.treatAsLeafNode(cursor.node)){for(var i=cursor.index-1;i>=0;i--){var node=cursor.node.childNodes[i];if(cvox.TraverseUtil.isHidden(node)){if(node instanceof HTMLElement){elementsEntered.push(node);}
continue;}
if(cvox.DomUtil.isVisible(node,{checkAncestors:false})){childNode=node;break;}}}
if(childNode){cursor.node=childNode;cursor.text=cvox.TraverseUtil.getNodeText(cursor.node);if(cursor.text.length)
cursor.index=cursor.text.length;else
cursor.index=cursor.node.childNodes.length;if(cursor.node instanceof HTMLElement){elementsEntered.push(cursor.node);}
continue;}
if(cursor.text.length>0&&cursor.index>0){return cursor.text[--cursor.index];}
while(true){var siblingNode=null;for(var node=cursor.node.previousSibling;node!=null;node=node.previousSibling){if(cvox.TraverseUtil.isHidden(node)){if(node instanceof HTMLElement){elementsEntered.push(node);}
continue;}
if(cvox.DomUtil.isVisible(node,{checkAncestors:false})){siblingNode=node;break;}}
if(siblingNode){if(cursor.node instanceof HTMLElement){elementsLeft.push(cursor.node);}
cursor.node=siblingNode;cursor.text=cvox.TraverseUtil.getNodeText(siblingNode);if(cursor.text.length)
cursor.index=cursor.text.length;else
cursor.index=cursor.node.childNodes.length;if(cursor.node instanceof HTMLElement){elementsEntered.push(cursor.node);}
break;}
if(cursor.node.parentNode&&cursor.node.parentNode.constructor!=HTMLBodyElement){if(cursor.node instanceof HTMLElement){elementsLeft.push(cursor.node);}
cursor.node=cursor.node.parentNode;cursor.text=null;cursor.index=0;}else{return null;}}}};cvox.TraverseUtil.getNextChar=function(startCursor,endCursor,elementsEntered,elementsLeft,skipWhitespace){startCursor.copyFrom(endCursor);var c=cvox.TraverseUtil.forwardsChar(endCursor,elementsEntered,elementsLeft);if(c==null)
return null;var initialWhitespace=cvox.TraverseUtil.isWhitespace(c);while((cvox.TraverseUtil.isWhitespace(c))||(cvox.TraverseUtil.isHidden(endCursor.node))){c=cvox.TraverseUtil.forwardsChar(endCursor,elementsEntered,elementsLeft);if(c==null)
return null;}
if(skipWhitespace||!initialWhitespace){startCursor.copyFrom(endCursor);startCursor.index--;return c;}
else{for(var i=0;i<elementsEntered.length;i++){if(cvox.TraverseUtil.isHidden(elementsEntered[i])){endCursor.index--;startCursor.copyFrom(endCursor);startCursor.index--;return' ';}}
endCursor.index--;return' ';}};cvox.TraverseUtil.getPreviousChar=function(startCursor,endCursor,elementsEntered,elementsLeft,skipWhitespace){endCursor.copyFrom(startCursor);var c=cvox.TraverseUtil.backwardsChar(startCursor,elementsEntered,elementsLeft);if(c==null)
return null;var initialWhitespace=cvox.TraverseUtil.isWhitespace(c);while((cvox.TraverseUtil.isWhitespace(c))||(cvox.TraverseUtil.isHidden(startCursor.node))){c=cvox.TraverseUtil.backwardsChar(startCursor,elementsEntered,elementsLeft);if(c==null)
return null;}
if(skipWhitespace||!initialWhitespace){endCursor.copyFrom(startCursor);endCursor.index++;return c;}else{for(var i=0;i<elementsEntered.length;i++){if(cvox.TraverseUtil.isHidden(elementsEntered[i])){startCursor.index++;endCursor.copyFrom(startCursor);endCursor.index++;return' ';}}
startCursor.index++;return' ';}};cvox.TraverseUtil.getNextWord=function(startCursor,endCursor,elementsEntered,elementsLeft){var cursor=endCursor.clone();var c=cvox.TraverseUtil.forwardsChar(cursor,elementsEntered,elementsLeft);if(c==null)
return null;while((cvox.TraverseUtil.isWhitespace(c))||(cvox.TraverseUtil.isHidden(cursor.node))){c=cvox.TraverseUtil.forwardsChar(cursor,elementsEntered,elementsLeft);if(c==null)
return null;}
startCursor.copyFrom(cursor);startCursor.index--;endCursor.copyFrom(cursor);var word=c;var newEntered=[];var newLeft=[];c=cvox.TraverseUtil.forwardsChar(cursor,newEntered,newLeft);if(c==null){return word;}
while(!cvox.TraverseUtil.isWhitespace(c)&&newEntered.length==0&&newLeft==0){word+=c;endCursor.copyFrom(cursor);c=cvox.TraverseUtil.forwardsChar(cursor,newEntered,newLeft);if(c==null){return word;}}
return word;};cvox.TraverseUtil.getPreviousWord=function(startCursor,endCursor,elementsEntered,elementsLeft){var cursor=startCursor.clone();var c=cvox.TraverseUtil.backwardsChar(cursor,elementsEntered,elementsLeft);if(c==null)
return null;while((cvox.TraverseUtil.isWhitespace(c)||(cvox.TraverseUtil.isHidden(cursor.node)))){c=cvox.TraverseUtil.backwardsChar(cursor,elementsEntered,elementsLeft);if(c==null)
return null;}
endCursor.copyFrom(cursor);endCursor.index++;startCursor.copyFrom(cursor);var word=c;var newEntered=[];var newLeft=[];c=cvox.TraverseUtil.backwardsChar(cursor,newEntered,newLeft);if(c==null)
return word;while(!cvox.TraverseUtil.isWhitespace(c)&&newEntered.length==0&&newLeft.length==0){word=c+word;startCursor.copyFrom(cursor);c=cvox.TraverseUtil.backwardsChar(cursor,newEntered,newLeft);if(c==null)
return word;}
return word;};cvox.TraverseUtil.includesBreakTagOrSkippedNode=function(elementsEntered,elementsLeft,breakTags){for(var i=0;i<elementsEntered.length;i++){if(cvox.TraverseUtil.isHidden(elementsEntered[i])){return true;}
var style=window.getComputedStyle(elementsEntered[i],null);if((style&&style.display!='inline')||breakTags[elementsEntered[i].tagName]){return true;}}
for(i=0;i<elementsLeft.length;i++){var style=window.getComputedStyle(elementsLeft[i],null);if((style&&style.display!='inline')||breakTags[elementsLeft[i].tagName]){return true;}}
return false;};cvox.TraverseUtil.getNextSentence=function(startCursor,endCursor,elementsEntered,elementsLeft,breakTags){return cvox.TraverseUtil.getNextString(startCursor,endCursor,elementsEntered,elementsLeft,function(str,word,elementsEntered,elementsLeft){if(str.substr(-1)=='.')
return true;return cvox.TraverseUtil.includesBreakTagOrSkippedNode(elementsEntered,elementsLeft,breakTags);});};cvox.TraverseUtil.getPreviousSentence=function(startCursor,endCursor,elementsEntered,elementsLeft,breakTags){return cvox.TraverseUtil.getPreviousString(startCursor,endCursor,elementsEntered,elementsLeft,function(str,word,elementsEntered,elementsLeft){if(word.substr(-1)=='.')
return true;return cvox.TraverseUtil.includesBreakTagOrSkippedNode(elementsEntered,elementsLeft,breakTags);});};cvox.TraverseUtil.getNextLine=function(startCursor,endCursor,elementsEntered,elementsLeft,breakTags){var range=document.createRange();var currentRect=null;var rightMostRect=null;var prevCursor=endCursor.clone();return cvox.TraverseUtil.getNextString(startCursor,endCursor,elementsEntered,elementsLeft,function(str,word,elementsEntered,elementsLeft){range.setStart(startCursor.node,startCursor.index);range.setEnd(endCursor.node,endCursor.index);var currentRect=range.getBoundingClientRect();if(!rightMostRect){rightMostRect=currentRect;}
if(currentRect.bottom!=rightMostRect.bottom&&!cvox.DomPredicates.linkPredicate(cvox.DomUtil.getAncestors(endCursor.node))){endCursor.copyFrom(prevCursor);return true;}
rightMostRect=currentRect;prevCursor.copyFrom(endCursor);return cvox.TraverseUtil.includesBreakTagOrSkippedNode(elementsEntered,elementsLeft,breakTags);});};cvox.TraverseUtil.getPreviousLine=function(startCursor,endCursor,elementsEntered,elementsLeft,breakTags){var range=document.createRange();var currentRect=null;var leftMostRect=null;var prevCursor=startCursor.clone();return cvox.TraverseUtil.getPreviousString(startCursor,endCursor,elementsEntered,elementsLeft,function(str,word,elementsEntered,elementsLeft){range.setStart(startCursor.node,startCursor.index);range.setEnd(endCursor.node,endCursor.index);var currentRect=range.getBoundingClientRect();if(!leftMostRect){leftMostRect=currentRect;}
if(currentRect.top!=leftMostRect.top&&!cvox.DomPredicates.linkPredicate(cvox.DomUtil.getAncestors(startCursor.node))){startCursor.copyFrom(prevCursor);return true;}
leftMostRect=currentRect;prevCursor.copyFrom(startCursor);return cvox.TraverseUtil.includesBreakTagOrSkippedNode(elementsEntered,elementsLeft,breakTags);});};cvox.TraverseUtil.getNextParagraph=function(startCursor,endCursor,elementsEntered,elementsLeft){return cvox.TraverseUtil.getNextString(startCursor,endCursor,elementsEntered,elementsLeft,function(str,word,elementsEntered,elementsLeft){for(var i=0;i<elementsEntered.length;i++){if(cvox.TraverseUtil.isHidden(elementsEntered[i])){return true;}
var style=window.getComputedStyle(elementsEntered[i],null);if(style&&style.display!='inline'){return true;}}
for(i=0;i<elementsLeft.length;i++){var style=window.getComputedStyle(elementsLeft[i],null);if(style&&style.display!='inline'){return true;}}
return false;});};cvox.TraverseUtil.getPreviousParagraph=function(startCursor,endCursor,elementsEntered,elementsLeft){return cvox.TraverseUtil.getPreviousString(startCursor,endCursor,elementsEntered,elementsLeft,function(str,word,elementsEntered,elementsLeft){for(var i=0;i<elementsEntered.length;i++){if(cvox.TraverseUtil.isHidden(elementsEntered[i])){return true;}
var style=window.getComputedStyle(elementsEntered[i],null);if(style&&style.display!='inline'){return true;}}
for(i=0;i<elementsLeft.length;i++){var style=window.getComputedStyle(elementsLeft[i],null);if(style&&style.display!='inline'){return true;}}
return false;});};cvox.TraverseUtil.getNextString=function(startCursor,endCursor,elementsEntered,elementsLeft,breakBefore){var wordStartCursor=endCursor.clone();var wordEndCursor=endCursor.clone();var newEntered=[];var newLeft=[];var str='';var word=cvox.TraverseUtil.getNextWord(wordStartCursor,wordEndCursor,newEntered,newLeft);if(word==null)
return null;startCursor.copyFrom(wordStartCursor);while(!str||!breakBefore(str,word,newEntered,newLeft)){if(str)
str+=' ';str+=word;elementsEntered=elementsEntered.concat(newEntered);elementsLeft=elementsLeft.concat(newLeft);endCursor.copyFrom(wordEndCursor);newEntered=[];newLeft=[];word=cvox.TraverseUtil.getNextWord(wordStartCursor,wordEndCursor,newEntered,newLeft);if(word==null)
return str;}
return str;};cvox.TraverseUtil.getPreviousString=function(startCursor,endCursor,elementsEntered,elementsLeft,breakBefore){var wordStartCursor=startCursor.clone();var wordEndCursor=startCursor.clone();var newEntered=[];var newLeft=[];var str='';var word=cvox.TraverseUtil.getPreviousWord(wordStartCursor,wordEndCursor,newEntered,newLeft);if(word==null)
return null;endCursor.copyFrom(wordEndCursor);while(!str||!breakBefore(str,word,newEntered,newLeft)){if(str)
str=' '+str;str=word+str;elementsEntered=elementsEntered.concat(newEntered);elementsLeft=elementsLeft.concat(newLeft);startCursor.copyFrom(wordStartCursor);newEntered=[];newLeft=[];word=cvox.TraverseUtil.getPreviousWord(wordStartCursor,wordEndCursor,newEntered,newLeft);if(word==null)
return str;}
return str;};goog.provide('cvox.CursorSelection');goog.require('cvox.Cursor');goog.require('cvox.SelectionUtil');goog.require('cvox.TraverseUtil');cvox.CursorSelection=function(start,end,opt_reverse){this.start=start.clone();this.end=end.clone();if(opt_reverse==undefined){opt_reverse=false;}
this.isReversed_=opt_reverse;if((this.isReversed_&&this.start.node.compareDocumentPosition(this.end.node)==cvox.CursorSelection.BEFORE)||(!this.isReversed_&&this.end.node.compareDocumentPosition(this.start.node)==cvox.CursorSelection.BEFORE)){var oldStart=this.start;this.start=this.end;this.end=oldStart;}};cvox.CursorSelection.BEFORE=4;cvox.CursorSelection.prototype.setReversed=function(reversed){if(reversed==this.isReversed_){return this;}
var oldStart=this.start;this.start=this.end;this.end=oldStart;this.isReversed_=reversed;return this;};cvox.CursorSelection.prototype.isReversed=function(){return this.isReversed_;};cvox.CursorSelection.prototype.absStart=function(){return this.isReversed_?this.end:this.start;};cvox.CursorSelection.prototype.absEnd=function(){return this.isReversed_?this.start:this.end;};cvox.CursorSelection.prototype.clone=function(){return new cvox.CursorSelection(this.start,this.end,this.isReversed_);};cvox.CursorSelection.prototype.select=function(){var sel=window.getSelection();sel.removeAllRanges();this.normalize();sel.addRange(this.getRange());};cvox.CursorSelection.fromNode=function(node){if(!node){return null;}
var text=cvox.TraverseUtil.getNodeText(node);return new cvox.CursorSelection(new cvox.Cursor(node,0,text),new cvox.Cursor(node,0,text));};cvox.CursorSelection.fromBody=function(){return(cvox.CursorSelection.fromNode(document.body));};cvox.CursorSelection.prototype.getText=function(){if(this.start.equals(this.end)){return cvox.TraverseUtil.getNodeText(this.start.node);}
return cvox.SelectionUtil.getRangeText(this.getRange());};cvox.CursorSelection.prototype.getRange=function(){var range=document.createRange();if(this.isReversed_){range.setStart(this.end.node,this.end.index);range.setEnd(this.start.node,this.start.index);}else{range.setStart(this.start.node,this.start.index);range.setEnd(this.end.node,this.end.index);}
return range;};cvox.CursorSelection.prototype.equals=function(rhs){return this.start.equals(rhs.start)&&this.end.equals(rhs.end);};cvox.CursorSelection.prototype.absEquals=function(rhs){return((this.start.equals(rhs.start)&&this.end.equals(rhs.end))||(this.end.equals(rhs.start)&&this.start.equals(rhs.end)));};cvox.CursorSelection.prototype.directedBefore=function(rhs){var leftToRight=this.start.node.compareDocumentPosition(rhs.start.node)==cvox.CursorSelection.BEFORE;return this.start.node==rhs.start.node||(this.isReversed()?!leftToRight:leftToRight);};cvox.CursorSelection.prototype.normalize=function(){if(this.absEnd().index==0&&this.absEnd().node){var node=this.absEnd().node;var testRange=document.createRange();testRange.selectNodeContents(node);this.absEnd().index=testRange.endOffset;}
return this;};cvox.CursorSelection.prototype.collapse=function(){if(this.start.equals(this.end)){return this;}
this.end.copyFrom(this.start);if(this.start.text.length==0){return this;}
if(this.isReversed()){if(this.end.index>0){this.end.index--;}}else{if(this.end.index<this.end.text.length){this.end.index++;}}
return this;};goog.provide('cvox.NavDescription');goog.require('cvox.AbstractTts');goog.require('cvox.ChromeVox');goog.require('cvox.CursorSelection');goog.require('cvox.QueueMode');cvox.NavDescription=function(kwargs){this.context=kwargs.context?kwargs.context:'';this.text=kwargs.text?kwargs.text:'';this.userValue=kwargs.userValue?kwargs.userValue:'';this.annotation=kwargs.annotation?kwargs.annotation:'';this.earcons=kwargs.earcons?kwargs.earcons:[];this.personality=kwargs.personality;this.hint=kwargs.hint?kwargs.hint:'';this.category=kwargs.category?kwargs.category:null;};cvox.NavDescription.prototype.isEmpty=function(){return(this.context.length==0&&this.earcons.length==0&&this.text.length==0&&this.userValue.length==0&&this.annotation.length==0);};cvox.NavDescription.prototype.toString=function(){return'NavDescription(context="'+this.context+'" '+' text="'+this.text+'" '+' userValue="'+this.userValue+'" '+' annotation="'+this.annotation+
(this.category?'" category="'+this.category+'")':'')+'")';};cvox.NavDescription.prototype.pushEarcon=function(earconId){this.earcons.push(earconId);};cvox.NavDescription.prototype.speak=function(queueMode,opt_startCallback,opt_endCallback){function makeAnnotationProps(){var properties={};var src=cvox.AbstractTts.PERSONALITY_ANNOTATION;for(var key in src){properties[key]=src[key];}
return properties;}
var speakArgs=new Array();if(this.context){speakArgs.push([this.context,queueMode,makeAnnotationProps()]);queueMode=cvox.QueueMode.QUEUE;}
speakArgs.push([this.text,queueMode,this.personality?this.personality:{}]);queueMode=cvox.QueueMode.QUEUE;if(this.userValue){speakArgs.push([this.userValue,queueMode,{}]);}
if(this.annotation){speakArgs.push([this.annotation,queueMode,makeAnnotationProps()]);}
if(this.hint){speakArgs.push([this.hint,queueMode,makeAnnotationProps()]);}
var length=speakArgs.length;for(var i=0;i<length;i++){if(i==0&&opt_startCallback){speakArgs[i][2]['startCallback']=opt_startCallback;}
if(i==length-1&&opt_endCallback){speakArgs[i][2]['endCallback']=opt_endCallback;}
if(this.category){speakArgs[i][2]['category']=this.category;}
cvox.ChromeVox.tts.speak.apply(cvox.ChromeVox.tts,speakArgs[i]);}};cvox.NavDescription.prototype.equals=function(that){return this.context==that.context&&this.text==that.text&&this.userValue==that.userValue&&this.annotation==that.annotation;};goog.provide('cvox.NavigationSpeaker');goog.require('cvox.NavDescription');cvox.NavigationSpeaker=function(){this.stopReading=false;this.id_=1;};cvox.NavigationSpeaker.prototype.speakDescriptionArray=function(descriptionArray,initialQueueMode,completionFunction){descriptionArray=this.reorderAnnotations(descriptionArray);this.stopReading=false;this.id_=(this.id_+1)%10000;var self=this;var speakDescriptionChain=function(i,queueMode,id){var description=descriptionArray[i];if(!description||self.stopReading||self.id_!=id){return;}
var startCallback=function(){for(var j=0;j<description.earcons.length;j++){cvox.ChromeVox.earcons.playEarcon(description.earcons[j]);}};var endCallbackHelper=function(){speakDescriptionChain(i+1,cvox.QueueMode.QUEUE,id);};var endCallback=function(){if(description.personality&&description.personality[cvox.AbstractTts.PAUSE]&&typeof(description.personality[cvox.AbstractTts.PAUSE])=='number'){setTimeout(endCallbackHelper,description.personality[cvox.AbstractTts.PAUSE]);}else{endCallbackHelper();}
if((i==descriptionArray.length-1)&&completionFunction){completionFunction();}};if(!description.isEmpty()){description.speak(queueMode,startCallback,endCallback);}else{startCallback();endCallback();return;}
if(!cvox.ChromeVox.host.hasTtsCallback()){startCallback();endCallback();}};speakDescriptionChain(0,initialQueueMode,this.id_);if((descriptionArray.length==0)&&completionFunction){completionFunction();}};cvox.NavigationSpeaker.structuredElement=function(annon){switch(annon){case'table':case'Math':return true;}
return false;};cvox.NavigationSpeaker.prototype.reorderAnnotations=function(descriptionArray){var descs=new Array;for(var i=0;i<descriptionArray.length;i++){var descr=descriptionArray[i];if(cvox.NavigationSpeaker.structuredElement(descr.annotation)){descs.push(new cvox.NavDescription({text:'',annotation:descr.annotation}));descr.annotation='';}
descs.push(descr);}
return descs;};goog.provide('cvox.SemanticUtil');cvox.SemanticUtil=function(){};cvox.SemanticUtil.objectsToKeys=function(objects){objects=Array.prototype.slice.call(arguments,0);var keys=[];return keys.concat.apply(keys,objects.map(Object.keys));};cvox.SemanticUtil.objectsToValues=function(objects){objects=Array.prototype.slice.call(arguments,0);var result=[];var collectValues=function(obj){for(var key in obj){result.push(obj[key]);}};objects.forEach(collectValues);return result;};cvox.SemanticUtil.unicodeToNumber=function(unicode){if(!unicode||unicode.length>2){return null;}
if(unicode.length==2){var hi=unicode.charCodeAt(0);var low=unicode.charCodeAt(1);if(0xD800<=hi&&hi<=0xDBFF&&!isNaN(low)){return((hi-0xD800)*0x400)+(low-0xDC00)+0x10000;}
return null;}
return unicode.charCodeAt(0);};cvox.SemanticUtil.numberToUnicode=function(number){if(number>=0x10000){var hi=(number-0x10000)/0x0400+0xD800;var lo=(number-0x10000)%0x0400+0xDC00;return String.fromCharCode(hi,lo);}
return String.fromCharCode(number);};cvox.SemanticUtil.tagName=function(node){return node.tagName.toUpperCase();};cvox.SemanticUtil.IGNORETAGS=['MERROR','MPHANTOM','MSPACE','MACTION','MALIGNGROUP','MALIGNMARK','MACTION'];cvox.SemanticUtil.EMPTYTAGS=['MATH','MROW','MPADDED','MSTYLE'];cvox.SemanticUtil.purgeNodes=function(nodes){var nodeArray=[];for(var i=0,node;node=nodes[i];i++){var tagName=cvox.SemanticUtil.tagName(node);if(cvox.SemanticUtil.IGNORETAGS.indexOf(tagName)!=-1)continue;if(cvox.SemanticUtil.EMPTYTAGS.indexOf(tagName)!=-1&&node.childNodes.length==0)
continue;nodeArray.push(node);}
return nodeArray;};goog.provide('cvox.SemanticAttr');goog.require('cvox.SemanticUtil');cvox.SemanticAttr=function(){this.generalPunctuations=['!','"','#','%','&','\'','*',',',':',';','?','@','\\','¡','§','¶','·','¿','‗','†','‡','•','‣','․','‥','‧','‰','‱','‸','※','‼','‽','‾','⁁','⁂','⁃','⁇','⁈','⁉','⁋','⁌','⁍','⁎','⁏','⁐','⁑','⁓','⁕','⁖','⁘','⁙','⁚','⁛','⁜','⁝','⁞','︐','︓','︔','︕','︖','︰','﹅','﹆','﹉','﹊','﹋','﹌','﹐','﹔','﹕','﹖','﹗','﹟','﹠','﹡','﹨','﹪','﹫','！','＂','＃','％','＆','＇','＊','，','／','：','；','？','＠','＼'];this.invisibleComma_=cvox.SemanticUtil.numberToUnicode(0x2063);this.generalPunctuations.push(this.invisibleComma_);this.ellipses=['…','⋮','⋯','⋰','⋱','︙'];this.fullStops=['.','﹒','．'];this.dashes=['‒','–','—','―','〜','︱','︲','﹘'];this.primes=['′','″','‴','‵','‶','‷','⁗'];this.openClosePairs={'(':')','[':']','{':'}','⁅':'⁆','〈':'〉','❨':'❩','❪':'❫','❬':'❭','❮':'❯','❰':'❱','❲':'❳','❴':'❵','⟅':'⟆','⟦':'⟧','⟨':'⟩','⟪':'⟫','⟬':'⟭','⟮':'⟯','⦃':'⦄','⦅':'⦆','⦇':'⦈','⦉':'⦊','⦋':'⦌','⦍':'⦎','⦏':'⦐','⦑':'⦒','⦓':'⦔','⦕':'⦖','⦗':'⦘','⧘':'⧙','⧚':'⧛','⧼':'⧽','⸢':'⸣','⸤':'⸥','⸦':'⸧','⸨':'⸩','〈':'〉','《':'》','「':'」','『':'』','【':'】','〔':'〕','〖':'〗','〘':'〙','〚':'〛','〝':'〞','﴾':'﴿','︗':'︘','﹙':'﹚','﹛':'﹜','﹝':'﹞','（':'）','［':'］','｛':'｝','｟':'｠','｢':'｣','⌈':'⌉','⌊':'⌋','⌌':'⌍','⌎':'⌏','⌜':'⌝','⌞':'⌟','⎛':'⎞','⎜':'⎟','⎝':'⎠','⎡':'⎤','⎢':'⎥','⎣':'⎦','⎧':'⎫','⎨':'⎬','⎩':'⎭','⎰':'⎱','⎸':'⎹'};this.topBottomPairs={'⎴':'⎵','⏜':'⏝','⏞':'⏟','⏠':'⏡','︵':'︶','︷':'︸','︹':'︺','︻':'︼','︽':'︾','︿':'﹀','﹁':'﹂','﹃':'﹄','﹇':'﹈'};this.leftFences=cvox.SemanticUtil.objectsToKeys(this.openClosePairs);this.rightFences=cvox.SemanticUtil.objectsToValues(this.openClosePairs);this.rightFences.push('〟');this.topFences=cvox.SemanticUtil.objectsToKeys(this.topBottomPairs);this.bottomFences=cvox.SemanticUtil.objectsToValues(this.topBottomPairs);this.neutralFences=['|','¦','‖','❘','⦀','⫴','￤','｜'];this.fences=this.neutralFences.concat(this.leftFences,this.rightFences,this.topFences,this.bottomFences);this.capitalLatin=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];this.smallLatin=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','ı','ȷ'];this.capitalLatinFullWidth=['Ａ','Ｂ','Ｃ','Ｄ','Ｅ','Ｆ','Ｇ','Ｈ','Ｉ','Ｊ','Ｋ','Ｌ','Ｍ','Ｎ','Ｏ','Ｐ','Ｑ','Ｒ','Ｓ','Ｔ','Ｕ','Ｖ','Ｗ','Ｘ','Ｙ','Ｚ'];this.smallLatinFullWidth=['ａ','ｂ','ｃ','ｄ','ｅ','ｆ','ｇ','ｈ','ｉ','ｊ','ｋ','ｌ','ｍ','ｎ','ｏ','ｐ','ｑ','ｒ','ｓ','ｔ','ｕ','ｖ','ｗ','ｘ','ｙ','ｚ'];this.capitalLatinBold=['𝐀','𝐁','𝐂','𝐃','𝐄','𝐅','𝐆','𝐇','𝐈','𝐉','𝐊','𝐋','𝐌','𝐍','𝐎','𝐏','𝐐','𝐑','𝐒','𝐓','𝐔','𝐕','𝐖','𝐗','𝐘','𝐙'];this.smallLatinBold=['𝐚','𝐛','𝐜','𝐝','𝐞','𝐟','𝐠','𝐡','𝐢','𝐣','𝐤','𝐥','𝐦','𝐧','𝐨','𝐩','𝐪','𝐫','𝐬','𝐭','𝐮','𝐯','𝐰','𝐱','𝐲','𝐳'];this.capitalLatinItalic=['𝐴','𝐵','𝐶','𝐷','𝐸','𝐹','𝐺','𝐻','𝐼','𝐽','𝐾','𝐿','𝑀','𝑁','𝑂','𝑃','𝑄','𝑅','𝑆','𝑇','𝑈','𝑉','𝑊','𝑋','𝑌','𝑍'];this.smallLatinItalic=['𝑎','𝑏','𝑐','𝑑','𝑒','𝑓','𝑔','ℎ','𝑖','𝑗','𝑘','𝑙','𝑚','𝑛','𝑜','𝑝','𝑞','𝑟','𝑠','𝑡','𝑢','𝑣','𝑤','𝑥','𝑦','𝑧','𝚤','𝚥'];this.capitalLatinScript=['𝒜','ℬ','𝒞','𝒟','ℰ','ℱ','𝒢','ℋ','ℐ','𝒥','𝒦','ℒ','ℳ','𝒩','𝒪','𝒫','𝒬','ℛ','𝒮','𝒯','𝒰','𝒱','𝒲','𝒳','𝒴','𝒵','℘'];this.smallLatinScript=['𝒶','𝒷','𝒸','𝒹','ℯ','𝒻','ℊ','𝒽','𝒾','𝒿','𝓀','𝓁','𝓂','𝓃','ℴ','𝓅','𝓆','𝓇','𝓈','𝓉','𝓊','𝓋','𝓌','𝓍','𝓎','𝓏','ℓ'];this.capitalLatinBoldScript=['𝓐','𝓑','𝓒','𝓓','𝓔','𝓕','𝓖','𝓗','𝓘','𝓙','𝓚','𝓛','𝓜','𝓝','𝓞','𝓟','𝓠','𝓡','𝓢','𝓣','𝓤','𝓥','𝓦','𝓧','𝓨','𝓩'];this.smallLatinBoldScript=['𝓪','𝓫','𝓬','𝓭','𝓮','𝓯','𝓰','𝓱','𝓲','𝓳','𝓴','𝓵','𝓶','𝓷','𝓸','𝓹','𝓺','𝓻','𝓼','𝓽','𝓾','𝓿','𝔀','𝔁','𝔂','𝔃'];this.capitalLatinFraktur=['𝔄','𝔅','ℭ','𝔇','𝔈','𝔉','𝔊','ℌ','ℑ','𝔍','𝔎','𝔏','𝔐','𝔑','𝔒','𝔓','𝔔','ℜ','𝔖','𝔗','𝔘','𝔙','𝔚','𝔛','𝔜','ℨ'];this.smallLatinFraktur=['𝔞','𝔟','𝔠','𝔡','𝔢','𝔣','𝔤','𝔥','𝔦','𝔧','𝔨','𝔩','𝔪','𝔫','𝔬','𝔭','𝔮','𝔯','𝔰','𝔱','𝔲','𝔳','𝔴','𝔵','𝔶','𝔷'];this.capitalLatinDoubleStruck=['𝔸','𝔹','ℂ','𝔻','𝔼','𝔽','𝔾','ℍ','𝕀','𝕁','𝕂','𝕃','𝕄','ℕ','𝕆','ℙ','ℚ','ℝ','𝕊','𝕋','𝕌','𝕍','𝕎','𝕏','𝕐','ℤ'];this.smallLatinDoubleStruck=['𝕒','𝕓','𝕔','𝕕','𝕖','𝕗','𝕘','𝕙','𝕚','𝕛','𝕜','𝕝','𝕞','𝕟','𝕠','𝕡','𝕢','𝕣','𝕤','𝕥','𝕦','𝕧','𝕨','𝕩','𝕪','𝕫'];this.capitalLatinBoldFraktur=['𝕬','𝕭','𝕮','𝕯','𝕰','𝕱','𝕲','𝕳','𝕴','𝕵','𝕶','𝕷','𝕸','𝕹','𝕺','𝕻','𝕼','𝕽','𝕾','𝕿','𝖀','𝖁','𝖂','𝖃','𝖄','𝖅'];this.smallLatinBoldFraktur=['𝖆','𝖇','𝖈','𝖉','𝖊','𝖋','𝖌','𝖍','𝖎','𝖏','𝖐','𝖑','𝖒','𝖓','𝖔','𝖕','𝖖','𝖗','𝖘','𝖙','𝖚','𝖛','𝖜','𝖝','𝖞','𝖟'];this.capitalLatinSansSerif=['𝖠','𝖡','𝖢','𝖣','𝖤','𝖥','𝖦','𝖧','𝖨','𝖩','𝖪','𝖫','𝖬','𝖭','𝖮','𝖯','𝖰','𝖱','𝖲','𝖳','𝖴','𝖵','𝖶','𝖷','𝖸','𝖹'];this.smallLatinSansSerif=['𝖺','𝖻','𝖼','𝖽','𝖾','𝖿','𝗀','𝗁','𝗂','𝗃','𝗄','𝗅','𝗆','𝗇','𝗈','𝗉','𝗊','𝗋','𝗌','𝗍','𝗎','𝗏','𝗐','𝗑','𝗒','𝗓'];this.capitalLatinSansSerifBold=['𝗔','𝗕','𝗖','𝗗','𝗘','𝗙','𝗚','𝗛','𝗜','𝗝','𝗞','𝗟','𝗠','𝗡','𝗢','𝗣','𝗤','𝗥','𝗦','𝗧','𝗨','𝗩','𝗪','𝗫','𝗬','𝗭'];this.smallLatinSansSerifBold=['𝗮','𝗯','𝗰','𝗱','𝗲','𝗳','𝗴','𝗵','𝗶','𝗷','𝗸','𝗹','𝗺','𝗻','𝗼','𝗽','𝗾','𝗿','𝘀','𝘁','𝘂','𝘃','𝘄','𝘅','𝘆','𝘇'];this.capitalLatinSansSerifItalic=['𝘈','𝘉','𝘊','𝘋','𝘌','𝘍','𝘎','𝘏','𝘐','𝘑','𝘒','𝘓','𝘔','𝘕','𝘖','𝘗','𝘘','𝘙','𝘚','𝘛','𝘜','𝘝','𝘞','𝘟','𝘠','𝘡'];this.smallLatinSansSerifItalic=['𝘢','𝘣','𝘤','𝘥','𝘦','𝘧','𝘨','𝘩','𝘪','𝘫','𝘬','𝘭','𝘮','𝘯','𝘰','𝘱','𝘲','𝘳','𝘴','𝘵','𝘶','𝘷','𝘸','𝘹','𝘺','𝘻'];this.capitalLatinMonospace=['𝙰','𝙱','𝙲','𝙳','𝙴','𝙵','𝙶','𝙷','𝙸','𝙹','𝙺','𝙻','𝙼','𝙽','𝙾','𝙿','𝚀','𝚁','𝚂','𝚃','𝚄','𝚅','𝚆','𝚇','𝚈','𝚉'];this.smallLatinMonospace=['𝚊','𝚋','𝚌','𝚍','𝚎','𝚏','𝚐','𝚑','𝚒','𝚓','𝚔','𝚕','𝚖','𝚗','𝚘','𝚙','𝚚','𝚛','𝚜','𝚝','𝚞','𝚟','𝚠','𝚡','𝚢','𝚣'];this.latinDoubleStruckItalic=['ⅅ','ⅆ','ⅇ','ⅈ','ⅉ'];this.capitalGreek=['Α','Β','Γ','Δ','Ε','Ζ','Η','Θ','Ι','Κ','Λ','Μ','Ν','Ξ','Ο','Π','Ρ','Σ','Τ','Υ','Φ','Χ','Ψ','Ω'];this.smallGreek=['α','β','γ','δ','ε','ζ','η','θ','ι','κ','λ','μ','ν','ξ','ο','π','ρ','ς','σ','τ','υ','φ','χ','ψ','ω'];this.capitalGreekBold=['𝚨','𝚩','𝚪','𝚫','𝚬','𝚭','𝚮','𝚯','𝚰','𝚱','𝚲','𝚳','𝚴','𝚵','𝚶','𝚷','𝚸','𝚺','𝚻','𝚼','𝚽','𝚾','𝚿','𝛀'];this.smallGreekBold=['𝛂','𝛃','𝛄','𝛅','𝛆','𝛇','𝛈','𝛉','𝛊','𝛋','𝛌','𝛍','𝛎','𝛏','𝛐','𝛑','𝛒','𝛓','𝛔','𝛕','𝛖','𝛗','𝛘','𝛙','𝛚'];this.capitalGreekItalic=['𝛢','𝛣','𝛤','𝛥','𝛦','𝛧','𝛨','𝛩','𝛪','𝛫','𝛬','𝛭','𝛮','𝛯','𝛰','𝛱','𝛲','𝛴','𝛵','𝛶','𝛷','𝛸','𝛹','𝛺'];this.smallGreekItalic=['𝛼','𝛽','𝛾','𝛿','𝜀','𝜁','𝜂','𝜃','𝜄','𝜅','𝜆','𝜇','𝜈','𝜉','𝜊','𝜋','𝜌','𝜍','𝜎','𝜏','𝜐','𝜑','𝜒','𝜓','𝜔'];this.capitalGreekSansSerifBold=['𝝖','𝝗','𝝘','𝝙','𝝚','𝝛','𝝜','𝝝','𝝞','𝝟','𝝠','𝝡','𝝢','𝝣','𝝤','𝝥','𝝦','𝝨','𝝩','𝝪','𝝫','𝝬','𝝭','𝝮'];this.smallGreekSansSerifBold=['𝝰','𝝱','𝝲','𝝳','𝝴','𝝵','𝝶','𝝷','𝝸','𝝹','𝝺','𝝻','𝝼','𝝽','𝝾','𝝿','𝞀','𝞁','𝞂','𝞃','𝞄','𝞅','𝞆','𝞇','𝞈'];this.greekDoubleStruck=['ℼ','ℽ','ℾ','ℿ'];this.hebrewLetters=['ℵ','ℶ','ℷ','ℸ'];this.additions=['+','±','∓','∔','∧','∨','∩','∪','⊌','⊓','⊔','⊝','⊞','⊤','⊥','⊺','⊻','⊼','⋄','⋎','⋏','⋒','⋓','△','▷','▽','◁','⩞','⊕'];this.invisiblePlus_=cvox.SemanticUtil.numberToUnicode(0x2064);this.additions.push(this.invisiblePlus_);this.multiplications=['†','‡','∐','∗','∘','∙','≀','⊚','⊛','⊠','⊡','⋅','⋆','⋇','⋉','⋊','⋋','⋌','○'];this.invisibleTimes_=cvox.SemanticUtil.numberToUnicode(0x2062);this.multiplications.push(this.invisibleTimes_);this.subtractions=['-','⁒','⁻','₋','−','∖','∸','≂','⊖','⊟','➖','⨩','⨪','⨫','⨬','⨺','⩁','⩬','﹣','－','‐','‑'];this.divisions=['/','÷','⁄','∕','⊘','⟌','⦼','⨸'];this.functionApplication_=cvox.SemanticUtil.numberToUnicode(0x2061);this.equalities=['=','~','⁼','₌','∼','∽','≃','≅','≈','≊','≋','≌','≍','≎','≑','≒','≓','≔','≕','≖','≗','≘','≙','≚','≛','≜','≝','≞','≟','≡','≣','⧤','⩦','⩮','⩯','⩰','⩱','⩲','⩳','⩴','⩵','⩶','⩷','⩸','⋕','⩭','⩪','⩫','⩬','﹦','＝'];this.inequalities=['<','>','≁','≂','≄','≆','≇','≉','≏','≐','≠','≢','≤','≥','≦','≧','≨','≩','≪','≫','≬','≭','≮','≯','≰','≱','≲','≳','≴','≵','≶','≷','≸','≹','≺','≻','≼','≽','≾','≿','⊀','⊁','⋖','⋗','⋘','⋙','⋚','⋛','⋜','⋝','⋞','⋟','⋠','⋡','⋢','⋣','⋤','⋥','⋦','⋧','⋨','⋩','⩹','⩺','⩻','⩼','⩽','⩾','⩿','⪀','⪁','⪂','⪃','⪄','⪅','⪆','⪇','⪈','⪉','⪊','⪋','⪌','⪍','⪎','⪏','⪐','⪑','⪒','⪓','⪔','⪕','⪖','⪗','⪘','⪙','⪚','⪛','⪜','⪝','⪞','⪟','⪠','⪡','⪢','⪣','⪤','⪥','⪦','⪧','⪨','⪩','⪪','⪫','⪬','⪭','⪮','⪯','⪰','⪱','⪲','⪳','⪴','⪵','⪶','⪷','⪸','⪹','⪺','⪻','⪼','⫷','⫸','⫹','⫺','⧀','⧁','﹤','﹥','＜','＞'];this.relations=[];this.arrows=['←','↑','→','↓','↔','↕','↖','↗','↘','↙','↚','↛','↜','↝','↞','↟','↠','↡','↢','↣','↤','↥','↦','↧','↨','↩','↪','↫','↬','↭','↮','↯','↰','↱','↲','↳','↴','↵','↶','↷','↸','↹','↺','↻','⇄','⇅','⇆','⇇','⇈','⇉','⇊','⇍','⇎','⇏','⇐','⇑','⇒','⇓','⇔','⇕','⇖','⇗','⇘','⇙','⇚','⇛','⇜','⇝','⇞','⇟','⇠','⇡','⇢','⇣','⇤','⇥','⇦','⇧','⇨','⇩','⇪','⇫','⇬','⇭','⇮','⇯','⇰','⇱','⇲','⇳','⇴','⇵','⇶','⇷','⇸','⇹','⇺','⇻','⇼','⇽','⇾','⇿','⌁','⌃','⌄','⌤','⎋','➔','➘','➙','➚','➛','➜','➝','➞','➟','➠','➡','➢','➣','➤','➥','➦','➧','➨','➩','➪','➫','➬','➭','➮','➯','➱','➲','➳','➴','➵','➶','➷','➸','➹','➺','➻','➼','➽','➾','⟰','⟱','⟲','⟳','⟴','⟵','⟶','⟷','⟸','⟹','⟺','⟻','⟼','⟽','⟾','⟿','⤀','⤁','⤂','⤃','⤄','⤅','⤆','⤇','⤈','⤉','⤊','⤋','⤌','⤍','⤎','⤏','⤐','⤑','⤒','⤓','⤔','⤕','⤖','⤗','⤘','⤙','⤚','⤛','⤜','⤝','⤞','⤟','⤠','⤡','⤢','⤣','⤤','⤥','⤦','⤧','⤨','⤩','⤪','⤭','⤮','⤯','⤰','⤱','⤲','⤳','⤴','⤵','⤶','⤷','⤸','⤹','⤺','⤻','⤼','⤽','⤾','⤿','⥀','⥁','⥂','⥃','⥄','⥅','⥆','⥇','⥈','⥉','⥰','⥱','⥲','⥳','⥴','⥵','⥶','⥷','⥸','⥹','⥺','⥻','⦳','⦴','⦽','⧪','⧬','⧭','⨗','⬀','⬁','⬂','⬃','⬄','⬅','⬆','⬇','⬈','⬉','⬊','⬋','⬌','⬍','⬎','⬏','⬐','⬑','⬰','⬱','⬲','⬳','⬴','⬵','⬶','⬷','⬸','⬹','⬺','⬻','⬼','⬽','⬾','⬿','⭀','⭁','⭂','⭃','⭄','⭅','⭆','⭇','⭈','⭉','⭊','⭋','⭌','￩','￪','￫','￬','↼','↽','↾','↿','⇀','⇁','⇂','⇃','⇋','⇌','⥊','⥋','⥌','⥍','⥎','⥏','⥐','⥑','⥒','⥓','⥔','⥕','⥖','⥗','⥘','⥙','⥚','⥛','⥜','⥝','⥞','⥟','⥠','⥡','⥢','⥣','⥤','⥥','⥦','⥧','⥨','⥩','⥪','⥫','⥬','⥭','⥮','⥯','⥼','⥽','⥾','⥿'];this.sumOps=['⅀','∏','∐','∑','⋀','⋁','⋂','⋃','⨀','⨁','⨂','⨃','⨄','⨅','⨆','⨇','⨈','⨉','⨊','⨋','⫼','⫿'];this.intOps=['∫','∬','∭','∮','∯','∰','∱','∲','∳','⨌','⨍','⨎','⨏','⨐','⨑','⨒','⨓','⨔','⨕','⨖','⨗','⨘','⨙','⨚','⨛','⨜'];this.prefixOps=['∀','∃'];this.operatorBits=['⌠','⌡','⎶','⎪','⎮','⎯','⎲','⎳','⎷'];this.digitsNormal=['0','1','2','3','4','5','6','7','8','9'];this.digitsFullWidth=['０','１','２','３','４','５','６','７','８','９'];this.digitsBold=['𝟎','𝟏','𝟐','𝟑','𝟒','𝟓','𝟔','𝟕','𝟖','𝟗'];this.digitsDoubleStruck=['𝟘','𝟙','𝟚','𝟛','𝟜','𝟝','𝟞','𝟟','𝟠','𝟡'];this.digitsSansSerif=['𝟢','𝟣','𝟤','𝟥','𝟦','𝟧','𝟨','𝟩','𝟪','𝟫'];this.digitsSansSerifBold=['𝟬','𝟭','𝟮','𝟯','𝟰','𝟱','𝟲','𝟳','𝟴','𝟵'];this.digitsMonospace=['𝟶','𝟷','𝟸','𝟹','𝟺','𝟻','𝟼','𝟽','𝟾','𝟿'];this.digitsSuperscript=['²','³','¹','⁰','⁴','⁵','⁶','⁷','⁸','⁹'];this.digitsSubscript=['₀','₁','₂','₃','₄','₅','₆','₇','₈','₉'];this.fractions=['¼','½','¾','⅐','⅑','⅒','⅓','⅔','⅕','⅖','⅗','⅘','⅙','⅚','⅛','⅜','⅝','⅞','⅟','↉'];this.enclosedNumbers=['①','②','③','④','⑤','⑥','⑦','⑧','⑨','⑩','⑪','⑫','⑬','⑭','⑮','⑯','⑰','⑱','⑲','⑳','⓪','⓫','⓬','⓭','⓮','⓯','⓰','⓱','⓲','⓳','⓴','⓵','⓶','⓷','⓸','⓹','⓺','⓻','⓼','⓽','⓾','⓿','❶','❷','❸','❹','❺','❻','❼','❽','❾','❿','➀','➁','➂','➃','➄','➅','➆','➇','➈','➉','➊','➋','➌','➍','➎','➏','➐','➑','➒','➓','㉈','㉉','㉊','㉋','㉌','㉍','㉎','㉏','㉑','㉒','㉓','㉔','㉕','㉖','㉗','㉘','㉙','㉚','㉛','㉜','㉝','㉞','㉟','㊱','㊲','㊳','㊴','㊵','㊶','㊷','㊸','㊹','㊺','㊻','㊼','㊽','㊾','㊿'];this.fencedNumbers=['⑴','⑵','⑶','⑷','⑸','⑹','⑺','⑻','⑼','⑽','⑾','⑿','⒀','⒁','⒂','⒃','⒄','⒅','⒆','⒇'];this.punctuatedNumbers=['⒈','⒉','⒊','⒋','⒌','⒍','⒎','⒏','⒐','⒑','⒒','⒓','⒔','⒕','⒖','⒗','⒘','⒙','⒚','⒛','🄀','🄁','🄂','🄃','🄄','🄅','🄆','🄇','🄈','🄉','🄊'];this.digits=this.digitsNormal.concat(this.digitsFullWidth,this.digitsBold,this.digitsDoubleStruck,this.digitsSansSerif,this.digitsSansSerifBold,this.digitsMonospace);this.numbers=this.fractions.concat(this.digitsSuperscript,this.digitsSubscript,this.enclosedNumbers,this.fencedNumbers,this.punctuatedNumbers);this.allNumbers=this.digits.concat(this.numbers);this.trigonometricFunctions=['cos','cot','csc','sec','sin','tan','arccos','arccot','arccsc','arcsec','arcsin','arctan'];this.hyperbolicFunctions=['cosh','coth','csch','sech','sinh','tanh','arcosh','arcoth','arcsch','arsech','arsinh','artanh','arccosh','arccoth','arccsch','arcsech','arcsinh','arctanh'];this.algebraicFunctions=['deg','det','dim','hom','ker','Tr','tr'];this.elementaryFunctions=['log','ln','lg','exp','expt','gcd','gcd','arg','im','re','Pr'];this.prefixFunctions=this.trigonometricFunctions.concat(this.hyperbolicFunctions,this.algebraicFunctions,this.elementaryFunctions);this.limitFunctions=['inf','lim','liminf','limsup','max','min','sup','injlim','projlim'];this.infixFunctions=['mod','rem'];this.symbolSetToSemantic_=[{set:this.generalPunctuations,type:cvox.SemanticAttr.Type.PUNCTUATION,role:cvox.SemanticAttr.Role.UNKNOWN},{set:this.ellipses,type:cvox.SemanticAttr.Type.PUNCTUATION,role:cvox.SemanticAttr.Role.ELLIPSIS},{set:this.fullStops,type:cvox.SemanticAttr.Type.PUNCTUATION,role:cvox.SemanticAttr.Role.FULLSTOP},{set:this.dashes,type:cvox.SemanticAttr.Type.PUNCTUATION,role:cvox.SemanticAttr.Role.DASH},{set:this.primes,type:cvox.SemanticAttr.Type.PUNCTUATION,role:cvox.SemanticAttr.Role.PRIME},{set:this.leftFences,type:cvox.SemanticAttr.Type.FENCE,role:cvox.SemanticAttr.Role.OPEN},{set:this.rightFences,type:cvox.SemanticAttr.Type.FENCE,role:cvox.SemanticAttr.Role.CLOSE},{set:this.topFences,type:cvox.SemanticAttr.Type.FENCE,role:cvox.SemanticAttr.Role.TOP},{set:this.bottomFences,type:cvox.SemanticAttr.Type.FENCE,role:cvox.SemanticAttr.Role.BOTTOM},{set:this.neutralFences,type:cvox.SemanticAttr.Type.FENCE,role:cvox.SemanticAttr.Role.NEUTRAL},{set:this.smallLatin,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.capitalLatin,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.smallLatinFullWidth,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.capitalLatinFullWidth,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.smallLatinBold,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.BOLD},{set:this.capitalLatinBold,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.BOLD},{set:this.smallLatinItalic,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.ITALIC},{set:this.capitalLatinItalic,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.ITALIC},{set:this.smallLatinScript,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.SCRIPT},{set:this.capitalLatinScript,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.SCRIPT},{set:this.smallLatinBoldScript,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.BOLDSCRIPT},{set:this.capitalLatinBoldScript,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.BOLDSCRIPT},{set:this.smallLatinFraktur,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.FRAKTUR},{set:this.capitalLatinFraktur,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.FRAKTUR},{set:this.smallLatinDoubleStruck,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.DOUBLESTRUCK},{set:this.capitalLatinDoubleStruck,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.DOUBLESTRUCK},{set:this.smallLatinBoldFraktur,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.BOLDFRAKTUR},{set:this.capitalLatinBoldFraktur,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.BOLDFRAKTUR},{set:this.smallLatinSansSerif,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.SANSSERIF},{set:this.capitalLatinSansSerif,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.SANSSERIF},{set:this.smallLatinSansSerifBold,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.SANSSERIFBOLD},{set:this.capitalLatinSansSerifBold,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.SANSSERIFBOLD},{set:this.smallLatinSansSerifItalic,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.SANSSERIFITALIC},{set:this.capitalLatinSansSerifItalic,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.SANSSERIFITALIC},{set:this.smallLatinMonospace,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.MONOSPACE},{set:this.capitalLatinMonospace,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.MONOSPACE},{set:this.latinDoubleStruckItalic,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.LATINLETTER,font:cvox.SemanticAttr.Font.DOUBLESTRUCKITALIC},{set:this.smallGreek,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.capitalGreek,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.smallGreekBold,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.BOLD},{set:this.capitalGreekBold,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.BOLD},{set:this.smallGreekItalic,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.ITALIC},{set:this.capitalGreekItalic,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.ITALIC},{set:this.smallGreekSansSerifBold,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.SANSSERIFBOLD},{set:this.capitalGreekSansSerifBold,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.SANSSERIFBOLD},{set:this.greekDoubleStruck,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.GREEKLETTER,font:cvox.SemanticAttr.Font.DOUBLESTRUCK},{set:this.hebrewLetters,type:cvox.SemanticAttr.Type.IDENTIFIER,role:cvox.SemanticAttr.Role.OTHERLETTER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.digitsNormal,type:cvox.SemanticAttr.Type.NUMBER,role:cvox.SemanticAttr.Role.INTEGER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.digitsFullWidth,type:cvox.SemanticAttr.Type.NUMBER,role:cvox.SemanticAttr.Role.INTEGER,font:cvox.SemanticAttr.Font.NORMAL},{set:this.digitsBold,type:cvox.SemanticAttr.Type.NUMBER,role:cvox.SemanticAttr.Role.INTEGER,font:cvox.SemanticAttr.Font.BOLD},{set:this.digitsDoubleStruck,type:cvox.SemanticAttr.Type.NUMBER,role:cvox.SemanticAttr.Role.INTEGER,font:cvox.SemanticAttr.Font.DOUBLESTRUCK},{set:this.digitsSansSerif,type:cvox.SemanticAttr.Type.NUMBER,role:cvox.SemanticAttr.Role.INTEGER,font:cvox.SemanticAttr.Font.SANSSERIF},{set:this.digitsSansSerifBold,type:cvox.SemanticAttr.Type.NUMBER,role:cvox.SemanticAttr.Role.INTEGER,font:cvox.SemanticAttr.Font.SANSSERIFBOLD},{set:this.digitsMonospace,type:cvox.SemanticAttr.Type.NUMBER,role:cvox.SemanticAttr.Role.INTEGER,font:cvox.SemanticAttr.Font.MONOSPACE},{set:this.numbers,type:cvox.SemanticAttr.Type.NUMBER,role:cvox.SemanticAttr.Role.INTEGER},{set:this.additions,type:cvox.SemanticAttr.Type.OPERATOR,role:cvox.SemanticAttr.Role.ADDITION},{set:this.multiplications,type:cvox.SemanticAttr.Type.OPERATOR,role:cvox.SemanticAttr.Role.MULTIPLICATION},{set:this.subtractions,type:cvox.SemanticAttr.Type.OPERATOR,role:cvox.SemanticAttr.Role.SUBTRACTION},{set:this.divisions,type:cvox.SemanticAttr.Type.OPERATOR,role:cvox.SemanticAttr.Role.DIVISION},{set:this.prefixOps,type:cvox.SemanticAttr.Type.PREFIXOP,role:cvox.SemanticAttr.Role.PREFIXFUNC},{set:this.equalities,type:cvox.SemanticAttr.Type.RELATION,role:cvox.SemanticAttr.Role.EQUALITY},{set:this.inequalities,type:cvox.SemanticAttr.Type.RELATION,role:cvox.SemanticAttr.Role.INEQUALITY},{set:this.relations,type:cvox.SemanticAttr.Type.RELATION,role:cvox.SemanticAttr.Role.UNKNOWN},{set:this.arrows,type:cvox.SemanticAttr.Type.RELATION,role:cvox.SemanticAttr.Role.ARROW},{set:this.sumOps,type:cvox.SemanticAttr.Type.LARGEOP,role:cvox.SemanticAttr.Role.SUM},{set:this.intOps,type:cvox.SemanticAttr.Type.LARGEOP,role:cvox.SemanticAttr.Role.INTEGRAL},{set:this.limitFunctions,type:cvox.SemanticAttr.Type.FUNCTION,role:cvox.SemanticAttr.Role.LIMFUNC},{set:this.prefixFunctions,type:cvox.SemanticAttr.Type.FUNCTION,role:cvox.SemanticAttr.Role.PREFIXFUNC},{set:this.infixFunctions,type:cvox.SemanticAttr.Type.OPERATOR,role:cvox.SemanticAttr.Role.MULTIPLICATION}];};goog.addSingletonGetter(cvox.SemanticAttr);cvox.SemanticAttr.Attr;cvox.SemanticAttr.Type={PUNCTUATION:'punctuation',FENCE:'fence',NUMBER:'number',IDENTIFIER:'identifier',TEXT:'text',OPERATOR:'operator',RELATION:'relation',LARGEOP:'largeop',FUNCTION:'function',ACCENT:'accent',FENCED:'fenced',FRACTION:'fraction',PUNCTUATED:'punctuated',RELSEQ:'relseq',MULTIREL:'multirel',INFIXOP:'infixop',PREFIXOP:'prefixop',POSTFIXOP:'postfixop',APPL:'appl',INTEGRAL:'integral',BIGOP:'bigop',SQRT:'sqrt',ROOT:'root',LIMUPPER:'limupper',LIMLOWER:'limlower',LIMBOTH:'limboth',SUBSCRIPT:'subscript',SUPERSCRIPT:'superscript',UNDERSCORE:'underscore',OVERSCORE:'overscore',TABLE:'table',MULTILINE:'multiline',MATRIX:'matrix',VECTOR:'vector',CASES:'cases',ROW:'row',LINE:'line',CELL:'cell',UNKNOWN:'unknown',EMPTY:'empty'};cvox.SemanticAttr.Role={ELLIPSIS:'ellipsis',FULLSTOP:'fullstop',DASH:'dash',PRIME:'prime',VBAR:'vbar',OPENFENCE:'openfence',CLOSEFENCE:'closefence',APPLICATION:'application',OPEN:'open',CLOSE:'close',TOP:'top',BOTTOM:'bottom',NEUTRAL:'neutral',LATINLETTER:'latinletter',GREEKLETTER:'greekletter',OTHERLETTER:'otherletter',INTEGER:'integer',FLOAT:'float',OTHERNUMBER:'othernumber',MULTIACCENT:'multiaccent',OVERACCENT:'overaccent',UNDERACCENT:'underaccent',LEFTRIGHT:'leftright',ABOVEBELOW:'abovebelow',SEQUENCE:'sequence',ENDPUNCT:'endpunct',STARTPUNCT:'startpunct',NEGATIVE:'negative',NEGATION:'negation',MULTIOP:'multiop',LIMFUNC:'limit function',INFIXFUNC:'infix function',PREFIXFUNC:'prefix function',POSTFIXFUNC:'postfix function',SUM:'sum',INTEGRAL:'integral',ADDITION:'addition',MULTIPLICATION:'multiplication',DIVISION:'division',SUBTRACTION:'subtraction',IMPLICIT:'implicit',EQUALITY:'equality',INEQUALITY:'inequality',ELEMENT:'element',BINREL:'binrel',ARROW:'arrow',MULTILINE:'multiline',MATRIX:'matrix',VECTOR:'vector',CASES:'cases',TABLE:'table',UNKNOWN:'unknown'};cvox.SemanticAttr.Font={BOLD:'bold',BOLDFRAKTUR:'bold-fraktur',BOLDITALIC:'bold-italic',BOLDSCRIPT:'bold-script',DOUBLESTRUCK:'double-struck',DOUBLESTRUCKITALIC:'double-struck-italic',FRAKTUR:'fraktur',ITALIC:'italic',MONOSPACE:'monospace',NORMAL:'normal',SCRIPT:'script',SANSSERIF:'sans-serif',SANSSERIFITALIC:'sans-serif-italic',SANSSERIFBOLD:'sans-serif-bold',SANSSERIFBOLDITALIC:'sans-serif-bold-italic',UNKNOWN:'unknown'};cvox.SemanticAttr.prototype.lookupType=function(symbol){return cvox.SemanticAttr.Type.UNKNOWN;};cvox.SemanticAttr.prototype.lookupRole=function(symbol){return cvox.SemanticAttr.Role.UNKNOWN;};cvox.SemanticAttr.lookupMeaning=function(symbol){return cvox.SemanticAttr.getInstance().lookupMeaning_(symbol);};cvox.SemanticAttr.invisibleTimes=function(){return cvox.SemanticAttr.getInstance().invisibleTimes_;};cvox.SemanticAttr.invisibleComma=function(){return cvox.SemanticAttr.getInstance().invisibleComma_;};cvox.SemanticAttr.functionApplication=function(){return cvox.SemanticAttr.getInstance().functionApplication_;};cvox.SemanticAttr.isMatchingFenceRole=function(open,close){return(open==cvox.SemanticAttr.Role.OPEN&&close==cvox.SemanticAttr.Role.CLOSE)||(open==cvox.SemanticAttr.Role.NEUTRAL&&close==cvox.SemanticAttr.Role.NEUTRAL)||(open==cvox.SemanticAttr.Role.TOP&&close==cvox.SemanticAttr.Role.BOTTOM);};cvox.SemanticAttr.isMatchingFence=function(open,close){return cvox.SemanticAttr.getInstance().isMatchingFence_(open,close);};cvox.SemanticAttr.isOpeningFence=function(fence){return(fence==cvox.SemanticAttr.Role.OPEN||fence==cvox.SemanticAttr.Role.NEUTRAL);};cvox.SemanticAttr.isClosingFence=function(fence){return(fence==cvox.SemanticAttr.Role.CLOSE||fence==cvox.SemanticAttr.Role.NEUTRAL);};cvox.SemanticAttr.isCharacterD=function(chr){var Ds=['d','ⅆ','ｄ','𝐝','𝑑','𝒹','𝓭','𝔡','𝕕','𝖉','𝖽','𝗱','𝘥','𝚍'];return Ds.indexOf(chr)!=-1;};cvox.SemanticAttr.prototype.isMatchingFence_=function(open,close){if(this.neutralFences.indexOf(open)!=-1){return open==close;}
return this.openClosePairs[open]==close||this.topBottomPairs[open]==close;};cvox.SemanticAttr.prototype.lookupMeaning_=function(symbol){for(var i=0,set;set=this.symbolSetToSemantic_[i];i++){if(set.set.indexOf(symbol)!=-1){return{role:set.role||cvox.SemanticAttr.Role.UNKNOWN,type:set.type||cvox.SemanticAttr.Type.UNKNOWN,font:set.font||cvox.SemanticAttr.Font.UNKNOWN};}}
return{role:cvox.SemanticAttr.Role.UNKNOWN,type:cvox.SemanticAttr.Type.UNKNOWN,font:cvox.SemanticAttr.Font.UNKNOWN};};goog.provide('cvox.SemanticTree');goog.provide('cvox.SemanticTree.Node');goog.require('cvox.DomUtil');goog.require('cvox.SemanticAttr');goog.require('cvox.SemanticUtil');cvox.SemanticTree=function(mml){this.idCounter_=0;this.mathml=mml;this.root=this.parseMathml_(mml);};cvox.SemanticTree.Node=function(id){this.id=id;this.mathml=[];this.parent=null;this.type=cvox.SemanticAttr.Type.UNKNOWN;this.role=cvox.SemanticAttr.Role.UNKNOWN;this.font=cvox.SemanticAttr.Font.UNKNOWN;this.childNodes=[];this.textContent='';this.contentNodes=[];};cvox.SemanticTree.Node.prototype.querySelectorAll=function(pred){var result=[];for(var i=0,child;child=this.childNodes[i];i++){result=result.concat(child.querySelectorAll(pred));}
if(pred(this)){result.unshift(this);}
return result;};cvox.SemanticTree.prototype.xml=function(brief){var dp=new DOMParser();var xml=dp.parseFromString('<stree></stree>','text/xml');var xmlRoot=this.root.xml(xml,brief);xml.childNodes[0].appendChild(xmlRoot);return xml.childNodes[0];};cvox.SemanticTree.Node.prototype.xml=function(xml,brief){var xmlNodeList=function(tag,nodes){var xmlNodes=nodes.map(function(x){return x.xml(xml,brief);});var tagNode=xml.createElement(tag);for(var i=0,child;child=xmlNodes[i];i++){tagNode.appendChild(child);}
return tagNode;};var node=xml.createElement(this.type);if(!brief){this.xmlAttributes_(node);}
node.textContent=this.textContent;if(this.contentNodes.length>0){node.appendChild(xmlNodeList('content',this.contentNodes));}
if(this.childNodes.length>0){node.appendChild(xmlNodeList('children',this.childNodes));}
return node;};cvox.SemanticTree.prototype.toString=function(brief){var xmls=new XMLSerializer();return xmls.serializeToString(this.xml(brief));};cvox.SemanticTree.prototype.formatXml=function(brief){var xml=this.toString(brief);return cvox.SemanticTree.formatXml(xml);};cvox.SemanticTree.formatXml=function(xml){var reg=/(>)(<)(\/*)/g;xml=xml.replace(reg,'$1\r\n$2$3');reg=/(>)(.+)(<c)/g;xml=xml.replace(reg,'$1\r\n$2\r\n$3');var formatted='';var padding='';xml.split('\r\n').forEach(function(node){if(node.match(/.+<\/\w[^>]*>$/)){formatted+=padding+node+'\r\n';}else if(node.match(/^<\/\w/)){if(padding){padding=padding.slice(2);formatted+=padding+node+'\r\n';}}else if(node.match(/^<\w[^>]*[^\/]>.*$/)){formatted+=padding+node+'\r\n';padding+='  ';}else{formatted+=padding+node+'\r\n';}});return formatted;};cvox.SemanticTree.Node.prototype.toString=function(brief){var xmls=new XMLSerializer();var dp=new DOMParser();var xml=dp.parseFromString('','text/xml');return xmls.serializeToString(this.xml(xml,brief));};cvox.SemanticTree.Node.prototype.xmlAttributes_=function(node){node.setAttribute('role',this.role);if(this.font!=cvox.SemanticAttr.Font.UNKNOWN){node.setAttribute('font',this.font);}
node.setAttribute('id',this.id);};cvox.SemanticTree.prototype.createNode_=function(){return new cvox.SemanticTree.Node(this.idCounter_++);};cvox.SemanticTree.prototype.replaceNode_=function(oldNode,newNode){var parent=oldNode.parent;if(!parent){this.root=newNode;return;}
parent.replaceChild_(oldNode,newNode);};cvox.SemanticTree.Node.prototype.updateContent_=function(content){content=content.trim();if(this.textContent==content){return;}
var meaning=cvox.SemanticAttr.lookupMeaning(content);this.textContent=content;this.role=meaning.role;this.type=meaning.type;this.font=meaning.font;};cvox.SemanticTree.Node.prototype.addMathmlNodes_=function(mmlNodes){for(var i=0,mml;mml=mmlNodes[i];i++){if(this.mathml.indexOf(mml)==-1){this.mathml.push(mml);}}};cvox.SemanticTree.Node.prototype.removeMathmlNodes_=function(mmlNodes){var mmlList=this.mathml;for(var i=0,mml;mml=mmlNodes[i];i++){var index=mmlList.indexOf(mml);if(index!=-1){mmlList.splice(index,1);}}
this.mathml=mmlList;};cvox.SemanticTree.Node.prototype.appendChild_=function(child){this.childNodes.push(child);this.addMathmlNodes_(child.mathml);child.parent=this;};cvox.SemanticTree.Node.prototype.replaceChild_=function(oldNode,newNode){var index=this.childNodes.indexOf(oldNode);if(index==-1){return;}
newNode.parent=this;oldNode.parent=null;this.childNodes[index]=newNode;var removeMathml=oldNode.mathml.filter(function(x){return newNode.mathml.indexOf(x)==-1;});var addMathml=newNode.mathml.filter(function(x){return oldNode.mathml.indexOf(x)==-1;});this.removeMathmlNodes_(removeMathml);this.addMathmlNodes_(addMathml);};cvox.SemanticTree.Node.prototype.appendContentNode_=function(node){if(node){this.contentNodes.push(node);this.addMathmlNodes_(node.mathml);node.parent=this;}};cvox.SemanticTree.Node.prototype.removeContentNode_=function(node){if(node){var index=this.contentNodes.indexOf(node);if(index!=-1){this.contentNodes.splice(index,1);}}};cvox.SemanticTree.prototype.parseMathml_=function(mml){var children=cvox.DomUtil.toArray(mml.children);switch(cvox.SemanticUtil.tagName(mml)){case'MATH':case'MROW':case'MPADDED':case'MSTYLE':children=cvox.SemanticUtil.purgeNodes(children);if(children.length==1){return this.parseMathml_((children[0]));}
return this.processRow_(this.parseMathmlChildren_(children));break;case'MFRAC':var newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.FRACTION,[this.parseMathml_(children[0]),this.parseMathml_(children[1])],[]);newNode.role=cvox.SemanticAttr.Role.DIVISION;return newNode;break;case'MSUB':case'MSUP':case'MSUBSUP':case'MOVER':case'MUNDER':case'MUNDEROVER':return this.makeLimitNode_(cvox.SemanticUtil.tagName(mml),this.parseMathmlChildren_(children));break;case'MROOT':return this.makeBranchNode_(cvox.SemanticAttr.Type.ROOT,[this.parseMathml_(children[0]),this.parseMathml_(children[1])],[]);break;case'MSQRT':children=this.parseMathmlChildren_(cvox.SemanticUtil.purgeNodes(children));return this.makeBranchNode_(cvox.SemanticAttr.Type.SQRT,[this.processRow_(children)],[]);break;case'MTABLE':newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.TABLE,this.parseMathmlChildren_(children),[]);if(cvox.SemanticTree.tableIsMultiline_(newNode)){this.tableToMultiline_(newNode);}
return newNode;break;case'MTR':newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.ROW,this.parseMathmlChildren_(children),[]);newNode.role=cvox.SemanticAttr.Role.TABLE;return newNode;break;case'MTD':children=this.parseMathmlChildren_(cvox.SemanticUtil.purgeNodes(children));newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.CELL,[this.processRow_(children)],[]);newNode.role=cvox.SemanticAttr.Role.TABLE;return newNode;break;case'MTEXT':var leaf=this.makeLeafNode_(mml);leaf.type=cvox.SemanticAttr.Type.TEXT;return leaf;break;case'MI':leaf=this.makeLeafNode_(mml);if(leaf.type==cvox.SemanticAttr.Type.UNKNOWN){leaf.type=cvox.SemanticAttr.Type.IDENTIFIER;}
return leaf;break;case'MN':leaf=this.makeLeafNode_(mml);if(leaf.type==cvox.SemanticAttr.Type.UNKNOWN){leaf.type=cvox.SemanticAttr.Type.NUMBER;}
return leaf;break;case'MO':leaf=this.makeLeafNode_(mml);if(leaf.type==cvox.SemanticAttr.Type.UNKNOWN){leaf.type=cvox.SemanticAttr.Type.OPERATOR;}
return leaf;break;default:return this.makeUnprocessed_(mml);}};cvox.SemanticTree.prototype.parseMathmlChildren_=function(mmls){var result=[];for(var i=0,mml;mml=mmls[i];i++){result.push(this.parseMathml_(mml));}
return result;};cvox.SemanticTree.prototype.makeUnprocessed_=function(mml){var node=this.createNode_();node.mathml=[mml];return node;};cvox.SemanticTree.prototype.makeEmptyNode_=function(){var node=this.createNode_();node.type=cvox.SemanticAttr.Type.EMPTY;return node;};cvox.SemanticTree.prototype.makeLeafNode_=function(mml){var node=this.createNode_();node.mathml=[mml];node.updateContent_(mml.textContent);node.font=mml.getAttribute('mathvariant')||node.font;return node;};cvox.SemanticTree.prototype.makeBranchNode_=function(type,children,contentNodes,content){var node=this.createNode_();if(content){node.updateContent_(content);}
node.type=type;node.childNodes=children;node.contentNodes=contentNodes;children.concat(contentNodes).forEach(function(x){x.parent=node;node.addMathmlNodes_(x.mathml);});return node;};cvox.SemanticTree.prototype.makeImplicitNode_=function(nodes){if(nodes.length==1){return nodes[0];}
var operator=this.createNode_();operator.updateContent_(cvox.SemanticAttr.invisibleTimes());var newNode=this.makeInfixNode_(nodes,operator);newNode.role=cvox.SemanticAttr.Role.IMPLICIT;return newNode;};cvox.SemanticTree.prototype.makeInfixNode_=function(children,opNode){return this.makeBranchNode_(cvox.SemanticAttr.Type.INFIXOP,children,[opNode],opNode.textContent);};cvox.SemanticTree.prototype.makeConcatNode_=function(inner,nodeList,type){if(nodeList.length==0){return inner;}
var content=nodeList.map(function(x){return x.textContent;}).join(' ');var newNode=this.makeBranchNode_(type,[inner],nodeList,content);if(nodeList.length>0){newNode.role=cvox.SemanticAttr.Role.MULTIOP;}
return newNode;};cvox.SemanticTree.prototype.makePrefixNode_=function(node,prefixes){var negatives=cvox.SemanticTree.partitionNodes_(prefixes,cvox.SemanticTree.attrPred_('role','SUBTRACTION'));var newNode=this.makeConcatNode_(node,negatives.comp.pop(),cvox.SemanticAttr.Type.PREFIXOP);while(negatives.rel.length>0){newNode=this.makeConcatNode_(newNode,[negatives.rel.pop()],cvox.SemanticAttr.Type.PREFIXOP);newNode.role=cvox.SemanticAttr.Role.NEGATIVE;newNode=this.makeConcatNode_(newNode,negatives.comp.pop(),cvox.SemanticAttr.Type.PREFIXOP);}
return newNode;};cvox.SemanticTree.prototype.makePostfixNode_=function(node,postfixes){return this.makeConcatNode_(node,postfixes,cvox.SemanticAttr.Type.POSTFIXOP);};cvox.SemanticTree.prototype.processRow_=function(nodes){if(nodes.length==0){return this.makeEmptyNode_();}
nodes=this.getFencesInRow_(nodes);nodes=this.processTablesInRow_(nodes);nodes=this.getPunctuationInRow_(nodes);nodes=this.getFunctionsInRow_(nodes);return this.processRelationsInRow_(nodes);};cvox.SemanticTree.prototype.processRelationsInRow_=function(nodes){var partition=cvox.SemanticTree.partitionNodes_(nodes,cvox.SemanticTree.attrPred_('type','RELATION'));var firstRel=partition.rel[0];if(!firstRel){return this.processOperationsInRow_(nodes);}
if(nodes.length==1){return nodes[0];}
var children=partition.comp.map(goog.bind(this.processOperationsInRow_,this));if(partition.rel.every(function(x){return x.textContent==firstRel.textContent;})){return this.makeBranchNode_(cvox.SemanticAttr.Type.RELSEQ,children,partition.rel,firstRel.textContent);}
return this.makeBranchNode_(cvox.SemanticAttr.Type.MULTIREL,children,partition.rel);};cvox.SemanticTree.prototype.processOperationsInRow_=function(nodes){if(nodes.length==0){return this.makeEmptyNode_();}
if(nodes.length==1){return nodes[0];}
var prefix=[];while(nodes.length>0&&nodes[0].type==cvox.SemanticAttr.Type.OPERATOR){prefix.push(nodes.shift());}
if(nodes.length==0){return this.makePrefixNode_(prefix.pop(),prefix);}
if(nodes.length==1){return this.makePrefixNode_(nodes[0],prefix);}
var split=cvox.SemanticTree.sliceNodes_(nodes,cvox.SemanticTree.attrPred_('type','OPERATOR'));var node=this.makePrefixNode_(this.makeImplicitNode_((split.head)),prefix);if(!split.div){return node;}
return this.makeOperationsTree_(split.tail,node,split.div);};cvox.SemanticTree.prototype.makeOperationsTree_=function(nodes,root,lastop,prefixes){prefixes=prefixes||[];if(nodes.length==0){prefixes.unshift(lastop);if(root.type==cvox.SemanticAttr.Type.INFIXOP){var node=this.makePostfixNode_((root.childNodes.pop()),prefixes);root.appendChild_(node);return root;}
return this.makePostfixNode_(root,prefixes);}
var split=cvox.SemanticTree.sliceNodes_(nodes,cvox.SemanticTree.attrPred_('type','OPERATOR'));if(split.head.length==0){prefixes.push(split.div);return this.makeOperationsTree_(split.tail,root,lastop,prefixes);}
var node=this.makePrefixNode_(this.makeImplicitNode_(split.head),prefixes);var newNode=this.appendOperand_(root,lastop,node);if(!split.div){return newNode;}
return this.makeOperationsTree_(split.tail,newNode,split.div,[]);};cvox.SemanticTree.prototype.appendOperand_=function(root,op,node){if(root.type!=cvox.SemanticAttr.Type.INFIXOP){return this.makeInfixNode_([root,node],op);}
if(this.appendExistingOperator_(root,op,node)){return root;}
return op.role==cvox.SemanticAttr.Role.MULTIPLICATION?this.appendMultiplicativeOp_(root,op,node):this.appendAdditiveOp_(root,op,node);};cvox.SemanticTree.prototype.appendMultiplicativeOp_=function(root,op,node){var lastRoot=root;var lastChild=root.childNodes[root.childNodes.length-1];while(lastChild&&lastChild.type==cvox.SemanticAttr.Type.INFIXOP){lastRoot=lastChild;lastChild=lastRoot.childNodes[root.childNodes.length-1];}
var newNode=this.makeInfixNode_([lastRoot.childNodes.pop(),node],op);lastRoot.appendChild_(newNode);return root;};cvox.SemanticTree.prototype.appendAdditiveOp_=function(root,op,node){return this.makeInfixNode_([root,node],op);};cvox.SemanticTree.prototype.appendExistingOperator_=function(root,op,node){if(!root||root.type!=cvox.SemanticAttr.Type.INFIXOP){return false;}
if(root.textContent==op.textContent){root.appendContentNode_(op);root.appendChild_(node);return true;}
this.appendExistingOperator_((root.childNodes[root.childNodes.length-1]),op,node);return false;};cvox.SemanticTree.prototype.getFencesInRow_=function(nodes){var partition=cvox.SemanticTree.partitionNodes_(nodes,cvox.SemanticTree.attrPred_('type','FENCE'));var felem=partition.comp.shift();return this.processFences_(partition.rel,partition.comp,[],[felem]);};cvox.SemanticTree.prototype.processFences_=function(fences,content,openStack,contentStack){if(fences.length==0&&openStack.length==0){return contentStack[0];}
var openPred=cvox.SemanticTree.attrPred_('role','OPEN');if(fences.length==0){var result=contentStack.shift();while(openStack.length>0){if(openPred(openStack[0])){var firstOpen=openStack.shift();cvox.SemanticTree.fenceToPunct_(firstOpen);result.push(firstOpen);}else{var split=cvox.SemanticTree.sliceNodes_(openStack,openPred);var cutLength=split.head.length-1;var innerNodes=this.processNeutralFences_(split.head,contentStack.slice(0,cutLength));contentStack=contentStack.slice(cutLength);result.push.apply(result,innerNodes);if(split.div){split.tail.unshift(split.div);}
openStack=split.tail;}
result.push.apply(result,contentStack.shift());}
return result;}
var lastOpen=openStack[openStack.length-1];var firstRole=fences[0].role;if(firstRole==cvox.SemanticAttr.Role.OPEN||(firstRole==cvox.SemanticAttr.Role.NEUTRAL&&(!lastOpen||fences[0].textContent!=lastOpen.textContent))){openStack.push(fences.shift());contentStack.push(content.shift());return this.processFences_(fences,content,openStack,contentStack);}
if(lastOpen&&((firstRole==cvox.SemanticAttr.Role.CLOSE&&lastOpen.role==cvox.SemanticAttr.Role.OPEN)||(firstRole==cvox.SemanticAttr.Role.NEUTRAL&&fences[0].textContent==lastOpen.textContent))){var fenced=this.makeHorizontalFencedNode_(openStack.pop(),fences.shift(),contentStack.pop());contentStack.push(contentStack.pop().concat([fenced],content.shift()));return this.processFences_(fences,content,openStack,contentStack);}
if(lastOpen&&firstRole==cvox.SemanticAttr.Role.CLOSE&&lastOpen.role==cvox.SemanticAttr.Role.NEUTRAL&&openStack.some(openPred)){var split=cvox.SemanticTree.sliceNodes_(openStack,openPred,true);var rightContent=contentStack.pop();var cutLength=contentStack.length-split.tail.length+1;var innerNodes=this.processNeutralFences_(split.tail,contentStack.slice(cutLength));contentStack=contentStack.slice(0,cutLength);var fenced=this.makeHorizontalFencedNode_(split.div,fences.shift(),contentStack.pop().concat(innerNodes,rightContent));contentStack.push(contentStack.pop().concat([fenced],content.shift()));return this.processFences_(fences,content,split.head,contentStack);}
var fenced=fences.shift();cvox.SemanticTree.fenceToPunct_(fenced);contentStack.push(contentStack.pop().concat([fenced],content.shift()));return this.processFences_(fences,content,openStack,contentStack);};cvox.SemanticTree.prototype.processNeutralFences_=function(fences,content){if(fences.length==0){return fences;}
if(fences.length==1){cvox.SemanticTree.fenceToPunct_(fences[0]);return fences;}
var firstFence=fences.shift();var split=cvox.SemanticTree.sliceNodes_(fences,function(x){return x.textContent==firstFence.textContent;});if(!split.div){cvox.SemanticTree.fenceToPunct_(firstFence);var restContent=content.shift();restContent.unshift(firstFence);return restContent.concat(this.processNeutralFences_(fences,content));}
var newContent=this.combineFencedContent_(firstFence,split.div,split.head,content);if(split.tail.length>0){var leftContent=newContent.shift();var result=this.processNeutralFences_(split.tail,newContent);return leftContent.concat(result);}
return newContent[0];};cvox.SemanticTree.prototype.combineFencedContent_=function(leftFence,rightFence,midFences,content){if(midFences.length==0){var fenced=this.makeHorizontalFencedNode_(leftFence,rightFence,content.shift());content.unshift(fenced);return content;}
var leftContent=content.shift();var cutLength=midFences.length-1;var midContent=content.slice(0,cutLength);content=content.slice(cutLength);var rightContent=content.shift();var innerNodes=this.processNeutralFences_(midFences,midContent);leftContent.push.apply(leftContent,innerNodes);leftContent.push.apply(leftContent,rightContent);var fenced=this.makeHorizontalFencedNode_(leftFence,rightFence,leftContent);if(content.length>0){content[0].unshift(fenced);}else{content=[[fenced]];}
return content;};cvox.SemanticTree.fenceToPunct_=function(fence){fence.type=cvox.SemanticAttr.Type.PUNCTUATION;switch(fence.role){case cvox.SemanticAttr.Role.NEUTRAL:fence.role=cvox.SemanticAttr.Role.VBAR;break;case cvox.SemanticAttr.Role.OPEN:fence.role=cvox.SemanticAttr.Role.OPENFENCE;break;case cvox.SemanticAttr.Role.CLOSE:fence.role=cvox.SemanticAttr.Role.CLOSEFENCE;break;}};cvox.SemanticTree.prototype.makeHorizontalFencedNode_=function(ofence,cfence,content){var childNode=this.processRow_(content);var newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.FENCED,[childNode],[ofence,cfence]);if(ofence.role==cvox.SemanticAttr.Role.OPEN){newNode.role=cvox.SemanticAttr.Role.LEFTRIGHT;}else{newNode.role=ofence.role;}
return newNode;};cvox.SemanticTree.prototype.getPunctuationInRow_=function(nodes){var partition=cvox.SemanticTree.partitionNodes_(nodes,function(x){return cvox.SemanticTree.attrPred_('type','PUNCTUATION')(x)&&!cvox.SemanticTree.attrPred_('role','ELLIPSIS')(x);});if(partition.rel.length==0){return nodes;}
var newNodes=[];var firstComp=partition.comp.shift();if(firstComp.length>0){newNodes.push(this.processRow_(firstComp));}
var relCounter=0;while(partition.comp.length>0){newNodes.push(partition.rel[relCounter++]);firstComp=partition.comp.shift();if(firstComp.length>0){newNodes.push(this.processRow_(firstComp));}}
return[this.makePunctuatedNode_(newNodes,partition.rel)];};cvox.SemanticTree.prototype.makePunctuatedNode_=function(nodes,punctuations){var newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.PUNCTUATED,nodes,punctuations);if(punctuations.length==1&&nodes[0].type==cvox.SemanticAttr.Type.PUNCTUATION){newNode.role=cvox.SemanticAttr.Role.STARTPUNCT;}else if(punctuations.length==1&&nodes[nodes.length-1].type==cvox.SemanticAttr.Type.PUNCTUATION){newNode.role=cvox.SemanticAttr.Role.ENDPUNCT;}else{newNode.role=cvox.SemanticAttr.Role.SEQUENCE;}
return newNode;};cvox.SemanticTree.prototype.makeLimitNode_=function(mmlTag,children){var center=children[0];var isFunction=cvox.SemanticTree.attrPred_('type','FUNCTION')(center);var isLimit=cvox.SemanticTree.attrPred_('type','LARGEOP')(center)||cvox.SemanticTree.attrPred_('type','LIMBOTH')(center)||cvox.SemanticTree.attrPred_('type','LIMLOWER')(center)||cvox.SemanticTree.attrPred_('type','LIMUPPER')(center)||(isFunction&&cvox.SemanticTree.attrPred_('role','LIMFUNC')(center));var type=cvox.SemanticAttr.Type.UNKNOWN;if(isLimit){switch(mmlTag){case'MSUB':case'MUNDER':type=cvox.SemanticAttr.Type.LIMLOWER;break;case'MSUP':case'MOVER':type=cvox.SemanticAttr.Type.LIMUPPER;break;case'MSUBSUP':case'MUNDEROVER':type=cvox.SemanticAttr.Type.LIMBOTH;break;}}else{switch(mmlTag){case'MSUB':type=cvox.SemanticAttr.Type.SUBSCRIPT;break;case'MSUP':type=cvox.SemanticAttr.Type.SUPERSCRIPT;break;case'MSUBSUP':var innerNode=this.makeBranchNode_(cvox.SemanticAttr.Type.SUBSCRIPT,[center,children[1]],[]);innerNode.role=center.role;children=[innerNode,children[2]];type=cvox.SemanticAttr.Type.SUPERSCRIPT;break;case'MOVER':type=cvox.SemanticAttr.Type.OVERSCORE;break;case'MUNDER':type=cvox.SemanticAttr.Type.UNDERSCORE;break;case'MUNDEROVER':default:var innerNode=this.makeBranchNode_(cvox.SemanticAttr.Type.UNDERSCORE,[center,children[1]],[]);innerNode.role=center.role;children=[innerNode,children[2]];type=cvox.SemanticAttr.Type.OVERSCORE;break;}}
var newNode=this.makeBranchNode_(type,children,[]);newNode.role=center.role;return newNode;};cvox.SemanticTree.prototype.getFunctionsInRow_=function(restNodes,result){result=result||[];if(restNodes.length==0){return result;}
var firstNode=(restNodes.shift());var heuristic=cvox.SemanticTree.classifyFunction_(firstNode,restNodes);if(!heuristic){result.push(firstNode);return this.getFunctionsInRow_(restNodes,result);}
var processedRest=this.getFunctionsInRow_(restNodes,[]);var newRest=this.getFunctionArgs_(firstNode,processedRest,heuristic);return result.concat(newRest);};cvox.SemanticTree.classifyFunction_=function(funcNode,restNodes){if(funcNode.type==cvox.SemanticAttr.Type.APPL||funcNode.type==cvox.SemanticAttr.Type.BIGOP||funcNode.type==cvox.SemanticAttr.Type.INTEGRAL){return'';}
if(restNodes[0]&&restNodes[0].textContent==cvox.SemanticAttr.functionApplication()){restNodes.shift();cvox.SemanticTree.propagatePrefixFunc_(funcNode);return'prefix';}
switch(funcNode.role){case cvox.SemanticAttr.Role.INTEGRAL:return'integral';break;case cvox.SemanticAttr.Role.SUM:return'bigop';break;case cvox.SemanticAttr.Role.PREFIXFUNC:case cvox.SemanticAttr.Role.LIMFUNC:return'prefix';break;default:if(funcNode.type==cvox.SemanticAttr.Type.IDENTIFIER){return'simple';}}
return'';};cvox.SemanticTree.propagatePrefixFunc_=function(funcNode){if(funcNode){funcNode.role=cvox.SemanticAttr.Role.PREFIXFUNC;cvox.SemanticTree.propagatePrefixFunc_(funcNode.childNodes[0]);}};cvox.SemanticTree.prototype.getFunctionArgs_=function(func,rest,heuristic){switch(heuristic){case'integral':var components=this.getIntegralArgs_(rest);var integrand=this.processRow_(components.integrand);var funcNode=this.makeIntegralNode_(func,integrand,components.intvar);components.rest.unshift(funcNode);return components.rest;break;case'prefix':if(rest[0]&&rest[0].type==cvox.SemanticAttr.Type.FENCED){funcNode=this.makeFunctionNode_(func,(rest.shift()));rest.unshift(funcNode);return rest;}
case'bigop':var partition=cvox.SemanticTree.sliceNodes_(rest,cvox.SemanticTree.prefixFunctionBoundary_);var arg=this.processRow_(partition.head);if(heuristic=='prefix'){funcNode=this.makeFunctionNode_(func,arg);}else{funcNode=this.makeBigOpNode_(func,arg);}
if(partition.div){partition.tail.unshift(partition.div);}
partition.tail.unshift(funcNode);return partition.tail;break;case'simple':if(rest.length==0){return[func];}
var firstArg=rest[0];if(firstArg.type==cvox.SemanticAttr.Type.FENCED&&firstArg.role!=cvox.SemanticAttr.Role.NEUTRAL&&this.simpleFunctionHeuristic_(firstArg)){funcNode=this.makeFunctionNode_(func,(rest.shift()));rest.unshift(funcNode);return rest;}
rest.unshift(func);return rest;break;}
return[];};cvox.SemanticTree.prototype.getIntegralArgs_=function(nodes,args){args=args||[];if(nodes.length==0){return{integrand:args,intvar:null,rest:nodes};}
var firstNode=nodes[0];if(cvox.SemanticTree.generalFunctionBoundary_(firstNode)){return{integrand:args,intvar:null,rest:nodes};}
if(cvox.SemanticTree.integralDxBoundarySingle_(firstNode)){return{integrand:args,intvar:firstNode,rest:nodes.slice(1)};}
if(nodes[1]&&cvox.SemanticTree.integralDxBoundary_(firstNode,nodes[1])){var comma=this.createNode_();comma.updateContent_(cvox.SemanticAttr.invisibleComma());var intvar=this.makePunctuatedNode_([firstNode,comma,nodes[1]],[comma]);intvar.role=cvox.SemanticAttr.Role.INTEGRAL;return{integrand:args,intvar:intvar,rest:nodes.slice(2)};}
args.push(nodes.shift());return this.getIntegralArgs_(nodes,args);};cvox.SemanticTree.prototype.makeFunctionNode_=function(func,arg){var applNode=this.createNode_();applNode.updateContent_(cvox.SemanticAttr.functionApplication());applNode.type=cvox.SemanticAttr.Type.PUNCTUATION;applNode.role=cvox.SemanticAttr.Role.APPLICATION;var newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.APPL,[func,arg],[applNode]);newNode.role=func.role;return newNode;};cvox.SemanticTree.prototype.makeBigOpNode_=function(bigOp,arg){var newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.BIGOP,[bigOp,arg],[]);newNode.role=bigOp.role;return newNode;};cvox.SemanticTree.prototype.makeIntegralNode_=function(integral,integrand,intvar){integrand=integrand||this.makeEmptyNode_();intvar=intvar||this.makeEmptyNode_();var newNode=this.makeBranchNode_(cvox.SemanticAttr.Type.INTEGRAL,[integral,integrand,intvar],[]);newNode.role=integral.role;return newNode;};cvox.SemanticTree.prototype.simpleFunctionHeuristic_=function(node){var children=node.childNodes;if(children.length==0){return true;}
if(children.length>1){return false;}
var child=children[0];if(child.type==cvox.SemanticAttr.Type.INFIXOP){if(child.role!=cvox.SemanticAttr.Role.IMPLICIT){return false;}
if(child.childNodes.some(cvox.SemanticTree.attrPred_('type','INFIXOP'))){return false;}}
return true;};cvox.SemanticTree.prefixFunctionBoundary_=function(node){return cvox.SemanticTree.attrPred_('type','OPERATOR')(node)||cvox.SemanticTree.generalFunctionBoundary_(node);};cvox.SemanticTree.integralDxBoundary_=function(firstNode,secondNode){return!!secondNode&&cvox.SemanticTree.attrPred_('type','IDENTIFIER')(secondNode)&&cvox.SemanticAttr.isCharacterD(firstNode.textContent);};cvox.SemanticTree.integralDxBoundarySingle_=function(node){if(cvox.SemanticTree.attrPred_('type','IDENTIFIER')(node)){var firstChar=node.textContent[0];return firstChar&&node.textContent[1]&&cvox.SemanticAttr.isCharacterD(firstChar);}
return false;};cvox.SemanticTree.generalFunctionBoundary_=function(node){return cvox.SemanticTree.attrPred_('type','RELATION')(node)||cvox.SemanticTree.attrPred_('type','PUNCTUATION')(node);};cvox.SemanticTree.prototype.processTablesInRow_=function(nodes){var partition=cvox.SemanticTree.partitionNodes_(nodes,cvox.SemanticTree.tableIsMatrixOrVector_);var result=[];for(var i=0,matrix;matrix=partition.rel[i];i++){result=result.concat(partition.comp.shift());result.push(this.tableToMatrixOrVector_(matrix));}
result=result.concat(partition.comp.shift());partition=cvox.SemanticTree.partitionNodes_(result,cvox.SemanticTree.isTableOrMultiline_);result=[];for(var i=0,table;table=partition.rel[i];i++){var prevNodes=partition.comp.shift();if(cvox.SemanticTree.tableIsCases_(table,prevNodes)){this.tableToCases_(table,(prevNodes.pop()));}
result=result.concat(prevNodes);result.push(table);}
return result.concat(partition.comp.shift());};cvox.SemanticTree.isTableOrMultiline_=function(node){return!!node&&(cvox.SemanticTree.attrPred_('type','TABLE')(node)||cvox.SemanticTree.attrPred_('type','MULTILINE')(node));};cvox.SemanticTree.tableIsMatrixOrVector_=function(node){return!!node&&cvox.SemanticTree.attrPred_('type','FENCED')(node)&&cvox.SemanticTree.attrPred_('role','LEFTRIGHT')(node)&&node.childNodes.length==1&&cvox.SemanticTree.isTableOrMultiline_(node.childNodes[0]);};cvox.SemanticTree.prototype.tableToMatrixOrVector_=function(node){var matrix=node.childNodes[0];var type=cvox.SemanticTree.attrPred_('type','MULTILINE')(matrix)?'VECTOR':'MATRIX';matrix.type=cvox.SemanticAttr.Type[type];node.contentNodes.forEach(goog.bind(matrix.appendContentNode_,matrix));for(var i=0,row;row=matrix.childNodes[i];i++){cvox.SemanticTree.assignRoleToRow_(row,cvox.SemanticAttr.Role[type]);}
return matrix;};cvox.SemanticTree.tableIsCases_=function(table,prevNodes){return prevNodes.length>0&&cvox.SemanticTree.attrPred_('role','OPENFENCE')(prevNodes[prevNodes.length-1]);};cvox.SemanticTree.prototype.tableToCases_=function(table,openFence){for(var i=0,row;row=table.childNodes[i];i++){cvox.SemanticTree.assignRoleToRow_(row,cvox.SemanticAttr.Role.CASES);}
table.type=cvox.SemanticAttr.Type.CASES;table.appendContentNode_(openFence);return table;};cvox.SemanticTree.tableIsMultiline_=function(table){return table.childNodes.every(function(row){var length=row.childNodes.length;return length<=1;});};cvox.SemanticTree.prototype.tableToMultiline_=function(table){table.type=cvox.SemanticAttr.Type.MULTILINE;for(var i=0,row;row=table.childNodes[i];i++){cvox.SemanticTree.rowToLine_(row,cvox.SemanticAttr.Role.MULTILINE);}};cvox.SemanticTree.rowToLine_=function(row,role){role=role||cvox.SemanticAttr.Role.UNKNOWN;if(cvox.SemanticTree.attrPred_('type','ROW')(row)&&row.childNodes.length==1&&cvox.SemanticTree.attrPred_('type','CELL')(row.childNodes[0])){row.type=cvox.SemanticAttr.Type.LINE;row.role=role;row.childNodes=row.childNodes[0].childNodes;}};cvox.SemanticTree.assignRoleToRow_=function(row,role){if(cvox.SemanticTree.attrPred_('type','LINE')(row)){row.role=role;return;}
if(cvox.SemanticTree.attrPred_('type','ROW')(row)){row.role=role;var cellPred=cvox.SemanticTree.attrPred_('type','CELL');row.childNodes.forEach(function(cell){if(cellPred(cell)){cell.role=role;}});}};cvox.SemanticTree.sliceNodes_=function(nodes,pred,reverse){if(reverse){nodes.reverse();}
var head=[];for(var i=0,node;node=nodes[i];i++){if(pred(node)){if(reverse){return{head:nodes.slice(i+1).reverse(),div:node,tail:head.reverse()};}
return{head:head,div:node,tail:nodes.slice(i+1)};}
head.push(node);}
if(reverse){return{head:[],div:null,tail:head.reverse()};}
return{head:head,div:null,tail:[]};};cvox.SemanticTree.partitionNodes_=function(nodes,pred){var restNodes=nodes;var rel=[];var comp=[];do{var result=cvox.SemanticTree.sliceNodes_(restNodes,pred);comp.push(result.head);rel.push(result.div);restNodes=result.tail;}while(result.div);rel.pop();return{rel:rel,comp:comp};};cvox.SemanticTree.attrPred_=function(prop,attr){var getAttr=function(prop){switch(prop){case'type':return cvox.SemanticAttr.Type[attr];case'role':return cvox.SemanticAttr.Role[attr];case'font':return cvox.SemanticAttr.Font[attr];}};return function(node){return node[prop]==getAttr(prop);};};goog.provide('cvox.TraverseMath');goog.require('cvox.ChromeVox');goog.require('cvox.DomUtil');goog.require('cvox.SemanticTree');cvox.TraverseMath=function(){this.activeMath=null;this.activeNode=null;this.allTexs_={};this.allMathjaxs_={};this.todoMathjaxs_={};this.activeMathmlHost=null;this.activeSemanticHost=null;this.allDomains=[];this.allStyles=[];this.domain='default';this.style='short';if(cvox.ChromeVox.mathJax){this.initializeMathjaxs();this.initializeAltMaths();}};goog.addSingletonGetter(cvox.TraverseMath);cvox.TraverseMath.setSemantic_=false;cvox.TraverseMath.toggleSemantic=function(){return cvox.TraverseMath.setSemantic_=!cvox.TraverseMath.setSemantic_;};cvox.TraverseMath.prototype.initialize=function(node){if(cvox.DomUtil.isMathImg(node)){if(!node.hasAttribute('cvoxid')){return;}
var cvoxid=node.getAttribute('cvoxid');node=this.allTexs_[cvoxid];}
if(cvox.DomUtil.isMathJax(node)){this.activeMathmlHost=this.allMathjaxs_[node.getAttribute('id')];}
this.activeMath=this.activeMathmlHost||node;this.activeNode=this.activeMathmlHost||node;if(this.activeNode&&cvox.TraverseMath.setSemantic_&&this.activeNode.nodeType==Node.ELEMENT_NODE){this.activeNode=(new cvox.SemanticTree((this.activeNode))).xml();}};cvox.TraverseMath.prototype.addMathjax=function(mml,id){var spanId=cvox.DomUtil.getMathSpanId(id);if(spanId){this.allMathjaxs_[spanId]=mml;}else{this.redoMathjaxs(mml,id);}};cvox.TraverseMath.prototype.redoMathjaxs=function(mml,id){var fetch=goog.bind(function(){this.addMathjax(mml,id);},this);setTimeout(fetch,500);};cvox.TraverseMath.prototype.initializeMathjaxs=function(){var callback=goog.bind(function(mml,id){this.addMathjax(mml,id);},this);cvox.ChromeVox.mathJax.isMathjaxActive(function(bool){if(bool){cvox.ChromeVox.mathJax.getAllJax(callback);cvox.ChromeVox.mathJax.registerSignal(callback,'New Math');}});};cvox.TraverseMath.prototype.initializeAltMaths=function(){if(!document.querySelector(cvox.DomUtil.altMathQuerySelector('tex')+', '+
cvox.DomUtil.altMathQuerySelector('asciimath'))){return;}
var callback=goog.bind(function(mml,id){this.allTexs_[id]=mml;},this);cvox.ChromeVox.mathJax.injectScripts();cvox.ChromeVox.mathJax.isMathjaxActive(function(active){if(active){cvox.ChromeVox.mathJax.configMediaWiki();cvox.ChromeVox.mathJax.getAllTexs(callback);cvox.ChromeVox.mathJax.getAllAsciiMaths(callback);}});};cvox.TraverseMath.prototype.nextLeaf=function(reverse,pred){if(this.activeNode&&this.activeMath){var next=pred(this.activeNode)?cvox.DomUtil.directedFindNextNode(this.activeNode,this.activeMath,reverse,pred):cvox.DomUtil.directedFindFirstNode(this.activeNode,reverse,pred);if(next){this.activeNode=next;}}
return this.activeNode;};cvox.TraverseMath.prototype.activeContent=function(){return this.activeNode.textContent;};cvox.TraverseMath.prototype.nextSubtree=function(reverse,pred){if(!this.activeNode||!this.activeMath){return null;}
if(!reverse){var child=cvox.DomUtil.directedFindFirstNode(this.activeNode,reverse,pred);if(child){this.activeNode=child;}else{var next=cvox.DomUtil.directedFindNextNode(this.activeNode,this.activeMath,reverse,pred);if(next){this.activeNode=next;}}}else{if(this.activeNode==this.activeMath){var child=cvox.DomUtil.directedFindDeepestNode(this.activeNode,reverse,pred);if(child!=this.activeNode){this.activeNode=child;return this.activeNode;}}
var prev=cvox.DomUtil.directedFindNextNode(this.activeNode,this.activeMath,reverse,pred,true,true);if(prev){this.activeNode=prev;}}
return this.activeNode;};cvox.TraverseMath.prototype.nextSibling=function(r){if(!this.activeNode||!this.activeMath){return null;}
var node=this.activeNode;node=r?node.previousSibling:node.nextSibling;if(!node){return null;}
this.activeNode=node;return this.activeNode;};cvox.TraverseMath.prototype.nextParentChild=function(r){if(!this.activeNode||!this.activeMath){return null;}
if(this.activeNode==this.activeMath&&r){return null;}
var node=this.activeNode;node=r?node.parentNode:node.firstChild;if(!node){return null;}
this.activeNode=node;return this.activeNode;};cvox.TraverseMath.prototype.addDomainsAndStyles=function(domains,styles){this.allDomains.push.apply(this.allDomains,domains.filter(goog.bind(function(x){return this.allDomains.indexOf(x)<0;},this)));this.allStyles.push.apply(this.allStyles,styles.filter(goog.bind(function(x){return this.allStyles.indexOf(x)<0;},this)));};cvox.TraverseMath.prototype.initDomainsAndStyles=function(){if(cvox.ChromeVox.host['mathMap']){this.addDomainsAndStyles(cvox.ChromeVox.host['mathMap'].allDomains,cvox.ChromeVox.host['mathMap'].allStyles);}else{cvox.ChromeVox.host.sendToBackgroundPage({'target':'Math','action':'getDomains'});}};cvox.TraverseMath.prototype.cycleDomain=function(){this.initDomainsAndStyles();var index=this.allDomains.indexOf(this.domain);if(index==-1){return this.domain;}
this.domain=this.allDomains[(++index)%this.allDomains.length];return this.domain;};cvox.TraverseMath.prototype.cycleStyle=function(){this.initDomainsAndStyles();var index=this.allStyles.indexOf(this.style);if(index==-1){return this.domain;}
this.style=this.allStyles[(++index)%this.allStyles.length];return this.style;};cvox.TraverseMath.prototype.setDomain_=function(domain){if(this.allDomains.indexOf(domain)!=-1){this.domain=domain;}else{this.domain='default';}};cvox.TraverseMath.prototype.setStyle_=function(style){if(this.allStyles.indexOf(style)!=-1){this.style=style;}else{this.style='default';}};cvox.TraverseMath.prototype.getAttachedActiveNode=function(){var node=this.activeNode;if(!node||node.nodeType!=Node.ELEMENT_NODE){return null;}
var id=node.getAttribute('spanID');return document.getElementById(id);};goog.provide('cvox.SpeechRule');goog.provide('cvox.SpeechRule.Action');goog.provide('cvox.SpeechRule.Component');goog.provide('cvox.SpeechRule.DynamicCstr');goog.provide('cvox.SpeechRule.Precondition');goog.provide('cvox.SpeechRule.Type');cvox.SpeechRule=function(name,dynamic,prec,action){this.name=name;this.dynamicCstr=dynamic;this.precondition=prec;this.action=action;};cvox.SpeechRule.prototype.toString=function(){var cstrStrings=[];for(var key in this.dynamicCstr){cstrStrings.push(this.dynamicCstr[key]);}
return this.name+' | '+cstrStrings.join('.')+' | '+
this.precondition.toString()+' ==> '+
this.action.toString();};cvox.SpeechRule.Type={NODE:'NODE',MULTI:'MULTI',TEXT:'TEXT',PERSONALITY:'PERSONALITY'};cvox.SpeechRule.Type.fromString=function(str){switch(str){case'[n]':return cvox.SpeechRule.Type.NODE;case'[m]':return cvox.SpeechRule.Type.MULTI;case'[t]':return cvox.SpeechRule.Type.TEXT;case'[p]':return cvox.SpeechRule.Type.PERSONALITY;default:throw'Parse error: '+str;}};cvox.SpeechRule.Type.toString=function(speechType){switch(speechType){case cvox.SpeechRule.Type.NODE:return'[n]';case cvox.SpeechRule.Type.MULTI:return'[m]';case cvox.SpeechRule.Type.TEXT:return'[t]';case cvox.SpeechRule.Type.PERSONALITY:return'[p]';default:throw'Unknown type error: '+speechType;}};cvox.SpeechRule.Component=function(kwargs){this.type=kwargs.type;this.content=kwargs.content;};cvox.SpeechRule.Component.fromString=function(input){var output={};output.type=cvox.SpeechRule.Type.fromString(input.substring(0,3));var rest=input.slice(3).trimLeft();if(!rest){throw new cvox.SpeechRule.OutputError('Missing content.');}
switch(output.type){case cvox.SpeechRule.Type.TEXT:if(rest[0]=='"'){var quotedString=cvox.SpeechRule.splitString_(rest,'\\(')[0].trim();if(quotedString.slice(-1)!='"'){throw new cvox.SpeechRule.OutputError('Invalid string syntax.');}
output.content=quotedString;rest=rest.slice(quotedString.length).trim();if(rest.indexOf('(')==-1){rest='';}
break;}
case cvox.SpeechRule.Type.NODE:case cvox.SpeechRule.Type.MULTI:var bracket=rest.indexOf(' (');if(bracket==-1){output.content=rest.trim();rest='';break;}
output.content=rest.substring(0,bracket).trim();rest=rest.slice(bracket).trimLeft();break;}
output=new cvox.SpeechRule.Component(output);if(rest){output.addAttributes(rest);}
return output;};cvox.SpeechRule.Component.prototype.toString=function(){var strs='';strs+=cvox.SpeechRule.Type.toString(this.type);strs+=this.content?' '+this.content:'';var attribs=this.getAttributes();if(attribs.length>0){strs+=' ('+attribs.join(', ')+')';}
return strs;};cvox.SpeechRule.Component.prototype.addAttribute=function(attr){var colon=attr.indexOf(':');if(colon==-1){this[attr.trim()]='true';}else{this[attr.substring(0,colon).trim()]=attr.slice(colon+1).trim();}};cvox.SpeechRule.Component.prototype.addAttributes=function(attrs){if(attrs[0]!='('||attrs.slice(-1)!=')'){throw new cvox.SpeechRule.OutputError('Invalid attribute expression: '+attrs);}
var attribs=cvox.SpeechRule.splitString_(attrs.slice(1,-1),',');for(var i=0;i<attribs.length;i++){this.addAttribute(attribs[i]);}};cvox.SpeechRule.Component.prototype.getAttributes=function(){var attribs=[];for(var key in this){if(key!='content'&&key!='type'&&typeof(this[key])!='function'){attribs.push(key+':'+this[key]);}}
return attribs;};cvox.SpeechRule.Action=function(components){this.components=components;};cvox.SpeechRule.Action.fromString=function(input){var comps=cvox.SpeechRule.splitString_(input,';').filter(function(x){return x.match(/\S/);}).map(function(x){return x.trim();});var newComps=[];for(var i=0;i<comps.length;i++){var comp=cvox.SpeechRule.Component.fromString(comps[i]);if(comp){newComps.push(comp);}}
return new cvox.SpeechRule.Action(newComps);};cvox.SpeechRule.Action.prototype.toString=function(){var comps=this.components.map(function(c){return c.toString();});return comps.join('; ');};cvox.SpeechRule.Precondition=function(query,opt_constraints){this.query=query;this.constraints=opt_constraints||[];};cvox.SpeechRule.Precondition.prototype.toString=function(){var constrs=this.constraints.join(', ');return this.query+', '+constrs;};cvox.SpeechRule.splitString_=function(str,sep){var strList=[];var prefix='';while(str!=''){var sepPos=str.search(sep);if(sepPos==-1){if((str.match(/"/g)||[]).length%2!=0){throw new cvox.SpeechRule.OutputError('Invalid string in expression: '+str);}
strList.push(prefix+str);prefix='';str='';}else if((str.substring(0,sepPos).match(/"/g)||[]).length%2==0){strList.push(prefix+str.substring(0,sepPos));prefix='';str=str.substring(sepPos+1);}else{var nextQuot=str.substring(sepPos).search('"');if(nextQuot==-1){throw new cvox.SpeechRule.OutputError('Invalid string in expression: '+str);}else{prefix=prefix+str.substring(0,sepPos+nextQuot+1);str=str.substring(sepPos+nextQuot+1);}}}
if(prefix){strList.push(prefix);}
return strList;};cvox.SpeechRule.DynamicCstrAttrib={STYLE:'style'};cvox.SpeechRule.DynamicCstr;cvox.SpeechRule.OutputError=function(msg){this.name='RuleError';this.message=msg||'';};goog.inherits(cvox.SpeechRule.OutputError,Error);goog.provide('cvox.NavMathDescription');goog.require('cvox.NavDescription');cvox.NavMathDescription=function(kwargs){goog.base(this,kwargs);var newPersonality=this.personality?this.personality:{};var mathDescr=new Object();mathDescr['domain']=kwargs.domain?kwargs.domain:'';mathDescr['style']=kwargs.style?kwargs.style:'';newPersonality['math']=mathDescr;this.personality=newPersonality;};goog.inherits(cvox.NavMathDescription,cvox.NavDescription);goog.provide('cvox.SpeechRuleFunctions');goog.provide('cvox.SpeechRuleFunctions.ContextFunctions');goog.provide('cvox.SpeechRuleFunctions.CustomQueries');goog.provide('cvox.SpeechRuleFunctions.CustomStrings');cvox.SpeechRuleFunctions=function(){};cvox.SpeechRuleFunctions.Store_=function(prefix,store){this.prefix_=prefix;this.store_=store;};cvox.SpeechRuleFunctions.Store_.prototype.add=function(name,func){if(this.checkCustomFunctionSyntax_(name)){this.store_[name]=func;}};cvox.SpeechRuleFunctions.Store_.prototype.lookup=function(name){return this.store_[name];};cvox.SpeechRuleFunctions.CustomQuery;cvox.SpeechRuleFunctions.CustomQueries=function(){var store=({});goog.base(this,'CQF',store);};goog.inherits(cvox.SpeechRuleFunctions.CustomQueries,cvox.SpeechRuleFunctions.Store_);cvox.SpeechRuleFunctions.CustomString;cvox.SpeechRuleFunctions.CustomStrings=function(){var store=({});goog.base(this,'CSF',store);};goog.inherits(cvox.SpeechRuleFunctions.CustomStrings,cvox.SpeechRuleFunctions.Store_);cvox.SpeechRuleFunctions.ContextFunction;cvox.SpeechRuleFunctions.ContextFunctions=function(){var store=({});goog.base(this,'CTXF',store);};goog.inherits(cvox.SpeechRuleFunctions.ContextFunctions,cvox.SpeechRuleFunctions.Store_);cvox.SpeechRuleFunctions.Store_.prototype.checkCustomFunctionSyntax_=function(name){var reg=new RegExp('^'+this.prefix_);if(!name.match(reg)){console.log('FunctionError: Invalid function name. Expected prefix'+
this.prefix_);return false;}
return true;};goog.provide('cvox.SpeechRuleEvaluator');goog.require('cvox.SpeechRule');cvox.SpeechRuleEvaluator=goog.abstractMethod;cvox.SpeechRuleEvaluator.prototype.evaluateDefault=goog.abstractMethod;goog.provide('cvox.SpeechRuleStore');cvox.SpeechRuleStore=goog.abstractMethod;cvox.SpeechRuleStore.prototype.addRule=goog.abstractMethod;cvox.SpeechRuleStore.prototype.deleteRule=goog.abstractMethod;cvox.SpeechRuleStore.prototype.findRule=goog.abstractMethod;cvox.SpeechRuleStore.prototype.findAllRules=goog.abstractMethod;cvox.SpeechRuleStore.prototype.lookupRule=goog.abstractMethod;cvox.SpeechRuleStore.prototype.defineRule=goog.abstractMethod;goog.provide('cvox.MathUtil');goog.require('cvox.ChromeVox');goog.require('cvox.XpathUtil');cvox.MathUtil.isMathmlNodeOfClass_=function(node,tags){return tags.indexOf(node.tagName.toUpperCase())!=-1;};cvox.MathUtil.isMathjaxNodeOfClass_=function(node,tags){if(node.tagName=='SPAN'){var classes=node.className.split(' ');return classes.some(function(x)
{return tags.indexOf(x.toUpperCase())!=-1;});}
return false;};cvox.MathUtil.isMathNodeOfClass_=function(node,tags){return(node.nodeType==Node.ELEMENT_NODE&&(cvox.MathUtil.isMathmlNodeOfClass_(node,tags)||cvox.MathUtil.isMathjaxNodeOfClass_(node,tags)));};cvox.MathUtil.TOKEN_LIST=['MI','MN','MO','MTEXT','MSPACE','MS'];cvox.MathUtil.isToken=function(element){return cvox.MathUtil.isMathNodeOfClass_(element,cvox.MathUtil.TOKEN_LIST);};cvox.MathUtil.LAYOUT_LIST=['MROW','MFRAC','MSQRT','MROOT','MSTYLE','MERROR','MPADDED','MPHANTOM','MFENCED','MENCLOSE'];cvox.MathUtil.isLayout=function(element){return cvox.MathUtil.isMathNodeOfClass_(element,cvox.MathUtil.LAYOUT_LIST);};cvox.MathUtil.SCRIPT_LIST=['MSUB','MSUP','MSUBSUP','MUNDER','MOVER','MUNDEROVER','MMULTISCRIPTS','MPRESCRIPTS'];cvox.MathUtil.isScript=function(element){return cvox.MathUtil.isMathNodeOfClass_(element,cvox.MathUtil.SCRIPT_LIST);};cvox.MathUtil.TABLES_LIST=['MTABLE','MLABELEDTR','MTR','MTD','MALIGNGROUP','MALIGNMARK'];cvox.MathUtil.isTables=function(element){return cvox.MathUtil.isMathNodeOfClass_(element,cvox.MathUtil.TABLES_LIST);};cvox.MathUtil.ELEMENTARY_LIST=['MSTACK','MLONGDIV','MSGROUP','MSROW','MSCARRIES','MSCARRY','MSLINE'];cvox.MathUtil.isElementary=function(element){return cvox.MathUtil.isMathNodeOfClass_(element,cvox.MathUtil.ELEMENTARY_LIST);};cvox.MathUtil.MATHML_TAG_LIST=[cvox.MathUtil.TOKEN_LIST,cvox.MathUtil.LAYOUT_LIST,cvox.MathUtil.SCRIPT_LIST,cvox.MathUtil.TABLES_LIST,cvox.MathUtil.ELEMENTARY_LIST].reduce(function(x,y){return x.concat(y);});cvox.MathUtil.isMathmlTag=function(element){return cvox.MathUtil.isMathNodeOfClass_(element,cvox.MathUtil.MATHML_TAG_LIST);};cvox.MathUtil.WHITESPACE_LIST=['MSROW','MROW','MSPACE','MPHANTOM','MPADDED'];cvox.MathUtil.isWhitespace=function(element){return cvox.MathUtil.isMathNodeOfClass_(element,cvox.MathUtil.WHITESPACE_LIST);};cvox.MathUtil.isNotWhitespace=function(element){return(cvox.MathUtil.isMathmlTag(element)&&!cvox.MathUtil.isWhitespace(element));};cvox.MathUtil.union=function(a,b){return a.concat(b.filter(function(x){return a.indexOf(x)<0;}));};goog.provide('cvox.BaseRuleStore');goog.require('cvox.MathUtil');goog.require('cvox.SpeechRule');goog.require('cvox.SpeechRuleEvaluator');goog.require('cvox.SpeechRuleFunctions');goog.require('cvox.SpeechRuleStore');cvox.BaseRuleStore=function(){this.customQueries=new cvox.SpeechRuleFunctions.CustomQueries();this.customStrings=new cvox.SpeechRuleFunctions.CustomStrings();this.contextFunctions=new cvox.SpeechRuleFunctions.ContextFunctions();this.speechRules_=[];this.dynamicCstrAttribs=[cvox.SpeechRule.DynamicCstrAttrib.STYLE];this.defaultTtsProps=[];};cvox.BaseRuleStore.prototype.lookupRule=function(node,dynamic){if(!node||(node.nodeType!=Node.ELEMENT_NODE&&node.nodeType!=Node.TEXT_NODE)){return null;}
var matchingRules=this.speechRules_.filter(goog.bind(function(rule){return this.testDynamicConstraints(dynamic,rule)&&this.testPrecondition_((node),rule);},this));return(matchingRules.length>0)?this.pickMostConstraint_(dynamic,matchingRules):null;};cvox.BaseRuleStore.prototype.defineRule=function(name,dynamic,action,prec,cstr){try{var postc=cvox.SpeechRule.Action.fromString(action);var cstrList=Array.prototype.slice.call(arguments,4);var fullPrec=new cvox.SpeechRule.Precondition(prec,cstrList);var dynamicCstr={};dynamicCstr[cvox.SpeechRule.DynamicCstrAttrib.STYLE]=dynamic;var rule=new cvox.SpeechRule(name,dynamicCstr,fullPrec,postc);}catch(err){if(err.name=='RuleError'){console.log('Rule Error ',prec,'('+dynamic+'):',err.message);return null;}
else{throw err;}}
this.addRule(rule);return rule;};cvox.BaseRuleStore.prototype.addRule=function(rule){this.speechRules_.unshift(rule);};cvox.BaseRuleStore.prototype.deleteRule=function(rule){var index=this.speechRules_.indexOf(rule);if(index!=-1){this.speechRules_.splice(index,1);}};cvox.BaseRuleStore.prototype.findRule=function(pred){for(var i=0,rule;rule=this.speechRules_[i];i++){if(pred(rule)){return rule;}}
return null;};cvox.BaseRuleStore.prototype.findAllRules=function(pred){return this.speechRules_.filter(pred);};cvox.BaseRuleStore.prototype.evaluateDefault=function(node){return[new cvox.NavDescription({'text':node.textContent})];};cvox.BaseRuleStore.prototype.debugSpeechRule=goog.abstractMethod;cvox.BaseRuleStore.prototype.initialize=goog.abstractMethod;cvox.BaseRuleStore.prototype.removeDuplicates=function(rule){for(var i=this.speechRules_.length-1,oldRule;oldRule=this.speechRules_[i];i--){if(oldRule!=rule&&cvox.BaseRuleStore.compareDynamicConstraints_(oldRule.dynamicCstr,rule.dynamicCstr)&&cvox.BaseRuleStore.comparePreconditions_(oldRule,rule)){this.speechRules_.splice(i,1);}}};cvox.BaseRuleStore.prototype.applyCustomQuery=function(node,funcName){var func=this.customQueries.lookup(funcName);return func?func(node):null;};cvox.BaseRuleStore.prototype.applySelector=function(node,expr){var result=this.applyCustomQuery(node,expr);return result||cvox.XpathUtil.evalXPath(expr,node);};cvox.BaseRuleStore.prototype.applyQuery=function(node,expr){var results=this.applySelector(node,expr);if(results.length>0){return results[0];}
return null;};cvox.BaseRuleStore.prototype.applyConstraint=function(node,expr){var result=this.applyQuery(node,expr);return!!result||cvox.XpathUtil.evaluateBoolean(expr,node);};cvox.BaseRuleStore.prototype.testDynamicConstraints=function(dynamic,rule){var allKeys=(Object.keys(dynamic));return allKeys.every(function(key){return dynamic[key]==rule.dynamicCstr[key]||rule.dynamicCstr[key]=='default';});};cvox.BaseRuleStore.prototype.getDynamicConstraintValues=function(){var result={};for(var i=0,rule;rule=this.speechRules_[i];i++){for(var key in rule.dynamicCstr){var newKey=[rule.dynamicCstr[key]];if(result[key]){result[key]=cvox.MathUtil.union(result[key],newKey);}else{result[key]=newKey;}}}
return result;};cvox.BaseRuleStore.prototype.countMatchingDynamicConstraintValues_=function(dynamic,rule){var result=0;for(var i=0,key;key=this.dynamicCstrAttribs[i];i++){if(dynamic[key]==rule.dynamicCstr[key]){result++;}else break;}
return result;};cvox.BaseRuleStore.prototype.pickMostConstraint_=function(dynamic,rules){rules.sort(goog.bind(function(r1,r2){var count1=this.countMatchingDynamicConstraintValues_(dynamic,r1);var count2=this.countMatchingDynamicConstraintValues_(dynamic,r2);if(count1>count2){return-1;}
if(count2>count1){return 1;}
return(r2.precondition.constraints.length-
r1.precondition.constraints.length);},this));return rules[0];};cvox.BaseRuleStore.prototype.testPrecondition_=function(node,rule){var prec=rule.precondition;return this.applyQuery(node,prec.query)===node&&prec.constraints.every(goog.bind(function(cstr){return this.applyConstraint(node,cstr);},this));};cvox.BaseRuleStore.compareDynamicConstraints_=function(cstr1,cstr2){if(Object.keys(cstr1).length!=Object.keys(cstr2).length){return false;}
for(var key in cstr1){if(!cstr2[key]||cstr1[key]!==cstr2[key]){return false;}}
return true;};cvox.BaseRuleStore.compareStaticConstraints_=function(cstr1,cstr2){if(cstr1.length!=cstr2.length){return false;}
for(var i=0,cstr;cstr=cstr1[i];i++){if(cstr2.indexOf(cstr)==-1){return false;}}
return true;};cvox.BaseRuleStore.comparePreconditions_=function(rule1,rule2){var prec1=rule1.precondition;var prec2=rule2.precondition;if(prec1.query!=prec2.query){return false;}
return cvox.BaseRuleStore.compareStaticConstraints_(prec1.constraints,prec2.constraints);};goog.provide('cvox.MathStore');goog.require('cvox.AbstractTts');goog.require('cvox.BaseRuleStore');goog.require('cvox.ChromeVox');goog.require('cvox.NavMathDescription');goog.require('cvox.SpeechRule');goog.require('cvox.TraverseMath');cvox.MathStore=function(){goog.base(this);this.dynamicCstrAttribs=[cvox.SpeechRule.DynamicCstrAttrib.DOMAIN,cvox.SpeechRule.DynamicCstrAttrib.STYLE];this.defaultTtsProps=[cvox.AbstractTts.PITCH];};goog.inherits(cvox.MathStore,cvox.BaseRuleStore);cvox.SpeechRule.DynamicCstrAttrib.DOMAIN='domain';cvox.MathStore.prototype.defineRule=function(name,dynamic,action,query,cstr){var dynamicCstr=this.parseDynamicConstraint(dynamic);var cstrList=Array.prototype.slice.call(arguments,4);var rule=cvox.MathStore.superClass_.defineRule.apply(this,[name,dynamicCstr[cvox.SpeechRule.DynamicCstrAttrib.STYLE],action,query].concat(cstrList));rule.dynamicCstr=dynamicCstr;this.removeDuplicates(rule);return rule;};cvox.MathStore.prototype.parseDynamicConstraint=function(cstr){var domainStyle=cstr.split('.');if(!domainStyle[0]||!domainStyle[1]){throw new cvox.SpeechRule.OutputError('Invalid domain assignment:'+cstr);}
return cvox.MathStore.createDynamicConstraint(domainStyle[0],domainStyle[1]);};cvox.MathStore.createDynamicConstraint=function(domain,style){var dynamicCstr={};dynamicCstr[cvox.SpeechRule.DynamicCstrAttrib.DOMAIN]=domain;dynamicCstr[cvox.SpeechRule.DynamicCstrAttrib.STYLE]=style;return dynamicCstr;};cvox.MathStore.prototype.defineUniqueRuleAlias=function(name,dynamic,query,cstr){var dynamicCstr=this.parseDynamicConstraint(dynamic);var rule=this.findRule(goog.bind(function(rule){return rule.name==name&&this.testDynamicConstraints(dynamicCstr,rule);},this));if(!rule){throw new cvox.SpeechRule.OutputError('Rule named '+name+' with style '+dynamic+' does not exist.');}
this.addAlias_(rule,query,Array.prototype.slice.call(arguments,3));};cvox.MathStore.prototype.defineRuleAlias=function(name,query,cstr){var rule=this.findRule(function(rule){return rule.name==name;});if(!rule){throw new cvox.SpeechRule.OutputError('Rule with named '+name+' does not exist.');}
this.addAlias_(rule,query,Array.prototype.slice.call(arguments,2));};cvox.MathStore.prototype.defineRulesAlias=function(name,query,cstr){var rules=this.findAllRules(function(rule){return rule.name==name;});if(rules.length==0){throw new cvox.SpeechRule.OutputError('Rule with name '+name+' does not exist.');}
var cstrList=Array.prototype.slice.call(arguments,2);rules.forEach(goog.bind(function(rule){this.addAlias_(rule,query,cstrList);},this));};cvox.MathStore.prototype.addAlias_=function(rule,query,cstrList){var prec=new cvox.SpeechRule.Precondition(query,cstrList);var newRule=new cvox.SpeechRule(rule.name,rule.dynamicCstr,prec,rule.action);newRule.name=rule.name;this.addRule(newRule);};cvox.MathStore.prototype.evaluateDefault=function(node){return this.evaluateString_(node.textContent);};cvox.MathStore.prototype.evaluateString_=function(str){var descs=new Array();if(str.match(/^\s+$/)){return descs;}
var split=cvox.MathStore.removeEmpty_(str.replace(/\s/g,' ').split(' '));for(var i=0,s;s=split[i];i++){if(s.length==1){descs.push(this.evaluate_(s));}else if(s.match(/^[a-zA-Z]+$/)){descs.push(this.evaluate_(s));}else{var rest=s;var count=0;while(rest){var num=rest.match(/^\d+/);var alpha=rest.match(/^[a-zA-Z]+/);if(num){descs.push(this.evaluate_(num[0]));rest=rest.substring(num[0].length);}else if(alpha){descs.push(this.evaluate_(alpha[0]));rest=rest.substring(alpha[0].length);}else{var chr=rest[0];var code=chr.charCodeAt(0);if(0xD800<=code&&code<=0xDBFF&&rest.length>1&&!isNaN(rest.charCodeAt(1))){descs.push(this.evaluate_(rest.slice(0,2)));rest=rest.substring(2);}else{descs.push(this.evaluate_(rest[0]));rest=rest.substring(1);}}}}}
return descs;};cvox.MathStore.prototype.evaluate_=function(text){if(cvox.ChromeVox.host['mathMap']){return cvox.ChromeVox.host['mathMap'].evaluate(text,cvox.TraverseMath.getInstance().domain,cvox.TraverseMath.getInstance().style);}
return new cvox.NavMathDescription({'text':text,'domain':cvox.TraverseMath.getInstance().domain,'style':cvox.TraverseMath.getInstance().style});};cvox.MathStore.removeEmpty_=function(strs){return strs.filter(function(str){return str;});};goog.provide('cvox.MathmlStore');goog.require('cvox.MathStore');cvox.MathmlStore=function(){goog.base(this);};goog.inherits(cvox.MathmlStore,cvox.MathStore);goog.addSingletonGetter(cvox.MathmlStore);cvox.MathmlStore.prototype.defineMathmlRule=function(name,domain,rule){this.defineRule(name,domain,rule,'self::mathml:'+name);};cvox.MathmlStore.prototype.defineDefaultMathmlRule=function(name,rule){this.defineRule(name,'default.default',rule,'self::mathml:'+name);};goog.provide('cvox.EarconUtil');goog.require('cvox.AbstractEarcons');goog.require('cvox.AriaUtil');goog.require('cvox.DomUtil');cvox.EarconUtil.getEarcon=function(node){var earcon=cvox.AriaUtil.getEarcon(node);if(earcon!=null){return earcon;}
switch(node.tagName){case'BUTTON':return cvox.Earcon.BUTTON;case'A':if(node.hasAttribute('href')){return cvox.Earcon.LINK;}
break;case'IMG':if(cvox.DomUtil.hasLongDesc(node)){return cvox.Earcon.LONG_DESC;}
break;case'LI':return cvox.Earcon.LIST_ITEM;case'SELECT':return cvox.Earcon.LISTBOX;case'TEXTAREA':return cvox.Earcon.EDITABLE_TEXT;case'INPUT':switch(node.type){case'button':case'submit':case'reset':return cvox.Earcon.BUTTON;case'checkbox':case'radio':if(node.checked){return cvox.Earcon.CHECK_ON;}else{return cvox.Earcon.CHECK_OFF;}
default:if(cvox.DomUtil.isInputTypeText(node)){return cvox.Earcon.EDITABLE_TEXT;}}}
return null;};goog.provide('cvox.SpeechRuleEngine');goog.require('cvox.BaseRuleStore');goog.require('cvox.NavDescription');goog.require('cvox.NavMathDescription');goog.require('cvox.SpeechRule');cvox.SpeechRuleEngine=function(){this.activeStore_=null;this.dynamicCstr={};this.dynamicCstr[cvox.SpeechRule.DynamicCstrAttrib.STYLE]='short';};goog.addSingletonGetter(cvox.SpeechRuleEngine);cvox.SpeechRuleEngine.prototype.parameterize=function(store){try{store.initialize();}catch(err){if(err.name=='StoreError'){console.log('Store Error:',err.message);}
else{throw err;}}
this.activeStore_=store;};cvox.SpeechRuleEngine.prototype.setDynamicConstraint=function(dynamic){if(dynamic){this.dynamicCstr=dynamic;}};cvox.SpeechRuleEngine.prototype.constructString=function(node,expr){if(!expr){return'';}
if(expr.charAt(0)=='"'){return expr.slice(1,-1);}
var func=this.activeStore_.customStrings.lookup(expr);if(func){return func(node);}
return cvox.XpathUtil.evaluateString(expr,node);};cvox.SpeechRuleEngine.prototype.evaluateNode=function(node){if(!node){return[];}
return this.evaluateTree_(node);};cvox.SpeechRuleEngine.prototype.evaluateTree_=function(node){var rule=this.activeStore_.lookupRule(node,this.dynamicCstr);if(!rule){return this.activeStore_.evaluateDefault(node);}
var components=rule.action.components;var result=[];for(var i=0,component;component=components[i];i++){var navs=[];var content=component['content']||'';switch(component.type){case cvox.SpeechRule.Type.NODE:var selected=this.activeStore_.applyQuery(node,content);if(selected){navs=this.evaluateTree_(selected);}
break;case cvox.SpeechRule.Type.MULTI:selected=this.activeStore_.applySelector(node,content);if(selected.length>0){navs=this.evaluateNodeList_(selected,component['sepFunc'],this.constructString(node,component['separator']),component['ctxtFunc'],this.constructString(node,component['context']));}
break;case cvox.SpeechRule.Type.TEXT:selected=this.constructString(node,content);if(selected){navs=[new cvox.NavDescription({text:selected})];}
break;case cvox.SpeechRule.Type.PERSONALITY:default:navs=[new cvox.NavDescription({text:content})];}
if(navs[0]&&component['context']&&component.type!=cvox.SpeechRule.Type.MULTI){navs[0]['context']=this.constructString(node,component['context'])+
(navs[0]['context']||'');}
result=result.concat(this.addPersonality_(navs,component));}
return result;};cvox.SpeechRuleEngine.prototype.evaluateNodeList_=function(nodes,sepFunc,separator,ctxtFunc,context){if(nodes==[]){return[];}
var sep=separator||'';var cont=context||'';var cFunc=this.activeStore_.contextFunctions.lookup(ctxtFunc);var ctxtClosure=cFunc?cFunc(nodes,cont):function(){return cont;};var sFunc=this.activeStore_.contextFunctions.lookup(sepFunc);var sepClosure=sFunc?sFunc(nodes,sep):function(){return sep;};var result=[];for(var i=0,node;node=nodes[i];i++){var navs=this.evaluateTree_(node);if(navs.length>0){navs[0]['context']=ctxtClosure()+(navs[0]['context']||'');result=result.concat(navs);if(i<nodes.length-1){var text=sepClosure();if(text){result.push(new cvox.NavDescription({text:text}));}}}}
return result;};cvox.SpeechRuleEngine.propMap={'pitch':cvox.AbstractTts.RELATIVE_PITCH,'rate':cvox.AbstractTts.RELATIVE_RATE,'volume':cvox.AbstractTts.RELATIVE_VOLUME,'pause':cvox.AbstractTts.PAUSE};cvox.SpeechRuleEngine.prototype.addPersonality_=function(navs,props){var personality={};for(var key in cvox.SpeechRuleEngine.propMap){var value=parseFloat(props[key]);if(!isNaN(value)){personality[cvox.SpeechRuleEngine.propMap[key]]=value;}}
navs.forEach(goog.bind(function(nav){this.addRelativePersonality_(nav,personality);this.resetPersonality_(nav);},this));return navs;};cvox.SpeechRuleEngine.prototype.addRelativePersonality_=function(nav,personality){if(!nav['personality']){nav['personality']=personality;return nav;}
var navPersonality=nav['personality'];for(var p in personality){if(navPersonality[p]&&typeof(navPersonality[p])=='number'){navPersonality[p]=navPersonality[p]+personality[p];}else{navPersonality[p]=personality[p];}}
return nav;};cvox.SpeechRuleEngine.prototype.resetPersonality_=function(nav){if(this.activeStore_.defaultTtsProps){for(var i=0,prop;prop=this.activeStore_.defaultTtsProps[i];i++){nav.personality[prop]=cvox.ChromeVox.tts.getDefaultProperty(prop);}}};cvox.SpeechRuleEngine.debugMode=false;cvox.SpeechRuleEngine.outputDebug=function(output){if(cvox.SpeechRuleEngine.debugMode){var outputList=Array.prototype.slice.call(arguments,0);console.log.apply(console,['Speech Rule Engine Debugger:'].concat(outputList));}};cvox.SpeechRuleEngine.prototype.toString=function(){var allRules=this.activeStore_.findAllRules(function(x){return true;});return allRules.map(function(rule){return rule.toString();}).join('\n');};cvox.SpeechRuleEngine.debugSpeechRule=function(rule,node){var store=cvox.SpeechRuleEngine.getInstance().activeStore_;if(store){var prec=rule.precondition;cvox.SpeechRuleEngine.outputDebug(prec.query,store.applyQuery(node,prec.query));prec.constraints.forEach(function(cstr){cvox.SpeechRuleEngine.outputDebug(cstr,store.applyConstraint(node,cstr));});}};cvox.SpeechRuleEngine.debugNamedSpeechRule=function(name,node){var store=cvox.SpeechRuleEngine.getInstance().activeStore_;var allRules=store.findAllRules(function(rule){return rule.name==name;});for(var i=0,rule;rule=allRules[i];i++){cvox.SpeechRuleEngine.outputDebug('Rule',name,'number',i);cvox.SpeechRuleEngine.debugSpeechRule(rule,node);}};goog.provide('cvox.AuralProperty');goog.provide('cvox.AuralStyleConverter');goog.provide('cvox.AuralStyleUtil');cvox.AuralProperty={VOLUME:'VOLUME',SPEAK:'SPEAK',PAUSE_BEFORE:'PAUSE_BEFORE',PAUSE_AFTER:'PAUSE_AFTER',PAUSE:'PAUSE',CUE_BEFORE:'CUE_BEFORE',CUE_AFTER:'CUE_AFTER',CUE:'CUE',PLAY_DURING:'PLAY_DURING',AZIMUTH:'AZIMUTH',ELEVATION:'ELEVATION',SPEECH_RATE:'SPEECH_RATE',VOICE_FAMILY:'VOICE_FAMILY',PITCH:'PITCH',PITCH_RANGE:'PITCH_RANGE',STRESS:'STRESS',RICHNESS:'RICHNESS',SPEAK_PUNCTUATION:'SPEAK_PUNCTUATION',SPEAK_NUMERIAL:'SPEAK_NUMERIAL',SPEAK_HEADER:'SPEAK_HEADER',NONE:'NONE'};cvox.AuralStyleConverter.identity=function(value){return value;};cvox.AuralStyleConverter.propertyTable={VOLUME:'volume',SPEAK:'no-op',PAUSE_BEFORE:'no-op',PAUSE_AFTER:'no-op',PAUSE:'no-op',CUE_BEFORE:'no-op',CUE_AFTER:'no-op',CUE:'no-op',PLAY_DURING:'no-op',AZIMUTH:'no-op',ELEVATION:'no-op',SPEECH_RATE:'relativeRate',VOICE_FAMILY:'no-op',PITCH:'relativePitch',PITCH_RANGE:'no-op',STRESS:'no-op',RICHNESS:'no-op',SPEAK_PUNCTUATION:'no-op',SPEAK_NUMERIAL:'no-op',SPEAK_HEADER:'no-op',NONE:'no-op'};cvox.AuralStyleConverter.valueTable={VOLUME:cvox.AuralStyleConverter.identity,SPEAK:cvox.AuralStyleConverter.identity,PAUSE_BEFORE:cvox.AuralStyleConverter.identity,PAUSE_AFTER:cvox.AuralStyleConverter.identity,PAUSE:cvox.AuralStyleConverter.identity,CUE_BEFORE:cvox.AuralStyleConverter.identity,CUE_AFTER:cvox.AuralStyleConverter.identity,CUE:cvox.AuralStyleConverter.identity,PLAY_DURING:cvox.AuralStyleConverter.identity,AZIMUTH:cvox.AuralStyleConverter.identity,ELEVATION:cvox.AuralStyleConverter.identity,SPEECH_RATE:cvox.AuralStyleConverter.identity,VOICE_FAMILY:cvox.AuralStyleConverter.identity,PITCH:cvox.AuralStyleConverter.identity,PITCH_RANGE:cvox.AuralStyleConverter.identity,STRESS:cvox.AuralStyleConverter.identity,RICHNESS:cvox.AuralStyleConverter.identity,SPEAK_PUNCTUATION:cvox.AuralStyleConverter.identity,SPEAK_NUMERIAL:cvox.AuralStyleConverter.identity,SPEAK_HEADER:cvox.AuralStyleConverter.identity,NONE:cvox.AuralStyleConverter.identity};cvox.AuralStyleConverter.convertRule=function(property,value){return{property:cvox.AuralStyleConverter.propertyTable[property],value:cvox.AuralStyleConverter.valueTable[property](value)};};cvox.AuralStyleConverter.convertStyle=function(style){var ttsProperties={};for(var property in style){var ttsProperty=cvox.AuralStyleConverter.convertRule(property,style[property]);ttsProperties[ttsProperty.property]=ttsProperty.value;}
return ttsProperties;};cvox.AuralStyleUtil.getStyleForNode=function(node){var style=cvox.AuralStyleUtil.defaultStyles[node.tagName];if(!style){return null;}
return cvox.AuralStyleConverter.convertStyle(style);};cvox.AuralStyleUtil.defaultStyles={'ARTICLE':{PITCH:-0.1},'ASIDE':{PITCH:-0.1},'FOOTER':{PITCH:-0.1},'H1':{PITCH:-0.3},'H2':{PITCH:-0.25},'H3':{PITCH:-0.2},'H4':{PITCH:-0.15},'H5':{PITCH:-0.1},'H6':{PITCH:-0.05},'HEADER':{PITCH:-0.1},'HGROUP':{PITCH:-0.1},'MARK':{PITCH:-0.1},'NAV':{PITCH:-0.1},'SECTION':{PITCH:-0.1},'TIME':{PITCH:-0.1}};goog.provide('Spannable');goog.scope(function(){Spannable=function(opt_string,opt_annotation){this.string_=opt_string instanceof Spannable?'':opt_string||'';this.spans_=[];if(opt_string instanceof Spannable)
this.append(opt_string);if(goog.isDef(opt_annotation)){var len=this.string_.length;this.spans_.push({value:opt_annotation,start:0,end:len});}};Spannable.prototype={toString:function(){return this.string_;},get length(){return this.string_.length;},setSpan:function(value,start,end){this.removeSpan(value);if(0<=start&&start<=end&&end<=this.string_.length){this.spans_.push({value:value,start:start,end:end});this.spans_.sort(function(a,b){var ret=a.start-b.start;if(ret==0)
ret=a.end-b.end;return ret;});}else{throw new RangeError('span out of range (start='+start+', end='+end+', len='+this.string_.length+')');}},removeSpan:function(value){for(var i=this.spans_.length-1;i>=0;i--){if(this.spans_[i].value===value){this.spans_.splice(i,1);}}},append:function(other){if(other instanceof Spannable){var otherSpannable=(other);var originalLength=this.length;this.string_+=otherSpannable.string_;other.spans_.forEach(function(span){this.setSpan(span.value,span.start+originalLength,span.end+originalLength);}.bind(this));}else if(typeof other==='string'){this.string_+=(other);}},getSpan:function(position){return valueOfSpan(this.spans_.find(spanCoversPosition(position)));},getSpanInstanceOf:function(constructor){return valueOfSpan(this.spans_.find(spanInstanceOf(constructor)));},getSpansInstanceOf:function(constructor){return(this.spans_.filter(spanInstanceOf(constructor)).map(valueOfSpan));},getSpans:function(position){return(this.spans_.filter(spanCoversPosition(position)).map(valueOfSpan));},hasSpan:function(value){return this.spans_.some(spanValueIs(value));},getSpanStart:function(value){return this.getSpanByValueOrThrow_(value).start;},getSpanEnd:function(value){return this.getSpanByValueOrThrow_(value).end;},getSpanLength:function(value){var span=this.getSpanByValueOrThrow_(value);return span.end-span.start;},getSpanByValueOrThrow_:function(value){var span=this.spans_.find(spanValueIs(value));if(span)
return span;throw new Error('Span '+value+' doesn\'t exist in spannable');},substring:function(start,opt_end){var end=goog.isDef(opt_end)?opt_end:this.string_.length;if(start<0||end>this.string_.length||start>end){throw new RangeError('substring indices out of range');}
var result=new Spannable(this.string_.substring(start,end));this.spans_.forEach(function(span){if(span.start<=end&&span.end>=start){var newStart=Math.max(0,span.start-start);var newEnd=Math.min(end-start,span.end-start);result.spans_.push({value:span.value,start:newStart,end:newEnd});}});return result;},trimLeft:function(){return this.trim_(true,false);},trimRight:function(){return this.trim_(false,true);},trim:function(){return this.trim_(true,true);},trim_:function(trimStart,trimEnd){if(!trimStart&&!trimEnd){return this;}
if(/^\s*$/.test(this.string_)){return this.substring(0,0);}
var trimmedStart=trimStart?this.string_.match(/^\s*/)[0].length:0;var trimmedEnd=trimEnd?this.string_.match(/\s*$/).index:this.string_.length;return this.substring(trimmedStart,trimmedEnd);},toJson:function(){var result={};result.string=this.string_;result.spans=[];this.spans_.forEach(function(span){var serializeInfo=serializableSpansByConstructor.get(span.value.constructor);if(serializeInfo){var spanObj={type:serializeInfo.name,start:span.start,end:span.end};if(serializeInfo.toJson){spanObj.value=serializeInfo.toJson.apply(span.value);}
result.spans.push(spanObj);}});return result;}};Spannable.fromJson=function(obj){if(typeof obj.string!=='string'){throw new Error('Invalid spannable json object: string field not a string');}
if(!(obj.spans instanceof Array)){throw new Error('Invalid spannable json object: no spans array');}
var result=new Spannable(obj.string);result.spans_=obj.spans.map(function(span){if(typeof span.type!=='string'){throw new Error('Invalid span in spannable json object: type not a string');}
if(typeof span.start!=='number'||typeof span.end!=='number'){throw new Error('Invalid span in spannable json object: start or end not a number');}
var serializeInfo=serializableSpansByName.get(span.type);var value=serializeInfo.fromJson(span.value);return{value:value,start:span.start,end:span.end};});return result;};Spannable.registerSerializableSpan=function(constructor,name,fromJson,toJson){var obj={name:name,fromJson:fromJson,toJson:toJson};serializableSpansByName.set(name,obj);serializableSpansByConstructor.set(constructor,obj);};Spannable.registerStatelessSerializableSpan=function(constructor,name){var obj={name:name,toJson:undefined};obj.fromJson=function(obj){return new constructor();};serializableSpansByName.set(name,obj);serializableSpansByConstructor.set(constructor,obj);};var SpanStruct;var SerializeInfo;var SerializedSpannable;var SerializedSpan;var serializableSpansByName=new Map();var serializableSpansByConstructor=new Map();function spanInstanceOf(constructor){return function(span){return span.value instanceof constructor;}}
function spanCoversPosition(position){return function(span){return span.start<=position&&position<span.end;}}
function spanValueIs(value){return function(span){return span.value===value;}}
function valueOfSpan(span){return span?span.value:undefined;}});goog.provide('cvox.NavBraille');goog.require('Spannable');cvox.NavBraille=function(kwargs){this.text=(kwargs.text instanceof Spannable)?kwargs.text:new Spannable(kwargs.text);this.startIndex=goog.isDef(kwargs.startIndex)?kwargs.startIndex:-1;this.endIndex=goog.isDef(kwargs.endIndex)?kwargs.endIndex:this.startIndex;};cvox.NavBraille.fromText=function(text){return new cvox.NavBraille({'text':text});};cvox.NavBraille.fromJson=function(json){if(typeof json.startIndex!=='number'||typeof json.endIndex!=='number'){throw'Invalid start or end index in serialized NavBraille: '+json;}
return new cvox.NavBraille({text:Spannable.fromJson(json.spannable),startIndex:json.startIndex,endIndex:json.endIndex});};cvox.NavBraille.prototype.isEmpty=function(){return this.text.length==0;};cvox.NavBraille.prototype.toString=function(){return'NavBraille(text="'+this.text.toString()+'" '+' startIndex="'+this.startIndex+'" '+' endIndex="'+this.endIndex+'")';};cvox.NavBraille.prototype.toJson=function(){return{spannable:this.text.toJson(),startIndex:this.startIndex,endIndex:this.endIndex};};goog.provide('cvox.AbstractWalker');goog.require('cvox.CursorSelection');goog.require('cvox.NavBraille');cvox.AbstractWalker=function(){};cvox.AbstractWalker.prototype.next=goog.abstractMethod;cvox.AbstractWalker.prototype.begin=function(kwargs){kwargs=kwargs||{reversed:false};return(this.sync(cvox.CursorSelection.fromBody().setReversed(kwargs.reversed)));};cvox.AbstractWalker.prototype.sync=goog.abstractMethod;cvox.AbstractWalker.prototype.getDescription=goog.abstractMethod;cvox.AbstractWalker.prototype.getBraille=goog.abstractMethod;cvox.AbstractWalker.prototype.hasAction=function(name){return typeof(this[name])=='function';};cvox.AbstractWalker.prototype.performAction=function(name,sel){if(this.hasAction(name)){return this[name](sel);}
return null;};cvox.AbstractWalker.prototype.getGranularityMsg=goog.abstractMethod;goog.provide('cvox.AbstractNodeWalker');goog.require('cvox.AbstractWalker');goog.require('cvox.CursorSelection');goog.require('cvox.DomUtil');cvox.AbstractNodeWalker=function(){goog.base(this);this.wasBegin_=false;};goog.inherits(cvox.AbstractNodeWalker,cvox.AbstractWalker);cvox.AbstractNodeWalker.prototype.next=function(sel){var r=sel.isReversed();var node=sel.end.node||document.body;if(!node){return null;}
do{node=cvox.DomUtil.directedNextLeafLikeNode(node,r,goog.bind(this.stopNodeDescent,this));if(!node){return null;}}while(node&&!cvox.DomUtil.hasContent(node));return cvox.CursorSelection.fromNode(node).setReversed(r);};cvox.AbstractNodeWalker.prototype.sync=function(sel){var ret=this.privateSync_(sel);this.wasBegin_=false;return ret;};cvox.AbstractNodeWalker.prototype.privateSync_=function(sel){var r=sel.isReversed();if(sel.equals(cvox.CursorSelection.fromBody())){if(this.wasBegin_){return cvox.CursorSelection.fromBody().setReversed(r);}
this.wasBegin_=true;}
var node=sel.start.node;while(node!=document.body&&node.parentNode&&this.stopNodeDescent(node.parentNode)){node=node.parentNode;}
while(node&&!this.stopNodeDescent(node)){node=cvox.DomUtil.directedFirstChild(node,r);}
var n=cvox.CursorSelection.fromNode(node);if(!cvox.DomUtil.hasContent(node)){n=this.next((cvox.CursorSelection.fromNode(node)).setReversed(r));}
if(n){return n.setReversed(r);}
return this.begin({reversed:r});};cvox.AbstractNodeWalker.prototype.stopNodeDescent=goog.abstractMethod;goog.provide('cvox.BareObjectWalker');goog.require('cvox.AbstractNodeWalker');cvox.BareObjectWalker=function(){goog.base(this);};goog.inherits(cvox.BareObjectWalker,cvox.AbstractNodeWalker);cvox.BareObjectWalker.prototype.stopNodeDescent=function(node){return cvox.DomUtil.isLeafNode(node);};goog.provide('cvox.DescriptionUtil');goog.require('cvox.AriaUtil');goog.require('cvox.AuralStyleUtil');goog.require('cvox.BareObjectWalker');goog.require('cvox.CursorSelection');goog.require('cvox.DomUtil');goog.require('cvox.EarconUtil');goog.require('cvox.MathmlStore');goog.require('cvox.NavDescription');goog.require('cvox.SpeechRuleEngine');goog.require('cvox.TraverseMath');cvox.DescriptionUtil.COLLECTION_NODE_TYPE={'H1':true,'H2':true,'H3':true,'H4':true,'H5':true,'H6':true};cvox.DescriptionUtil.getControlDescription=function(control,opt_changedAncestors){var ancestors=[control];if(opt_changedAncestors&&(opt_changedAncestors.length>0)){ancestors=opt_changedAncestors;}else{var surroundingControl=cvox.DomUtil.getSurroundingControl(control);if(surroundingControl){ancestors=[surroundingControl,control];}}
var description=cvox.DescriptionUtil.getDescriptionFromAncestors(ancestors,true,cvox.VERBOSITY_VERBOSE);if(surroundingControl){var name=cvox.DomUtil.getName(surroundingControl);if(name.length==0){name=cvox.DomUtil.getControlLabelHeuristics(surroundingControl);if(name.length>0){description.context=name+' '+description.context;}}}else{var name=cvox.DomUtil.getName(control);if(name.length==0){name=cvox.DomUtil.getControlLabelHeuristics(control);if(name.length>0){description.text=cvox.DomUtil.collapseWhitespace(name);}}
var value=cvox.DomUtil.getValue(control);if(value.length>0){description.userValue=cvox.DomUtil.collapseWhitespace(value);}}
return description;};cvox.DescriptionUtil.getDescriptionFromAncestors=function(ancestorsArray,recursive,verbosity){if(typeof(recursive)==='undefined'){recursive=true;}
var len=ancestorsArray.length;var context='';var text='';var userValue='';var annotation='';var earcons=[];var personality=null;var hint='';if(len>0){text=cvox.DomUtil.getName(ancestorsArray[len-1],recursive);userValue=cvox.DomUtil.getValue(ancestorsArray[len-1]);}
for(var i=len-1;i>=0;i--){var node=ancestorsArray[i];hint=cvox.DomUtil.getHint(node);var role=node.getAttribute?node.getAttribute('role'):null;if(role=='alertdialog'){continue;}
var roleText=cvox.DomUtil.getRole(node,verbosity);if(!personality){personality=cvox.AuralStyleUtil.getStyleForNode(node);}
if(i<len-1&&node.hasAttribute('role')){var name=cvox.DomUtil.getName(node,false);if(name){roleText=name+' '+roleText;}}
if(roleText.length>0){if(context.length>0||(annotation.length>0&&node.childElementCount>1)){context=roleText+' '+cvox.DomUtil.getState(node,false)+' '+context;}else{if(annotation.length>0){annotation+=' '+roleText+' '+cvox.DomUtil.getState(node,true);}else{annotation=roleText+' '+cvox.DomUtil.getState(node,true);}}}
var earcon=cvox.EarconUtil.getEarcon(node);if(earcon!=null&&earcons.indexOf(earcon)==-1){earcons.push(earcon);}}
return new cvox.NavDescription({context:cvox.DomUtil.collapseWhitespace(context),text:cvox.DomUtil.collapseWhitespace(text),userValue:cvox.DomUtil.collapseWhitespace(userValue),annotation:cvox.DomUtil.collapseWhitespace(annotation),earcons:earcons,personality:personality,hint:cvox.DomUtil.collapseWhitespace(hint)});};cvox.DescriptionUtil.getDescriptionFromNavigation=function(prevNode,node,recursive,verbosity){if(!prevNode||!node){return[];}
if(cvox.DomUtil.isMath(node)&&!cvox.AriaUtil.isMath(node)){return cvox.DescriptionUtil.getMathDescription(node);}
if(cvox.DescriptionUtil.COLLECTION_NODE_TYPE[node.tagName]){return cvox.DescriptionUtil.getCollectionDescription((cvox.CursorSelection.fromNode(prevNode)),(cvox.CursorSelection.fromNode(node)));}
var ancestors=cvox.DomUtil.getUniqueAncestors(prevNode,node,true);var desc=cvox.DescriptionUtil.getDescriptionFromAncestors(ancestors,recursive,verbosity);var prevAncestors=cvox.DomUtil.getUniqueAncestors(node,prevNode);if(cvox.DescriptionUtil.shouldDescribeExit_(prevAncestors)){var prevDesc=cvox.DescriptionUtil.getDescriptionFromAncestors(prevAncestors,recursive,verbosity);if(prevDesc.context&&!desc.context){desc.context=Msgs.getMsg('exited_container',[prevDesc.context]);}}
return[desc];};cvox.DescriptionUtil.getCollectionDescription=function(prevSel,sel){var descriptions=cvox.DescriptionUtil.getRawDescriptions_(prevSel,sel);cvox.DescriptionUtil.insertCollectionDescription_(descriptions);return descriptions;};cvox.DescriptionUtil.subWalker_=new cvox.BareObjectWalker();cvox.DescriptionUtil.getRawDescriptions_=function(prevSel,sel){var descriptions=[];sel=sel.clone().setReversed(false);var node=cvox.DescriptionUtil.subWalker_.sync(sel).start.node;var prevNode=prevSel.end.node;var curSel=cvox.CursorSelection.fromNode(node);if(!curSel){return[];}
while(cvox.DomUtil.isDescendantOfNode(node,sel.start.node)){var ancestors=cvox.DomUtil.getUniqueAncestors(prevNode,node);if(cvox.DomUtil.isMath(node)&&!cvox.AriaUtil.isMath(node)){descriptions=descriptions.concat(cvox.DescriptionUtil.getMathDescription(node));}else{var description=cvox.DescriptionUtil.getDescriptionFromAncestors(ancestors,true,cvox.ChromeVox.verbosity);descriptions.push(description);}
curSel=cvox.DescriptionUtil.subWalker_.next(curSel);if(!curSel){break;}
curSel=(curSel);prevNode=node;node=curSel.start.node;}
return descriptions;};cvox.DescriptionUtil.getFullDescriptionsFromChildren=function(prevnode,node){var descriptions=[];if(!node){return descriptions;}
var desc;if(cvox.DomUtil.isLeafNode(node)){var ancestors;if(prevnode){ancestors=cvox.DomUtil.getUniqueAncestors(prevnode,node);}else{ancestors=new Array();ancestors.push(node);}
desc=cvox.DescriptionUtil.getDescriptionFromAncestors(ancestors,true,cvox.ChromeVox.verbosity);descriptions.push(desc);return descriptions;}
var originalNode=node;var curSel=cvox.CursorSelection.fromNode(node);if(!curSel){return descriptions;}
var newNode=cvox.DescriptionUtil.subWalker_.sync(curSel).start.node;curSel=cvox.CursorSelection.fromNode(newNode);if(!curSel){return descriptions;}
while(newNode&&cvox.DomUtil.isDescendantOfNode(newNode,originalNode)){descriptions=descriptions.concat(cvox.DescriptionUtil.getFullDescriptionsFromChildren(prevnode,newNode));curSel=cvox.DescriptionUtil.subWalker_.next(curSel);if(!curSel){break;}
curSel=(curSel);prevnode=newNode;newNode=curSel.start.node;}
return descriptions;};cvox.DescriptionUtil.insertCollectionDescription_=function(descriptions){var annotations=cvox.DescriptionUtil.getAnnotations_(descriptions);if(descriptions.length>=3&&descriptions[0].context.length==0&&annotations.length==1&&annotations[0].length>0&&cvox.DescriptionUtil.isAnnotationCollection_(annotations[0])){var commonAnnotation=annotations[0];var firstContext=descriptions[0].context;descriptions[0].context='';for(var i=0;i<descriptions.length;i++){descriptions[i].annotation='';}
descriptions.splice(0,0,new cvox.NavDescription({context:firstContext,text:'',annotation:Msgs.getMsg('collection',[commonAnnotation,Msgs.getNumber(descriptions.length)])}));}};cvox.DescriptionUtil.getAnnotations_=function(descriptions){var annotations=[];for(var i=0;i<descriptions.length;++i){var description=descriptions[i];if(annotations.indexOf(description.annotation)==-1){var linkMsg=Msgs.getMsg('role_link');if(description.annotation.toLowerCase().indexOf(linkMsg.toLowerCase())!=-1){if(annotations.indexOf(linkMsg)==-1){annotations.push(linkMsg);}}else{annotations.push(description.annotation);}}}
return annotations;};cvox.DescriptionUtil.isAnnotationCollection_=function(annotation){return(annotation==Msgs.getMsg('role_link'));};cvox.DescriptionUtil.shouldDescribeExit_=function(ancestors){return ancestors.some(function(node){switch(node.tagName){case'TABLE':case'MATH':return true;}
return cvox.AriaUtil.isLandmark(node);});};cvox.DescriptionUtil.getMathDescription=function(node){if(!node){return[];}
var speechEngine=cvox.SpeechRuleEngine.getInstance();var traverse=cvox.TraverseMath.getInstance();speechEngine.parameterize(cvox.MathmlStore.getInstance());traverse.initialize(node);var ret=speechEngine.evaluateNode(traverse.activeNode);if(ret==[]){return[new cvox.NavDescription({'text':'empty math'})];}
if(cvox.ChromeVox.verbosity==cvox.VERBOSITY_VERBOSE){ret[ret.length-1].annotation='math';}
ret[0].pushEarcon(cvox.Earcon.MATH);return ret;};goog.provide('cvox.LiveRegions');goog.require('cvox.AriaUtil');goog.require('cvox.ChromeVox');goog.require('cvox.DescriptionUtil');goog.require('cvox.DomUtil');goog.require('cvox.Interframe');goog.require('cvox.NavDescription');goog.require('cvox.NavigationSpeaker');cvox.LiveRegions=function(){};cvox.LiveRegions.pageLoadTime=null;cvox.LiveRegions.INITIAL_SILENCE_MS=2000;cvox.LiveRegions.VISIBILITY_TIMEOUT_MS=50;cvox.LiveRegions.lastAnnouncedMap={};cvox.LiveRegions.MAX_DISCARD_DUPS_MS=2000;cvox.LiveRegions.lastAnnouncedTime=null;cvox.LiveRegions.nodesAlreadyHandled=[];cvox.LiveRegions.init=function(pageLoadTime,queueMode,disableSpeak){cvox.LiveRegions.pageLoadTime=pageLoadTime;if(disableSpeak||!cvox.ChromeVox.documentHasFocus()){return false;}
var anyRegionsAnnounced=false;var regions=cvox.AriaUtil.getLiveRegions(document.body);for(var i=0;i<regions.length;i++){cvox.LiveRegions.handleOneChangedNode(regions[i],regions[i],false,false,function(assertive,navDescriptions){if(!assertive&&queueMode==cvox.QueueMode.FLUSH){queueMode=cvox.QueueMode.QUEUE;}
var descSpeaker=new cvox.NavigationSpeaker();descSpeaker.speakDescriptionArray(navDescriptions,queueMode,null);anyRegionsAnnounced=true;});}
cvox.Interframe.addListener(function(message){if(message['command']!='speakLiveRegion'){return;}
var iframes=document.getElementsByTagName('iframe');for(var i=0,iframe;iframe=iframes[i];i++){if(iframe.src==message['src']){if(!cvox.DomUtil.isVisible(iframe)){return;}
var structs=JSON.parse(message['content']);var descriptions=[];for(var j=0,description;description=structs[j];j++){descriptions.push(new cvox.NavDescription(description));}
new cvox.NavigationSpeaker().speakDescriptionArray(descriptions,message['queueMode'],null);}}});return anyRegionsAnnounced;};cvox.LiveRegions.processMutations=function(mutations,handler){cvox.LiveRegions.nodesAlreadyHandled=[];mutations.forEach(function(mutation){if(mutation.target.hasAttribute&&mutation.target.hasAttribute('cvoxIgnore')){return;}
if(mutation.addedNodes){for(var i=0;i<mutation.addedNodes.length;i++){if(mutation.addedNodes[i].hasAttribute&&mutation.addedNodes[i].hasAttribute('cvoxIgnore')){continue;}
cvox.LiveRegions.handleOneChangedNode(mutation.addedNodes[i],mutation.target,false,true,handler);}}
if(mutation.removedNodes){for(var i=0;i<mutation.removedNodes.length;i++){if(mutation.removedNodes[i].hasAttribute&&mutation.removedNodes[i].hasAttribute('cvoxIgnore')){continue;}
cvox.LiveRegions.handleOneChangedNode(mutation.removedNodes[i],mutation.target,true,false,handler);}}
if(mutation.type=='characterData'){cvox.LiveRegions.handleOneChangedNode(mutation.target,mutation.target,false,false,handler);}
if(mutation.attributeName=='class'||mutation.attributeName=='style'||mutation.attributeName=='hidden'){var attr=mutation.attributeName;var target=mutation.target;var newInvisible=!cvox.DomUtil.isVisible(target);var testElement=document.createElement('div');testElement.setAttribute('cvoxIgnore','1');testElement.setAttribute('class',target.getAttribute('class'));testElement.setAttribute('style',target.getAttribute('style'));testElement.setAttribute('hidden',target.getAttribute('hidden'));testElement.setAttribute(attr,(mutation.oldValue));var oldInvisible=true;if(target.parentElement){target.parentElement.appendChild(testElement);oldInvisible=!cvox.DomUtil.isVisible(testElement);target.parentElement.removeChild(testElement);}else{oldInvisible=!cvox.DomUtil.isVisible(testElement);}
if(oldInvisible===true&&newInvisible===false){cvox.LiveRegions.handleOneChangedNode(mutation.target,mutation.target,false,true,handler);}else if(oldInvisible===false&&newInvisible===true){cvox.LiveRegions.handleOneChangedNode(mutation.target,mutation.target,true,false,handler);}}});cvox.LiveRegions.nodesAlreadyHandled.length=0;};cvox.LiveRegions.handleOneChangedNode=function(node,parent,isRemoval,subtree,handler){var liveRoot=isRemoval?parent:node;if(!(liveRoot instanceof Element)){liveRoot=liveRoot.parentElement;}
while(liveRoot){if(cvox.AriaUtil.getAriaLive(liveRoot)){break;}
liveRoot=liveRoot.parentElement;}
if(!liveRoot){if(subtree&&node!=document.body){var subLiveRegions=cvox.AriaUtil.getLiveRegions(node);for(var i=0;i<subLiveRegions.length;i++){cvox.LiveRegions.handleOneChangedNode(subLiveRegions[i],parent,isRemoval,false,handler);}}
return;}
var deltaTime=new Date()-cvox.LiveRegions.pageLoadTime;if(cvox.AriaUtil.getRoleAttribute(liveRoot)!='alert'&&deltaTime<cvox.LiveRegions.INITIAL_SILENCE_MS){return;}
if(cvox.LiveRegions.nodesAlreadyHandled.indexOf(node)>=0){return;}
cvox.LiveRegions.nodesAlreadyHandled.push(node);if(cvox.AriaUtil.getAriaBusy(liveRoot)){return;}
if(isRemoval){if(!cvox.AriaUtil.getAriaRelevant(liveRoot,'removals')){return;}}else{if(!cvox.AriaUtil.getAriaRelevant(liveRoot,'additions')){return;}}
cvox.LiveRegions.announceChangeIfVisible(node,liveRoot,isRemoval,handler);};cvox.LiveRegions.announceChangeIfVisible=function(node,liveRoot,isRemoval,handler){if(cvox.DomUtil.isVisible(liveRoot)){cvox.LiveRegions.announceChange(node,liveRoot,isRemoval,handler);}else{window.setTimeout(function(){if(cvox.DomUtil.isVisible(liveRoot)){cvox.LiveRegions.announceChange(node,liveRoot,isRemoval,handler);}},cvox.LiveRegions.VISIBILITY_TIMEOUT_MS);}};cvox.LiveRegions.announceChange=function(node,liveRoot,isRemoval,handler){if(node!=liveRoot){var atomicContainer=node.parentElement;while(atomicContainer){if((cvox.AriaUtil.getAriaAtomic(atomicContainer)||cvox.AriaUtil.isLeafElement(atomicContainer)||cvox.AriaUtil.isControlWidget(atomicContainer))&&!cvox.AriaUtil.isCompositeControl(atomicContainer)){node=atomicContainer;}
if(atomicContainer==liveRoot){break;}
atomicContainer=atomicContainer.parentElement;}}
var navDescriptions=cvox.LiveRegions.getNavDescriptionsRecursive(node);if(isRemoval){navDescriptions=[cvox.DescriptionUtil.getDescriptionFromAncestors([node],true,cvox.ChromeVox.verbosity)];navDescriptions=[new cvox.NavDescription({context:Msgs.getMsg('live_regions_removed'),text:''})].concat(navDescriptions);}
if(navDescriptions.length==0){return;}
var deltaTime=new Date()-cvox.LiveRegions.pageLoadTime;if(cvox.AriaUtil.getRoleAttribute(liveRoot)=='alert'&&deltaTime<cvox.LiveRegions.INITIAL_SILENCE_MS){var regionText='';for(var i=0;i<navDescriptions.length;i++){regionText+=navDescriptions[i].text;regionText+=navDescriptions[i].userValue;}
if(cvox.DomUtil.collapseWhitespace(regionText)==''){return;}}
var now=new Date();for(var announced in cvox.LiveRegions.lastAnnouncedMap){if(now-cvox.LiveRegions.lastAnnouncedMap[announced]>cvox.LiveRegions.MAX_DISCARD_DUPS_MS){delete cvox.LiveRegions.lastAnnouncedMap[announced];}}
var key=navDescriptions.reduce(function(prev,navDescription){return prev+'|'+navDescription.text;},'');if(cvox.LiveRegions.lastAnnouncedMap[key]){return;}
cvox.LiveRegions.lastAnnouncedMap[key]=now;var assertive=cvox.AriaUtil.getAriaLive(liveRoot)=='assertive';if(cvox.Interframe.isIframe()&&!cvox.ChromeVox.documentHasFocus()){cvox.Interframe.sendMessageToParentWindow({'command':'speakLiveRegion','content':JSON.stringify(navDescriptions),'queueMode':assertive?0:1,'src':window.location.href});return;}
navDescriptions.forEach(function(desc){if(!desc.category){desc.category=cvox.TtsCategory.LIVE;}});if(navDescriptions.length>1){var allStrings=[];navDescriptions.forEach(function(desc){if(desc.context){allStrings.push(desc.context);}
if(desc.text){allStrings.push(desc.text);}
if(desc.userValue){allStrings.push(desc.userValue);}});navDescriptions=[new cvox.NavDescription({text:allStrings.join(', '),category:cvox.TtsCategory.LIVE})];}
handler(assertive,navDescriptions);};cvox.LiveRegions.getNavDescriptionsRecursive=function(node){if(cvox.AriaUtil.getAriaAtomic(node)||cvox.DomUtil.isLeafNode(node)){var description=cvox.DescriptionUtil.getDescriptionFromAncestors([node],true,cvox.ChromeVox.verbosity);if(!description.isEmpty()){return[description];}else{return[];}}
return cvox.DescriptionUtil.getFullDescriptionsFromChildren(null,(node));};goog.provide('cvox.NodeBreadcrumb');goog.require('cvox.ChromeVox');cvox.NodeBreadcrumb=function(){this.cvTagCounter_=0;};goog.addSingletonGetter(cvox.NodeBreadcrumb);cvox.NodeBreadcrumb.TOUCHED_TAG='chromevoxtag';cvox.NodeBreadcrumb.NEEDED_TAG_='chromevoxneeded';cvox.NodeBreadcrumb.prototype.tagCurrentNode=function(){var cvTag;var currentNode=cvox.ChromeVox.navigationManager.getCurrentNode();while(currentNode&&!currentNode.hasAttribute){currentNode=currentNode.parentNode;}
if(!currentNode){cvTag=-1;}else if(currentNode.hasAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG)){cvTag=currentNode.getAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG);}else{cvTag=this.cvTagCounter_;currentNode.setAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG,cvTag);this.cvTagCounter_++;}
return cvTag;};cvox.NodeBreadcrumb.prototype.smartStart_=function(node){for(var i=0;i<node.children.length;++i){var child=node.children[i];this.smartStart_(child);if(child.getAttribute&&!goog.isNull(child.getAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG))){this.setNeeded_(child);}}};cvox.NodeBreadcrumb.prototype.setNeeded_=function(node){if(!node){return;}
if(node.getAttribute&&goog.isNull(node.getAttribute(cvox.NodeBreadcrumb.NEEDED_TAG_))){node.setAttribute(cvox.NodeBreadcrumb.NEEDED_TAG_,true);if(node.nodeName!=='body'){this.setNeeded_(node.parentElement);}}};cvox.NodeBreadcrumb.prototype.smartClone_=function(node){var skipattrs={};skipattrs[cvox.NodeBreadcrumb.TOUCHED_TAG]=true;skipattrs[cvox.NodeBreadcrumb.NEEDED_TAG_]=true;if(node.getAttribute&&node.getAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG)){return cvox.DomUtil.deepClone(node,skipattrs);}
var ret=cvox.DomUtil.shallowChildlessClone(node,skipattrs);for(var i=0;i<node.childNodes.length;++i){var child=node.childNodes[i];if(child.getAttribute&&!goog.isNull(child.getAttribute(cvox.NodeBreadcrumb.NEEDED_TAG_))){ret.appendChild(this.smartClone_(child));}}
return ret;};cvox.NodeBreadcrumb.prototype.dumpWalkedDom=function(){this.smartStart_(document.body);return this.smartClone_(document.body);};cvox.NodeBreadcrumb.getCurrentNodeTag=function(){var currentNode=cvox.ChromeVox.navigationManager.getCurrentNode();while(currentNode&&!currentNode.hasAttribute){currentNode=currentNode.parentNode;}
if(currentNode&&currentNode.hasAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG)){return currentNode.getAttribute(cvox.NodeBreadcrumb.TOUCHED_TAG);}else{return-1;}};goog.provide('cvox.History');goog.require('cvox.DomUtil');goog.require('cvox.NodeBreadcrumb');cvox.HistoryEvent=function(opt_json){this.startTime_;this.endTime_;this.userCommand_;this.spoken_=[];this.cvTag_;this.replayed_=false;if(opt_json){this.replayed_=true;this.userCommand_=opt_json['cmd'];}else{this.startTime_=new Date().getTime();}};cvox.HistoryEvent.prototype.withUserCommand=function(functionName){if(this.userCommand_){window.console.error('Two user commands on '+functionName,this);return this;}
this.userCommand_=functionName;return this;};cvox.HistoryEvent.prototype.speak=function(str){this.spoken_.push(str);return this;};cvox.HistoryEvent.prototype.done=function(){this.endTime_=new Date().getTime();this.cvTag_=cvox.NodeBreadcrumb.getInstance().tagCurrentNode();window.console.log('User command done.',this);return this;};cvox.HistoryEvent.prototype.outputObject=function(){return{'start':this.startTime_,'end':this.endTime_,'cmd':this.userCommand_,'spoken':this.spoken_};};cvox.HistoryEvent.prototype.outputHTML=function(){var div=document.createElement('div');div.className='cvoxHistoryEvent';var dur=this.endTime_-this.startTime_;div.innerHTML=this.userCommand_+' ('+dur+'ms)';for(var i=0;i<this.spoken_.length;i++){var sdiv=document.createElement('div');sdiv.className='cvoxHistoryEventSpoken';sdiv.innerHTML=this.spoken_[i].substr(0,20);if(this.spoken_[i].length>20){sdiv.innerHTML+='...';}
div.appendChild(sdiv);}
return div;};cvox.HistoryEvent.prototype.outputJs=function(){var o='this.waitForCalm(this.userCommand, \''+this.userCommand_+'\')';if(this.spoken_.length>0){o+='\n  .waitForCalm(this.assertSpoken, \''+
cvox.DomUtil.collapseWhitespace(this.spoken_.join(' '))+'\');\n';}else{o+=';\n';}
return o;};cvox.History=function(){this.recording_=false;this.events_=[];this.markers_={};this.currentEvent_=null;this.mainDiv_=null;this.listDiv_=null;this.styleDiv_=null;this.bigBoxDiv_=null;this.nodeBreadcrumb_=cvox.NodeBreadcrumb.getInstance();};goog.addSingletonGetter(cvox.History);cvox.History.prototype.addListDiv_=function(){this.mainDiv_=document.createElement('div');this.mainDiv_.style.position='fixed';this.mainDiv_.style.bottom='0';this.mainDiv_.style.right='0';this.mainDiv_.style.zIndex='999';this.listDiv_=document.createElement('div');this.listDiv_.id='cvoxEventList';this.mainDiv_.appendChild(this.listDiv_);var buttonDiv=document.createElement('div');var button=document.createElement('button');button.onclick=cvox.History.sendToFeedback;button.innerHTML='Create bug';buttonDiv.appendChild(button);this.mainDiv_.appendChild(buttonDiv);var dumpDiv=document.createElement('div');var dumpButton=document.createElement('button');dumpButton.onclick=cvox.History.dumpJs;dumpButton.innerHTML='Dump test case';dumpDiv.appendChild(dumpButton);this.mainDiv_.appendChild(dumpDiv);document.body.appendChild(this.mainDiv_);this.styleDiv_=document.createElement('style');this.styleDiv_.innerHTML='.cvoxHistoryEventSpoken { color: gray; font-size: 75% }';document.body.appendChild(this.styleDiv_);};cvox.History.prototype.removeListDiv_=function(){document.body.removeChild(this.mainDiv_);document.body.removeChild(this.styleDiv_);this.mainDiv_=null;this.listDiv_=null;this.styleDiv_=null;};cvox.History.prototype.addBigTextBox_=function(){var bigBoxDiv=document.createElement('div');bigBoxDiv.style.position='fixed';bigBoxDiv.style.top='0';bigBoxDiv.style.left='0';bigBoxDiv.style.zIndex='999';var textarea=document.createElement('textarea');textarea.style.width='500px';textarea.style.height='500px';textarea.innerHTML=this.dumpJsOutput_();bigBoxDiv.appendChild(textarea);var buttons=document.createElement('div');bigBoxDiv.appendChild(buttons);function link(name,func){var linkElt=document.createElement('button');linkElt.onclick=func;linkElt.innerHTML=name;buttons.appendChild(linkElt);}
link('Close dialog',function(){document.body.removeChild(bigBoxDiv);});link('Remove fluff',goog.bind(function(){textarea.innerHTML=this.dumpJsOutput_(['stopSpeech','toggleKeyPrefix']);},this));document.body.appendChild(bigBoxDiv);};cvox.History.prototype.startRecording=function(){this.recording_=true;this.addListDiv_();};cvox.History.prototype.stopRecording=function(){this.recording_=false;this.removeListDiv_();this.events_=[];this.currentEvent_=null;};cvox.History.prototype.enterUserCommand=function(functionName){if(!this.recording_){return;}
if(this.currentEvent_){window.console.error('User command '+functionName+' overlaps current event',this.currentEvent_);}
this.currentEvent_=new cvox.HistoryEvent().withUserCommand(functionName);this.events_.push(this.currentEvent_);};cvox.History.prototype.exitUserCommand=function(functionName){if(!this.recording_||!this.currentEvent_){return;}
this.currentEvent_.done();this.listDiv_.appendChild(this.currentEvent_.outputHTML());this.currentEvent_=null;};cvox.History.prototype.speak=function(str,mode,props){if(!this.recording_){return this;}
if(!this.currentEvent_){window.console.error('Speak called outside of a user command.');return this;}
this.currentEvent_.speak(str);return this;};cvox.History.prototype.isSpeaking=function(){return false;};cvox.History.prototype.stop=function(){};cvox.History.prototype.addCapturingEventListener=function(listener){};cvox.History.prototype.increaseOrDecreaseProperty=function(propertyName,increase){};cvox.History.prototype.propertyToPercentage=function(property){};cvox.History.prototype.getDefaultProperty=function(property){};cvox.History.dumpJs=function(){var history=cvox.History.getInstance();history.addBigTextBox_();window.console.log(history.dumpJsOutput_());};cvox.History.prototype.dumpJsOutput_=function(opt_skipCommands){var skipMap={};if(opt_skipCommands){opt_skipCommands.forEach(function(e){skipMap[e]=1;});}
return['/*DOC: += ',this.nodeBreadcrumb_.dumpWalkedDom().innerHTML,'*/\n'].concat(this.events_.filter(function(e){return!(e.userCommand_ in skipMap);}).map(function(e){return e.outputJs();})).join('');};cvox.History.sendToFeedback=function(){var history=cvox.History.getInstance();var output=history.events_.map(function(e){return e.outputObject();});var feedbackScript=document.createElement('script');feedbackScript.type='text/javascript';feedbackScript.src='https://www.gstatic.com/feedback/api.js';var runFeedbackScript=document.createElement('script');runFeedbackScript.type='text/javascript';runFeedbackScript.innerHTML='userfeedback.api.startFeedback('+'{ productId: \'76092\' }, '+'{ cvoxHistory: '+cvox.ChromeVoxJSON.stringify(cvox.ChromeVoxJSON.stringify(output))+' });';feedbackScript.onload=function(){document.body.appendChild(runFeedbackScript);};document.body.appendChild(feedbackScript);};goog.provide('cvox.ActiveIndicator');goog.require('cvox.Cursor');goog.require('cvox.DomUtil');cvox.ActiveIndicator=function(){this.lastMoveTime_=0;this.zoom_=1;this.container_=null;this.rects_=null;this.lastSyncTarget_=null;this.lastClientRects_=null;this.updateIndicatorTimeoutId_=null;this.blurred_=false;this.innerHeight_;this.innerWidth_;window.addEventListener('focus',goog.bind(function(){this.blurred_=false;if(this.container_){this.container_.classList.remove('cvox_indicator_window_not_focused');}},this),false);window.addEventListener('blur',goog.bind(function(){this.blurred_=true;if(this.container_){this.container_.classList.add('cvox_indicator_window_not_focused');}},this),false);};cvox.ActiveIndicator.STYLE='.cvox_indicator_container {'+'  position: absolute !important;'+'  left: 0 !important;'+'  top: 0 !important;'+'  z-index: 2147483647 !important;'+'  pointer-events: none !important;'+'  margin: 0px !important;'+'  padding: 0px !important;'+'}'+'.cvox_indicator_window_not_focused {'+'  visibility: hidden !important;'+'}'+'.cvox_indicator_pulsing {'+'  -webkit-animation: '+'      cvox_indicator_pulsing_animation 0s 2 alternate !important;'+'  -webkit-animation-timing-function: ease-in-out !important;'+'}'+'.cvox_indicator_region {'+'  opacity: 0 !important;'+'  -webkit-transition: opacity 1s !important;'+'}'+'.cvox_indicator_visible {'+'  opacity: 1 !important;'+'}'+'.cvox_indicator_container .cvox_indicator_region * {'+'  position:absolute !important;'+'  box-shadow: 0 0 4px 4px #f7983a !important;'+'  border-radius: 6px !important;'+'  margin: 0px !important;'+'  padding: 0px !important;'+'  -webkit-transition: none !important;'+'}'+'.cvox_indicator_animate_normal .cvox_indicator_region * {'+'  -webkit-transition: all 0.3s !important;'+'}'+'.cvox_indicator_animate_quick .cvox_indicator_region * {'+'  -webkit-transition: all 0.1s !important;'+'}'+'.cvox_indicator_top {'+'  border-radius: inherit inherit 0 0 !important;'+'}'+'.cvox_indicator_middle_nw {'+'  border-radius: inherit 0 0 0 !important;'+'}'+'.cvox_indicator_middle_ne {'+'  border-radius: 0 inherit 0 0 !important;'+'}'+'.cvox_indicator_middle_se {'+'  border-radius: 0 0 inherit 0 !important;'+'}'+'.cvox_indicator_middle_sw {'+'  border-radius: 0 0 0 inherit !important;'+'}'+'.cvox_indicator_bottom {'+'  border-radius: 0 0 inherit inherit !important;'+'}'+'@-webkit-keyframes cvox_indicator_pulsing_animation {'+'   0% {opacity: 1.0}'+'  50% {opacity: 0.5}'+' 100% {opacity: 1.0}'+'}';cvox.ActiveIndicator.QUICK_ANIM_DELAY_MS=100;cvox.ActiveIndicator.NORMAL_ANIM_DELAY_MS=300;cvox.ActiveIndicator.MARGIN=8;cvox.ActiveIndicator.prototype.removeFromDom=function(){if(this.container_&&this.container_.parentElement){this.container_.parentElement.removeChild(this.container_);}};cvox.ActiveIndicator.prototype.syncToNode=function(node){if(!node){return;}
if(node==document.body){this.removeFromDom();return;}
this.syncToNodes([node]);};cvox.ActiveIndicator.prototype.syncToNodes=function(nodes){var clientRects=this.clientRectsFromNodes_(nodes);this.moveIndicator_(clientRects,cvox.ActiveIndicator.MARGIN);this.lastSyncTarget_=nodes;this.lastClientRects_=clientRects;if(this.updateIndicatorTimeoutId_!=null){window.clearTimeout(this.updateIndicatorTimeoutId_);this.updateIndicatorTimeoutId_=null;}};cvox.ActiveIndicator.prototype.syncToRange=function(range){var margin=cvox.ActiveIndicator.MARGIN;if(range.startContainer==range.endContainer&&range.startOffset+1==range.endOffset){margin=1;}
var clientRects=range.getClientRects();this.moveIndicator_(clientRects,margin);this.lastSyncTarget_=range;this.lastClientRects_=clientRects;if(this.updateIndicatorTimeoutId_!=null){window.clearTimeout(this.updateIndicatorTimeoutId_);this.updateIndicatorTimeoutId_=null;}};cvox.ActiveIndicator.prototype.syncToCursorSelection=function(sel){if(sel.start.node==sel.end.node&&sel.start.index==sel.end.index){this.syncToNode(sel.start.node);}else{var range=document.createRange();range.setStart(sel.start.node,sel.start.index);range.setEnd(sel.end.node,sel.end.index);this.syncToRange(range);}};cvox.ActiveIndicator.prototype.updateIndicatorIfChanged=function(){if(this.updateIndicatorTimeoutId_){return;}
this.updateIndicatorTimeoutId_=window.setTimeout(goog.bind(function(){this.handleUpdateIndicatorIfChanged_();},this),100);};cvox.ActiveIndicator.prototype.handleUpdateIndicatorIfChanged_=function(){this.updateIndicatorTimeoutId_=null;if(!this.lastSyncTarget_){return;}
var newClientRects;if(this.lastSyncTarget_ instanceof Array){newClientRects=this.clientRectsFromNodes_(this.lastSyncTarget_);}else{newClientRects=this.lastSyncTarget_.getClientRects();}
if(!newClientRects||newClientRects.length==0){this.syncToNode(document.body);return;}
var needsUpdate=false;if(newClientRects.length!=this.lastClientRects_.length){needsUpdate=true;}else{for(var i=0;i<this.lastClientRects_.length;++i){var last=this.lastClientRects_[i];var current=newClientRects[i];if(last.top!=current.top||last.right!=current.right||last.bottom!=current.bottom||last.left!=last.left){needsUpdate=true;break;}}}
if(needsUpdate){this.moveIndicator_(newClientRects,cvox.ActiveIndicator.MARGIN);this.lastClientRects_=newClientRects;}};cvox.ActiveIndicator.prototype.clientRectsFromNodes_=function(nodes){var clientRects=[];for(var i=0;i<nodes.length;++i){var node=nodes[i];if(node.constructor==Text){var range=document.createRange();range.selectNode(node);var rangeRects=range.getClientRects();for(var j=0;j<rangeRects.length;++j)
clientRects.push(rangeRects[j]);}else{while(!node.getClientRects){node=node.parentElement;}
if(!node){return[];}
var nodeRects=node.getClientRects();for(var j=0;j<nodeRects.length;++j)
clientRects.push(nodeRects[j]);}}
return clientRects;};cvox.ActiveIndicator.prototype.moveIndicator_=function(immutableRects,margin){if(document.body.isContentEditable){this.removeFromDom();return;}
var n=immutableRects.length;if(n==0){return;}
var offsetX;var offsetY;if(window.getComputedStyle(document.body,null).position!='static'){offsetX=-document.body.getBoundingClientRect().left;offsetY=-document.body.getBoundingClientRect().top;}else if(window.getComputedStyle(document.documentElement,null).position!='static'){offsetX=-document.documentElement.getBoundingClientRect().left;offsetY=-document.documentElement.getBoundingClientRect().top;}else{offsetX=window.pageXOffset;offsetY=window.pageYOffset;}
var rects=[];for(var i=0;i<n;i++){rects.push(this.inset_(immutableRects[i],offsetX,offsetY,-offsetX,-offsetY));}
if(!this.container_||!this.container_.parentElement){var oldContainers=document.getElementsByClassName('cvox_indicator_container');for(var j=0,oldContainer;oldContainer=oldContainers[j];j++){if(oldContainer.parentNode){oldContainer.parentNode.removeChild(oldContainer);}}
this.container_=this.createDiv_(document.body,'cvox_indicator_container',document.body.firstChild);}
var style=document.createElement('style');style.id='cvox_indicator_style';style.innerHTML=cvox.ActiveIndicator.STYLE;cvox.DomUtil.addNodeToHead(style,style.id);var now=new Date().getTime();var delta=now-this.lastMoveTime_;this.container_.className='cvox_indicator_container';if(!cvox.ChromeVox.documentHasFocus()||this.blurred_){this.container_.classList.add('cvox_indicator_window_not_focused');}
if(delta>cvox.ActiveIndicator.NORMAL_ANIM_DELAY_MS){this.container_.classList.add('cvox_indicator_animate_normal');}else if(delta>cvox.ActiveIndicator.QUICK_ANIM_DELAY_MS){this.container_.classList.add('cvox_indicator_animate_quick');}
this.lastMoveTime_=now;this.computeZoomLevel_();window.setTimeout(goog.bind(function(){this.container_.classList.add('cvox_indicator_pulsing');},this),0);while(this.container_.childElementCount>1){this.container_.removeChild(this.container_.lastElementChild);}
var regions=[[rects[0]]];var regionRects=[rects[0]];for(i=1;i<rects.length;i++){var found=false;for(var j=0;j<regions.length&&!found;j++){if(this.intersects_(rects[i],regionRects[j])){regions[j].push(rects[i]);regionRects[j]=this.union_(regionRects[j],rects[i]);found=true;}}
if(!found){regions.push([rects[i]]);regionRects.push(rects[i]);}}
do{var merged=false;for(i=0;i<regions.length-1&&!merged;i++){for(j=i+1;j<regions.length&&!merged;j++){if(this.intersects_(regionRects[i],regionRects[j])){regions[i]=regions[i].concat(regions[j]);regionRects[i]=this.union_(regionRects[i],regionRects[j]);regions.splice(j,1);regionRects.splice(j,1);merged=true;}}}}while(merged);for(i=0;i<regions.length;i++){regions[i].sort(function(r1,r2){if(r1.top!=r2.top){return r1.top-r2.top;}else{return r1.left-r2.left;}});}
for(i=0;i<regions.length;i++){var parent=null;if(i==0&&this.container_.childElementCount==1&&this.container_.children[0].childElementCount==6){parent=this.container_.children[0];}
this.updateIndicatorRegion_(regions[i],parent,margin);}};cvox.ActiveIndicator.prototype.updateIndicatorRegion_=function(rects,parent,margin){if(parent){var regionTop=parent.children[0];var regionMiddleNW=parent.children[1];var regionMiddleNE=parent.children[2];var regionMiddleSW=parent.children[3];var regionMiddleSE=parent.children[4];var regionBottom=parent.children[5];}else{parent=this.createDiv_(this.container_,'cvox_indicator_region');window.setTimeout(function(){parent.classList.add('cvox_indicator_visible');},0);regionTop=this.createDiv_(parent,'cvox_indicator_top');regionMiddleNW=this.createDiv_(parent,'cvox_indicator_middle_nw');regionMiddleNE=this.createDiv_(parent,'cvox_indicator_middle_ne');regionMiddleSW=this.createDiv_(parent,'cvox_indicator_middle_sw');regionMiddleSE=this.createDiv_(parent,'cvox_indicator_middle_se');regionBottom=this.createDiv_(parent,'cvox_indicator_bottom');}
var topRect=rects[0];var topMiddle=Math.floor((topRect.top+topRect.bottom)/2);var topIndex=1;var n=rects.length;while(topIndex<n&&rects[topIndex].top<topMiddle){topRect=this.union_(topRect,rects[topIndex]);topMiddle=Math.floor((topRect.top+topRect.bottom)/2);topIndex++;}
if(topIndex==n){var r=this.inset_(topRect,-margin,-margin,-margin,-margin);var q1=Math.floor((3*r.top+1*r.bottom)/4);var q2=Math.floor((2*r.top+2*r.bottom)/4);var q3=Math.floor((1*r.top+3*r.bottom)/4);this.setElementCoords_(regionTop,r.left,r.top,r.right,q1,true,true,true,false);this.setElementCoords_(regionMiddleNW,r.left,q1,r.left,q2,true,true,false,false);this.setElementCoords_(regionMiddleSW,r.left,q2,r.left,q3,true,false,false,true);this.setElementCoords_(regionMiddleNE,r.right,q1,r.right,q2,false,true,true,false);this.setElementCoords_(regionMiddleSE,r.right,q2,r.right,q3,false,false,true,true);this.setElementCoords_(regionBottom,r.left,q3,r.right,r.bottom,true,false,true,true);return;}
var bottomRect=rects[n-1];var bottomMiddle=Math.floor((bottomRect.top+bottomRect.bottom)/2);var bottomIndex=n-2;while(bottomIndex>=0&&rects[bottomIndex].bottom>bottomMiddle){bottomRect=this.union_(bottomRect,rects[bottomIndex]);bottomMiddle=Math.floor((bottomRect.top+bottomRect.bottom)/2);bottomIndex--;}
topRect=this.inset_(topRect,-margin,-margin,-margin,margin);bottomRect=this.inset_(bottomRect,-margin,margin,-margin,-margin);var middleRect;if(topIndex>bottomIndex){middleRect=this.union_(topRect,bottomRect);middleRect.top=topRect.bottom;middleRect.bottom=bottomRect.top;middleRect.height=Math.floor((middleRect.top+middleRect.bottom)/2);}else{middleRect=rects[topIndex];var middleIndex=topIndex+1;while(middleIndex<=bottomIndex){middleRect=this.union_(middleRect,rects[middleIndex]);middleIndex++;}
middleRect=this.inset_(middleRect,-margin,-margin,-margin,-margin);middleRect.left=Math.min(middleRect.left,topRect.left,bottomRect.left);middleRect.right=Math.max(middleRect.right,topRect.right,bottomRect.right);middleRect.width=middleRect.right-middleRect.left;}
if(topRect.right>middleRect.right-40){topRect.right=middleRect.right;topRect.width=topRect.right-topRect.left;}
if(topRect.left<middleRect.left+40){topRect.left=middleRect.left;topRect.width=topRect.right-topRect.left;}
if(bottomRect.right>middleRect.right-40){bottomRect.right=middleRect.right;bottomRect.width=bottomRect.right-bottomRect.left;}
if(bottomRect.left<middleRect.left+40){bottomRect.left=middleRect.left;bottomRect.width=bottomRect.right-bottomRect.left;}
var midline=Math.floor((middleRect.top+middleRect.bottom)/2);this.setElementRect_(regionTop,topRect,true,true,true,false);this.setElementRect_(regionBottom,bottomRect,true,false,true,true);this.setElementCoords_(regionMiddleNW,middleRect.left,topRect.bottom,topRect.left,midline,true,true,false,false);this.setElementCoords_(regionMiddleNE,topRect.right,topRect.bottom,middleRect.right,midline,false,true,true,false);this.setElementCoords_(regionMiddleSW,middleRect.left,midline,bottomRect.left,bottomRect.top,true,false,false,true);this.setElementCoords_(regionMiddleSE,bottomRect.right,midline,middleRect.right,bottomRect.top,false,false,true,true);};cvox.ActiveIndicator.prototype.intersects_=function(r1,r2){var slop=2*cvox.ActiveIndicator.MARGIN;return(r2.left<=r1.right+slop&&r2.right>=r1.left-slop&&r2.top<=r1.bottom+slop&&r2.bottom>=r1.top-slop);};cvox.ActiveIndicator.prototype.union_=function(r1,r2){var result={left:Math.min(r1.left,r2.left),top:Math.min(r1.top,r2.top),right:Math.max(r1.right,r2.right),bottom:Math.max(r1.bottom,r2.bottom)};result.width=result.right-result.left;result.height=result.bottom-result.top;return(result);};cvox.ActiveIndicator.prototype.inset_=function(r,left,top,right,bottom){var result={left:r.left+left,top:r.top+top,right:r.right-right,bottom:r.bottom-bottom};result.width=result.right-result.left;result.height=result.bottom-result.top;return(result);};cvox.ActiveIndicator.prototype.createDiv_=function(parent,className,opt_before){var elem=document.createElement('div');elem.setAttribute('aria-hidden','true');elem.setAttribute('cvoxIgnore','');elem.className=className;if(opt_before){parent.insertBefore(elem,opt_before);}else{parent.appendChild(elem);}
return elem;};cvox.ActiveIndicator.prototype.fixZoom_=function(x){return(Math.round(x*this.zoom_)+0.1)/this.zoom_;};cvox.ActiveIndicator.prototype.fixZoomSum_=function(x,width){var zoomedX=Math.round(x*this.zoom_);var zoomedRight=Math.round((x+width)*this.zoom_);var zoomedWidth=(zoomedRight-zoomedX);return(zoomedWidth+0.1)/this.zoom_;};cvox.ActiveIndicator.prototype.setElementCoords_=function(element,left,top,right,bottom,showLeft,showTop,showRight,showBottom){var origWidth=right-left;var origHeight=bottom-top;var width=right-left;var height=bottom-top;var clipLeft=showLeft?-20:0;var clipTop=showTop?-20:0;var clipRight=showRight?20:0;var clipBottom=showBottom?20:0;if(width==0){if(showRight){left-=5;width+=5;}else if(showLeft){width+=10;}
clipTop=10;clipBottom=10;top-=10;height+=20;}
if(!showBottom)
height+=5;if(!showTop){top-=5;height+=5;clipTop+=5;clipBottom+=5;}
if(clipRight==0&&origWidth==0){clipRight=1;}else{clipRight=this.fixZoomSum_(left,clipRight+origWidth);}
clipBottom=this.fixZoomSum_(top,clipBottom+origHeight);element.style.left=this.fixZoom_(left)+'px';element.style.top=this.fixZoom_(top)+'px';element.style.width=this.fixZoomSum_(left,width)+'px';element.style.height=this.fixZoomSum_(top,height)+'px';element.style.clip='rect('+[clipTop,clipRight,clipBottom,clipLeft].join('px ')+'px)';};cvox.ActiveIndicator.prototype.setElementRect_=function(element,r,showLeft,showTop,showRight,showBottom){this.setElementCoords_(element,r.left,r.top,r.right,r.bottom,showLeft,showTop,showRight,showBottom);};cvox.ActiveIndicator.prototype.computeZoomLevel_=function(){if(window.innerHeight===this.innerHeight_&&window.innerWidth===this.innerWidth_){return;}
this.innerHeight_=window.innerHeight;this.innerWidth_=window.innerWidth;var zoomMeasureElement=document.createElement('div');zoomMeasureElement.innerHTML='X';zoomMeasureElement.setAttribute('style','font: 5000px/1em sans-serif !important;'+' -webkit-text-size-adjust:none !important;'+' visibility:hidden !important;'+' left: -10000px !important;'+' top: -10000px !important;'+' position:absolute !important;');document.body.appendChild(zoomMeasureElement);var zoomLevel=5000/zoomMeasureElement.clientHeight;var newZoom=Math.round(zoomLevel*500)/500;if(newZoom>0.1&&newZoom<10){this.zoom_=newZoom;}
zoomMeasureElement.parentNode.removeChild(zoomMeasureElement);};goog.provide('cvox.ChromeVoxHTMLMediaWidget');cvox.ChromeVoxHTMLMediaWidget=function(mediaElem,tts){var self=this;this.mediaElem_=mediaElem;this.mediaTts_=tts;this.keyListener_=function(evt){self.eventHandler_(evt);}
this.blurListener_=function(evt){self.shutdown();}
this.mediaElem_.addEventListener('keydown',this.keyListener_,false);this.mediaElem_.addEventListener('keyup',this.keyListener_,false);this.mediaElem_.addEventListener('blur',this.blurListener_,false);};cvox.ChromeVoxHTMLMediaWidget.prototype.shutdown=function(){this.mediaElem_.removeEventListener('blur',this.blurListener_,false);this.mediaElem_.removeEventListener('keydown',this.keyListener_,false);this.mediaElem_.removeEventListener('keyup',this.keyListener_,false);};cvox.ChromeVoxHTMLMediaWidget.prototype.jumpToTime_=function(targetTime){if(targetTime<0){targetTime=0;}
if(targetTime>this.mediaElem_.duration){targetTime=this.mediaElem_.duration;}
this.mediaElem_.currentTime=targetTime;};cvox.ChromeVoxHTMLMediaWidget.prototype.setVolume_=function(targetVolume){if(targetVolume<0){targetVolume=0;}
if(targetVolume>1.0){targetVolume=1.0;}
this.mediaElem_.volume=targetVolume;};cvox.ChromeVoxHTMLMediaWidget.prototype.eventHandler_=function(evt){if(evt.type=='keydown'){if((evt.keyCode==13)||(evt.keyCode==32)){if(this.mediaElem_.paused){this.mediaElem_.play();}else{this.mediaElem_.pause();}}else if(evt.keyCode==39){this.jumpToTime_(this.mediaElem_.currentTime+(this.mediaElem_.duration/10));}else if(evt.keyCode==37){this.jumpToTime_(this.mediaElem_.currentTime-(this.mediaElem_.duration/10));}else if(evt.keyCode==38){this.setVolume_(this.mediaElem_.volume+.1);}else if(evt.keyCode==40){this.setVolume_(this.mediaElem_.volume-.1);}}};goog.provide('cvox.PlatformFilter');goog.provide('cvox.PlatformUtil');goog.require('cvox.ChromeVox');cvox.PlatformFilter={NONE:0,WINDOWS:1,MAC:2,LINUX:4,WML:7,CHROMEOS:8,ANDROID:16};cvox.PlatformUtil.matchesPlatform=function(filter){var uA=navigator.userAgent;if(filter==undefined){return true;}else if(uA.indexOf('Android')!=-1){return(filter&cvox.PlatformFilter.ANDROID)!=0;}else if(uA.indexOf('Win')!=-1){return(filter&cvox.PlatformFilter.WINDOWS)!=0;}else if(uA.indexOf('Mac')!=-1){return(filter&cvox.PlatformFilter.MAC)!=0;}else if(uA.indexOf('Linux')!=-1){return(filter&cvox.PlatformFilter.LINUX)!=0;}else if(uA.indexOf('CrOS')!=-1){return(filter&cvox.PlatformFilter.CHROMEOS)!=0;}
return false;};goog.provide('cvox.KeySequence');goog.require('cvox.ChromeVox');goog.require('cvox.PlatformFilter');cvox.KeySequence=function(originalEvent,opt_cvoxModifier,opt_doubleTap,opt_skipStripping,opt_requireStickyMode){this.doubleTap=!!opt_doubleTap;this.requireStickyMode=!!opt_requireStickyMode;this.platformFilter;this.skipStripping=!!opt_skipStripping;if(opt_cvoxModifier==undefined){this.cvoxModifier=this.isCVoxModifierActive(originalEvent);}else{this.cvoxModifier=opt_cvoxModifier;}
this.stickyMode=!!originalEvent['stickyMode'];this.prefixKey=!!originalEvent['keyPrefix'];if(this.stickyMode&&this.prefixKey){throw'Prefix key and sticky mode cannot both be enabled: '+originalEvent;}
var event=this.resolveChromeOSSpecialKeys_(originalEvent);this.keys={ctrlKey:[],searchKeyHeld:[],altKey:[],altGraphKey:[],shiftKey:[],metaKey:[],keyCode:[]};this.extractKey_(event);};cvox.KeySequence.KEY_PRESS_CODE={39:222,44:188,45:189,46:190,47:191,59:186,91:219,92:220,93:221};cvox.KeySequence.doubleTapCache=[];cvox.KeySequence.prototype.addKeyEvent=function(additionalKeyEvent){if(this.keys.keyCode.length>1){return false;}
this.extractKey_(additionalKeyEvent);return true;};cvox.KeySequence.prototype.equals=function(rhs){if(!this.checkKeyEquality_(rhs)){return false;}
if(this.doubleTap!=rhs.doubleTap){return false;}
if(this.requireStickyMode||rhs.requireStickyMode){return(this.stickyMode||rhs.stickyMode)&&!this.cvoxModifier&&!rhs.cvoxModifier;}
if(this.cvoxModifier===rhs.cvoxModifier){return true;}
var unmodified=this.cvoxModifier?rhs:this;return unmodified.stickyMode||unmodified.prefixKey;};cvox.KeySequence.prototype.extractKey_=function(keyEvent){for(var prop in this.keys){if(prop=='keyCode'){var keyCode;if(keyEvent.type=='keypress'&&keyEvent[prop]>=97&&keyEvent[prop]<=122){keyCode=keyEvent[prop]-32;}else if(keyEvent.type=='keypress'){keyCode=cvox.KeySequence.KEY_PRESS_CODE[keyEvent[prop]];}
this.keys[prop].push(keyCode||keyEvent[prop]);}else{if(this.isKeyModifierActive(keyEvent,prop)){this.keys[prop].push(true);}else{this.keys[prop].push(false);}}}
if(this.cvoxModifier){this.rationalizeKeys_();}};cvox.KeySequence.prototype.rationalizeKeys_=function(){if(this.skipStripping){return;}
var modifierKeyCombo=cvox.ChromeVox.modKeyStr.split(/\+/g);var index=this.keys.keyCode.length-1;if(modifierKeyCombo.indexOf('Ctrl')!=-1){this.keys.ctrlKey[index]=false;}
if(modifierKeyCombo.indexOf('Alt')!=-1){this.keys.altKey[index]=false;}
if(modifierKeyCombo.indexOf('Shift')!=-1){this.keys.shiftKey[index]=false;}
var metaKeyName=this.getMetaKeyName_();if(modifierKeyCombo.indexOf(metaKeyName)!=-1){if(metaKeyName=='Search'){this.keys.searchKeyHeld[index]=false;this.keys.metaKey[index]=false;}else if(metaKeyName=='Cmd'||metaKeyName=='Win'){this.keys.metaKey[index]=false;}}};cvox.KeySequence.prototype.getMetaKeyName_=function(){if(cvox.ChromeVox.isChromeOS){return'Search';}else if(cvox.ChromeVox.isMac){return'Cmd';}else{return'Win';}};cvox.KeySequence.prototype.checkKeyEquality_=function(rhs){for(var i in this.keys){for(var j=this.keys[i].length;j--;){if(this.keys[i][j]!==rhs.keys[i][j])
return false;}}
return true;};cvox.KeySequence.prototype.getFirstKeyCode=function(){return this.keys.keyCode[0];};cvox.KeySequence.prototype.length=function(){return this.keys.keyCode.length;};cvox.KeySequence.prototype.isModifierKey=function(keyCode){return keyCode==16||keyCode==17||keyCode==18||keyCode==91||keyCode==93;};cvox.KeySequence.prototype.isCVoxModifierActive=function(keyEvent){var modifierKeyCombo=cvox.ChromeVox.modKeyStr.split(/\+/g);if(this.isKeyModifierActive(keyEvent,'ctrlKey')){modifierKeyCombo=modifierKeyCombo.filter(function(modifier){return modifier!='Ctrl';});}
if(this.isKeyModifierActive(keyEvent,'altKey')){modifierKeyCombo=modifierKeyCombo.filter(function(modifier){return modifier!='Alt';});}
if(this.isKeyModifierActive(keyEvent,'shiftKey')){modifierKeyCombo=modifierKeyCombo.filter(function(modifier){return modifier!='Shift';});}
if(this.isKeyModifierActive(keyEvent,'metaKey')||this.isKeyModifierActive(keyEvent,'searchKeyHeld')){var metaKeyName=this.getMetaKeyName_();modifierKeyCombo=modifierKeyCombo.filter(function(modifier){return modifier!=metaKeyName;});}
return(modifierKeyCombo.length==0);};cvox.KeySequence.prototype.isKeyModifierActive=function(keyEvent,modifier){switch(modifier){case'ctrlKey':return(keyEvent.ctrlKey||keyEvent.keyCode==17);break;case'altKey':return(keyEvent.altKey||(keyEvent.keyCode==18));break;case'shiftKey':return(keyEvent.shiftKey||(keyEvent.keyCode==16));break;case'metaKey':return(keyEvent.metaKey||(keyEvent.keyCode==91));break;case'searchKeyHeld':return((cvox.ChromeVox.isChromeOS&&keyEvent.keyCode==91)||keyEvent['searchKeyHeld']);break;}
return false;};cvox.KeySequence.prototype.isAnyModifierActive=function(){for(var modifierType in this.keys){for(var i=0;i<this.length();i++){if(this.keys[modifierType][i]&&modifierType!='keyCode'){return true;}}}
return false;};cvox.KeySequence.deserialize=function(sequenceObject){var firstSequenceEvent={};firstSequenceEvent['stickyMode']=(sequenceObject.stickyMode==undefined)?false:sequenceObject.stickyMode;firstSequenceEvent['prefixKey']=(sequenceObject.prefixKey==undefined)?false:sequenceObject.prefixKey;var secondKeyPressed=sequenceObject.keys.keyCode.length>1;var secondSequenceEvent={};for(var keyPressed in sequenceObject.keys){firstSequenceEvent[keyPressed]=sequenceObject.keys[keyPressed][0];if(secondKeyPressed){secondSequenceEvent[keyPressed]=sequenceObject.keys[keyPressed][1];}}
var skipStripping=sequenceObject.skipStripping!==undefined?sequenceObject.skipStripping:true;var keySeq=new cvox.KeySequence(firstSequenceEvent,sequenceObject.cvoxModifier,sequenceObject.doubleTap,skipStripping,sequenceObject.requireStickyMode);if(secondKeyPressed){cvox.ChromeVox.sequenceSwitchKeyCodes.push(new cvox.KeySequence(firstSequenceEvent,sequenceObject.cvoxModifier));keySeq.addKeyEvent(secondSequenceEvent);}
if(sequenceObject.doubleTap){cvox.KeySequence.doubleTapCache.push(keySeq);}
return keySeq;};cvox.KeySequence.fromStr=function(keyStr){var sequenceEvent={};var secondSequenceEvent={};var secondKeyPressed;if(keyStr.indexOf('>')==-1){secondKeyPressed=false;}else{secondKeyPressed=true;}
var cvoxPressed=false;sequenceEvent['stickyMode']=false;sequenceEvent['prefixKey']=false;var tokens=keyStr.split('+');for(var i=0;i<tokens.length;i++){var seqs=tokens[i].split('>');for(var j=0;j<seqs.length;j++){if(seqs[j].charAt(0)=='#'){var keyCode=parseInt(seqs[j].substr(1),10);if(j>0){secondSequenceEvent['keyCode']=keyCode;}else{sequenceEvent['keyCode']=keyCode;}}
var keyName=seqs[j];if(seqs[j].length==1){if(j>0){secondSequenceEvent['keyCode']=seqs[j].charCodeAt(0);}else{sequenceEvent['keyCode']=seqs[j].charCodeAt(0);}}else{if(j>0){cvox.KeySequence.setModifiersOnEvent_(keyName,secondSequenceEvent);if(keyName=='Cvox'){cvoxPressed=true;}}else{cvox.KeySequence.setModifiersOnEvent_(keyName,sequenceEvent);if(keyName=='Cvox'){cvoxPressed=true;}}}}}
var keySeq=new cvox.KeySequence(sequenceEvent,cvoxPressed);if(secondKeyPressed){keySeq.addKeyEvent(secondSequenceEvent);}
return keySeq;};cvox.KeySequence.setModifiersOnEvent_=function(keyName,seqEvent){if(keyName=='Ctrl'){seqEvent['ctrlKey']=true;seqEvent['keyCode']=17;}else if(keyName=='Alt'){seqEvent['altKey']=true;seqEvent['keyCode']=18;}else if(keyName=='Shift'){seqEvent['shiftKey']=true;seqEvent['keyCode']=16;}else if(keyName=='Search'){seqEvent['searchKeyHeld']=true;seqEvent['keyCode']=91;}else if(keyName=='Cmd'){seqEvent['metaKey']=true;seqEvent['keyCode']=91;}else if(keyName=='Win'){seqEvent['metaKey']=true;seqEvent['keyCode']=91;}else if(keyName=='Insert'){seqEvent['keyCode']=45;}};cvox.KeySequence.prototype.resolveChromeOSSpecialKeys_=function(originalEvent){if(!this.cvoxModifier||this.stickyMode||this.prefixKey||!cvox.ChromeVox.isChromeOS){return originalEvent;}
var evt={};for(var key in originalEvent){evt[key]=originalEvent[key];}
switch(evt['keyCode']){case 33:evt['keyCode']=38;break;case 34:evt['keyCode']=40;break;case 35:evt['keyCode']=39;break;case 36:evt['keyCode']=37;break;case 45:evt['keyCode']=190;break;case 46:evt['keyCode']=8;break;case 112:evt['keyCode']=49;break;case 113:evt['keyCode']=50;break;case 114:evt['keyCode']=51;break;case 115:evt['keyCode']=52;break;case 116:evt['keyCode']=53;break;case 117:evt['keyCode']=54;break;case 118:evt['keyCode']=55;break;case 119:evt['keyCode']=56;break;case 120:evt['keyCode']=57;break;case 121:evt['keyCode']=48;break;case 122:evt['keyCode']=189;break;case 123:evt['keyCode']=187;break;}
return evt;};goog.provide('cvox.KeyUtil');goog.provide('cvox.SimpleKeyEvent');goog.require('Msgs');goog.require('cvox.ChromeVox');goog.require('cvox.KeySequence');cvox.SimpleKeyEvent;cvox.KeyUtil=function(){};cvox.KeyUtil.modeKeyPressTime=0;cvox.KeyUtil.sequencing=false;cvox.KeyUtil.prevKeySequence=null;cvox.KeyUtil.stickyKeySequence=null;cvox.KeyUtil.maxSeqLength=2;cvox.KeyUtil.keyEventToKeySequence=function(keyEvent){var util=cvox.KeyUtil;if(util.prevKeySequence&&(util.maxSeqLength==util.prevKeySequence.length())){util.sequencing=false;util.prevKeySequence=null;}
var keyIsPrefixed=util.sequencing||keyEvent['keyPrefix']||keyEvent['stickyMode'];var keySequence=new cvox.KeySequence(keyEvent);var keyWasCvox=keySequence.cvoxModifier;if(keyIsPrefixed||keyWasCvox){if(!util.sequencing&&util.isSequenceSwitchKeyCode(keySequence)){util.sequencing=true;util.prevKeySequence=keySequence;return keySequence;}else if(util.sequencing){if(util.prevKeySequence.addKeyEvent(keyEvent)){keySequence=util.prevKeySequence;util.prevKeySequence=null;util.sequencing=false;return keySequence;}else{throw'Think sequencing is enabled, yet util.prevKeySequence already'+'has two key codes'+util.prevKeySequence;}}}else{util.sequencing=false;}
var currTime=new Date().getTime();if(cvox.KeyUtil.isDoubleTapKey(keySequence)&&util.prevKeySequence&&keySequence.equals(util.prevKeySequence)){var prevTime=util.modeKeyPressTime;var delta=currTime-prevTime;if(prevTime>0&&delta>100&&delta<300){keySequence=util.prevKeySequence;keySequence.doubleTap=true;util.prevKeySequence=null;util.sequencing=false;if(cvox.ChromeVox.isChromeOS&&keyEvent.keyCode==cvox.KeyUtil.getStickyKeyCode()){cvox.ChromeVox.searchKeyHeld=false;}
return keySequence;}}
util.prevKeySequence=keySequence;util.modeKeyPressTime=currTime;return keySequence;};cvox.KeyUtil.keyCodeToString=function(keyCode){if(keyCode==17){return'Ctrl';}
if(keyCode==18){return'Alt';}
if(keyCode==16){return'Shift';}
if((keyCode==91)||(keyCode==93)){if(cvox.ChromeVox.isChromeOS){return'Search';}else if(cvox.ChromeVox.isMac){return'Cmd';}else{return'Win';}}
if(keyCode==45){return'Insert';}
if(keyCode>=65&&keyCode<=90){return String.fromCharCode(keyCode);}else if(keyCode>=48&&keyCode<=57){return String.fromCharCode(keyCode);}else{return'#'+keyCode;}};cvox.KeyUtil.modStringToKeyCode=function(keyString){switch(keyString){case'Ctrl':return 17;case'Alt':return 18;case'Shift':return 16;case'Cmd':case'Win':return 91;}
return-1;};cvox.KeyUtil.cvoxModKeyCodes=function(){var modKeyCombo=cvox.ChromeVox.modKeyStr.split(/\+/g);var modKeyCodes=modKeyCombo.map(function(keyString){return cvox.KeyUtil.modStringToKeyCode(keyString);});return modKeyCodes;};cvox.KeyUtil.isSequenceSwitchKeyCode=function(rhKeySeq){for(var i=0;i<cvox.ChromeVox.sequenceSwitchKeyCodes.length;i++){var lhKeySeq=cvox.ChromeVox.sequenceSwitchKeyCodes[i];if(lhKeySeq.equals(rhKeySeq)){return true;}}
return false;};cvox.KeyUtil.getReadableNameForKeyCode=function(keyCode){var msg=Msgs.getMsg.bind(Msgs);var cros=cvox.ChromeVox.isChromeOS;if(keyCode==0){return'Power button';}else if(keyCode==17){return'Control';}else if(keyCode==18){return'Alt';}else if(keyCode==16){return'Shift';}else if(keyCode==9){return'Tab';}else if((keyCode==91)||(keyCode==93)){if(cros){return'Search';}else if(cvox.ChromeVox.isMac){return'Cmd';}else{return'Win';}}else if(keyCode==8){return'Backspace';}else if(keyCode==32){return'Space';}else if(keyCode==35){return'end';}else if(keyCode==36){return'home';}else if(keyCode==37){return'Left arrow';}else if(keyCode==38){return'Up arrow';}else if(keyCode==39){return'Right arrow';}else if(keyCode==40){return'Down arrow';}else if(keyCode==45){return'Insert';}else if(keyCode==13){return'Enter';}else if(keyCode==27){return'Escape';}else if(keyCode==112){return cros?msg('back_key'):'F1';}else if(keyCode==113){return cros?msg('forward_key'):'F2';}else if(keyCode==114){return cros?msg('refresh_key'):'F3';}else if(keyCode==115){return cros?msg('toggle_full_screen_key'):'F4';}else if(keyCode==116){return cros?msg('window_overview_key'):'F5';}else if(keyCode==117){return cros?msg('brightness_down_key'):'F6';}else if(keyCode==118){return cros?msg('brightness_up_key'):'F7';}else if(keyCode==119){return cros?msg('volume_mute_key'):'F8';}else if(keyCode==120){return cros?msg('volume_down_key'):'F9';}else if(keyCode==121){return cros?msg('volume_up_key'):'F10';}else if(keyCode==122){return'F11';}else if(keyCode==123){return'F12';}else if(keyCode==186){return'Semicolon';}else if(keyCode==187){return'Equal sign';}else if(keyCode==188){return'Comma';}else if(keyCode==189){return'Dash';}else if(keyCode==190){return'Period';}else if(keyCode==191){return'Forward slash';}else if(keyCode==192){return'Grave accent';}else if(keyCode==219){return'Open bracket';}else if(keyCode==220){return'Back slash';}else if(keyCode==221){return'Close bracket';}else if(keyCode==222){return'Single quote';}else if(keyCode==115){return'Toggle full screen';}else if(keyCode>=48&&keyCode<=90){return String.fromCharCode(keyCode);}
return'';};cvox.KeyUtil.getStickyKeyCode=function(){var stickyKeyCode=45;if(cvox.ChromeVox.isChromeOS||cvox.ChromeVox.isMac){stickyKeyCode=91;}
return stickyKeyCode;};cvox.KeyUtil.getReadableNameForStr=function(keyStr){return null;};cvox.KeyUtil.keySequenceToString=function(keySequence,opt_readableKeyCode,opt_modifiers){var str='';var numKeys=keySequence.length();for(var index=0;index<numKeys;index++){if(str!=''&&!opt_modifiers){str+='>';}else if(str!=''){str+='+';}
var tempStr='';for(var keyPressed in keySequence.keys){if(!keySequence.keys[keyPressed][index]){continue;}
var modifier='';switch(keyPressed){case'ctrlKey':modifier='Ctrl';break;case'searchKeyHeld':var searchKey=cvox.KeyUtil.getReadableNameForKeyCode(91);modifier=searchKey;break;case'altKey':modifier='Alt';break;case'altGraphKey':modifier='AltGraph';break;case'shiftKey':modifier='Shift';break;case'metaKey':var metaKey=cvox.KeyUtil.getReadableNameForKeyCode(91);modifier=metaKey;break;case'keyCode':var keyCode=keySequence.keys[keyPressed][index];if(!keySequence.isModifierKey(keyCode)&&!opt_modifiers){if(opt_readableKeyCode){tempStr+=cvox.KeyUtil.getReadableNameForKeyCode(keyCode);}else{tempStr+=cvox.KeyUtil.keyCodeToString(keyCode);}}}
if(str.indexOf(modifier)==-1){tempStr+=modifier+'+';}}
str+=tempStr;if(str[str.length-1]=='+'){str=str.slice(0,-1);}}
if(keySequence.cvoxModifier||keySequence.prefixKey){if(str!=''){str='ChromeVox+'+str;}else{str='Cvox';}}else if(keySequence.stickyMode){if(str[str.length-1]=='>'){str=str.slice(0,-1);}
str=str+'+'+str;}
return str;};cvox.KeyUtil.isDoubleTapKey=function(key){var isSet=false;var originalState=key.doubleTap;key.doubleTap=true;for(var i=0,keySeq;keySeq=cvox.KeySequence.doubleTapCache[i];i++){if(keySeq.equals(key)){isSet=true;break;}}
key.doubleTap=originalState;return isSet;};goog.provide('cvox.KeyMap');goog.require('cvox.KeyUtil');goog.require('cvox.PlatformUtil');cvox.KeyMap=function(commandsAndKeySequences){this.bindings_=commandsAndKeySequences;this.commandToKey_={};this.buildCommandToKey_();};cvox.KeyMap.KEYMAP_PATH='chromevox/background/keymaps/';cvox.KeyMap.AVAILABLE_MAP_INFO={'keymap_classic':{'file':'classic_keymap.json'},'keymap_flat':{'file':'flat_keymap.json'},'keymap_next':{'file':'next_keymap.json'},'keymap_experimental':{'file':'experimental.json'}};cvox.KeyMap.DEFAULT_KEYMAP=0;cvox.KeyMap.prototype.length=function(){return this.bindings_.length;};cvox.KeyMap.prototype.keys=function(){return this.bindings_.map(function(binding){return binding.sequence;});};cvox.KeyMap.prototype.bindings=function(){return this.bindings_;};cvox.KeyMap.prototype.toJSON=function(){return JSON.stringify({bindings:this.bindings_});};cvox.KeyMap.prototype.toLocalStorage=function(){localStorage['keyBindings']=this.toJSON();};cvox.KeyMap.prototype.hasBinding=function(command,sequence){if(this.commandToKey_!=null){return this.commandToKey_[command]==sequence;}else{for(var i=0;i<this.bindings_.length;i++){var binding=this.bindings_[i];if(binding.command==command&&binding.sequence==sequence){return true;}}}
return false;};cvox.KeyMap.prototype.hasCommand=function(command){if(this.commandToKey_!=null){return this.commandToKey_[command]!=undefined;}else{for(var i=0;i<this.bindings_.length;i++){var binding=this.bindings_[i];if(binding.command==command){return true;}}}
return false;};cvox.KeyMap.prototype.hasKey=function(key){for(var i=0;i<this.bindings_.length;i++){var binding=this.bindings_[i];if(binding.sequence.equals(key)){return true;}}
return false;};cvox.KeyMap.prototype.commandForKey=function(key){if(key!=null){for(var i=0;i<this.bindings_.length;i++){var binding=this.bindings_[i];if(binding.sequence.equals(key)){return binding.command;}}}
return null;};cvox.KeyMap.prototype.keyForCommand=function(command){if(this.commandToKey_!=null){return[this.commandToKey_[command]];}else{var keySequenceArray=[];for(var i=0;i<this.bindings_.length;i++){var binding=this.bindings_[i];if(binding.command==command){keySequenceArray.push(binding.sequence);}}}
return(keySequenceArray.length>0)?keySequenceArray:[];};cvox.KeyMap.prototype.merge=function(inputMap){var keys=inputMap.keys();var cleanMerge=true;for(var i=0;i<keys.length;++i){var key=keys[i];var command=inputMap.commandForKey(key);if(command=='toggleStickyMode'){continue;}else if(key&&command&&!this.hasKey(key)&&!this.hasCommand(command)){this.bind_(command,key);}else{cleanMerge=false;}}
return cleanMerge;};cvox.KeyMap.prototype.rebind=function(command,newKey){if(this.hasCommand(command)&&!this.hasKey(newKey)){this.bind_(command,newKey);return true;}
return false;};cvox.KeyMap.prototype.bind_=function(command,newKey){var bound=false;for(var i=0;i<this.bindings_.length;i++){var binding=this.bindings_[i];if(binding.command==command){delete binding.sequence;binding.sequence=newKey;if(this.commandToKey_!=null){this.commandToKey_[binding.command]=newKey;}
bound=true;}}
if(!bound){var binding={'command':command,'sequence':newKey};this.bindings_.push(binding);this.commandToKey_[binding.command]=binding.sequence;}};cvox.KeyMap.fromDefaults=function(){return(cvox.KeyMap.fromPath(cvox.KeyMap.KEYMAP_PATH+
cvox.KeyMap.AVAILABLE_MAP_INFO['keymap_classic'].file));};cvox.KeyMap.fromNext=function(){return cvox.KeyMap.fromPath(cvox.KeyMap.KEYMAP_PATH+
cvox.KeyMap.AVAILABLE_MAP_INFO['keymap_next'].file);};cvox.KeyMap.fromJSON=function(json){try{var commandsAndKeySequences=(JSON.parse(json).bindings);commandsAndKeySequences=commandsAndKeySequences.filter(function(value){return value.sequence.platformFilter===undefined||cvox.PlatformUtil.matchesPlatform(value.sequence.platformFilter);});}catch(e){console.error('Failed to load key map from JSON');console.error(e);return null;}
if(typeof(commandsAndKeySequences)!='object'){return null;}
for(var i=0;i<commandsAndKeySequences.length;i++){if(commandsAndKeySequences[i].command==undefined||commandsAndKeySequences[i].sequence==undefined){return null;}else{commandsAndKeySequences[i].sequence=(cvox.KeySequence.deserialize(commandsAndKeySequences[i].sequence));}}
return new cvox.KeyMap(commandsAndKeySequences);};cvox.KeyMap.fromLocalStorage=function(){if(localStorage['keyBindings']){return cvox.KeyMap.fromJSON(localStorage['keyBindings']);}
return null;};cvox.KeyMap.fromPath=function(path){return cvox.KeyMap.fromJSON(cvox.KeyMap.readJSON_(path));};cvox.KeyMap.fromCurrentKeyMap=function(){var map=localStorage['currentKeyMap'];if(map&&cvox.KeyMap.AVAILABLE_MAP_INFO[map]){return(cvox.KeyMap.fromPath(cvox.KeyMap.KEYMAP_PATH+cvox.KeyMap.AVAILABLE_MAP_INFO[map].file));}else{return cvox.KeyMap.fromDefaults();}};cvox.KeyMap.readJSON_=function(path){var url=chrome.extension.getURL(path);if(!url){throw'Invalid path: '+path;}
var xhr=new XMLHttpRequest();xhr.open('GET',url,false);xhr.send();return xhr.responseText;};cvox.KeyMap.prototype.resetModifier=function(){localStorage['cvoxKey']=cvox.ChromeVox.modKeyStr;};cvox.KeyMap.prototype.buildCommandToKey_=function(){for(var i=0;i<this.bindings_.length;i++){var binding=this.bindings_[i];if(this.commandToKey_[binding.command]!=undefined){continue;}
this.commandToKey_[binding.command]=binding.sequence;}};goog.provide('cvox.ChromeVoxKbHandler');goog.require('cvox.ChromeVox');goog.require('cvox.KeyMap');goog.require('cvox.KeySequence');goog.require('cvox.KeyUtil');cvox.ChromeVoxKbHandler={};cvox.ChromeVoxKbHandler.handlerKeyMap;cvox.ChromeVoxKbHandler.commandHandler;cvox.ChromeVoxKbHandler.loadKeyToFunctionsTable=function(keyToFunctionsTable){if(!window.JSON){return;}
cvox.ChromeVoxKbHandler.handlerKeyMap=cvox.KeyMap.fromJSON(keyToFunctionsTable);};cvox.ChromeVoxKbHandler.sortKeyToFunctionsTable_=function(keyToFunctionsTable){var sortingArray=[];for(var keySeqStr in keyToFunctionsTable){sortingArray.push([keySeqStr,keyToFunctionsTable[keySeqStr]]);}
function compareKeyStr(a,b){if(a[0].length<b[0].length){return-1;}else if(b[0].length<a[0].length){return 1;}else{return a[0].localeCompare(b[0]);}};sortingArray.sort(compareKeyStr);return sortingArray;};cvox.ChromeVoxKbHandler.basicKeyDownActionsListener=function(evt){var keySequence=cvox.KeyUtil.keyEventToKeySequence(evt);var functionName;if(cvox.ChromeVoxKbHandler.handlerKeyMap!=undefined){functionName=cvox.ChromeVoxKbHandler.handlerKeyMap.commandForKey(keySequence);}else{functionName=null;}
if(!functionName){return!cvox.KeyUtil.sequencing;}
if(!cvox.ChromeVox.isActive&&functionName!='toggleChromeVox'){return true;}
var returnValue=true;var commandResult=cvox.ChromeVoxKbHandler.commandHandler(functionName);if(commandResult!==undefined){returnValue=commandResult;}else if(keySequence.cvoxModifier){returnValue=false;}
if(cvox.ChromeVox.entireDocumentIsHidden){returnValue=true;}
return returnValue;};goog.provide('cvox.ChromeVoxEventSuspender');cvox.ChromeVoxEventSuspender=function(){};cvox.ChromeVoxEventSuspender.suspendLevel_=0;cvox.ChromeVoxEventSuspender.enterSuspendEvents=function(){cvox.ChromeVoxEventSuspender.suspendLevel_+=1;}
cvox.ChromeVoxEventSuspender.exitSuspendEvents=function(){cvox.ChromeVoxEventSuspender.suspendLevel_-=1;}
cvox.ChromeVoxEventSuspender.areEventsSuspended=function(){return cvox.ChromeVoxEventSuspender.suspendLevel_>0;};cvox.ChromeVoxEventSuspender.withSuspendedEvents=function(f){return function(){cvox.ChromeVoxEventSuspender.enterSuspendEvents();var ret=f.apply(this,arguments);cvox.ChromeVoxEventSuspender.exitSuspendEvents();return ret;};};cvox.ChromeVoxEventSuspender.makeSuspendableHandler=function(handler,ret){return function(){if(cvox.ChromeVoxEventSuspender.areEventsSuspended()){return ret;}
return handler();};};goog.provide('cvox.UserEventDetail');goog.require('cvox.ChromeVox');cvox.UserEventDetail=function(detailObj){this.category='';this.command='';if(cvox.UserEventDetail.JUMP_COMMANDS.indexOf(detailObj.command)!=-1){this.command=detailObj.command;this.category=cvox.UserEventDetail.Category.JUMP;}
this.customCommand='';if(detailObj.customCommand){this.customCommand=detailObj.customCommand;this.category=cvox.UserEventDetail.Category.CUSTOM;}
this.status=cvox.UserEventDetail.Status.PENDING;switch(detailObj.status){case cvox.UserEventDetail.Status.SUCCESS:this.status=cvox.UserEventDetail.Status.SUCCESS;break;case cvox.UserEventDetail.Status.FAILURE:this.status=cvox.UserEventDetail.Status.FAILURE;break;}
this.resultNode=null;if(detailObj.resultNode&&cvox.DomUtil.isAttachedToDocument(detailObj.resultNode)){this.resultNode=detailObj.resultNode;}};cvox.UserEventDetail.Category={JUMP:'ATJumpEvent',CUSTOM:'ATCustomEvent'};cvox.UserEventDetail.Status={PENDING:'PENDING',SUCCESS:'SUCCESS',FAILURE:'FAILURE'};cvox.UserEventDetail.JUMP_COMMANDS=['nextCheckbox','previousCheckbox','nextRadio','previousRadio','nextSlider','previousSlider','nextGraphic','previousGraphic','nextButton','previousButton','nextComboBox','previousComboBox','nextEditText','previousEditText','nextHeading','previousHeading','nextHeading1','previousHeading1','nextHeading2','previousHeading2','nextHeading3','previousHeading3','nextHeading4','previousHeading4','nextHeading5','previousHeading5','nextHeading6','previousHeading6','nextLink','previousLink','nextMath','previousMath','nextTable','previousTable','nextList','previousList','nextListItem','previousListItem','nextFormField','previousFormField','nextLandmark','previousLandmark','nextSection','previousSection','nextControl','previousControl'];cvox.UserEventDetail.prototype.createEventObject=function(){var evt=document.createEvent('CustomEvent');evt.initCustomEvent(this.category,true,true,this);return evt;};goog.provide('cvox.ExtensionBridge');goog.require('cvox.ChromeVoxJSON');cvox.ExtensionBridge=function(){};cvox.ExtensionBridge.init=function(){var self=cvox.ExtensionBridge;self.messageListeners=[];self.disconnectListeners=[];if(/^chrome-extension:\/\/.*background\.html$/.test(window.location.href)){self.context=self.BACKGROUND;self.initBackground();return;}
if(chrome&&chrome.extension){self.context=self.CONTENT_SCRIPT;self.initContentScript();}};cvox.ExtensionBridge.BACKGROUND=0;cvox.ExtensionBridge.CONTENT_SCRIPT=1;cvox.ExtensionBridge.PORT_NAME='cvox.ExtensionBridge.Port';cvox.ExtensionBridge.PING_MSG='cvox.ExtensionBridge.Ping';cvox.ExtensionBridge.PONG_MSG='cvox.ExtensionBridge.Pong';cvox.ExtensionBridge.send=function(message){var self=cvox.ExtensionBridge;switch(self.context){case self.BACKGROUND:self.sendBackgroundToContentScript(message);break;case self.CONTENT_SCRIPT:self.sendContentScriptToBackground(message);break;}};cvox.ExtensionBridge.addMessageListener=function(listener){cvox.ExtensionBridge.messageListeners.push(listener);};cvox.ExtensionBridge.addDisconnectListener=function(listener){cvox.ExtensionBridge.disconnectListeners.push(listener);};cvox.ExtensionBridge.removeMessageListeners=function(){cvox.ExtensionBridge.messageListeners.length=0;};cvox.ExtensionBridge.uniqueId=function(){return cvox.ExtensionBridge.id_;};cvox.ExtensionBridge.initBackground=function(){var self=cvox.ExtensionBridge;self.portCache_=[];self.nextPongId_=1;self.id_=0;var onConnectHandler=function(port){if(port.name!=self.PORT_NAME){return;}
self.portCache_.push(port);port.onMessage.addListener(function(message){if(message[cvox.ExtensionBridge.PING_MSG]){var pongMessage={};pongMessage[cvox.ExtensionBridge.PONG_MSG]=self.nextPongId_++;port.postMessage(pongMessage);return;}
for(var i=0;i<self.messageListeners.length;i++){self.messageListeners[i](message,port);}});port.onDisconnect.addListener(function(message){for(var i=0;i<self.portCache_.length;i++){if(self.portCache_[i]==port){self.portCache_.splice(i,1);break;}}});};chrome.extension.onConnect.addListener(onConnectHandler);};cvox.ExtensionBridge.initContentScript=function(){var self=cvox.ExtensionBridge;self.connected=false;self.pingAttempts=0;self.queuedMessages=[];self.id_=-1;var onMessageHandler=function(request,sender,sendResponse){if(request&&request['srcFile']){return;}
if(request[cvox.ExtensionBridge.PONG_MSG]){self.gotPongFromBackgroundPage(request[cvox.ExtensionBridge.PONG_MSG]);}else{for(var i=0;i<self.messageListeners.length;i++){self.messageListeners[i](request,cvox.ExtensionBridge.backgroundPort);}}
sendResponse({});};chrome.extension.onMessage.addListener(onMessageHandler);self.setupBackgroundPort();self.tryToPingBackgroundPage();};cvox.ExtensionBridge.setupBackgroundPort=function(){var self=cvox.ExtensionBridge;self.backgroundPort=chrome.extension.connect({name:self.PORT_NAME});if(!self.backgroundPort){return;}
self.backgroundPort.onMessage.addListener(function(message){if(message[cvox.ExtensionBridge.PONG_MSG]){self.gotPongFromBackgroundPage(message[cvox.ExtensionBridge.PONG_MSG]);}else{for(var i=0;i<self.messageListeners.length;i++){self.messageListeners[i](message,self.backgroundPort);}}});self.backgroundPort.onDisconnect.addListener(function(event){if(!self.connected){self.backgroundPort=null;return;}
for(var i=0;i<self.disconnectListeners.length;i++){self.disconnectListeners[i]();}});};cvox.ExtensionBridge.tryToPingBackgroundPage=function(){var self=cvox.ExtensionBridge;if(self.connected){return;}
self.pingAttempts++;if(self.pingAttempts>5){for(var i=0;i<self.disconnectListeners.length;i++){self.disconnectListeners[i]();}
return;}
var msg={};msg[cvox.ExtensionBridge.PING_MSG]=1;if(!self.backgroundPort){self.setupBackgroundPort();}
if(self.backgroundPort){self.backgroundPort.postMessage(msg);}
window.setTimeout(cvox.ExtensionBridge.tryToPingBackgroundPage,500);};cvox.ExtensionBridge.gotPongFromBackgroundPage=function(pongId){var self=cvox.ExtensionBridge;self.connected=true;self.id_=pongId;while(self.queuedMessages.length>0){self.sendContentScriptToBackground(self.queuedMessages.shift());}};cvox.ExtensionBridge.sendContentScriptToBackground=function(message){var self=cvox.ExtensionBridge;if(!self.connected){self.queuedMessages.push(message);return;}
if(cvox.ExtensionBridge.backgroundPort){cvox.ExtensionBridge.backgroundPort.postMessage(message);}else{chrome.extension.sendMessage(message);}};cvox.ExtensionBridge.sendBackgroundToContentScript=function(message){cvox.ExtensionBridge.portCache_.forEach(function(port){port.postMessage(message);});};cvox.ExtensionBridge.init();goog.provide('cvox.BrailleOverlayWidget');goog.require('cvox.ExtensionBridge');cvox.BrailleOverlayWidget=function(){this.active_=false;this.containerNode_=null;this.contentNode_=null;this.brailleNode_=null;};goog.addSingletonGetter(cvox.BrailleOverlayWidget);cvox.BrailleOverlayWidget.prototype.init=function(){cvox.ExtensionBridge.addMessageListener(goog.bind(this.onMessage_,this));};cvox.BrailleOverlayWidget.prototype.setActive=function(value){this.active_=value;if(!value){this.hide_();}};cvox.BrailleOverlayWidget.prototype.isActive=function(){return this.active_;};cvox.BrailleOverlayWidget.prototype.show_=function(){var containerNode=this.createContainerNode_();this.containerNode_=containerNode;var overlayNode=this.createOverlayNode_();containerNode.appendChild(overlayNode);this.contentNode_=document.createElement('div');this.brailleNode_=document.createElement('div');overlayNode.appendChild(this.contentNode_);overlayNode.appendChild(this.brailleNode_);document.body.appendChild(containerNode);window.setTimeout(function(){containerNode.style['opacity']='1.0';},0);};cvox.BrailleOverlayWidget.prototype.hide_=function(){if(this.containerNode_){var containerNode=this.containerNode_;containerNode.style.opacity='0.0';window.setTimeout(function(){document.body.removeChild(containerNode);},1000);this.containerNode_=null;this.contentNode_=null;this.brailleNode_=null;}};cvox.BrailleOverlayWidget.prototype.setContent_=function(text,brailleChars){if(!this.contentNode_){this.show_();}
this.contentNode_.textContent=text;this.brailleNode_.textContent=brailleChars;};cvox.BrailleOverlayWidget.prototype.createContainerNode_=function(){var containerNode=document.createElement('div');containerNode.id='cvox-braille-overlay';containerNode.style['position']='fixed';containerNode.style['top']='50%';containerNode.style['left']='50%';containerNode.style['-webkit-transition']='all 0.3s ease-in';containerNode.style['opacity']='0.0';containerNode.style['z-index']='2147483647';containerNode.setAttribute('aria-hidden','true');return containerNode;};cvox.BrailleOverlayWidget.prototype.createOverlayNode_=function(){var overlayNode=document.createElement('div');overlayNode.style['position']='fixed';overlayNode.style['left']='40px';overlayNode.style['bottom']='20px';overlayNode.style['line-height']='1.2em';overlayNode.style['font-size']='20px';overlayNode.style['font-family']='monospace';overlayNode.style['padding']='30px';overlayNode.style['min-width']='150px';overlayNode.style['color']='#fff';overlayNode.style['background-color']='rgba(0, 0, 0, 0.7)';overlayNode.style['border-radius']='10px';return overlayNode;};cvox.BrailleOverlayWidget.prototype.onMessage_=function(msg){if(msg['message']=='BRAILLE_CAPTION'){this.setContent_(msg['text'],msg['brailleChars']);}};goog.provide('cvox.FocusUtil');cvox.FocusUtil=function(){};cvox.FocusUtil.INPUT_TYPE_ACCEPTS_SELECTION_TABLE={'hidden':false,'text':true,'search':true,'tel':true,'url':true,'email':true,'password':true,'datetime':false,'date':false,'month':false,'week':false,'time':false,'datetime-local':false,'number':false,'range':false,'color':false,'checkbox':false,'radio':false,'file':false,'submit':false,'image':false,'reset':false,'button':false};cvox.FocusUtil.isFocusInTextInputField=function(){var activeElement=document.activeElement;if(!activeElement){return false;}
if(activeElement.isContentEditable){return true;}
if(activeElement.getAttribute('role')=='textbox'){return true;}
if(activeElement.getAttribute('readOnly')=='true'){return false;}
if(activeElement.tagName==='TEXTAREA'||activeElement.tagName==='SELECT'){return true;}
if(activeElement.tagName==='INPUT'){if(!activeElement.hasAttribute('type')){return true;}else{var activeType=activeElement.getAttribute('type').toLowerCase();return cvox.FocusUtil.INPUT_TYPE_ACCEPTS_SELECTION_TABLE[activeType];}}
return false;};goog.provide('cvox.ConsoleTts');goog.require('cvox.AbstractTts');goog.require('cvox.TtsInterface');cvox.ConsoleTts=function(){this.enabled_=false;};goog.addSingletonGetter(cvox.ConsoleTts);cvox.ConsoleTts.prototype.speak=function(textString,queueMode,properties){if(this.enabled_&&window['console']){var logStr='Speak';if(queueMode==cvox.QueueMode.FLUSH){logStr+=' (I)';}else if(queueMode==cvox.QueueMode.CATEGORY_FLUSH){logStr+=' (C)';}else{logStr+=' (Q)';}
if(properties&&properties.category){logStr+=' category='+properties.category;}
logStr+=' "'+textString+'"';console.log(logStr);}
return this;};cvox.ConsoleTts.prototype.isSpeaking=function(){return false;};cvox.ConsoleTts.prototype.stop=function(){if(this.enabled_){console.log('Stop');}};cvox.ConsoleTts.prototype.addCapturingEventListener=function(listener){};cvox.ConsoleTts.prototype.increaseOrDecreaseProperty=function(){};cvox.ConsoleTts.prototype.propertyToPercentage=function(){};cvox.ConsoleTts.prototype.setEnabled=function(enabled){this.enabled_=enabled;};cvox.ConsoleTts.prototype.getDefaultProperty=function(property){};goog.provide('goog.object');goog.object.forEach=function(obj,f,opt_obj){for(var key in obj){f.call(opt_obj,obj[key],key,obj);}};goog.object.filter=function(obj,f,opt_obj){var res={};for(var key in obj){if(f.call(opt_obj,obj[key],key,obj)){res[key]=obj[key];}}
return res;};goog.object.map=function(obj,f,opt_obj){var res={};for(var key in obj){res[key]=f.call(opt_obj,obj[key],key,obj);}
return res;};goog.object.some=function(obj,f,opt_obj){for(var key in obj){if(f.call(opt_obj,obj[key],key,obj)){return true;}}
return false;};goog.object.every=function(obj,f,opt_obj){for(var key in obj){if(!f.call(opt_obj,obj[key],key,obj)){return false;}}
return true;};goog.object.getCount=function(obj){var rv=0;for(var key in obj){rv++;}
return rv;};goog.object.getAnyKey=function(obj){for(var key in obj){return key;}};goog.object.getAnyValue=function(obj){for(var key in obj){return obj[key];}};goog.object.contains=function(obj,val){return goog.object.containsValue(obj,val);};goog.object.getValues=function(obj){var res=[];var i=0;for(var key in obj){res[i++]=obj[key];}
return res;};goog.object.getKeys=function(obj){var res=[];var i=0;for(var key in obj){res[i++]=key;}
return res;};goog.object.getValueByKeys=function(obj,var_args){var isArrayLike=goog.isArrayLike(var_args);var keys=isArrayLike?var_args:arguments;for(var i=isArrayLike?0:1;i<keys.length;i++){obj=obj[keys[i]];if(!goog.isDef(obj)){break;}}
return obj;};goog.object.containsKey=function(obj,key){return key in obj;};goog.object.containsValue=function(obj,val){for(var key in obj){if(obj[key]==val){return true;}}
return false;};goog.object.findKey=function(obj,f,opt_this){for(var key in obj){if(f.call(opt_this,obj[key],key,obj)){return key;}}
return undefined;};goog.object.findValue=function(obj,f,opt_this){var key=goog.object.findKey(obj,f,opt_this);return key&&obj[key];};goog.object.isEmpty=function(obj){for(var key in obj){return false;}
return true;};goog.object.clear=function(obj){for(var i in obj){delete obj[i];}};goog.object.remove=function(obj,key){var rv;if((rv=key in obj)){delete obj[key];}
return rv;};goog.object.add=function(obj,key,val){if(key in obj){throw Error('The object already contains the key "'+key+'"');}
goog.object.set(obj,key,val);};goog.object.get=function(obj,key,opt_val){if(key in obj){return obj[key];}
return opt_val;};goog.object.set=function(obj,key,value){obj[key]=value;};goog.object.setIfUndefined=function(obj,key,value){return key in obj?obj[key]:(obj[key]=value);};goog.object.clone=function(obj){var res={};for(var key in obj){res[key]=obj[key];}
return res;};goog.object.unsafeClone=function(obj){var type=goog.typeOf(obj);if(type=='object'||type=='array'){if(obj.clone){return obj.clone();}
var clone=type=='array'?[]:{};for(var key in obj){clone[key]=goog.object.unsafeClone(obj[key]);}
return clone;}
return obj;};goog.object.transpose=function(obj){var transposed={};for(var key in obj){transposed[obj[key]]=key;}
return transposed;};goog.object.PROTOTYPE_FIELDS_=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'];goog.object.extend=function(target,var_args){var key,source;for(var i=1;i<arguments.length;i++){source=arguments[i];for(key in source){target[key]=source[key];}
for(var j=0;j<goog.object.PROTOTYPE_FIELDS_.length;j++){key=goog.object.PROTOTYPE_FIELDS_[j];if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}};goog.object.create=function(var_args){var argLength=arguments.length;if(argLength==1&&goog.isArray(arguments[0])){return goog.object.create.apply(null,arguments[0]);}
if(argLength%2){throw Error('Uneven number of arguments');}
var rv={};for(var i=0;i<argLength;i+=2){rv[arguments[i]]=arguments[i+1];}
return rv;};goog.object.createSet=function(var_args){var argLength=arguments.length;if(argLength==1&&goog.isArray(arguments[0])){return goog.object.createSet.apply(null,arguments[0]);}
var rv={};for(var i=0;i<argLength;i++){rv[arguments[i]]=true;}
return rv;};goog.object.createImmutableView=function(obj){var result=obj;if(Object.isFrozen&&!Object.isFrozen(obj)){result=Object.create(obj);Object.freeze(result);}
return result;};goog.object.isImmutableView=function(obj){return!!Object.isFrozen&&Object.isFrozen(obj);};goog.provide('cvox.ScriptInstaller');goog.require('cvox.DomUtil');cvox.ScriptInstaller.blacklistPattern=/chrome:\/\/|chrome-extension:\/\//;cvox.ScriptInstaller.installScript=function(srcs,uid,opt_onload,opt_chromevoxScriptBase){if(cvox.ScriptInstaller.blacklistPattern.test(document.URL)){return false;}
if(document.querySelector('script['+uid+']')){return false;}
if(!srcs||srcs.length==0){return false;}
cvox.ScriptInstaller.installScriptHelper_(srcs,uid,opt_onload,opt_chromevoxScriptBase);return true;};cvox.ScriptInstaller.installScriptHelper_=function(srcs,uid,opt_onload,opt_chromevoxScriptBase){function next(){if(srcs.length>0){cvox.ScriptInstaller.installScriptHelper_(srcs,uid,opt_onload,opt_chromevoxScriptBase);}else if(opt_onload){opt_onload();}}
var scriptSrc=srcs.shift();if(!scriptSrc){next();return;}
var xhr=new XMLHttpRequest();var url=scriptSrc+'?'+new Date().getTime();xhr.onreadystatechange=function(){if(xhr.readyState==4){var scriptText=xhr.responseText;scriptText+='\n//# sourceURL='+scriptSrc+'\n';var apiScript=document.createElement('script');apiScript.type='text/javascript';apiScript.setAttribute(uid,'1');apiScript.textContent=scriptText;if(opt_chromevoxScriptBase){apiScript.setAttribute('chromevoxScriptBase',opt_chromevoxScriptBase);}
cvox.DomUtil.addNodeToHead(apiScript);next();}};try{xhr.open('GET',url,true);xhr.send(null);}catch(exception){console.log('Warning: ChromeVox external script loading for '+
document.location+' stopped after failing to install '+scriptSrc);next();}};if(typeof(goog)!='undefined'&&goog.provide){goog.provide('cvox.ApiUtil');}
if(!window['cvox']){window['cvox']={};}
cvox.ApiUtils=function(){};cvox.ApiUtils.nextCvoxId_=1;cvox.ApiUtils.makeNodeReference=function(targetNode){if(targetNode.id&&document.getElementById(targetNode.id)==targetNode){return{'id':targetNode.id};}else if(targetNode instanceof HTMLElement){var cvoxid=cvox.ApiUtils.nextCvoxId_;targetNode.setAttribute('cvoxid',cvoxid);cvox.ApiUtils.nextCvoxId_=(cvox.ApiUtils.nextCvoxId_+1)%100;return{'cvoxid':cvoxid};}else if(targetNode.parentElement){var parent=targetNode.parentElement;var childIndex=-1;for(var i=0;i<parent.childNodes.length;i++){if(parent.childNodes[i]==targetNode){childIndex=i;break;}}
if(childIndex>=0){var cvoxid=cvox.ApiUtils.nextCvoxId_;parent.setAttribute('cvoxid',cvoxid);cvox.ApiUtils.nextCvoxId_=(cvox.ApiUtils.nextCvoxId_+1)%100;return{'cvoxid':cvoxid,'childIndex':childIndex};}}
throw'Cannot reference node: '+targetNode;};cvox.ApiUtils.getNodeFromRef=function(nodeRef){if(nodeRef['id']){return document.getElementById(nodeRef['id']);}else if(nodeRef['cvoxid']){var selector='*[cvoxid="'+nodeRef['cvoxid']+'"]';var element=document.querySelector(selector);if(element&&element.removeAttribute){element.removeAttribute('cvoxid');}
if(nodeRef['childIndex']!=null){return element.childNodes[nodeRef['childIndex']];}else{return element;}}
throw'Bad node reference: '+cvox.ChromeVoxJSON.stringify(nodeRef);};goog.provide('cvox.BuildInfo');cvox.BuildInfo.build='development build';goog.provide('cvox.ApiImplementation');goog.provide('cvox.ApiImplementation.Math');goog.require('cvox.ApiUtil');goog.require('cvox.AriaUtil');goog.require('cvox.BuildInfo');goog.require('cvox.ChromeVox');goog.require('cvox.ChromeVoxJSON');goog.require('cvox.DomUtil');goog.require('cvox.ScriptInstaller');cvox.ApiImplementation=function(){};cvox.ApiImplementation.siteSpecificScriptLoader;cvox.ApiImplementation.siteSpecificScriptBase;cvox.ApiImplementation.init=function(opt_onload){window.addEventListener('message',cvox.ApiImplementation.portSetup,true);var scripts=new Array();scripts.push(cvox.ChromeVox.host.getFileSrc('chromevox/injected/api_util.js'));scripts.push(cvox.ChromeVox.host.getApiSrc());scripts.push(cvox.ApiImplementation.siteSpecificScriptLoader);var didInstall=cvox.ScriptInstaller.installScript(scripts,'cvoxapi',opt_onload,cvox.ApiImplementation.siteSpecificScriptBase);if(!didInstall){window.location.href='javascript:cvox.Api.internalEnable();';}};cvox.ApiImplementation.portSetup=function(event){if(event.data=='cvox.PortSetup'){cvox.ApiImplementation.port=event.ports[0];cvox.ApiImplementation.port.onmessage=function(event){cvox.ApiImplementation.dispatchApiMessage(cvox.ChromeVoxJSON.parse(event.data));};event.stopPropagation();return false;}
return true;};cvox.ApiImplementation.dispatchApiMessage=function(message){var method;switch(message['cmd']){case'speak':method=cvox.ApiImplementation.speak;break;case'speakNodeRef':method=cvox.ApiImplementation.speakNodeRef;break;case'stop':method=cvox.ApiImplementation.stop;break;case'playEarcon':method=cvox.ApiImplementation.playEarcon;break;case'syncToNodeRef':method=cvox.ApiImplementation.syncToNodeRef;break;case'clickNodeRef':method=cvox.ApiImplementation.clickNodeRef;break;case'getBuild':method=cvox.ApiImplementation.getBuild;break;case'getVersion':method=cvox.ApiImplementation.getVersion;break;case'getCurrentNode':method=cvox.ApiImplementation.getCurrentNode;break;case'getCvoxModKeys':method=cvox.ApiImplementation.getCvoxModKeys;break;case'isKeyShortcut':method=cvox.ApiImplementation.isKeyShortcut;break;case'setKeyEcho':method=cvox.ApiImplementation.setKeyEcho;break;case'Math.defineRule':method=cvox.ApiImplementation.Math.defineRule;break;break;}
if(!method){throw'Unknown API call: '+message['cmd'];}
method.apply(cvox.ApiImplementation,message['args']);};function setupEndCallback_(properties,callbackId){var endCallback=function(){cvox.ApiImplementation.port.postMessage(cvox.ChromeVoxJSON.stringify({'id':callbackId}));};if(properties){properties['endCallback']=endCallback;}}
cvox.ApiImplementation.speak=function(callbackId,textString,queueMode,properties){if(cvox.ChromeVox.isActive){if(!properties){properties={};}
setupEndCallback_(properties,callbackId);cvox.ChromeVox.tts.speak(textString,(queueMode),properties);}};cvox.ApiImplementation.speakNode=function(node,queueMode,properties){if(cvox.ChromeVox.isActive){cvox.ChromeVox.tts.speak(cvox.DomUtil.getName(node),(queueMode),properties);}};cvox.ApiImplementation.speakNodeRef=function(callbackId,nodeRef,queueMode,properties){var node=cvox.ApiUtils.getNodeFromRef(nodeRef);if(!properties){properties={};}
setupEndCallback_(properties,callbackId);cvox.ApiImplementation.speakNode(node,queueMode,properties);};cvox.ApiImplementation.stop=function(){if(cvox.ChromeVox.isActive){cvox.ChromeVox.tts.stop();}};cvox.ApiImplementation.playEarcon=function(earcon){if(cvox.ChromeVox.isActive&&cvox.Earcon[earcon]){cvox.ChromeVox.earcons.playEarcon(cvox.Earcon[earcon]);}};cvox.ApiImplementation.syncToNodeRef=function(nodeRef,speakNode){var node=cvox.ApiUtils.getNodeFromRef(nodeRef);cvox.ApiImplementation.syncToNode(node,speakNode);};cvox.ApiImplementation.syncToNode=function(targetNode,opt_speakNode,opt_queueMode){if(!cvox.ChromeVox.isActive){return;}
if(opt_queueMode==undefined){opt_queueMode=cvox.QueueMode.CATEGORY_FLUSH;}
cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(targetNode,true);cvox.ChromeVox.navigationManager.updateIndicator();if(opt_speakNode==undefined){opt_speakNode=false;}
if(cvox.AriaUtil.isHiddenRecursive(targetNode)){opt_speakNode=false;}
if(opt_speakNode){cvox.ChromeVox.navigationManager.speakDescriptionArray(cvox.ApiImplementation.getDesc_(targetNode),(opt_queueMode),null,null,cvox.TtsCategory.NAV);}
cvox.ChromeVox.braille.write(cvox.ChromeVox.navigationManager.getBraille());cvox.ChromeVox.navigationManager.updatePosition(targetNode);};cvox.ApiImplementation.getCurrentNode=function(callbackId){var currentNode=cvox.ChromeVox.navigationManager.getCurrentNode();cvox.ApiImplementation.port.postMessage(cvox.ChromeVoxJSON.stringify({'id':callbackId,'currentNode':cvox.ApiUtils.makeNodeReference(currentNode)}));};cvox.ApiImplementation.getDesc_=function(node){if(!node.hasAttribute('cvoxnodedesc')){return cvox.ChromeVox.navigationManager.getDescription();}
var preDesc=cvox.ChromeVoxJSON.parse(node.getAttribute('cvoxnodedesc'));var currentDesc=new Array();for(var i=0;i<preDesc.length;++i){var inDesc=preDesc[i];currentDesc.push(new cvox.NavDescription({context:inDesc.context,text:inDesc.text,userValue:inDesc.userValue,annotation:inDesc.annotation}));}
return currentDesc;};cvox.ApiImplementation.clickNodeRef=function(nodeRef,shiftKey){cvox.DomUtil.clickElem(cvox.ApiUtils.getNodeFromRef(nodeRef),shiftKey,false);};cvox.ApiImplementation.getBuild=function(callbackId){cvox.ApiImplementation.port.postMessage(cvox.ChromeVoxJSON.stringify({'id':callbackId,'build':cvox.BuildInfo.build}));};cvox.ApiImplementation.getVersion=function(callbackId){var version=cvox.ChromeVox.version;if(version==null){window.setTimeout(function(){cvox.ApiImplementation.getVersion(callbackId);},1000);return;}
cvox.ApiImplementation.port.postMessage(cvox.ChromeVoxJSON.stringify({'id':callbackId,'version':version}));};cvox.ApiImplementation.getCvoxModKeys=function(callbackId){cvox.ApiImplementation.port.postMessage(cvox.ChromeVoxJSON.stringify({'id':callbackId,'keyCodes':cvox.KeyUtil.cvoxModKeyCodes()}));};cvox.ApiImplementation.isKeyShortcut=function(callbackId,keyEvent){var keySeq=cvox.KeyUtil.keyEventToKeySequence(keyEvent);cvox.ApiImplementation.port.postMessage(cvox.ChromeVoxJSON.stringify({'id':callbackId,'isHandled':cvox.ChromeVoxKbHandler.handlerKeyMap.hasKey(keySeq)}));};cvox.ApiImplementation.setKeyEcho=function(keyEcho){var msg=cvox.ChromeVox.keyEcho;msg[document.location.href]=keyEcho;cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'keyEcho','value':JSON.stringify(msg)});};cvox.ApiImplementation.Math=function(){};cvox.ApiImplementation.Math.defineRule=function(name,dynamic,action,prec,constraints){var mathStore=cvox.MathmlStore.getInstance();var constraintList=Array.prototype.slice.call(arguments,4);var args=[name,dynamic,action,prec].concat(constraintList);mathStore.defineRule.apply(mathStore,args);};goog.provide('cvox.Focuser');goog.require('cvox.ChromeVoxEventSuspender');goog.require('cvox.DomUtil');cvox.Focuser.setFocus=function(targetNode,opt_focusDescendants){var sel=window.getSelection();var range;if(sel.rangeCount>0){range=sel.getRangeAt(0);}
if(document.activeElement&&!cvox.DomUtil.isDescendantOfNode(targetNode,document.activeElement)){document.activeElement.blur();}
if(targetNode&&(targetNode.constructor==HTMLVideoElement)){if(!cvox.DomUtil.isFocusable(targetNode)){targetNode.setAttribute('tabIndex',0);}}
if(opt_focusDescendants&&!cvox.DomUtil.isFocusable(targetNode)){var focusableDescendant=cvox.DomUtil.findFocusableDescendant(targetNode);if(focusableDescendant){targetNode=focusableDescendant;}}else{while(targetNode&&!cvox.DomUtil.isFocusable(targetNode)){targetNode=targetNode.parentNode;}}
if(cvox.DomUtil.isFocusable(targetNode)){if(targetNode.tagName!='IFRAME'){if(cvox.ChromeVoxEventSuspender.areEventsSuspended()){if(cvox.Focuser.shouldEnterSuspendEvents_(targetNode)){cvox.ChromeVoxEventSuspender.enterSuspendEvents();}
window.setTimeout(function(){targetNode.focus();cvox.ChromeVoxEventSuspender.exitSuspendEvents();},0);}
else{window.setTimeout(function(){targetNode.focus();},0);}}}else if(document.activeElement&&document.activeElement.tagName!='BODY'){document.activeElement.blur();}
if(cvox.DomUtil.isInputTypeText(targetNode)){targetNode.select();}else if(range){sel.removeAllRanges();sel.addRange(range);}};cvox.Focuser.shouldEnterSuspendEvents_=function(targetNode){if(targetNode.constructor&&targetNode.constructor==HTMLVideoElement){return false;}
if(targetNode.hasAttribute){switch(targetNode.getAttribute('type')){case'time':case'date':case'week':case'month':return false;}}
return true;};goog.provide('cvox.ExtraCellsSpan');goog.provide('cvox.ValueSelectionSpan');goog.provide('cvox.ValueSpan');goog.require('Spannable');cvox.ValueSpan=function(offset){this.offset=offset;};cvox.ValueSpan.fromJson=function(obj){return new cvox.ValueSpan(obj.offset);};cvox.ValueSpan.prototype.toJson=function(){return this;};Spannable.registerSerializableSpan(cvox.ValueSpan,'cvox.ValueSpan',cvox.ValueSpan.fromJson,cvox.ValueSpan.prototype.toJson);cvox.ValueSelectionSpan=function(){};Spannable.registerStatelessSerializableSpan(cvox.ValueSelectionSpan,'cvox.ValueSelectionSpan');cvox.ExtraCellsSpan=function(){this.cells=new Uint8Array(0).buffer;};goog.provide('cvox.EditableTextAreaShadow');cvox.EditableTextAreaShadow=function(){this.shadowElement_=document.createElement('div');this.lines_={};this.characterToLineMap_=[];};cvox.EditableTextAreaShadow.prototype.update=function(element){document.body.appendChild(this.shadowElement_);while(this.shadowElement_.childNodes.length){this.shadowElement_.removeChild(this.shadowElement_.childNodes[0]);}
this.shadowElement_.style.cssText=window.getComputedStyle(element,null).cssText;this.shadowElement_.style.position='absolute';this.shadowElement_.style.top='-9999';this.shadowElement_.style.left='-9999';this.shadowElement_.setAttribute('aria-hidden','true');var text=element.value;var textNode=document.createTextNode(text+'.');this.shadowElement_.appendChild(textNode);var SKIP=8;var lines={0:{startIndex:0,endIndex:0}};var range=document.createRange();var offset=0;var lastGoodOffset=0;var lineIndex=0;var lastBottom=null;var nearNewline=false;var rect;while(offset<=text.length){range.setStart(textNode,offset);if(offset+SKIP>text.length||text.substr(offset,SKIP).indexOf('\n')>=0){nearNewline=true;}
if(nearNewline){offset++;range.setEnd(textNode,offset);rect=range.getBoundingClientRect();}else{range.setEnd(textNode,offset+SKIP);rect=range.getBoundingClientRect();if(rect.bottom==lastBottom){offset+=SKIP;}else{if(rect&&lastBottom!==null){nearNewline=true;}
offset++;range.setEnd(textNode,offset);rect=range.getBoundingClientRect();}}
if(offset>0&&text[offset-1]=='\n'){lines[lineIndex].endIndex=offset-1;lineIndex++;lines[lineIndex]={startIndex:offset,endIndex:offset};lastBottom=null;nearNewline=false;lastGoodOffset=offset;}else if(rect&&(lastBottom===null)){lastBottom=rect.bottom;}else if(rect&&rect.bottom!=lastBottom){lines[lineIndex].endIndex=lastGoodOffset;lineIndex++;lines[lineIndex]={startIndex:lastGoodOffset,endIndex:lastGoodOffset};lastBottom=rect?rect.bottom:null;nearNewline=false;}
if(rect){lastGoodOffset=offset;}}
lines[lineIndex].endIndex=text.length;var characterToLineMap=[];for(var i=0;i<=lineIndex;i++){for(var j=lines[i].startIndex;j<=lines[i].endIndex;j++){characterToLineMap[j]=i;}}
this.characterToLineMap_=characterToLineMap;this.lines_=lines;document.body.removeChild(this.shadowElement_);};cvox.EditableTextAreaShadow.prototype.getLineIndex=function(index){return this.characterToLineMap_[index];};cvox.EditableTextAreaShadow.prototype.getLineStart=function(index){return this.lines_[index].startIndex;};cvox.EditableTextAreaShadow.prototype.getLineEnd=function(index){return this.lines_[index].endIndex;};goog.provide('cvox.BrailleUtil');goog.require('Spannable');goog.require('cvox.ChromeVox');goog.require('cvox.DomUtil');goog.require('cvox.EditableTextAreaShadow');goog.require('cvox.Focuser');goog.require('cvox.NavBraille');goog.require('cvox.NodeStateUtil');goog.require('cvox.ValueSelectionSpan');goog.require('cvox.ValueSpan');cvox.BrailleUtil.ITEM_SEPARATOR=' ';cvox.BrailleUtil.CONTAINER=['tag_h1_brl','tag_h2_brl','tag_h3_brl','tag_h4_brl','tag_h5_brl','tag_h6_brl'];cvox.BrailleUtil.TEMPLATE={'base':'c n v r s','role_alert':'r: n','role_button':'n r s','role_checkbox':'n r s','role_menuitemcheckbox':'n r s','role_menuitemradio':'n r s','role_radio':'n r s','role_textbox':'n: v r s','input_type_email':'n: v r s','input_type_number':'n: v r s','input_type_password':'n: v r s','input_type_search':'n: v r s','input_type_text':'n: v r s','input_type_url':'n: v r s','tag_textarea':'n: v r s'};cvox.BrailleUtil.getName=function(node){if(!node){return'';}
return cvox.DomUtil.getName(node).trim();};cvox.BrailleUtil.getRoleMsg=function(node){if(!node){return'';}
var roleMsg=cvox.DomUtil.getRoleMsg(node,cvox.VERBOSITY_VERBOSE);if(roleMsg){roleMsg=cvox.DomUtil.collapseWhitespace(roleMsg);}
if(roleMsg&&(roleMsg.length>0)){if(Msgs.getMsg(roleMsg+'_brl')){roleMsg+='_brl';}}
return roleMsg;};cvox.BrailleUtil.expandStateMsgs_=function(stateMsgs){stateMsgs.forEach(function(state){var dummySubs=['dummy','dummy','dummy'];if(Msgs.getMsg(state[0]+'_brl',dummySubs)){state[0]+='_brl';}});return cvox.NodeStateUtil.expand(stateMsgs);};cvox.BrailleUtil.getContainer=function(prev,node){if(!prev||!node){return'';}
var ancestors=cvox.DomUtil.getUniqueAncestors(prev,node);for(var i=0,container;container=ancestors[i];i++){var msg=cvox.BrailleUtil.getRoleMsg(container);if(msg&&cvox.BrailleUtil.CONTAINER.indexOf(msg)!=-1){return Msgs.getMsg(msg);}}
return'';};cvox.BrailleUtil.getValue=function(node){if(!node){return new Spannable();}
var valueSpan=new cvox.ValueSpan(0);if(cvox.DomUtil.isInputTypeText(node)){var value=node.value;if(node.type==='password'){value=value.replace(/./g,'*');}
var spannable=new Spannable(value,valueSpan);if(node===document.activeElement&&cvox.DomUtil.doesInputSupportSelection(node)){var selectionStart=cvox.BrailleUtil.clamp_(node.selectionStart,0,spannable.length);var selectionEnd=cvox.BrailleUtil.clamp_(node.selectionEnd,0,spannable.length);spannable.setSpan(new cvox.ValueSelectionSpan(),Math.min(selectionStart,selectionEnd),Math.max(selectionStart,selectionEnd));}
return spannable;}else if(node instanceof HTMLTextAreaElement){var shadow=new cvox.EditableTextAreaShadow();shadow.update(node);var lineIndex=shadow.getLineIndex(node.selectionEnd);var lineStart=shadow.getLineStart(lineIndex);var lineEnd=shadow.getLineEnd(lineIndex);var lineText=node.value.substring(lineStart,lineEnd);valueSpan.offset=lineStart;var spannable=new Spannable(lineText,valueSpan);if(node===document.activeElement){var selectionStart=cvox.BrailleUtil.clamp_(node.selectionStart-lineStart,0,spannable.length);var selectionEnd=cvox.BrailleUtil.clamp_(node.selectionEnd-lineStart,0,spannable.length);spannable.setSpan(new cvox.ValueSelectionSpan(),Math.min(selectionStart,selectionEnd),Math.max(selectionStart,selectionEnd));}
return spannable;}else{return new Spannable(cvox.DomUtil.getValue(node),valueSpan);}};cvox.BrailleUtil.getTemplated=function(prev,node,opt_override){opt_override=opt_override?opt_override:{};var roleMsg=opt_override.roleMsg||(node?cvox.DomUtil.getRoleMsg(node,cvox.VERBOSITY_VERBOSE):'');var template=cvox.BrailleUtil.TEMPLATE[roleMsg]||cvox.BrailleUtil.TEMPLATE['base'];var state=opt_override.state;if(!state){if(node){state=cvox.BrailleUtil.expandStateMsgs_(cvox.DomUtil.getStateMsgs(node,true));}else{state='';}}
var role=opt_override.role||'';if(!role&&roleMsg){role=Msgs.getMsg(roleMsg+'_brl')||Msgs.getMsg(roleMsg);}
var templated=new Spannable();var mapChar=function(c){switch(c){case'n':return opt_override.name||cvox.BrailleUtil.getName(node);case'r':return role;case's':return state;case'c':return opt_override.container||cvox.BrailleUtil.getContainer(prev,node);case'v':return opt_override.value||cvox.BrailleUtil.getValue(node);default:return c;}};for(var i=0;i<template.length;i++){var component=mapChar(template[i]);templated.append(component);if(!component.toString()&&template[i+1]==' '&&(!(component instanceof Spannable)||!(component).getSpanInstanceOf(cvox.ValueSelectionSpan))){i++;}}
return templated.trimRight();};cvox.BrailleUtil.createValue=function(text,opt_selStart,opt_selEnd,opt_textOffset){var spannable=new Spannable(text,new cvox.ValueSpan(opt_textOffset||0));if(goog.isDef(opt_selStart)){opt_selEnd=goog.isDef(opt_selEnd)?opt_selEnd:opt_selStart;if(opt_selStart>opt_selEnd){var temp=opt_selStart;opt_selStart=opt_selEnd;opt_selEnd=temp;}
spannable.setSpan(new cvox.ValueSelectionSpan(),opt_selStart,opt_selEnd);}
return spannable;};cvox.BrailleUtil.click=function(braille,opt_displayPosition){var handled=false;var spans=braille.text.getSpans(opt_displayPosition||0);var node=spans.filter(function(n){return n instanceof Node;})[0];if(node){if(goog.isDef(opt_displayPosition)&&(cvox.DomUtil.isInputTypeText(node)||node instanceof HTMLTextAreaElement)){var valueSpan=spans.filter(function(s){return s instanceof cvox.ValueSpan;})[0];if(valueSpan){if(document.activeElement!==node){cvox.Focuser.setFocus(node);}
var cursorPosition=opt_displayPosition-
braille.text.getSpanStart(valueSpan)+
valueSpan.offset;cvox.ChromeVoxEventWatcher.setUpTextHandler();node.selectionStart=node.selectionEnd=cursorPosition;cvox.ChromeVoxEventWatcher.handleTextChanged(true);handled=true;}}}
if(!handled){cvox.DomUtil.clickElem(node||cvox.ChromeVox.navigationManager.getCurrentNode(),false,false,false,true);}};cvox.BrailleUtil.clamp_=function(number,min,max){return Math.min(Math.max(number,min),max);};goog.provide('cvox.TableUtil');goog.require('cvox.XpathUtil');cvox.TableUtil.checkIfHeader=function(cell){return((cell.tagName=='TH')||cell.hasAttribute('scope')||(cell.hasAttribute('role')&&((cell.getAttribute('role')=='rowheader')||(cell.getAttribute('role')=='columnheader'))));};cvox.TableUtil.determineColGroups=function(colGroups){var colToColGroup=[];if(colGroups.length==0){return colToColGroup;}
for(var colGroupCtr=0;colGroupCtr<colGroups.length;colGroupCtr++){var currentColGroup=colGroups[colGroupCtr];var childCols=cvox.TableUtil.getColNodes(currentColGroup);if(childCols.length>0){for(var colNodeCtr=0;colNodeCtr<childCols.length;colNodeCtr++){var colElement=childCols[colNodeCtr];if(colElement.hasAttribute('span')){var span=parseInt(colElement.getAttribute('span'),10);for(var s=0;s<span;s++){colToColGroup.push(colGroupCtr);}}else{colToColGroup.push(colGroupCtr);}}}else{if(currentColGroup.hasAttribute('span')){var span=parseInt(currentColGroup.getAttribute('span'),10);for(var s=0;s<span;s++){colToColGroup.push(colGroupCtr);}}else{colToColGroup.push(colGroupCtr);}}}
return colToColGroup;};cvox.TableUtil.pushIfNotContained=function(givenArray,givenElement){if(givenArray.indexOf(givenElement)==-1){givenArray.push(givenElement);}};cvox.TableUtil.getChildRows=function(table){return cvox.XpathUtil.evalXPath('child::tbody/tr | child::thead/tr | '+'child::*[attribute::role="row"]',table);};cvox.TableUtil.getChildCells=function(rowNode){return cvox.XpathUtil.evalXPath('child::td | child::th | '+'child::*[attribute::role="gridcell"] |'+'child::*[attribute::role="rowheader"] |'+'child::*[attribute::role="columnheader"]',rowNode);};cvox.TableUtil.getCellWithID=function(table,cellID){return cvox.XpathUtil.evalXPath('id(\''+cellID+'\')',table);};cvox.TableUtil.getColGroups=function(table){return cvox.XpathUtil.evalXPath('child::colgroup',table);};cvox.TableUtil.getColNodes=function(colGroupNode){return cvox.XpathUtil.evalXPath('child::col',colGroupNode);};goog.provide('cvox.TraverseTable');goog.require('cvox.DomPredicates');goog.require('cvox.DomUtil');goog.require('cvox.SelectionUtil');goog.require('cvox.TableUtil');goog.require('cvox.TraverseUtil');function ShadowTableNode(){this.rowHeaderCells=[];this.colHeaderCells=[];}
ShadowTableNode.prototype.spanned;ShadowTableNode.prototype.rowSpan;ShadowTableNode.prototype.colSpan;ShadowTableNode.prototype.i=-1;ShadowTableNode.prototype.j=-1;ShadowTableNode.prototype.activeCell;cvox.TraverseTable=function(tableNode){this.activeTable_=null;this.shadowTable_=[];this.candidateHeaders_=[];this.idToShadowNode_=[];this.initialize(tableNode);};cvox.TraverseTable.prototype.currentCellCursor;cvox.TraverseTable.prototype.colCount=null;cvox.TraverseTable.prototype.rowCount=null;cvox.TraverseTable.prototype.tableRowHeaders=null;cvox.TraverseTable.prototype.tableColHeaders=null;cvox.TraverseTable.prototype.initialize=function(tableNode){if(!tableNode){return;}
if(tableNode==this.activeTable_){return;}
this.activeTable_=tableNode;this.currentCellCursor=null;this.tableRowHeaders=[];this.tableColHeaders=[];this.buildShadowTable_();this.colCount=this.shadowColCount_();this.rowCount=this.countRows_();this.findHeaderCells_();this.activeTable_.addEventListener('DOMSubtreeModified',goog.bind(function(){this.buildShadowTable_();this.colCount=this.shadowColCount_();this.rowCount=this.countRows_();this.tableRowHeaders=[];this.tableColHeaders=[];this.findHeaderCells_();if(this.colCount==0&&this.rowCount==0){return;}
if(this.getCell()==null){this.attachCursorToNearestCell_();}},this),false);};cvox.TraverseTable.prototype.findNearestCursor=function(node){if(!node){return null;}
var n=node;while(n.firstElementChild&&!(n.firstElementChild.tagName=='TABLE'||cvox.AriaUtil.isGrid(n.firstElementChild))){n=n.firstElementChild;}
while(!cvox.DomPredicates.cellPredicate(cvox.DomUtil.getAncestors(n))){n=cvox.DomUtil.directedNextLeafNode(n);if(!cvox.DomUtil.getContainingTable(n,{allowCaptions:true})){return null;}}
for(var i=0;i<this.rowCount;++i){for(var j=0;j<this.colCount;++j){if(this.shadowTable_[i][j]){if(cvox.DomUtil.isDescendantOfNode(n,this.shadowTable_[i][j].activeCell)){return[i,j];}}}}
return null;};cvox.TraverseTable.prototype.attachCursorToNearestCell_=function(){if(!this.currentCellCursor){this.goToLastCell();return;}
var currentCursor=this.currentCellCursor;var currentRow=this.shadowTable_[currentCursor[0]];if(currentRow){this.currentCellCursor=[currentCursor[0],(currentRow.length-1)];}else{var numRows=this.shadowTable_.length;if(numRows==0){this.currentCellCursor=null;return;}
var aboveCell=this.shadowTable_[numRows-1][currentCursor[1]];if(aboveCell){this.currentCellCursor=[(numRows-1),currentCursor[1]];}else{this.goToLastCell();}}};cvox.TraverseTable.prototype.buildShadowTable_=function(){this.shadowTable_=[];var allRows=cvox.TableUtil.getChildRows(this.activeTable_);var currentRowParent=null;var currentRowGroup=null;var colGroups=cvox.TableUtil.getColGroups(this.activeTable_);var colToColGroup=cvox.TableUtil.determineColGroups(colGroups);for(var ctr=0;ctr<allRows.length;ctr++){this.shadowTable_.push([]);}
for(var i=0;i<allRows.length;i++){var childCells=cvox.TableUtil.getChildCells(allRows[i]);var activeTableCol=0;var shadowTableCol=0;while(activeTableCol<childCells.length){if(this.shadowTable_[i][shadowTableCol]==null){var activeTableCell=childCells[activeTableCol];var colsSpanned=1;var rowsSpanned=1;if(activeTableCell.hasAttribute('colspan')){colsSpanned=parseInt(activeTableCell.getAttribute('colspan'),10);if((isNaN(colsSpanned))||(colsSpanned<=0)){colsSpanned=1;}}
if(activeTableCell.hasAttribute('rowspan')){rowsSpanned=parseInt(activeTableCell.getAttribute('rowspan'),10);if((isNaN(rowsSpanned))||(rowsSpanned<=0)){rowsSpanned=1;}}
for(var r=0;r<rowsSpanned;r++){for(var c=0;c<colsSpanned;c++){var shadowNode=new ShadowTableNode();if((r==0)&&(c==0)){shadowNode.spanned=false;shadowNode.rowSpan=false;shadowNode.colSpan=false;shadowNode.i=i;shadowNode.j=shadowTableCol;shadowNode.activeCell=activeTableCell;shadowNode.rowHeaderCells=[];shadowNode.colHeaderCells=[];shadowNode.isRowHeader=false;shadowNode.isColHeader=false;}else{shadowNode.spanned=true;shadowNode.rowSpan=(rowsSpanned>1);shadowNode.colSpan=(colsSpanned>1);shadowNode.i=i;shadowNode.j=shadowTableCol;shadowNode.activeCell=activeTableCell;shadowNode.rowHeaderCells=[];shadowNode.colHeaderCells=[];shadowNode.isRowHeader=false;shadowNode.isColHeader=false;}
if(cvox.TableUtil.checkIfHeader(shadowNode.activeCell)){this.candidateHeaders_.push(shadowNode);}else if(shadowNode.activeCell.hasAttribute('headers')){this.candidateHeaders_.push(shadowNode);}
if(currentRowParent==null){currentRowParent=allRows[i].parentNode;currentRowGroup=0;}else{if(allRows[i].parentNode!=currentRowParent){currentRowParent=allRows[i].parentNode;currentRowGroup=currentRowGroup+1;}}
shadowNode.rowGroup=currentRowGroup;if(colToColGroup.length>0){shadowNode.colGroup=colToColGroup[shadowTableCol];}else{shadowNode.colGroup=0;}
if(!shadowNode.spanned){if(activeTableCell.id!=null){this.idToShadowNode_[activeTableCell.id]=shadowNode;}}
this.shadowTable_[i+r][shadowTableCol+c]=shadowNode;}}
shadowTableCol+=colsSpanned;activeTableCol++;}else{shadowTableCol+=1;}}}
return this.shadowTable_;};cvox.TraverseTable.prototype.findHeaderCells_=function(){for(var i=0;i<this.candidateHeaders_.length;i++){var currentShadowNode=this.candidateHeaders_[i];var currentCell=currentShadowNode.activeCell;var assumedScope=null;var specifiedScope=null;if(currentShadowNode.spanned){continue;}
if((currentCell.tagName=='TH')&&!(currentCell.hasAttribute('scope'))){if(currentShadowNode.j>0){if(this.shadowTable_[currentShadowNode.i][currentShadowNode.j-1].activeCell.tagName=='TH'){assumedScope='col';}}else if(currentShadowNode.j<this.shadowTable_[currentShadowNode.i].length-1){if(this.shadowTable_[currentShadowNode.i][currentShadowNode.j+1].activeCell.tagName=='TH'){assumedScope='col';}}else{assumedScope='col';}
if(assumedScope==null){if(currentShadowNode.i>0){if(this.shadowTable_[currentShadowNode.i-1][currentShadowNode.j].activeCell.tagName=='TH'){assumedScope='row';}}else if(currentShadowNode.i<this.shadowTable_.length-1){if(this.shadowTable_[currentShadowNode.i+1][currentShadowNode.j].activeCell.tagName=='TH'){assumedScope='row';}}else{assumedScope='row';}}}else if(currentCell.hasAttribute('scope')){specifiedScope=currentCell.getAttribute('scope');}else if(currentCell.hasAttribute('role')&&(currentCell.getAttribute('role')=='rowheader')){specifiedScope='row';}else if(currentCell.hasAttribute('role')&&(currentCell.getAttribute('role')=='columnheader')){specifiedScope='col';}
if((specifiedScope=='row')||(assumedScope=='row')){currentShadowNode.isRowHeader=true;for(var rightCtr=currentShadowNode.j;rightCtr<this.shadowTable_[currentShadowNode.i].length;rightCtr++){var rightShadowNode=this.shadowTable_[currentShadowNode.i][rightCtr];var rightCell=rightShadowNode.activeCell;if((rightCell.tagName=='TH')||(rightCell.hasAttribute('scope'))){if(rightCtr<this.shadowTable_[currentShadowNode.i].length-1){var checkDataCell=this.shadowTable_[currentShadowNode.i][rightCtr+1];}}
rightShadowNode.rowHeaderCells.push(currentCell);}
this.tableRowHeaders.push(currentCell);}else if((specifiedScope=='col')||(assumedScope=='col')){currentShadowNode.isColHeader=true;for(var downCtr=currentShadowNode.i;downCtr<this.shadowTable_.length;downCtr++){var downShadowNode=this.shadowTable_[downCtr][currentShadowNode.j];if(downShadowNode==null){break;}
var downCell=downShadowNode.activeCell;if((downCell.tagName=='TH')||(downCell.hasAttribute('scope'))){if(downCtr<this.shadowTable_.length-1){var checkDataCell=this.shadowTable_[downCtr+1][currentShadowNode.j];}}
downShadowNode.colHeaderCells.push(currentCell);}
this.tableColHeaders.push(currentCell);}else if(specifiedScope=='rowgroup'){currentShadowNode.isRowHeader=true;var currentRowGroup=currentShadowNode.rowGroup;for(var cellsInRow=currentShadowNode.j+1;cellsInRow<this.shadowTable_[currentShadowNode.i].length;cellsInRow++){this.shadowTable_[currentShadowNode.i][cellsInRow].rowHeaderCells.push(currentCell);}
for(var downCtr=currentShadowNode.i+1;downCtr<this.shadowTable_.length;downCtr++){if(this.shadowTable_[downCtr][0].rowGroup!=currentRowGroup){break;}
for(var rightCtr=0;rightCtr<this.shadowTable_[downCtr].length;rightCtr++){this.shadowTable_[downCtr][rightCtr].rowHeaderCells.push(currentCell);}}
this.tableRowHeaders.push(currentCell);}else if(specifiedScope=='colgroup'){currentShadowNode.isColHeader=true;var currentColGroup=currentShadowNode.colGroup;for(var cellsInCol=currentShadowNode.j+1;cellsInCol<this.shadowTable_[currentShadowNode.i].length;cellsInCol++){if(this.shadowTable_[currentShadowNode.i][cellsInCol].colGroup==currentColGroup){this.shadowTable_[currentShadowNode.i][cellsInCol].colHeaderCells.push(currentCell);}}
for(var downCtr=currentShadowNode.i+1;downCtr<this.shadowTable_.length;downCtr++){for(var rightCtr=0;rightCtr<this.shadowTable_[downCtr].length;rightCtr++){if(this.shadowTable_[downCtr][rightCtr].colGroup==currentColGroup){this.shadowTable_[downCtr][rightCtr].colHeaderCells.push(currentCell);}}}
this.tableColHeaders.push(currentCell);}
if(currentCell.hasAttribute('headers')){this.findAttrbHeaders_(currentShadowNode);}
if(currentCell.hasAttribute('aria-describedby')){this.findAttrbDescribedBy_(currentShadowNode);}}};cvox.TraverseTable.prototype.findAttrbHeaders_=function(currentShadowNode){var activeTableCell=currentShadowNode.activeCell;var idList=activeTableCell.getAttribute('headers').split(' ');for(var idToken=0;idToken<idList.length;idToken++){var idCellArray=cvox.TableUtil.getCellWithID(this.activeTable_,idList[idToken]);for(var idCtr=0;idCtr<idCellArray.length;idCtr++){if(idCellArray[idCtr].id==activeTableCell.id){break;}
var possibleHeaderNode=this.idToShadowNode_[idCellArray[idCtr].id];if(!cvox.TableUtil.checkIfHeader(possibleHeaderNode.activeCell)){var iDiff=Math.abs(possibleHeaderNode.i-currentShadowNode.i);var jDiff=Math.abs(possibleHeaderNode.j-currentShadowNode.j);if((iDiff==0)||(iDiff<jDiff)){cvox.TableUtil.pushIfNotContained(currentShadowNode.rowHeaderCells,possibleHeaderNode.activeCell);cvox.TableUtil.pushIfNotContained(this.tableRowHeaders,possibleHeaderNode.activeCell);}else{cvox.TableUtil.pushIfNotContained(currentShadowNode.colHeaderCells,possibleHeaderNode.activeCell);cvox.TableUtil.pushIfNotContained(this.tableColHeaders,possibleHeaderNode.activeCell);}}}}};cvox.TraverseTable.prototype.findAttrbDescribedBy_=function(currentShadowNode){var activeTableCell=currentShadowNode.activeCell;var idList=activeTableCell.getAttribute('aria-describedby').split(' ');for(var idToken=0;idToken<idList.length;idToken++){var idCellArray=cvox.TableUtil.getCellWithID(this.activeTable_,idList[idToken]);for(var idCtr=0;idCtr<idCellArray.length;idCtr++){if(idCellArray[idCtr].id==activeTableCell.id){break;}
var possibleHeaderNode=this.idToShadowNode_[idCellArray[idCtr].id];if(!cvox.TableUtil.checkIfHeader(possibleHeaderNode.activeCell)){if(possibleHeaderNode.activeCell.hasAttribute('role')&&(possibleHeaderNode.activeCell.getAttribute('role')=='rowheader')){cvox.TableUtil.pushIfNotContained(currentShadowNode.rowHeaderCells,possibleHeaderNode.activeCell);cvox.TableUtil.pushIfNotContained(this.tableRowHeaders,possibleHeaderNode.activeCell);}else if(possibleHeaderNode.activeCell.hasAttribute('role')&&(possibleHeaderNode.activeCell.getAttribute('role')=='columnheader')){cvox.TableUtil.pushIfNotContained(currentShadowNode.colHeaderCells,possibleHeaderNode.activeCell);cvox.TableUtil.pushIfNotContained(this.tableColHeaders,possibleHeaderNode.activeCell);}}}}};cvox.TraverseTable.prototype.getCell=function(){if(!this.currentCellCursor||!this.shadowTable_){return null;}
var shadowEntry=this.shadowTable_[this.currentCellCursor[0]][this.currentCellCursor[1]];return shadowEntry&&shadowEntry.activeCell;};cvox.TraverseTable.prototype.getCellAt=function(index){if(((index[0]<this.rowCount)&&(index[0]>=0))&&((index[1]<this.colCount)&&(index[1]>=0))){var shadowEntry=this.shadowTable_[index[0]][index[1]];if(shadowEntry!=null){return shadowEntry.activeCell;}}
return null;};cvox.TraverseTable.prototype.getCellRowHeaders=function(){var shadowEntry=this.shadowTable_[this.currentCellCursor[0]][this.currentCellCursor[1]];return shadowEntry.rowHeaderCells;};cvox.TraverseTable.prototype.getCellColHeaders=function(){var shadowEntry=this.shadowTable_[this.currentCellCursor[0]][this.currentCellCursor[1]];return shadowEntry.colHeaderCells;};cvox.TraverseTable.prototype.isSpanned=function(){var shadowEntry=this.shadowTable_[this.currentCellCursor[0]][this.currentCellCursor[1]];return shadowEntry.spanned;};cvox.TraverseTable.prototype.isRowHeader=function(){var shadowEntry=this.shadowTable_[this.currentCellCursor[0]][this.currentCellCursor[1]];return shadowEntry.isRowHeader;};cvox.TraverseTable.prototype.isColHeader=function(){var shadowEntry=this.shadowTable_[this.currentCellCursor[0]][this.currentCellCursor[1]];return shadowEntry.isColHeader;};cvox.TraverseTable.prototype.getCol=function(){var colArray=[];for(var i=0;i<this.shadowTable_.length;i++){if(this.shadowTable_[i][this.currentCellCursor[1]]){var shadowEntry=this.shadowTable_[i][this.currentCellCursor[1]];if(shadowEntry.colSpan&&shadowEntry.rowSpan){var prev=colArray[colArray.length-1];if(prev!=shadowEntry.activeCell){colArray.push(shadowEntry.activeCell);}}else if((shadowEntry.colSpan)||(!shadowEntry.rowSpan)){colArray.push(shadowEntry.activeCell);}}}
return colArray;};cvox.TraverseTable.prototype.getRow=function(){var childRows=cvox.TableUtil.getChildRows(this.activeTable_);return childRows[this.currentCellCursor[0]];};cvox.TraverseTable.prototype.summaryText=function(){if(!this.activeTable_.hasAttribute('summary')){return null;}
return this.activeTable_.getAttribute('summary');};cvox.TraverseTable.prototype.captionText=function(){var captionNodes=cvox.XpathUtil.evalXPath('caption\[1]',this.activeTable_);if(captionNodes.length>0){return captionNodes[0].innerHTML;}else{return null;}};cvox.TraverseTable.prototype.shadowColCount_=function(){var max=0;for(var i=0;i<this.shadowTable_.length;i++){if(this.shadowTable_[i].length>max){max=this.shadowTable_[i].length;}}
return max;};cvox.TraverseTable.prototype.countRows_=function(){var rowCount=cvox.TableUtil.getChildRows(this.activeTable_);return rowCount.length;};cvox.TraverseTable.prototype.getW3CColCount_=function(){var colgroupNodes=cvox.XpathUtil.evalXPath('child::colgroup',this.activeTable_);var colNodes=cvox.XpathUtil.evalXPath('child::col',this.activeTable_);if((colgroupNodes.length==0)&&(colNodes.length==0)){var maxcols=0;var outerChildren=cvox.TableUtil.getChildRows(this.activeTable_);for(var i=0;i<outerChildren.length;i++){var childrenCount=cvox.TableUtil.getChildCells(outerChildren[i]);if(childrenCount.length>maxcols){maxcols=childrenCount.length;}}
return maxcols;}else{var sum=0;for(var i=0;i<colNodes.length;i++){if(colNodes[i].hasAttribute('span')){sum+=colNodes[i].getAttribute('span');}else{sum+=1;}}
for(i=0;i<colgroupNodes.length;i++){var colChildren=cvox.XpathUtil.evalXPath('child::col',colgroupNodes[i]);if(colChildren.length==0){if(colgroupNodes[i].hasAttribute('span')){sum+=colgroupNodes[i].getAttribute('span');}else{sum+=1;}}}}
return sum;};cvox.TraverseTable.prototype.nextRow=function(){if(!this.currentCellCursor){return this.goToRow(0);}else{return this.goToRow(this.currentCellCursor[0]+1);}};cvox.TraverseTable.prototype.prevRow=function(){if(!this.currentCellCursor){return this.goToRow(this.rowCount-1);}else{return this.goToRow(this.currentCellCursor[0]-1);}};cvox.TraverseTable.prototype.nextCol=function(){if(!this.currentCellCursor){return this.goToCol(0);}else{return this.goToCol(this.currentCellCursor[1]+1);}};cvox.TraverseTable.prototype.prevCol=function(){if(!this.currentCellCursor){return this.goToCol(this.shadowColCount_()-1);}else{return this.goToCol(this.currentCellCursor[1]-1);}};cvox.TraverseTable.prototype.goToRow=function(index){if(this.shadowTable_[index]!=null){if(this.currentCellCursor==null){this.currentCellCursor=[index,0];}else{this.currentCellCursor=[index,this.currentCellCursor[1]];}
return true;}else{return false;}};cvox.TraverseTable.prototype.goToCol=function(index){if(index<0||index>=this.colCount){return false;}
if(this.currentCellCursor==null){this.currentCellCursor=[0,index];}else{this.currentCellCursor=[this.currentCellCursor[0],index];}
return true;};cvox.TraverseTable.prototype.goToCell=function(index){if(((index[0]<this.rowCount)&&(index[0]>=0))&&((index[1]<this.colCount)&&(index[1]>=0))){var cell=this.shadowTable_[index[0]][index[1]];if(cell!=null){this.currentCellCursor=index;return true;}}
return false;};cvox.TraverseTable.prototype.goToLastCell=function(){var numRows=this.shadowTable_.length;if(numRows==0){return false;}
var lastRow=this.shadowTable_[numRows-1];var lastIndex=[(numRows-1),(lastRow.length-1)];var cell=this.shadowTable_[lastIndex[0]][lastIndex[1]];if(cell!=null){this.currentCellCursor=lastIndex;return true;}
return false;};cvox.TraverseTable.prototype.goToRowLastCell=function(){var currentRow=this.currentCellCursor[0];var lastIndex=[currentRow,(this.shadowTable_[currentRow].length-1)];var cell=this.shadowTable_[lastIndex[0]][lastIndex[1]];if(cell!=null){this.currentCellCursor=lastIndex;return true;}
return false;};cvox.TraverseTable.prototype.goToColLastCell=function(){var currentCol=this.getCol();var lastIndex=[(currentCol.length-1),this.currentCellCursor[1]];var cell=this.shadowTable_[lastIndex[0]][lastIndex[1]];if(cell!=null){this.currentCellCursor=lastIndex;return true;}
return false;};cvox.TraverseTable.prototype.resetCursor=function(){this.currentCellCursor=null;};goog.provide('cvox.TableWalker');goog.require('cvox.AbstractWalker');goog.require('cvox.BrailleUtil');goog.require('cvox.DescriptionUtil');goog.require('cvox.DomUtil');goog.require('cvox.NavDescription');goog.require('cvox.QueueMode');goog.require('cvox.TraverseTable');cvox.TableWalker=function(){cvox.AbstractWalker.call(this);this.tt=new cvox.TraverseTable(null);};goog.inherits(cvox.TableWalker,cvox.AbstractWalker);cvox.TableWalker.prototype.next=function(sel){return this.nextRow(sel);};cvox.TableWalker.prototype.sync=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToCell(position);},this));};cvox.TableWalker.prototype.getDescription=function(prevSel,sel){var position=this.syncPosition_(sel);if(!position){return[];}
this.tt.goToCell(position);var descs=cvox.DescriptionUtil.getCollectionDescription(prevSel,sel);if(descs.length==0){descs.push(new cvox.NavDescription({annotation:Msgs.getMsg('empty_cell')}));}
return descs;};cvox.TableWalker.prototype.getBraille=function(prevSel,sel){var ret=new cvox.NavBraille({});var position=this.syncPosition_(sel);if(position){var text=cvox.BrailleUtil.getTemplated(prevSel.start.node,sel.start.node);text.append(' '+ ++position[0]+'/'+ ++position[1]);}
return new cvox.NavBraille({text:text});};cvox.TableWalker.prototype.getGranularityMsg=goog.abstractMethod;cvox.TableWalker.prototype.goToFirstCell=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToCell([0,0]);},this));};cvox.TableWalker.prototype.goToLastCell=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToLastCell();},this));};cvox.TableWalker.prototype.goToRowFirstCell=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToCell([position[0],0]);},this));};cvox.TableWalker.prototype.goToRowLastCell=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToRowLastCell();},this));};cvox.TableWalker.prototype.goToColFirstCell=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToCell([0,position[1]]);},this));};cvox.TableWalker.prototype.goToColLastCell=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToColLastCell();},this));};cvox.TableWalker.prototype.nextRow=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToCell([position[0]+(sel.isReversed()?-1:1),position[1]]);},this));};cvox.TableWalker.prototype.nextCol=function(sel){return this.goTo_(sel,goog.bind(function(position){return this.tt.goToCell([position[0],position[1]+(sel.isReversed()?-1:1)]);},this));};cvox.TableWalker.prototype.announceHeaders=function(sel){cvox.ChromeVox.tts.speak(this.getHeaderText_(sel),cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOTATION);return sel;};cvox.TableWalker.prototype.speakTableLocation=function(sel){cvox.ChromeVox.navigationManager.speakDescriptionArray(this.getLocationDescription_(sel),cvox.QueueMode.FLUSH,null);return sel;};cvox.TableWalker.prototype.exitShifterContent=function(sel){var tableNode=this.getTableNode_(sel);if(!tableNode){return null;}
var nextNode=cvox.DomUtil.directedNextLeafNode(tableNode,false);return cvox.CursorSelection.fromNode(nextNode);};cvox.TableWalker.prototype.getHeaderText_=function(sel){this.tt.initialize(this.getTableNode_(sel));var position=this.tt.findNearestCursor(sel.start.node);if(!position){return Msgs.getMsg('not_inside_table');}
if(!this.tt.goToCell(position)){return Msgs.getMsg('not_inside_table');}
return(this.getRowHeaderText_(position)+' '+
this.getColHeaderText_(position));};cvox.TableWalker.prototype.getLocationDescription_=function(sel){var locationInfo=this.getLocationInfo(sel);if(locationInfo==null){return null;}
return[new cvox.NavDescription({text:Msgs.getMsg('table_location',locationInfo)})];};cvox.TableWalker.prototype.getRowHeaderText_=function(position){var rowHeaderText='';var rowHeaders=this.tt.getCellRowHeaders();if(rowHeaders.length==0){var firstCellInRow=this.tt.getCellAt([position[0],0]);rowHeaderText+=cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(firstCellInRow)+' '+
cvox.DomUtil.getName(firstCellInRow));return Msgs.getMsg('row_header')+rowHeaderText;}
for(var i=0;i<rowHeaders.length;++i){rowHeaderText+=cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(rowHeaders[i])+' '+
cvox.DomUtil.getName(rowHeaders[i]));}
if(rowHeaderText==''){return Msgs.getMsg('empty_row_header');}
return Msgs.getMsg('row_header')+rowHeaderText;};cvox.TableWalker.prototype.getColHeaderText_=function(position){var colHeaderText='';var colHeaders=this.tt.getCellColHeaders();if(colHeaders.length==0){var firstCellInCol=this.tt.getCellAt([0,position[1]]);colHeaderText+=cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(firstCellInCol)+' '+
cvox.DomUtil.getName(firstCellInCol));return Msgs.getMsg('column_header')+colHeaderText;}
for(var i=0;i<colHeaders.length;++i){colHeaderText+=cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(colHeaders[i])+' '+
cvox.DomUtil.getName(colHeaders[i]));}
if(colHeaderText==''){return Msgs.getMsg('empty_row_header');}
return Msgs.getMsg('column_header')+colHeaderText;};cvox.TableWalker.prototype.getLocationInfo=function(sel){this.tt.initialize(this.getTableNode_(sel));var position=this.tt.findNearestCursor(sel.start.node);if(!position){return null;}
return[position[0]+1,this.tt.rowCount,position[1]+1,this.tt.colCount].map(function(x){return Msgs.getNumber(x);});};cvox.TableWalker.prototype.isInTable=function(sel){return this.getTableNode_(sel)!=null;};cvox.TableWalker.prototype.goTo_=function(sel,f){if(!sel.end.node){return null;}
this.tt.initialize(this.getTableNode_(sel));var position=this.tt.findNearestCursor(sel.end.node);if(!position){return null;}
this.tt.goToCell(position);if(!f(position)){return null;}
return cvox.CursorSelection.fromNode(this.tt.getCell()).setReversed(sel.isReversed());};cvox.TableWalker.prototype.getTableNode_=function(sel){return cvox.DomUtil.getContainingTable(sel.end.node);};cvox.TableWalker.prototype.syncPosition_=function(sel){var tableNode=this.getTableNode_(sel);this.tt.initialize(tableNode);return this.tt.findNearestCursor(sel.end.node);};goog.provide('cvox.ColumnWalker');goog.require('cvox.TableWalker');cvox.ColumnWalker=function(){goog.base(this);};goog.inherits(cvox.ColumnWalker,cvox.TableWalker);cvox.ColumnWalker.prototype.next=function(sel){return this.nextCol(sel);};cvox.ColumnWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('column_granularity');};goog.provide('cvox.RowWalker');goog.require('cvox.TableWalker');cvox.RowWalker=function(){goog.base(this);};goog.inherits(cvox.RowWalker,cvox.TableWalker);cvox.RowWalker.prototype.next=function(sel){return this.nextRow(sel);};cvox.RowWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('row_granularity');};goog.provide('cvox.AbstractShifter');goog.require('cvox.AbstractWalker');goog.require('cvox.CursorSelection');goog.require('cvox.NavBraille');cvox.AbstractShifter=function(){this.isSubnavigating_=false;};cvox.AbstractShifter.prototype.next=goog.abstractMethod;cvox.AbstractShifter.prototype.begin=function(sel,kwargs){return this.currentWalker_.begin(kwargs);};cvox.AbstractShifter.prototype.sync=goog.abstractMethod;cvox.AbstractShifter.prototype.getName=goog.abstractMethod;cvox.AbstractShifter.prototype.getDescription=goog.abstractMethod;cvox.AbstractShifter.prototype.getBraille=goog.abstractMethod;cvox.AbstractShifter.prototype.getGranularityMsg=goog.abstractMethod;cvox.AbstractShifter.prototype.makeLessGranular=function(){this.ensureNotSubnavigating();};cvox.AbstractShifter.prototype.makeMoreGranular=function(){this.ensureNotSubnavigating();};cvox.AbstractShifter.prototype.ensureSubnavigating=function(){if(this.isSubnavigating_==false){this.makeMoreGranular();this.isSubnavigating_=true;}};cvox.AbstractShifter.prototype.ensureNotSubnavigating=function(){if(this.isSubnavigating_==true){this.isSubnavigating_=false;this.makeLessGranular();}};cvox.AbstractShifter.prototype.isSubnavigating=function(){return this.isSubnavigating_;};cvox.AbstractShifter.prototype.hasAction=function(name){return this.currentWalker_.hasAction(name);};cvox.AbstractShifter.prototype.performAction=function(name,sel){return this.currentWalker_.performAction(name,sel);};cvox.AbstractShifter.create=goog.abstractMethod;goog.provide('cvox.TableShifter');goog.require('cvox.AbstractShifter');goog.require('cvox.ColumnWalker');goog.require('cvox.CursorSelection');goog.require('cvox.DomPredicates');goog.require('cvox.DomUtil');goog.require('cvox.NavBraille');goog.require('cvox.RowWalker');cvox.TableShifter=function(){this.rowWalker_=new cvox.RowWalker();this.columnWalker_=new cvox.ColumnWalker();this.currentWalker_=this.rowWalker_;this.bumpedEdge_=false;this.begin_=true;goog.base(this);};goog.inherits(cvox.TableShifter,cvox.AbstractShifter);cvox.TableShifter.prototype.next=function(sel){var nextSel=this.currentWalker_.next(sel);if(!nextSel){this.bumpedEdge_=true;return sel;}
return nextSel;};cvox.TableShifter.prototype.sync=function(sel){if(sel.start.node.tagName=='TABLE'){return sel.isReversed()?this.currentWalker_.goToLastCell(sel):this.currentWalker_.goToFirstCell(sel);}
return this.currentWalker_.sync(sel);};cvox.TableShifter.prototype.getName=function(){return Msgs.getMsg('table_shifter');};cvox.TableShifter.prototype.getDescription=function(prevSel,sel){var descs=this.currentWalker_.getDescription(prevSel,sel);if(descs.length>0){if(this.bumpedEdge_){descs[0].pushEarcon(cvox.Earcon.WRAP_EDGE);this.bumpedEdge_=false;}
if(this.begin_){var len=descs.length;var summaryText=this.currentWalker_.tt.summaryText();var locationInfo=this.currentWalker_.getLocationInfo(sel);if(locationInfo!=null){descs.push(new cvox.NavDescription({context:Msgs.getMsg('table_location',locationInfo),text:'',annotation:summaryText?summaryText+' ':''}));}
if(this.currentWalker_.tt.isSpanned()){descs.push(new cvox.NavDescription({text:'',annotation:Msgs.getMsg('spanned')}));}
this.begin_=false;}}
return descs;};cvox.TableShifter.prototype.getBraille=function(prevSel,sel){return this.currentWalker_.getBraille(prevSel,sel);};cvox.TableShifter.prototype.getGranularityMsg=function(){return this.currentWalker_.getGranularityMsg();};cvox.TableShifter.prototype.makeLessGranular=function(){goog.base(this,'makeLessGranular');this.currentWalker_=this.rowWalker_;};cvox.TableShifter.prototype.makeMoreGranular=function(){goog.base(this,'makeMoreGranular');this.currentWalker_=this.columnWalker_;};cvox.TableShifter.create=function(sel){var ancestors=cvox.DomUtil.getAncestors(sel.start.node);if(cvox.DomPredicates.tablePredicate(ancestors)&&!cvox.DomPredicates.captionPredicate(ancestors)){return new cvox.TableShifter();}
return null;};goog.provide('cvox.NavigationHistory');goog.require('cvox.DomUtil');cvox.NavigationHistory=function(){this.reset_();};cvox.NavigationHistory.MAX_HISTORY_LEN_=30;cvox.NavigationHistory.prototype.reset_=function(){var startNode=document.body;this.history_=[startNode];this.arrivedValid_=true;};cvox.NavigationHistory.prototype.update=function(newNode){var previousNode=this.history_[0];if(newNode&&newNode!=previousNode){this.history_.unshift(newNode);}
if(this.history_.length>cvox.NavigationHistory.MAX_HISTORY_LEN_){this.history_.pop();}
this.arrivedValid_=this.isValidNode_(newNode);};cvox.NavigationHistory.prototype.becomeInvalid=function(node){this.clean_();if(!this.arrivedValid_){this.arrivedValid_=true;return false;}
return!this.isValidNode_(node);};cvox.NavigationHistory.prototype.revert=function(opt_predicate){var active=document.activeElement;if(active!=document.body&&this.isValidNode_(active)){this.update(active);}
if(opt_predicate){while(this.history_.length>0){var node=this.history_[0];if(opt_predicate(node)){break;}
this.history_.shift();}}
return{current:this.history_[0],previous:this.history_[1]};};cvox.NavigationHistory.prototype.clean_=function(){var changed=false;for(var i=this.history_.length-1;i>=0;i--){var valid=this.isValidNode_(this.history_[i]);if(!valid){this.history_.splice(i,1);changed=true;}}
return changed;};cvox.NavigationHistory.prototype.isValidNode_=function(node){if(!cvox.DomUtil.isAttachedToDocument(node)){return false;}
if(!cvox.DomUtil.isVisible(node)){return false;}
return true;};goog.provide('cvox.TraverseContent');goog.require('cvox.CursorSelection');goog.require('cvox.DomUtil');goog.require('cvox.SelectionUtil');goog.require('cvox.TraverseUtil');cvox.TraverseContent=function(domObj){if(domObj!=null){this.currentDomObj=domObj;}else{this.currentDomObj=document.body;}
var range=document.createRange();try{range.selectNode(this.currentDomObj);this.startCursor_=new cvox.Cursor(range.startContainer,range.startOffset,cvox.TraverseUtil.getNodeText(range.startContainer));this.endCursor_=new cvox.Cursor(range.endContainer,range.endOffset,cvox.TraverseUtil.getNodeText(range.endContainer));}catch(e){window.console.log('Error: Unselectable node:');window.console.log(domObj);}};goog.addSingletonGetter(cvox.TraverseContent);cvox.TraverseContent.prototype.lastSelectionWasWhitespace=false;cvox.TraverseContent.prototype.skipWhitespace=false;cvox.TraverseContent.prototype.skipInvalidSelections=true;cvox.TraverseContent.prototype.breakAtLinks=true;cvox.TraverseContent.kCharacter='character';cvox.TraverseContent.kWord='word';cvox.TraverseContent.kSentence='sentence';cvox.TraverseContent.kLine='line';cvox.TraverseContent.kParagraph='paragraph';cvox.TraverseContent.kAllGrains=[cvox.TraverseContent.kParagraph,cvox.TraverseContent.kSentence,cvox.TraverseContent.kLine,cvox.TraverseContent.kWord,cvox.TraverseContent.kCharacter];cvox.TraverseContent.prototype.syncToSelection=function(){this.normalizeSelection();var selection=window.getSelection();if(!selection||!selection.anchorNode||!selection.focusNode){return;}
this.startCursor_=new cvox.Cursor(selection.anchorNode,selection.anchorOffset,cvox.TraverseUtil.getNodeText(selection.anchorNode));this.endCursor_=new cvox.Cursor(selection.focusNode,selection.focusOffset,cvox.TraverseUtil.getNodeText(selection.focusNode));};cvox.TraverseContent.prototype.syncToCursorSelection=function(sel){this.startCursor_=sel.start.clone();this.endCursor_=sel.end.clone();};cvox.TraverseContent.prototype.getCurrentCursorSelection=function(){return new cvox.CursorSelection(this.startCursor_,this.endCursor_);};cvox.TraverseContent.prototype.updateSelection=function(){cvox.TraverseUtil.setSelection(this.startCursor_,this.endCursor_);cvox.SelectionUtil.scrollToSelection(window.getSelection());};cvox.TraverseContent.prototype.getCurrentRange=function(){var range=document.createRange();try{range.setStart(this.startCursor_.node,this.startCursor_.index);range.setEnd(this.endCursor_.node,this.endCursor_.index);}catch(e){console.log('Invalid range ');}
return range;};cvox.TraverseContent.prototype.getCurrentText=function(){return cvox.SelectionUtil.getRangeText(this.getCurrentRange());};cvox.TraverseContent.prototype.collapseToEnd=function(){this.startCursor_=this.endCursor_.clone();};cvox.TraverseContent.prototype.collapseToStart=function(){this.endCursor_=this.startCursor_.clone();};cvox.TraverseContent.prototype.moveNext=function(grain){var breakTags=this.getBreakTags();var skipWhitespace=this.skipWhitespace;var range=this.getCurrentRange();if(!cvox.SelectionUtil.isRangeValid(range)){skipWhitespace=true;}
var elementsEntered=[];var elementsLeft=[];var str;do{if(grain===cvox.TraverseContent.kSentence){str=cvox.TraverseUtil.getNextSentence(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft,breakTags);}else if(grain===cvox.TraverseContent.kWord){str=cvox.TraverseUtil.getNextWord(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft);}else if(grain===cvox.TraverseContent.kCharacter){str=cvox.TraverseUtil.getNextChar(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft,skipWhitespace);}else if(grain===cvox.TraverseContent.kParagraph){str=cvox.TraverseUtil.getNextParagraph(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft);}else if(grain===cvox.TraverseContent.kLine){str=cvox.TraverseUtil.getNextLine(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft,breakTags);}else{window.console.log('Invalid selection granularity: "'+grain+'"');grain=cvox.TraverseContent.kSentence;str=cvox.TraverseUtil.getNextSentence(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft,breakTags);}
if(str==null){return null;}
range=this.getCurrentRange();var isInvalid=!range.getBoundingClientRect();}while(this.skipInvalidSelections&&isInvalid);if(!cvox.SelectionUtil.isRangeValid(range)){if(!this.lastSelectionWasWhitespace&&grain==cvox.TraverseContent.kCharacter){this.lastSelectionWasWhitespace=true;}else{while(!cvox.SelectionUtil.isRangeValid(this.getCurrentRange())){if(this.moveNext(grain)==null){break;}}}}else{this.lastSelectionWasWhitespace=false;}
return this.getCurrentText();};cvox.TraverseContent.prototype.movePrev=function(grain){var breakTags=this.getBreakTags();var skipWhitespace=this.skipWhitespace;var range=this.getCurrentRange();if(!cvox.SelectionUtil.isRangeValid(range)){skipWhitespace=true;}
var elementsEntered=[];var elementsLeft=[];var str;do{if(grain===cvox.TraverseContent.kSentence){str=cvox.TraverseUtil.getPreviousSentence(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft,breakTags);}else if(grain===cvox.TraverseContent.kWord){str=cvox.TraverseUtil.getPreviousWord(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft);}else if(grain===cvox.TraverseContent.kCharacter){str=cvox.TraverseUtil.getPreviousChar(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft,skipWhitespace);}else if(grain===cvox.TraverseContent.kParagraph){str=cvox.TraverseUtil.getPreviousParagraph(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft);}else if(grain===cvox.TraverseContent.kLine){str=cvox.TraverseUtil.getPreviousLine(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft,breakTags);}else{window.console.log('Invalid selection granularity: "'+grain+'"');grain=cvox.TraverseContent.kSentence;str=cvox.TraverseUtil.getPreviousSentence(this.startCursor_,this.endCursor_,elementsEntered,elementsLeft,breakTags);}
if(str==null){return null;}
range=this.getCurrentRange();var isInvalid=!range.getBoundingClientRect();}while(this.skipInvalidSelections&&isInvalid);if(!cvox.SelectionUtil.isRangeValid(range)){if(!this.lastSelectionWasWhitespace&&grain==cvox.TraverseContent.kCharacter){this.lastSelectionWasWhitespace=true;}else{while(!cvox.SelectionUtil.isRangeValid(this.getCurrentRange())){if(this.movePrev(grain)==null){break;}}}}else{this.lastSelectionWasWhitespace=false;}
return this.getCurrentText();};cvox.TraverseContent.prototype.getBreakTags=function(){return{'A':this.breakAtLinks,'BR':true,'HR':true};};cvox.TraverseContent.prototype.nextElement=function(grain,domObj){if(domObj!=null){this.currentDomObj=domObj;}
var result=this.moveNext(grain);if(result!=null&&(!cvox.DomUtil.isDescendantOfNode(this.startCursor_.node,this.currentDomObj)||!cvox.DomUtil.isDescendantOfNode(this.endCursor_.node,this.currentDomObj))){return null;}
return result;};cvox.TraverseContent.prototype.prevElement=function(grain,domObj){if(domObj!=null){this.currentDomObj=domObj;}
var result=this.movePrev(grain);if(result!=null&&(!cvox.DomUtil.isDescendantOfNode(this.startCursor_.node,this.currentDomObj)||!cvox.DomUtil.isDescendantOfNode(this.endCursor_.node,this.currentDomObj))){return null;}
return result;};cvox.TraverseContent.prototype.normalizeSelection=function(){var selection=window.getSelection();if(selection.rangeCount<1){var range=document.createRange();range.setStart(this.currentDomObj,0);range.setEnd(this.currentDomObj,0);selection.removeAllRanges();selection.addRange(range);}else if(selection.rangeCount>1){for(var i=0;i<(selection.rangeCount-1);i++){selection.removeRange(selection.getRangeAt(i));}}};cvox.TraverseContent.prototype.reset=function(domObj){window.getSelection().removeAllRanges();};goog.provide('cvox.AbstractSelectionWalker');goog.require('Spannable');goog.require('cvox.AbstractWalker');goog.require('cvox.BareObjectWalker');goog.require('cvox.DescriptionUtil');goog.require('cvox.DomUtil');goog.require('cvox.TraverseContent');cvox.AbstractSelectionWalker=function(){cvox.AbstractWalker.call(this);this.objWalker_=new cvox.BareObjectWalker();this.tc_=cvox.TraverseContent.getInstance();this.grain='';};goog.inherits(cvox.AbstractSelectionWalker,cvox.AbstractWalker);cvox.AbstractSelectionWalker.prototype.next=function(sel){var r=sel.isReversed();this.tc_.syncToCursorSelection(sel.clone().setReversed(false));var ret=r?this.tc_.prevElement(this.grain):this.tc_.nextElement(this.grain);if(ret==null){return this.objWalker_.next(sel);}
var retSel=this.tc_.getCurrentCursorSelection().setReversed(r);var objSel=this.objWalker_.next(sel);objSel=objSel?objSel.setReversed(r):null;if(objSel&&(retSel.end.node.constructor.name!='Text'||objSel.end.node.constructor.name!='Text')&&!cvox.DomUtil.isDescendantOfNode(retSel.end.node,sel.end.node)&&!cvox.DomUtil.isDescendantOfNode(retSel.end.node,objSel.end.node)){return objSel;}
return retSel;};cvox.AbstractSelectionWalker.prototype.sync=function(sel){var r=sel.isReversed();var newSel=null;if(sel.start.equals(sel.end)&&sel.start.node.constructor.name!='Text'){var node=sel.start.node;while(node&&cvox.DomUtil.directedFirstChild(node,r)&&!cvox.TraverseUtil.treatAsLeafNode(node)){var child=cvox.DomUtil.directedFirstChild(node,r);while(child){if(cvox.DomUtil.isVisible(child,{checkAncestors:false,checkDescendants:false})){node=child;break;}else{child=cvox.DomUtil.directedNextSibling(child,r);}}
if(!child){break;}}
newSel=cvox.CursorSelection.fromNode(node);}else{newSel=sel.clone();if(r){newSel.start=newSel.end;}else{newSel.end=newSel.start;}}
newSel=this.next(newSel.setReversed(false));var objSel=this.objWalker_.sync(sel);objSel=objSel?objSel.setReversed(r):null;if(!newSel){return objSel;}
newSel.setReversed(r);if(objSel&&(newSel.end.node.constructor.name!='Text'||objSel.end.node.constructor.name!='Text')&&!cvox.DomUtil.isDescendantOfNode(newSel.end.node,sel.end.node)&&!cvox.DomUtil.isDescendantOfNode(newSel.end.node,objSel.end.node)){return objSel;}
return newSel;};cvox.AbstractSelectionWalker.prototype.getDescription=function(prevSel,sel){var description=cvox.DescriptionUtil.getDescriptionFromAncestors(cvox.DomUtil.getUniqueAncestors(prevSel.end.node,sel.start.node),true,cvox.ChromeVox.verbosity);description.text=sel.getText()||description.text;return[description];};cvox.AbstractSelectionWalker.prototype.getBraille=function(prevSel,sel){var node=sel.absStart().node;var text=cvox.TraverseUtil.getNodeText(node);var spannable=new Spannable(text);spannable.setSpan(node,0,text.length);return new cvox.NavBraille({text:spannable,startIndex:sel.absStart().index,endIndex:sel.absEnd().index});};goog.provide('cvox.CharacterWalker');goog.require('cvox.AbstractSelectionWalker');goog.require('cvox.TraverseContent');cvox.CharacterWalker=function(){cvox.AbstractSelectionWalker.call(this);this.grain=cvox.TraverseContent.kCharacter;};goog.inherits(cvox.CharacterWalker,cvox.AbstractSelectionWalker);cvox.CharacterWalker.prototype.getDescription=function(prevSel,sel){var desc=goog.base(this,'getDescription',prevSel,sel);desc.forEach(function(item){if(!item.personality){item.personality={};}
item.personality['phoneticCharacters']=true;});return desc;};cvox.CharacterWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('character_granularity');};goog.provide('cvox.SentenceWalker');goog.require('cvox.AbstractSelectionWalker');goog.require('cvox.TraverseContent');cvox.SentenceWalker=function(){cvox.AbstractSelectionWalker.call(this);this.grain=cvox.TraverseContent.kSentence;};goog.inherits(cvox.SentenceWalker,cvox.AbstractSelectionWalker);cvox.SentenceWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('sentence_granularity');};goog.provide('cvox.ObjectWalker');goog.require('cvox.AbstractNodeWalker');goog.require('cvox.BrailleUtil');goog.require('cvox.DescriptionUtil');cvox.ObjectWalker=function(){goog.base(this);};goog.inherits(cvox.ObjectWalker,cvox.AbstractNodeWalker);cvox.ObjectWalker.prototype.stopNodeDescent=function(node){return cvox.DomUtil.isLeafNode(node);};cvox.AbstractNodeWalker.prototype.getDescription=function(prevSel,sel){return cvox.DescriptionUtil.getDescriptionFromNavigation(prevSel.end.node,sel.start.node,true,cvox.ChromeVox.verbosity);};cvox.ObjectWalker.prototype.getBraille=function(prevSel,sel){throw'getBraille is unsupported';};cvox.ObjectWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('object_strategy');};goog.provide('cvox.StructuralLineWalker');goog.require('cvox.AbstractSelectionWalker');goog.require('cvox.BrailleUtil');goog.require('cvox.TraverseContent');cvox.StructuralLineWalker=function(){goog.base(this);this.grain=cvox.TraverseContent.kLine;};goog.inherits(cvox.StructuralLineWalker,cvox.AbstractSelectionWalker);cvox.StructuralLineWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('structural_line');};cvox.StructuralLineWalker.prototype.getDescription=function(prevSel,sel){var desc=goog.base(this,'getDescription',prevSel,sel);desc[0].text=cvox.DomUtil.getPrefixText(sel.absStart().node,sel.absStart().index)+desc[0].text;return desc;};cvox.StructuralLineWalker.prototype.getBraille=function(prevSel,sel){var braille=goog.base(this,'getBraille',prevSel,sel);var objNode=this.objWalker_.sync(sel).absStart().node;var node=sel.absStart().node;var prevNode=prevSel.absEnd().node;var name=undefined;if(!sel.start.equals(sel.end)&&!cvox.DomPredicates.editTextPredicate([objNode])){var prefix=cvox.DomUtil.getPrefixText(sel.absStart().node,sel.absStart().index);name=prefix+sel.getText();}
var spannable=cvox.BrailleUtil.getTemplated(prevNode,objNode,{name:name});spannable.setSpan(objNode,0,spannable.length);braille.text=spannable;braille.startIndex=0;braille.endIndex=0;return braille;};goog.provide('cvox.LayoutLineWalker');goog.require('cvox.AbstractWalker');goog.require('cvox.StructuralLineWalker');cvox.LayoutLineWalker=function(){this.subWalker_=new cvox.StructuralLineWalker();};goog.inherits(cvox.LayoutLineWalker,cvox.AbstractWalker);cvox.LayoutLineWalker.prototype.next=function(sel){var endSel=new cvox.CursorSelection(sel.end,sel.end,sel.isReversed());var sync=this.subWalker_.sync(endSel);if(!sync){return null;}
var start=this.subWalker_.next(endSel);if(!start){return null;}
start.setReversed(sel.isReversed());return this.extend_(start).setReversed(false);};cvox.LayoutLineWalker.prototype.sync=function(sel){var line=this.subWalker_.sync(sel);if(!line){return null;}
var end=this.extend_(line);var start=this.extend_(line.setReversed(!line.isReversed()));return new cvox.CursorSelection(start.end,end.end,sel.isReversed());};cvox.LayoutLineWalker.prototype.getDescription=function(prevSel,sel){var descriptions=[];var prev=prevSel;var absSel=sel.clone().setReversed(false);var cur=new cvox.CursorSelection(absSel.start,absSel.start);cur=this.subWalker_.sync(cur);if(!cur){return[];}
if(absSel.start.node==absSel.end.node){return this.subWalker_.getDescription(prevSel,sel);}
while(cur&&!cur.end.equals(absSel.end)){descriptions.push.apply(descriptions,this.subWalker_.getDescription(prev,cur));prev=cur;cur=this.subWalker_.next(cur);}
if(cur){descriptions.push.apply(descriptions,this.subWalker_.getDescription(prev,cur));}
return descriptions;};cvox.LayoutLineWalker.prototype.getBraille=function(prevSel,sel){var braille=new cvox.NavBraille({});var absSel=this.subWalker_.sync(sel.clone().setReversed(false));var layoutSel=this.sync(sel).setReversed(false);if(!layoutSel||!absSel){return braille;}
var cur=new cvox.CursorSelection(layoutSel.start,layoutSel.start);cur=this.subWalker_.sync(cur);if(!cur){return braille;}
while(cur&&!cur.end.equals(layoutSel.end)){this.appendBraille_(prevSel,absSel,cur,braille);prevSel=cur;cur=this.subWalker_.next(cur);}
if(cur){this.appendBraille_(prevSel,absSel,cur,braille);}
return braille;};cvox.LayoutLineWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('layout_line');};cvox.LayoutLineWalker.prototype.isVisualLineBreak_=function(lSel,rSel){if(this.wantsOwnLine_(lSel.end.node)||this.wantsOwnLine_(rSel.start.node)){return true;}
var lRect=lSel.getRange().getBoundingClientRect();var rRect=rSel.getRange().getBoundingClientRect();if(lRect.width==0&&lRect.height==0&&lSel.end.node.nodeType==Node.ELEMENT_NODE){lRect=lSel.end.node.getBoundingClientRect();}
if(rRect.width==0&&rRect.height==0&&rSel.start.node.nodeType==Node.ELEMENT_NODE){rRect=rSel.start.node.getBoundingClientRect();}
return lRect.bottom!=rRect.bottom;};cvox.LayoutLineWalker.prototype.wantsOwnLine_=function(node){if(!node){return false;}
return node instanceof HTMLTextAreaElement||node.parentNode instanceof HTMLTextAreaElement;};cvox.LayoutLineWalker.prototype.extend_=function(start){var end=start;var next=start;do{end=next;next=this.subWalker_.next(end);}while(next&&!this.isVisualLineBreak_(end,next));return new cvox.CursorSelection(start.start,end.end,start.isReversed());};cvox.LayoutLineWalker.prototype.appendBraille_=function(prevSel,sel,cur,braille){var item=this.subWalker_.getBraille(prevSel,cur).text;var valueSelectionSpan=item.getSpanInstanceOf(cvox.ValueSelectionSpan);if(braille.text.length>0){braille.text.append(cvox.BrailleUtil.ITEM_SEPARATOR);}
var node=cur.start.node;while(node.parentNode&&cvox.DomUtil.isLeafNode(node.parentNode)){node=node.parentNode;}
var nodeStart=braille.text.length;var nodeEnd=nodeStart+item.length;braille.text.append(item);braille.text.setSpan(node,nodeStart,nodeEnd);if(sel&&cur.absEquals(sel)){if(valueSelectionSpan){braille.startIndex=nodeStart+item.getSpanStart(valueSelectionSpan);braille.endIndex=nodeStart+item.getSpanEnd(valueSelectionSpan);}else{braille.startIndex=nodeStart;braille.endIndex=nodeStart+1;}}};goog.provide('cvox.WordWalker');goog.require('cvox.AbstractSelectionWalker');goog.require('cvox.TraverseContent');cvox.WordWalker=function(){cvox.AbstractSelectionWalker.call(this);this.grain=cvox.TraverseContent.kWord;};goog.inherits(cvox.WordWalker,cvox.AbstractSelectionWalker);cvox.WordWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('word_granularity');};goog.provide('cvox.GroupUtil');goog.require('cvox.AriaUtil');goog.require('cvox.DomUtil');cvox.GroupUtil.MAX_CHARCOUNT_=1500;cvox.GroupUtil.BREAKOUT_SELECTOR_='blockquote,'+'button,'+'code,'+'form,'+'frame,'+'h1,'+'h2,'+'h3,'+'h4,'+'h5,'+'h6,'+'hr,'+'iframe,'+'input,'+'object,'+'ol,'+'p,'+'pre,'+'select,'+'table,'+'tr,'+'ul,'+'math,'+'span.math,'+'[role~="alert '+'alertdialog '+'button '+'checkbox '+'combobox '+'dialog '+'log '+'marquee '+'menubar '+'progressbar '+'radio '+'radiogroup '+'scrollbar '+'slider '+'spinbutton '+'status '+'tab '+'tabpanel '+'textbox '+'toolbar '+'tooltip '+'treeitem '+'article '+'document '+'group '+'heading '+'img '+'list '+'math '+'region '+'row '+'separator"]';cvox.GroupUtil.isLeafNode=function(node){if(node.tagName=='LABEL'){return cvox.DomUtil.isLeafNode(node);}
if(cvox.DomUtil.isLeafNode(node)){return true;}
if(!cvox.DomUtil.isSemanticElt(node)){var breakingNodes=node.querySelectorAll(cvox.GroupUtil.BREAKOUT_SELECTOR_);for(var i=0;i<breakingNodes.length;++i){if(cvox.DomUtil.hasContent(breakingNodes[i])){return false;}}}
if(cvox.AriaUtil.isCompositeControl(node)&&!cvox.DomUtil.isFocusable(node)){return false;}
var content=cvox.DomUtil.collapseWhitespace(cvox.DomUtil.getValue(node)+' '+
cvox.DomUtil.getName(node));if(content.length>cvox.GroupUtil.MAX_CHARCOUNT_){return false;}
if(content.replace(/\s/g,'')===''){return false;}
return true;};goog.provide('cvox.GroupWalker');goog.require('cvox.AbstractNodeWalker');goog.require('cvox.BrailleUtil');goog.require('cvox.CursorSelection');goog.require('cvox.DescriptionUtil');goog.require('cvox.DomUtil');goog.require('cvox.GroupUtil');cvox.GroupWalker=function(){cvox.AbstractNodeWalker.call(this);};goog.inherits(cvox.GroupWalker,cvox.AbstractNodeWalker);cvox.GroupWalker.prototype.getDescription=function(prevSel,sel){return cvox.DescriptionUtil.getCollectionDescription(prevSel,sel);};cvox.GroupWalker.prototype.getBraille=function(prevSel,sel){throw'getBraille is unsupported';};cvox.GroupWalker.prototype.getGranularityMsg=function(){return Msgs.getMsg('group_strategy');};cvox.GroupWalker.prototype.stopNodeDescent=function(node){return cvox.GroupUtil.isLeafNode(node);};goog.provide('cvox.NavigationShifter');goog.require('cvox.AbstractShifter');goog.require('cvox.CharacterWalker');goog.require('cvox.GroupWalker');goog.require('cvox.LayoutLineWalker');goog.require('cvox.ObjectWalker');goog.require('cvox.SentenceWalker');goog.require('cvox.TraverseContent');goog.require('cvox.WordWalker');cvox.NavigationShifter=function(){this.reset_();goog.base(this);};goog.inherits(cvox.NavigationShifter,cvox.AbstractShifter);cvox.NavigationShifter.GRANULARITIES={'CHARACTER':0,'WORD':1,'LINE':2,'SENTENCE':3,'OBJECT':4,'GROUP':5};cvox.NavigationShifter.prototype.storeOn=function(store){store['granularity']=this.getGranularity();};cvox.NavigationShifter.prototype.readFrom=function(store){this.setGranularity(store['granularity']);};cvox.NavigationShifter.prototype.next=function(sel){var ret=this.currentWalker_.next(sel);if(this.currentWalkerIndex_<=cvox.NavigationShifter.GRANULARITIES.LINE&&ret){cvox.TraverseContent.getInstance().syncToCursorSelection(ret.clone().setReversed(false));cvox.TraverseContent.getInstance().updateSelection();}
return ret;};cvox.NavigationShifter.prototype.sync=function(sel){return this.currentWalker_.sync(sel);};cvox.NavigationShifter.prototype.getName=function(){return Msgs.getMsg('navigation_shifter');};cvox.NavigationShifter.prototype.getDescription=function(prevSel,sel){return this.currentWalker_.getDescription(prevSel,sel);};cvox.NavigationShifter.prototype.getBraille=function(prevSel,sel){return this.lineWalker_.getBraille(prevSel,sel);};cvox.NavigationShifter.prototype.getGranularityMsg=function(){return this.currentWalker_.getGranularityMsg();};cvox.NavigationShifter.prototype.makeMoreGranular=function(){goog.base(this,'makeMoreGranular');this.currentWalkerIndex_=Math.max(this.currentWalkerIndex_-1,0);if(!cvox.NavigationShifter.allowSentence&&this.currentWalkerIndex_==cvox.NavigationShifter.GRANULARITIES.SENTENCE){this.currentWalkerIndex_--;}
this.currentWalker_=this.walkers_[this.currentWalkerIndex_];};cvox.NavigationShifter.prototype.makeLessGranular=function(){goog.base(this,'makeLessGranular');this.currentWalkerIndex_=Math.min(this.currentWalkerIndex_+1,this.walkers_.length-1);if(!cvox.NavigationShifter.allowSentence&&this.currentWalkerIndex_==cvox.NavigationShifter.GRANULARITIES.SENTENCE){this.currentWalkerIndex_++;}
this.currentWalker_=this.walkers_[this.currentWalkerIndex_];};cvox.NavigationShifter.prototype.setGranularity=function(granularity){this.ensureNotSubnavigating();this.currentWalkerIndex_=granularity;this.currentWalker_=this.walkers_[this.currentWalkerIndex_];};cvox.NavigationShifter.prototype.getGranularity=function(){var wasSubnavigating=this.isSubnavigating();this.ensureNotSubnavigating();var ret=this.currentWalkerIndex_;if(wasSubnavigating){this.ensureSubnavigating();}
return ret;};cvox.NavigationShifter.prototype.hasAction=function(name){if(name=='toggleLineType'){return true;}
return goog.base(this,'hasAction',name);};cvox.NavigationShifter.create=function(sel){return new cvox.NavigationShifter();};cvox.NavigationShifter.prototype.reset_=function(){this.groupWalker_=new cvox.GroupWalker();this.objectWalker_=new cvox.ObjectWalker();this.sentenceWalker_=new cvox.SentenceWalker();this.lineWalker_=new cvox.LayoutLineWalker();this.wordWalker_=new cvox.WordWalker();this.characterWalker_=new cvox.CharacterWalker();this.walkers_=[this.characterWalker_,this.wordWalker_,this.lineWalker_,this.sentenceWalker_,this.objectWalker_,this.groupWalker_];this.currentWalkerIndex_=this.walkers_.indexOf(this.groupWalker_);this.currentWalker_=this.walkers_[this.currentWalkerIndex_];};cvox.NavigationShifter.allowSentence=false;goog.provide('cvox.FindUtil');goog.require('cvox.BareObjectWalker');goog.require('cvox.CursorSelection');cvox.FindUtil.objectWalker_=new cvox.BareObjectWalker();cvox.FindUtil.findNext=function(sel,predicate,opt_initialNode){var r=sel.isReversed();var cur=new cvox.CursorSelection(sel.absStart(),sel.absStart()).setReversed(r);var ancestor;if(ancestor=predicate(cvox.DomUtil.getAncestors(cur.start.node))){cur=cvox.CursorSelection.fromNode(ancestor).setReversed(r);if(opt_initialNode){return cur;}}
while(cur){cur=cvox.FindUtil.objectWalker_.next(cur);var retNode=null;if(!cur||(retNode=predicate(cvox.DomUtil.getAncestors(cur.start.node)))){return retNode?cvox.CursorSelection.fromNode(retNode):null;}
if(cur.start.node.tagName=='IFRAME'){return cur;}}
return null;};goog.provide('cvox.PageSelection');goog.require('cvox.AbstractEarcons');goog.require('cvox.CursorSelection');goog.require('cvox.NavDescription');cvox.PageSelection=function(sel){this.sel_=sel.clone();this.sel_.select();this.wasBegin_=true;};cvox.PageSelection.prototype.getDescription=function(navShifter,prevSel,curSel){var desc=[];if(this.sel_.isReversed()!=curSel.isReversed()){desc=navShifter.getDescription(curSel,prevSel);desc[0].annotation=Msgs.getMsg('describe_unselected');desc[0].pushEarcon(cvox.Earcon.SELECTION_REVERSE);}else{desc=navShifter.getDescription(prevSel,curSel);desc[0].annotation=Msgs.getMsg('describe_selected');desc[0].pushEarcon(cvox.Earcon.SELECTION);if(!this.wasBegin_&&this.sel_.absEquals(curSel.clone().normalize())){var prevDesc=navShifter.getDescription(curSel,prevSel);prevDesc[0].annotation=Msgs.getMsg('describe_unselected');prevDesc[0].pushEarcon(cvox.Earcon.SELECTION_REVERSE);prevDesc[0].pushEarcon(cvox.Earcon.WRAP);desc=prevDesc.concat(desc);}}
return desc;};cvox.PageSelection.prototype.getFullDescription=function(){return[new cvox.NavDescription({text:window.getSelection().toString(),context:Msgs.getMsg('selection_is')})];};cvox.PageSelection.prototype.extend=function(sel){if(!this.sel_.directedBefore(sel)){this.sel_=sel.clone();}else{this.sel_.end=this.sel_.isReversed()==sel.isReversed()?sel.end.clone():sel.start.clone();}
this.sel_.select();this.wasBegin_=false;return!this.sel_.absEquals(sel);};goog.provide('cvox.MathmlStoreUtil');goog.require('cvox.MathUtil');goog.require('cvox.TraverseMath');cvox.MathmlStoreUtil.matchMathjaxToMathml=function(inner){var mml=cvox.TraverseMath.getInstance().activeMathmlHost;return mml.querySelector('#'+inner.id);};cvox.MathmlStoreUtil.retrieveMathjaxExtender=function(jax){var ext=cvox.MathmlStoreUtil.matchMathjaxToMathml(jax);if(ext){return[ext];}
return[];};cvox.MathmlStoreUtil.retrieveMathjaxLeaf=function(jax){var leaf=cvox.MathmlStoreUtil.matchMathjaxToMathml(jax);if(leaf){return[leaf];}
return[];};cvox.MathmlStoreUtil.checkMathjaxTag=function(jax,tag){var node=cvox.MathmlStoreUtil.matchMathjaxToMathml(jax);if(node&&node.tagName.toUpperCase()==tag){return[node];}
return[];};cvox.MathmlStoreUtil.checkMathjaxMunder=function(jax){return cvox.MathmlStoreUtil.checkMathjaxTag(jax,'MUNDER');};cvox.MathmlStoreUtil.checkMathjaxMover=function(jax){return cvox.MathmlStoreUtil.checkMathjaxTag(jax,'MOVER');};cvox.MathmlStoreUtil.checkMathjaxMsub=function(jax){return cvox.MathmlStoreUtil.checkMathjaxTag(jax,'MSUB');};cvox.MathmlStoreUtil.checkMathjaxMsup=function(jax){return cvox.MathmlStoreUtil.checkMathjaxTag(jax,'MSUP');};cvox.MathmlStoreUtil.nextSeparatorFunction=function(separators){if(separators){if(separators.match(/^\s+$/)){return null;}else{var sepList=separators.replace(/\s/g,'').split('').filter(function(x){return x;});}}else{var sepList=[','];}
return function(){if(sepList.length>1){return sepList.shift();}
return sepList[0];};};cvox.MathmlStoreUtil.mfencedSeparators=function(nodes,context){var nextSeparator=cvox.MathmlStoreUtil.nextSeparatorFunction(context);return function(){return nextSeparator?nextSeparator():'';};};cvox.MathmlStoreUtil.contentIterator=function(nodes,context){if(nodes.length>0){var contentNodes=cvox.XpathUtil.evalXPath('../../content/*',nodes[0]);}else{var contentNodes=[];}
return function(){var content=contentNodes.shift();return context+(content?content.textContent:'');};};goog.provide('cvox.StoreUtil');cvox.StoreUtil.nodeCounter=function(nodes,context){var localLength=nodes.length;var localCounter=0;var localContext=context;if(!context){localContext='';}
return function(){if(localCounter<localLength){localCounter+=1;}
return localContext+' '+localCounter;};};goog.provide('cvox.MathmlStoreRules');goog.require('cvox.MathStore');goog.require('cvox.MathmlStore');goog.require('cvox.MathmlStoreUtil');goog.require('cvox.StoreUtil');cvox.MathmlStoreRules=function(){cvox.MathmlStoreRules.initCustomFunctions_();cvox.MathmlStoreRules.initDefaultRules_();cvox.MathmlStoreRules.initMathjaxRules_();cvox.MathmlStoreRules.initAliases_();cvox.MathmlStoreRules.initSpecializationRules_();cvox.MathmlStoreRules.initSemanticRules_();};goog.addSingletonGetter(cvox.MathmlStoreRules);cvox.MathmlStoreRules.mathStore=cvox.MathmlStore.getInstance();cvox.MathmlStoreRules.mathStore.initialize=cvox.MathmlStoreRules.getInstance;cvox.MathmlStoreRules.defineDefaultMathmlRule_=goog.bind(cvox.MathmlStoreRules.mathStore.defineDefaultMathmlRule,cvox.MathmlStoreRules.mathStore);cvox.MathmlStoreRules.defineRule_=goog.bind(cvox.MathmlStoreRules.mathStore.defineRule,cvox.MathmlStoreRules.mathStore);cvox.MathmlStoreRules.defineRuleAlias_=goog.bind(cvox.MathmlStoreRules.mathStore.defineRuleAlias,cvox.MathmlStoreRules.mathStore);cvox.MathmlStoreRules.addContextFunction_=goog.bind(cvox.MathmlStoreRules.mathStore.contextFunctions.add,cvox.MathmlStoreRules.mathStore.contextFunctions);cvox.MathmlStoreRules.addCustomQuery_=goog.bind(cvox.MathmlStoreRules.mathStore.customQueries.add,cvox.MathmlStoreRules.mathStore.customQueries);goog.scope(function(){var defineDefaultMathmlRule=cvox.MathmlStoreRules.defineDefaultMathmlRule_;var defineRule=cvox.MathmlStoreRules.defineRule_;var defineRuleAlias=cvox.MathmlStoreRules.defineRuleAlias_;var addCTXF=cvox.MathmlStoreRules.addContextFunction_;var addCQF=cvox.MathmlStoreRules.addCustomQuery_;cvox.MathmlStoreRules.initCustomFunctions_=function(){addCTXF('CTXFnodeCounter',cvox.StoreUtil.nodeCounter);addCTXF('CTXFmfSeparators',cvox.MathmlStoreUtil.mfencedSeparators);addCTXF('CTXFcontentIterator',cvox.MathmlStoreUtil.contentIterator);addCQF('CQFextender',cvox.MathmlStoreUtil.retrieveMathjaxExtender);addCQF('CQFmathmlmunder',cvox.MathmlStoreUtil.checkMathjaxMunder);addCQF('CQFmathmlmover',cvox.MathmlStoreUtil.checkMathjaxMover);addCQF('CQFmathmlmsub',cvox.MathmlStoreUtil.checkMathjaxMsub);addCQF('CQFmathmlmsup',cvox.MathmlStoreUtil.checkMathjaxMsup);addCQF('CQFlookupleaf',cvox.MathmlStoreUtil.retrieveMathjaxLeaf);};cvox.MathmlStoreRules.initDefaultRules_=function(){defineDefaultMathmlRule('math','[m] ./*');defineDefaultMathmlRule('semantics','[n] ./*[1]');defineDefaultMathmlRule('mspace','[p] (pause:250)');defineDefaultMathmlRule('mstyle','[m] ./*');defineDefaultMathmlRule('mpadded','[m] ./*');defineDefaultMathmlRule('merror','[t] ""');defineDefaultMathmlRule('mphantom','[t] ""');defineDefaultMathmlRule('mtext','[t] text(); [p] (pause:200)');defineDefaultMathmlRule('mi','[n] text()');defineDefaultMathmlRule('mo','[n] text() (rate:-0.1)');defineDefaultMathmlRule('mn','[n] text()');defineRule('mtext-variant','default.default','[t] "begin"; [t] @mathvariant (pause:150);'+'[t] text() (pause:150); [t] "end"; '+'[t] @mathvariant (pause:200)','self::mathml:mtext','@mathvariant','@mathvariant!="normal"');defineRule('mi-variant','default.default','[t] @mathvariant; [n] text()','self::mathml:mi','@mathvariant','@mathvariant!="normal"');defineRuleAlias('mi-variant','self::mathml:mn','@mathvariant','@mathvariant!="normal"');defineRule('mo-variant','default.default','[t] @mathvariant; [n] text() (rate:-0.1)','self::mathml:mo','@mathvariant','@mathvariant!="normal"');defineDefaultMathmlRule('ms','[t] "string" (pitch:0.5, rate:0.5); [t] text()');defineDefaultMathmlRule('msup','[n] ./*[1]; [t] "super";'+'[n] ./*[2] (pitch:0.35); [p] (pause:300)');defineDefaultMathmlRule('msubsup','[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);'+'[t] "super"; [n] ./*[3] (pitch:0.35); [p] (pause:300)');defineDefaultMathmlRule('msub','[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:300)');defineDefaultMathmlRule('mover','[n] ./*[2] (pitch:0.35); [p] (pause:200);'+' [t] "over"; [n] ./*[1]; [p] (pause:400)');defineDefaultMathmlRule('munder','[n] ./*[2] (pitch:-0.35); [t] "under"; [n] ./*[1]; [p] (pause:400)');defineDefaultMathmlRule('munderover','[n] ./*[2] (pitch:-0.35); [t] "under and"; [n] ./*[3] (pitch:0.35);'+' [t] "over"; [n] ./*[1]; [p] (pause:400)');defineDefaultMathmlRule('mrow','[m] ./*');defineDefaultMathmlRule('msqrt','[t] "Square root of"; [m] ./* (rate:0.2); [p] (pause:400)');defineDefaultMathmlRule('mroot','[t] "root of order"; [n] ./*[2]; [t] "of";'+'[n] ./*[1] (rate:0.2); [p] (pause:400)');defineDefaultMathmlRule('mfrac',' [p] (pause:400); [n] ./*[1] (pitch:0.3);'+' [t] "divided by"; [n] ./*[2] (pitch:-0.3); [p] (pause:400)');defineRule('mfrac','default.short','[p] (pause:200); [t] "start frac";'+'[n] ./*[1] (pitch:0.3); [t] "over"; '+'[n] ./*[2] (pitch:-0.3); [p] (pause:400); [t] "end frac"','self::mathml:mfrac');defineRule('mfenced-single','default.default','[t] concat(substring(@open, 0 div boolean(@open)), '+'substring("(", 0 div not(boolean(@open)))) (context:"opening"); '+'[m] ./* (separator:@separators); '+'[t] concat(substring(@close, 0 div boolean(@close)), '+'substring(")", 0 div not(boolean(@close)))) (context:"closing")','self::mathml:mfenced','string-length(string(@separators))=1');defineRule('mfenced-omit','default.default','[t] concat(substring(@open, 0 div boolean(@open)), '+'substring("(", 0 div not(boolean(@open)))) (context:"opening"); '+'[m] ./*; '+'[t] concat(substring(@close, 0 div boolean(@close)), '+'substring(")", 0 div not(boolean(@close)))) (context:"closing")','self::mathml:mfenced','@separators','string-length(string(@separators))=0','string(@separators)=""');defineRule('mfenced-empty','default.default','[t] concat(substring(@open, 0 div boolean(@open)), '+'substring("(", 0 div not(boolean(@open)))) (context:"opening"); '+'[m] ./*;'+'[t] concat(substring(@close, 0 div boolean(@close)), '+'substring(")", 0 div not(boolean(@close)))) (context:"closing")','self::mathml:mfenced','string-length(string(@separators))=1','string(@separators)=" "');defineRule('mfenced-comma','default.default','[t] concat(substring(@open, 0 div boolean(@open)), '+'substring("(", 0 div not(boolean(@open)))) (context:"opening"); '+'[m] ./* (separator:"comma");'+'[t] concat(substring(@close, 0 div boolean(@close)), '+'substring(")", 0 div not(boolean(@close)))) (context:"closing")','self::mathml:mfenced');defineRule('mfenced-multi','default.default','[t] concat(substring(@open, 0 div boolean(@open)), '+'substring("(", 0 div not(boolean(@open)))) (context:"opening"); '+'[m] ./* (sepFunc:CTXFmfSeparators, separator:@separators); '+'[t] concat(substring(@close, 0 div boolean(@close)), '+'substring(")", 0 div not(boolean(@close)))) (context:"closing")','self::mathml:mfenced','string-length(string(@separators))>1');defineRule('mtable','default.default','[t] "matrix"; [m] ./* (ctxtFunc:CTXFnodeCounter,'+'context:"row",pause:100)','self::mathml:mtable');defineRule('mtr','default.default','[m] ./* (ctxtFunc:CTXFnodeCounter,context:"column",pause:100)','self::mathml:mtr');defineRule('mtd','default.default','[m] ./*','self::mathml:mtd');defineRule('mtable','default.superbrief','[t] count(child::mathml:mtr);  [t] "by";'+'[t] count(child::mathml:mtr[1]/mathml:mtd); [t] "matrix";','self::mathml:mtable');defineRule('mtable','default.short','[t] "matrix"; [m] ./*','self::mathml:mtable');defineRule('mtr','default.short','[m] ./*','self::mathml:mtr');defineRule('mtd','default.short','[t] "Element"; [t] count(./preceding-sibling::mathml:mtd)+1;'+'[t] count(./parent::mathml:mtr/preceding-sibling::mathml:mtr)+1;'+'[p] (pause:500); [m] ./*','self::mathml:mtd');defineRule('mmultiscripts-4','default.default','[n] ./*[1]; [p] (pause:200);'+'[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);'+'[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);'+'[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);'+'[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);','self::mathml:mmultiscripts');defineRule('mmultiscripts-3-1','default.default','[n] ./*[1]; [p] (pause:200);'+'[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);'+'[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);'+'[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);','self::mathml:mmultiscripts','./mathml:none=./*[2]','./mathml:mprescripts=./*[4]');defineRule('mmultiscripts-3-2','default.default','[n] ./*[1]; [p] (pause:200);'+'[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);'+'[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);'+'[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);','self::mathml:mmultiscripts','./mathml:none=./*[3]','./mathml:mprescripts=./*[4]');defineRule('mmultiscripts-3-3','default.default','[n] ./*[1]; [p] (pause:200);'+'[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:200);'+'[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);'+'[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);','self::mathml:mmultiscripts','./mathml:none=./*[5]','./mathml:mprescripts=./*[4]');defineRule('mmultiscripts-3-4','default.default','[n] ./*[1]; [p] (pause:200);'+'[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);'+'[t] "right sub"; [n] ./*[2] (pitch:-0.35); [p] (pause:200);'+'[t] "right super"; [n] ./*[3] (pitch:0.35); [p] (pause:300);','self::mathml:mmultiscripts','./mathml:none=./*[6]','./mathml:mprescripts=./*[4]');defineRule('mmultiscripts-2-1','default.default','[n] ./*[1]; [p] (pause:200);'+'[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);'+'[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:300);','self::mathml:mmultiscripts','./mathml:none=./*[2]','./mathml:none=./*[3]','./mathml:mprescripts=./*[4]');defineRule('mmultiscripts-1-1','default.default','[n] ./*[1]; [p] (pause:200);'+'[t] "left super"; [n] ./*[6] (pitch:0.35); [p] (pause:300);','self::mathml:mmultiscripts','./mathml:none=./*[2]','./mathml:none=./*[3]','./mathml:mprescripts=./*[4]','./mathml:none=./*[5]');defineRule('mmultiscripts-1-2','default.default','[n] ./*[1]; [p] (pause:200);'+'[t] "left sub"; [n] ./*[5] (pitch:-0.35); [p] (pause:200);','self::mathml:mmultiscripts','./mathml:none=./*[2]','./mathml:none=./*[3]','./mathml:mprescripts=./*[4]','./mathml:none=./*[6]');};cvox.MathmlStoreRules.initMathjaxRules_=function(){defineRule('mj-math','default.default','[n] ./*[1]/*[1]/*[1]','self::span[@class="math"]');defineRule('mj-leaf','default.default','[n] CQFlookupleaf','self::span[@class="mi"]');defineRuleAlias('mj-leaf','self::span[@class="mo"]');defineRuleAlias('mj-leaf','self::span[@class="mn"]');defineRuleAlias('mj-leaf','self::span[@class="mtext"]');defineRule('mj-mo-ext','default.default','[n] CQFextender','self::span[@class="mo"]','./*[1]/*[1]/text()','./*[1]/*[2]/text()');defineRule('mj-texatom','default.default','[n] ./*[1]','self::span[@class="texatom"]');defineRule('mj-msubsup','default.default','[n] ./*[1]/*[1]/*[1]; [t] "sub"; [n] ./*[1]/*[3]/*[1] (pitch:-0.35);'+'[p] (pause:200); [t] "super"; [n] ./*[1]/*[2]/*[1] (pitch:0.35);'+'[p] (pause:300)','self::span[@class="msubsup"]');defineRule('mj-msub','default.default','[n] ./*[1]/*[1]/*[1]; [t] "sub";'+'[n] ./*[1]/*[2]/*[1] (pitch:-0.35); [p] (pause:300)','self::span[@class="msub"]');defineRule('mj-msup','default.default','[n] ./*[1]/*[1]/*[1]; [t] "super";'+'[n] ./*[1]/*[2]/*[1] (pitch:0.35); [p] (pause:300)','self::span[@class="msup"]');defineRule('mj-munderover','default.default','[n] ./*[1]/*[2]/*[1] (pitch:0.35); [t] "under and";'+'[n] ./*[1]/*[3]/*[1] (pitch:-0.35); [t] "over";'+'[n] ./*[1]/*[1]/*[1]; [p] (pause:400)','self::span[@class="munderover"]');defineRule('mj-munder','default.default','[n] ./*[1]/*[2]/*[1] (pitch:0.35); [t] "under";'+'[n] ./*[1]/*[1]/*[1]; [p] (pause:400)','self::span[@class="munder"]');defineRule('mj-mover','default.default','[n] ./*[1]/*[2]/*[1] (pitch:0.35); [t] "over";'+'[n] ./*[1]/*[1]/*[1]; [p] (pause:400)','self::span[@class="mover"]');defineRule('mj-mfrac','default.default','[p] (pause:250); [n] ./*[1]/*[1]/*[1] (pitch:0.3); [p] (pause:250);'+' [t] "divided by"; [n] ./*[1]/*[2]/*[1] (pitch:-0.3);'+'[p] (pause:400)','self::span[@class="mfrac"]');defineRule('mj-msqrt','default.default','[t] "Square root of";'+'[n] ./*[1]/*[1]/*[1] (rate:0.2); [p] (pause:400)','self::span[@class="msqrt"]');defineRule('mj-mroot','default.default','[t] "root of order"; [n] ./*[1]/*[4]/*[1]; [t] "of";'+'[n] ./*[1]/*[1]/*[1] (rate:0.2); [p] (pause:400)','self::span[@class="mroot"]');defineRule('mj-mfenced','default.default','[t] "opening"; [n] ./*[1]; '+'[m] ./*[position()>1 and position()<last()];'+' [t] "closing"; [n] ./*[last()]','self::span[@class="mfenced"]');defineRuleAlias('mj-leaf','self::span[@class="mtable"]');defineRuleAlias('mj-leaf','self::span[@class="mmultiscripts"]');};cvox.MathmlStoreRules.initAliases_=function(){defineRuleAlias('mspace','self::span[@class="mspace"]');defineRuleAlias('mstyle','self::span[@class="mstyle"]');defineRuleAlias('mpadded','self::span[@class="mpadded"]');defineRuleAlias('merror','self::span[@class="merror"]');defineRuleAlias('mphantom','self::span[@class="mphantom"]');defineRuleAlias('ms','self::span[@class="ms"]');defineRuleAlias('mrow','self::span[@class="mrow"]');defineRuleAlias('mj-msub','self::span[@class="msubsup"]','CQFmathmlmsub');defineRuleAlias('mj-msup','self::span[@class="msubsup"]','CQFmathmlmsup');defineRuleAlias('mj-munder','self::span[@class="munderover"]','CQFmathmlmunder');defineRuleAlias('mj-mover','self::span[@class="munderover"]','CQFmathmlmover');};cvox.MathmlStoreRules.initSpecializationRules_=function(){defineRule('square','default.default','[n] ./*[1]; [t] "square" (pitch:0.35); [p] (pause:300)','self::mathml:msup','./*[2][text()=2]');defineRuleAlias('square','self::mathml:msup','./mathml:mrow=./*[2]','count(./*[2]/*)=1','./*[2]/*[1][text()=2]');defineRule('cube','default.default','[n] ./*[1]; [t] "cube" (pitch:0.35); [p] (pause:300)','self::mathml:msup','./*[2][text()=3]');defineRuleAlias('cube','self::mathml:msup','./mathml:mrow=./*[2]','count(./*[2]/*)=1','./*[2]/*[1][text()=3]');defineRule('square-sub','default.default','[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35);'+'[p] (pause:300); [t] "square" (pitch:0.35); [p] (pause:400)','self::mathml:msubsup','./*[3][text()=2]');defineRuleAlias('square-sub','self::mathml:msubsup','./mathml:mrow=./*[3]','count(./*[3]/*)=1','./*[3]/*[1][text()=2]');defineRule('cube-sub','default.default','[n] ./*[1]; [t] "sub"; [n] ./*[2] (pitch:-0.35);'+'[p] (pause:300); [t] "cube" (pitch:0.35); [p] (pause:400)','self::mathml:msubsup','./*[3][text()=3]');defineRuleAlias('cube-sub','self::mathml:msubsup','./mathml:mrow=./*[3]','count(./*[3]/*)=1','./*[3]/*[1][text()=3]');defineRule('mj-square','default.default','[n] ./*[1]/*[1]/*[1]; [t] "square" (pitch:0.35); [p] (pause:300)','self::span[@class="msup"]','./*[1]/*[2]/*[1][text()=2]');defineRuleAlias('mj-square','self::span[@class="msup"]','./*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]','count(./*[1]/*[2]/*[1]/*)=1','./*[1]/*[2]/*[1]/*[1][text()=2]');defineRuleAlias('mj-square','self::span[@class="msubsup"]','CQFmathmlmsup','./*[1]/*[2]/*[1][text()=2]');defineRuleAlias('mj-square','self::span[@class="msubsup"]','CQFmathmlmsup','./*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]','count(./*[1]/*[2]/*[1]/*)=1','./*[1]/*[2]/*[1]/*[1][text()=2]');defineRule('mj-cube','default.default','[n] ./*[1]/*[1]/*[1]; [t] "cube" (pitch:0.35); [p] (pause:300)','self::span[@class="msup"]','./*[1]/*[2]/*[1][text()=3]');defineRuleAlias('mj-cube','self::span[@class="msup"]','./*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]','count(./*[1]/*[2]/*[1]/*)=1','./*[1]/*[2]/*[1]/*[1][text()=3]');defineRuleAlias('mj-cube','self::span[@class="msubsup"]','CQFmathmlmsup','./*[1]/*[2]/*[1][text()=3]');defineRuleAlias('mj-cube','self::span[@class="msubsup"]','CQFmathmlmsup','./*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]','count(./*[1]/*[2]/*[1]/*)=1','./*[1]/*[2]/*[1]/*[1][text()=3]');defineRule('mj-square-sub','default.default','[n] ./*[1]/*[1]/*[1]; [t] "sub"; [n] ./*[1]/*[3]/*[1] (pitch:-0.35); '+'[p] (pause:300); [t] "square" (pitch:0.35); [p] (pause:400)','self::span[@class="msubsup"]','./*[1]/*[2]/*[1][text()=2]');defineRuleAlias('mj-square-sub','self::span[@class="msubsup"]','./*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]','count(./*[1]/*[2]/*[1]/*)=1','./*[1]/*[2]/*[1]/*[1][text()=2]');defineRule('mj-cube-sub','default.default','[n] ./*[1]/*[1]/*[1]; [t] "sub"; [n] ./*[1]/*[3]/*[1] (pitch:-0.35); '+'[p] (pause:300); [t] "cube" (pitch:0.35); [p] (pause:400)','self::span[@class="msubsup"]','./*[1]/*[2]/*[1][text()=3]');defineRuleAlias('mj-cube-sub','self::span[@class="msubsup"]','./*[1]/*[2]/*[1]=./*[1]/*[2]/span[@class="mrow"]','count(./*[1]/*[2]/*[1]/*)=1','./*[1]/*[2]/*[1]/*[1][text()=3]');};cvox.MathmlStoreRules.initSemanticRules_=function(){defineRule('stree','default.default','[n] ./*[1]','self::stree');defineRule('multrel','default.default','[t] "multirelation"; [m] children/* (sepFunc:CTXFcontentIterator)','self::multirel');defineRule('variable-equality','default.default','[t] "equation sequence"; [m] ./children/* '+'(context:"part",ctxtFunc:CTXFnodeCounter,separator:./text())','self::relseq[@role="equality"]','count(./children/*)>2','./children/punct[@role="ellipsis"]');defineRule('multi-equality','default.default','[t] "equation sequence"; [m] ./children/* '+'(context:"part",ctxtFunc:CTXFnodeCounter,separator:./text())','self::relseq[@role="equality"]','count(./children/*)>2');defineRule('multi-equality','default.short','[t] "equation sequence"; [m] ./children/* '+'(separator:./text())','self::relseq[@role="equality"]','count(./children/*)>2');defineRule('equality','default.default','[t] "equation"; [t] "left hand side"; [n] children/*[1];'+'[p] (pause:200); [n] text() (pause:200);'+'[t] "right hand side"; [n] children/*[2]','self::relseq[@role="equality"]','count(./children/*)=2');defineRule('simple-equality','default.default','[n] children/*[1]; [p] (pause:200); [n] text() (pause:200);'+'[n] children/*[2]','self::relseq[@role="equality"]','count(./children/*)=2','./children/identifier or ./children/number');defineRule('simple-equality2','default.default','[n] children/*[1]; [p] (pause:200); [n] text() (pause:200);'+'[n] children/*[2]','self::relseq[@role="equality"]','count(./children/*)=2','./children/function or ./children/appl');defineRule('multrel','default.default','[m] children/* (separator:./text())','self::relseq');defineRule('binary-operation','default.default','[m] children/* (separator:text());','self::infixop');defineRule('variable-addition','default.default','[t] "sum with variable number of summands";'+'[p] (pause:400); [m] children/* (separator:./text())','self::infixop[@role="addition"]','count(children/*)>2','children/punct[@role="ellipsis"]');defineRule('multi-addition','default.default','[t] "sum with,"; [t] count(./children/*); [t] ", summands";'+'[p] (pause:400); [m] ./children/* (separator:./text())','self::infixop[@role="addition"]','count(./children/*)>2');defineRule('prefix','default.default','[t] "prefix"; [n] text(); [t] "of" (pause 150);'+'[n] children/*[1]','self::prefixop');defineRule('negative','default.default','[t] "negative"; [n] children/*[1]','self::prefixop','self::prefixop[@role="negative"]');defineRule('postfix','default.default','[n] children/*[1]; [t] "postfix"; [n] text() (pause 300)','self::postfixop');defineRule('identifier','default.default','[n] text()','self::identifier');defineRule('number','default.default','[n] text()','self::number');defineRule('fraction','default.default','[p] (pause:250); [n] children/*[1] (pitch:0.3); [p] (pause:250);'+' [t] "divided by"; [n] children/*[2] (pitch:-0.3); [p] (pause:400)','self::fraction');defineRule('superscript','default.default','[n] children/*[1]; [t] "super"; [n] children/*[2] (pitch:0.35);'+'[p] (pause:300)','self::superscript');defineRule('subscript','default.default','[n] children/*[1]; [t] "sub"; [n] children/*[2] (pitch:-0.35);'+'[p] (pause:300)','self::subscript');defineRule('ellipsis','default.default','[p] (pause:200); [t] "dot dot dot"; [p] (pause:300)','self::punct','self::punct[@role="ellipsis"]');defineRule('fence-single','default.default','[n] text()','self::punct','self::punct[@role="openfence"]');defineRuleAlias('fence-single','self::punct','self::punct[@role="closefence"]');defineRuleAlias('fence-single','self::punct','self::punct[@role="vbar"]');defineRuleAlias('fence-single','self::punct','self::punct[@role="application"]');defineRule('omit-punct','default.default','[p] (pause:200);','self::punct');defineRule('omit-empty','default.default','','self::empty');defineRule('fences-open-close','default.default','[p] (pause:100); [t] "open"; [n] children/*[1]; [p] (pause:200);'+'[t] "close"','self::fenced[@role="leftright"]');defineRule('fences-open-close-in-appl','default.default','[p] (pause:100); [n] children/*[1]; [p] (pause:200);','self::fenced[@role="leftright"]','./parent::children/parent::appl');defineRule('fences-neutral','default.default','[p] (pause:100); [t] "absolute value of"; [n] children/*[1];'+'[p] (pause:350);','self::fenced','self::fenced[@role="neutral"]');defineRule('omit-fences','default.default','[p] (pause:500); [n] children/*[1]; [p] (pause:200);','self::fenced');defineRule('matrix','default.default','[t] "matrix"; [m] children/* '+'(ctxtFunc:CTXFnodeCounter,context:"row",pause:100)','self::matrix');defineRule('matrix-row','default.default','[m] children/* (ctxtFunc:CTXFnodeCounter,context:"column",pause:100)','self::row[@role="matrix"]');defineRule('matrix-cell','default.default','[n] children/*[1]','self::cell[@role="matrix"]');defineRule('vector','default.default','[t] "vector"; [m] children/* '+'(ctxtFunc:CTXFnodeCounter,context:"element",pause:100)','self::vector');defineRule('cases','default.default','[t] "case statement"; [m] children/* '+'(ctxtFunc:CTXFnodeCounter,context:"case",pause:100)','self::cases');defineRule('cases-row','default.default','[m] children/*','self::row[@role="cases"]');defineRule('cases-cell','default.default','[n] children/*[1]','self::cell[@role="cases"]');defineRule('row','default.default','[m] ./* (ctxtFunc:CTXFnodeCounter,context:"column",pause:100)','self::row"');defineRule('cases-end','default.default','[t] "case statement"; '+'[m] children/* (ctxtFunc:CTXFnodeCounter,context:"case",pause:100);'+'[t] "end cases"','self::cases','following-sibling::*');defineRule('multiline','default.default','[t] "multiline equation";'+'[m] children/* (ctxtFunc:CTXFnodeCounter,context:"line",pause:100)','self::multiline');defineRule('line','default.default','[m] children/*','self::line');defineRule('table','default.default','[t] "multiline equation";'+'[m] children/* (ctxtFunc:CTXFnodeCounter,context:"row",pause:200)','self::table');defineRule('table-row','default.default','[m] children/* (pause:100)','self::row[@role="table"]');defineRuleAlias('cases-cell','self::cell[@role="table"]');defineRule('end-punct','default.default','[m] children/*; [p] (pause:300)','self::punctuated','@role="endpunct"');defineRule('start-punct','default.default','[n] content/*[1]; [p] (pause:200); [m] children/*','self::punctuated','@role="startpunct"');defineRule('integral-punct','default.default','[n] children/*[1] (rate:0.2); [n] children/*[3] (rate:0.2)','self::punctuated','@role="integral"');defineRule('punctuated','default.default','[m] children/* (pause:100)','self::punctuated');defineRule('function','default.default','[n] text()','self::function');defineRule('appl','default.default','[n] children/*[1]; [n] content/*[1]; [n] children/*[2]','self::appl');defineRule('limboth','default.default','[n] children/*[1]; [t] "from"; [n] children/*[2]; [t] "to";'+'[n] children/*[3]','self::limboth');defineRule('sum-only','default.default','[n] children/*[1]; [p] (pause 100); [t] "over"; [n] children/*[2];'+'[p] (pause 250);','self::limboth','self::limboth[@role="sum"]');defineRule('limlower','default.default','[n] children/*[1]; [t] "over"; [n] children/*[2];','self::limlower');defineRule('limupper','default.default','[n] children/*[1]; [t] "under"; [n] children/*[2];','self::limupper');defineRule('largeop','default.default','[n] text()','self::largeop');defineRule('bigop','default.default','[n] children/*[1]; [p] (pause 100); [t] "over"; [n] children/*[2];'+'[p] (pause 250);','self::bigop');defineRule('integral','default.default','[n] children/*[1]; [p] (pause 100); [n] children/*[2]; [p] (pause 200);'+'[n] children/*[3] (rate:0.35);','self::integral');defineRule('sqrt','default.default','[t] "Square root of"; [n] children/*[1] (rate:0.2); [p] (pause:400)','self::sqrt');defineRule('square','default.default','[n] children/*[1]; [t] "square" (pitch:0.35); [p] (pause:300)','self::superscript','children/*[2][text()=2]');defineRule('text-no-mult','default.default','[n] children/*[1]; [p] (pause:200); [n] children/*[2]','self::infixop','children/text');};});goog.provide('cvox.MathShifter');goog.require('cvox.AbstractShifter');goog.require('cvox.BrailleUtil');goog.require('cvox.CursorSelection');goog.require('cvox.DomUtil');goog.require('cvox.MathmlStore');goog.require('cvox.MathmlStoreRules');goog.require('cvox.NavDescription');goog.require('cvox.SpeechRuleEngine');goog.require('cvox.TraverseMath');cvox.MathShifter=function(sel){goog.base(this);this.level_=0;this.direction_=false;this.bumped_=false;cvox.TraverseMath.getInstance().initialize(sel.start.node);};goog.inherits(cvox.MathShifter,cvox.AbstractShifter);cvox.MathShifter.prototype.next=function(sel){var r=sel.isReversed();this.bumped_=!cvox.TraverseMath.getInstance().nextSibling(r);var attachedNode=cvox.TraverseMath.getInstance().getAttachedActiveNode();return attachedNode?cvox.CursorSelection.fromNode(attachedNode):sel;};cvox.MathShifter.prototype.sync=function(sel){var attachedNode=cvox.TraverseMath.getInstance().getAttachedActiveNode();return attachedNode?cvox.CursorSelection.fromNode(attachedNode):sel;};cvox.MathShifter.prototype.getName=function(){return Msgs.getMsg('math_shifter');};cvox.MathShifter.prototype.getDescription=function(prevSel,sel){var descs=cvox.SpeechRuleEngine.getInstance().evaluateNode(cvox.TraverseMath.getInstance().activeNode);if(this.bumped_&&descs.length>0){descs[0].pushEarcon(cvox.Earcon.WRAP_EDGE);}
return descs;};cvox.MathShifter.prototype.getBraille=function(prevSel,sel){return new cvox.NavBraille({text:cvox.BrailleUtil.getTemplated(prevSel.start.node,sel.start.node)});};cvox.MathShifter.prototype.getGranularityMsg=function(){return this.direction_?'up to level '+this.level_:'down to level '+this.level_;};cvox.MathShifter.prototype.makeLessGranular=function(){this.level_=this.level_>0?this.level_-1:0;this.direction_=true;this.bumped_=!cvox.TraverseMath.getInstance().nextParentChild(true);};cvox.MathShifter.prototype.makeMoreGranular=function(){this.direction_=false;this.bumped_=!cvox.TraverseMath.getInstance().nextParentChild(false);if(!this.bumped_){this.level_++;}};cvox.MathShifter.create=function(sel){if(cvox.DomPredicates.mathPredicate(cvox.DomUtil.getAncestors(sel.start.node))){var mathNode=cvox.DomUtil.getContainingMath(sel.end.node);cvox.TraverseMath.getInstance().initialize(mathNode);cvox.SpeechRuleEngine.getInstance().parameterize(cvox.MathmlStore.getInstance());var dynamicCstr=cvox.MathStore.createDynamicConstraint(cvox.TraverseMath.getInstance().domain,cvox.TraverseMath.getInstance().style);cvox.SpeechRuleEngine.getInstance().setDynamicConstraint(dynamicCstr);return new cvox.MathShifter(sel);}
return null;};cvox.MathShifter.prototype.getDomainMsg=function(){return cvox.TraverseMath.getInstance().domain;};goog.provide('cvox.SpokenMessage');goog.provide('cvox.SpokenMessages');goog.require('cvox.AbstractTts');goog.require('cvox.ChromeVox');cvox.SpokenMessage=function(){this.id=null;};cvox.SpokenMessages.messages=[];cvox.SpokenMessages.speakFlush=function(){cvox.SpokenMessages.speak(cvox.QueueMode.FLUSH);};cvox.SpokenMessages.speak=function(mode){for(var i=0;i<cvox.SpokenMessages.messages.length;++i){var message=cvox.SpokenMessages.messages[i];if(!message||!message.id)
throw'Invalid message received.';var finalText=Msgs.getMsg.apply(Msgs,message.id);cvox.ChromeVox.tts.speak(finalText,mode,cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);mode=cvox.QueueMode.QUEUE;}
cvox.SpokenMessages.messages=[];};cvox.SpokenMessages.andMessage=function(messageId){var newMessage=new cvox.SpokenMessage();newMessage.id=typeof(messageId)=='string'?[messageId]:messageId;cvox.SpokenMessages.messages.push(newMessage);return cvox.SpokenMessages;};cvox.SpokenMessages.andPause=function(){return cvox.SpokenMessages.andMessage('pause');};cvox.$m=cvox.SpokenMessages.andMessage;goog.provide('cvox.Widget');goog.require('cvox.AbstractEarcons');goog.require('cvox.ApiImplementation');goog.require('cvox.ChromeVox');goog.require('cvox.SpokenMessages');cvox.Widget.ref_;cvox.Widget=function(){this.active=false;this.initialFocus=null;this.initialNode=null;if(!cvox.Widget.ref_||!cvox.Widget.ref_.isActive()){cvox.Widget.ref_=this;}};cvox.Widget.prototype.isActive=function(){return this.active;};cvox.Widget.prototype.show=function(){if(this.isActive()){this.hide(true);}
this.onKeyDown=goog.bind(this.onKeyDown,this);this.onKeyPress=goog.bind(this.onKeyPress,this);window.addEventListener('keydown',this.onKeyDown,true);window.addEventListener('keypress',this.onKeyPress,true);this.initialNode=cvox.ChromeVox.navigationManager.getCurrentNode();this.initialFocus=document.activeElement;cvox.ChromeVox.stickyOverride=false;if(this.getNameMsg()&&this.getHelpMsg()){cvox.$m(this.getNameMsg()).andPause().andMessage(this.getHelpMsg()).speakFlush();}
cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_OPEN);this.active=true;};cvox.Widget.prototype.hide=function(opt_noSync){window.removeEventListener('keypress',this.onKeyPress,true);window.removeEventListener('keydown',this.onKeyDown,true);cvox.ChromeVox.stickyOverride=null;cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_CLOSE);if(!opt_noSync){this.initialNode=this.initialNode.nodeType==1?this.initialNode:this.initialNode.parentNode;cvox.ApiImplementation.syncToNode(this.initialNode,true,cvox.QueueMode.QUEUE);}
this.active=false;};cvox.Widget.prototype.toggle=function(){if(this.isActive()){this.hide();}else{this.show();}};cvox.Widget.prototype.getNameMsg=goog.abstractMethod;cvox.Widget.prototype.getHelpMsg=goog.abstractMethod;cvox.Widget.prototype.onKeyDown=function(evt){if(evt.keyCode==27){this.hide();evt.preventDefault();return true;}else if(evt.keyCode==9){this.hide();return true;}else if(evt.keyCode==17){cvox.ChromeVox.tts.stop();}
evt.stopPropagation();return true;};cvox.Widget.prototype.onKeyPress=function(evt){return false;};cvox.Widget.isActive=function(){return(cvox.Widget.ref_&&cvox.Widget.ref_.isActive())||false;};goog.provide('cvox.NavigationManager');goog.require('cvox.ActiveIndicator');goog.require('cvox.ChromeVox');goog.require('cvox.ChromeVoxEventSuspender');goog.require('cvox.CursorSelection');goog.require('cvox.DescriptionUtil');goog.require('cvox.DomUtil');goog.require('cvox.FindUtil');goog.require('cvox.Focuser');goog.require('cvox.Interframe');goog.require('cvox.MathShifter');goog.require('cvox.NavBraille');goog.require('cvox.NavDescription');goog.require('cvox.NavigationHistory');goog.require('cvox.NavigationShifter');goog.require('cvox.NavigationSpeaker');goog.require('cvox.PageSelection');goog.require('cvox.SelectionUtil');goog.require('cvox.TableShifter');goog.require('cvox.TraverseMath');goog.require('cvox.Widget');cvox.NavigationManager=function(){this.addInterframeListener_();this.reset();this.iframeRetries_=0;};cvox.NavigationManager.prototype.storeOn=function(store){store['reversed']=this.isReversed();store['keepReading']=this.keepReading_;store['findNext']=this.predicate_;this.shifter_.storeOn(store);};cvox.NavigationManager.prototype.readFrom=function(store){this.curSel_.setReversed(store['reversed']);this.shifter_.readFrom(store);this.keepReading_=store['keepReading'];};cvox.NavigationManager.prototype.reset=function(){this.navSpeaker_=new cvox.NavigationSpeaker();this.shifterTypes_=[cvox.NavigationShifter,cvox.TableShifter,cvox.MathShifter];this.shifterStack_=[];this.shifter_=new cvox.NavigationShifter();this.curSel_=document.activeElement!=document.body?(cvox.CursorSelection.fromNode(document.activeElement)):this.shifter_.begin(this.curSel_,{reversed:false});this.prevSel_=this.curSel_.clone();this.skipped_=false;this.recovered_=false;this.keepReading_=false;this.pageEnd_=false;this.pageEndAnnounced_=false;this.enteredShifter_=false;this.exitedShifter_=false;this.ignoreIframesNoMatterWhat_=false;this.pageSel_=null;this.predicate_='';this.saveSel_=null;if(this.activeIndicator){this.activeIndicator.removeFromDom();}
this.activeIndicator=new cvox.ActiveIndicator();this.navigationHistory_=new cvox.NavigationHistory();this.focusRecovery_=window.location.protocol!='chrome:';this.iframeIdMap={};this.nextIframeId=1;if(document.activeElement!=document.body){this.sync();}
cvox.TraverseMath.getInstance();};cvox.NavigationManager.prototype.resolve=function(opt_predicate){if(!this.getFocusRecovery()){return true;}
var current=this.getCurrentNode();if(!this.navigationHistory_.becomeInvalid(current)){return true;}
if(this.hasNext_()){return true;}
var revert=this.navigationHistory_.revert(opt_predicate);if(!revert.current){return true;}
var newSel=cvox.CursorSelection.fromNode(revert.current);var context=cvox.CursorSelection.fromNode(revert.previous);newSel=newSel||cvox.CursorSelection.fromBody();context=context||cvox.CursorSelection.fromBody();newSel.setReversed(this.isReversed());this.updateSel(newSel,context);this.recovered_=true;return false;};cvox.NavigationManager.prototype.getFocusRecovery=function(){return this.focusRecovery_;};cvox.NavigationManager.prototype.setFocusRecovery=function(value){this.focusRecovery_=value;};cvox.NavigationManager.prototype.next_=function(iframes){if(this.tryBoundaries_(this.shifter_.next(this.curSel_),iframes)){this.pageSel_&&this.pageSel_.extend(this.curSel_);return true;}
return false;};cvox.NavigationManager.prototype.hasNext_=function(){if(this.shifterStack_.length>0){return true;}
var dummySel=this.curSel_.clone();var result=false;var dummyNavShifter=new cvox.NavigationShifter();dummyNavShifter.setGranularity(this.shifter_.getGranularity());dummyNavShifter.sync(dummySel);if(dummyNavShifter.next(dummySel)){result=true;}
return result;};cvox.NavigationManager.prototype.findNext=function(predicate,opt_predicateName,opt_initialNode){this.predicate_=opt_predicateName||'';this.resolve();this.shifter_=this.shifterStack_[0]||this.shifter_;this.shifterStack_=[];var ret=cvox.FindUtil.findNext(this.curSel_,predicate,opt_initialNode);if(!this.ignoreIframesNoMatterWhat_){this.tryIframe_(ret&&ret.start.node);}
if(ret){this.updateSelToArbitraryNode(ret.start.node);}
this.predicate_='';return ret;};cvox.NavigationManager.prototype.sync=function(){this.resolve();var ret=this.shifter_.sync(this.curSel_);if(ret){this.curSel_=ret;}};cvox.NavigationManager.prototype.syncAll=function(opt_skipText){this.sync();this.setFocus(opt_skipText);this.updateIndicator();};cvox.NavigationManager.prototype.clearPageSel=function(opt_announce){var hasSel=!!this.pageSel_;if(hasSel&&opt_announce){var announcement=Msgs.getMsg('clear_page_selection');cvox.ChromeVox.tts.speak(announcement,cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOTATION);}
this.pageSel_=null;return hasSel;};cvox.NavigationManager.prototype.togglePageSel=function(){this.pageSel_=this.pageSel_?null:new cvox.PageSelection(this.curSel_.setReversed(false));return!!this.pageSel_;};cvox.NavigationManager.prototype.getDescription=function(){if(this.getCurrentNode().hasAttribute&&this.getCurrentNode().hasAttribute('cvoxnodedesc')){var preDesc=cvox.ChromeVoxJSON.parse(this.getCurrentNode().getAttribute('cvoxnodedesc'));var currentDesc=new Array();for(var i=0;i<preDesc.length;++i){var inDesc=preDesc[i];currentDesc.push(new cvox.NavDescription({context:inDesc.context,text:inDesc.text,userValue:inDesc.userValue,annotation:inDesc.annotation}));}
return currentDesc;}
var desc=this.pageSel_?this.pageSel_.getDescription(this.shifter_,this.prevSel_,this.curSel_):this.shifter_.getDescription(this.prevSel_,this.curSel_);var earcons=[];if(this.skipped_){earcons.push(cvox.Earcon.SKIP);this.skipped_=false;}
if(this.recovered_){earcons.push(cvox.Earcon.RECOVER_FOCUS);this.recovered_=false;}
if(this.pageEnd_){earcons.push(cvox.Earcon.WRAP);this.pageEnd_=false;}
if(this.enteredShifter_){earcons.push(cvox.Earcon.OBJECT_ENTER);this.enteredShifter_=false;}
if(this.exitedShifter_){earcons.push(cvox.Earcon.OBJECT_EXIT);this.exitedShifter_=false;}
if(earcons.length>0&&desc.length>0){earcons.forEach(function(earcon){desc[0].pushEarcon(earcon);});}
return desc;};cvox.NavigationManager.prototype.getBraille=function(){return this.shifter_.getBraille(this.prevSel_,this.curSel_);};cvox.NavigationManager.prototype.performAction=function(name){var newSel=null;switch(name){case'enterShifter':case'enterShifterSilently':for(var i=this.shifterTypes_.length-1,shifterType;shifterType=this.shifterTypes_[i];i--){var shifter=shifterType.create(this.curSel_);if(shifter&&shifter.getName()!=this.shifter_.getName()){this.shifterStack_.push(this.shifter_);this.shifter_=shifter;this.sync();this.enteredShifter_=name!='enterShifterSilently';break;}else if(shifter&&this.shifter_.getName()==shifter.getName()){break;}}
break;case'exitShifter':if(this.shifterStack_.length==0){return false;}
this.shifter_=this.shifterStack_.pop();this.sync();this.exitedShifter_=true;break;case'exitShifterContent':if(this.shifterStack_.length==0){return false;}
this.updateSel(this.shifter_.performAction(name,this.curSel_));this.shifter_=this.shifterStack_.pop()||this.shifter_;this.sync();this.exitedShifter_=true;break;default:if(this.shifter_.hasAction(name)){return this.updateSel(this.shifter_.performAction(name,this.curSel_));}else{return false;}}
return true;};cvox.NavigationManager.prototype.getGranularityMsg=function(){return this.shifter_.getGranularityMsg();};cvox.NavigationManager.prototype.makeMoreGranular=function(opt_persist){this.shifter_.makeMoreGranular();this.sync();this.persistGranularity_(opt_persist);};cvox.NavigationManager.prototype.makeLessGranular=function(opt_persist){this.shifter_.makeLessGranular();this.sync();this.persistGranularity_(opt_persist);};cvox.NavigationManager.prototype.setGranularity=function(granularity,opt_force,opt_persist){if(!opt_force&&this.shifterStack_.length>0){return;}
this.shifter_=this.shifterStack_.shift()||this.shifter_;this.shifters_=[];this.shifter_.setGranularity(granularity);this.persistGranularity_(opt_persist);};cvox.NavigationManager.prototype.getGranularity=function(){var shifter=this.shifterStack_[0]||this.shifter_;return shifter.getGranularity();};cvox.NavigationManager.prototype.ensureSubnavigating=function(){if(!this.shifter_.isSubnavigating()){this.shifter_.ensureSubnavigating();this.sync();}};cvox.NavigationManager.prototype.ensureNotSubnavigating=function(){if(this.shifter_.isSubnavigating()){this.shifter_.ensureNotSubnavigating();this.sync();}};cvox.NavigationManager.prototype.speakDescriptionArray=function(descriptionArray,initialQueueMode,completionFunction,opt_personality,opt_category){if(opt_personality){descriptionArray.forEach(function(desc){if(!desc.personality){desc.personality=opt_personality;}});}
if(opt_category){descriptionArray.forEach(function(desc){if(!desc.category){desc.category=opt_category;}});}
this.navSpeaker_.speakDescriptionArray(descriptionArray,initialQueueMode,completionFunction);};cvox.NavigationManager.prototype.updatePosition=function(node){var msg=cvox.ChromeVox.position;msg[document.location.href]=cvox.DomUtil.elementToPoint(node);cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'position','value':JSON.stringify(msg)});};cvox.NavigationManager.prototype.finishNavCommand=function(opt_prefix,opt_setFocus,opt_queueMode,opt_callback){if(this.pageEnd_&&!this.pageEndAnnounced_){this.pageEndAnnounced_=true;cvox.ChromeVox.tts.stop();cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP);if(cvox.ChromeVox.verbosity===cvox.VERBOSITY_VERBOSE){var msg=Msgs.getMsg('wrapped_to_top');if(this.isReversed()){msg=Msgs.getMsg('wrapped_to_bottom');}
cvox.ChromeVox.tts.speak(msg,cvox.QueueMode.QUEUE,cvox.AbstractTts.PERSONALITY_ANNOTATION);}
return;}
if(this.enteredShifter_||this.exitedShifter_){opt_prefix=Msgs.getMsg('enter_content_say',[this.shifter_.getName()]);}
var descriptionArray=cvox.ChromeVox.navigationManager.getDescription();opt_setFocus=opt_setFocus===undefined?true:opt_setFocus;if(opt_setFocus){this.setFocus();}
this.updateIndicator();var queueMode=opt_queueMode||cvox.QueueMode.FLUSH;if(opt_prefix){cvox.ChromeVox.tts.speak(opt_prefix,queueMode,cvox.AbstractTts.PERSONALITY_ANNOTATION);queueMode=cvox.QueueMode.QUEUE;}
this.speakDescriptionArray(descriptionArray,queueMode,opt_callback||null,null,cvox.TtsCategory.NAV);cvox.ChromeVox.braille.write(this.getBraille());this.updatePosition(this.getCurrentNode());};cvox.NavigationManager.prototype.navigate=function(opt_ignoreIframes,opt_granularity){this.pageEndAnnounced_=false;if(this.pageEnd_){this.pageEnd_=false;this.syncToBeginning(opt_ignoreIframes);return true;}
if(!this.resolve()){return false;}
this.ensureNotSubnavigating();if(opt_granularity!==undefined&&(opt_granularity!==this.getGranularity()||this.shifterStack_.length>0)){this.setGranularity(opt_granularity,true);this.sync();}
return this.next_(!opt_ignoreIframes);};cvox.NavigationManager.prototype.subnavigate=function(){this.pageEndAnnounced_=false;if(!this.resolve()){return;}
this.ensureSubnavigating();this.next_(true);};cvox.NavigationManager.prototype.skip=function(){if(!this.keepReading_){return false;}
if(cvox.ChromeVox.host.hasTtsCallback()){this.skipped_=true;this.setReversed(false);this.startCallbackReading_(cvox.QueueMode.FLUSH);}
return true;};cvox.NavigationManager.prototype.startReading=function(queueMode){this.keepReading_=true;if(cvox.ChromeVox.host.hasTtsCallback()){this.startCallbackReading_(queueMode);}else{this.startNonCallbackReading_(queueMode);}
cvox.ChromeVox.stickyOverride=true;};cvox.NavigationManager.prototype.stopReading=function(stopTtsImmediately){this.keepReading_=false;this.navSpeaker_.stopReading=true;if(stopTtsImmediately){cvox.ChromeVox.tts.stop();}
cvox.ChromeVox.stickyOverride=null;};cvox.NavigationManager.prototype.isReading=function(){return this.keepReading_;};cvox.NavigationManager.prototype.startCallbackReading_=cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(queueMode){this.finishNavCommand('',true,queueMode,goog.bind(function(){if(this.prevReadingSel_==this.curSel_){this.stopReading();return;}
this.prevReadingSel_=this.curSel_;if(this.next_(true)&&this.keepReading_){this.startCallbackReading_(cvox.QueueMode.QUEUE);}},this));});cvox.NavigationManager.prototype.startNonCallbackReading_=cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(queueMode){if(!this.keepReading_){return;}
if(!cvox.ChromeVox.tts.isSpeaking()){this.finishNavCommand('',true,queueMode,null);if(!this.next_(true)){this.keepReading_=false;}}
window.setTimeout(goog.bind(this.startNonCallbackReading_,this),1000);});cvox.NavigationManager.prototype.getFullDescription=function(){if(this.pageSel_){return this.pageSel_.getFullDescription();}
return[cvox.DescriptionUtil.getDescriptionFromAncestors(cvox.DomUtil.getAncestors(this.curSel_.start.node),true,cvox.ChromeVox.verbosity)];};cvox.NavigationManager.prototype.setFocus=function(opt_skipText){if(this.pageSel_||(opt_skipText&&this.curSel_.start.node.constructor==Text)){return;}
cvox.Focuser.setFocus(this.curSel_.start.node);};cvox.NavigationManager.prototype.getCurrentNode=function(){return this.curSel_.absStart().node;};cvox.NavigationManager.prototype.addInterframeListener_=function(){var self=this;cvox.Interframe.addListener(function(message){if(message['command']!='enterIframe'&&message['command']!='exitIframe'){return;}
cvox.ChromeVox.serializer.readFrom(message);cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(){window.focus();if(message['findNext']){var predicateName=message['findNext'];var predicate=cvox.DomPredicates[predicateName];var found=self.findNext(predicate,predicateName,true);if(predicate&&(!found||found.start.node.tagName=='IFRAME')){return;}}else if(message['command']=='exitIframe'){var id=message['sourceId'];var iframeElement=self.iframeIdMap[id];var reversed=message['reversed'];var granularity=message['granularity'];if(iframeElement){self.updateSel(cvox.CursorSelection.fromNode(iframeElement));}
self.setReversed(reversed);self.sync();self.navigate();}else{self.syncToBeginning();if(!cvox.DomUtil.hasContent(document.body)){self.tryIframe_(null);return;}}
self.finishNavCommand('',true);if(self.keepReading_){self.startReading(cvox.QueueMode.FLUSH);}})();});};cvox.NavigationManager.prototype.updateIndicator=function(){this.activeIndicator.syncToCursorSelection(this.curSel_);};cvox.NavigationManager.prototype.updateIndicatorIfChanged=function(){this.activeIndicator.updateIndicatorIfChanged();};cvox.NavigationManager.prototype.showOrHideIndicator=function(active){if(!active){this.activeIndicator.removeFromDom();}};cvox.NavigationManager.prototype.collapseSelection=function(){this.curSel_.collapse();};cvox.NavigationManager.prototype.updateSelToArbitraryNode=function(node,opt_precise){if(node){this.setGranularity(cvox.NavigationShifter.GRANULARITIES.OBJECT,true);this.updateSel(cvox.CursorSelection.fromNode(node));if(!opt_precise){this.sync();}}else{this.syncToBeginning();}};cvox.NavigationManager.prototype.updateSel=function(sel,opt_context){if(sel){this.prevSel_=opt_context||this.curSel_;this.curSel_=sel;}
var currentNode=this.getCurrentNode();this.navigationHistory_.update(currentNode);return!!sel;};cvox.NavigationManager.prototype.setReversed=function(r){this.curSel_.setReversed(r);};cvox.NavigationManager.prototype.isReversed=function(){return this.curSel_.isReversed();};cvox.NavigationManager.prototype.tryBoundaries_=function(sel,iframes){iframes=(!!iframes&&!this.ignoreIframesNoMatterWhat_)||false;this.pageEnd_=false;if(iframes&&this.tryIframe_(sel&&sel.start.node)){return true;}
if(sel){this.updateSel(sel);return true;}
if(this.shifterStack_.length>0){return true;}
this.syncToBeginning(!iframes);this.clearPageSel(true);this.stopReading(true);this.pageEnd_=true;return false;};cvox.NavigationManager.prototype.tryIframe_=function(node){if(node==null&&cvox.Interframe.isIframe()){var message={'command':'exitIframe','reversed':this.isReversed(),'granularity':this.getGranularity()};cvox.ChromeVox.serializer.storeOn(message);cvox.Interframe.sendMessageToParentWindow(message);this.keepReading_=false;return true;}
if(node==null||node.tagName!='IFRAME'||!node.src){return false;}
var iframeElement=(node);var iframeId=undefined;for(var id in this.iframeIdMap){if(this.iframeIdMap[id]==iframeElement){iframeId=id;break;}}
if(iframeId==undefined){iframeId=this.nextIframeId;this.nextIframeId++;cvox.Interframe.sendIdToIFrame(iframeId,iframeElement,function(){this.iframeIdMap[iframeId]=iframeElement;this.iframeRetries_=0;}.bind(this));}
if(!this.iframeIdMap[iframeId]){this.iframeRetries_++;if(this.iframeRetries_>5){this.iframeRetries_=0;return false;}}
var message={'command':'enterIframe','id':iframeId};cvox.ChromeVox.serializer.storeOn(message);cvox.Interframe.sendMessageToIFrame(message,iframeElement);return true;};cvox.NavigationManager.prototype.syncToBeginning=function(opt_skipIframe){var ret=this.shifter_.begin(this.curSel_,{reversed:this.curSel_.isReversed()});if(!opt_skipIframe&&this.tryIframe_(ret&&ret.start.node)){return;}
this.updateSel(ret);};cvox.NavigationManager.prototype.ignoreIframesNoMatterWhat=function(){this.ignoreIframesNoMatterWhat_=true;};cvox.NavigationManager.prototype.saveSel=function(){this.saveSel_=this.curSel_;};cvox.NavigationManager.prototype.restoreSel=function(){this.curSel_=this.saveSel_||this.curSel_;};cvox.NavigationManager.prototype.persistGranularity_=function(opt_persist){opt_persist=opt_persist===undefined?false:opt_persist;if(opt_persist){cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'granularity','value':this.getGranularity()});}};goog.provide('cvox.SearchWidget');goog.require('cvox.AbstractEarcons');goog.require('cvox.ApiImplementation');goog.require('cvox.ChromeVox');goog.require('cvox.CursorSelection');goog.require('cvox.NavigationManager');goog.require('cvox.SpokenMessages');goog.require('cvox.Widget');cvox.SearchWidget=function(){this.containerNode_=null;this.txtNode_=null;this.PROMPT_='Search:';this.caseSensitive_=false;this.hasMatch_=false;goog.base(this);};goog.inherits(cvox.SearchWidget,cvox.Widget);goog.addSingletonGetter(cvox.SearchWidget);cvox.SearchWidget.prototype.show=function(){goog.base(this,'show');this.active=true;this.hasMatch_=false;cvox.ChromeVox.navigationManager.setGranularity(cvox.NavigationShifter.GRANULARITIES.OBJECT,true,false);cvox.ChromeVox.navigationManager.setReversed(false);this.focusRecovery_=cvox.ChromeVox.navigationManager.getFocusRecovery();cvox.ChromeVox.navigationManager.setFocusRecovery(false);var containerNode=this.createContainerNode_();this.containerNode_=containerNode;var overlayNode=this.createOverlayNode_();containerNode.appendChild(overlayNode);var promptNode=document.createElement('span');promptNode.innerHTML=this.PROMPT_;overlayNode.appendChild(promptNode);this.txtNode_=this.createTextAreaNode_();overlayNode.appendChild(this.txtNode_);document.body.appendChild(containerNode);this.txtNode_.focus();window.setTimeout(function(){containerNode.style['opacity']='1.0';},0);};cvox.SearchWidget.prototype.hide=function(opt_noSync){if(this.isActive()){var containerNode=this.containerNode_;containerNode.style.opacity='0.0';window.setTimeout(function(){document.body.removeChild(containerNode);},1000);this.txtNode_=null;cvox.SearchWidget.containerNode=null;cvox.ChromeVox.navigationManager.setFocusRecovery(this.focusRecovery_);this.active=false;}
cvox.$m('choice_widget_exited').andPause().andMessage(this.getNameMsg()).speakFlush();if(!this.hasMatch_||!opt_noSync){cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(this.initialNode);}
cvox.ChromeVoxEventSuspender.withSuspendedEvents(goog.bind(cvox.ChromeVox.navigationManager.syncAll,cvox.ChromeVox.navigationManager))(true);cvox.ChromeVox.navigationManager.speakDescriptionArray(cvox.ChromeVox.navigationManager.getDescription(),cvox.QueueMode.QUEUE,null,cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);var text=this.textFromCurrentDescription_();cvox.ChromeVox.braille.write(new cvox.NavBraille({text:text,startIndex:0,endIndex:0}));goog.base(this,'hide',true);};cvox.SearchWidget.prototype.getNameMsg=function(){return['search_widget_intro'];};cvox.SearchWidget.prototype.getHelpMsg=function(){return'search_widget_intro_help';};cvox.SearchWidget.prototype.onKeyDown=function(evt){if(!this.isActive()){return false;}
var searchStr=this.txtNode_.value;if(evt.keyCode==8){if(searchStr.length>0){searchStr=searchStr.substring(0,searchStr.length-1);this.txtNode_.value=searchStr;this.beginSearch_(searchStr);}else{cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(this.initialNode);cvox.ChromeVox.navigationManager.syncAll();}}else if(evt.keyCode==40){this.next_(searchStr,false);}else if(evt.keyCode==38){this.next_(searchStr,true);}else if(evt.keyCode==13){this.hide(true);}else if(evt.keyCode==27){this.hide(false);}else if(evt.ctrlKey&&evt.keyCode==67){this.toggleCaseSensitivity_();}else{return goog.base(this,'onKeyDown',evt);}
evt.preventDefault();evt.stopPropagation();return true;};cvox.SearchWidget.prototype.onKeyPress=function(evt){if(!this.isActive()){return false;}
this.txtNode_.value+=String.fromCharCode(evt.charCode);var searchStr=this.txtNode_.value;this.beginSearch_(searchStr);evt.preventDefault();evt.stopPropagation();return true;};cvox.SearchWidget.prototype.onNavigate=function(){};cvox.SearchWidget.prototype.getPredicate=function(){return null;};cvox.SearchWidget.prototype.nextResult=function(opt_reverse){if(!this.isActive()){return null;}
var searchStr=this.txtNode_.value;return this.next_(searchStr,opt_reverse);};cvox.SearchWidget.prototype.createContainerNode_=function(){var containerNode=document.createElement('div');containerNode.id='cvox-search';containerNode.style['position']='fixed';containerNode.style['top']='50%';containerNode.style['left']='50%';containerNode.style['-webkit-transition']='all 0.3s ease-in';containerNode.style['opacity']='0.0';containerNode.style['z-index']='2147483647';containerNode.setAttribute('aria-hidden','true');return containerNode;};cvox.SearchWidget.prototype.createOverlayNode_=function(){var overlayNode=document.createElement('div');overlayNode.style['position']='relative';overlayNode.style['left']='-50%';overlayNode.style['top']='-40px';overlayNode.style['line-height']='1.2em';overlayNode.style['font-size']='20px';overlayNode.style['padding']='30px';overlayNode.style['min-width']='150px';overlayNode.style['color']='#fff';overlayNode.style['background-color']='rgba(0, 0, 0, 0.7)';overlayNode.style['border-radius']='10px';return overlayNode;};cvox.SearchWidget.prototype.createTextAreaNode_=function(){var textNode=document.createElement('textarea');textNode.setAttribute('aria-hidden','true');textNode.setAttribute('rows','1');textNode.style['color']='#fff';textNode.style['background-color']='rgba(0, 0, 0, 0.7)';textNode.style['vertical-align']='middle';textNode.addEventListener('textInput',this.handleSearchChanged_,false);return textNode;};cvox.SearchWidget.prototype.toggleCaseSensitivity_=function(){if(this.caseSensitive_){cvox.SearchWidget.caseSensitive_=false;cvox.ChromeVox.tts.speak(Msgs.getMsg('ignoring_case'),cvox.QueueMode.FLUSH,null);}else{this.caseSensitive_=true;cvox.ChromeVox.tts.speak(Msgs.getMsg('case_sensitive'),cvox.QueueMode.FLUSH,null);}};cvox.SearchWidget.prototype.getNextResult_=function(searchStr){var r=cvox.ChromeVox.navigationManager.isReversed();if(!this.caseSensitive_){searchStr=searchStr.toLowerCase();}
cvox.ChromeVox.navigationManager.setGranularity(cvox.NavigationShifter.GRANULARITIES.OBJECT,true,false);do{if(this.getPredicate()){var retNode=this.getPredicate()(cvox.DomUtil.getAncestors(cvox.ChromeVox.navigationManager.getCurrentNode()));if(!retNode){continue;}}
var descriptions=cvox.ChromeVox.navigationManager.getDescription();for(var i=0;i<descriptions.length;i++){var targetStr=this.caseSensitive_?descriptions[i].text:descriptions[i].text.toLowerCase();var targetIndex=targetStr.indexOf(searchStr);if(targetIndex!=-1&&targetStr.length>searchStr.length){descriptions[i].text=cvox.DomUtil.collapseWhitespace(targetStr.substring(0,targetIndex))+', '+searchStr+', '+
targetStr.substring(targetIndex+searchStr.length);descriptions[i].text=cvox.DomUtil.collapseWhitespace(descriptions[i].text);}
if(targetIndex!=-1){return descriptions;}}
cvox.ChromeVox.navigationManager.setReversed(r);}while(cvox.ChromeVox.navigationManager.navigate(true,cvox.NavigationShifter.GRANULARITIES.OBJECT));return null;};cvox.SearchWidget.prototype.beginSearch_=function(searchStr){var result=this.getNextResult_(searchStr);this.outputSearchResult_(result,searchStr);this.onNavigate();};cvox.SearchWidget.prototype.next_=function(searchStr,opt_reversed){cvox.ChromeVox.navigationManager.setReversed(!!opt_reversed);var success=false;if(this.getPredicate()){success=cvox.ChromeVox.navigationManager.findNext((this.getPredicate()));cvox.ChromeVox.navigationManager.setReversed(!!opt_reversed);if(!success){cvox.ChromeVox.navigationManager.syncToBeginning();cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP);success=true;}}else{success=cvox.ChromeVox.navigationManager.navigate(true);}
var result=success?this.getNextResult_(searchStr):null;this.outputSearchResult_(result,searchStr);this.onNavigate();return result;};cvox.SearchWidget.prototype.outputSearchResult_=function(result,searchStr){cvox.ChromeVox.tts.stop();if(!result){cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP);this.hasMatch_=false;return;}
this.hasMatch_=true;cvox.ChromeVoxEventSuspender.withSuspendedEvents(goog.bind(cvox.ChromeVox.navigationManager.syncAll,cvox.ChromeVox.navigationManager))(true);cvox.ChromeVox.navigationManager.speakDescriptionArray(result,cvox.QueueMode.FLUSH,null,cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);cvox.ChromeVox.tts.speak(Msgs.getMsg('search_help_item'),cvox.QueueMode.QUEUE,cvox.AbstractTts.PERSONALITY_ANNOTATION);this.outputSearchResultToBraille_(searchStr);};cvox.SearchWidget.prototype.outputSearchResultToBraille_=function(searchStr){var text=this.textFromCurrentDescription_();var targetStr=this.caseSensitive_?text:text.toLowerCase();searchStr=this.caseSensitive_?searchStr:searchStr.toLowerCase();var targetIndex=targetStr.indexOf(searchStr);if(targetIndex==-1){console.log('Search string not in result when preparing for Braille.');return;}
var oldLength=text.length;text=Msgs.getMsg('mark_as_search_result_brl',[text]);var newLength=text.length;targetIndex+=(newLength-oldLength);cvox.ChromeVox.braille.write(new cvox.NavBraille({text:text,startIndex:(targetIndex+searchStr.length),endIndex:(targetIndex+searchStr.length)}));};cvox.SearchWidget.prototype.textFromCurrentDescription_=function(){var descriptions=cvox.ChromeVox.navigationManager.getDescription();var text='';for(var i=0;i<descriptions.length;i++){text+=descriptions[i].text+' ';}
return text;};cvox.SearchWidget.prototype.handleSearchChanged_=function(evt){var searchStr=evt.target.value+evt.data;cvox.SearchWidget.prototype.beginSearch_(searchStr);};goog.provide('cvox.OverlayWidget');goog.require('cvox.DomUtil');goog.require('cvox.SearchWidget');cvox.OverlayWidget=function(snippet){goog.base(this);this.snippet_=snippet;};goog.inherits(cvox.OverlayWidget,cvox.SearchWidget);cvox.OverlayWidget.prototype.show=function(){goog.base(this,'show');var host=document.createElement('DIV');host.innerHTML=this.snippet_;var hitPoint=cvox.DomUtil.elementToPoint(cvox.ChromeVox.navigationManager.getCurrentNode());host.style.position='absolute';host.style.left=String(hitPoint.x);host.style.top=String(hitPoint.y);document.body.appendChild(host);cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(host);this.host_=host;};cvox.OverlayWidget.prototype.hide=function(opt_noSync){this.host_.remove();goog.base(this,'hide');};cvox.OverlayWidget.prototype.onKeyDown=function(evt){goog.base(this,'onKeyDown',evt);if(evt.keyCode==13||evt.keyCode==27){return true;}
var r=cvox.ChromeVox.navigationManager.isReversed();if(!cvox.DomUtil.isDescendantOfNode(cvox.ChromeVox.navigationManager.getCurrentNode(),this.host_)){if(r){cvox.ChromeVox.navigationManager.syncToBeginning();}else{cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(this.host_);}
this.onNavigate();cvox.ChromeVox.navigationManager.speakDescriptionArray(cvox.ChromeVox.navigationManager.getDescription(),cvox.QueueMode.FLUSH,null);}
return false;};goog.provide('cvox.ContextMenuWidget');goog.require('cvox.ChromeVox');goog.require('cvox.OverlayWidget');goog.require('cvox.UserEventDetail');var CONTEXT_MENU_ATTR='contextMenuActions';var extractMenuList_=function(node){var curr=node;while(curr!==document){var menuListJSON=curr.getAttribute(CONTEXT_MENU_ATTR);if(menuListJSON){return JSON.parse(menuListJSON);}
curr=curr.parentNode;}
return null;};var getCurrentElement_=function(){var currNode=cvox.ChromeVox.navigationManager.getCurrentNode();while(currNode.nodeType!==Node.ELEMENT_NODE){currNode=currNode.parentNode;}
return currNode;};cvox.ContextMenuWidget=function(){goog.base(this,'');this.container_=document.createElement('div');this.triggerElement_=getCurrentElement_();this.menuList=extractMenuList_(this.triggerElement_);if(!this.menuList){console.log('No context menu found.');return;}
this.menuList.forEach(goog.bind(function(menuItem){if(menuItem['desc']||menuItem['cmd']){var desc=menuItem['desc'];var cmd=menuItem['cmd'];var menuElem=document.createElement('p');menuElem.id=cmd;menuElem.textContent=desc;menuElem.setAttribute('role','menuitem');this.container_.appendChild(menuElem);}},this));};goog.inherits(cvox.ContextMenuWidget,cvox.OverlayWidget);cvox.ContextMenuWidget.prototype.show=function(){if(this.menuList){goog.base(this,'show');this.host_.appendChild(this.container_);}};cvox.ContextMenuWidget.prototype.getNameMsg=function(){return['context_menu_intro'];};cvox.ContextMenuWidget.prototype.onKeyDown=function(evt){var ENTER_KEYCODE=13;if(evt.keyCode==ENTER_KEYCODE){var currentNode=cvox.ChromeVox.navigationManager.getCurrentNode();var cmd=currentNode.parentNode.id;var detail=new cvox.UserEventDetail({customCommand:cmd});var userEvt=detail.createEventObject();this.triggerElement_.dispatchEvent(userEvt);this.hide();evt.preventDefault();evt.stopPropagation();return true;}else{return goog.base(this,'onKeyDown',evt);}};goog.provide('cvox.SelectWidget');goog.require('cvox.OverlayWidget');cvox.SelectWidget=function(node){goog.base(this,'');this.selectNode_=node;};goog.inherits(cvox.SelectWidget,cvox.OverlayWidget);cvox.SelectWidget.prototype.show=function(){goog.base(this,'show');var container=document.createElement('div');container.setAttribute('role','menu');for(var i=0,item=null;item=this.selectNode_.options[i];i++){var newItem=document.createElement('p');newItem.innerHTML=item.innerHTML;newItem.id=i;newItem.setAttribute('role','menuitem');container.appendChild(newItem);}
this.host_.appendChild(container);var currentSelection=this.selectNode_.selectedIndex;if(typeof(currentSelection)=='number'){cvox.ChromeVox.syncToNode(container.children[currentSelection],true);}};cvox.SelectWidget.prototype.hide=function(opt_noSync){var evt=document.createEvent('Event');evt.initEvent('change',false,false);this.selectNode_.dispatchEvent(evt);goog.base(this,'hide',true);};cvox.SelectWidget.prototype.onNavigate=function(){var self=this;cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(){var selectedIndex=cvox.ChromeVox.navigationManager.getCurrentNode().parentNode.id;self.selectNode_.selectedIndex=selectedIndex;})();};cvox.SelectWidget.prototype.getNameMsg=function(){return['role_menu'];};goog.provide('cvox.BrailleDisplayState');goog.provide('cvox.BrailleKeyCommand');goog.provide('cvox.BrailleKeyEvent');cvox.BrailleKeyCommand={PAN_LEFT:'pan_left',PAN_RIGHT:'pan_right',LINE_UP:'line_up',LINE_DOWN:'line_down',TOP:'top',BOTTOM:'bottom',ROUTING:'routing',SECONDARY_ROUTING:'secondary_routing',DOTS:'dots',STANDARD_KEY:'standard_key'};cvox.BrailleKeyEvent={};cvox.BrailleKeyEvent.keyCodeToLegacyCode=function(code){return cvox.BrailleKeyEvent.legacyKeyCodeMap_[code];};cvox.BrailleKeyEvent.keyCodeToCharValue=function(keyCode){var SPECIAL_CODES={'Backspace':0x08,'Tab':0x09,'Enter':0x0A};return SPECIAL_CODES[keyCode]||keyCode.charCodeAt(0);};cvox.BrailleKeyEvent.legacyKeyCodeMap_={'Backspace':8,'Tab':9,'Enter':13,'Escape':27,'Home':36,'ArrowLeft':37,'ArrowUp':38,'ArrowRight':39,'ArrowDown':40,'PageUp':33,'PageDown':34,'End':35,'Insert':45,'Delete':46};(function(){for(var i=0;i<12;++i){cvox.BrailleKeyEvent.legacyKeyCodeMap_['F'+(i+1)]=112+i;}})();cvox.BrailleDisplayState;goog.provide('cvox.ChromeVoxEditableTextBase');goog.provide('cvox.TextChangeEvent');goog.provide('cvox.TypingEcho');goog.require('cvox.AbstractTts');goog.require('cvox.ChromeVox');goog.require('cvox.TtsInterface');goog.require('goog.i18n.MessageFormat');cvox.TextChangeEvent=function(newValue,newStart,newEnd,triggeredByUser){this.value=newValue;this.start=newStart;this.end=newEnd;this.triggeredByUser=triggeredByUser;if(this.start>this.end){var tempOffset=this.end;this.end=this.start;this.start=tempOffset;}};cvox.TypingEcho={CHARACTER:0,WORD:1,CHARACTER_AND_WORD:2,NONE:3,COUNT:4};cvox.TypingEcho.cycle=function(cur){return(cur+1)%cvox.TypingEcho.COUNT;};cvox.TypingEcho.shouldSpeakChar=function(typingEcho){return typingEcho==cvox.TypingEcho.CHARACTER_AND_WORD||typingEcho==cvox.TypingEcho.CHARACTER;};cvox.ChromeVoxEditableTextBase=function(value,start,end,isPassword,tts){this.value=value;this.start=start;this.end=end;this.isPassword=isPassword;this.tts=tts;this.multiline=false;this.lastChangeDescribed=false;};cvox.ChromeVoxEditableTextBase.prototype.setup=function(){};cvox.ChromeVoxEditableTextBase.prototype.teardown=function(){};cvox.ChromeVoxEditableTextBase.useIBeamCursor=cvox.ChromeVox.isMac;cvox.ChromeVoxEditableTextBase.eventTypingEcho=false;cvox.ChromeVoxEditableTextBase.prototype.maxShortPhraseLen=60;cvox.ChromeVoxEditableTextBase.prototype.getLineIndex=function(index){return 0;};cvox.ChromeVoxEditableTextBase.prototype.getLineStart=function(index){return 0;};cvox.ChromeVoxEditableTextBase.prototype.getLineEnd=function(index){return this.value.length;};cvox.ChromeVoxEditableTextBase.prototype.getLine=function(index){var lineStart=this.getLineStart(index);var lineEnd=this.getLineEnd(index);return this.value.substr(lineStart,lineEnd-lineStart);};cvox.ChromeVoxEditableTextBase.prototype.isWhitespaceChar=function(ch){return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';};cvox.ChromeVoxEditableTextBase.prototype.isWordBreakChar=function(ch){return!!ch.match(/^\W$/);};cvox.ChromeVoxEditableTextBase.prototype.shouldDescribeChange=function(evt){if(evt.value==this.value&&evt.start==this.start&&evt.end==this.end){return false;}
return true;};cvox.ChromeVoxEditableTextBase.prototype.speak=function(str,opt_triggeredByUser,opt_personality){if(!str){return;}
var queueMode=cvox.QueueMode.QUEUE;if(opt_triggeredByUser===true){queueMode=cvox.QueueMode.FLUSH;}
this.tts.speak(str,queueMode,opt_personality||{});};cvox.ChromeVoxEditableTextBase.prototype.changed=function(evt){evt.value=evt.value.replace('\u00a0',' ');if(!this.shouldDescribeChange(evt)){this.lastChangeDescribed=false;return;}
if(evt.value==this.value){this.describeSelectionChanged(evt);}else{this.describeTextChanged(evt);}
this.lastChangeDescribed=true;this.value=evt.value;this.start=evt.start;this.end=evt.end;};cvox.ChromeVoxEditableTextBase.prototype.describeSelectionChanged=function(evt){if(this.isPassword){this.speak((new goog.i18n.MessageFormat(Msgs.getMsg('bullet')).format({'COUNT':1})),evt.triggeredByUser);return;}
if(evt.start==evt.end){if(this.start!=this.end){this.speak(Msgs.getMsg('Unselected'),evt.triggeredByUser);}else if(this.getLineIndex(this.start)!=this.getLineIndex(evt.start)){var lineValue=this.getLine(this.getLineIndex(evt.start));if(lineValue==''){lineValue=Msgs.getMsg('text_box_blank');}else if(/^\s+$/.test(lineValue)){lineValue=Msgs.getMsg('text_box_whitespace');}
this.speak(lineValue,evt.triggeredByUser);}else if(this.start==evt.start+1||this.start==evt.start-1){if(!cvox.ChromeVoxEditableTextBase.useIBeamCursor){if(evt.start==this.value.length){if(cvox.ChromeVox.verbosity==cvox.VERBOSITY_VERBOSE){this.speak(Msgs.getMsg('end_of_text_verbose'),evt.triggeredByUser);}else{this.speak(Msgs.getMsg('end_of_text_brief'),evt.triggeredByUser);}}else{this.speak(this.value.substr(evt.start,1),evt.triggeredByUser,{'phoneticCharacters':evt.triggeredByUser});}}else{this.speak(this.value.substr(Math.min(this.start,evt.start),1),evt.triggeredByUser,{'phoneticCharacters':evt.triggeredByUser});}}else{this.speak(this.value.substr(Math.min(this.start,evt.start),Math.abs(this.start-evt.start)),evt.triggeredByUser);}}else{if(this.start+1==evt.start&&this.end==this.value.length&&evt.end==this.value.length){this.speak(this.value.substr(this.start,1),evt.triggeredByUser);this.speak(this.value.substr(evt.start));}else if(this.start==this.end){this.speak(this.value.substr(evt.start,evt.end-evt.start),evt.triggeredByUser);this.speak(Msgs.getMsg('selected'));}else if(this.start==evt.start&&this.end<evt.end){this.speak(this.value.substr(this.end,evt.end-this.end),evt.triggeredByUser);this.speak(Msgs.getMsg('added_to_selection'));}else if(this.start==evt.start&&this.end>evt.end){this.speak(this.value.substr(evt.end,this.end-evt.end),evt.triggeredByUser);this.speak(Msgs.getMsg('removed_from_selection'));}else if(this.end==evt.end&&this.start>evt.start){this.speak(this.value.substr(evt.start,this.start-evt.start),evt.triggeredByUser);this.speak(Msgs.getMsg('added_to_selection'));}else if(this.end==evt.end&&this.start<evt.start){this.speak(this.value.substr(this.start,evt.start-this.start),evt.triggeredByUser);this.speak(Msgs.getMsg('removed_from_selection'));}else{this.speak(this.value.substr(evt.start,evt.end-evt.start),evt.triggeredByUser);this.speak(Msgs.getMsg('selected'));}}};cvox.ChromeVoxEditableTextBase.prototype.describeTextChanged=function(evt){var personality={};if(evt.value.length<this.value.length){personality=cvox.AbstractTts.PERSONALITY_DELETED;}
if(this.isPassword){this.speak((new goog.i18n.MessageFormat(Msgs.getMsg('bullet')).format({'COUNT':1})),evt.triggeredByUser,personality);return;}
var value=this.value;var len=value.length;var newLen=evt.value.length;var autocompleteSuffix='';var evtValue=evt.value;var evtEnd=evt.end;if(evt.start<evtEnd&&evtEnd==newLen){autocompleteSuffix=evtValue.substr(evt.start);evtValue=evtValue.substr(0,evt.start);evtEnd=evt.start;}
var prefixLen=this.start;var suffixLen=len-this.end;if(newLen>=prefixLen+suffixLen+(evtEnd-evt.start)&&evtValue.substr(0,prefixLen)==value.substr(0,prefixLen)&&evtValue.substr(newLen-suffixLen)==value.substr(this.end)){if(!(cvox.ChromeVoxEditableContentEditable&&this instanceof cvox.ChromeVoxEditableContentEditable)||newLen<len||this.isWordBreakChar(evt.value[newLen-1]||'')){this.describeTextChangedHelper(evt,prefixLen,suffixLen,autocompleteSuffix,personality);}
return;}
prefixLen=evt.start;suffixLen=newLen-evtEnd;if(this.start==this.end&&evt.start==evtEnd&&evtValue.substr(0,prefixLen)==value.substr(0,prefixLen)&&evtValue.substr(newLen-suffixLen)==value.substr(len-suffixLen)){if(this.start==evt.start&&this.end==evt.end&&!cvox.ChromeVoxEditableTextBase.useIBeamCursor){this.speak(evt.value[evt.start],evt.triggeredByUser);}else{this.describeTextChangedHelper(evt,prefixLen,suffixLen,autocompleteSuffix,personality);}
return;}
evtValue+=autocompleteSuffix;if((evtValue.length==(value.length+1))||((evtValue.length+1)==value.length)){if(evtValue.length>value.length){if(evtValue.startsWith(value)){this.speak(evtValue[evtValue.length-1],evt.triggeredByUser,personality);return;}else if(evtValue.indexOf(value)==1){this.speak(evtValue[0],evt.triggeredByUser,personality);return;}}
if(evtValue.length<value.length){if(value.startsWith(evtValue)){this.speak(value[value.length-1],evt.triggeredByUser,personality);return;}else if(value.indexOf(evtValue)==1){this.speak(value[0],evt.triggeredByUser,personality);return;}}}
if(this.multiline){if(evt.value.length<this.value.length){this.speak(Msgs.getMsg('text_deleted'),evt.triggeredByUser,personality);}
return;}
if(newLen<=this.maxShortPhraseLen){this.describeTextChangedHelper(evt,0,0,'',personality);return;}
prefixLen=0;while(prefixLen<len&&prefixLen<newLen&&value[prefixLen]==evtValue[prefixLen]){prefixLen++;}
while(prefixLen>0&&!this.isWordBreakChar(value[prefixLen-1])){prefixLen--;}
suffixLen=0;while(suffixLen<(len-prefixLen)&&suffixLen<(newLen-prefixLen)&&value[len-suffixLen-1]==evtValue[newLen-suffixLen-1]){suffixLen++;}
while(suffixLen>0&&!this.isWordBreakChar(value[len-suffixLen])){suffixLen--;}
this.describeTextChangedHelper(evt,prefixLen,suffixLen,'',personality);};cvox.ChromeVoxEditableTextBase.prototype.describeTextChangedHelper=function(evt,prefixLen,suffixLen,autocompleteSuffix,opt_personality){var len=this.value.length;var newLen=evt.value.length;var deletedLen=len-prefixLen-suffixLen;var deleted=this.value.substr(prefixLen,deletedLen);var insertedLen=newLen-prefixLen-suffixLen;var inserted=evt.value.substr(prefixLen,insertedLen);var utterance='';var triggeredByUser=evt.triggeredByUser;if(insertedLen>1){utterance=inserted;}else if(insertedLen==1){if((cvox.ChromeVox.typingEcho==cvox.TypingEcho.WORD||cvox.ChromeVox.typingEcho==cvox.TypingEcho.CHARACTER_AND_WORD)&&this.isWordBreakChar(inserted)&&prefixLen>0&&!this.isWordBreakChar(evt.value.substr(prefixLen-1,1))){var index=prefixLen;while(index>0&&!this.isWordBreakChar(evt.value[index-1])){index--;}
if(index<prefixLen){utterance=evt.value.substr(index,prefixLen+1-index);}else{utterance=inserted;triggeredByUser=false;}}else if(cvox.ChromeVox.typingEcho==cvox.TypingEcho.CHARACTER||cvox.ChromeVox.typingEcho==cvox.TypingEcho.CHARACTER_AND_WORD){utterance=cvox.ChromeVoxEditableTextBase.eventTypingEcho?'':inserted;}}else if(deletedLen>1&&!autocompleteSuffix){utterance=deleted+', deleted';}else if(deletedLen==1){utterance=deleted;}
if(autocompleteSuffix&&utterance){utterance+=', '+autocompleteSuffix;}else if(autocompleteSuffix){utterance=autocompleteSuffix;}
if(utterance){this.speak(utterance,triggeredByUser,opt_personality);}};cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextCharacter=function(){return false;};cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousCharacter=function(){return false;};cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextWord=function(){return false;};cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousWord=function(){return false;};cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextLine=function(){return false;};cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousLine=function(){return false;};cvox.ChromeVoxEditableTextBase.prototype.moveCursorToNextParagraph=function(){return false;};cvox.ChromeVoxEditableTextBase.prototype.moveCursorToPreviousParagraph=function(){return false;};goog.provide('cvox.CommandStore');goog.require('cvox.PlatformFilter');cvox.CommandStore.categories=function(){var categorySet={};for(var cmd in cvox.CommandStore.CMD_WHITELIST){var struct=cvox.CommandStore.CMD_WHITELIST[cmd];if(struct.category){categorySet[struct.category]=true;}}
var ret=[];for(var category in categorySet){ret.push(category);}
return ret;};cvox.CommandStore.messageForCommand=function(command){return(cvox.CommandStore.CMD_WHITELIST[command]||{}).msgId;};cvox.CommandStore.categoryForCommand=function(command){return(cvox.CommandStore.CMD_WHITELIST[command]||{}).category;};cvox.CommandStore.commandsForCategory=function(category){var ret=[];for(var cmd in cvox.CommandStore.CMD_WHITELIST){var struct=cvox.CommandStore.CMD_WHITELIST[cmd];if(category==struct.category){ret.push(cmd);}}
return ret;};cvox.CommandStore.CMD_WHITELIST={'toggleStickyMode':{announce:false,msgId:'toggle_sticky_mode','disallowOOBE':true,category:'modifier_keys'},'toggleKeyPrefix':{announce:false,skipInput:true,msgId:'prefix_key','disallowOOBE':true,category:'modifier_keys'},'passThroughMode':{announce:false,msgId:'pass_through_key_description',category:'modifier_keys'},'stopSpeech':{announce:false,disallowContinuation:true,doDefault:true,msgId:'stop_speech_key',category:'controlling_speech'},'toggleChromeVox':{announce:false,platformFilter:cvox.PlatformFilter.WML,msgId:'toggle_chromevox_active',category:'modifier_keys'},'toggleChromeVoxVersion':{announce:false},'showNextUpdatePage':{msgId:'show_next_update_description',announce:false,'category':'help_commands'},'openChromeVoxMenus':{announce:false,msgId:'menus_title'},'decreaseTtsRate':{announce:false,msgId:'decrease_tts_rate',category:'controlling_speech'},'increaseTtsRate':{announce:false,msgId:'increase_tts_rate',category:'controlling_speech'},'decreaseTtsPitch':{announce:false,msgId:'decrease_tts_pitch',category:'controlling_speech'},'increaseTtsPitch':{announce:false,msgId:'increase_tts_pitch',category:'controlling_speech'},'decreaseTtsVolume':{announce:false,msgId:'decrease_tts_volume',category:'controlling_speech'},'increaseTtsVolume':{announce:false,msgId:'increase_tts_volume',category:'controlling_speech'},'cyclePunctuationEcho':{announce:false,msgId:'cycle_punctuation_echo',category:'controlling_speech'},'cycleTypingEcho':{announce:false,msgId:'cycle_typing_echo',category:'controlling_speech'},'toggleEarcons':{announce:true,msgId:'toggle_earcons',category:'controlling_speech'},'handleTab':{allowEvents:true,msgId:'handle_tab_next',disallowContinuation:true,category:'navigation'},'handleTabPrev':{allowEvents:true,msgId:'handle_tab_prev',disallowContinuation:true,category:'navigation'},'forward':{forward:true,announce:true,msgId:'forward',category:'navigation'},'backward':{backward:true,announce:true,msgId:'backward',category:'navigation'},'right':{forward:true,announce:true,msgId:'right',category:'navigation'},'left':{backward:true,announce:true,msgId:'left',category:'navigation'},'previousGranularity':{announce:true,msgId:'previous_granularity',category:'navigation'},'nextGranularity':{announce:true,msgId:'next_granularity',category:'navigation'},'previousCharacter':{backward:true,announce:true,msgId:'previous_character',skipInput:true,category:'navigation'},'nextCharacter':{forward:true,announce:true,msgId:'next_character',skipInput:true,category:'navigation'},'previousWord':{backward:true,announce:true,msgId:'previous_word',skipInput:true,category:'navigation'},'nextWord':{forward:true,announce:true,msgId:'next_word',skipInput:true,category:'navigation'},'previousLine':{backward:true,announce:true,msgId:'previous_line',category:'navigation'},'nextLine':{forward:true,announce:true,msgId:'next_line',category:'navigation'},'previousSentence':{backward:true,announce:true,msgId:'previous_sentence',skipInput:true,category:'navigation'},'nextSentence':{forward:true,announce:true,msgId:'next_sentence',skipInput:true,category:'navigation'},'previousObject':{backward:true,announce:true,msgId:'previous_object',skipInput:true,category:'navigation'},'nextObject':{forward:true,announce:true,msgId:'next_object',skipInput:true,category:'navigation'},'previousGroup':{backward:true,announce:true,msgId:'previous_group',skipInput:true,category:'navigation'},'nextGroup':{forward:true,announce:true,msgId:'next_group',skipInput:true,category:'navigation'},'jumpToTop':{forward:true,announce:true,msgId:'jump_to_top',category:'navigation'},'jumpToBottom':{backward:true,announce:true,msgId:'jump_to_bottom',category:'navigation'},'moveToStartOfLine':{forward:true,announce:true},'moveToEndOfLine':{backward:true,announce:true},'readFromHere':{forward:true,announce:false,msgId:'read_from_here',category:'navigation'},'performDefaultAction':{disallowContinuation:true,msgId:'perform_default_action',doDefault:true,skipInput:true,category:'navigation'},'forceClickOnCurrentItem':{announce:true,disallowContinuation:true,allowEvents:true,msgId:'force_click_on_current_item',category:'navigation'},'forceDoubleClickOnCurrentItem':{announce:true,allowEvents:true,disallowContinuation:true},'readLinkURL':{announce:false,msgId:'read_link_url',category:'information'},'readCurrentTitle':{announce:false,msgId:'read_current_title',category:'information'},'readCurrentURL':{announce:false,msgId:'read_current_url',category:'information'},'fullyDescribe':{announce:false,msgId:'fully_describe',category:'information'},'speakTimeAndDate':{announce:false,msgId:'speak_time_and_date',category:'information'},'toggleSelection':{announce:true,msgId:'toggle_selection',category:'information'},'toggleSearchWidget':{announce:false,disallowContinuation:true,msgId:'toggle_search_widget',category:'information'},'toggleKeyboardHelp':{announce:false,disallowContinuation:true,msgId:'show_power_key',category:'help_commands'},'help':{announce:false,msgId:'help','disallowOOBE':true,disallowContinuation:true,category:'help_commands'},'contextMenu':{announce:false,msgId:'show_context_menu',disallowContinuation:true},'showOptionsPage':{announce:false,disallowContinuation:true,msgId:'show_options_page','disallowOOBE':true,category:'help_commands'},'showKbExplorerPage':{announce:false,disallowContinuation:true,msgId:'show_kb_explorer_page','disallowOOBE':true,category:'help_commands'},'toggleBrailleCaptions':{announce:false,msgId:'braille_captions',category:'help_commands'},'showFormsList':{announce:false,disallowContinuation:true,nodeList:'formField',msgId:'show_forms_list',category:'overview'},'showHeadingsList':{announce:false,nodeList:'heading',disallowContinuation:true,msgId:'show_headings_list',category:'overview'},'showLandmarksList':{announce:false,nodeList:'landmark',disallowContinuation:true,msgId:'show_landmarks_list',category:'overview'},'showLinksList':{announce:false,nodeList:'link',disallowContinuation:true,msgId:'show_links_list',category:'overview'},'showTablesList':{announce:false,nodeList:'table',disallowContinuation:true,msgId:'show_tables_list',category:'overview'},'nextArticle':{forward:true,findNext:'article'},'nextButton':{forward:true,findNext:'button',msgId:'next_button',category:'jump_commands'},'nextCheckbox':{forward:true,findNext:'checkbox',msgId:'next_checkbox',category:'jump_commands'},'nextComboBox':{forward:true,findNext:'combobox',msgId:'next_combo_box',category:'jump_commands'},'nextControl':{forward:true,findNext:'control'},'nextEditText':{forward:true,findNext:'editText',msgId:'next_edit_text',category:'jump_commands'},'nextFormField':{forward:true,findNext:'formField',msgId:'next_form_field',category:'jump_commands'},'nextGraphic':{forward:true,findNext:'graphic',msgId:'next_graphic',category:'jump_commands'},'nextHeading':{forward:true,findNext:'heading',msgId:'next_heading',category:'jump_commands'},'nextHeading1':{forward:true,findNext:'heading1',msgId:'next_heading1',category:'jump_commands'},'nextHeading2':{forward:true,findNext:'heading2',msgId:'next_heading2',category:'jump_commands'},'nextHeading3':{forward:true,findNext:'heading3',msgId:'next_heading3',category:'jump_commands'},'nextHeading4':{forward:true,findNext:'heading4',msgId:'next_heading4',category:'jump_commands'},'nextHeading5':{forward:true,findNext:'heading5',msgId:'next_heading5',category:'jump_commands'},'nextHeading6':{forward:true,findNext:'heading6',msgId:'next_heading6',category:'jump_commands'},'nextLandmark':{forward:true,findNext:'landmark',msgId:'next_landmark',category:'jump_commands'},'nextLink':{forward:true,findNext:'link',msgId:'next_link',category:'jump_commands'},'nextList':{forward:true,findNext:'list',msgId:'next_list',category:'jump_commands'},'nextListItem':{forward:true,findNext:'listItem',msgId:'next_list_item',category:'jump_commands'},'nextMath':{forward:true,findNext:'math',msgId:'next_math',category:'jump_commands'},'nextMedia':{forward:true,findNext:'media',msgId:'next_media',category:'jump_commands'},'nextRadio':{forward:true,findNext:'radio',msgId:'next_radio',category:'jump_commands'},'nextSection':{forward:true,findNext:'section'},'nextSlider':{forward:true,findNext:'slider'},'nextTable':{forward:true,findNext:'table',msgId:'next_table',category:'jump_commands'},'nextVisitedLink':{forward:true,findNext:'visitedLink',msgId:'next_visited_link',category:'jump_commands'},'previousArticle':{backward:true,findNext:'article'},'previousButton':{backward:true,findNext:'button',msgId:'previous_button',category:'jump_commands'},'previousCheckbox':{backward:true,findNext:'checkbox',msgId:'previous_checkbox',category:'jump_commands'},'previousComboBox':{backward:true,findNext:'combobox',msgId:'previous_combo_box',category:'jump_commands'},'previousControl':{backward:true,findNext:'control'},'previousEditText':{backward:true,findNext:'editText',msgId:'previous_edit_text',category:'jump_commands'},'previousFormField':{backward:true,findNext:'formField',msgId:'previous_form_field',category:'jump_commands'},'previousGraphic':{backward:true,findNext:'graphic',msgId:'previous_graphic',category:'jump_commands'},'previousHeading':{backward:true,findNext:'heading',msgId:'previous_heading',category:'jump_commands'},'previousHeading1':{backward:true,findNext:'heading1',msgId:'previous_heading1',category:'jump_commands'},'previousHeading2':{backward:true,findNext:'heading2',msgId:'previous_heading2',category:'jump_commands'},'previousHeading3':{backward:true,findNext:'heading3',msgId:'previous_heading3',category:'jump_commands'},'previousHeading4':{backward:true,findNext:'heading4',msgId:'previous_heading4',category:'jump_commands'},'previousHeading5':{backward:true,findNext:'heading5',msgId:'previous_heading5',category:'jump_commands'},'previousHeading6':{backward:true,findNext:'heading6',msgId:'previous_heading6',category:'jump_commands'},'previousLandmark':{backward:true,findNext:'landmark',msgId:'previous_landmark',category:'jump_commands'},'previousLink':{backward:true,findNext:'link',msgId:'previous_link',category:'jump_commands'},'previousList':{backward:true,findNext:'list',msgId:'previous_list',category:'jump_commands'},'previousListItem':{backward:true,findNext:'listItem',msgId:'previous_list_item',category:'jump_commands'},'previousMath':{backward:true,findNext:'math',msgId:'previous_math',category:'jump_commands'},'previousMedia':{backward:true,findNext:'media',msgId:'previous_media',category:'jump_commands'},'previousRadio':{backward:true,findNext:'radio',msgId:'previous_radio',category:'jump_commands'},'previousSection':{backward:true,findNext:'section'},'previousSlider':{backward:true,findNext:'slider'},'previousTable':{backward:true,findNext:'table',msgId:'previous_table',category:'jump_commands'},'previousVisitedLink':{backward:true,findNext:'visitedLink',msgId:'previous_visited_link',category:'jump_commands'},'announceHeaders':{announce:false,msgId:'announce_headers',category:'tables'},'speakTableLocation':{announce:false,msgId:'speak_table_location',category:'tables'},'goToFirstCell':{announce:true,msgId:'skip_to_beginning',category:'tables'},'goToLastCell':{announce:true,msgId:'skip_to_end',category:'tables'},'goToRowFirstCell':{announce:true,msgId:'skip_to_row_beginning',category:'tables'},'goToRowLastCell':{announce:true,msgId:'skip_to_row_end',category:'tables'},'goToColFirstCell':{announce:true,msgId:'skip_to_col_beginning',category:'tables'},'goToColLastCell':{announce:true,msgId:'skip_to_col_end',category:'tables'},'previousRow':{backward:true,announce:true,skipInput:true},'previousCol':{backward:true,announce:true,skipInput:true},'nextRow':{forward:true,announce:true,skipInput:true},'nextCol':{forward:true,announce:true,skipInput:true},'enterShifter':{announce:true,msgId:'enter_content',category:'navigation'},'exitShifter':{announce:true,msgId:'exit_content',category:'navigation'},'exitShifterContent':{announce:true},'openLongDesc':{announce:false,msgId:'open_long_desc',category:'information'},'pauseAllMedia':{announce:false,msgId:'pause_all_media',category:'information'},'toggleSemantics':{announce:false,msgId:'toggle_semantics',category:'information'},'routing':{announce:false,allowEvents:true,msgId:'braille_routing',category:'braille'},'pan_left':{backward:true,announce:true,msgId:'braille_pan_left',category:'braille'},'pan_right':{forward:true,announce:true,msgId:'braille_pan_right',category:'braille'},'line_up':{backward:true,announce:true,msgId:'braille_line_up',category:'braille'},'line_down':{forward:true,announce:true,msgId:'braille_line_down',category:'braille'},'top':{forward:true,announce:true,msgId:'braille_top',category:'braille'},'bottom':{backward:true,announce:true,msgId:'braille_bottom',category:'braille'},'enableConsoleTts':{announce:false,msgId:'enable_tts_log',category:'developer'},'startHistoryRecording':{announce:false},'stopHistoryRecording':{announce:false},'autorunner':{announce:false},'debug':{announce:false},'nop':{announce:false}};cvox.CommandStore.NODE_INFO_MAP={'checkbox':{predicate:'checkboxPredicate',forwardError:'no_next_checkbox',backwardError:'no_previous_checkbox',typeMsg:'role_checkbox'},'radio':{predicate:'radioPredicate',forwardError:'no_next_radio_button',backwardError:'no_previous_radio_button',typeMsg:'role_radio'},'slider':{predicate:'sliderPredicate',forwardError:'no_next_slider',backwardError:'no_previous_slider',typeMsg:'role_slider'},'graphic':{predicate:'graphicPredicate',forwardError:'no_next_graphic',backwardError:'no_previous_graphic',typeMsg:'UNUSED'},'article':{predicate:'articlePredicate',forwardError:'no_next_ARTICLE',backwardError:'no_previous_ARTICLE',typeMsg:'TAG_ARTICLE'},'button':{predicate:'buttonPredicate',forwardError:'no_next_button',backwardError:'no_previous_button',typeMsg:'role_button'},'combobox':{predicate:'comboBoxPredicate',forwardError:'no_next_combo_box',backwardError:'no_previous_combo_box',typeMsg:'role_combobox'},'editText':{predicate:'editTextPredicate',forwardError:'no_next_edit_text',backwardError:'no_previous_edit_text',typeMsg:'input_type_text'},'heading':{predicate:'headingPredicate',forwardError:'no_next_heading',backwardError:'no_previous_heading',typeMsg:'role_heading'},'heading1':{predicate:'heading1Predicate',forwardError:'no_next_heading_1',backwardError:'no_previous_heading_1'},'heading2':{predicate:'heading2Predicate',forwardError:'no_next_heading_2',backwardError:'no_previous_heading_2'},'heading3':{predicate:'heading3Predicate',forwardError:'no_next_heading_3',backwardError:'no_previous_heading_3'},'heading4':{predicate:'heading4Predicate',forwardError:'no_next_heading_4',backwardError:'no_previous_heading_4'},'heading5':{predicate:'heading5Predicate',forwardError:'no_next_heading_5',backwardError:'no_previous_heading_5'},'heading6':{predicate:'heading6Predicate',forwardError:'no_next_heading_6',backwardError:'no_previous_heading_6'},'link':{predicate:'linkPredicate',forwardError:'no_next_link',backwardError:'no_previous_link',typeMsg:'role_link'},'table':{predicate:'tablePredicate',forwardError:'no_next_table',backwardError:'no_previous_table',typeMsg:'table_strategy'},'visitedLink':{predicate:'visitedLinkPredicate',forwardError:'no_next_visited_link',backwardError:'no_previous_visited_link',typeMsg:'role_link'},'list':{predicate:'listPredicate',forwardError:'no_next_list',backwardError:'no_previous_list',typeMsg:'role_list'},'listItem':{predicate:'listItemPredicate',forwardError:'no_next_list_item',backwardError:'no_previous_list_item',typeMsg:'role_listitem'},'formField':{predicate:'formFieldPredicate',forwardError:'no_next_form_field',backwardError:'no_previous_form_field',typeMsg:'role_form'},'landmark':{predicate:'landmarkPredicate',forwardError:'no_next_landmark',backwardError:'no_previous_landmark',typeMsg:'role_landmark'},'math':{predicate:'mathPredicate',forwardError:'no_next_math',backwardError:'no_previous_math',typeMsg:'math_expr'},'media':{predicate:'mediaPredicate',forwardError:'no_next_media_widget',backwardError:'no_previous_media_widget'},'section':{predicate:'sectionPredicate',forwardError:'no_next_section',backwardError:'no_previous_section'},'control':{predicate:'controlPredicate',forwardError:'no_next_control',backwardError:'no_previous_control'}};goog.provide('cvox.KeyboardHelpWidget');goog.require('cvox.ChromeVox');goog.require('cvox.CommandStore');goog.require('cvox.KeyUtil');goog.require('cvox.OverlayWidget');cvox.KeyboardHelpWidget=function(){goog.base(this,'');this.container_=document.createElement('div');var list=[];var callbacks=[];var keymap=cvox.ChromeVoxKbHandler.handlerKeyMap;keymap.bindings().forEach(goog.bind(function(pair){var command=pair.command;var keySeq=pair.sequence;var message=command;try{var id=cvox.CommandStore.messageForCommand(command);if(!id){return;}
message=Msgs.getMsg(id);}catch(e){}
var commandElement=document.createElement('p');commandElement.id=command;commandElement.setAttribute('role','menuitem');commandElement.textContent=message+' - '+cvox.KeyUtil.keySequenceToString(keySeq,true);this.container_.appendChild(commandElement);},this));};goog.inherits(cvox.KeyboardHelpWidget,cvox.OverlayWidget);goog.addSingletonGetter(cvox.KeyboardHelpWidget);cvox.KeyboardHelpWidget.prototype.show=function(){goog.base(this,'show');this.host_.appendChild(this.container_);};cvox.KeyboardHelpWidget.prototype.getNameMsg=function(){return['keyboard_help_intro'];};cvox.KeyboardHelpWidget.prototype.onKeyDown=function(evt){if(evt.keyCode==13){var currentCommand=cvox.ChromeVox.navigationManager.getCurrentNode().parentNode.id;this.hide();cvox.ChromeVoxEventSuspender.withSuspendedEvents(cvox.ChromeVoxUserCommands.commands[currentCommand])();evt.preventDefault();evt.stopPropagation();return true;}else{return goog.base(this,'onKeyDown',evt);}};goog.provide('cvox.NodeSearchWidget');goog.require('cvox.ChromeVox');goog.require('cvox.DomUtil');goog.require('cvox.SearchWidget');cvox.NodeSearchWidget=function(typeMsg,predicate){this.typeMsg_=typeMsg;this.predicate_=predicate;goog.base(this);};goog.inherits(cvox.NodeSearchWidget,cvox.SearchWidget);cvox.NodeSearchWidget.prototype.getNameMsg=function(){return['choice_widget_name',[Msgs.getMsg(this.typeMsg_)]];};cvox.NodeSearchWidget.prototype.getHelpMsg=function(){return'choice_widget_help';};cvox.NodeSearchWidget.prototype.getPredicate=function(){return this.predicate_;};cvox.NodeSearchWidget.create=function(typeMsg,predicate){return new cvox.NodeSearchWidget(typeMsg,predicate);};goog.provide('cvox.ChromeVoxUserCommands');goog.require('cvox.BrailleKeyCommand');goog.require('cvox.BrailleOverlayWidget');goog.require('cvox.ChromeVox');goog.require('cvox.ChromeVoxKbHandler');goog.require('cvox.CommandStore');goog.require('cvox.ConsoleTts');goog.require('cvox.ContextMenuWidget');goog.require('cvox.DomPredicates');goog.require('cvox.DomUtil');goog.require('cvox.FocusUtil');goog.require('cvox.History');goog.require('cvox.KeyboardHelpWidget');goog.require('cvox.NodeSearchWidget');goog.require('cvox.PlatformUtil');goog.require('cvox.SearchWidget');goog.require('cvox.SelectWidget');goog.require('cvox.TypingEcho');goog.require('cvox.UserEventDetail');goog.require('goog.object');cvox.ChromeVoxUserCommands.init_=function(){cvox.ChromeVoxKbHandler.commandHandler=function(commandName){var command=cvox.ChromeVoxUserCommands.commands[commandName];if(!command)
return undefined;var history=cvox.History.getInstance();history.enterUserCommand(commandName);var ret=command();history.exitUserCommand(commandName);return ret;};if(cvox.ChromeVoxUserCommands.commands){return;}else{cvox.ChromeVoxUserCommands.commands={};}
for(var cmd in cvox.CommandStore.CMD_WHITELIST){cvox.ChromeVoxUserCommands.commands[cmd]=cvox.ChromeVoxUserCommands.createCommand_(cmd);}};cvox.ChromeVoxUserCommands.commands;cvox.ChromeVoxUserCommands.wasMouseClicked=false;cvox.ChromeVoxUserCommands.enableCommandDispatchingToPage=true;cvox.ChromeVoxUserCommands.handleTabAction_=function(){cvox.ChromeVox.tts.stop();if(!cvox.ChromeVox.navigationManager.resolve(cvox.DomUtil.isFocusable)){cvox.ChromeVox.navigationManager.setFocus();return false;}
if(document.activeElement!=document.body){return true;}
var anchorNode=null;var focusNode=null;var sel=window.getSelection();if(!cvox.ChromeVoxUserCommands.wasMouseClicked){sel=null;}else{cvox.ChromeVoxUserCommands.wasMouseClicked=false;}
if(sel==null||sel.anchorNode==null||sel.focusNode==null){anchorNode=cvox.ChromeVox.navigationManager.getCurrentNode();focusNode=cvox.ChromeVox.navigationManager.getCurrentNode();}else{anchorNode=sel.anchorNode;focusNode=sel.focusNode;}
if(anchorNode==null||focusNode==null){return true;}
if(cvox.DomUtil.isFocusable(anchorNode)){anchorNode.focus();return true;}
if(cvox.DomUtil.isFocusable(focusNode)){focusNode.focus();return true;}
if(cvox.DomUtil.isFocusable(anchorNode.parentNode)){anchorNode.parentNode.focus();return true;}
if(cvox.DomUtil.isFocusable(focusNode.parentNode)){focusNode.parentNode.focus();return true;}
var bestGuess=anchorNode;var dummySpan=cvox.ChromeVoxUserCommands.createTabDummySpan_();bestGuess.parentNode.insertBefore(dummySpan,bestGuess);dummySpan.focus();return true;};cvox.ChromeVoxUserCommands.removeTabDummySpan=function(){var previousDummySpan=document.getElementById('ChromeVoxTabDummySpan');if(previousDummySpan&&document.activeElement!=previousDummySpan){previousDummySpan.parentNode.removeChild(previousDummySpan);}};cvox.ChromeVoxUserCommands.createTabDummySpan_=function(){var span=document.createElement('span');span.id='ChromeVoxTabDummySpan';span.tabIndex=-1;return span;};cvox.ChromeVoxUserCommands.createCommand_=function(cmd){return goog.bind(function(opt_kwargs){var cmdStruct=cvox.ChromeVoxUserCommands.lookupCommand_(cmd,opt_kwargs);return cvox.ChromeVoxUserCommands.dispatchCommand_(cmdStruct);},cvox.ChromeVoxUserCommands);};cvox.ChromeVoxUserCommands.dispatchCommand_=function(cmdStruct){if(cvox.Widget.isActive()){return true;}
if(!cvox.PlatformUtil.matchesPlatform(cmdStruct.platformFilter)||(cmdStruct.skipInput&&cvox.FocusUtil.isFocusInTextInputField())){return true;}
if(cvox.ChromeVoxUserCommands.enableCommandDispatchingToPage&&(cvox.UserEventDetail.JUMP_COMMANDS.indexOf(cmdStruct.command)!=-1)){var detail=new cvox.UserEventDetail({command:cmdStruct.command});var evt=detail.createEventObject();var currentNode=cvox.ChromeVox.navigationManager.getCurrentNode();if(!currentNode){currentNode=document.body;}
currentNode.dispatchEvent(evt);return false;}
return cvox.ChromeVoxUserCommands.doCommand_(cmdStruct);};cvox.ChromeVoxUserCommands.doCommand_=function(cmdStruct){if(cvox.Widget.isActive()){return true;}
if(!cvox.PlatformUtil.matchesPlatform(cmdStruct.platformFilter)||(cmdStruct.skipInput&&cvox.FocusUtil.isFocusInTextInputField())){return true;}
if(cmdStruct.disallowOOBE&&document.URL.match(/^chrome:\/\/oobe/i)){return true;}
var cmd=cmdStruct.command;if(!cmdStruct.allowEvents){cvox.ChromeVoxEventSuspender.enterSuspendEvents();}
if(cmdStruct.disallowContinuation){cvox.ChromeVox.navigationManager.stopReading(true);}
if(cmdStruct.forward){cvox.ChromeVox.navigationManager.setReversed(false);}else if(cmdStruct.backward){cvox.ChromeVox.navigationManager.setReversed(true);}
if(cmdStruct.findNext){cmd='find';cmdStruct.announce=true;}
var errorMsg='';var prefixMsg='';var ret=false;switch(cmd){case'handleTab':case'handleTabPrev':ret=cvox.ChromeVoxUserCommands.handleTabAction_();break;case'forward':case'backward':ret=!cvox.ChromeVox.navigationManager.navigate();break;case'right':case'left':cvox.ChromeVox.navigationManager.subnavigate();break;case'find':if(!cmdStruct.findNext){throw'Invalid find command.';}
var NodeInfoStruct=cvox.CommandStore.NODE_INFO_MAP[cmdStruct.findNext];var predicateName=NodeInfoStruct.predicate;var predicate=cvox.DomPredicates[predicateName];var error='';var wrap='';if(cmdStruct.forward){wrap=Msgs.getMsg('wrapped_to_top');error=Msgs.getMsg(NodeInfoStruct.forwardError);}else if(cmdStruct.backward){wrap=Msgs.getMsg('wrapped_to_bottom');error=Msgs.getMsg(NodeInfoStruct.backwardError);}
var found=null;var status=cmdStruct.status||cvox.UserEventDetail.Status.PENDING;var resultNode=cmdStruct.resultNode||null;switch(status){case cvox.UserEventDetail.Status.SUCCESS:if(resultNode){cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(resultNode,true);}
break;case cvox.UserEventDetail.Status.FAILURE:prefixMsg=error;break;default:found=cvox.ChromeVox.navigationManager.findNext(predicate,predicateName);if(!found){cvox.ChromeVox.navigationManager.saveSel();prefixMsg=wrap;cvox.ChromeVox.navigationManager.syncToBeginning();cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP);found=cvox.ChromeVox.navigationManager.findNext(predicate,predicateName,true);if(!found){prefixMsg=error;cvox.ChromeVox.navigationManager.restoreSel();}}
break;}
if(found&&found.start.node.tagName=='IFRAME'){cmdStruct.announce=false;}
break;case'previousGranularity':cvox.ChromeVox.navigationManager.makeLessGranular(true);prefixMsg=cvox.ChromeVox.navigationManager.getGranularityMsg();break;case'nextGranularity':cvox.ChromeVox.navigationManager.makeMoreGranular(true);prefixMsg=cvox.ChromeVox.navigationManager.getGranularityMsg();break;case'previousCharacter':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.CHARACTER);break;case'nextCharacter':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.CHARACTER);break;case'previousWord':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.WORD);break;case'nextWord':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.WORD);break;case'previousSentence':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.SENTENCE);break;case'nextSentence':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.SENTENCE);break;case'previousLine':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.LINE);break;case'nextLine':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.LINE);break;case'previousObject':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.OBJECT);break;case'nextObject':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.OBJECT);break;case'previousGroup':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.GROUP);break;case'nextGroup':cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.GROUP);break;case'previousRow':case'previousCol':cmd=cmd=='previousRow'?'nextRow':'nextCol';case'nextRow':case'nextCol':cvox.ChromeVox.navigationManager.performAction('enterShifterSilently');cvox.ChromeVox.navigationManager.performAction(cmd);break;case'moveToStartOfLine':case'moveToEndOfLine':cvox.ChromeVox.navigationManager.setGranularity(cvox.NavigationShifter.GRANULARITIES.LINE);cvox.ChromeVox.navigationManager.sync();cvox.ChromeVox.navigationManager.collapseSelection();break;case'readFromHere':cvox.ChromeVox.navigationManager.setGranularity(cvox.NavigationShifter.GRANULARITIES.OBJECT,true,true);cvox.ChromeVox.navigationManager.startReading(cvox.QueueMode.FLUSH);break;case'cycleTypingEcho':cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'typingEcho','value':cvox.TypingEcho.cycle(cvox.ChromeVox.typingEcho),'announce':true});break;case'jumpToTop':case cvox.BrailleKeyCommand.TOP:cvox.ChromeVox.navigationManager.syncToBeginning();break;case'jumpToBottom':case cvox.BrailleKeyCommand.BOTTOM:cvox.ChromeVox.navigationManager.syncToBeginning();break;case'stopSpeech':cvox.ChromeVox.navigationManager.stopReading(true);break;case'toggleKeyboardHelp':cvox.KeyboardHelpWidget.getInstance().toggle();break;case'help':cvox.ChromeVox.tts.stop();cvox.ChromeVox.host.sendToBackgroundPage({'target':'HelpDocs','action':'open'});break;case'contextMenu':var node=cvox.ChromeVox.navigationManager.getCurrentNode();if(node.tagName=='SELECT'&&!node.multiple){new cvox.SelectWidget(node).show();}else{var contextMenuWidget=new cvox.ContextMenuWidget();contextMenuWidget.toggle();}
break;case'showBookmarkManager':cvox.ChromeVox.host.sendToBackgroundPage({'target':'BookmarkManager','action':'open'});break;case'showOptionsPage':cvox.ChromeVox.tts.stop();cvox.ChromeVox.host.sendToBackgroundPage({'target':'Options','action':'open'});break;case'showKbExplorerPage':cvox.ChromeVox.tts.stop();cvox.ChromeVox.host.sendToBackgroundPage({'target':'KbExplorer','action':'open'});break;case'readLinkURL':var activeElement=document.activeElement;var currentSelectionAnchor=window.getSelection().anchorNode;var url='';if(activeElement.tagName=='A'){url=cvox.DomUtil.getLinkURL(activeElement);}else if(currentSelectionAnchor){url=cvox.DomUtil.getLinkURL(currentSelectionAnchor.parentNode);}
if(url!=''){cvox.ChromeVox.tts.speak(url,cvox.QueueMode.QUEUE);}else{cvox.ChromeVox.tts.speak(Msgs.getMsg('no_url_found'),cvox.QueueMode.QUEUE);}
break;case'readCurrentTitle':cvox.ChromeVox.tts.speak(document.title,cvox.QueueMode.QUEUE);break;case'readCurrentURL':cvox.ChromeVox.tts.speak(document.URL,cvox.QueueMode.QUEUE);break;case'performDefaultAction':if(cvox.DomPredicates.linkPredicate([document.activeElement])){if(cvox.DomUtil.isInternalLink(document.activeElement)){cvox.DomUtil.syncInternalLink(document.activeElement);cvox.ChromeVox.navigationManager.sync();cmdStruct.announce=true;}}
break;case'forceClickOnCurrentItem':prefixMsg=Msgs.getMsg('element_clicked');var targetNode=cvox.ChromeVox.navigationManager.getCurrentNode();cvox.DomUtil.clickElem(targetNode,false,false);break;case'forceDoubleClickOnCurrentItem':prefixMsg=Msgs.getMsg('element_double_clicked');var targetNode=cvox.ChromeVox.navigationManager.getCurrentNode();cvox.DomUtil.clickElem(targetNode,false,false,true);break;case'toggleChromeVox':cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'active','value':!cvox.ChromeVox.isActive});break;case'toggleChromeVoxVersion':case'showNextUpdatePage':cvox.ChromeVox.host.sendToBackgroundPage({'target':'next','action':'onCommand','command':cmd});break;case'fullyDescribe':var descs=cvox.ChromeVox.navigationManager.getFullDescription();cvox.ChromeVox.navigationManager.speakDescriptionArray(descs,cvox.QueueMode.FLUSH,null);break;case'speakTimeAndDate':var dateTime=new Date();cvox.ChromeVox.tts.speak(dateTime.toLocaleTimeString()+', '+dateTime.toLocaleDateString(),cvox.QueueMode.QUEUE);break;case'toggleSelection':var selState=cvox.ChromeVox.navigationManager.togglePageSel();prefixMsg=Msgs.getMsg(selState?'begin_selection':'end_selection');break;case'startHistoryRecording':cvox.History.getInstance().startRecording();break;case'stopHistoryRecording':cvox.History.getInstance().stopRecording();break;case'enableConsoleTts':cvox.ConsoleTts.getInstance().setEnabled(true);break;case'toggleBrailleCaptions':cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'brailleCaptions','value':!cvox.BrailleOverlayWidget.getInstance().isActive()});break;case'goToFirstCell':case'goToLastCell':case'goToRowFirstCell':case'goToRowLastCell':case'goToColFirstCell':case'goToColLastCell':case'announceHeaders':case'speakTableLocation':case'exitShifterContent':if(!cvox.DomPredicates.tablePredicate(cvox.DomUtil.getAncestors(cvox.ChromeVox.navigationManager.getCurrentNode()))){errorMsg='not_inside_table';}else if(!cvox.ChromeVox.navigationManager.performAction(cmd)){errorMsg='not_in_table_mode';}
break;case'enterShifter':case'exitShifter':cvox.ChromeVox.navigationManager.performAction(cmd);break;case'decreaseTtsRate':cvox.ChromeVox.tts.increaseOrDecreaseProperty(cvox.AbstractTts.RATE,false);break;case'increaseTtsRate':cvox.ChromeVox.tts.increaseOrDecreaseProperty(cvox.AbstractTts.RATE,true);break;case'decreaseTtsPitch':cvox.ChromeVox.tts.increaseOrDecreaseProperty(cvox.AbstractTts.PITCH,false);break;case'increaseTtsPitch':cvox.ChromeVox.tts.increaseOrDecreaseProperty(cvox.AbstractTts.PITCH,true);break;case'decreaseTtsVolume':cvox.ChromeVox.tts.increaseOrDecreaseProperty(cvox.AbstractTts.VOLUME,false);break;case'increaseTtsVolume':cvox.ChromeVox.tts.increaseOrDecreaseProperty(cvox.AbstractTts.VOLUME,true);break;case'cyclePunctuationEcho':cvox.ChromeVox.host.sendToBackgroundPage({'target':'TTS','action':'cyclePunctuationEcho'});break;case'toggleStickyMode':cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'sticky','value':!cvox.ChromeVox.isStickyPrefOn,'announce':true});break;case'toggleKeyPrefix':cvox.ChromeVox.keyPrefixOn=!cvox.ChromeVox.keyPrefixOn;break;case'passThroughMode':cvox.ChromeVox.passThroughMode=true;cvox.ChromeVox.tts.speak(Msgs.getMsg('pass_through_key'),cvox.QueueMode.QUEUE);break;case'toggleSearchWidget':cvox.SearchWidget.getInstance().toggle();break;case'toggleEarcons':prefixMsg=cvox.ChromeVox.earcons.toggle()?Msgs.getMsg('earcons_on'):Msgs.getMsg('earcons_off');break;case'showHeadingsList':case'showLinksList':case'showFormsList':case'showTablesList':case'showLandmarksList':if(!cmdStruct.nodeList){break;}
var nodeListStruct=cvox.CommandStore.NODE_INFO_MAP[cmdStruct.nodeList];cvox.NodeSearchWidget.create(nodeListStruct.typeMsg,cvox.DomPredicates[nodeListStruct.predicate]).show();break;case'openLongDesc':var currentNode=cvox.ChromeVox.navigationManager.getCurrentNode();if(cvox.DomUtil.hasLongDesc(currentNode)){cvox.ChromeVox.host.sendToBackgroundPage({'target':'OpenTab','url':currentNode.longDesc});}else{cvox.ChromeVox.tts.speak(Msgs.getMsg('no_long_desc'),cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOTATION);}
break;case'pauseAllMedia':var videos=document.getElementsByTagName('VIDEO');for(var i=0,mediaElem;mediaElem=videos[i];i++){mediaElem.pause();}
var audios=document.getElementsByTagName('AUDIO');for(var i=0,mediaElem;mediaElem=audios[i];i++){mediaElem.pause();}
break;case'toggleSemantics':if(cvox.TraverseMath.toggleSemantic()){cvox.ChromeVox.tts.speak(Msgs.getMsg('semantics_on'),cvox.QueueMode.QUEUE);}else{cvox.ChromeVox.tts.speak(Msgs.getMsg('semantics_off'),cvox.QueueMode.QUEUE);}
break;case cvox.BrailleKeyCommand.ROUTING:var braille=cmdStruct.content;if(braille){cvox.BrailleUtil.click(braille,cmdStruct.event.displayPosition);}
break;case cvox.BrailleKeyCommand.PAN_LEFT:case cvox.BrailleKeyCommand.LINE_UP:case cvox.BrailleKeyCommand.PAN_RIGHT:case cvox.BrailleKeyCommand.LINE_DOWN:cvox.ChromeVox.navigationManager.navigate(false,cvox.NavigationShifter.GRANULARITIES.LINE);break;case'debug':break;case'nop':break;default:throw'Command behavior not defined: '+cmd;}
if(errorMsg!=''){cvox.ChromeVox.tts.speak(Msgs.getMsg(errorMsg),cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOTATION);}else if(cvox.ChromeVox.navigationManager.isReading()){if(cmdStruct.disallowContinuation){cvox.ChromeVox.navigationManager.stopReading(true);}else if(cmd!='readFromHere'){cvox.ChromeVox.navigationManager.skip();}}else{if(cmdStruct.announce){cvox.ChromeVox.navigationManager.finishNavCommand(prefixMsg);}}
if(!cmdStruct.allowEvents){cvox.ChromeVoxEventSuspender.exitSuspendEvents();}
return!!cmdStruct.doDefault||ret;};cvox.ChromeVoxUserCommands.handleChromeVoxUserEvent=function(cvoxUserEvent){var detail=new cvox.UserEventDetail(cvoxUserEvent.detail);if(detail.command){cvox.ChromeVoxUserCommands.doCommand_(cvox.ChromeVoxUserCommands.lookupCommand_(detail.command,detail));}};cvox.ChromeVoxUserCommands.lookupCommand_=function(cmd,opt_kwargs){var cmdStruct=cvox.CommandStore.CMD_WHITELIST[cmd];if(!cmdStruct){throw'Invalid command: '+cmd;}
cmdStruct=goog.object.clone(cmdStruct);cmdStruct.command=cmd;if(opt_kwargs){goog.object.extend(cmdStruct,opt_kwargs);}
return cmdStruct;};cvox.ChromeVoxUserCommands.init_();goog.provide('cvox.BrailleInterface');goog.require('cvox.BrailleKeyCommand');goog.require('cvox.BrailleKeyEvent');goog.require('cvox.NavBraille');cvox.BrailleInterface=function(){};cvox.BrailleInterface.prototype.write=function(params){};goog.provide('cvox.BrailleTextHandler');goog.require('cvox.BrailleInterface');goog.require('cvox.BrailleUtil');goog.require('cvox.ChromeVox');goog.require('cvox.NavBraille');cvox.BrailleTextHandler=function(braille){this.braille_=braille;};cvox.BrailleTextHandler.prototype.changed=function(line,start,end,multiline,element,lineStart){var content;if(multiline){var spannable=cvox.BrailleUtil.createValue(line,start,end,lineStart);if(element){spannable.setSpan(element,0,line.length);}
content=new cvox.NavBraille({text:spannable,startIndex:start,endIndex:end});}else{if(cvox.ChromeVox.navigationManager){content=cvox.ChromeVox.navigationManager.getBraille();}}
if(content){this.braille_.write(content);}};goog.provide('cvox.ContentEditableExtractor');goog.require('cvox.Cursor');goog.require('cvox.TraverseUtil');cvox.ContentEditableExtractor=function(){this.text_='';this.start_=0;this.end_=0;this.lines_={};this.characterToLineMap_=[];};cvox.ContentEditableExtractor.prototype.update=function(element){var lines={0:{startIndex:0,endIndex:0}};var startCursor=new cvox.Cursor(element,0,'');var endCursor=startCursor.clone();var range=document.createRange();var rect;var lineIndex=0;var lastBottom=null;var text='';var textSize=0;var selectionStartIndex=-1;var selectionEndIndex=-1;var sel=window.getSelection();var selectionStart=new cvox.Cursor(sel.baseNode,sel.baseOffset,'');var selectionEnd=new cvox.Cursor(sel.extentNode,sel.extentOffset,'');var setStart=false;var setEnd=false;while(true){var entered=[];var left=[];var c=cvox.TraverseUtil.forwardsChar(endCursor,entered,left);var done=false;if(!c){done=true;}
for(var i=0;i<left.length&&!done;i++){if(left[i]==element){done=true;}}
if(done){break;}
range.setStart(startCursor.node,startCursor.index);range.setEnd(endCursor.node,endCursor.index);rect=range.getBoundingClientRect();if(!rect||rect.width==0||rect.height==0){continue;}
if(lastBottom!==null&&rect.bottom!=lastBottom&&textSize>0&&text.substr(-1).match(/\S/)&&c.match(/\S/)){text+='\n';textSize++;}
if(startCursor.node!=endCursor.node&&endCursor.index>0){range.setStart(endCursor.node,endCursor.index-1);rect=range.getBoundingClientRect();if(!rect||rect.width==0||rect.height==0){continue;}}
if(!setStart&&selectionStartIndex==-1&&endCursor.node==selectionStart.node&&endCursor.index>=selectionStart.index){if(endCursor.index>selectionStart.index){selectionStartIndex=textSize;}else{setStart=true;}}
if(!setEnd&&selectionEndIndex==-1&&endCursor.node==selectionEnd.node&&endCursor.index>=selectionEnd.index){if(endCursor.index>selectionEnd.index){selectionEndIndex=textSize;}else{setEnd=true;}}
if(lastBottom===null){lastBottom=rect.bottom;}else if(rect.bottom!=lastBottom){lines[lineIndex].endIndex=textSize;lineIndex++;lines[lineIndex]={startIndex:textSize,endIndex:textSize};lastBottom=rect.bottom;}
text+=c;textSize++;startCursor=endCursor.clone();if(setStart){selectionStartIndex=textSize;setStart=false;}
if(setEnd){selectionEndIndex=textSize;setEnd=false;}}
lines[lineIndex].endIndex=textSize;var characterToLineMap=[];for(var i=0;i<=lineIndex;i++){for(var j=lines[i].startIndex;j<=lines[i].endIndex;j++){characterToLineMap[j]=i;}}
this.text_=text;this.characterToLineMap_=characterToLineMap;this.lines_=lines;this.start_=selectionStartIndex>=0?selectionStartIndex:text.length;this.end_=selectionEndIndex>=0?selectionEndIndex:text.length;};cvox.ContentEditableExtractor.prototype.getText=function(){return this.text_;};cvox.ContentEditableExtractor.prototype.getStartIndex=function(){return this.start_;};cvox.ContentEditableExtractor.prototype.getEndIndex=function(){return this.end_;};cvox.ContentEditableExtractor.prototype.getLineIndex=function(index){return this.characterToLineMap_[index];};cvox.ContentEditableExtractor.prototype.getLineStart=function(index){return this.lines_[index].startIndex;};cvox.ContentEditableExtractor.prototype.getLineEnd=function(index){return this.lines_[index].endIndex;};goog.provide('cvox.ChromeVoxEditableContentEditable');goog.provide('cvox.ChromeVoxEditableElement');goog.provide('cvox.ChromeVoxEditableHTMLInput');goog.provide('cvox.ChromeVoxEditableTextArea');goog.provide('cvox.TextHandlerInterface');goog.require('cvox.BrailleTextHandler');goog.require('cvox.ChromeVoxEditableTextBase');goog.require('cvox.ContentEditableExtractor');goog.require('cvox.DomUtil');goog.require('cvox.EditableTextAreaShadow');goog.require('cvox.TextChangeEvent');goog.require('cvox.TtsInterface');cvox.TextHandlerInterface=function(){};cvox.TextHandlerInterface.prototype.changed=function(evt){};cvox.ChromeVoxEditableElement=function(node,value,start,end,isPassword,tts){goog.base(this,value,start,end,isPassword,tts);this.brailleHandler_=cvox.ChromeVox.braille?new cvox.BrailleTextHandler(cvox.ChromeVox.braille):undefined;this.node=node;this.justSpokeDescription_=false;};goog.inherits(cvox.ChromeVoxEditableElement,cvox.ChromeVoxEditableTextBase);cvox.ChromeVoxEditableElement.prototype.changed=function(evt){if(this.justSpokeDescription_&&this.value==evt.value){this.value=evt.value;this.start=evt.start;this.end=evt.end;this.justSpokeDescription_=false;}
goog.base(this,'changed',evt);if(this.lastChangeDescribed){this.brailleCurrentLine_();}};cvox.ChromeVoxEditableElement.prototype.speak=function(str,opt_triggeredByUser,opt_personality){if(this.node&&(document.activeElement!=this.node)){return;}
goog.base(this,'speak',str,opt_triggeredByUser,opt_personality);};cvox.ChromeVoxEditableElement.prototype.moveCursorToNextCharacter=function(){var node=this.node;node.selectionEnd++;node.selectionStart=node.selectionEnd;cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableElement.prototype.moveCursorToPreviousCharacter=function(){var node=this.node;node.selectionStart--;node.selectionEnd=node.selectionStart;cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableElement.prototype.moveCursorToNextWord=function(){var node=this.node;var length=node.value.length;var re=/\W+/gm;var substring=node.value.substring(node.selectionEnd);var match=re.exec(substring);if(match!==null&&match.index==0){match=re.exec(substring);}
var index=(match===null)?length:match.index+node.selectionEnd;node.selectionStart=node.selectionEnd=index;cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableElement.prototype.moveCursorToPreviousWord=function(){var node=this.node;var length=node.value.length;var re=/\W+/gm;var substring=node.value.substring(0,node.selectionStart);var index=0;while(re.exec(substring)!==null){if(re.lastIndex<node.selectionStart){index=re.lastIndex;}}
node.selectionStart=node.selectionEnd=index;cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableElement.prototype.moveCursorToNextParagraph=function(){var node=this.node;var length=node.value.length;var index=node.selectionEnd>=length?length:node.value.indexOf('\n',node.selectionEnd);if(index<0){index=length;}
node.selectionStart=node.selectionEnd=index+1;cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableElement.prototype.moveCursorToPreviousParagraph=function(){var node=this.node;var index=node.selectionStart<=0?0:node.value.lastIndexOf('\n',node.selectionStart-2)+1;if(index<0){index=0;}
node.selectionStart=node.selectionEnd=index;cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableElement.prototype.brailleCurrentLine_=function(){if(this.brailleHandler_){var lineIndex=this.getLineIndex(this.start);var line=this.getLine(lineIndex);if(this instanceof cvox.ChromeVoxEditableContentEditable){line=line.replace(/\u00A0/g,' ');}
var lineStart=this.getLineStart(lineIndex);var start=this.start-lineStart;var end=Math.min(this.end-lineStart,line.length);this.brailleHandler_.changed(line,start,end,this.multiline,this.node,lineStart);}};cvox.ChromeVoxEditableHTMLInput=function(node,tts){this.node=node;this.setup();goog.base(this,node,node.value,node.selectionStart,node.selectionEnd,node.type==='password',tts);};goog.inherits(cvox.ChromeVoxEditableHTMLInput,cvox.ChromeVoxEditableElement);cvox.ChromeVoxEditableHTMLInput.prototype.setup=function(){if(!this.node){return;}
if(!cvox.DomUtil.doesInputSupportSelection(this.node)){this.originalType=this.node.type;this.node.type='text';}};cvox.ChromeVoxEditableHTMLInput.prototype.teardown=function(){if(this.node&&this.originalType){this.node.type=this.originalType;}};cvox.ChromeVoxEditableHTMLInput.prototype.update=function(triggeredByUser){var newValue=this.node.value;var textChangeEvent=new cvox.TextChangeEvent(newValue,this.node.selectionStart,this.node.selectionEnd,triggeredByUser);this.changed(textChangeEvent);};cvox.ChromeVoxEditableTextArea=function(node,tts){goog.base(this,node,node.value,node.selectionStart,node.selectionEnd,false,tts);this.multiline=true;this.shadowIsCurrent_=false;};goog.inherits(cvox.ChromeVoxEditableTextArea,cvox.ChromeVoxEditableElement);cvox.ChromeVoxEditableTextArea.shadow_;cvox.ChromeVoxEditableTextArea.prototype.update=function(triggeredByUser){if(this.node.value!=this.value){this.shadowIsCurrent_=false;}
var textChangeEvent=new cvox.TextChangeEvent(this.node.value,this.node.selectionStart,this.node.selectionEnd,triggeredByUser);this.changed(textChangeEvent);};cvox.ChromeVoxEditableTextArea.prototype.getLineIndex=function(index){return this.getShadow().getLineIndex(index);};cvox.ChromeVoxEditableTextArea.prototype.getLineStart=function(index){return this.getShadow().getLineStart(index);};cvox.ChromeVoxEditableTextArea.prototype.getLineEnd=function(index){return this.getShadow().getLineEnd(index);};cvox.ChromeVoxEditableTextArea.prototype.getShadow=function(){var shadow=cvox.ChromeVoxEditableTextArea.shadow_;if(!shadow){shadow=cvox.ChromeVoxEditableTextArea.shadow_=new cvox.EditableTextAreaShadow();}
if(!this.shadowIsCurrent_){shadow.update(this.node);this.shadowIsCurrent_=true;}
return shadow;};cvox.ChromeVoxEditableTextArea.prototype.moveCursorToNextLine=function(){var node=this.node;var length=node.value.length;if(node.selectionEnd>=length){return false;}
var shadow=this.getShadow();var lineIndex=shadow.getLineIndex(node.selectionEnd);var lineStart=shadow.getLineStart(lineIndex);var offset=node.selectionEnd-lineStart;var lastLine=(length==0)?0:shadow.getLineIndex(length-1);var newCursorPosition=(lineIndex>=lastLine)?length:Math.min(shadow.getLineStart(lineIndex+1)+offset,shadow.getLineEnd(lineIndex+1));node.selectionStart=node.selectionEnd=newCursorPosition;cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableTextArea.prototype.moveCursorToPreviousLine=function(){var node=this.node;if(node.selectionStart<=0){return false;}
var shadow=this.getShadow();var lineIndex=shadow.getLineIndex(node.selectionStart);var lineStart=shadow.getLineStart(lineIndex);var offset=node.selectionStart-lineStart;var newCursorPosition=(lineIndex<=0)?0:Math.min(shadow.getLineStart(lineIndex-1)+offset,shadow.getLineEnd(lineIndex-1));node.selectionStart=node.selectionEnd=newCursorPosition;cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableContentEditable=function(node,tts){goog.base(this,node,'',0,0,false,tts);this.extractorIsCurrent_=false;var extractor=this.getExtractor();this.value=extractor.getText();this.start=extractor.getStartIndex();this.end=extractor.getEndIndex();this.multiline=true;};goog.inherits(cvox.ChromeVoxEditableContentEditable,cvox.ChromeVoxEditableElement);cvox.ChromeVoxEditableContentEditable.extractor_;cvox.ChromeVoxEditableContentEditable.prototype.update=function(triggeredByUser){this.extractorIsCurrent_=false;var textChangeEvent=new cvox.TextChangeEvent(this.getExtractor().getText(),this.getExtractor().getStartIndex(),this.getExtractor().getEndIndex(),triggeredByUser);this.changed(textChangeEvent);};cvox.ChromeVoxEditableContentEditable.prototype.getLineIndex=function(index){return this.getExtractor().getLineIndex(index);};cvox.ChromeVoxEditableContentEditable.prototype.getLineStart=function(index){return this.getExtractor().getLineStart(index);};cvox.ChromeVoxEditableContentEditable.prototype.getLineEnd=function(index){return this.getExtractor().getLineEnd(index);};cvox.ChromeVoxEditableContentEditable.prototype.getExtractor=function(){var extractor=cvox.ChromeVoxEditableContentEditable.extractor_;if(!extractor){extractor=cvox.ChromeVoxEditableContentEditable.extractor_=new cvox.ContentEditableExtractor();}
if(!this.extractorIsCurrent_){extractor.update(this.node);this.extractorIsCurrent_=true;}
return extractor;};cvox.ChromeVoxEditableContentEditable.prototype.changed=function(evt){if(!evt.triggeredByUser){return;}
if(!this.shouldDescribeChange(evt)){this.speak(Msgs.getMsg('text_box_blank'),true);if(this.brailleHandler_){this.brailleHandler_.changed('',0,0,true,null,evt.start);}}else{goog.base(this,'changed',evt);}};cvox.ChromeVoxEditableContentEditable.prototype.moveCursorToNextCharacter=function(){window.getSelection().modify('move','forward','character');cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableContentEditable.prototype.moveCursorToPreviousCharacter=function(){window.getSelection().modify('move','backward','character');cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableContentEditable.prototype.moveCursorToNextParagraph=function(){window.getSelection().modify('move','forward','paragraph');cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableContentEditable.prototype.moveCursorToPreviousParagraph=function(){window.getSelection().modify('move','backward','paragraph');cvox.ChromeVoxEventWatcher.handleTextChanged(true);return true;};cvox.ChromeVoxEditableContentEditable.prototype.shouldDescribeChange=function(evt){var sel=window.getSelection();var cursor=new cvox.Cursor(sel.baseNode,sel.baseOffset,'');if(Math.abs(this.start-evt.start)!=1&&this.start==this.end&&evt.start==evt.end&&sel.baseNode==sel.extentNode&&sel.baseOffset==sel.extentOffset&&sel.baseNode.nodeType==Node.ELEMENT_NODE&&sel.baseNode.querySelector('BR')&&cvox.TraverseUtil.forwardsChar(cursor,[],[])){return false;}
return true;};goog.provide('cvox.ChromeVoxHTMLTimeWidget');cvox.ChromeVoxHTMLTimeWidget=function(timeElem,tts){var self=this;this.timeElem_=timeElem;this.timeTts_=tts;this.pHours_=-1;this.pMinutes_=-1;this.pSeconds_=0;this.pMilliseconds_=0;this.pAmpm_='';this.pos_=0;this.maxPos_=2;this.keyListener_=function(evt){self.eventHandler_(evt);};this.blurListener_=function(evt){self.shutdown();};if(this.timeElem_.hasAttribute('step')){var step=this.timeElem_.getAttribute('step');if(step>0){if(step>=1){this.maxPos_=3;}else{this.maxPos_=4;}}}
if(this.timeElem_.value.length==0){this.forceInitTime_();}
for(var i=0;i<this.maxPos_;i++){var evt=document.createEvent('KeyboardEvent');evt.initKeyboardEvent('keydown',true,true,window,'Left',0,false,false,false,false);this.timeElem_.dispatchEvent(evt);evt=document.createEvent('KeyboardEvent');evt.initKeyboardEvent('keyup',true,true,window,'Left',0,false,false,false,false);this.timeElem_.dispatchEvent(evt);}
this.timeElem_.addEventListener('keydown',this.keyListener_,false);this.timeElem_.addEventListener('keyup',this.keyListener_,false);this.timeElem_.addEventListener('blur',this.blurListener_,false);this.update_(true);};cvox.ChromeVoxHTMLTimeWidget.prototype.shutdown=function(){this.timeElem_.removeEventListener('blur',this.blurListener_,false);this.timeElem_.removeEventListener('keydown',this.keyListener_,false);this.timeElem_.removeEventListener('keyup',this.keyListener_,false);};cvox.ChromeVoxHTMLTimeWidget.prototype.forceInitTime_=function(){this.timeElem_.setAttribute('value','12:00');};cvox.ChromeVoxHTMLTimeWidget.prototype.handlePosChange_=function(){if(this.pos_<0){this.pos_=0;}
if(this.pos_>this.maxPos_){this.pos_=this.maxPos_;}
if(this.pos_==this.maxPos_){this.pAmpm_='';return;}
switch(this.pos_){case 0:this.pHours_=-1;break;case 1:this.pMinutes_=-1;break;case 2:this.pSeconds_=-1;break;case 3:this.pMilliseconds_=-1;break;}};cvox.ChromeVoxHTMLTimeWidget.prototype.update_=function(shouldSpeakLabel){var splitTime=this.timeElem_.value.split(':');if(splitTime.length<1){this.forceInitTime_();return;}
var hours=splitTime[0];var minutes=-1;var seconds=0;var milliseconds=0;var ampm=Msgs.getMsg('timewidget_am');if(splitTime.length>1){minutes=splitTime[1];}
if(splitTime.length>2){var splitSecondsAndMilliseconds=splitTime[2].split('.');seconds=splitSecondsAndMilliseconds[0];if(splitSecondsAndMilliseconds.length>1){milliseconds=splitSecondsAndMilliseconds[1];}}
if(hours>12){hours=hours-12;ampm=Msgs.getMsg('timewidget_pm');}
if(hours==12){ampm=Msgs.getMsg('timewidget_pm');}
if(hours==0){hours=12;ampm=Msgs.getMsg('timewidget_am');}
var changeMessage='';if(shouldSpeakLabel){changeMessage=cvox.DomUtil.getName(this.timeElem_,true,true)+'\n';}
if(hours!=this.pHours_){changeMessage=changeMessage+hours+' '+
Msgs.getMsg('timewidget_hours')+'\n';this.pHours_=hours;}
if(minutes!=this.pMinutes_){changeMessage=changeMessage+minutes+' '+
Msgs.getMsg('timewidget_minutes')+'\n';this.pMinutes_=minutes;}
if(seconds!=this.pSeconds_){changeMessage=changeMessage+seconds+' '+
Msgs.getMsg('timewidget_seconds')+'\n';this.pSeconds_=seconds;}
if(milliseconds!=this.pMilliseconds_){changeMessage=changeMessage+milliseconds+' '+
Msgs.getMsg('timewidget_milliseconds')+'\n';this.pMilliseconds_=milliseconds;}
if(ampm!=this.pAmpm_){changeMessage=changeMessage+ampm;this.pAmpm_=ampm;}
if(changeMessage.length>0){this.timeTts_.speak(changeMessage,cvox.QueueMode.FLUSH,null);}};cvox.ChromeVoxHTMLTimeWidget.prototype.eventHandler_=function(evt){var shouldSpeakLabel=false;if(evt.type=='keydown'){if(((evt.keyCode==9)&&!evt.shiftKey)||(evt.keyCode==39)){this.pos_++;this.handlePosChange_();shouldSpeakLabel=true;}
if(((evt.keyCode==9)&&evt.shiftKey)||(evt.keyCode==37)){this.pos_--;this.handlePosChange_();shouldSpeakLabel=true;}}
this.update_(shouldSpeakLabel);};goog.provide('cvox.ChromeVoxHTMLDateWidget');goog.require('Msgs');cvox.ChromeVoxHTMLDateWidget=function(dateElem,tts){var self=this;this.pos_=0;var maxpos=2;if(dateElem.type=='month'||dateElem.type=='week'){maxpos=1;}
this.maxPos_=maxpos;this.dateElem_=dateElem;this.dateTts_=tts;this.pYear_=-1;this.pMonth_=-1;this.pWeek_=-1;this.pDay_=-1;this.keyListener_=function(evt){self.eventHandler_(evt);};this.blurListener_=function(evt){self.shutdown();};if(this.dateElem_.value.length==0){this.forceInitTime_();}
for(var i=0;i<this.maxPos_;i++){var evt=document.createEvent('KeyboardEvent');evt.initKeyboardEvent('keydown',true,true,window,'Left',0,false,false,false,false);this.dateElem_.dispatchEvent(evt);evt=document.createEvent('KeyboardEvent');evt.initKeyboardEvent('keyup',true,true,window,'Left',0,false,false,false,false);this.dateElem_.dispatchEvent(evt);}
this.dateElem_.addEventListener('keydown',this.keyListener_,false);this.dateElem_.addEventListener('keyup',this.keyListener_,false);this.dateElem_.addEventListener('blur',this.blurListener_,false);this.update_(true);};cvox.ChromeVoxHTMLDateWidget.prototype.shutdown=function(){this.dateElem_.removeEventListener('blur',this.blurListener_,false);this.dateElem_.removeEventListener('keydown',this.keyListener_,false);this.dateElem_.removeEventListener('keyup',this.keyListener_,false);};cvox.ChromeVoxHTMLDateWidget.prototype.forceInitTime_=function(){var currentDate=new Date();var valueString='';var yearString=currentDate.getFullYear()+'';var monthString=currentDate.getMonth()+1+'';if(monthString.length<2){monthString='0'+monthString;}
var dayString=currentDate.getDate()+'';switch(this.dateElem_.type){case'month':valueString=yearString+'-'+monthString;break;case'week':currentDate.setHours(0,0,0);currentDate.setDate(currentDate.getDate()+4-(currentDate.getDay()||7));var yearStart=new Date(currentDate.getFullYear(),0,1);var weekString=Math.ceil((((currentDate-yearStart)/86400000)+1)/7)+'';if(weekString.length<2){weekString='0'+weekString;}
weekString='W'+weekString;valueString=yearString+'-'+weekString;break;default:valueString=yearString+'-'+monthString+'-'+dayString;break;}
this.dateElem_.setAttribute('value',valueString);};cvox.ChromeVoxHTMLDateWidget.prototype.handlePosChange_=function(){this.pos_=Math.max(this.pos_,0);this.pos_=Math.min(this.pos_,this.maxPos_);switch(this.pos_){case 0:if(this.dateElem_.type=='week'){this.pWeek_=-1;}else{this.pMonth_=-1;}
break;case 1:if(this.dateElem_.type=='date'){this.pDay_=-1;}else{this.pYear_=-1;}
break;case 2:this.pYear_=-1;break;}};cvox.ChromeVoxHTMLDateWidget.prototype.update_=function(shouldSpeakLabel){var splitDate=this.dateElem_.value.split('-');if(splitDate.length<1){this.forceInitTime_();return;}
var year=-1;var month=-1;var week=-1;var day=-1;year=parseInt(splitDate[0],10);if(this.dateElem_.type=='week'){week=parseInt(splitDate[1].replace('W',''),10);}else if(this.dateElem_.type=='date'){month=parseInt(splitDate[1],10);day=parseInt(splitDate[2],10);}else{month=parseInt(splitDate[1],10);}
var changeMessage='';if(shouldSpeakLabel){changeMessage=cvox.DomUtil.getName(this.dateElem_,true,true)+'\n';}
if(week!=this.pWeek_){changeMessage=changeMessage+
Msgs.getMsg('datewidget_week')+week+'\n';this.pWeek_=week;}
if(month!=this.pMonth_){var monthName='';switch(month){case 1:monthName=Msgs.getMsg('datewidget_january');break;case 2:monthName=Msgs.getMsg('datewidget_february');break;case 3:monthName=Msgs.getMsg('datewidget_march');break;case 4:monthName=Msgs.getMsg('datewidget_april');break;case 5:monthName=Msgs.getMsg('datewidget_may');break;case 6:monthName=Msgs.getMsg('datewidget_june');break;case 7:monthName=Msgs.getMsg('datewidget_july');break;case 8:monthName=Msgs.getMsg('datewidget_august');break;case 9:monthName=Msgs.getMsg('datewidget_september');break;case 10:monthName=Msgs.getMsg('datewidget_october');break;case 11:monthName=Msgs.getMsg('datewidget_november');break;case 12:monthName=Msgs.getMsg('datewidget_december');break;}
changeMessage=changeMessage+monthName+'\n';this.pMonth_=month;}
if(day!=this.pDay_){changeMessage=changeMessage+day+'\n';this.pDay_=day;}
if(year!=this.pYear_){changeMessage=changeMessage+year+'\n';this.pYear_=year;}
if(changeMessage.length>0){this.dateTts_.speak(changeMessage,0,null);}};cvox.ChromeVoxHTMLDateWidget.prototype.eventHandler_=function(evt){var shouldSpeakLabel=false;if(evt.type=='keydown'){if(((evt.keyCode==9)&&!evt.shiftKey)||(evt.keyCode==39)){this.pos_++;this.handlePosChange_();shouldSpeakLabel=true;}
if(((evt.keyCode==9)&&evt.shiftKey)||(evt.keyCode==37)){this.pos_--;this.handlePosChange_();shouldSpeakLabel=true;}}
this.update_(shouldSpeakLabel);};goog.provide('cvox.ChromeVoxEventWatcher');goog.provide('cvox.ChromeVoxEventWatcherUtil');goog.require('cvox.ActiveIndicator');goog.require('cvox.ApiImplementation');goog.require('cvox.AriaUtil');goog.require('cvox.ChromeVox');goog.require('cvox.ChromeVoxEditableTextBase');goog.require('cvox.ChromeVoxEventSuspender');goog.require('cvox.ChromeVoxHTMLDateWidget');goog.require('cvox.ChromeVoxHTMLMediaWidget');goog.require('cvox.ChromeVoxHTMLTimeWidget');goog.require('cvox.ChromeVoxKbHandler');goog.require('cvox.ChromeVoxUserCommands');goog.require('cvox.DomUtil');goog.require('cvox.Focuser');goog.require('cvox.History');goog.require('cvox.LiveRegions');goog.require('cvox.Memoize');goog.require('cvox.NavigationSpeaker');goog.require('cvox.PlatformFilter');goog.require('cvox.PlatformUtil');goog.require('cvox.QueueMode');goog.require('cvox.TextHandlerInterface');goog.require('cvox.UserEventDetail');cvox.ChromeVoxEventWatcher=function(){};cvox.ChromeVoxEventWatcher.MAX_WAIT_TIME_MS_=50;cvox.ChromeVoxEventWatcher.WAIT_TIME_MS_=10;cvox.ChromeVoxEventWatcher.MAX_LIVE_REGIONS_=5;cvox.ChromeVoxEventWatcher.shouldEchoKeys=true;cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance=false;cvox.ChromeVoxEventWatcher.init=function(doc){cvox.ChromeVoxEventWatcher.lastFocusedNode=null;cvox.ChromeVoxEventWatcher.announcedMouseOverNode=null;cvox.ChromeVoxEventWatcher.pendingMouseOverNode=null;cvox.ChromeVoxEventWatcher.mouseOverTimeoutId=null;cvox.ChromeVoxEventWatcher.lastFocusedNodeValue=null;cvox.ChromeVoxEventWatcher.eventToEat=null;cvox.ChromeVoxEventWatcher.currentTextControl=null;cvox.ChromeVoxEventWatcher.currentTextHandler=null;cvox.ChromeVoxEventWatcher.listeners_=[];cvox.ChromeVoxEventWatcher.mutationObserver_=null;cvox.ChromeVoxEventWatcher.focusFollowsMouse=false;cvox.ChromeVoxEventWatcher.mouseoverDelayMs=500;cvox.ChromeVoxEventWatcher.events_=new Array();cvox.ChromeVoxEventWatcher.lastEventTime=0;cvox.ChromeVoxEventWatcher.firstUnprocessedEventTime=-1;cvox.ChromeVoxEventWatcher.queueProcessingScheduled_=false;cvox.ChromeVoxEventWatcher.readyCallbacks_=new Array();cvox.ChromeVoxEventWatcher.secondPassThroughKeyUp_=false;cvox.ChromeVox.searchKeyHeld=false;cvox.ChromeVoxEventWatcher.textMutationObserver_=null;cvox.ChromeVoxEventWatcher.addEventListeners_(doc);};cvox.ChromeVoxEventWatcher.storeOn=function(store){store['searchKeyHeld']=cvox.ChromeVox.searchKeyHeld;};cvox.ChromeVoxEventWatcher.readFrom=function(store){cvox.ChromeVox.searchKeyHeld=store['searchKeyHeld'];};cvox.ChromeVoxEventWatcher.addEvent=function(evt){if(!cvox.ChromeVox.isActive||!cvox.ChromeVox.documentHasFocus()){if(evt.type=='focus'){cvox.ChromeVox.navigationManager.activeIndicator.syncToNode(evt.target);}
return;}
cvox.ChromeVoxEventWatcher.events_.push(evt);cvox.ChromeVoxEventWatcher.lastEventTime=new Date().getTime();if(cvox.ChromeVoxEventWatcher.firstUnprocessedEventTime==-1){cvox.ChromeVoxEventWatcher.firstUnprocessedEventTime=new Date().getTime();}
if(!cvox.ChromeVoxEventWatcher.queueProcessingScheduled_){cvox.ChromeVoxEventWatcher.queueProcessingScheduled_=true;window.setTimeout(cvox.ChromeVoxEventWatcher.processQueue_,cvox.ChromeVoxEventWatcher.WAIT_TIME_MS_);}};cvox.ChromeVoxEventWatcher.addReadyCallback=function(cb){cvox.ChromeVoxEventWatcher.readyCallbacks_.push(cb);cvox.ChromeVoxEventWatcher.maybeCallReadyCallbacks_();};cvox.ChromeVoxEventWatcher.hasPendingEvents_=function(){return cvox.ChromeVoxEventWatcher.firstUnprocessedEventTime!=-1||cvox.ChromeVoxEventWatcher.queueProcessingScheduled_;};cvox.ChromeVoxEventWatcher.readyCallbackRunning_=false;cvox.ChromeVoxEventWatcher.maybeCallReadyCallbacks_=function(){if(!cvox.ChromeVoxEventWatcher.readyCallbackRunning_){cvox.ChromeVoxEventWatcher.readyCallbackRunning_=true;window.setTimeout(function(){cvox.ChromeVoxEventWatcher.readyCallbackRunning_=false;if(!cvox.ChromeVoxEventWatcher.hasPendingEvents_()&&!cvox.ChromeVoxEventWatcher.queueProcessingScheduled_&&cvox.ChromeVoxEventWatcher.readyCallbacks_.length>0){cvox.ChromeVoxEventWatcher.readyCallbacks_.shift()();cvox.ChromeVoxEventWatcher.maybeCallReadyCallbacks_();}},5);}};cvox.ChromeVoxEventWatcher.addEventListeners_=function(doc){cvox.ChromeVoxEventWatcher.addEventListener_(doc,'keydown',cvox.ChromeVoxEventWatcher.keyDownEventWatcher,true);if(!cvox.ChromeVox.isActive||cvox.ChromeVox.entireDocumentIsHidden){return;}
cvox.ChromeVoxEventWatcher.addEventListener_(doc,'keypress',cvox.ChromeVoxEventWatcher.keyPressEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'keyup',cvox.ChromeVoxEventWatcher.keyUpEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,cvox.UserEventDetail.Category.JUMP,cvox.ChromeVoxUserCommands.handleChromeVoxUserEvent,false);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'focus',cvox.ChromeVoxEventWatcher.focusEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'blur',cvox.ChromeVoxEventWatcher.blurEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'change',cvox.ChromeVoxEventWatcher.changeEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'copy',cvox.ChromeVoxEventWatcher.clipboardEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'cut',cvox.ChromeVoxEventWatcher.clipboardEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'paste',cvox.ChromeVoxEventWatcher.clipboardEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'select',cvox.ChromeVoxEventWatcher.selectEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'webkitvisibilitychange',cvox.ChromeVoxEventWatcher.visibilityChangeWatcher,true);cvox.ChromeVoxEventWatcher.events_=new Array();cvox.ChromeVoxEventWatcher.queueProcessingScheduled_=false;cvox.ChromeVoxEventWatcher.addEventListener_(doc,'mouseover',cvox.ChromeVoxEventWatcher.mouseOverEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'mouseout',cvox.ChromeVoxEventWatcher.mouseOutEventWatcher,true);cvox.ChromeVoxEventWatcher.addEventListener_(doc,'click',cvox.ChromeVoxEventWatcher.mouseClickEventWatcher,true);cvox.ChromeVoxEventWatcher.mutationObserver_=new window.WebKitMutationObserver(cvox.ChromeVoxEventWatcher.mutationHandler);var observerTarget=null;if(doc.documentElement){observerTarget=doc.documentElement;}else if(doc.document&&doc.document.documentElement){observerTarget=doc.document.documentElement;}
if(observerTarget){cvox.ChromeVoxEventWatcher.mutationObserver_.observe(observerTarget,({childList:true,attributes:true,characterData:true,subtree:true,attributeOldValue:true,characterDataOldValue:true}));}};cvox.ChromeVoxEventWatcher.cleanup=function(doc){for(var i=0;i<cvox.ChromeVoxEventWatcher.listeners_.length;i++){var listener=cvox.ChromeVoxEventWatcher.listeners_[i];doc.removeEventListener(listener.type,listener.listener,listener.useCapture);}
cvox.ChromeVoxEventWatcher.listeners_=[];if(cvox.ChromeVoxEventWatcher.currentDateHandler){cvox.ChromeVoxEventWatcher.currentDateHandler.shutdown();}
if(cvox.ChromeVoxEventWatcher.currentTimeHandler){cvox.ChromeVoxEventWatcher.currentTimeHandler.shutdown();}
if(cvox.ChromeVoxEventWatcher.currentMediaHandler){cvox.ChromeVoxEventWatcher.currentMediaHandler.shutdown();}
if(cvox.ChromeVoxEventWatcher.mutationObserver_){cvox.ChromeVoxEventWatcher.mutationObserver_.disconnect();}
cvox.ChromeVoxEventWatcher.mutationObserver_=null;};cvox.ChromeVoxEventWatcher.addEventListener_=function(doc,type,listener,useCapture){cvox.ChromeVoxEventWatcher.listeners_.push({'type':type,'listener':listener,'useCapture':useCapture});doc.addEventListener(type,listener,useCapture);};cvox.ChromeVoxEventWatcher.getLastFocusedNode=function(){return cvox.ChromeVoxEventWatcher.lastFocusedNode;};cvox.ChromeVoxEventWatcher.setLastFocusedNode_=function(element){cvox.ChromeVoxEventWatcher.lastFocusedNode=element;cvox.ChromeVoxEventWatcher.lastFocusedNodeValue=!element?null:cvox.DomUtil.getControlValueAndStateString(element);};cvox.ChromeVoxEventWatcher.mutationHandler=function(mutations){if(cvox.ChromeVoxEventSuspender.areEventsSuspended()){return true;}
cvox.ChromeVox.navigationManager.updateIndicatorIfChanged();cvox.LiveRegions.processMutations(mutations,function(assertive,navDescriptions){var evt=new window.Event('LiveRegion');evt.navDescriptions=navDescriptions;evt.assertive=assertive;cvox.ChromeVoxEventWatcher.addEvent(evt);return true;});return false;};cvox.ChromeVoxEventWatcher.mouseClickEventWatcher=function(evt){if(evt.fromCvox){return true;}
if(cvox.ChromeVox.host.mustRedispatchClickEvent()){cvox.ChromeVoxUserCommands.wasMouseClicked=true;evt.stopPropagation();evt.preventDefault();cvox.Focuser.setFocus(cvox.ChromeVox.navigationManager.getCurrentNode());cvox.ChromeVox.tts.speak(Msgs.getMsg('element_clicked'),cvox.ChromeVoxEventWatcher.queueMode_(),cvox.AbstractTts.PERSONALITY_ANNOTATION);var targetNode=cvox.ChromeVox.navigationManager.getCurrentNode();cvox.DomUtil.clickElem(targetNode,false,true);return false;}else{cvox.ChromeVoxEventWatcher.addEvent(evt);}
cvox.ChromeVoxUserCommands.wasMouseClicked=true;return true;};cvox.ChromeVoxEventWatcher.mouseOverEventWatcher=function(evt){var isTouchEvent=(evt.metaKey);var mouseoverDelayMs=cvox.ChromeVoxEventWatcher.mouseoverDelayMs;if(isTouchEvent){mouseoverDelayMs=0;}else if(!cvox.ChromeVoxEventWatcher.focusFollowsMouse){return true;}
if(cvox.DomUtil.isDescendantOfNode(cvox.ChromeVoxEventWatcher.announcedMouseOverNode,evt.target)){return true;}
if(evt.target==cvox.ChromeVoxEventWatcher.pendingMouseOverNode){return true;}
cvox.ChromeVoxEventWatcher.pendingMouseOverNode=evt.target;if(cvox.ChromeVoxEventWatcher.mouseOverTimeoutId){window.clearTimeout(cvox.ChromeVoxEventWatcher.mouseOverTimeoutId);cvox.ChromeVoxEventWatcher.mouseOverTimeoutId=null;}
if(evt.target.tagName&&(evt.target.tagName=='BODY')){cvox.ChromeVoxEventWatcher.pendingMouseOverNode=null;cvox.ChromeVoxEventWatcher.announcedMouseOverNode=null;return true;}
cvox.ChromeVoxEventWatcher.mouseOverTimeoutId=window.setTimeout(function(){cvox.ChromeVoxEventWatcher.mouseOverTimeoutId=null;if(evt.target!=cvox.ChromeVoxEventWatcher.pendingMouseOverNode){return;}
cvox.Memoize.scope(function(){cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance=true;cvox.ChromeVox.navigationManager.stopReading(true);var target=(evt.target);cvox.Focuser.setFocus(target);cvox.ApiImplementation.syncToNode(target,true,cvox.ChromeVoxEventWatcher.queueMode_());cvox.ChromeVoxEventWatcher.announcedMouseOverNode=target;});},mouseoverDelayMs);return true;};cvox.ChromeVoxEventWatcher.mouseOutEventWatcher=function(evt){if(evt.target==cvox.ChromeVoxEventWatcher.pendingMouseOverNode){cvox.ChromeVoxEventWatcher.pendingMouseOverNode=null;if(cvox.ChromeVoxEventWatcher.mouseOverTimeoutId){window.clearTimeout(cvox.ChromeVoxEventWatcher.mouseOverTimeoutId);cvox.ChromeVoxEventWatcher.mouseOverTimeoutId=null;}}
return true;};cvox.ChromeVoxEventWatcher.focusEventWatcher=function(evt){cvox.ChromeVoxUserCommands.removeTabDummySpan();if(!cvox.ChromeVoxEventSuspender.areEventsSuspended()){cvox.ChromeVoxEventWatcher.addEvent(evt);}else if(evt.target&&evt.target.nodeType==Node.ELEMENT_NODE){cvox.ChromeVoxEventWatcher.setLastFocusedNode_((evt.target));}
return true;};cvox.ChromeVoxEventWatcher.focusHandler=function(evt){if(!cvox.ChromeVox.documentHasFocus()){return;}
if(evt.target&&evt.target.hasAttribute&&evt.target.getAttribute('aria-hidden')=='true'&&evt.target.getAttribute('chromevoxignoreariahidden')!='true'){cvox.ChromeVoxEventWatcher.setLastFocusedNode_(null);cvox.ChromeVoxEventWatcher.setUpTextHandler();return;}
if(evt.target&&evt.target!=window){var target=(evt.target);var parentControl=cvox.DomUtil.getSurroundingControl(target);if(parentControl&&parentControl==cvox.ChromeVoxEventWatcher.lastFocusedNode){cvox.ChromeVoxEventWatcher.handleControlChanged(target);return;}
if(parentControl){cvox.ChromeVoxEventWatcher.setLastFocusedNode_((parentControl));}else{cvox.ChromeVoxEventWatcher.setLastFocusedNode_(target);}
var queueMode=cvox.ChromeVoxEventWatcher.queueMode_();if(cvox.ChromeVoxEventWatcher.getInitialVisibility()||cvox.ChromeVoxEventWatcher.handleDialogFocus(target)){queueMode=cvox.QueueMode.QUEUE;}
if(cvox.ChromeVox.navigationManager.clearPageSel(true)){queueMode=cvox.QueueMode.QUEUE;}
cvox.ApiImplementation.syncToNode(target,!document.webkitHidden,queueMode);if((evt.target.constructor==HTMLVideoElement)||(evt.target.constructor==HTMLAudioElement)){cvox.ChromeVoxEventWatcher.setUpMediaHandler_();return;}
if(evt.target.hasAttribute){var inputType=evt.target.getAttribute('type');switch(inputType){case'time':cvox.ChromeVoxEventWatcher.setUpTimeHandler_();return;case'date':case'month':case'week':cvox.ChromeVoxEventWatcher.setUpDateHandler_();return;}}
cvox.ChromeVoxEventWatcher.setUpTextHandler();}else{cvox.ChromeVoxEventWatcher.setLastFocusedNode_(null);}
return;};cvox.ChromeVoxEventWatcher.blurEventWatcher=function(evt){window.setTimeout(function(){if(!document.activeElement){cvox.ChromeVoxEventWatcher.setLastFocusedNode_(null);cvox.ChromeVoxEventWatcher.addEvent(evt);}},0);return true;};cvox.ChromeVoxEventWatcher.keyDownEventWatcher=function(evt){return(cvox.Memoize.scope(cvox.ChromeVoxEventWatcher.doKeyDownEventWatcher_.bind(this,evt)));};cvox.ChromeVoxEventWatcher.doKeyDownEventWatcher_=function(evt){cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance=true;if(cvox.ChromeVox.passThroughMode){return true;}
if(cvox.ChromeVox.isChromeOS&&evt.keyCode==91){cvox.ChromeVox.searchKeyHeld=true;}
evt.searchKeyHeld=cvox.ChromeVox.searchKeyHeld&&cvox.ChromeVox.isActive;evt.stickyMode=cvox.ChromeVox.isStickyModeOn()&&cvox.ChromeVox.isActive;evt.keyPrefix=cvox.ChromeVox.keyPrefixOn&&cvox.ChromeVox.isActive;cvox.ChromeVox.keyPrefixOn=false;cvox.ChromeVoxEventWatcher.eventToEat=null;if(!cvox.ChromeVoxKbHandler.basicKeyDownActionsListener(evt)||cvox.ChromeVoxEventWatcher.handleControlAction(evt)){evt.preventDefault();evt.stopPropagation();cvox.ChromeVoxEventWatcher.eventToEat=evt;return false;}
cvox.ChromeVoxEventWatcher.addEvent(evt);return true;};cvox.ChromeVoxEventWatcher.keyUpEventWatcher=function(evt){if(evt.keyCode==91){cvox.ChromeVox.searchKeyHeld=false;}
if(cvox.ChromeVox.passThroughMode){if(!evt.ctrlKey&&!evt.altKey&&!evt.metaKey&&!evt.shiftKey&&!cvox.ChromeVox.searchKeyHeld){if(this.secondPassThroughKeyUp_){this.secondPassThroughKeyUp_=false;cvox.ChromeVox.passThroughMode=false;}else{this.secondPassThroughKeyUp_=true;}}
return true;}
if(cvox.ChromeVoxEventWatcher.eventToEat&&evt.keyCode==cvox.ChromeVoxEventWatcher.eventToEat.keyCode){evt.stopPropagation();evt.preventDefault();return false;}
cvox.ChromeVoxEventWatcher.addEvent(evt);return true;};cvox.ChromeVoxEventWatcher.keyPressEventWatcher=function(evt){var url=document.location.href;var speakChar=cvox.TypingEcho.shouldSpeakChar(cvox.ChromeVox.typingEcho);if(typeof cvox.ChromeVox.keyEcho[url]!=='undefined'){speakChar=cvox.ChromeVox.keyEcho[url];}
if(cvox.ChromeVoxEditableTextBase.eventTypingEcho&&(speakChar&&cvox.DomPredicates.editTextPredicate([document.activeElement]))&&document.activeElement.type!=='password'){cvox.ChromeVox.tts.speak(String.fromCharCode(evt.charCode),cvox.QueueMode.FLUSH);}
cvox.ChromeVoxEventWatcher.addEvent(evt);if(cvox.ChromeVoxEventWatcher.eventToEat&&evt.keyCode==cvox.ChromeVoxEventWatcher.eventToEat.keyCode){evt.preventDefault();evt.stopPropagation();return false;}
return true;};cvox.ChromeVoxEventWatcher.changeEventWatcher=function(evt){cvox.ChromeVoxEventWatcher.addEvent(evt);return true;};cvox.ChromeVoxEventWatcher.clipboardEventWatcher=function(evt){var targetNode=(evt.target);if(!cvox.ChromeVox.documentHasFocus()||!targetNode||!cvox.DomUtil.isVisible(targetNode)||cvox.AriaUtil.isHidden(targetNode)){return true;}
var text='';switch(evt.type){case'paste':text=evt.clipboardData.getData('text');break;case'copy':case'cut':text=window.getSelection().toString();break;}
cvox.ChromeVox.tts.speak(Msgs.getMsg(evt.type,[text]),cvox.QueueMode.QUEUE);cvox.ChromeVox.navigationManager.clearPageSel();return true;};cvox.ChromeVoxEventWatcher.changeHandler=function(evt){if(cvox.ChromeVoxEventWatcher.setUpTextHandler()){return;}
if(document.activeElement==evt.target){cvox.ChromeVoxEventWatcher.handleControlChanged(document.activeElement);}};cvox.ChromeVoxEventWatcher.selectEventWatcher=function(evt){cvox.ChromeVoxEventWatcher.addEvent(evt);return true;};cvox.ChromeVoxEventWatcher.visibilityChangeWatcher=function(){cvox.ChromeVoxEventWatcher.initialVisibility=!document.webkitHidden;if(document.webkitHidden){cvox.ChromeVox.navigationManager.stopReading(true);}};cvox.ChromeVoxEventWatcher.getInitialVisibility=function(){var ret=cvox.ChromeVoxEventWatcher.initialVisibility;cvox.ChromeVoxEventWatcher.initialVisibility=false;return ret;};cvox.ChromeVoxEventWatcher.speakLiveRegion_=function(assertive,messages){var queueMode=cvox.ChromeVoxEventWatcher.queueMode_();var descSpeaker=new cvox.NavigationSpeaker();descSpeaker.speakDescriptionArray(messages,queueMode,null);};cvox.ChromeVoxEventWatcher.setUpTextHandler=function(){var currentFocus=document.activeElement;if(currentFocus&&currentFocus.hasAttribute&&currentFocus.getAttribute('aria-hidden')=='true'&&currentFocus.getAttribute('chromevoxignoreariahidden')!='true'){currentFocus=null;}
if(currentFocus!=cvox.ChromeVoxEventWatcher.currentTextControl){if(cvox.ChromeVoxEventWatcher.currentTextControl){cvox.ChromeVoxEventWatcher.currentTextControl.removeEventListener('input',cvox.ChromeVoxEventWatcher.changeEventWatcher,false);cvox.ChromeVoxEventWatcher.currentTextControl.removeEventListener('click',cvox.ChromeVoxEventWatcher.changeEventWatcher,false);if(cvox.ChromeVoxEventWatcher.textMutationObserver_){cvox.ChromeVoxEventWatcher.textMutationObserver_.disconnect();cvox.ChromeVoxEventWatcher.textMutationObserver_=null;}}
cvox.ChromeVoxEventWatcher.currentTextControl=null;if(cvox.ChromeVoxEventWatcher.currentTextHandler){cvox.ChromeVoxEventWatcher.currentTextHandler.teardown();cvox.ChromeVoxEventWatcher.currentTextHandler=null;}
if(currentFocus==null){return false;}
if(currentFocus.constructor==HTMLInputElement&&cvox.DomUtil.isInputTypeText(currentFocus)&&cvox.ChromeVoxEventWatcher.shouldEchoKeys){cvox.ChromeVoxEventWatcher.currentTextControl=currentFocus;cvox.ChromeVoxEventWatcher.currentTextHandler=new cvox.ChromeVoxEditableHTMLInput(currentFocus,cvox.ChromeVox.tts);}else if((currentFocus.constructor==HTMLTextAreaElement)&&cvox.ChromeVoxEventWatcher.shouldEchoKeys){cvox.ChromeVoxEventWatcher.currentTextControl=currentFocus;cvox.ChromeVoxEventWatcher.currentTextHandler=new cvox.ChromeVoxEditableTextArea(currentFocus,cvox.ChromeVox.tts);}else if(currentFocus.isContentEditable||currentFocus.getAttribute('role')=='textbox'){cvox.ChromeVoxEventWatcher.currentTextControl=currentFocus;cvox.ChromeVoxEventWatcher.currentTextHandler=new cvox.ChromeVoxEditableContentEditable(currentFocus,cvox.ChromeVox.tts);}
if(cvox.ChromeVoxEventWatcher.currentTextControl){cvox.ChromeVoxEventWatcher.currentTextControl.addEventListener('input',cvox.ChromeVoxEventWatcher.changeEventWatcher,false);cvox.ChromeVoxEventWatcher.currentTextControl.addEventListener('click',cvox.ChromeVoxEventWatcher.changeEventWatcher,false);if(window.WebKitMutationObserver){cvox.ChromeVoxEventWatcher.textMutationObserver_=new window.WebKitMutationObserver(cvox.ChromeVoxEventWatcher.onTextMutation);cvox.ChromeVoxEventWatcher.textMutationObserver_.observe(cvox.ChromeVoxEventWatcher.currentTextControl,({childList:true,attributes:true,subtree:true,attributeOldValue:false,characterDataOldValue:false}));}
if(!cvox.ChromeVoxEventSuspender.areEventsSuspended()){cvox.ChromeVox.navigationManager.updateSel(cvox.CursorSelection.fromNode(cvox.ChromeVoxEventWatcher.currentTextControl));}}
return(null!=cvox.ChromeVoxEventWatcher.currentTextHandler);}
return false;};cvox.ChromeVoxEventWatcher.handleTextChanged=function(isKeypress){if(cvox.ChromeVoxEventWatcher.currentTextHandler){var handler=cvox.ChromeVoxEventWatcher.currentTextHandler;var shouldFlush=false;if(isKeypress&&cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance){shouldFlush=true;cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance=false;}
handler.update(shouldFlush);cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance=false;return true;}
return false;};cvox.ChromeVoxEventWatcher.onTextMutation=function(){if(cvox.ChromeVoxEventWatcher.currentTextHandler){window.setTimeout(function(){cvox.ChromeVoxEventWatcher.handleTextChanged(false);},cvox.ChromeVoxEventWatcher.MAX_WAIT_TIME_MS_);}};cvox.ChromeVoxEventWatcher.handleControlChanged=function(control){var newValue=cvox.DomUtil.getControlValueAndStateString(control);var parentControl=cvox.DomUtil.getSurroundingControl(control);var announceChange=false;if(control!=cvox.ChromeVoxEventWatcher.lastFocusedNode&&(parentControl==null||parentControl!=cvox.ChromeVoxEventWatcher.lastFocusedNode)){cvox.ChromeVoxEventWatcher.setLastFocusedNode_(control);}else if(newValue==cvox.ChromeVoxEventWatcher.lastFocusedNodeValue){return;}
cvox.ChromeVoxEventWatcher.lastFocusedNodeValue=newValue;if(cvox.DomPredicates.checkboxPredicate([control])||cvox.DomPredicates.radioPredicate([control])){announceChange=true;if(control.checked){cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.CHECK_ON);}else{cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.CHECK_OFF);}}
if(control.tagName=='SELECT'){announceChange=true;}
if(control.tagName=='INPUT'){switch(control.type){case'color':case'datetime':case'datetime-local':case'range':announceChange=true;break;default:break;}}
if(control.hasAttribute&&control.hasAttribute('role')){announceChange=true;}
var activeDescendant=cvox.AriaUtil.getActiveDescendant(control);if((parentControl&&parentControl!=control&&document.activeElement==control)){cvox.ApiImplementation.syncToNode(activeDescendant||control,true,cvox.ChromeVoxEventWatcher.queueMode_());announceChange=false;}else if(activeDescendant){cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(activeDescendant,true);announceChange=true;}
if(newValue&&announceChange&&!cvox.ChromeVoxEventSuspender.areEventsSuspended()){cvox.ChromeVox.tts.speak(newValue,cvox.ChromeVoxEventWatcher.queueMode_(),null);cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(newValue));}};cvox.ChromeVoxEventWatcher.handleControlAction=function(evt){if(!cvox.ChromeVox.isActive){return false;}
var control=evt.target;if(control.tagName=='SELECT'&&(control.size<=1)&&(evt.keyCode==13||evt.keyCode==32)){evt.preventDefault();evt.stopPropagation();return true;}
if(control.tagName=='INPUT'&&control.type=='range'){var value=parseFloat(control.value);var step;if(control.step&&control.step>0.0){step=control.step;}else if(control.min&&control.max){var range=(control.max-control.min);if(range>2&&range<31){step=1;}else{step=(control.max-control.min)/10;}}else{step=1;}
if(evt.keyCode==37||evt.keyCode==38){value-=step;}else if(evt.keyCode==39||evt.keyCode==40){value+=step;}
if(control.max&&value>control.max){value=control.max;}
if(control.min&&value<control.min){value=control.min;}
control.value=value;}
return false;};cvox.ChromeVoxEventWatcher.handleDialogFocus=function(target){var dialog=target;var role='';while(dialog){if(dialog.hasAttribute){role=dialog.getAttribute('role');if(role=='dialog'||role=='alertdialog'){break;}}
dialog=dialog.parentElement;}
if(dialog==cvox.ChromeVox.navigationManager.currentDialog){return false;}
if(cvox.ChromeVox.navigationManager.currentDialog&&!dialog){if(!cvox.DomUtil.isDescendantOfNode(document.activeElement,cvox.ChromeVox.navigationManager.currentDialog)){cvox.ChromeVox.navigationManager.currentDialog=null;cvox.ChromeVoxEventWatcher.speakAnnotationWithCategory_(Msgs.getMsg('exiting_dialog'),cvox.TtsCategory.NAV);return true;}}else{if(dialog){cvox.ChromeVox.navigationManager.currentDialog=dialog;cvox.ChromeVoxEventWatcher.speakAnnotationWithCategory_(Msgs.getMsg('entering_dialog'),cvox.TtsCategory.NAV);if(role=='alertdialog'){var dialogDescArray=cvox.DescriptionUtil.getFullDescriptionsFromChildren(null,dialog);var descSpeaker=new cvox.NavigationSpeaker();descSpeaker.speakDescriptionArray(dialogDescArray,cvox.QueueMode.QUEUE,null);}
return true;}}
return false;};cvox.ChromeVoxEventWatcher.speakAnnotationWithCategory_=function(text,category){var properties={};var src=cvox.AbstractTts.PERSONALITY_ANNOTATION;for(var key in src){properties[key]=src[key];}
properties['category']=category;cvox.ChromeVox.tts.speak(text,cvox.ChromeVoxEventWatcher.queueMode_(),properties);};cvox.ChromeVoxEventWatcherUtil.shouldWaitToProcess=function(lastFocusTimestamp,firstTimestamp,currentTime){var timeSinceFocusEvent=currentTime-lastFocusTimestamp;var timeSinceFirstEvent=currentTime-firstTimestamp;return timeSinceFocusEvent<cvox.ChromeVoxEventWatcher.WAIT_TIME_MS_&&timeSinceFirstEvent<cvox.ChromeVoxEventWatcher.MAX_WAIT_TIME_MS_;};cvox.ChromeVoxEventWatcher.queueMode_=function(){if(cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance){cvox.ChromeVoxEventWatcher.shouldFlushNextUtterance=false;return cvox.QueueMode.FLUSH;}
return cvox.QueueMode.CATEGORY_FLUSH;};cvox.ChromeVoxEventWatcher.processQueue_=function(){cvox.Memoize.scope(cvox.ChromeVoxEventWatcher.doProcessQueue_);};cvox.ChromeVoxEventWatcher.doProcessQueue_=function(){if(cvox.ChromeVoxEventWatcher.events_.length==0){return;}
var events=cvox.ChromeVoxEventWatcher.events_;var lastFocusIndex=-1;var lastFocusTimestamp=0;var evt;var i;for(i=0;evt=events[i];i++){if(evt.type=='focus'){lastFocusIndex=i;lastFocusTimestamp=evt.timeStamp;}}
cvox.ChromeVoxEventWatcher.events_=[];for(i=0;evt=events[i];i++){var prevEvt=events[i-1]||{};if((i>=lastFocusIndex||evt.type=='LiveRegion')&&(prevEvt.type!='focus'||evt.type!='change')){cvox.ChromeVoxEventWatcher.events_.push(evt);}}
cvox.ChromeVoxEventWatcher.events_.sort(function(a,b){if(b.type!='LiveRegion'&&a.type=='LiveRegion'){return 1;}
return-1;});var currentTime=new Date().getTime();if(lastFocusIndex>=0&&cvox.ChromeVoxEventWatcherUtil.shouldWaitToProcess(lastFocusTimestamp,cvox.ChromeVoxEventWatcher.firstUnprocessedEventTime,currentTime)){window.setTimeout(cvox.ChromeVoxEventWatcher.processQueue_,cvox.ChromeVoxEventWatcher.WAIT_TIME_MS_);return;}
for(i=0;evt=cvox.ChromeVoxEventWatcher.events_[i];i++){cvox.ChromeVoxEventWatcher.handleEvent_(evt);}
cvox.ChromeVoxEventWatcher.events_=new Array();cvox.ChromeVoxEventWatcher.firstUnprocessedEventTime=-1;cvox.ChromeVoxEventWatcher.queueProcessingScheduled_=false;cvox.ChromeVoxEventWatcher.maybeCallReadyCallbacks_();};cvox.ChromeVoxEventWatcher.handleEvent_=function(evt){switch(evt.type){case'keydown':case'input':cvox.ChromeVoxEventWatcher.setUpTextHandler();if(cvox.ChromeVoxEventWatcher.currentTextControl){cvox.ChromeVoxEventWatcher.handleTextChanged(true);var editableText=(cvox.ChromeVoxEventWatcher.currentTextHandler);if(editableText&&editableText.lastChangeDescribed){break;}}
cvox.ChromeVoxEventWatcher.handleControlChanged(document.activeElement);break;case'keyup':cvox.ChromeVoxEventWatcher.handleControlChanged(document.activeElement);break;case'keypress':cvox.ChromeVoxEventWatcher.setUpTextHandler();break;case'click':cvox.ApiImplementation.syncToNode((evt.target),true);break;case'focus':cvox.ChromeVoxEventWatcher.focusHandler(evt);break;case'blur':cvox.ChromeVoxEventWatcher.setUpTextHandler();break;case'change':cvox.ChromeVoxEventWatcher.changeHandler(evt);break;case'select':cvox.ChromeVoxEventWatcher.setUpTextHandler();break;case'LiveRegion':cvox.ChromeVoxEventWatcher.speakLiveRegion_(evt.assertive,evt.navDescriptions);break;}};cvox.ChromeVoxEventWatcher.setUpTimeHandler_=function(){var currentFocus=document.activeElement;if(currentFocus&&currentFocus.hasAttribute&&currentFocus.getAttribute('aria-hidden')=='true'&&currentFocus.getAttribute('chromevoxignoreariahidden')!='true'){currentFocus=null;}
if(currentFocus.constructor==HTMLInputElement&&currentFocus.type&&(currentFocus.type=='time')){cvox.ChromeVoxEventWatcher.currentTimeHandler=new cvox.ChromeVoxHTMLTimeWidget(currentFocus,cvox.ChromeVox.tts);}else{cvox.ChromeVoxEventWatcher.currentTimeHandler=null;}
return(null!=cvox.ChromeVoxEventWatcher.currentTimeHandler);};cvox.ChromeVoxEventWatcher.setUpMediaHandler_=function(){var currentFocus=document.activeElement;if(currentFocus&&currentFocus.hasAttribute&&currentFocus.getAttribute('aria-hidden')=='true'&&currentFocus.getAttribute('chromevoxignoreariahidden')!='true'){currentFocus=null;}
if((currentFocus.constructor==HTMLVideoElement)||(currentFocus.constructor==HTMLAudioElement)){cvox.ChromeVoxEventWatcher.currentMediaHandler=new cvox.ChromeVoxHTMLMediaWidget(currentFocus,cvox.ChromeVox.tts);}else{cvox.ChromeVoxEventWatcher.currentMediaHandler=null;}
return(null!=cvox.ChromeVoxEventWatcher.currentMediaHandler);};cvox.ChromeVoxEventWatcher.setUpDateHandler_=function(){var currentFocus=document.activeElement;if(currentFocus&&currentFocus.hasAttribute&&currentFocus.getAttribute('aria-hidden')=='true'&&currentFocus.getAttribute('chromevoxignoreariahidden')!='true'){currentFocus=null;}
if(currentFocus.constructor==HTMLInputElement&&currentFocus.type&&((currentFocus.type=='date')||(currentFocus.type=='month')||(currentFocus.type=='week'))){cvox.ChromeVoxEventWatcher.currentDateHandler=new cvox.ChromeVoxHTMLDateWidget(currentFocus,cvox.ChromeVox.tts);}else{cvox.ChromeVoxEventWatcher.currentDateHandler=null;}
return(null!=cvox.ChromeVoxEventWatcher.currentDateHandler);};goog.provide('cvox.AbstractHost');goog.require('cvox.ChromeVoxEventWatcher');cvox.AbstractHost=function(){};cvox.AbstractHost.State={ACTIVE:0,INACTIVE:1,KILLED:2};cvox.AbstractHost.prototype.init=function(){};cvox.AbstractHost.prototype.reinit=function(){};cvox.AbstractHost.prototype.onPageLoad=function(){};cvox.AbstractHost.prototype.sendToBackgroundPage=function(message){};cvox.AbstractHost.prototype.getApiSrc=function(){return'';};cvox.AbstractHost.prototype.getFileSrc=function(path){return'';};cvox.AbstractHost.prototype.hasTtsCallback=function(){return true;};cvox.AbstractHost.prototype.ttsLoaded=function(){return true;};cvox.AbstractHost.prototype.mustRedispatchClickEvent=function(){return false;};cvox.AbstractHost.prototype.activateOrDeactivateChromeVox=function(active){this.onStateChanged_(active?cvox.AbstractHost.State.ACTIVE:cvox.AbstractHost.State.INACTIVE);};cvox.AbstractHost.prototype.killChromeVox=function(){this.onStateChanged_(cvox.AbstractHost.State.KILLED);};cvox.AbstractHost.prototype.onStateChanged_=function(state){var active=state==cvox.AbstractHost.State.ACTIVE;if(active==cvox.ChromeVox.isActive){return;}
cvox.ChromeVoxEventWatcher.cleanup(window);switch(state){case cvox.AbstractHost.State.ACTIVE:cvox.ChromeVox.isActive=true;cvox.ChromeVox.navigationManager.showOrHideIndicator(true);cvox.ChromeVoxEventWatcher.init(window);if(document.activeElement){var speakNodeAlso=cvox.ChromeVox.documentHasFocus();cvox.ApiImplementation.syncToNode(document.activeElement,speakNodeAlso);}else{cvox.ChromeVox.navigationManager.updateIndicator();}
break;case cvox.AbstractHost.State.INACTIVE:cvox.ChromeVox.isActive=false;cvox.ChromeVox.navigationManager.showOrHideIndicator(false);cvox.ChromeVoxEventWatcher.init(window);break;case cvox.AbstractHost.State.KILLED:cvox.ChromeVox.isActive=false;cvox.ChromeVox.navigationManager.showOrHideIndicator(false);break;}};goog.provide('cvox.MathJaxInterface');cvox.MathJaxInterface=function(){};cvox.MathJaxInterface.prototype.isMathjaxActive=function(callback){};cvox.MathJaxInterface.prototype.getAllJax=function(callback){};cvox.MathJaxInterface.prototype.registerSignal=function(callback,signal){};cvox.MathJaxInterface.prototype.injectScripts=function(){};cvox.MathJaxInterface.prototype.configMediaWiki=function(){};cvox.MathJaxInterface.prototype.getTex=function(callback,texNode){};cvox.MathJaxInterface.prototype.getAsciiMath=function(callback,asciiMathNode){};goog.provide('cvox.AbstractMathJax');goog.require('cvox.MathJaxInterface');cvox.AbstractMathJax=function(){};cvox.AbstractMathJax.prototype.isMathjaxActive=goog.abstractMethod;cvox.AbstractMathJax.prototype.getAllJax=goog.abstractMethod;cvox.AbstractMathJax.prototype.registerSignal=goog.abstractMethod;cvox.AbstractMathJax.prototype.getTex=goog.abstractMethod;cvox.AbstractMathJax.prototype.getAsciiMath=goog.abstractMethod;cvox.AbstractMathJax.prototype.injectScripts=goog.abstractMethod;cvox.AbstractMathJax.prototype.configMediaWiki=goog.abstractMethod;cvox.AbstractMathJax.prototype.getAllTexs=function(callback){var allTexs=document.querySelectorAll(cvox.DomUtil.altMathQuerySelector('tex'));for(var i=0,tex;tex=allTexs[i];i++){this.getTex(callback,tex);}};cvox.AbstractMathJax.prototype.getAllAsciiMaths=function(callback){var allAsciiMaths=document.querySelectorAll(cvox.DomUtil.altMathQuerySelector('asciimath'));for(var i=0,tex;tex=allAsciiMaths[i];i++){this.getAsciiMath(callback,tex);}};cvox.AbstractMathJax.prototype.convertMarkupToDom=function(callback,mml,id){if(mml){var dp=new DOMParser;var cleanMml=mml.replace(/>\s+</g,'><');callback(dp.parseFromString(cleanMml,'text/xml').firstChild,id);}};goog.provide('cvox.HostFactory');goog.require('cvox.AbstractEarcons');goog.require('cvox.AbstractHost');goog.require('cvox.AbstractMathJax');goog.require('cvox.AbstractTts');cvox.HostFactory=function(){};cvox.HostFactory.getHost=function(){return new cvox.HostFactory.hostConstructor;};cvox.HostFactory.getTts=function(){return new cvox.HostFactory.ttsConstructor;};cvox.HostFactory.getBraille=function(){return new cvox.HostFactory.brailleConstructor;};cvox.HostFactory.getEarcons=function(){return new cvox.HostFactory.earconsConstructor;};cvox.HostFactory.getMathJax=function(){return new cvox.HostFactory.mathJaxConstructor;};cvox.HostFactory.hostConstructor;cvox.HostFactory.ttsConstructor;cvox.HostFactory.brailleConstructor;cvox.HostFactory.earconsConstructor;cvox.HostFactory.mathJaxConstructor;goog.provide('cvox.ChromeTtsBase');goog.require('cvox.AbstractTts');cvox.ChromeTtsBase=function(){goog.base(this);this.propertyDefault['pitch']=1;this.propertyMin['pitch']=0.2;this.propertyMax['pitch']=2.0;this.propertyDefault['rate']=1;this.propertyMin['rate']=0.2;this.propertyMax['rate']=5.0;this.propertyDefault['volume']=1;this.propertyMin['volume']=0.2;this.propertyMax['volume']=1.0;};goog.inherits(cvox.ChromeTtsBase,cvox.AbstractTts);goog.provide('cvox.ChromeTts');goog.require('cvox.ChromeTtsBase');goog.require('cvox.HostFactory');cvox.ChromeTts=function(){goog.base(this);this.addBridgeListener();};goog.inherits(cvox.ChromeTts,cvox.ChromeTtsBase);cvox.ChromeTts.callId=1;cvox.ChromeTts.functionMap=new Object();cvox.ChromeTts.prototype.speak=function(textString,queueMode,properties){if(!properties){properties={};}
goog.base(this,'speak',textString,queueMode,properties);cvox.ExtensionBridge.send(this.createMessageForProperties_(textString,queueMode,properties));return this;};cvox.ChromeTts.prototype.isSpeaking=function(){cvox.ChromeTts.superClass_.isSpeaking.call(this);return false;};cvox.ChromeTts.prototype.stop=function(){cvox.ChromeTts.superClass_.stop.call(this);cvox.ExtensionBridge.send({'target':'TTS','action':'stop'});};cvox.ChromeTts.prototype.increaseOrDecreaseProperty=function(propertyName,increase){cvox.ExtensionBridge.send({'target':'TTS','action':'increaseOrDecrease','property':propertyName,'increase':increase});};cvox.ChromeTts.prototype.increaseProperty=function(property_name,announce){goog.base(this,'increaseProperty',property_name,announce);cvox.ExtensionBridge.send({'target':'TTS','action':'increase'+property_name,'announce':announce});};cvox.ChromeTts.prototype.addBridgeListener=function(){cvox.ExtensionBridge.addMessageListener(function(msg,port){var message=msg['message'];if(message=='TTS_CALLBACK'){var id=msg['id'];var func=cvox.ChromeTts.functionMap[id];if(func!=undefined){if(!msg['cleanupOnly']){func();}
delete cvox.ChromeTts.functionMap[id];}}});};cvox.ChromeTts.prototype.createMessageForProperties_=function(textString,queueMode,properties){var message={'target':'TTS','action':'speak','text':textString,'queueMode':queueMode,'properties':properties};if(properties['startCallback']!=undefined){cvox.ChromeTts.functionMap[cvox.ChromeTts.callId]=properties['startCallback'];message['startCallbackId']=cvox.ChromeTts.callId++;}
if(properties['endCallback']!=undefined){cvox.ChromeTts.functionMap[cvox.ChromeTts.callId]=properties['endCallback'];message['endCallbackId']=cvox.ChromeTts.callId++;}
return message;};cvox.HostFactory.ttsConstructor=cvox.ChromeTts;goog.provide('cvox.InitialSpeech');goog.require('cvox.AbstractTts');goog.require('cvox.BrailleOverlayWidget');goog.require('cvox.ChromeVox');goog.require('cvox.CursorSelection');goog.require('cvox.DescriptionUtil');goog.require('cvox.DomUtil');goog.require('cvox.LiveRegions');if(!window['INJECTED_AFTER_LOAD'])
window['INJECTED_AFTER_LOAD']=false;cvox.InitialSpeech.speak=function(){var disableSpeak=window['INJECTED_AFTER_LOAD'];if(!cvox.ChromeVox.isActive||document.webkitHidden){disableSpeak=true;}
if(window.top==window){var title=document.title;var titleElement=document.querySelector('head > title');if(titleElement&&titleElement.getAttribute('aria-hidden')=='true'){title=null;}
if(title&&!disableSpeak){cvox.ChromeVox.tts.speak(title,cvox.QueueMode.FLUSH);}
cvox.BrailleOverlayWidget.getInstance().init();}
cvox.LiveRegions.init(new Date(),cvox.QueueMode.QUEUE,disableSpeak);if(cvox.ChromeVox.documentHasFocus()&&document.activeElement==document.body){cvox.ChromeVox.navigationManager.syncToBeginning();}
if(cvox.ChromeVox.position[document.location.href]){var pos=cvox.ChromeVox.position[document.location.href];cvox.ChromeVox.navigationManager.updateSelToArbitraryNode(document.elementFromPoint(pos.x,pos.y));}
if(cvox.ChromeVox.documentHasFocus()){if(!disableSpeak){cvox.ChromeVoxEventSuspender.withSuspendedEvents(function(){cvox.ChromeVox.navigationManager.finishNavCommand('',true,cvox.QueueMode.QUEUE);})();}}};goog.provide('cvox.SearchUtil');cvox.SearchUtil=function(){};cvox.SearchUtil.extractURL=function(node){if(node){if(node.tagName==='A'){return node.href;}
var anchor=node.querySelector('a');if(anchor){return anchor.href;}}
return null;};cvox.SearchUtil.isSearchWidgetActive=function(){var SEARCH_WIDGET_SELECT='#cvox-search';return document.querySelector(SEARCH_WIDGET_SELECT)!==null;};cvox.SearchUtil.addOneWrap=function(index,length){return(index+1)%length;};cvox.SearchUtil.subOneWrap=function(index,length){return(index-1+length)%length;};var getActiveDescendantId_=function(targetNode){if(!targetNode.getAttribute){return null;}
var activeId=targetNode.getAttribute('aria-activedescendant');if(!activeId){return null;}
return activeId;};var getActiveDescendant=function(targetNode){var seenIds={};var node=targetNode;while(node){var activeId=getActiveDescendantId_(node);if(!activeId){break;}
if(activeId in seenIds){return null;}
seenIds[activeId]=true;node=document.getElementById(activeId);}
if(node==targetNode){return null;}
return node;};cvox.SearchUtil.clickElem=function(targetNode,shiftKey,callOnClickDirectly,opt_double){var activeDescendant=getActiveDescendant(targetNode);if(activeDescendant){targetNode=activeDescendant;}
if(callOnClickDirectly){var onClickFunction=null;if(targetNode.onclick){onClickFunction=targetNode.onclick;}
if(!onClickFunction&&(targetNode.nodeType!=1)&&targetNode.parentNode&&targetNode.parentNode.onclick){onClickFunction=targetNode.parentNode.onclick;}
var keepGoing=true;if(onClickFunction){try{keepGoing=onClickFunction();}catch(exception){}}
if(!keepGoing){return;}}
var evt=document.createEvent('MouseEvents');var evtType=opt_double?'dblclick':'mousedown';evt.initMouseEvent(evtType,true,true,document.defaultView,1,0,0,0,0,false,false,shiftKey,false,0,null);evt.fromCvox=true;try{targetNode.dispatchEvent(evt);}catch(e){}
evt=document.createEvent('MouseEvents');evt.initMouseEvent('mouseup',true,true,document.defaultView,1,0,0,0,0,false,false,shiftKey,false,0,null);evt.fromCvox=true;try{targetNode.dispatchEvent(evt);}catch(e){}
evt=document.createEvent('MouseEvents');evt.initMouseEvent('click',true,true,document.defaultView,1,0,0,0,0,false,false,shiftKey,false,0,null);evt.fromCvox=true;try{targetNode.dispatchEvent(evt);}catch(e){}};goog.provide('cvox.AbstractResult');goog.require('cvox.SearchUtil');cvox.AbstractResult=function(){};cvox.AbstractResult.prototype.isType=function(result){return false;};cvox.AbstractResult.prototype.speak=function(result){return false;};cvox.AbstractResult.prototype.getURL=cvox.SearchUtil.extractURL;cvox.AbstractResult.prototype.getSyncNode=function(result){return result;};goog.provide('cvox.SearchResults');goog.provide('cvox.UnknownResult');goog.require('cvox.AbstractResult');goog.require('cvox.ChromeVox');goog.require('cvox.SearchUtil');cvox.SearchResults=function(){};cvox.SearchResults.speakResultBySelectTexts=function(result,selectTexts){for(var j=0;j<selectTexts.length;j++){var selectText=selectTexts[j];if(selectText.select){var elems=result.querySelectorAll(selectText.select);for(var i=0;i<elems.length;i++){cvox.ChromeVox.speakNode(elems.item(i),cvox.QueueMode.QUEUE);}}
if(selectText.text){cvox.ChromeVox.tts.speak(selectText.text,cvox.QueueMode.QUEUE);}}};cvox.UnknownResult=function(){};goog.inherits(cvox.UnknownResult,cvox.AbstractResult);cvox.NormalResult=function(){};goog.inherits(cvox.NormalResult,cvox.AbstractResult);cvox.NormalResult.prototype.isType=function(result){var NORMAL_SELECT='.rc';return result.querySelector(NORMAL_SELECT)!==null;};cvox.NormalResult.prototype.speak=function(result){if(!result){return false;}
var NORMAL_TITLE_SELECT='.rc .r';var NORMAL_URL_SELECT='.kv';var NORMAL_DESC_SELECT='.rc .st';var SITE_LINK_SELECT='.osl';var MORE_RESULTS_SELECT='.sld';var MORE_RESULTS_LINK_SELECT='.mrf';var NORMAL_SELECTORS=[{select:NORMAL_TITLE_SELECT},{select:NORMAL_DESC_SELECT},{select:NORMAL_URL_SELECT},{select:SITE_LINK_SELECT},{select:MORE_RESULTS_SELECT},{select:MORE_RESULTS_LINK_SELECT}];cvox.SearchResults.speakResultBySelectTexts(result,NORMAL_SELECTORS);var DISCUSS_TITLE_SELECT='.mas-1st-col div';var DISCUSS_DATE_SELECT='.mas-col div';var discussTitles=result.querySelectorAll(DISCUSS_TITLE_SELECT);var discussDates=result.querySelectorAll(DISCUSS_DATE_SELECT);for(var i=0;i<discussTitles.length;i++){cvox.ChromeVox.speakNode(discussTitles.item(i),cvox.QueueMode.QUEUE);cvox.ChromeVox.speakNode(discussDates.item(i),cvox.QueueMode.QUEUE);}
return true;};cvox.WeatherResult=function(){};goog.inherits(cvox.WeatherResult,cvox.AbstractResult);cvox.WeatherResult.prototype.isType=function(result){var WEATHER_SELECT='#wob_wc';return result.querySelector(WEATHER_SELECT)!==null;};cvox.WeatherResult.speakForecast=function(forecast){if(!forecast){return;}
var FORE_DAY_SELECT='.vk_lgy';var FORE_COND_SELECT='img';var FORE_HIGH_SELECT='.vk_gy';var FORE_LOW_SELECT='.vk_lgy';var FORE_SELECTORS=[{select:FORE_DAY_SELECT},{select:FORE_COND_SELECT},{select:FORE_HIGH_SELECT},{select:FORE_LOW_SELECT}];cvox.SearchResults.speakResultBySelectTexts(forecast,FORE_SELECTORS);};cvox.WeatherResult.prototype.speak=function(result){if(!result){return false;}
var WEATHER_INTRO='The weather forcast for';var WEATHER_TEMP_UNITS='degrees fahrenheit';var WEATHER_PREC_INTRO='precipitation is';var WEATHER_HUMID_INTRO='humidity is';var WEATHER_WIND_INTRO='wind is';var FORE_INTRO='Forecasts for this week';var WEATHER_LOC_SELECT='.vk_h';var WEATHER_WHEN_SELECT='#wob_dts';var WEATHER_COND_SELECT='#wob_dc';var WEATHER_TEMP_SELECT='#wob_tm';var WEATHER_PREC_SELECT='#wob_pp';var WEATHER_HUMID_SELECT='#wob_hm';var WEATHER_WIND_SELECT='#wob_ws';var WEATHER_SELECT_TEXTS=[{text:WEATHER_INTRO},{select:WEATHER_LOC_SELECT},{select:WEATHER_WHEN_SELECT},{select:WEATHER_COND_SELECT},{select:WEATHER_TEMP_SELECT},{text:WEATHER_TEMP_UNITS},{text:WEATHER_PREC_INTRO},{select:WEATHER_PREC_SELECT},{text:WEATHER_HUMID_INTRO},{select:WEATHER_HUMID_SELECT},{text:WEATHER_WIND_INTRO},{select:WEATHER_WIND_SELECT}];cvox.SearchResults.speakResultBySelectTexts(result,WEATHER_SELECT_TEXTS);var WEATHER_FORCAST_CLASS='wob_df';var forecasts=result.getElementsByClassName(WEATHER_FORCAST_CLASS);cvox.ChromeVox.tts.speak(FORE_INTRO,cvox.QueueMode.QUEUE);for(var i=0;i<forecasts.length;i++){var forecast=forecasts.item(i);cvox.WeatherResult.speakForecast(forecast);}
return true;};cvox.KnowResult=function(){};goog.inherits(cvox.KnowResult,cvox.AbstractResult);cvox.KnowResult.prototype.isType=function(result){var KNOP_SELECT='.kno-ec';return result.querySelector(KNOP_SELECT)!==null;};cvox.KnowResult.prototype.speak=function(result){cvox.ChromeVox.speakNode(result,cvox.QueueMode.QUEUE);return true;};cvox.KnowResult.prototype.getURL=function(result){var LINK_SELECTOR='.q';return cvox.SearchUtil.extractURL(result.querySelector(LINK_SELECTOR));};cvox.KnowResult.prototype.getSyncNode=function(result){var HEADER_SELECTOR='.kno-ecr-pt';return result.querySelector(HEADER_SELECTOR);};cvox.CalcResult=function(){};goog.inherits(cvox.CalcResult,cvox.AbstractResult);cvox.CalcResult.prototype.isType=function(result){var CALC_SELECT='#cwmcwd';return result.querySelector(CALC_SELECT)!==null;};cvox.CalcResult.prototype.speak=function(result){if(!result){return false;}
var CALC_QUERY_SELECT='#cwles';var CALC_RESULT_SELECT='#cwos';var CALC_SELECTORS=[{select:CALC_QUERY_SELECT},{select:CALC_RESULT_SELECT}];cvox.SearchResults.speakResultBySelectTexts(result,CALC_SELECTORS);return true;};cvox.GameResult=function(){};goog.inherits(cvox.GameResult,cvox.AbstractResult);cvox.GameResult.prototype.isType=function(result){var GAME_SELECT='.xpdbox';return result.querySelector(GAME_SELECT)!==null;};cvox.ImageResult=function(){};goog.inherits(cvox.ImageResult,cvox.AbstractResult);cvox.ImageResult.prototype.isType=function(result){var IMAGE_CLASSES='rg_di';return result.className===IMAGE_CLASSES;};cvox.ImageResult.prototype.speak=function(result){if(!result){return false;}
var META_CLASS='rg_meta';var metaDiv=result.querySelector('.'+META_CLASS);var metaJSON=metaDiv.innerHTML;var metaData=JSON.parse(metaJSON);var imageSelectTexts=[];var filename=metaData['fn'];if(filename){imageSelectTexts.push({text:filename});}
var rawDimensions=metaData['is'];if(rawDimensions){var tmpDiv=document.createElement('div');tmpDiv.innerHTML=rawDimensions;var dimensions=tmpDiv.textContent||tmpDiv.innerText;imageSelectTexts.push({text:dimensions});}
var url=metaData['isu'];if(url){imageSelectTexts.push({text:url});}
cvox.SearchResults.speakResultBySelectTexts(result,imageSelectTexts);return true;};cvox.CategoryResult=function(){};goog.inherits(cvox.CategoryResult,cvox.AbstractResult);cvox.CategoryResult.prototype.isType=function(result){var CATEGORY_CLASSES='rg_fbl nj';return result.className===CATEGORY_CLASSES;};cvox.CategoryResult.prototype.speak=function(result){if(!result){return false;}
var LABEL_SELECT='.rg_bb_label';var label=result.querySelector(LABEL_SELECT);cvox.ChromeVox.speakNode(label,cvox.QueueMode.QUEUE);return true;};cvox.AdResult=function(){};goog.inherits(cvox.AdResult,cvox.AbstractResult);cvox.AdResult.prototype.isType=function(result){var ADS_CLASS='ads-ad';return result.className===ADS_CLASS;};cvox.AdResult.prototype.speak=function(result){if(!result){return false;}
var HEADER_SELECT='h3';var DESC_SELECT='.ads-creative';var URL_SELECT='.ads-visurl';var AD_SELECTS=[{select:HEADER_SELECT},{select:DESC_SELECT},{select:URL_SELECT}];cvox.SearchResults.speakResultBySelectTexts(result,AD_SELECTS);return true;};cvox.SearchResults.RESULT_TYPES=[cvox.UnknownResult,cvox.NormalResult,cvox.KnowResult,cvox.WeatherResult,cvox.AdResult,cvox.CalcResult,cvox.GameResult,cvox.ImageResult,cvox.CategoryResult];goog.provide('cvox.SearchConstants');cvox.SearchConstants=function(){};cvox.SearchConstants.KeyCode={UP:38,DOWN:40,PAGE_UP:33,PAGE_DOWN:34,LEFT:37,RIGHT:39,ENTER:13,ESC:27};goog.provide('cvox.Search');goog.require('cvox.ChromeVox');goog.require('cvox.SearchConstants');goog.require('cvox.SearchResults');goog.require('cvox.SearchUtil');goog.require('cvox.UnknownResult');cvox.Search=function(){};cvox.Search.selectors={};cvox.Search.webSelectors={TOPSTUFF_SELECT:'#topstuff',SPELL_SUGG_SELECT:'.ssp',SPELL_CORRECTION_SELECT:'.sp_cnt',KNOW_PANEL_SELECT:'.knop',RESULT_SELECT:'.g',RELATED_SELECT:'#brs'};cvox.Search.imageSelectors={IMAGE_CATEGORIES_SELECT:'#ifbc .rg_fbl',IMAGE_RESULT_SELECT:'#rg_s .rg_di'};cvox.Search.index;cvox.Search.results=[];cvox.Search.panes=[];cvox.Search.paneIndex;cvox.Search.isPane=false;cvox.Search.SELECTED_PANE_CLASS='hdtb_mitem hdtb_msel';cvox.Search.speakSync_=function(){var result=cvox.Search.results[cvox.Search.index];var resultType=cvox.Search.getResultType(result);var isSpoken=resultType.speak(result);cvox.ChromeVox.syncToNode(resultType.getSyncNode(result),!isSpoken);cvox.Search.isPane=false;};cvox.Search.syncToIndex=function(){cvox.ChromeVox.tts.stop();var prop={endCallback:cvox.Search.speakSync_};if(cvox.Search.index===0){cvox.ChromeVox.tts.speak('First result',cvox.QueueMode.QUEUE,prop);}else if(cvox.Search.index===cvox.Search.results.length-1){cvox.ChromeVox.tts.speak('Last result',cvox.QueueMode.QUEUE,prop);}else{cvox.Search.speakSync_();}};cvox.Search.syncPaneToIndex=function(){var pane=cvox.Search.panes[cvox.Search.paneIndex];var anchor=pane.querySelector('a');if(anchor){cvox.ChromeVox.syncToNode(anchor,true);}else{cvox.ChromeVox.syncToNode(pane,true);}
cvox.Search.isPane=true;};cvox.Search.getResultType=function(result){for(var i=0;i<cvox.SearchResults.RESULT_TYPES.length;i++){var resultType=new cvox.SearchResults.RESULT_TYPES[i]();if(resultType.isType(result)){return resultType;}}
return new cvox.UnknownResult();};cvox.Search.getPageNumber=function(url){var PAGE_ANCHOR_SELECTOR='#nav .fl';var pageAnchors=document.querySelectorAll(PAGE_ANCHOR_SELECTOR);for(var i=0;i<pageAnchors.length;i++){var pageAnchor=pageAnchors.item(i);if(pageAnchor.href===url){return parseInt(pageAnchor.innerText,10);}}
return NaN;};cvox.Search.navigatePage=function(next){var NAV_END_CLASS='navend';var navEnds=document.getElementsByClassName(NAV_END_CLASS);var navEnd=next?navEnds[1]:navEnds[0];var url=cvox.SearchUtil.extractURL(navEnd);var navToUrl=function(){window.location=url;};var prop={endCallback:navToUrl};if(url){var pageNumber=cvox.Search.getPageNumber(url);if(!isNaN(pageNumber)){cvox.ChromeVox.tts.speak('Page '+pageNumber,cvox.QueueMode.FLUSH,prop);}else{cvox.ChromeVox.tts.speak('Unknown page.',cvox.QueueMode.FLUSH,prop);}}};cvox.Search.goToPane=function(){var pane=cvox.Search.panes[cvox.Search.paneIndex];if(pane.className===cvox.Search.SELECTED_PANE_CLASS){cvox.ChromeVox.tts.speak('You are already on that page.',cvox.QueueMode.QUEUE);return;}
var anchor=pane.querySelector('a');cvox.ChromeVox.tts.speak(anchor.textContent,cvox.QueueMode.QUEUE);var url=cvox.SearchUtil.extractURL(pane);if(url){window.location=url;}};cvox.Search.goToResult=function(){var result=cvox.Search.results[cvox.Search.index];var resultType=cvox.Search.getResultType(result);var url=resultType.getURL(result);if(url){window.location=url;}};cvox.Search.keyhandler=function(evt){var SEARCH_INPUT_ID='gbqfq';var searchInput=document.getElementById(SEARCH_INPUT_ID);var result=cvox.Search.results[cvox.Search.index];var ret=false;if(evt.shiftKey||evt.altKey||evt.ctrlKey){return false;}
if(document.activeElement!==searchInput&&!cvox.SearchUtil.isSearchWidgetActive()){switch(evt.keyCode){case cvox.SearchConstants.KeyCode.UP:cvox.Search.index=cvox.SearchUtil.subOneWrap(cvox.Search.index,cvox.Search.results.length);if(cvox.Search.index===cvox.Search.results.length-1){cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP);}
cvox.Search.syncToIndex();break;case cvox.SearchConstants.KeyCode.DOWN:cvox.Search.index=cvox.SearchUtil.addOneWrap(cvox.Search.index,cvox.Search.results.length);if(cvox.Search.index===0){cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP);}
cvox.Search.syncToIndex();break;case cvox.SearchConstants.KeyCode.PAGE_UP:cvox.Search.navigatePage(false);break;case cvox.SearchConstants.KeyCode.PAGE_DOWN:cvox.Search.navigatePage(true);break;case cvox.SearchConstants.KeyCode.LEFT:cvox.Search.paneIndex=cvox.SearchUtil.subOneWrap(cvox.Search.paneIndex,cvox.Search.panes.length);cvox.Search.syncPaneToIndex();break;case cvox.SearchConstants.KeyCode.RIGHT:cvox.Search.paneIndex=cvox.SearchUtil.addOneWrap(cvox.Search.paneIndex,cvox.Search.panes.length);cvox.Search.syncPaneToIndex();break;case cvox.SearchConstants.KeyCode.ENTER:if(cvox.Search.isPane){cvox.Search.goToPane();}else{cvox.Search.goToResult();}
break;default:return false;}
evt.preventDefault();evt.stopPropagation();return true;}
return false;};cvox.Search.addToResultsBySelector=function(selector){var nodes=document.querySelectorAll(selector);for(var i=0;i<nodes.length;i++){var node=nodes.item(i);if(node.innerHTML!==''){cvox.Search.results.push(nodes.item(i));}}};cvox.Search.populatePanes=function(){cvox.Search.panes=[];var PANE_SELECT='.hdtb_mitem';var paneElems=document.querySelectorAll(PANE_SELECT);for(var i=0;i<paneElems.length;i++){cvox.Search.panes.push(paneElems.item(i));}};cvox.Search.populateResults=function(){for(var prop in cvox.Search.selectors){cvox.Search.addToResultsBySelector(cvox.Search.selectors[prop]);}};cvox.Search.populateAdResults=function(){cvox.Search.results=[];var ADS_SELECT='.ads-ad';cvox.Search.addToResultsBySelector(ADS_SELECT);};cvox.Search.observeMutation=function(){var SEARCH_AREA_SELECT='#rg_s';var target=document.querySelector(SEARCH_AREA_SELECT);var observer=new MutationObserver(function(mutations){cvox.Search.results=[];cvox.Search.populateResults();});var config=({attributes:true,childList:true,characterData:true});observer.observe(target,config);};cvox.Search.getSelectedPaneIndex=function(){var panes=cvox.Search.panes;for(var i=0;i<panes.length;i++){if(panes[i].className===cvox.Search.SELECTED_PANE_CLASS){return i;}}
return 0;};cvox.Search.getAncestorResult=function(node){var curr=node;while(curr){for(var prop in cvox.Search.selectors){var selector=cvox.Search.selectors[prop];if(curr.webkitMatchesSelector&&curr.webkitMatchesSelector(selector)){return curr;}}
curr=curr.parentNode;}
return null;};cvox.Search.initialSync=function(){var currNode=cvox.ChromeVox.navigationManager.getCurrentNode();var result=cvox.Search.getAncestorResult(currNode);cvox.Search.index=cvox.Search.results.indexOf(result);if(cvox.Search.index===-1){cvox.Search.index=0;}
if(cvox.Search.results.length>0){cvox.Search.syncToIndex();}};cvox.Search.init=function(){cvox.Search.index=0;cvox.ChromeVox.tts.stop();var SELECTED_CLASS='hdtb-msel';var selected=document.getElementsByClassName(SELECTED_CLASS)[0];if(!selected){return;}
var selectedHTML=selected.innerHTML;switch(selectedHTML){case'Web':case'News':cvox.Search.selectors=cvox.Search.webSelectors;break;case'Images':cvox.Search.selectors=cvox.Search.imageSelectors;cvox.Search.observeMutation();break;default:return;}
cvox.Search.populateResults();cvox.Search.populatePanes();cvox.Search.paneIndex=cvox.Search.getSelectedPaneIndex();cvox.Search.initialSync();};goog.provide('cvox.SearchTool');goog.require('cvox.ChromeVox');goog.require('cvox.DomUtil');goog.require('cvox.Search');goog.require('cvox.SearchConstants');goog.require('cvox.SearchUtil');cvox.SearchTool=function(){};cvox.SearchTool.menuIndex;cvox.SearchTool.menus=[];cvox.SearchTool.menuItemIndex;cvox.SearchTool.menuItems=[];cvox.SearchTool.CLEAR_ID='hdtb_rst';cvox.SearchTool.toggleMenu=function(){var menu=cvox.SearchTool.menus[cvox.SearchTool.menuIndex];var menuDiv=menu.previousSibling;cvox.DomUtil.clickElem(menuDiv,false,false,false);};cvox.SearchTool.syncToMenu=function(){cvox.SearchTool.menuItemIndex=0;cvox.SearchTool.toggleMenu();cvox.SearchTool.populateMenuItems();cvox.SearchTool.syncToMenuItem();};cvox.SearchTool.syncToMenuItem=function(){var menuItem=cvox.SearchTool.menuItems[cvox.SearchTool.menuItemIndex];cvox.ChromeVox.syncToNode(menuItem,true);};cvox.SearchTool.populateMenuItems=function(){var menu=cvox.SearchTool.menus[cvox.SearchTool.menuIndex];cvox.SearchTool.menuItems=[];if(menu.id!==cvox.SearchTool.CLEAR_ID){var MENU_ITEM_SELECTOR='.hdtbItm';var menuItemNodeList=menu.querySelectorAll(MENU_ITEM_SELECTOR);for(var i=0;i<menuItemNodeList.length;i++){cvox.SearchTool.menuItems.push(menuItemNodeList.item(i));}}else{cvox.SearchTool.menuItems=[];cvox.SearchTool.menuItems.push(menu);}};cvox.SearchTool.populateMenus=function(){var MENU_SELECTOR='.hdtbU';var menuDivs=document.querySelectorAll(MENU_SELECTOR);for(var i=0;i<menuDivs.length;i++){cvox.SearchTool.menus.push(menuDivs.item(i));}
var clearDiv=document.getElementById(cvox.SearchTool.CLEAR_ID);if(clearDiv){cvox.SearchTool.menus.push(clearDiv);}};cvox.SearchTool.activateTools=function(){var MENU_BAR_SELECTOR='#hdtbMenus';var menuBar=document.querySelector(MENU_BAR_SELECTOR);var MENUS_OPEN_CLASS='hdtb-td-o';menuBar.className=MENUS_OPEN_CLASS;cvox.SearchTool.populateMenus();cvox.SearchTool.menuIndex=0;cvox.SearchTool.syncToMenu();};cvox.SearchTool.gotoMenuItem=function(){var menuItem=cvox.SearchTool.menuItems[cvox.SearchTool.menuItemIndex];var LOCATION_INPUT_ID='#lc-input';var input=menuItem.querySelector(LOCATION_INPUT_ID);if(input){input.focus();return;}
var CDR_ID='cdr_opt';switch(menuItem.id){case cvox.SearchTool.CLEAR_ID:window.location=menuItem.dataset.url;break;case CDR_ID:var CDR_LINK_SELECTOR='#cdrlnk';var cdrLink=menuItem.querySelector(CDR_LINK_SELECTOR);cvox.DomUtil.clickElem(cdrLink,false,false,false);cvox.SearchTool.toggleMenu();break;default:window.location=cvox.SearchUtil.extractURL(menuItem);break;}};cvox.SearchTool.keyhandler=function(evt){if(cvox.SearchUtil.isSearchWidgetActive()){return false;}
switch(evt.keyCode){case cvox.SearchConstants.KeyCode.UP:cvox.SearchTool.menuItemIndex=cvox.SearchUtil.subOneWrap(cvox.SearchTool.menuItemIndex,cvox.SearchTool.menuItems.length);cvox.SearchTool.syncToMenuItem();break;case cvox.SearchConstants.KeyCode.DOWN:cvox.SearchTool.menuItemIndex=cvox.SearchUtil.addOneWrap(cvox.SearchTool.menuItemIndex,cvox.SearchTool.menuItems.length);cvox.SearchTool.syncToMenuItem();break;case cvox.SearchConstants.KeyCode.LEFT:cvox.SearchTool.toggleMenu();cvox.SearchTool.menuIndex=cvox.SearchUtil.subOneWrap(cvox.SearchTool.menuIndex,cvox.SearchTool.menus.length);cvox.SearchTool.syncToMenu();break;case cvox.SearchConstants.KeyCode.RIGHT:cvox.SearchTool.toggleMenu();cvox.SearchTool.menuIndex=cvox.SearchUtil.addOneWrap(cvox.SearchTool.menuIndex,cvox.SearchTool.menus.length);cvox.SearchTool.syncToMenu();break;case cvox.SearchConstants.KeyCode.ENTER:cvox.SearchTool.gotoMenuItem();break;default:return false;}
evt.preventDefault();evt.stopPropagation();return true;};goog.provide('cvox.SearchContextMenu');goog.require('cvox.ChromeVoxKbHandler');goog.require('cvox.KeySequence');goog.require('cvox.Search');goog.require('cvox.SearchTool');cvox.SearchContextMenu=function(){};var Command={TOOLS:'tools',ADS:'ads',MAIN:'main'};cvox.SearchContextMenu.currState=Command.MAIN;cvox.SearchContextMenu.contextMenuHandler=function(evt){var cmd=evt.detail['customCommand'];switch(cmd){case Command.TOOLS:cvox.SearchContextMenu.focusTools();break;case Command.ADS:cvox.SearchContextMenu.focusAds();break;case Command.MAIN:cvox.SearchContextMenu.focusMain();break;}};cvox.SearchContextMenu.keyhandler=function(evt){var ret=false;var keySeq=new cvox.KeySequence(evt);var command=cvox.ChromeVoxKbHandler.handlerKeyMap.commandForKey(keySeq);if(!command||command==='performDefaultAction'){switch(cvox.SearchContextMenu.currState){case Command.TOOLS:ret=cvox.SearchTool.keyhandler(evt);break;case Command.ADS:case Command.MAIN:ret=cvox.Search.keyhandler(evt);break;}}
return ret;};cvox.SearchContextMenu.focusMain=function(){if(cvox.SearchContextMenu.currState===Command.TOOLS){cvox.SearchTool.toggleMenu();}
cvox.Search.populateResults();cvox.Search.index=0;cvox.Search.syncToIndex();cvox.SearchContextMenu.currState=Command.MAIN;};cvox.SearchContextMenu.focusAds=function(){cvox.Search.populateAdResults();if(cvox.Search.results.length===0){cvox.SearchContextMenu.focusMain();return;}
cvox.Search.index=0;cvox.Search.syncToIndex();if(cvox.SearchContextMenu.currState===Command.TOOLS){cvox.SearchTool.toggleMenu();}
cvox.SearchContextMenu.currState=Command.ADS;};cvox.SearchContextMenu.focusTools=function(){if(cvox.SearchContextMenu.currState!==Command.TOOLS){cvox.SearchTool.activateTools();cvox.SearchContextMenu.currState=Command.TOOLS;}};cvox.SearchContextMenu.init=function(){var ACTIONS=[{desc:'Main Results',cmd:Command.MAIN},{desc:'Search Tools',cmd:Command.TOOLS},{desc:'Ads',cmd:Command.ADS}];var body=document.querySelector('body');body.setAttribute('contextMenuActions',JSON.stringify(ACTIONS));body.addEventListener('ATCustomEvent',cvox.SearchContextMenu.contextMenuHandler,true);window.addEventListener('keydown',cvox.SearchContextMenu.keyhandler,true);cvox.Search.init();};goog.provide('cvox.SearchLoader');goog.require('cvox.SearchContextMenu');cvox.SearchLoader=function(){};cvox.SearchLoader.onReadyStateChange=function(){if(document.readyState!=='complete'){return;}
var GOOGLE_HOST='www.google.com';var SEARCH_PATH='/search';if(window.location.host!==GOOGLE_HOST||window.location.pathname!==SEARCH_PATH){return;}
cvox.SearchContextMenu.init();};cvox.SearchLoader.init=function(){if(document.readyState!=='complete'){document.onreadystatechange=cvox.SearchLoader.onReadyStateChange;}else{cvox.SearchLoader.onReadyStateChange();}};goog.provide('cvox.ChromeHost');goog.require('cvox.AbstractHost');goog.require('cvox.ApiImplementation');goog.require('cvox.BrailleOverlayWidget');goog.require('cvox.ChromeVox');goog.require('cvox.ChromeVoxEventWatcher');goog.require('cvox.ChromeVoxKbHandler');goog.require('cvox.ExtensionBridge');goog.require('cvox.HostFactory');goog.require('cvox.InitialSpeech');goog.require('cvox.SearchLoader');goog.require('cvox.TraverseMath');cvox.ChromeHost=function(){goog.base(this);this.gotPrefsAtLeastOnce_=false;};goog.inherits(cvox.ChromeHost,cvox.AbstractHost);cvox.ChromeHost.prototype.init=function(){var self=this;var listener=function(message){if(message['history']){cvox.ChromeVox.visitedUrls=message['history'];}
if(message['keyBindings']){cvox.ChromeVoxKbHandler.loadKeyToFunctionsTable(message['keyBindings']);}
if(message['prefs']){var prefs=message['prefs'];cvox.ChromeVoxEditableTextBase.useIBeamCursor=(prefs['useIBeamCursor']=='true');cvox.ChromeVoxEditableTextBase.eventTypingEcho=true;cvox.ChromeVoxEventWatcher.focusFollowsMouse=(prefs['focusFollowsMouse']=='true');cvox.ChromeVox.version=prefs['version'];cvox.ChromeVox.typingEcho=(JSON.parse(prefs['typingEcho']));if(prefs['position']){cvox.ChromeVox.position=(JSON.parse(prefs['position']));}
if(prefs['granularity']!='undefined'){cvox.ChromeVox.navigationManager.setGranularity((JSON.parse(prefs['granularity'])));}
self.activateOrDeactivateChromeVox(prefs['active']=='true');self.activateOrDeactivateStickyMode(prefs['sticky']=='true');if(!self.gotPrefsAtLeastOnce_){cvox.InitialSpeech.speak();}
self.gotPrefsAtLeastOnce_=true;if(prefs['useVerboseMode']=='false'){cvox.ChromeVox.verbosity=cvox.VERBOSITY_BRIEF;}else{cvox.ChromeVox.verbosity=cvox.VERBOSITY_VERBOSE;}
if(prefs['cvoxKey']){cvox.ChromeVox.modKeyStr=prefs['cvoxKey'];}
var apiPrefsChanged=(prefs['siteSpecificScriptLoader']!=cvox.ApiImplementation.siteSpecificScriptLoader||prefs['siteSpecificScriptBase']!=cvox.ApiImplementation.siteSpecificScriptBase);cvox.ApiImplementation.siteSpecificScriptLoader=prefs['siteSpecificScriptLoader'];cvox.ApiImplementation.siteSpecificScriptBase=prefs['siteSpecificScriptBase'];if(apiPrefsChanged){var searchInit=prefs['siteSpecificEnhancements']==='true'?cvox.SearchLoader.init:undefined;cvox.ApiImplementation.init(searchInit);}
cvox.BrailleOverlayWidget.getInstance().setActive(prefs['brailleCaptions']=='true');}};cvox.ExtensionBridge.addMessageListener(listener);cvox.ExtensionBridge.addMessageListener(function(msg,port){if(msg['message']=='DOMAINS_STYLES'){cvox.TraverseMath.getInstance().addDomainsAndStyles(msg['domains'],msg['styles']);}});cvox.ExtensionBridge.addMessageListener(function(msg,port){var message=msg['message'];var cmd=msg['command'];if(message=='USER_COMMAND'){if(cmd!='toggleChromeVox'&&!cvox.ChromeVox.documentHasFocus()){return;}
cvox.ChromeVoxUserCommands.commands[cmd](msg);}else if(message=='SYSTEM_COMMAND'){if(cmd=='killChromeVox'){var reStr=msg['excludeUrlRegExp'];if(reStr&&new RegExp(reStr).test(location.href)){return;}
this.killChromeVox();}}}.bind(this));cvox.ExtensionBridge.send({'target':'Prefs','action':'getPrefs'});cvox.ExtensionBridge.send({'target':'Data','action':'getHistory'});};cvox.ChromeHost.prototype.reinit=function(){cvox.ExtensionBridge.init();};cvox.ChromeHost.prototype.onPageLoad=function(){cvox.ExtensionBridge.addDisconnectListener(goog.bind(function(){cvox.ChromeVox.isActive=false;cvox.ChromeVoxEventWatcher.cleanup(window);cvox.ChromeVox.navigationManager.reset();},this));};cvox.ChromeHost.prototype.sendToBackgroundPage=function(message){cvox.ExtensionBridge.send(message);};cvox.ChromeHost.prototype.getApiSrc=function(){return this.getFileSrc('chromevox/injected/api.js');};cvox.ChromeHost.prototype.getFileSrc=function(file){return window.chrome.extension.getURL(file);};cvox.ChromeHost.prototype.killChromeVox=function(){goog.base(this,'killChromeVox');cvox.ExtensionBridge.removeMessageListeners();};cvox.ChromeHost.prototype.activateOrDeactivateStickyMode=function(sticky){cvox.ChromeVox.isStickyPrefOn=sticky;};cvox.HostFactory.hostConstructor=cvox.ChromeHost;goog.provide('cvox.ChromeEarcons');goog.require('cvox.AbstractEarcons');goog.require('cvox.ExtensionBridge');goog.require('cvox.HostFactory');cvox.ChromeEarcons=function(){goog.base(this);};goog.inherits(cvox.ChromeEarcons,cvox.AbstractEarcons);cvox.ChromeEarcons.prototype.playEarcon=function(earcon){goog.base(this,'playEarcon',earcon);if(!cvox.AbstractEarcons.enabled){return;}
cvox.ExtensionBridge.send({'target':'EARCON','action':'play','earcon':earcon});};cvox.ChromeEarcons.prototype.toggle=function(){goog.base(this,'toggle');cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'earcons','value':cvox.AbstractEarcons.enabled});if(!cvox.AbstractEarcons.enabled){cvox.ChromeVox.host.sendToBackgroundPage({'target':'Prefs','action':'setPref','pref':'useVerboseMode','value':true});}
return cvox.AbstractEarcons.enabled;};cvox.HostFactory.earconsConstructor=cvox.ChromeEarcons;goog.provide('cvox.CompositeTts');goog.require('cvox.TtsInterface');cvox.CompositeTts=function(){this.ttsEngines_=[];};cvox.CompositeTts.prototype.add=function(tts){this.ttsEngines_.push(tts);return this;};cvox.CompositeTts.prototype.speak=function(textString,queueMode,properties){this.ttsEngines_.forEach(function(engine){engine.speak(textString,queueMode,properties);});return this;};cvox.CompositeTts.prototype.isSpeaking=function(){return this.ttsEngines_.some(function(engine){return engine.isSpeaking();});};cvox.CompositeTts.prototype.stop=function(){this.ttsEngines_.forEach(function(engine){engine.stop();});};cvox.CompositeTts.prototype.addCapturingEventListener=function(listener){this.ttsEngines_.forEach(function(engine){engine.addCapturingEventListener(listener);});};cvox.CompositeTts.prototype.increaseOrDecreaseProperty=function(propertyName,increase){this.ttsEngines_.forEach(function(engine){engine.increaseOrDecreaseProperty(propertyName,increase);});};cvox.CompositeTts.prototype.propertyToPercentage=function(property){for(var i=0,engine;engine=this.ttsEngines_[i];i++){var value=engine.propertyToPercentage(property);if(value!==undefined)
return value;}
return null;};cvox.CompositeTts.prototype.getDefaultProperty=function(property){for(var i=0,engine;engine=this.ttsEngines_[i];i++){var value=engine.getDefaultProperty(property);if(value!==undefined)
return value;}
return null;};goog.provide('cvox.Serializer');goog.require('cvox.ChromeVox');goog.require('cvox.ChromeVoxEventWatcher');cvox.Serializer=function(){};cvox.Serializer.prototype.storeOn=function(store){cvox.ChromeVox.storeOn(store);cvox.ChromeVoxEventWatcher.storeOn(store);cvox.ChromeVox.navigationManager.storeOn(store);};cvox.Serializer.prototype.readFrom=function(store){cvox.ChromeVox.readFrom(store);cvox.ChromeVoxEventWatcher.readFrom(store);cvox.ChromeVox.navigationManager.readFrom(store);};goog.provide('cvox.InitGlobals');goog.require('cvox.ApiImplementation');goog.require('cvox.ChromeVox');goog.require('cvox.ChromeVoxEventWatcher');goog.require('cvox.CompositeTts');goog.require('cvox.ConsoleTts');goog.require('cvox.HostFactory');goog.require('cvox.NavigationManager');goog.require('cvox.Serializer');cvox.InitGlobals=function(){};cvox.InitGlobals.initGlobals=function(){if(!cvox.ChromeVox.host){cvox.ChromeVox.host=cvox.HostFactory.getHost();}
cvox.ChromeVox.tts=new cvox.CompositeTts().add(cvox.HostFactory.getTts()).add(cvox.History.getInstance()).add(cvox.ConsoleTts.getInstance());if(!cvox.ChromeVox.braille){cvox.ChromeVox.braille=cvox.HostFactory.getBraille();}
cvox.ChromeVox.mathJax=cvox.HostFactory.getMathJax();cvox.ChromeVox.earcons=cvox.HostFactory.getEarcons();cvox.ChromeVox.isActive=true;cvox.ChromeVox.navigationManager=new cvox.NavigationManager();cvox.ChromeVox.navigationManager.updateIndicator();cvox.ChromeVox.syncToNode=cvox.ApiImplementation.syncToNode;cvox.ChromeVox.speakNode=cvox.ApiImplementation.speakNode;cvox.ChromeVox.serializer=new cvox.Serializer();cvox.ChromeVox.host.init();cvox.ChromeVoxEventWatcher.init(window);cvox.ChromeVox.executeUserCommand=function(commandName){cvox.ChromeVoxUserCommands.commands[commandName]();};cvox.ChromeVox.host.onPageLoad();};goog.provide('cvox.ChromeVoxInit');goog.require('cvox.ChromeVox');goog.require('cvox.ExtensionBridge');goog.require('cvox.HostFactory');goog.require('cvox.InitGlobals');cvox.ChromeVox.initTimeout_=100;cvox.ChromeVox.initTimer_=0;cvox.ChromeVox.MAX_INIT_TIMEOUT_=30000;cvox.ChromeVox.isClassicEnabled_=undefined;cvox.ChromeVox.recallInit_=function(reason){if(cvox.ChromeVox.initTimeout_>cvox.ChromeVox.MAX_INIT_TIMEOUT_){window.console.log(reason+' Taking too long - giving up.');return;}
window.console.log(reason+' Will try again in '+
cvox.ChromeVox.initTimeout_+'ms');cvox.ChromeVox.initTimer_=window.setTimeout(cvox.ChromeVox.initDocument,cvox.ChromeVox.initTimeout_);cvox.ChromeVox.initTimeout_*=2;};cvox.ChromeVox.initDocument=function(){if(/^chrome-extension:\/\/.*background\.html$/.test(window.location.href)){return;}
var disableContentScript=false;if(document.head){var metaNodes=document.head.querySelectorAll('meta[name="chromevox"]');for(var i=0,meta;meta=metaNodes[i];i++){var contentScript=meta.getAttribute('content-script');if(contentScript&&contentScript.toLowerCase()=='no'){disableContentScript=true;}}}
if(disableContentScript){var url=location.href;url=url.substring(0,url.indexOf('#'))||url;cvox.ExtensionBridge.send({target:'next',action:'enableClassicCompatForUrl',url:url});return;}
cvox.ExtensionBridge.send({target:'next',action:'getIsClassicEnabled',url:location.href});cvox.ChromeVox.initTimer_=0;var reinitReason;if(!document.body){reinitReason='ChromeVox not starting on unloaded page';}
if(cvox.ChromeVox.isClassicEnabled_===undefined){reinitReason='ChromeVox waiting for background page';}
if(reinitReason){cvox.ChromeVox.recallInit_(reinitReason+': '+
document.location.href+'.');return;}
if(!cvox.ChromeVox.isClassicEnabled_){return;}
cvox.ChromeVox.host=cvox.HostFactory.getHost();if(!cvox.ChromeVox.host.ttsLoaded()){cvox.ChromeVox.recallInit_('ChromeVox not starting; waiting for TTS. '+
document.location.href+'.');return;}
window.console.log('Starting ChromeVox.');cvox.InitGlobals.initGlobals();window.disableChromeVox=function(){cvox.ChromeVox.host.killChromeVox();};};cvox.ChromeVox.reinit=function(){cvox.ChromeVox.host.reinit();cvox.ChromeVox.initDocument();};if(!COMPILED){cvox.ChromeVox.initDocument();}
cvox.ExtensionBridge.addMessageListener(function(msg,port){if(msg['target']=='next'){cvox.ChromeVox.isClassicEnabled_=msg['isClassicEnabled'];}});cvox.ExtensionBridge.addDisconnectListener(function(){if(cvox.ChromeVox.initTimer_>0){window.clearTimeout(cvox.ChromeVox.initTimer_);cvox.ChromeVox.initTimer_=0;}});goog.provide('cvox.ChromeMathJax');goog.require('cvox.AbstractMathJax');goog.require('cvox.ApiImplementation');goog.require('cvox.ChromeVox');goog.require('cvox.HostFactory');goog.require('cvox.ScriptInstaller');cvox.ChromeMathJax=function(){goog.base(this);this.initialized_=false;this.port=null;this.nextCallbackId_=1;this.callbackMap_={};this.texNodeId_=0;this.init();};goog.inherits(cvox.ChromeMathJax,cvox.AbstractMathJax);cvox.ChromeMathJax.prototype.registerCallback_=function(callback){var id=this.nextCallbackId_;this.nextCallbackId_++;this.callbackMap_[id]=callback;return id;};cvox.ChromeMathJax.prototype.retrieveCallback_=function(idStr){var id=parseInt(idStr,10);var callback=this.callbackMap_[id];if(callback){return callback;}
return null;};cvox.ChromeMathJax.prototype.init=function(){window.addEventListener('message',goog.bind(this.portSetup,this),true);var scripts=new Array();scripts.push(cvox.ChromeVox.host.getFileSrc('chromevox/injected/mathjax_external_util.js'));scripts.push(cvox.ChromeVox.host.getFileSrc('chromevox/injected/mathjax.js'));scripts.push(cvox.ApiImplementation.siteSpecificScriptLoader);this.initialized_=cvox.ScriptInstaller.installScript(scripts,'mathjax',undefined,cvox.ApiImplementation.siteSpecificScriptBase);};cvox.ChromeMathJax.prototype.postMsg=function(data,callback,args){args=args||{};var id=this.registerCallback_(callback);var idStr=id.toString();this.port.postMessage({'cmd':data,'id':idStr,'args':args});};cvox.ChromeMathJax.prototype.portSetup=function(event){if(event.data=='cvox.MathJaxPortSetup'){this.port=event.ports[0];this.port.onmessage=goog.bind(function(event){this.dispatchMessage(event.data);},this);return false;}
return true;};cvox.ChromeMathJax.prototype.dispatchMessage=function(message){var method;var argNames=[];switch(message['cmd']){case'NodeMml':method=this.convertMarkupToDom;argNames=['mathml','elementId'];break;case'Active':method=this.applyBoolean;argNames=['status'];break;}
if(!method){throw'Unknown MathJax call: '+message['cmd'];}
var callback=this.retrieveCallback_(message['id']);var args=message['args'];if(callback&&method){method.apply(this,[callback].concat(argNames.map(function(x){return args[x];})));}};cvox.ChromeMathJax.prototype.applyBoolean=function(callback,bool){callback(bool);};cvox.ChromeMathJax.prototype.isMathjaxActive=function(callback){if(!this.initialized_){callback(false);return;}
var retries=0;var fetch=goog.bind(function(){retries++;try{this.postMsg('Active',function(result){if(result){callback(result);}else if(retries<5){setTimeout(fetch,1000);}});}catch(x){if(retries<5){setTimeout(fetch,1000);}else{throw x;}}},this);fetch();};cvox.ChromeMathJax.prototype.getAllJax=function(callback){this.postMsg('AllJax',callback);};cvox.ChromeMathJax.prototype.registerSignal=function(callback,signal){this.postMsg('RegSig',callback,{sig:signal});};cvox.ChromeMathJax.prototype.injectScripts=function(){var retries=0;var fetch=goog.bind(function(){retries++;if(this.port){this.postMsg('InjectScripts',function(){});}else if(retries<10){setTimeout(fetch,500);}},this);fetch();};cvox.ChromeMathJax.prototype.configMediaWiki=function(){this.postMsg('ConfWikipedia',function(){});};cvox.ChromeMathJax.prototype.getTex=function(callback,tex){var altText=tex['alt']||tex['title'];if(altText){var newId='cvoxId-'+this.texNodeId_++;tex.setAttribute('cvoxId',newId);this.postMsg('TexToMml',callback,{alt:altText,id:newId});}};cvox.ChromeMathJax.prototype.getAsciiMath=function(callback,asciiMathNode){var altText=asciiMathNode['alt']||asciiMathNode['title'];if(altText){var newId='cvoxId-'+this.texNodeId_++;asciiMathNode.setAttribute('cvoxId',newId);this.postMsg('AsciiMathToMml',callback,{alt:altText,id:newId});}};cvox.HostFactory.mathJaxConstructor=cvox.ChromeMathJax;goog.provide('cvox.ChromeBraille');goog.require('cvox.BrailleInterface');goog.require('cvox.BrailleKeyEvent');goog.require('cvox.ChromeVoxUserCommands');goog.require('cvox.HostFactory');cvox.ChromeBraille=function(){this.lastContent_=null;this.lastContentId_='';this.nextLocalId_=1;cvox.ExtensionBridge.addMessageListener(goog.bind(function(msg,port){if(!cvox.ChromeVox.documentHasFocus()){return;}
if(msg['message']=='BRAILLE'&&msg['args']){var content=null;if(msg['contentId']==this.lastContentId_){content=this.lastContent_;}
this.onKeyEvent_(msg['args'],content);}},this));};cvox.ChromeBraille.prototype.write=function(params){this.lastContent_=params;this.updateLastContentId_();var outParams=params.toJson();var message={'target':'BRAILLE','action':'write','params':outParams,'contentId':this.lastContentId_};cvox.ExtensionBridge.send(message);};cvox.ChromeBraille.prototype.updateLastContentId_=function(){this.lastContentId_=cvox.ExtensionBridge.uniqueId()+'.'+
this.nextLocalId_++;};cvox.ChromeBraille.prototype.onKeyEvent_=function(brailleEvt,content){var command=cvox.ChromeVoxUserCommands.commands[brailleEvt.command];if(command){command({event:brailleEvt,content:content});}else{console.error('Unknown braille command: '+JSON.stringify(brailleEvt));}};cvox.ChromeBraille.prototype.setKeyEventHandlerForTest=function(listener){this.onKeyEvent_=listener;};cvox.HostFactory.brailleConstructor=cvox.ChromeBraille;window.CLOSURE_USE_EXT_MESSAGES=true;goog.require('Msgs');goog.require('cvox.ChromeBraille');goog.require('cvox.ChromeEarcons');goog.require('cvox.ChromeHost');goog.require('cvox.ChromeMathJax');goog.require('cvox.ChromeTts');goog.require('cvox.ChromeVoxInit');if(COMPILED){cvox.ChromeVox.initDocument();}
