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('constants');constants.Dir={FORWARD:'forward',BACKWARD:'backward'};goog.provide('AutomationTreeWalker');goog.provide('AutomationTreeWalkerPhase');goog.provide('AutomationTreeWalkerRestriction');goog.require('constants');AutomationTreeWalkerPhase={INITIAL:'initial',ANCESTOR:'ancestor',DESCENDANT:'descendant',OTHER:'other'};var AutomationTreeWalkerRestriction;AutomationTreeWalker=function(node,dir,opt_restrictions){this.node_=node;this.phase_=AutomationTreeWalkerPhase.INITIAL;this.dir_=dir;this.initialNode_=node;this.backwardAncestor_=node.parent;var restrictions=opt_restrictions||{};this.visitPred_=function(node){if(this.skipInitialAncestry_&&this.phase_==AutomationTreeWalkerPhase.ANCESTOR)
return false;if(this.skipInitialSubtree_&&this.phase!=AutomationTreeWalkerPhase.ANCESTOR&&this.phase!=AutomationTreeWalkerPhase.OTHER)
return false;if(restrictions.visit)
return restrictions.visit(node);return true;};this.leafPred_=restrictions.leaf?restrictions.leaf:AutomationTreeWalker.falsePredicate_;this.rootPred_=restrictions.root?restrictions.root:AutomationTreeWalker.falsePredicate_;this.skipInitialAncestry_=restrictions.skipInitialAncestry||false;this.skipInitialSubtree_=restrictions.skipInitialSubtree||false;};AutomationTreeWalker.falsePredicate_=function(node){return false;};AutomationTreeWalker.prototype={get node(){return this.node_;},get phase(){return this.phase_;},next:function(){if(!this.node_)
return this;do{if(this.rootPred_(this.node_)&&this.dir_==constants.Dir.BACKWARD){this.node_=null;return this;}
if(this.dir_==constants.Dir.FORWARD)
this.forward_(this.node_);else
this.backward_(this.node_);}while(this.node_&&!this.visitPred_(this.node_));return this;},forward_:function(node){if(!this.leafPred_(node)&&node.firstChild){if(this.phase_==AutomationTreeWalkerPhase.INITIAL)
this.phase_=AutomationTreeWalkerPhase.DESCENDANT;if(!this.skipInitialSubtree_||this.phase!=AutomationTreeWalkerPhase.DESCENDANT){this.node_=node.firstChild;return;}}
var searchNode=node;while(searchNode){if(searchNode==this.initialNode_)
this.phase_=AutomationTreeWalkerPhase.OTHER;if(searchNode.nextSibling){this.node_=searchNode.nextSibling;return;}
if(searchNode.parent&&this.rootPred_(searchNode.parent))
break;searchNode=searchNode.parent;}
this.node_=null;},backward_:function(node){if(node.previousSibling){this.phase_=AutomationTreeWalkerPhase.OTHER;node=node.previousSibling;while(!this.leafPred_(node)&&node.lastChild)
node=node.lastChild;this.node_=node;return;}
if(node.parent&&this.backwardAncestor_==node.parent){this.phase_=AutomationTreeWalkerPhase.ANCESTOR;this.backwardAncestor_=node.parent.parent;}
this.node_=node.parent;}};goog.provide('AutomationPredicate');goog.provide('AutomationPredicate.Binary');goog.provide('AutomationPredicate.Unary');goog.require('constants');goog.scope(function(){var AutomationNode=chrome.automation.AutomationNode;var Dir=constants.Dir;var Role=chrome.automation.RoleType;AutomationPredicate=function(){};AutomationPredicate.Unary;AutomationPredicate.Binary;AutomationPredicate.roles=function(roles){return AutomationPredicate.match({anyRole:roles});};AutomationPredicate.match=function(params){var anyRole=params.anyRole||[];var anyPredicate=params.anyPredicate||[];return function(node){return anyRole.some(function(role){return role==node.role;})||anyPredicate.some(function(p){return p(node);});};};AutomationPredicate.checkBox=AutomationPredicate.roles([Role.checkBox]);AutomationPredicate.comboBox=AutomationPredicate.roles([Role.comboBox,Role.popUpButton,Role.menuListPopup]);AutomationPredicate.heading=AutomationPredicate.roles([Role.heading]);AutomationPredicate.inlineTextBox=AutomationPredicate.roles([Role.inlineTextBox]);AutomationPredicate.link=AutomationPredicate.roles([Role.link]);AutomationPredicate.row=AutomationPredicate.roles([Role.row]);AutomationPredicate.table=AutomationPredicate.roles([Role.grid,Role.table]);AutomationPredicate.button=function(node){return/button/i.test(node.role);};AutomationPredicate.editText=function(node){return node.state.editable&&node.parent&&!node.parent.state.editable;};AutomationPredicate.formField=AutomationPredicate.match({anyPredicate:[AutomationPredicate.button,AutomationPredicate.comboBox,AutomationPredicate.editText],anyRole:[Role.checkBox,Role.listBox,Role.slider,Role.tab,Role.tree]});AutomationPredicate.landmark=AutomationPredicate.roles([Role.application,Role.banner,Role.complementary,Role.contentInfo,Role.form,Role.main,Role.navigation,Role.region,Role.search]);AutomationPredicate.visitedLink=function(node){return node.state.visited;};AutomationPredicate.focused=function(node){return node.state.focused;};AutomationPredicate.leaf=function(node){return!node.firstChild||node.role==Role.button||node.role==Role.buttonDropDown||node.role==Role.popUpButton||node.role==Role.slider||node.role==Role.textField||node.state.invisible||node.children.every(function(n){return n.state.invisible;});};AutomationPredicate.leafWithText=function(node){return AutomationPredicate.leaf(node)&&!!(node.name||node.value);};AutomationPredicate.leafOrStaticText=function(node){return AutomationPredicate.leaf(node)||node.role==Role.staticText;};AutomationPredicate.object=function(node){if(node.parent&&node.parent.state.editable)
return false;return node.state.focusable||(AutomationPredicate.leafOrStaticText(node)&&(/\S+/.test(node.name)||(node.role!=Role.lineBreak&&node.role!=Role.staticText&&node.role!=Role.inlineTextBox)));};AutomationPredicate.group=AutomationPredicate.match({anyRole:[Role.heading,Role.list,Role.paragraph],anyPredicate:[AutomationPredicate.editText,AutomationPredicate.formField,AutomationPredicate.object,AutomationPredicate.table]});AutomationPredicate.linebreak=function(first,second){var fl=first.location;var sl=second.location;return fl.top!=sl.top||(fl.top+fl.height!=sl.top+sl.height);};AutomationPredicate.container=function(node){return AutomationPredicate.structuralContainer(node)||node.role==Role.div||node.role==Role.document||node.role==Role.group||node.role==Role.listItem||node.role==Role.toolbar||node.role==Role.window||(node.role==Role.textField&&node.state.readOnly)||(node.state.editable&&node.parent&&!node.parent.state.editable);};AutomationPredicate.structuralContainer=AutomationPredicate.roles([Role.rootWebArea,Role.embeddedObject,Role.iframe,Role.iframePresentational]);AutomationPredicate.root=function(node){switch(node.role){case Role.dialog:case Role.window:return true;case Role.toolbar:return node.root.role==Role.desktop;case Role.rootWebArea:return!node.parent||node.parent.root.role==Role.desktop;default:return false;}};AutomationPredicate.shouldIgnoreNode=function(node){if(node.state.invisible||(node.location.height==0&&node.location.width==0))
return true;if(AutomationPredicate.structuralContainer(node))
return true;if(node.role==Role.listMarker)
return true;if(node.name||node.value||node.description)
return false;return AutomationPredicate.leaf(node)&&(AutomationPredicate.roles([Role.client,Role.column,Role.div,Role.group,Role.image,Role.staticText,Role.svgRoot,Role.tableHeaderContainer])(node));};AutomationPredicate.checkable=AutomationPredicate.roles([Role.checkBox,Role.radioButton,Role.menuItemCheckBox,Role.menuItemRadio,Role.treeItem]);AutomationPredicate.cellLike=AutomationPredicate.roles([Role.cell,Role.rowHeader,Role.columnHeader]);AutomationPredicate.makeTableCellPredicate=function(start,opts){if(!opts.row&&!opts.col)
throw new Error('You must set either row or col to true');var dir=opts.dir||Dir.FORWARD;var rowIndex=0,colIndex=0;var tableNode=start;while(tableNode){if(AutomationPredicate.table(tableNode))
break;if(AutomationPredicate.cellLike(tableNode)){rowIndex=tableNode.tableCellRowIndex;colIndex=tableNode.tableCellColumnIndex;}
tableNode=tableNode.parent;}
if(!tableNode)
return null;if(opts.end){if(!opts.col)
throw'Unsupported option.';if(dir==Dir.FORWARD){return function(node){return AutomationPredicate.cellLike(node)&&node.tableCellColumnIndex==colIndex&&node.tableCellRowIndex>=0;};}else{return function(node){return AutomationPredicate.cellLike(node)&&node.tableCellColumnIndex==colIndex&&node.tableCellRowIndex<tableNode.tableRowCount;};}}
if(opts.row)
rowIndex=dir==Dir.FORWARD?rowIndex+1:rowIndex-1;if(opts.col)
colIndex=dir==Dir.FORWARD?colIndex+1:colIndex-1;return function(node){return AutomationPredicate.cellLike(node)&&node.tableCellColumnIndex==colIndex&&node.tableCellRowIndex==rowIndex;};};AutomationPredicate.makeHeadingPredicate=function(level){return function(node){return node.role==Role.heading&&node.hierarchicalLevel==level;};};});goog.provide('AutomationUtil');goog.require('AutomationPredicate');goog.require('AutomationTreeWalker');goog.require('constants');AutomationUtil=function(){};goog.scope(function(){var AutomationNode=chrome.automation.AutomationNode;var Dir=constants.Dir;var RoleType=chrome.automation.RoleType;AutomationUtil.findNodePre=function(cur,dir,pred){if(!cur)
return null;if(pred(cur)&&!AutomationPredicate.shouldIgnoreNode(cur))
return cur;var child=dir==Dir.BACKWARD?cur.lastChild:cur.firstChild;while(child){var ret=AutomationUtil.findNodePre(child,dir,pred);if(ret)
return ret;child=dir==Dir.BACKWARD?child.previousSibling:child.nextSibling;}
return null;};AutomationUtil.findNodePost=function(cur,dir,pred){if(!cur)
return null;var child=dir==Dir.BACKWARD?cur.lastChild:cur.firstChild;while(child){var ret=AutomationUtil.findNodePost(child,dir,pred);if(ret)
return ret;child=dir==Dir.BACKWARD?child.previousSibling:child.nextSibling;}
if(pred(cur)&&!AutomationPredicate.shouldIgnoreNode(cur))
return cur;return null;};AutomationUtil.findNextNode=function(cur,dir,pred,opt_restrictions){var restrictions={};opt_restrictions=opt_restrictions||{leaf:undefined,root:undefined,visit:undefined,skipInitialSubtree:!AutomationPredicate.container(cur)&&pred(cur)};restrictions.root=opt_restrictions.root||AutomationPredicate.root;restrictions.leaf=opt_restrictions.leaf||function(node){return!AutomationPredicate.container(node)&&pred(node);};restrictions.skipInitialSubtree=opt_restrictions.skipInitialSubtree;restrictions.skipInitialAncestry=opt_restrictions.skipInitialAncestry;restrictions.visit=function(node){return pred(node)&&!AutomationPredicate.shouldIgnoreNode(node);};var walker=new AutomationTreeWalker(cur,dir,restrictions);return walker.next().node;};AutomationUtil.findNodeUntil=function(cur,dir,pred,opt_before){var before=cur;var after=before;do{before=after;after=AutomationUtil.findNextNode(before,dir,AutomationPredicate.leaf);}while(after&&!pred(before,after));return opt_before?before:after;};AutomationUtil.getAncestors=function(node){var ret=[];var candidate=node;while(candidate){ret.push(candidate);candidate=candidate.parent;}
return ret.reverse();};AutomationUtil.getDivergence=function(ancestorsA,ancestorsB){for(var i=0;i<ancestorsA.length;i++){if(ancestorsA[i]!==ancestorsB[i])
return i;}
if(ancestorsA.length==ancestorsB.length)
return-1;return ancestorsA.length;};AutomationUtil.getUniqueAncestors=function(prevNode,node){var prevAncestors=AutomationUtil.getAncestors(prevNode);var ancestors=AutomationUtil.getAncestors(node);var divergence=AutomationUtil.getDivergence(prevAncestors,ancestors);return ancestors.slice(divergence);};AutomationUtil.getDirection=function(nodeA,nodeB){var ancestorsA=AutomationUtil.getAncestors(nodeA);var ancestorsB=AutomationUtil.getAncestors(nodeB);var divergence=AutomationUtil.getDivergence(ancestorsA,ancestorsB);if(divergence==-1)
return Dir.FORWARD;var divA=ancestorsA[divergence];var divB=ancestorsB[divergence];if(!divA)
return Dir.FORWARD;if(!divB)
return Dir.BACKWARD;if(divA.parent===nodeB)
return Dir.BACKWARD;if(divB.parent===nodeA)
return Dir.FORWARD;return divA.indexInParent<=divB.indexInParent?Dir.FORWARD:Dir.BACKWARD;};AutomationUtil.isInSameTree=function(a,b){if(!a||!b)
return true;return a.root===b.root||(a.root.role==b.root.role&&a.root.role==RoleType.rootWebArea);};AutomationUtil.isDescendantOf=function(node,ancestor){var testNode=node;while(testNode&&testNode!==ancestor)
testNode=testNode.parent;return testNode===ancestor;};AutomationUtil.hitTest=function(node,point){var loc=node.location;var child=node.firstChild;while(child){var hit=AutomationUtil.hitTest(child,point);if(hit)
return hit;child=child.nextSibling;}
if(point.x<=(loc.left+loc.width)&&point.x>=loc.left&&point.y<=(loc.top+loc.height)&&point.y>=loc.top)
return node;return null;};AutomationUtil.getTopLevelRoot=function(node){var root=node.root;if(!root||root.role==RoleType.desktop)
return null;while(root&&root.parent&&root.parent.root&&root.parent.root.role!=RoleType.desktop){root=root.parent.root;}
return root;};});goog.provide('StringUtil');StringUtil=function(){};StringUtil.longestCommonPrefixLength=function(first,second){var limit=Math.min(first.length,second.length);var i;for(i=0;i<limit;++i){if(first.charAt(i)!=second.charAt(i)){break;}}
return i;};StringUtil.MAX_BMP_CODEPOINT=65535;StringUtil.nextCodePointOffset=function(str,offset){if(offset>=str.length)
return str.length;if(str.codePointAt(offset)>StringUtil.MAX_BMP_CODEPOINT)
return offset+2;return offset+1;};StringUtil.previousCodePointOffset=function(str,offset){if(offset<=0)
return-1;if(offset>1&&str.codePointAt(offset-2)>StringUtil.MAX_BMP_CODEPOINT)
return offset-2;return offset-1;};goog.provide('cursors.Cursor');goog.provide('cursors.Movement');goog.provide('cursors.Range');goog.provide('cursors.Unit');goog.require('AutomationPredicate');goog.require('AutomationUtil');goog.require('StringUtil');goog.require('constants');cursors.NODE_INDEX=-1;cursors.Unit={CHARACTER:'character',WORD:'word',NODE:'node',LINE:'line'};cursors.Movement={BOUND:'bound',DIRECTIONAL:'directional'};goog.scope(function(){var AutomationNode=chrome.automation.AutomationNode;var Dir=constants.Dir;var Movement=cursors.Movement;var RoleType=chrome.automation.RoleType;var Unit=cursors.Unit;cursors.Cursor=function(node,index){this.index_=index;this.ancestry_=[];var nodeWalker=node;while(nodeWalker){this.ancestry_.push(nodeWalker);nodeWalker=nodeWalker.parent;if(nodeWalker&&AutomationPredicate.root(nodeWalker))
break;}};cursors.Cursor.fromNode=function(node){return new cursors.Cursor(node,cursors.NODE_INDEX);};cursors.Cursor.prototype={equals:function(rhs){return this.node===rhs.node&&this.index===rhs.index;},contentEquals:function(rhs){var lNode=this.node;var rNode=rhs.node;while(lNode&&(lNode.role==RoleType.inlineTextBox||lNode.role==RoleType.staticText))
lNode=lNode.parent;while(rNode&&(rNode.role==RoleType.inlineTextBox||rNode.role==RoleType.staticText))
rNode=rNode.parent;return lNode===rNode&&lNode!=undefined;},get node(){for(var i=0;i<this.ancestry_.length;i++){var firstValidNode=this.ancestry_[i];if(firstValidNode!=null&&firstValidNode.role!==undefined&&firstValidNode.root!==undefined){return firstValidNode;}
this.index_=cursors.NODE_INDEX;}
return null;},get index(){return this.index_;},get selectionNode_(){var adjustedNode=this.node;if(!adjustedNode)
return null;var parent=adjustedNode.parent;var grandparent=parent&&parent.parent;if(parent.role==RoleType.lineBreak){adjustedNode=grandparent;}else if(grandparent.role==RoleType.lineBreak){adjustedNode=grandparent.parent;}else if(this.index_==cursors.NODE_INDEX||adjustedNode.role==RoleType.inlineTextBox||chrome.automation.NameFromType[adjustedNode.nameFrom]!='contents'){adjustedNode=parent;}else{adjustedNode=adjustedNode.find({role:RoleType.staticText})||adjustedNode;}
return adjustedNode;},get selectionIndex_(){var adjustedIndex=this.index_;if(this.node.role==RoleType.inlineTextBox&&this.node.parent&&this.node.parent.role!=RoleType.lineBreak){if(adjustedIndex==cursors.NODE_INDEX)
adjustedIndex=0;var sibling=this.node.previousSibling;while(sibling){adjustedIndex+=sibling.name.length;sibling=sibling.previousSibling;}}else if(this.index_==cursors.NODE_INDEX||chrome.automation.NameFromType[this.node.nameFrom]!='contents'){var childOfSelection=this.node;do{adjustedIndex=childOfSelection.indexInParent;childOfSelection=childOfSelection.parent;}while(childOfSelection&&childOfSelection!=this.selectionNode_);}
return adjustedIndex;},getText:function(opt_node){var node=opt_node||this.node;if(node.role===RoleType.textField)
return node.value;return node.name||'';},move:function(unit,movement,dir){var originalNode=this.node;if(!originalNode)
return this;var newNode=originalNode;var newIndex=this.index_;if(unit!=Unit.NODE&&newIndex===cursors.NODE_INDEX)
newIndex=0;switch(unit){case Unit.CHARACTER:var text=this.getText();newIndex=dir==Dir.FORWARD?StringUtil.nextCodePointOffset(text,newIndex):StringUtil.previousCodePointOffset(text,newIndex);if(newIndex<0||newIndex>=text.length){newNode=AutomationUtil.findNextNode(newNode,dir,AutomationPredicate.leafWithText);if(newNode){var newText=this.getText(newNode);newIndex=dir==Dir.FORWARD?0:StringUtil.previousCodePointOffset(newText,newText.length);newIndex=Math.max(newIndex,0);}else{newIndex=this.index_;}}
break;case Unit.WORD:if(newNode.role!=RoleType.inlineTextBox){newNode=AutomationUtil.findNextNode(newNode,Dir.FORWARD,AutomationPredicate.inlineTextBox,{skipInitialSubtree:false})||newNode;}
switch(movement){case Movement.BOUND:if(newNode.role==RoleType.inlineTextBox){var start,end;for(var i=0;i<newNode.wordStarts.length;i++){if(newIndex>=newNode.wordStarts[i]&&newIndex<=newNode.wordEnds[i]){start=newNode.wordStarts[i];end=newNode.wordEnds[i];break;}}
if(goog.isDef(start)&&goog.isDef(end))
newIndex=dir==Dir.FORWARD?end:start;}else{}
break;case Movement.DIRECTIONAL:if(newNode.role==RoleType.inlineTextBox){var start,end;for(var i=0;i<newNode.wordStarts.length;i++){if(newIndex>=newNode.wordStarts[i]&&newIndex<=newNode.wordEnds[i]){var nextIndex=dir==Dir.FORWARD?i+1:i-1;start=newNode.wordStarts[nextIndex];end=newNode.wordEnds[nextIndex];break;}}
if(goog.isDef(start)){newIndex=start;}else{if(dir==Dir.BACKWARD&&newIndex!=0){newIndex=0;}else{newNode=AutomationUtil.findNextNode(newNode,dir,AutomationPredicate.leaf);if(newNode){newIndex=0;if(dir==Dir.BACKWARD&&newNode.role==RoleType.inlineTextBox){var starts=newNode.wordStarts;newIndex=starts[starts.length-1]||0;}else{}}}}}else{}}
break;case Unit.NODE:switch(movement){case Movement.BOUND:newIndex=dir==Dir.FORWARD?this.getText().length-1:0;break;case Movement.DIRECTIONAL:newNode=AutomationUtil.findNextNode(newNode,dir,AutomationPredicate.object)||originalNode;newIndex=cursors.NODE_INDEX;break;}
break;case Unit.LINE:newIndex=0;switch(movement){case Movement.BOUND:newNode=AutomationUtil.findNodeUntil(newNode,dir,AutomationPredicate.linebreak,true);newNode=newNode||originalNode;newIndex=dir==Dir.FORWARD?this.getText(newNode).length:0;break;case Movement.DIRECTIONAL:newNode=AutomationUtil.findNodeUntil(newNode,dir,AutomationPredicate.linebreak);break;}
break;default:throw Error('Unrecognized unit: '+unit);}
newNode=newNode||originalNode;newIndex=goog.isDef(newIndex)?newIndex:this.index_;return new cursors.Cursor(newNode,newIndex);},isValid:function(){return this.node!=null;}};cursors.WrappingCursor=function(node,index){cursors.Cursor.call(this,node,index);};cursors.WrappingCursor.fromNode=function(node){return new cursors.WrappingCursor(node,cursors.NODE_INDEX);};cursors.WrappingCursor.prototype={__proto__:cursors.Cursor.prototype,move:function(unit,movement,dir){var result=this;if(!result.node)
return this;if(!AutomationPredicate.root(this.node)||dir==Dir.FORWARD||movement==Movement.BOUND)
result=cursors.Cursor.prototype.move.call(this,unit,movement,dir);if(movement==Movement.BOUND)
return new cursors.WrappingCursor(result.node,result.index);if(movement==Movement.DIRECTIONAL&&result.equals(this)){var pred=unit==Unit.NODE?AutomationPredicate.object:AutomationPredicate.leaf;var endpoint=this.node;if(!endpoint)
return this;while(!AutomationPredicate.root(endpoint)&&endpoint.parent)
endpoint=endpoint.parent;var playEarcon=dir==Dir.FORWARD;if(dir==Dir.BACKWARD&&endpoint==this.node){playEarcon=true;endpoint=AutomationUtil.findNodePre(endpoint,dir,function(n){return pred(n)&&!AutomationPredicate.shouldIgnoreNode(n);})||endpoint;}
if(playEarcon)
cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP);return new cursors.WrappingCursor(endpoint,cursors.NODE_INDEX);}
return new cursors.WrappingCursor(result.node,result.index);}};cursors.Range=function(start,end){this.start_=start;this.end_=end;};cursors.Range.fromNode=function(node){var cursor=cursors.WrappingCursor.fromNode(node);return new cursors.Range(cursor,cursor);};cursors.Range.getDirection=function(rangeA,rangeB){if(!rangeA||!rangeB)
return Dir.FORWARD;if(!rangeA.start.node||!rangeA.end.node||!rangeB.start.node||!rangeB.end.node)
return Dir.FORWARD;if(rangeA.start.node===rangeB.start.node&&rangeB.end.node===rangeA.end.node)
return Dir.FORWARD;var testDirA=AutomationUtil.getDirection(rangeA.start.node,rangeB.end.node);var testDirB=AutomationUtil.getDirection(rangeB.start.node,rangeA.end.node);if(testDirA==Dir.FORWARD&&testDirB==Dir.BACKWARD)
return Dir.FORWARD;else if(testDirA==Dir.BACKWARD&&testDirB==Dir.FORWARD)
return Dir.BACKWARD;else
return testDirA;};cursors.Range.prototype={equals:function(rhs){return this.start_.equals(rhs.start)&&this.end_.equals(rhs.end);},contentEquals:function(rhs){return this.start_.contentEquals(rhs.start)&&this.end_.contentEquals(rhs.end);},getBound:function(dir,opt_reverse){if(opt_reverse)
return dir==Dir.BACKWARD?this.end_:this.start_;return dir==Dir.FORWARD?this.end_:this.start_;},get start(){return this.start_;},get end(){return this.end_;},isSubNode:function(){return this.start.node===this.end.node&&this.start.index>-1&&this.end.index>-1;},move:function(unit,dir){var newStart=this.start_;if(!newStart.node)
return this;var newEnd;switch(unit){case Unit.CHARACTER:newStart=newStart.move(unit,Movement.DIRECTIONAL,dir);newEnd=newStart.move(unit,Movement.DIRECTIONAL,Dir.FORWARD);if(newStart.node!==newEnd.node)
newEnd=new cursors.Cursor(newStart.node,newStart.index+1);break;case Unit.WORD:case Unit.LINE:newStart=newStart.move(unit,Movement.DIRECTIONAL,dir);newStart=newStart.move(unit,Movement.BOUND,Dir.BACKWARD);newEnd=newStart.move(unit,Movement.BOUND,Dir.FORWARD);break;case Unit.NODE:newStart=newStart.move(unit,Movement.DIRECTIONAL,dir);newEnd=newStart;break;default:throw Error('Invalid unit: '+unit);}
return new cursors.Range(newStart,newEnd);},select:function(){var startNode=this.start.selectionNode_;var endNode=this.end.selectionNode_;if(!startNode||!endNode)
return;if(startNode.root&&startNode.root.role==RoleType.rootWebArea&&startNode.root==endNode.root){var startIndex=this.start.selectionIndex_;var endIndex=this.end.index_==cursors.NODE_INDEX?this.end.selectionIndex_+1:this.end.selectionIndex_;chrome.automation.setDocumentSelection({anchorObject:startNode,anchorOffset:startIndex,focusObject:endNode,focusOffset:endIndex});}},isWebRange:function(){return this.isValid()&&(this.start.node.root.role!=RoleType.desktop||this.end.node.root.role!=RoleType.desktop);},isValid:function(){return this.start.isValid()&&this.end.isValid();}};});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('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('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.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('Stubs');goog.require('cvox.ChromeVox');Stubs.init=function(){if(!cvox.ChromeVox.isChromeOS){chrome.accessibilityPrivate.onAccessibilityGesture={};chrome.accessibilityPrivate.onAccessibilityGesture.addListener=function(){};chrome.accessibilityPrivate.setFocusRing=function(){};chrome.accessibilityPrivate.setKeyboardListener=function(){};}
if(cvox.ChromeVox.isMac){chrome.automation.getDesktop=function(){};}
if(!chrome.automation.NameFromType){chrome.automation['NameFromType']={};chrome.automation['DescriptionFromType']={};}};Stubs.init();goog.provide('EarconEngine');EarconEngine=function(){this.masterVolume=1.0;this.masterPitch=-4;this.clickVolume=0.4;this.staticVolume=0.2;this.baseDelay=0.045;this.masterPan=0;this.masterReverb=0.4;this.reverbSound='small_room_2';this.wrapPitch=0;this.alertPitch=0;this.controlSound='control';this.sweepDelay=0.045;this.sweepEchoDelay=0.15;this.sweepEchoCount=3;this.sweepPitch=-7;this.progressFinalGain=0.05;this.progressGain_Decay=0.7;this.context_=new AudioContext();this.reverbConvolver_=null;this.buffers_={};this.progressSources_=[];this.progressGain_=1.0;this.progressTime_=this.context_.currentTime;this.progressIntervalID_=null;var allSoundFilesToLoad=EarconEngine.SOUNDS.concat(EarconEngine.REVERBS);allSoundFilesToLoad.forEach((function(sound){var url=EarconEngine.BASE_URL+sound+'.wav';this.loadSound(sound,url);}).bind(this));};EarconEngine.SOUNDS=['control','selection','selection_reverse','skim','static'];EarconEngine.REVERBS=['small_room_2'];EarconEngine.HALF_STEP=Math.pow(2.0,1.0/12.0);EarconEngine.BASE_URL=chrome.extension.getURL('cvox2/background/earcons/');EarconEngine.prototype.loadSound=function(name,url){var request=new XMLHttpRequest();request.open('GET',url,true);request.responseType='arraybuffer';request.onload=(function(){this.context_.decodeAudioData((request.response),(function(buffer){this.buffers_[name]=buffer;}).bind(this));}).bind(this);request.send();};EarconEngine.prototype.createCommonFilters=function(properties){var gain=this.masterVolume;if(properties.gain){gain*=properties.gain;}
var gainNode=this.context_.createGain();gainNode.gain.value=gain;var first=gainNode;var last=gainNode;var pan=this.masterPan;if(properties.pan!==undefined){pan=properties.pan;}
if(pan!=0){var panNode=this.context_.createPanner();panNode.setPosition(pan,0,-1);panNode.setOrientation(0,0,1);last.connect(panNode);last=panNode;}
var reverb=this.masterReverb;if(properties.reverb!==undefined){reverb=properties.reverb;}
if(reverb){if(!this.reverbConvolver_){this.reverbConvolver_=this.context_.createConvolver();this.reverbConvolver_.buffer=this.buffers_[this.reverbSound];this.reverbConvolver_.connect(this.context_.destination);}
last.connect(this.context_.destination);var reverbGainNode=this.context_.createGain();reverbGainNode.gain.value=reverb;last.connect(reverbGainNode);reverbGainNode.connect(this.reverbConvolver_);}else{last.connect(this.context_.destination);}
return first;};EarconEngine.prototype.play=function(sound,opt_properties){var source=this.context_.createBufferSource();source.buffer=this.buffers_[sound];if(!opt_properties){opt_properties=({});}
var pitch=this.masterPitch;if(opt_properties.pitch){pitch+=opt_properties.pitch;}
if(pitch!=0){source.playbackRate.value=Math.pow(EarconEngine.HALF_STEP,pitch);}
var destination=this.createCommonFilters(opt_properties);source.connect(destination);if(opt_properties.time){source.start(this.context_.currentTime+opt_properties.time);}else{source.start(this.context_.currentTime);}
return source;};EarconEngine.prototype.onStatic=function(){this.play('static',{gain:this.staticVolume});};EarconEngine.prototype.onLink=function(){this.play('static',{gain:this.clickVolume});this.play(this.controlSound,{pitch:12});};EarconEngine.prototype.onButton=function(){this.play('static',{gain:this.clickVolume});this.play(this.controlSound);};EarconEngine.prototype.onTextField=function(){this.play('static',{gain:this.clickVolume});this.play('static',{time:this.baseDelay*1.5,gain:this.clickVolume*0.5});this.play(this.controlSound,{pitch:4});this.play(this.controlSound,{pitch:4,time:this.baseDelay*1.5,gain:0.5});};EarconEngine.prototype.onPopUpButton=function(){this.play('static',{gain:this.clickVolume});this.play(this.controlSound);this.play(this.controlSound,{time:this.baseDelay*3,gain:0.2,pitch:12});this.play(this.controlSound,{time:this.baseDelay*4.5,gain:0.2,pitch:12});};EarconEngine.prototype.onCheckOn=function(){this.play('static',{gain:this.clickVolume});this.play(this.controlSound,{pitch:-5});this.play(this.controlSound,{pitch:7,time:this.baseDelay*2});};EarconEngine.prototype.onCheckOff=function(){this.play('static',{gain:this.clickVolume});this.play(this.controlSound,{pitch:7});this.play(this.controlSound,{pitch:-5,time:this.baseDelay*2});};EarconEngine.prototype.onSelect=function(){this.play('static',{gain:this.clickVolume});this.play(this.controlSound);this.play(this.controlSound,{time:this.baseDelay});this.play(this.controlSound,{time:this.baseDelay*2});};EarconEngine.prototype.onSlider=function(){this.play('static',{gain:this.clickVolume});this.play(this.controlSound);this.play(this.controlSound,{time:this.baseDelay,gain:0.5,pitch:2});this.play(this.controlSound,{time:this.baseDelay*2,gain:0.25,pitch:4});this.play(this.controlSound,{time:this.baseDelay*3,gain:0.125,pitch:6});this.play(this.controlSound,{time:this.baseDelay*4,gain:0.0625,pitch:8});};EarconEngine.prototype.onSkim=function(){this.play('skim');};EarconEngine.prototype.onSelection=function(){this.play('selection');};EarconEngine.prototype.onSelectionReverse=function(){this.play('selection_reverse');};EarconEngine.prototype.generateSinusoidal=function(properties){var envelopeNode=this.context_.createGain();envelopeNode.connect(this.context_.destination);var time=properties.time;if(time===undefined){time=0;}
var gain=properties.gain;for(var i=0;i<properties.overtones;i++){var osc=this.context_.createOscillator();osc.frequency.value=properties.freq*(i+1);if(properties.endFreq){osc.frequency.setValueAtTime(properties.freq*(i+1),this.context_.currentTime+time);osc.frequency.exponentialRampToValueAtTime(properties.endFreq*(i+1),this.context_.currentTime+properties.dur);}
osc.start(this.context_.currentTime+time);osc.stop(this.context_.currentTime+time+properties.dur);var gainNode=this.context_.createGain();gainNode.gain.value=gain;osc.connect(gainNode);gainNode.connect(envelopeNode);gain*=properties.overtoneFactor;}
envelopeNode.gain.setValueAtTime(0,this.context_.currentTime+time);envelopeNode.gain.linearRampToValueAtTime(1,this.context_.currentTime+time+properties.attack);envelopeNode.gain.setValueAtTime(1,this.context_.currentTime+time+
properties.dur-properties.decay);envelopeNode.gain.linearRampToValueAtTime(0,this.context_.currentTime+time+properties.dur);var destination=this.createCommonFilters({});envelopeNode.connect(destination);};EarconEngine.prototype.onChromeVoxSweep=function(reverse){var pitches=[-7,-5,0,5,7,12,17,19,24];if(reverse){pitches.reverse();}
var attack=0.015;var dur=pitches.length*this.sweepDelay;var destination=this.createCommonFilters({reverb:2.0});for(var k=0;k<this.sweepEchoCount;k++){var envelopeNode=this.context_.createGain();var startTime=this.context_.currentTime+this.sweepEchoDelay*k;var sweepGain=Math.pow(0.3,k);var overtones=2;var overtoneGain=sweepGain;for(var i=0;i<overtones;i++){var osc=this.context_.createOscillator();osc.start(startTime);osc.stop(startTime+dur);var gainNode=this.context_.createGain();osc.connect(gainNode);gainNode.connect(envelopeNode);for(var j=0;j<pitches.length;j++){var freqDecay;if(reverse){freqDecay=Math.pow(0.75,pitches.length-j);}else{freqDecay=Math.pow(0.75,j);}
var gain=overtoneGain*freqDecay;var freq=(i+1)*220*Math.pow(EarconEngine.HALF_STEP,pitches[j]+this.sweepPitch);if(j==0){osc.frequency.setValueAtTime(freq,startTime);gainNode.gain.setValueAtTime(gain,startTime);}else{osc.frequency.exponentialRampToValueAtTime(freq,startTime+j*this.sweepDelay);gainNode.gain.linearRampToValueAtTime(gain,startTime+j*this.sweepDelay);}
osc.frequency.setValueAtTime(freq,startTime+j*this.sweepDelay+this.sweepDelay-attack);}
overtoneGain*=0.1+0.2*k;}
envelopeNode.gain.setValueAtTime(0,startTime);envelopeNode.gain.linearRampToValueAtTime(1,startTime+this.sweepDelay);envelopeNode.gain.setValueAtTime(1,startTime+dur-attack*2);envelopeNode.gain.linearRampToValueAtTime(0,startTime+dur);envelopeNode.connect(destination);}};EarconEngine.prototype.onChromeVoxOn=function(){this.onChromeVoxSweep(false);};EarconEngine.prototype.onChromeVoxOff=function(){this.onChromeVoxSweep(true);};EarconEngine.prototype.onAlert=function(){var freq1=220*Math.pow(EarconEngine.HALF_STEP,this.alertPitch-2);var freq2=220*Math.pow(EarconEngine.HALF_STEP,this.alertPitch-3);this.generateSinusoidal({attack:0.02,decay:0.07,dur:0.15,gain:0.3,freq:freq1,overtones:3,overtoneFactor:0.1});this.generateSinusoidal({attack:0.02,decay:0.07,dur:0.15,gain:0.3,freq:freq2,overtones:3,overtoneFactor:0.1});};EarconEngine.prototype.onWrap=function(){this.play('static',{gain:this.clickVolume*0.3});var freq1=220*Math.pow(EarconEngine.HALF_STEP,this.wrapPitch-8);var freq2=220*Math.pow(EarconEngine.HALF_STEP,this.wrapPitch+8);this.generateSinusoidal({attack:0.01,decay:0.1,dur:0.15,gain:0.3,freq:freq1,endFreq:freq2,overtones:1,overtoneFactor:0.1});};EarconEngine.prototype.generateProgressTickTocks_=function(){while(this.progressTime_<this.context_.currentTime+3.0){var t=this.progressTime_-this.context_.currentTime;this.progressSources_.push([this.progressTime_,this.play('static',{gain:0.5*this.progressGain_,time:t})]);this.progressSources_.push([this.progressTime_,this.play(this.controlSound,{pitch:20,time:t,gain:this.progressGain_})]);if(this.progressGain_>this.progressFinalGain){this.progressGain_*=this.progressGain_Decay;}
t+=0.5;this.progressSources_.push([this.progressTime_,this.play('static',{gain:0.5*this.progressGain_,time:t})]);this.progressSources_.push([this.progressTime_,this.play(this.controlSound,{pitch:8,time:t,gain:this.progressGain_})]);if(this.progressGain_>this.progressFinalGain){this.progressGain_*=this.progressGain_Decay;}
this.progressTime_+=1.0;}
var removeCount=0;while(removeCount<this.progressSources_.length&&this.progressSources_[removeCount][0]<this.context_.currentTime-0.2){removeCount++;}
this.progressSources_.splice(0,removeCount);};EarconEngine.prototype.startProgress=function(){if(this.progressIntervalID_){this.cancelProgress();}
this.progressSources_=[];this.progressGain_=0.5;this.progressTime_=this.context_.currentTime;this.generateProgressTickTocks_();this.progressIntervalID_=window.setInterval(this.generateProgressTickTocks_.bind(this),1000);};EarconEngine.prototype.cancelProgress=function(){if(!this.progressIntervalID_){return;}
for(var i=0;i<this.progressSources_.length;i++){this.progressSources_[i][1].stop();}
this.progressSources_=[];window.clearInterval(this.progressIntervalID_);this.progressIntervalID_=null;};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.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.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('Output');goog.provide('Output.EventType');goog.require('AutomationTreeWalker');goog.require('EarconEngine');goog.require('Spannable');goog.require('Stubs');goog.require('constants');goog.require('cursors.Cursor');goog.require('cursors.Range');goog.require('cursors.Unit');goog.require('cvox.AbstractEarcons');goog.require('cvox.ChromeVox');goog.require('cvox.NavBraille');goog.require('cvox.TtsCategory');goog.require('cvox.ValueSelectionSpan');goog.require('cvox.ValueSpan');goog.require('goog.i18n.MessageFormat');goog.scope(function(){var AutomationNode=chrome.automation.AutomationNode;var Dir=constants.Dir;var EventType=chrome.automation.EventType;var RoleType=chrome.automation.RoleType;Output=function(){this.speechBuffer_=[];this.brailleBuffer_=[];this.locations_=[];this.speechEndCallback_;this.formatOptions_={speech:true,braille:false,auralStyle:false};this.speechCategory_=cvox.TtsCategory.NAV;this.queueMode_=cvox.QueueMode.QUEUE;this.outputContextFirst_=false;};Output.SPACE=' ';Output.ROLE_INFO_={alert:{msgId:'role_alert',earconId:'ALERT_NONMODAL'},alertDialog:{msgId:'role_alertdialog',outputContextFirst:true},article:{msgId:'role_article',inherits:'abstractContainer'},application:{msgId:'role_application',inherits:'abstractContainer'},banner:{msgId:'role_banner',inherits:'abstractContainer'},button:{msgId:'role_button',earconId:'BUTTON'},buttonDropDown:{msgId:'role_button',earconId:'BUTTON'},checkBox:{msgId:'role_checkbox'},columnHeader:{msgId:'role_columnheader',inherits:'cell'},comboBox:{msgId:'role_combobox',earconId:'LISTBOX'},complementary:{msgId:'role_complementary',inherits:'abstractContainer'},contentInfo:{msgId:'role_contentinfo',inherits:'abstractContainer'},date:{msgId:'input_type_date',inherits:'abstractContainer'},definition:{msgId:'role_definition',inherits:'abstractContainer'},dialog:{msgId:'role_dialog',outputContextFirst:true},directory:{msgId:'role_directory',inherits:'abstractContainer'},document:{msgId:'role_document',inherits:'abstractContainer'},form:{msgId:'role_form',inherits:'abstractContainer'},grid:{msgId:'role_grid'},group:{msgId:'role_group',inherits:'abstractContainer'},heading:{msgId:'role_heading',},image:{msgId:'role_img',},inputTime:{msgId:'input_type_time',inherits:'abstractContainer'},link:{msgId:'role_link',earconId:'LINK'},listBox:{msgId:'role_listbox',earconId:'LISTBOX'},listBoxOption:{msgId:'role_listitem',earconId:'LIST_ITEM'},listItem:{msgId:'role_listitem',earconId:'LIST_ITEM'},log:{msgId:'role_log',},main:{msgId:'role_main',inherits:'abstractContainer'},marquee:{msgId:'role_marquee',},math:{msgId:'role_math',inherits:'abstractContainer'},menu:{msgId:'role_menu',outputContextFirst:true},menuBar:{msgId:'role_menubar',},menuItem:{msgId:'role_menuitem'},menuItemCheckBox:{msgId:'role_menuitemcheckbox'},menuItemRadio:{msgId:'role_menuitemradio'},menuListOption:{msgId:'role_menuitem'},menuListPopup:{msgId:'role_menu'},navigation:{msgId:'role_navigation',inherits:'abstractContainer'},note:{msgId:'role_note',inherits:'abstractContainer'},popUpButton:{msgId:'role_button',earconId:'POP_UP_BUTTON'},radioButton:{msgId:'role_radio'},radioGroup:{msgId:'role_radiogroup',},rootWebArea:{outputContextFirst:true},row:{msgId:'role_row',inherits:'abstractContainer'},rowHeader:{msgId:'role_rowheader',inherits:'cell'},scrollBar:{msgId:'role_scrollbar',},search:{msgId:'role_search',inherits:'abstractContainer'},separator:{msgId:'role_separator',inherits:'abstractContainer'},spinButton:{msgId:'role_spinbutton',earconId:'LISTBOX'},status:{msgId:'role_status'},tab:{msgId:'role_tab'},tabList:{msgId:'role_tablist'},tabPanel:{msgId:'role_tabpanel'},textBox:{msgId:'input_type_text',earconId:'EDITABLE_TEXT'},textField:{msgId:'input_type_text',earconId:'EDITABLE_TEXT'},time:{msgId:'tag_time',inherits:'abstractContainer'},timer:{msgId:'role_timer'},toolbar:{msgId:'role_toolbar'},toggleButton:{msgId:'role_button',inherits:'checkBox'},tree:{msgId:'role_tree'},treeItem:{msgId:'role_treeitem'}};Output.STATE_INFO_={checked:{on:{msgId:'checkbox_checked_state'},off:{msgId:'checkbox_unchecked_state'},omitted:{msgId:'checkbox_unchecked_state'}},collapsed:{on:{msgId:'aria_expanded_false'},off:{msgId:'aria_expanded_true'}},disabled:{on:{msgId:'aria_disabled_true'}},expanded:{on:{msgId:'aria_expanded_true'},off:{msgId:'aria_expanded_false'}},visited:{on:{msgId:'visited_state'}}};Output.INPUT_TYPE_MESSAGE_IDS_={'email':'input_type_email','number':'input_type_number','password':'input_type_password','search':'input_type_search','tel':'input_type_number','text':'input_type_text','url':'input_type_url',};Output.RULES={navigate:{'default':{speak:'$name $value $state $role $description',braille:''},abstractContainer:{enter:'$nameFromNode $role $state $description',leave:'@exited_container($role)'},alert:{speak:'!doNotInterrupt $role $descendants $state'},alertDialog:{enter:'$nameFromNode $role $description',speak:'$name $role $descendants $state'},cell:{enter:'@cell_summary($tableCellRowIndex, $tableCellColumnIndex) '+'$node(tableColumnHeader)',speak:'@cell_summary($tableCellRowIndex, $tableCellColumnIndex) '+'$node(tableColumnHeader) $state'},checkBox:{speak:'$if($checked, $earcon(CHECK_ON), $earcon(CHECK_OFF)) '+'$name $role $checked $description $state'},client:{speak:'$name'},date:{enter:'$nameFromNode $role $description'},dialog:{enter:'$nameFromNode $role $description'},div:{enter:'$nameFromNode',speak:'$nameOrTextContent $description'},embeddedObject:{speak:'$name'},grid:{enter:'$nameFromNode $role $description'},group:{enter:'$nameFromNode $state $description',speak:'$nameOrDescendants $value $state $description',leave:''},heading:{enter:'!relativePitch(hierarchicalLevel) '+'$nameFromNode= '+'$if($hierarchicalLevel, @tag_h+$hierarchicalLevel, $role) $state',speak:'!relativePitch(hierarchicalLevel) '+'$nameOrDescendants= '+'$if($hierarchicalLevel, @tag_h+$hierarchicalLevel, $role) $state'},inlineTextBox:{speak:'$name='},inputTime:{enter:'$nameFromNode $role $description'},link:{enter:'$nameFromNode= $role $state'},list:{enter:'$role @@list_with_items($countChildren(listItem))',speak:'$descendants $role @@list_with_items($countChildren(listItem))'},listBox:{enter:'$nameFromNode '+'$role @@list_with_items($countChildren(listBoxOption)) '+'$description'},listBoxOption:{speak:'$name $role @describe_index($indexInParent, $parentChildCount) '+'$description $state'},listItem:{enter:'$role'},menu:{enter:'$name $role',speak:'$name $role @@list_with_items($countChildren(menuItem)) $state'},menuItem:{speak:'$name $role $if($haspopup, @has_submenu) '+'@describe_index($indexInParent, $parentChildCount) '+'$description $state'},menuItemCheckBox:{speak:'$if($checked, $earcon(CHECK_ON), $earcon(CHECK_OFF)) '+'$name $role $checked $description '+'@describe_index($indexInParent, $parentChildCount) '},menuItemRadio:{speak:'$if($checked, $earcon(CHECK_ON), $earcon(CHECK_OFF)) '+'$if($checked, @describe_radio_selected($name), '+'@describe_radio_unselected($name)) $description '+'@describe_index($indexInParent, $parentChildCount) '},menuListOption:{speak:'$name @role_menuitem '+'@describe_index($indexInParent, $parentChildCount) $description'},paragraph:{speak:'$descendants'},popUpButton:{speak:'$value $name $role @aria_has_popup '+'$state $description'},radioButton:{speak:'$if($checked, $earcon(CHECK_ON), $earcon(CHECK_OFF)) '+'$if($checked, @describe_radio_selected($name), '+'@describe_radio_unselected($name)) $description'},radioGroup:{enter:'$name $role $description'},rootWebArea:{enter:'$name',speak:'$if($name, $name, $docUrl)'},region:{speak:'$nameOrTextContent'},row:{enter:'$node(tableRowHeader)'},rowHeader:{speak:'$descendants $state'},slider:{speak:'$earcon(SLIDER) @describe_slider($value, $name) $description '+'$state'},staticText:{speak:'$name='},tab:{speak:'@describe_tab($name) $state $description'},table:{enter:'@table_summary($name, $tableRowCount, $tableColumnCount) '+'$node(tableHeader)'},tableHeaderContainer:{speak:'$descendants $state $description'},textField:{speak:'$name $value $if($multiline, @tag_textarea, $if('+'$inputType, $inputType, $role)) $description $state',braille:''},timer:{speak:'$nameFromNode $descendants $value $state $description'},toggleButton:{speak:'$if($pressed, $earcon(CHECK_ON), $earcon(CHECK_OFF)) '+'$name $role '+'$if($pressed, @aria_pressed_true, @aria_pressed_false) '+'$description $state'},toolbar:{enter:'$name $role $description'},tree:{enter:'$name $role @@list_with_items($countChildren(treeItem))'},treeItem:{enter:'$role $expanded $collapsed '+'@describe_index($indexInParent, $parentChildCount) '+'@describe_depth($hierarchicalLevel)',speak:'$name '+'$role $state '+'@describe_index($indexInParent, $parentChildCount) '+'@describe_depth($hierarchicalLevel)'},window:{enter:'@describe_window($name)',speak:'@describe_window($name) $earcon(OBJECT_OPEN)'}},menuStart:{'default':{speak:'@chrome_menu_opened($name)  $earcon(OBJECT_OPEN)'}},menuEnd:{'default':{speak:'@chrome_menu_closed $earcon(OBJECT_CLOSE)'}},menuListValueChanged:{'default':{speak:'$value $name '+'$find({"state": {"selected": true, "invisible": false}}, '+'@describe_index($indexInParent, $parentChildCount)) '}},alert:{default:{speak:'!doNotInterrupt @role_alert '+'$if($name, $name, $descendants) $earcon(ALERT_NONMODAL) $description'}}};Output.SpeechProperties=function(){};Output.Action=function(){};Output.Action.prototype={run:function(){}};Output.EarconAction=function(earconId){Output.Action.call(this);this.earconId=earconId;};Output.EarconAction.prototype={__proto__:Output.Action.prototype,run:function(){cvox.ChromeVox.earcons.playEarcon(cvox.Earcon[this.earconId]);}};Output.SelectionSpan=function(startIndex,endIndex,opt_offset){this.startIndex=startIndex<endIndex?startIndex:endIndex;this.endIndex=endIndex>startIndex?endIndex:startIndex;this.offset=opt_offset||0;};Output.NodeSpan=function(node){this.node=node;};Output.EventType={NAVIGATE:'navigate'};Output.forceModeForNextSpeechUtterance_;Output.forceModeForNextSpeechUtterance=function(mode){Output.forceModeForNextSpeechUtterance_=mode;};Output.prototype={get hasSpeech(){for(var i=0;i<this.speechBuffer_.length;i++){if(this.speechBuffer_[i].trim().length)
return true;}
return false;},withSpeech:function(range,prevRange,type){this.formatOptions_={speech:true,braille:false,auralStyle:false};this.render_(range,prevRange,type,this.speechBuffer_);return this;},withRichSpeech:function(range,prevRange,type){this.formatOptions_={speech:true,braille:false,auralStyle:true};this.render_(range,prevRange,type,this.speechBuffer_);return this;},withBraille:function(range,prevRange,type){this.formatOptions_={speech:false,braille:true,auralStyle:false};this.render_(range,prevRange,type,this.brailleBuffer_);return this;},withLocation:function(range,prevRange,type){this.formatOptions_={speech:false,braille:false,auralStyle:false};this.render_(range,prevRange,type,[]);return this;},withSpeechAndBraille:function(range,prevRange,type){this.withSpeech(range,prevRange,type);this.withBraille(range,prevRange,type);return this;},withRichSpeechAndBraille:function(range,prevRange,type){this.withRichSpeech(range,prevRange,type);this.withBraille(range,prevRange,type);return this;},withSpeechCategory:function(category){this.speechCategory_=category;return this;},withQueueMode:function(queueMode){this.queueMode_=queueMode;return this;},withString:function(value){this.append_(this.speechBuffer_,value);this.append_(this.brailleBuffer_,value);return this;},withContextFirst:function(){this.outputContextFirst_=true;return this;},format:function(formatStr,opt_node){return this.formatForSpeech(formatStr,opt_node).formatForBraille(formatStr,opt_node);},formatForSpeech:function(formatStr,opt_node){var node=opt_node||null;this.formatOptions_={speech:true,braille:false,auralStyle:false};this.format_(node,formatStr,this.speechBuffer_);return this;},formatForBraille:function(formatStr,opt_node){var node=opt_node||null;this.formatOptions_={speech:false,braille:true,auralStyle:false};this.format_(node,formatStr,this.brailleBuffer_);return this;},onSpeechEnd:function(callback){this.speechEndCallback_=function(opt_cleanupOnly){if(!opt_cleanupOnly)
callback();}.bind(this);return this;},go:function(){var queueMode=cvox.QueueMode.FLUSH;if(Output.forceModeForNextSpeechUtterance_!==undefined)
queueMode=Output.forceModeForNextSpeechUtterance_;else if(this.queueMode_!==undefined)
queueMode=this.queueMode_;if(this.speechBuffer_.length>0)
Output.forceModeForNextSpeechUtterance_=undefined;for(var i=0;i<this.speechBuffer_.length;i++){var buff=this.speechBuffer_[i];var speechProps=(buff.getSpanInstanceOf(Output.SpeechProperties))||{};speechProps.category=this.speechCategory_;(function(){var scopedBuff=buff;speechProps['startCallback']=function(){var actions=scopedBuff.getSpansInstanceOf(Output.Action);if(actions){actions.forEach(function(a){a.run();});}};}());if(i==this.speechBuffer_.length-1)
speechProps['endCallback']=this.speechEndCallback_;cvox.ChromeVox.tts.speak(buff.toString(),queueMode,speechProps);queueMode=cvox.QueueMode.QUEUE;}
if(this.brailleBuffer_.length){var buff=this.createBrailleOutput_();var selSpan=buff.getSpanInstanceOf(Output.SelectionSpan);var startIndex=-1,endIndex=-1;if(selSpan){var valueStart=buff.getSpanStart(selSpan);var valueEnd=buff.getSpanEnd(selSpan);startIndex=valueStart+selSpan.startIndex;endIndex=valueStart+selSpan.endIndex;buff.setSpan(new cvox.ValueSpan(selSpan.offset),valueStart,valueEnd);buff.setSpan(new cvox.ValueSelectionSpan(),startIndex,endIndex);}
var output=new cvox.NavBraille({text:buff,startIndex:startIndex,endIndex:endIndex});cvox.ChromeVox.braille.write(output);}
if(this.speechCategory_!=cvox.TtsCategory.LIVE)
chrome.accessibilityPrivate.setFocusRing(this.locations_);},render_:function(range,prevRange,type,buff){if(prevRange&&!prevRange.isValid())
prevRange=null;var parent=range.start.node;var prevParent=prevRange?prevRange.start.node:parent;if(!parent||!prevParent)
return;var uniqueAncestors=AutomationUtil.getUniqueAncestors(prevParent,parent);for(var i=0;parent=uniqueAncestors[i];i++){if(Output.ROLE_INFO_[parent.role]&&Output.ROLE_INFO_[parent.role].outputContextFirst){this.outputContextFirst_=true;break;}}
if(range.isSubNode())
this.subNode_(range,prevRange,type,buff);else
this.range_(range,prevRange,type,buff);},format_:function(node,format,buff,opt_prevNode){var tokens=[];var args=null;if(typeof(format)=='string'){format=format.replace(/([,:])\W/g,'$1');tokens=format.split(' ');}else{tokens=[format];}
var speechProps=null;tokens.forEach(function(token){if(!token)
return;var tree;if(typeof(token)=='string')
tree=this.createParseTree_(token);else
tree=token;token=tree.value;var options={};options.annotation=[];options.isUnique=token[token.length-1]=='=';if(options.isUnique)
token=token.substring(0,token.length-1);if(node&&this.formatOptions_.braille)
options.annotation.push(new Output.NodeSpan(node));var prefix=token[0];token=token.slice(1);if(prefix=='$'){if(token=='value'){var text=node.value;if(!node.state.editable&&node.name==text)
return;if(text!==undefined){if(node.textSelStart!==undefined){options.annotation.push(new Output.SelectionSpan(node.textSelStart,node.textSelEnd));}}
options.annotation.push(token);this.append_(buff,text,options);}else if(token=='name'){options.annotation.push(token);var earcon=node?this.findEarcon_(node,opt_prevNode):null;if(earcon)
options.annotation.push(earcon);this.append_(buff,node.name,options);}else if(token=='nameFromNode'){if(chrome.automation.NameFromType[node.nameFrom]=='contents')
return;options.annotation.push('name');this.append_(buff,node.name,options);}else if(token=='nameOrDescendants'){options.annotation.push(token);if(node.name)
this.append_(buff,node.name,options);else
this.format_(node,'$descendants',buff);}else if(token=='description'){if(node.name==node.description||node.value==node.description)
return;options.annotation.push(token);this.append_(buff,node.description,options);}else if(token=='indexInParent'){if(node.parent){options.annotation.push(token);var count=0;for(var i=0,child;child=node.parent.children[i];i++){if(node.role==child.role)
count++;if(node===child)
break;}
this.append_(buff,String(count));}}else if(token=='parentChildCount'){if(node.parent){options.annotation.push(token);var count=node.parent.children.filter(function(child){return node.role==child.role;}).length;this.append_(buff,String(count));}}else if(token=='state'){Object.getOwnPropertyNames(node.state).forEach(function(s){var stateInfo=Output.STATE_INFO_[s];if(stateInfo&&stateInfo.on)
this.format_(node,'@'+stateInfo.on.msgId,buff);}.bind(this));}else if(token=='find'){if(tree.firstChild){var jsonQuery=tree.firstChild.value;node=node.find((JSON.parse(jsonQuery)));var formatString=tree.firstChild.nextSibling;if(node)
this.format_(node,formatString,buff);}}else if(token=='descendants'){if(!node||AutomationPredicate.leafOrStaticText(node))
return;var leftmost=AutomationUtil.findNodePre(node,Dir.FORWARD,AutomationPredicate.leafOrStaticText);var rightmost=AutomationUtil.findNodePre(node,Dir.BACKWARD,AutomationPredicate.leafOrStaticText);if(!leftmost||!rightmost)
return;var subrange=new cursors.Range(new cursors.Cursor(leftmost,cursors.NODE_INDEX),new cursors.Cursor(rightmost,cursors.NODE_INDEX));var prev=null;if(node)
prev=cursors.Range.fromNode(node);this.render_(subrange,prev,Output.EventType.NAVIGATE,buff);}else if(token=='joinedDescendants'){var unjoined=[];this.format_(node,'$descendants',unjoined);this.append_(buff,unjoined.join(' '),options);}else if(token=='role'){if(localStorage['useVerboseMode']=='false')
return;if(this.formatOptions_.auralStyle){speechProps=new Output.SpeechProperties();speechProps['relativePitch']=-0.3;}
options.annotation.push(token);var msg=node.role;var info=Output.ROLE_INFO_[node.role];if(info){if(this.formatOptions_.braille)
msg=Msgs.getMsg(info.msgId+'_brl');else
msg=Msgs.getMsg(info.msgId);}else{console.error('Missing role info for '+node.role);}
this.append_(buff,msg,options);}else if(token=='inputType'){if(!node.inputType)
return;options.annotation.push(token);var msgId=Output.INPUT_TYPE_MESSAGE_IDS_[node.inputType]||'input_type_text';if(this.formatOptions_.braille)
msgId=msgId+'_brl';this.append_(buff,Msgs.getMsg(msgId),options);}else if(token=='tableCellRowIndex'||token=='tableCellColumnIndex'){var value=node[token];if(value==undefined)
return;value=String(value+1);options.annotation.push(token);this.append_(buff,value,options);}else if(token=='node'){if(!tree.firstChild||!node[tree.firstChild.value])
return;var related=node[tree.firstChild.value];this.node_(related,related,Output.EventType.NAVIGATE,buff);}else if(token=='nameOrTextContent'){if(node.name){this.format_(node,'$name',buff);}else{var walker=new AutomationTreeWalker(node,Dir.FORWARD,{visit:AutomationPredicate.leafOrStaticText,leaf:AutomationPredicate.leafOrStaticText});while(walker.next().node&&walker.phase==AutomationTreeWalkerPhase.DESCENDANT){if(walker.node.name)
this.append_(buff,walker.node.name,options);}}}else if(node[token]!==undefined){options.annotation.push(token);var value=node[token];if(typeof value=='number')
value=String(value);this.append_(buff,value,options);}else if(Output.STATE_INFO_[token]){options.annotation.push('state');var stateInfo=Output.STATE_INFO_[token];var resolvedInfo={};if(node.state[token]===undefined)
resolvedInfo=stateInfo.omitted;else
resolvedInfo=node.state[token]?stateInfo.on:stateInfo.off;if(!resolvedInfo)
return;if(this.formatOptions_.speech&&resolvedInfo.earconId){options.annotation.push(new Output.EarconAction(resolvedInfo.earconId));}
var msgId=this.formatOptions_.braille?resolvedInfo.msgId+'_brl':resolvedInfo.msgId;var msg=Msgs.getMsg(msgId);this.append_(buff,msg,options);}else if(tree.firstChild){if(token=='if'){var cond=tree.firstChild;var attrib=cond.value.slice(1);if(node[attrib]||node.state[attrib])
this.format_(node,cond.nextSibling,buff);else
this.format_(node,cond.nextSibling.nextSibling,buff);}else if(token=='earcon'){if(!this.formatOptions_.speech)
return;options.annotation.push(new Output.EarconAction(tree.firstChild.value));this.append_(buff,'',options);}else if(token=='countChildren'){var role=tree.firstChild.value;var count=node.children.filter(function(e){return e.role==role;}).length;this.append_(buff,String(count));}}}else if(prefix=='@'){if(this.formatOptions_.auralStyle){speechProps=new Output.SpeechProperties();speechProps['relativePitch']=-0.2;}
var isPluralized=(token[0]=='@');if(isPluralized)
token=token.slice(1);var pieces=token.split('+');token=pieces.reduce(function(prev,cur){var lookup=cur;if(cur[0]=='$')
lookup=node[cur.slice(1)];return prev+lookup;}.bind(this),'');var msgId=token;var msgArgs=[];if(!isPluralized){var curArg=tree.firstChild;while(curArg){if(curArg.value[0]!='$'){console.error('Unexpected value: '+curArg.value);return;}
var msgBuff=[];this.format_(node,curArg,msgBuff);if(!msgBuff.length)
msgBuff=[''];msgArgs=msgArgs.concat(msgBuff);curArg=curArg.nextSibling;}}
var msg=Msgs.getMsg(msgId,msgArgs);try{if(this.formatOptions_.braille)
msg=Msgs.getMsg(msgId+'_brl',msgArgs)||msg;}catch(e){}
if(!msg){console.error('Could not get message '+msgId);return;}
if(isPluralized){var arg=tree.firstChild;if(!arg||arg.nextSibling){console.error('Pluralized messages take exactly one argument');return;}
if(arg.value[0]!='$'){console.error('Unexpected value: '+arg.value);return;}
var argBuff=[];this.format_(node,arg,argBuff);var namedArgs={COUNT:Number(argBuff[0])};msg=new goog.i18n.MessageFormat(msg).format(namedArgs);}
this.append_(buff,msg,options);}else if(prefix=='!'){speechProps=new Output.SpeechProperties();speechProps[token]=true;if(tree.firstChild){if(!this.formatOptions_.auralStyle){speechProps=undefined;return;}
var value=tree.firstChild.value;var float=0;if(float=parseFloat(value))
value=float;else
value=parseFloat(node[value])/-10.0;speechProps[token]=value;return;}}
if(speechProps){if(buff.length>0){buff[buff.length-1].setSpan(speechProps,0,0);speechProps=null;}}}.bind(this));},range_:function(range,prevRange,type,rangeBuff){if(!range.start.node||!range.end.node)
return;if(!prevRange&&range.start.node.root)
prevRange=cursors.Range.fromNode(range.start.node.root);var cursor=cursors.Cursor.fromNode(range.start.node);var prevNode=prevRange.start.node;var formatNodeAndAncestors=function(node,prevNode){var buff=[];if(this.outputContextFirst_)
this.ancestry_(node,prevNode,type,buff);this.node_(node,prevNode,type,buff);if(!this.outputContextFirst_)
this.ancestry_(node,prevNode,type,buff);if(node.location)
this.locations_.push(node.location);return buff;}.bind(this);while(cursor.node&&range.end.node&&AutomationUtil.getDirection(cursor.node,range.end.node)==Dir.FORWARD){var node=cursor.node;rangeBuff.push.apply(rangeBuff,formatNodeAndAncestors(node,prevNode));prevNode=node;cursor=cursor.move(cursors.Unit.NODE,cursors.Movement.DIRECTIONAL,Dir.FORWARD);if(cursor.node==prevNode)
break;}},ancestry_:function(node,prevNode,type,buff){function byContextFirst(ancestors){var contextFirst=[];var rest=[];for(i=0;i<ancestors.length-1;i++){var node=ancestors[i];if(node.role==RoleType.window){contextFirst=[];rest=[];}
if((Output.ROLE_INFO_[node.role]||{}).outputContextFirst)
contextFirst.push(node);else
rest.push(node);}
return rest.concat(contextFirst.reverse());}
var prevUniqueAncestors=byContextFirst(AutomationUtil.getUniqueAncestors(node,prevNode));var uniqueAncestors=byContextFirst(AutomationUtil.getUniqueAncestors(prevNode,node));var eventBlock=Output.RULES[type]||Output.RULES['navigate'];var getMergedRoleBlock=function(role){var parentRole=(Output.ROLE_INFO_[role]||{}).inherits;var roleBlock=eventBlock[role]||eventBlock['default'];var parentRoleBlock=parentRole?eventBlock[parentRole]:{};var mergedRoleBlock={};for(var key in parentRoleBlock)
mergedRoleBlock[key]=parentRoleBlock[key];for(var key in roleBlock)
mergedRoleBlock[key]=roleBlock[key];return mergedRoleBlock;};var enteredRoleSet={};for(var j=uniqueAncestors.length-1,hashNode;(hashNode=uniqueAncestors[j]);j--)
enteredRoleSet[hashNode.role]=true;for(var i=0,formatPrevNode;(formatPrevNode=prevUniqueAncestors[i]);i++){if(enteredRoleSet[formatPrevNode.role]||node.role==formatPrevNode.role||localStorage['useVerboseMode']=='false')
continue;var roleBlock=getMergedRoleBlock(formatPrevNode.role);if(roleBlock.leave&&localStorage['useVerboseMode']=='true')
this.format_(formatPrevNode,roleBlock.leave,buff,prevNode);}
var enterOutputs=[];var enterRole={};for(var j=uniqueAncestors.length-1,formatNode;(formatNode=uniqueAncestors[j]);j--){var roleBlock=getMergedRoleBlock(formatNode.role);if(roleBlock.enter){if(enterRole[formatNode.role])
continue;enterRole[formatNode.role]=true;this.format_(formatNode,roleBlock.enter,buff,prevNode);}}},node_:function(node,prevNode,type,buff){var eventBlock=Output.RULES[type]||Output.RULES['navigate'];var roleBlock=eventBlock[node.role]||{};var parentRole=(Output.ROLE_INFO_[node.role]||{}).inherits;var parentRoleBlock=eventBlock[parentRole||'']||{};var speakFormat=roleBlock.speak||parentRoleBlock.speak||eventBlock['default'].speak;this.format_(node,speakFormat,buff,prevNode);},subNode_:function(range,prevRange,type,buff){if(!prevRange)
prevRange=range;var dir=cursors.Range.getDirection(prevRange,range);var node=range.start.node;var prevNode=prevRange.getBound(dir).node;if(!node||!prevNode)
return;var options={annotation:['name'],isUnique:true};var startIndex=range.start.index;var endIndex=range.end.index;if(this.formatOptions_.braille){options.annotation.push(new Output.NodeSpan(node));var selStart=node.textSelStart;var selEnd=node.textSelEnd;if(selStart!==undefined&&(selEnd>=startIndex&&selStart<=endIndex)){options.annotation.push(new Output.SelectionSpan(selStart-startIndex,selEnd-startIndex,startIndex));}}
if(this.outputContextFirst_)
this.ancestry_(node,prevNode,type,buff);var earcon=this.findEarcon_(node,prevNode);if(earcon)
options.annotation.push(earcon);this.append_(buff,range.start.getText().substring(startIndex,endIndex),options);if(!this.outputContextFirst_)
this.ancestry_(node,prevNode,type,buff);var loc=range.start.node.boundsForRange(startIndex,endIndex);if(loc)
this.locations_.push(loc);},append_:function(buff,value,opt_options){opt_options=opt_options||{isUnique:false,annotation:[]};if((!value||value.length==0)&&opt_options.annotation.every(function(a){return!(a instanceof Output.Action)&&!(a instanceof Output.SelectionSpan);}))
return;var spannableToAdd=new Spannable(value);opt_options.annotation.forEach(function(a){spannableToAdd.setSpan(a,0,spannableToAdd.length);});if(opt_options.isUnique){var annotationSansNodes=opt_options.annotation.filter(function(annotation){return!(annotation instanceof Output.NodeSpan);});var alreadyAnnotated=buff.some(function(s){return annotationSansNodes.some(function(annotation){if(!s.hasSpan(annotation))
return false;var start=s.getSpanStart(annotation);var end=s.getSpanEnd(annotation);var substr=s.substring(start,end);if(substr&&value)
return substr.toString()==value.toString();else
return false;});});if(alreadyAnnotated)
return;}
buff.push(spannableToAdd);},createParseTree_:function(inputStr){var root={value:''};var currentNode=root;var index=0;var braceNesting=0;while(index<inputStr.length){if(inputStr[index]=='('){currentNode.firstChild={value:''};currentNode.firstChild.parent=currentNode;currentNode=currentNode.firstChild;}else if(inputStr[index]==')'){currentNode=currentNode.parent;}else if(inputStr[index]=='{'){braceNesting++;currentNode.value+=inputStr[index];}else if(inputStr[index]=='}'){braceNesting--;currentNode.value+=inputStr[index];}else if(inputStr[index]==','&&braceNesting===0){currentNode.nextSibling={value:''};currentNode.nextSibling.parent=currentNode.parent;currentNode=currentNode.nextSibling;}else{currentNode.value+=inputStr[index];}
index++;}
if(currentNode!=root)
throw'Unbalanced parenthesis: '+inputStr;return root;},createBrailleOutput_:function(){var result=new Spannable();var separator='';this.brailleBuffer_.forEach(function(cur){if(cur.length==0&&!cur.getSpanInstanceOf(Output.SelectionSpan))
return;var spansToExtend=[];var spansToRemove=[];result.getSpansInstanceOf(Output.NodeSpan).forEach(function(leftSpan){if(result.getSpanEnd(leftSpan)<result.length)
return;var newEnd=result.length;cur.getSpansInstanceOf(Output.NodeSpan).forEach(function(rightSpan){if(cur.getSpanStart(rightSpan)==0&&leftSpan.node===rightSpan.node){newEnd=Math.max(newEnd,result.length+separator.length+
cur.getSpanEnd(rightSpan));spansToRemove.push(rightSpan);}});if(newEnd>result.length)
spansToExtend.push({span:leftSpan,end:newEnd});});result.append(separator);result.append(cur);spansToExtend.forEach(function(elem){result.setSpan(elem.span,result.getSpanStart(elem.span),elem.end);});spansToRemove.forEach(result.removeSpan.bind(result));separator=Output.SPACE;});return result;},findEarcon_:function(node,opt_prevNode){if(node===opt_prevNode)
return null;if(this.formatOptions_.speech){var earconFinder=node;var ancestors;if(opt_prevNode)
ancestors=AutomationUtil.getUniqueAncestors(opt_prevNode,node);else
ancestors=AutomationUtil.getAncestors(node);while(earconFinder=ancestors.pop()){var info=Output.ROLE_INFO_[earconFinder.role];if(info&&info.earconId){return new Output.EarconAction(info.earconId);break;}
earconFinder=earconFinder.parent;}}
return null;},toString:function(){return this.speechBuffer_.reduce(function(prev,cur){if(prev===null)
return cur.toString();prev+=' '+cur.toString();return prev;},null);},get speechOutputForTest(){return this.speechBuffer_.reduce(function(prev,cur){if(prev===null)
return cur;prev.append('|');prev.append(cur);return prev;},null);},get brailleOutputForTest(){return this.createBrailleOutput_();}};});goog.provide('FindHandler');goog.require('Output');FindHandler.onModeChanged=function(newMode,oldMode){if(newMode==ChromeVoxMode.FORCE_NEXT)
FindHandler.init_();else
FindHandler.uninit_();};FindHandler.init_=function(){chrome.automation.addTreeChangeObserver('textMarkerChanges',FindHandler.onTextMatch_);};FindHandler.uninit_=function(){chrome.automation.removeTreeChangeObserver(FindHandler.onTextMatch_);};FindHandler.onTextMatch_=function(evt){if(!evt.target.markerTypes.some(function(markerType){return markerType&4;}))
return;var range=cursors.Range.fromNode(evt.target);ChromeVoxState.instance.setCurrentRange(range);new Output().withRichSpeechAndBraille(range,null,Output.EventType.NAVIGATE).go();};goog.provide('NextEarcons');goog.require('EarconEngine');goog.require('cvox.AbstractEarcons');NextEarcons=function(){cvox.AbstractEarcons.call(this);if(localStorage['earcons']==='false'){cvox.AbstractEarcons.enabled=false;}
this.engine_=new EarconEngine();};NextEarcons.prototype={getName:function(){return'ChromeVox Next earcons';},playEarcon:function(earcon){if(!cvox.AbstractEarcons.enabled){return;}
console.log('Earcon '+earcon);switch(earcon){case cvox.Earcon.ALERT_MODAL:case cvox.Earcon.ALERT_NONMODAL:this.engine_.onAlert();break;case cvox.Earcon.BUTTON:this.engine_.onButton();break;case cvox.Earcon.CHECK_OFF:this.engine_.onCheckOff();break;case cvox.Earcon.CHECK_ON:this.engine_.onCheckOn();break;case cvox.Earcon.EDITABLE_TEXT:this.engine_.onTextField();break;case cvox.Earcon.INVALID_KEYPRESS:this.engine_.onWrap();break;case cvox.Earcon.LINK:this.engine_.onLink();break;case cvox.Earcon.LISTBOX:this.engine_.onSelect();break;case cvox.Earcon.LIST_ITEM:case cvox.Earcon.LONG_DESC:case cvox.Earcon.MATH:case cvox.Earcon.OBJECT_CLOSE:case cvox.Earcon.OBJECT_ENTER:case cvox.Earcon.OBJECT_EXIT:case cvox.Earcon.OBJECT_OPEN:case cvox.Earcon.OBJECT_SELECT:break;case cvox.Earcon.PAGE_FINISH_LOADING:this.engine_.cancelProgress();break;case cvox.Earcon.PAGE_START_LOADING:this.engine_.startProgress();break;case cvox.Earcon.POP_UP_BUTTON:this.engine_.onPopUpButton();break;case cvox.Earcon.RECOVER_FOCUS:break;case cvox.Earcon.SELECTION:this.engine_.onSelection();break;case cvox.Earcon.SELECTION_REVERSE:this.engine_.onSelectionReverse();break;case cvox.Earcon.SKIP:this.engine_.onSkim();break;case cvox.Earcon.SLIDER:this.engine_.onSlider();break;case cvox.Earcon.WRAP:case cvox.Earcon.WRAP_EDGE:this.engine_.onWrap();break;}},cancelEarcon:function(earcon){switch(earcon){case cvox.Earcon.PAGE_START_LOADING:this.engine_.cancelProgress();break;}},};goog.provide('ChromeVoxMode');goog.provide('ChromeVoxState');goog.require('cursors.Cursor');ChromeVoxMode={CLASSIC:'classic',CLASSIC_COMPAT:'classic_compat',NEXT:'next',NEXT_COMPAT:'next_compat',FORCE_NEXT:'force_next'};ChromeVoxState=function(){if(ChromeVoxState.instance)
throw'Trying to create two instances of singleton ChromeVoxState.';ChromeVoxState.instance=this;};ChromeVoxState.instance;ChromeVoxState.backgroundTts;ChromeVoxState.isReadingContinuously;ChromeVoxState.prototype={get mode(){return this.getMode();},getMode:function(){return ChromeVoxMode.NEXT;},get currentRange(){return this.getCurrentRange();},getCurrentRange:function(){return null;},setCurrentRange:goog.abstractMethod,};goog.provide('LiveRegions');goog.require('ChromeVoxState');goog.scope(function(){var AutomationNode=chrome.automation.AutomationNode;var RoleType=chrome.automation.RoleType;var TreeChange=chrome.automation.TreeChange;LiveRegions=function(chromeVoxState){this.chromeVoxState_=chromeVoxState;this.lastLiveRegionTime_=new Date(0);this.liveRegionNodeSet_=new WeakSet();chrome.automation.addTreeChangeObserver('liveRegionTreeChanges',this.onTreeChange.bind(this));};LiveRegions.LIVE_REGION_QUEUE_TIME_MS=5000;LiveRegions.LIVE_REGION_MIN_SAME_NODE_MS=20;LiveRegions.announceLiveRegionsFromBackgroundTabs_=true;LiveRegions.prototype={onTreeChange:function(treeChange){var node=treeChange.target;if(!node.containerLiveStatus)
return;var mode=this.chromeVoxState_.mode;var currentRange=this.chromeVoxState_.currentRange;if(mode===ChromeVoxMode.CLASSIC||!cvox.ChromeVox.isActive)
return;if(!currentRange)
return;var webView=AutomationUtil.getTopLevelRoot(node);webView=webView?webView.parent:null;if(!LiveRegions.announceLiveRegionsFromBackgroundTabs_&&currentRange.start.node.role!=RoleType.desktop&&(!webView||!webView.state.focused)){return;}
var type=treeChange.type;var relevant=node.containerLiveRelevant;var additions=relevant.indexOf('additions')>=0;var text=relevant.indexOf('text')>=0;var removals=relevant.indexOf('removals')>=0;var all=relevant.indexOf('all')>=0;if(all||(additions&&(type=='nodeCreated'||type=='subtreeCreated'))){this.outputLiveRegionChange_(node,null);}
if(all||(text&&type=='textChanged'))
this.outputLiveRegionChange_(node,null);if(all||(removals&&type=='nodeRemoved'))
this.outputLiveRegionChange_(node,'@live_regions_removed');},outputLiveRegionChange_:function(node,opt_prependFormatStr){if(node.containerLiveBusy)
return;if(node.containerLiveAtomic&&!node.liveAtomic){if(node.parent)
this.outputLiveRegionChange_(node.parent,opt_prependFormatStr);return;}
var range=cursors.Range.fromNode(node);var output=new Output();if(opt_prependFormatStr)
output.format(opt_prependFormatStr);output.withSpeech(range,range,Output.EventType.NAVIGATE);if(!output.hasSpeech&&node.liveAtomic)
output.format('$joinedDescendants',node);output.withSpeechCategory(cvox.TtsCategory.LIVE);var currentTime=new Date();if(!output.hasSpeech)
return;var webView=AutomationUtil.getTopLevelRoot(node);webView=webView?webView.parent:null;var forceQueueForBackgroundedLiveRegion=!webView||!webView.state.focused;var queueTime=LiveRegions.LIVE_REGION_QUEUE_TIME_MS;var delta=currentTime-this.lastLiveRegionTime_;if(delta>queueTime&&!forceQueueForBackgroundedLiveRegion)
output.withQueueMode(cvox.QueueMode.CATEGORY_FLUSH);else
output.withQueueMode(cvox.QueueMode.QUEUE);if(delta>LiveRegions.LIVE_REGION_MIN_SAME_NODE_MS)
this.liveRegionNodeSet_=new WeakSet();var parent=node;while(parent){if(this.liveRegionNodeSet_.has(parent)){this.lastLiveRegionTime_=currentTime;return;}
parent=parent.parent;}
this.liveRegionNodeSet_.add(node);output.go();this.lastLiveRegionTime_=currentTime;},};});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.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.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.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('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.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.ChromeVoxPrefs');goog.require('cvox.ChromeVox');goog.require('cvox.ExtensionBridge');goog.require('cvox.KeyMap');cvox.ChromeVoxPrefs=function(){var lastRunVersion=localStorage['lastRunVersion'];if(!lastRunVersion){lastRunVersion='1.16.0';}
var loadExistingSettings=true;if(lastRunVersion=='1.16.0'){loadExistingSettings=false;}
localStorage['lastRunVersion']=chrome.runtime.getManifest().version;this.keyMap_=cvox.KeyMap.fromLocalStorage()||cvox.KeyMap.fromDefaults();this.keyMap_.merge(cvox.KeyMap.fromDefaults());localStorage['position']='{}';localStorage['sticky']=false;this.init(loadExistingSettings);};cvox.ChromeVoxPrefs.DEFAULT_PREFS={'active':true,'brailleCaptions':false,'currentKeyMap':cvox.KeyMap.DEFAULT_KEYMAP,'cvoxKey':'','earcons':true,'focusFollowsMouse':false,'granularity':undefined,'position':'{}','siteSpecificScriptBase':'https://ssl.gstatic.com/accessibility/javascript/ext/','siteSpecificScriptLoader':'https://ssl.gstatic.com/accessibility/javascript/ext/loader.js','sticky':false,'typingEcho':0,'useIBeamCursor':cvox.ChromeVox.isMac,'useVerboseMode':true,'siteSpecificEnhancements':true,'useNext':false};cvox.ChromeVoxPrefs.prototype.init=function(pullFromLocalStorage){for(var pref in cvox.ChromeVoxPrefs.DEFAULT_PREFS){if(localStorage[pref]===undefined){localStorage[pref]=cvox.ChromeVoxPrefs.DEFAULT_PREFS[pref];}}};cvox.ChromeVoxPrefs.prototype.switchToKeyMap=function(selectedKeyMap){cvox.ChromeVox.sequenceSwitchKeyCodes=[];localStorage['currentKeyMap']=selectedKeyMap;this.keyMap_=cvox.KeyMap.fromCurrentKeyMap();cvox.ChromeVoxKbHandler.handlerKeyMap=this.keyMap_;this.keyMap_.toLocalStorage();this.keyMap_.resetModifier();this.sendPrefsToAllTabs(false,true);};cvox.ChromeVoxPrefs.prototype.getPrefs=function(){var prefs={};for(var pref in cvox.ChromeVoxPrefs.DEFAULT_PREFS){prefs[pref]=localStorage[pref];}
prefs['version']=chrome.runtime.getManifest().version;return prefs;};cvox.ChromeVoxPrefs.prototype.reloadKeyMap=function(){var currentKeyMap=cvox.KeyMap.fromLocalStorage();if(!currentKeyMap){currentKeyMap=cvox.KeyMap.fromCurrentKeyMap();currentKeyMap.toLocalStorage();}
this.keyMap_=currentKeyMap;};cvox.ChromeVoxPrefs.prototype.getKeyMap=function(){return this.keyMap_;};cvox.ChromeVoxPrefs.prototype.resetKeys=function(){this.keyMap_=cvox.KeyMap.fromDefaults();this.keyMap_.toLocalStorage();this.sendPrefsToAllTabs(false,true);};cvox.ChromeVoxPrefs.prototype.sendPrefsToAllTabs=function(sendPrefs,sendKeyBindings){var context=this;var message={};if(sendPrefs){message['prefs']=context.getPrefs();}
if(sendKeyBindings){message['keyBindings']=this.keyMap_.toJSON();}
chrome.windows.getAll({populate:true},function(windows){for(var i=0;i<windows.length;i++){var tabs=windows[i].tabs;for(var j=0;j<tabs.length;j++){chrome.tabs.sendMessage(tabs[j].id,message);}}});};cvox.ChromeVoxPrefs.prototype.sendPrefsToPort=function(port){port.postMessage({'keyBindings':this.keyMap_.toJSON(),'prefs':this.getPrefs()});};cvox.ChromeVoxPrefs.prototype.setPref=function(key,value){if(localStorage[key]!=value){localStorage[key]=value;this.sendPrefsToAllTabs(true,false);}};cvox.ChromeVoxPrefs.prototype.setKey=function(command,newKey){if(this.keyMap_.rebind(command,newKey)){this.keyMap_.toLocalStorage();this.sendPrefsToAllTabs(false,true);return true;}
return false;};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.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.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.InjectedScriptLoader');cvox.InjectedScriptLoader=function(){};cvox.InjectedScriptLoader.fetchCode=function(files,done){var code={};var waiting=files.length;var startTime=new Date();var loadScriptAsCode=function(src){var xhr=new XMLHttpRequest();var url=chrome.extension.getURL(src)+'?'+new Date().getTime();xhr.onreadystatechange=function(){if(xhr.readyState==4){var scriptText=xhr.responseText;var debugSrc=src.replace('closure/../','');scriptText+='\n//# sourceURL= chrome-extension://chromevox/'+
debugSrc+'\n';code[src]=scriptText;waiting--;if(waiting==0){done(code);}}};xhr.open('GET',url);xhr.send(null);};files.forEach(function(f){loadScriptAsCode(f);});};goog.provide('cvox.ClassicEarcons');goog.require('cvox.AbstractEarcons');cvox.ClassicEarcons=function(){goog.base(this);if(localStorage['earcons']==='false'){cvox.AbstractEarcons.enabled=false;}
this.audioMap=new Object();};goog.inherits(cvox.ClassicEarcons,cvox.AbstractEarcons);cvox.ClassicEarcons.prototype.getName=function(){return'ChromeVox earcons';};cvox.ClassicEarcons.prototype.getBaseUrl=function(){return cvox.ClassicEarcons.BASE_URL;};cvox.ClassicEarcons.prototype.playEarcon=function(earcon){goog.base(this,'playEarcon',earcon);if(!cvox.AbstractEarcons.enabled){return;}
console.log('Earcon '+earcon);this.currentAudio=this.audioMap[earcon];if(!this.currentAudio){this.currentAudio=new Audio(chrome.extension.getURL(this.getBaseUrl()+
earcon+'.ogg'));this.audioMap[earcon]=this.currentAudio;}
try{this.currentAudio.currentTime=0;}catch(e){}
if(this.currentAudio.paused){this.currentAudio.volume=0.7;this.currentAudio.play();}};cvox.ClassicEarcons.prototype.cancelEarcon=function(earcon){};cvox.ClassicEarcons.BASE_URL='chromevox/background/earcons/';goog.provide('cvox.LibLouis');cvox.LibLouis=function(nmfPath,opt_tablesDir){this.nmfPath_=nmfPath;this.tablesDir_=goog.isDef(opt_tablesDir)?opt_tablesDir:null;this.embedElement_=null;this.pendingRpcCallbacks_={};this.nextMessageId_=1;};cvox.LibLouis.DEBUG=false;cvox.LibLouis.prototype.attachToElement=function(elem){if(this.isAttached()){throw Error('Instance already attached');}
var embed=document.createElement('embed');embed.src=this.nmfPath_;embed.type='application/x-nacl';embed.width=0;embed.height=0;if(!goog.isNull(this.tablesDir_)){embed.setAttribute('tablesdir',this.tablesDir_);}
embed.addEventListener('load',goog.bind(this.onInstanceLoad_,this),false);embed.addEventListener('error',goog.bind(this.onInstanceError_,this),false);embed.addEventListener('message',goog.bind(this.onInstanceMessage_,this),false);elem.appendChild(embed);this.embedElement_=(embed);};cvox.LibLouis.prototype.detach=function(){if(!this.isAttached()){throw Error('cannot detach unattached instance');}
this.embedElement_.parentNode.removeChild(this.embedElement_);this.embedElement_=null;for(var id in this.pendingRpcCallbacks_){this.pendingRpcCallbacks_[id]({});}
this.pendingRpcCallbacks_={};};cvox.LibLouis.prototype.isAttached=function(){return this.embedElement_!==null;};cvox.LibLouis.prototype.getTranslator=function(tableNames,callback){if(!this.isAttached()){callback(null);return;}
this.rpc_('CheckTable',{'table_names':tableNames},function(reply){if(reply['success']){var translator=new cvox.LibLouis.Translator(this,tableNames);callback(translator);}else{callback(null);}}.bind(this));};cvox.LibLouis.prototype.rpc_=function(command,message,callback){if(!this.isAttached()){throw Error('Cannot send RPC: liblouis instance not loaded');}
var messageId=''+this.nextMessageId_++;message['message_id']=messageId;message['command']=command;var json=JSON.stringify(message);if(cvox.LibLouis.DEBUG){window.console.debug('RPC -> '+json);}
this.embedElement_.postMessage(json);this.pendingRpcCallbacks_[messageId]=callback;};cvox.LibLouis.prototype.onInstanceLoad_=function(e){window.console.info('loaded liblouis Native Client instance');};cvox.LibLouis.prototype.onInstanceError_=function(e){window.console.error('failed to load liblouis Native Client instance');this.detach();};cvox.LibLouis.prototype.onInstanceMessage_=function(e){if(cvox.LibLouis.DEBUG){window.console.debug('RPC <- '+e.data);}
var message=(JSON.parse(e.data));var messageId=message['in_reply_to'];if(!goog.isDef(messageId)){window.console.warn('liblouis Native Client module sent message with no ID',message);return;}
if(goog.isDef(message['error'])){window.console.error('liblouis Native Client error',message['error']);}
var callback=this.pendingRpcCallbacks_[messageId];if(goog.isDef(callback)){delete this.pendingRpcCallbacks_[messageId];callback(message);}};cvox.LibLouis.Translator=function(instance,tableNames){this.instance_=instance;this.tableNames_=tableNames;};cvox.LibLouis.Translator.prototype.translate=function(text,callback){if(!this.instance_.isAttached()){callback(null,null,null);return;}
var message={'table_names':this.tableNames_,'text':text};this.instance_.rpc_('Translate',message,function(reply){var cells=null;var textToBraille=null;var brailleToText=null;if(reply['success']&&goog.isString(reply['cells'])){cells=cvox.LibLouis.Translator.decodeHexString_(reply['cells']);if(goog.isDef(reply['text_to_braille'])){textToBraille=reply['text_to_braille'];}
if(goog.isDef(reply['braille_to_text'])){brailleToText=reply['braille_to_text'];}}else if(text.length>0){console.error('Braille translation error for '+JSON.stringify(message));}
callback(cells,textToBraille,brailleToText);});};cvox.LibLouis.Translator.prototype.backTranslate=function(cells,callback){if(!this.instance_.isAttached()){callback(null);return;}
if(cells.byteLength==0){callback('');return;}
var message={'table_names':this.tableNames_,'cells':cvox.LibLouis.Translator.encodeHexString_(cells)};this.instance_.rpc_('BackTranslate',message,function(reply){if(reply['success']&&goog.isString(reply['text'])){callback(reply['text']);}else{callback(null);}});};cvox.LibLouis.Translator.decodeHexString_=function(hex){if(!/^([0-9a-f]{2})*$/i.test(hex)){throw Error('invalid hexadecimal string');}
var array=new Uint8Array(hex.length/2);var idx=0;for(var i=0;i<hex.length;i+=2){array[idx++]=parseInt(hex.substring(i,i+2),16);}
return array.buffer;};cvox.LibLouis.Translator.encodeHexString_=function(arrayBuffer){var array=new Uint8Array(arrayBuffer);var hex='';for(var i=0;i<array.length;i++){var b=array[i];hex+=(b<0x10?'0':'')+b.toString(16);}
return hex;};goog.provide('cvox.ExpandingBrailleTranslator');goog.require('Spannable');goog.require('cvox.ExtraCellsSpan');goog.require('cvox.LibLouis');goog.require('cvox.ValueSelectionSpan');goog.require('cvox.ValueSpan');cvox.ExpandingBrailleTranslator=function(defaultTranslator,opt_uncontractedTranslator){this.defaultTranslator_=defaultTranslator;this.uncontractedTranslator_=opt_uncontractedTranslator||null;};cvox.ExpandingBrailleTranslator.ExpansionType={NONE:0,SELECTION:1,ALL:2};cvox.ExpandingBrailleTranslator.prototype.translate=function(text,expansionType,callback){var expandRanges=this.findExpandRanges_(text,expansionType);var extraCellsSpans=text.getSpansInstanceOf(cvox.ExtraCellsSpan).filter(function(span){return span.cells.byteLength>0;});var extraCellsPositions=extraCellsSpans.map(function(span){return text.getSpanStart(span);});if(expandRanges.length==0&&extraCellsSpans.length==0){this.defaultTranslator_.translate(text.toString(),cvox.ExpandingBrailleTranslator.nullParamsToEmptyAdapter_(text.length,callback));return;}
var chunks=[];function maybeAddChunkToTranslate(translator,start,end){if(start<end)
chunks.push({translator:translator,start:start,end:end});}
function addExtraCellsChunk(pos,cells){var chunk={translator:null,start:pos,end:pos,cells:cells,textToBraille:[],brailleToText:new Array(cells.byteLength)};for(var i=0;i<cells.byteLength;++i)
chunk.brailleToText[i]=0;chunks.push(chunk);}
function addChunk(translator,start,end){while(extraCellsSpans.length>0&&extraCellsPositions[0]<=end){maybeAddChunkToTranslate(translator,start,extraCellsPositions[0]);start=extraCellsPositions.shift();addExtraCellsChunk(start,extraCellsSpans.shift().cells);}
maybeAddChunkToTranslate(translator,start,end);}
var lastEnd=0;for(var i=0;i<expandRanges.length;++i){var range=expandRanges[i];if(lastEnd<range.start){addChunk(this.defaultTranslator_,lastEnd,range.start);}
addChunk(this.uncontractedTranslator_,range.start,range.end);lastEnd=range.end;}
addChunk(this.defaultTranslator_,lastEnd,text.length);var chunksToTranslate=chunks.filter(function(chunk){return chunk.translator;});var numPendingCallbacks=chunksToTranslate.length;function chunkTranslated(chunk,cells,textToBraille,brailleToText){chunk.cells=cells;chunk.textToBraille=textToBraille;chunk.brailleToText=brailleToText;if(--numPendingCallbacks<=0)
finish();}
function finish(){var totalCells=chunks.reduce(function(accum,chunk){return accum+chunk.cells.byteLength},0);var cells=new Uint8Array(totalCells);var cellPos=0;var textToBraille=[];var brailleToText=[];function appendAdjusted(array,toAppend,adjustment){array.push.apply(array,toAppend.map(function(elem){return adjustment+elem;}));}
for(var i=0,chunk;chunk=chunks[i];++i){cells.set(new Uint8Array(chunk.cells),cellPos);appendAdjusted(textToBraille,chunk.textToBraille,cellPos);appendAdjusted(brailleToText,chunk.brailleToText,chunk.start);cellPos+=chunk.cells.byteLength;}
callback(cells.buffer,textToBraille,brailleToText);}
if(chunksToTranslate.length>0){chunksToTranslate.forEach(function(chunk){chunk.translator.translate(text.toString().substring(chunk.start,chunk.end),cvox.ExpandingBrailleTranslator.nullParamsToEmptyAdapter_(chunk.end-chunk.start,goog.partial(chunkTranslated,chunk)));});}else{finish();}};cvox.ExpandingBrailleTranslator.rangeForPosition_=function(str,pos,start,end){if(start<0||end>str.length){throw RangeError('End-points out of range looking for braille expansion range');}
if(pos<start||pos>=end){throw RangeError('Position out of range looking for braille expansion range');}
start=str.substring(start,pos+1).search(/(\s+|\S+)$/)+start;end=pos+/^(\s+|\S+)/.exec(str.substring(pos,end))[0].length;return{start:start,end:end};};cvox.ExpandingBrailleTranslator.prototype.findExpandRanges_=function(text,expansionType){var result=[];if(this.uncontractedTranslator_&&expansionType!=cvox.ExpandingBrailleTranslator.ExpansionType.NONE){var value=text.getSpanInstanceOf(cvox.ValueSpan);if(value){var valueStart=text.getSpanStart(value);var valueEnd=text.getSpanEnd(value);switch(expansionType){case cvox.ExpandingBrailleTranslator.ExpansionType.SELECTION:this.addRangesForSelection_(text,valueStart,valueEnd,result);break;case cvox.ExpandingBrailleTranslator.ExpansionType.ALL:result.push({start:valueStart,end:valueEnd});break;}}}
return result;};cvox.ExpandingBrailleTranslator.prototype.addRangesForSelection_=function(text,valueStart,valueEnd,outRanges){var selection=text.getSpanInstanceOf(cvox.ValueSelectionSpan);if(!selection){return;}
var selectionStart=text.getSpanStart(selection);var selectionEnd=text.getSpanEnd(selection);if(selectionStart<valueStart||selectionEnd>valueEnd){return;}
var expandPositions=[];if(selectionStart==valueEnd){if(selectionStart>valueStart){expandPositions.push(selectionStart-1);}}else{if(selectionStart==selectionEnd&&selectionStart>valueStart){expandPositions.push(selectionStart-1);}
expandPositions.push(selectionStart);if(selectionEnd>selectionStart+1){expandPositions.push(selectionEnd-1);}}
var lastRange=outRanges[outRanges.length-1]||null;for(var i=0;i<expandPositions.length;++i){var range=cvox.ExpandingBrailleTranslator.rangeForPosition_(text.toString(),expandPositions[i],valueStart,valueEnd);if(lastRange&&lastRange.end>=range.start){lastRange.end=range.end;}else{outRanges.push(range);lastRange=range;}}};cvox.ExpandingBrailleTranslator.nullParamsToEmptyAdapter_=function(inputLength,callback){return function(cells,textToBraille,brailleToText){if(!textToBraille){textToBraille=new Array(inputLength);for(var i=0;i<inputLength;++i){textToBraille[i]=0;}}
callback(cells||new ArrayBuffer(0),textToBraille,brailleToText||[]);};};cvox.ExpandingBrailleTranslator.Range_;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.PanStrategy');cvox.PanStrategy=function(){this.displaySize_=0;this.contentLength_=0;this.breakPoints_=[];this.viewPort_={start:0,end:0};};cvox.PanStrategy.Range;cvox.PanStrategy.prototype={get viewPort(){return this.viewPort_;},setDisplaySize:function(size){this.displaySize_=size;this.panToPosition_(this.viewPort_.start);},setContent:function(translatedContent,targetPosition){this.breakPoints_=this.calculateBreakPoints_(translatedContent);this.contentLength_=translatedContent.byteLength;this.panToPosition_(targetPosition);},next:function(){var newStart=this.viewPort_.end;var newEnd;if(newStart+this.displaySize_<this.contentLength_){newEnd=this.extendRight_(newStart);}else{newEnd=this.contentLength_;}
if(newEnd>newStart){this.viewPort_={start:newStart,end:newEnd};return true;}
return false;},previous:function(){if(this.viewPort_.start>0){var newStart,newEnd;if(this.viewPort_.start<=this.displaySize_){newStart=0;newEnd=this.extendRight_(newStart);}else{newEnd=this.viewPort_.start;var limit=newEnd-this.displaySize_;newStart=limit;var pos=0;while(pos<this.breakPoints_.length&&this.breakPoints_[pos]<limit){pos++;}
if(pos<this.breakPoints_.length&&this.breakPoints_[pos]<newEnd){newStart=this.breakPoints_[pos];}}
if(newStart<newEnd){this.viewPort_={start:newStart,end:newEnd};return true;}}
return false;},extendRight_:function(from){var limit=Math.min(from+this.displaySize_,this.contentLength_);var pos=0;var result=limit;while(pos<this.breakPoints_.length&&this.breakPoints_[pos]<=from){pos++;}
while(pos<this.breakPoints_.length&&this.breakPoints_[pos]<=limit){result=this.breakPoints_[pos];pos++;}
return result;},calculateBreakPoints_:function(content){return[];},panToPosition_:function(position){if(this.displaySize_>0){this.viewPort_={start:0,end:0};while(this.next()&&this.viewPort_.end<=position){}}else{this.viewPort_={start:position,end:position};}},};cvox.FixedPanStrategy=cvox.PanStrategy;cvox.WrappingPanStrategy=function(){cvox.PanStrategy.call(this);};cvox.WrappingPanStrategy.prototype={__proto__:cvox.PanStrategy.prototype,calculateBreakPoints_:function(content){var view=new Uint8Array(content);var newContentLength=view.length;var result=[];var lastCellWasBlank=false;for(var pos=0;pos<view.length;++pos){if(lastCellWasBlank&&view[pos]!=0){result.push(pos);}
lastCellWasBlank=(view[pos]==0);}
return result;},};goog.provide('PanelCommand');goog.provide('PanelCommandType');PanelCommand=function(type,opt_data){this.type=type;this.data=opt_data;};PanelCommand.prototype.send=function(){var views=chrome.extension.getViews();for(var i=0;i<views.length;i++){if(views[i].location.href.indexOf('background/panel.html')>0){views[i].postMessage(JSON.stringify(this),window.location.origin);}}};PanelCommandType={CLEAR_SPEECH:'clear_speech',ADD_NORMAL_SPEECH:'add_normal_speech',ADD_ANNOTATION_SPEECH:'add_annotation_speech',UPDATE_BRAILLE:'update_braille',OPEN_MENUS:'open_menus',ENABLE_MENUS:'enable_menus',DISABLE_MENUS:'disable_menus',SEARCH:'search',TUTORIAL:'tutorial',};goog.provide('cvox.BrailleCaptionsBackground');goog.require('PanelCommand');goog.require('cvox.BrailleDisplayState');goog.require('cvox.ExtensionBridge');cvox.BrailleCaptionsBackground.PREF_KEY='brailleCaptions';cvox.BrailleCaptionsBackground.BRAILLE_UNICODE_BLOCK_START=0x2800;cvox.BrailleCaptionsBackground.init=function(stateCallback){var self=cvox.BrailleCaptionsBackground;self.stateCallback_=stateCallback;};cvox.BrailleCaptionsBackground.isEnabled=function(){var self=cvox.BrailleCaptionsBackground;return localStorage[self.PREF_KEY]===String(true);};cvox.BrailleCaptionsBackground.setContent=function(text,cells,brailleToText){var self=cvox.BrailleCaptionsBackground;var byteBuf=new Uint8Array(cells);var brailleChars='';for(var i=0;i<byteBuf.length;++i){brailleChars+=String.fromCharCode(self.BRAILLE_UNICODE_BLOCK_START|byteBuf[i]);}
var groups=this.groupBrailleAndText(brailleChars,text,brailleToText);if(cvox.ChromeVox.isChromeOS){var data={groups:groups};(new PanelCommand(PanelCommandType.UPDATE_BRAILLE,data)).send();}else{cvox.ExtensionBridge.send({message:'BRAILLE_CAPTION',text:text,brailleChars:brailleChars});}};cvox.BrailleCaptionsBackground.groupBrailleAndText=function(brailleChars,text,brailleToText){var brailleBuf='';var groups=[];var textIndex=0;for(var i=0;i<brailleChars.length;++i){if((i!=0)&&((brailleToText[i]!=textIndex))){groups.push([text.substr(textIndex,brailleToText[i]-textIndex),brailleBuf]);brailleBuf='';textIndex=brailleToText[i];}
brailleBuf+=brailleChars.charAt(i);}
if(brailleBuf.length>0){groups.push([text.substr(textIndex),brailleBuf]);}
return groups;};cvox.BrailleCaptionsBackground.setActive=function(newValue){var self=cvox.BrailleCaptionsBackground;var oldValue=self.isEnabled();window['prefs'].setPref(self.PREF_KEY,String(newValue));if(oldValue!=newValue){if(self.stateCallback_){self.stateCallback_();}
var msg=newValue?Msgs.getMsg('braille_captions_enabled'):Msgs.getMsg('braille_captions_disabled');cvox.ChromeVox.tts.speak(msg,cvox.QueueMode.QUEUE);cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(msg));}};cvox.BrailleCaptionsBackground.getVirtualDisplayState=function(){var self=cvox.BrailleCaptionsBackground;if(self.isEnabled()){return{available:true,textCellCount:40};}else{return{available:false};}};goog.provide('cvox.BrailleDisplayManager');goog.require('cvox.BrailleCaptionsBackground');goog.require('cvox.BrailleDisplayState');goog.require('cvox.ExpandingBrailleTranslator');goog.require('cvox.LibLouis');goog.require('cvox.NavBraille');goog.require('cvox.PanStrategy');cvox.BrailleDisplayManager=function(translatorManager){this.translatorManager_=translatorManager;this.content_=new cvox.NavBraille({});this.expansionType_=cvox.ExpandingBrailleTranslator.ExpansionType.SELECTION;this.translatedContent_=new ArrayBuffer(0);this.displayedContent_=this.translatedContent_;this.panStrategy_=new cvox.WrappingPanStrategy();this.commandListener_=function(){};this.displayState_={available:false,textCellCount:undefined};this.realDisplayState_=this.displayState_;this.textToBraille_=[];this.brailleToText_=[];translatorManager.addChangeListener(function(){this.translateContent_(this.content_,this.expansionType_);}.bind(this));chrome.storage.onChanged.addListener(function(changes,area){if(area=='local'&&'brailleWordWrap'in changes){this.updatePanStrategy_(changes.brailleWordWrap.newValue);}}.bind(this));chrome.storage.local.get({brailleWordWrap:true},function(items){this.updatePanStrategy_(items.brailleWordWrap);}.bind(this));cvox.BrailleCaptionsBackground.init(goog.bind(this.onCaptionsStateChanged_,this));if(goog.isDef(chrome.brailleDisplayPrivate)){var onDisplayStateChanged=goog.bind(this.refreshDisplayState_,this);chrome.brailleDisplayPrivate.getDisplayState(onDisplayStateChanged);chrome.brailleDisplayPrivate.onDisplayStateChanged.addListener(onDisplayStateChanged);chrome.brailleDisplayPrivate.onKeyEvent.addListener(goog.bind(this.onKeyEvent_,this));}else{this.onCaptionsStateChanged_();}};cvox.BrailleDisplayManager.CURSOR_DOTS_=1<<6|1<<7;cvox.BrailleDisplayManager.prototype.setContent=function(content,expansionType){this.translateContent_(content,expansionType);};cvox.BrailleDisplayManager.prototype.setCommandListener=function(func){this.commandListener_=func;};cvox.BrailleDisplayManager.prototype.refreshDisplayState_=function(newState){var oldSize=this.displayState_.textCellCount||0;this.realDisplayState_=newState;if(newState.available){this.displayState_=newState;}else{this.displayState_=cvox.BrailleCaptionsBackground.getVirtualDisplayState();}
var newSize=this.displayState_.textCellCount||0;if(oldSize!=newSize){this.panStrategy_.setDisplaySize(newSize);}
this.refresh_();};cvox.BrailleDisplayManager.prototype.onCaptionsStateChanged_=function(){this.refreshDisplayState_(this.realDisplayState_);};cvox.BrailleDisplayManager.prototype.refresh_=function(){if(!this.displayState_.available){return;}
var viewPort=this.panStrategy_.viewPort;var buf=this.displayedContent_.slice(viewPort.start,viewPort.end);if(this.realDisplayState_.available){chrome.brailleDisplayPrivate.writeDots(buf);}
if(cvox.BrailleCaptionsBackground.isEnabled()){var start=this.brailleToTextPosition_(viewPort.start);var end=this.brailleToTextPosition_(viewPort.end);cvox.BrailleCaptionsBackground.setContent(this.content_.text.toString().substring(start,end),buf,this.brailleToText_);}};cvox.BrailleDisplayManager.prototype.translateContent_=function(newContent,newExpansionType){var writeTranslatedContent=function(cells,textToBraille,brailleToText){this.content_=newContent;this.expansionType_=newExpansionType;this.textToBraille_=textToBraille;this.brailleToText_=brailleToText;var startIndex=this.content_.startIndex;var endIndex=this.content_.endIndex;var targetPosition;if(startIndex>=0){var translatedStartIndex;var translatedEndIndex;if(startIndex>=textToBraille.length){var extCells=new ArrayBuffer(cells.byteLength+1);new Uint8Array(extCells).set(new Uint8Array(cells));cells=extCells;translatedStartIndex=cells.byteLength-1;}else{translatedStartIndex=textToBraille[startIndex];}
if(endIndex>=textToBraille.length){translatedEndIndex=cells.byteLength;}else{translatedEndIndex=textToBraille[endIndex];}
this.translatedContent_=cells;this.displayedContent_=new ArrayBuffer(cells.byteLength);new Uint8Array(this.displayedContent_).set(new Uint8Array(cells));this.writeCursor_(this.displayedContent_,translatedStartIndex,translatedEndIndex);targetPosition=translatedStartIndex;}else{this.translatedContent_=this.displayedContent_=cells;targetPosition=0;}
this.panStrategy_.setContent(this.translatedContent_,targetPosition);this.refresh_();}.bind(this);var translator=this.translatorManager_.getExpandingTranslator();if(!translator){writeTranslatedContent(new ArrayBuffer(0),[],[]);}else{translator.translate(newContent.text,newExpansionType,writeTranslatedContent);}};cvox.BrailleDisplayManager.prototype.onKeyEvent_=function(event){switch(event.command){case cvox.BrailleKeyCommand.PAN_LEFT:this.panLeft_();break;case cvox.BrailleKeyCommand.PAN_RIGHT:this.panRight_();break;case cvox.BrailleKeyCommand.ROUTING:event.displayPosition=this.brailleToTextPosition_(event.displayPosition+this.panStrategy_.viewPort.start);default:this.commandListener_(event,this.content_);break;}};cvox.BrailleDisplayManager.prototype.panLeft_=function(){if(this.panStrategy_.previous()){this.refresh_();}else{this.commandListener_({command:cvox.BrailleKeyCommand.PAN_LEFT},this.content_);}};cvox.BrailleDisplayManager.prototype.panRight_=function(){if(this.panStrategy_.next()){this.refresh_();}else{this.commandListener_({command:cvox.BrailleKeyCommand.PAN_RIGHT},this.content_);}};cvox.BrailleDisplayManager.prototype.writeCursor_=function(buffer,startIndex,endIndex){if(startIndex<0||startIndex>=buffer.byteLength||endIndex<startIndex||endIndex>buffer.byteLength){return;}
if(startIndex==endIndex){endIndex=startIndex+1;}
var dataView=new DataView(buffer);while(startIndex<endIndex){var value=dataView.getUint8(startIndex);value|=cvox.BrailleDisplayManager.CURSOR_DOTS_;dataView.setUint8(startIndex,value);startIndex++;}};cvox.BrailleDisplayManager.prototype.brailleToTextPosition_=function(braillePosition){var mapping=this.brailleToText_;if(braillePosition<0){console.error('WARNING: Braille position < 0: '+braillePosition);return 0;}else if(braillePosition>=mapping.length){return this.content_.text.length;}else{return mapping[braillePosition];}};cvox.BrailleDisplayManager.prototype.updatePanStrategy_=function(wordWrap){var newStrategy=wordWrap?new cvox.WrappingPanStrategy():new cvox.FixedPanStrategy();newStrategy.setDisplaySize(this.displayState_.textCellCount||0);newStrategy.setContent(this.translatedContent_,this.panStrategy_.viewPort.start);this.panStrategy_=newStrategy;this.refresh_();};goog.provide('cvox.BrailleInputHandler');goog.require('StringUtil');goog.require('cvox.BrailleKeyCommand');goog.require('cvox.BrailleKeyEvent');goog.require('cvox.ExpandingBrailleTranslator');cvox.BrailleInputHandler=function(translatorManager){this.imePort_=null;this.imeActive_=false;this.inputContext_=null;this.translatorManager_=translatorManager;this.currentTextBefore_='';this.currentTextAfter_='';this.pendingCells_=[];this.entryState_=null;this.uncommittedCellsSpan_=null;this.uncommittedCellsChangedListener_=null;this.translatorManager_.addChangeListener(this.commitAndClearEntryState_.bind(this));};cvox.BrailleInputHandler.IME_EXTENSION_ID_='jddehjeebkoimngcbdkaahpobgicbffp';cvox.BrailleInputHandler.IME_PORT_NAME_='cvox.BrailleIme.Port';cvox.BrailleInputHandler.STARTS_WITH_NON_WHITESPACE_RE_=/^\S/;cvox.BrailleInputHandler.ENDS_WITH_NON_WHITESPACE_RE_=/\S$/;cvox.BrailleInputHandler.prototype={init:function(){chrome.runtime.onConnectExternal.addListener(this.onImeConnect_.bind(this));},onDisplayContentChanged:function(text,listener){var valueSpan=text.getSpanInstanceOf(cvox.ValueSpan);var selectionSpan=text.getSpanInstanceOf(cvox.ValueSelectionSpan);if(!(valueSpan&&selectionSpan))
return;this.uncommittedCellsChangedListener_=null;var valueStart=text.getSpanStart(valueSpan);var valueEnd=text.getSpanEnd(valueSpan);var selectionStart=text.getSpanStart(selectionSpan);var selectionEnd=text.getSpanEnd(selectionSpan);if(selectionStart<valueStart||selectionEnd>valueEnd){console.error('Selection outside of value in braille content');this.clearEntryState_();return;}
var newTextBefore=text.toString().substring(valueStart,selectionStart);if(this.currentTextBefore_!==newTextBefore&&this.entryState_)
this.entryState_.onTextBeforeChanged(newTextBefore);this.currentTextBefore_=newTextBefore;this.currentTextAfter_=text.toString().substring(selectionEnd,valueEnd);this.uncommittedCellsSpan_=new cvox.ExtraCellsSpan();text.setSpan(this.uncommittedCellsSpan_,selectionStart,selectionStart);if(this.entryState_&&this.entryState_.usesUncommittedCells){this.updateUncommittedCells_(new Uint8Array(this.entryState_.cells_).buffer);}
this.uncommittedCellsChangedListener_=listener;},onBrailleKeyEvent:function(event){if(event.command===cvox.BrailleKeyCommand.DOTS)
return this.onBrailleDots_((event.brailleDots));this.pendingCells_.length=0;if(event.command===cvox.BrailleKeyCommand.STANDARD_KEY){if(event.standardKeyCode==='Backspace'&&!event.altKey&&!event.ctrlKey&&!event.shiftKey&&this.onBackspace_()){return true;}else{this.commitAndClearEntryState_();this.sendKeyEventPair_(event);return true;}}
return false;},getExpansionType:function(){if(this.inAlwaysUncontractedContext_())
return cvox.ExpandingBrailleTranslator.ExpansionType.ALL;if(this.entryState_&&this.entryState_.translator===this.translatorManager_.getDefaultTranslator()){return cvox.ExpandingBrailleTranslator.ExpansionType.NONE;}
return cvox.ExpandingBrailleTranslator.ExpansionType.SELECTION;},inAlwaysUncontractedContext_:function(){var inputType=this.inputContext_?this.inputContext_.type:'';return inputType==='url'||inputType==='email';},onBrailleDots_:function(dots){if(!this.imeActive_){this.pendingCells_.push(dots);return true;}
if(!this.inputContext_)
return false;if(!this.entryState_){if(!(this.entryState_=this.createEntryState_()))
return false;}
this.entryState_.appendCell(dots);return true;},onBackspace_:function(){if(this.imeActive_&&this.entryState_){this.entryState_.deleteLastCell();return true;}
return false;},createEntryState_:function(){var translator=this.translatorManager_.getDefaultTranslator();if(!translator)
return null;var uncontractedTranslator=this.translatorManager_.getUncontractedTranslator();var constructor=cvox.BrailleInputHandler.EditsEntryState_;if(uncontractedTranslator){var textBefore=this.currentTextBefore_;var textAfter=this.currentTextAfter_;if(this.inAlwaysUncontractedContext_()||(cvox.BrailleInputHandler.ENDS_WITH_NON_WHITESPACE_RE_.test(textBefore))||(cvox.BrailleInputHandler.STARTS_WITH_NON_WHITESPACE_RE_.test(textAfter))){translator=uncontractedTranslator;}else{constructor=cvox.BrailleInputHandler.LateCommitEntryState_;}}
return new constructor(this,translator);},commitAndClearEntryState_:function(){if(this.entryState_){this.entryState_.commit();this.clearEntryState_();}},clearEntryState_:function(){if(this.entryState_){if(this.entryState_.usesUncommittedCells)
this.updateUncommittedCells_(new ArrayBuffer(0));this.entryState_.inputHandler_=null;this.entryState_=null;}},updateUncommittedCells_:function(cells){if(this.uncommittedCellsSpan_)
this.uncommittedCellsSpan_.cells=cells;if(this.uncommittedCellsChangedListener_)
this.uncommittedCellsChangedListener_();},onImeConnect_:function(port){if(port.name!==cvox.BrailleInputHandler.IME_PORT_NAME_||port.sender.id!==cvox.BrailleInputHandler.IME_EXTENSION_ID_){return;}
if(this.imePort_)
this.imePort_.disconnect();port.onDisconnect.addListener(this.onImeDisconnect_.bind(this,port));port.onMessage.addListener(this.onImeMessage_.bind(this));this.imePort_=port;},onImeMessage_:function(message){if(!goog.isObject(message)){console.error('Unexpected message from Braille IME: ',JSON.stringify(message));}
switch(message.type){case'activeState':this.imeActive_=message.active;break;case'inputContext':this.inputContext_=message.context;this.clearEntryState_();if(this.imeActive_&&this.inputContext_)
this.pendingCells_.forEach(this.onBrailleDots_,this);this.pendingCells_.length=0;break;case'brailleDots':this.onBrailleDots_(message['dots']);break;case'backspace':this.postImeMessage_({type:'keyEventHandled',requestId:message['requestId'],result:this.onBackspace_()});break;case'reset':this.clearEntryState_();break;default:console.error('Unexpected message from Braille IME: ',JSON.stringify(message));break;}},onImeDisconnect_:function(port){this.imePort_=null;this.clearEntryState_();this.imeActive_=false;this.inputContext_=null;},postImeMessage_:function(message){if(this.imePort_){this.imePort_.postMessage(message);return true;}
return false;},sendKeyEventPair_:function(event){var keyName=(event.standardKeyCode);var numericCode=cvox.BrailleKeyEvent.keyCodeToLegacyCode(keyName);if(!goog.isDef(numericCode))
throw Error('Unknown key code in event: '+JSON.stringify(event));var keyEvent={type:'keydown',keyCode:numericCode,keyName:keyName,charValue:cvox.BrailleKeyEvent.keyCodeToCharValue(keyName),modifiers:(event.shiftKey?2:0)|(event.ctrlKey?4:0)|(event.altKey?8:0)};chrome.virtualKeyboardPrivate.sendKeyEvent(keyEvent);keyEvent.type='keyup';chrome.virtualKeyboardPrivate.sendKeyEvent(keyEvent);}};cvox.BrailleInputHandler.EntryState_=function(inputHandler,translator){this.inputHandler_=inputHandler;this.translator_=translator;this.cells_=[];this.text_='';this.pendingTextsBefore_=[];};cvox.BrailleInputHandler.EntryState_.prototype={get translator(){return this.translator_;},appendCell:function(cell){this.cells_.push(cell);this.updateText_();},deleteLastCell:function(){if(--this.cells_.length<=0){this.sendTextChange_('');this.inputHandler_.clearEntryState_();return;}
this.updateText_();},onTextBeforeChanged:function(newText){for(var i=0;i<this.pendingTextsBefore_.length;++i){if(newText===this.pendingTextsBefore_[i]){this.pendingTextsBefore_.splice(0,i+1);return;}}
this.inputHandler_.clearEntryState_();},commit:function(){},get usesUncommittedCells(){return false;},updateText_:function(){var cellsBuffer=new Uint8Array(this.cells_).buffer;var commit=this.lastCellIsBlank_;if(!commit&&this.usesUncommittedCells)
this.inputHandler_.updateUncommittedCells_(cellsBuffer);this.translator_.backTranslate(cellsBuffer,function(result){if(result===null){console.error('Error when backtranslating braille cells');return;}
if(!this.inputHandler_)
return;this.sendTextChange_(result);this.text_=result;if(commit)
this.inputHandler_.commitAndClearEntryState_();}.bind(this));},get lastCellIsBlank_(){return this.cells_[this.cells_.length-1]===0;},sendTextChange_:function(newText){}};cvox.BrailleInputHandler.EditsEntryState_=function(inputHandler,translator){cvox.BrailleInputHandler.EntryState_.call(this,inputHandler,translator);};cvox.BrailleInputHandler.EditsEntryState_.prototype={__proto__:cvox.BrailleInputHandler.EntryState_.prototype,sendTextChange_:function(newText){var oldText=this.text_;var commonPrefixLength=StringUtil.longestCommonPrefixLength(oldText,newText);var deleteLength=oldText.length-commonPrefixLength;var toInsert=newText.substring(commonPrefixLength);if(deleteLength>0||toInsert.length>0){var textBeforeAfterDelete=this.inputHandler_.currentTextBefore_.substring(0,this.inputHandler_.currentTextBefore_.length-deleteLength);if(deleteLength>0){this.pendingTextsBefore_.push(textBeforeAfterDelete);}
if(toInsert.length>0){this.pendingTextsBefore_.push(textBeforeAfterDelete+toInsert);}
this.inputHandler_.postImeMessage_({type:'replaceText',contextID:this.inputHandler_.inputContext_.contextID,deleteBefore:deleteLength,newText:toInsert});}}};cvox.BrailleInputHandler.LateCommitEntryState_=function(inputHandler,translator){cvox.BrailleInputHandler.EntryState_.call(this,inputHandler,translator);};cvox.BrailleInputHandler.LateCommitEntryState_.prototype={__proto__:cvox.BrailleInputHandler.EntryState_.prototype,commit:function(){this.inputHandler_.postImeMessage_({type:'commitUncommitted',contextID:this.inputHandler_.inputContext_.contextID});},get usesUncommittedCells(){return true;},sendTextChange_:function(newText){this.inputHandler_.postImeMessage_({type:'setUncommitted',contextID:this.inputHandler_.inputContext_.contextID,text:newText});}};goog.provide('cvox.BrailleTable');cvox.BrailleTable.Table;cvox.BrailleTable.TABLE_PATH='braille/tables.json';cvox.BrailleTable.COMMON_DEFS_FILENAME_='cvox-common.cti';cvox.BrailleTable.getAll=function(callback){function appendCommonFilename(tables){tables.forEach(function(table){table.fileNames+=(','+cvox.BrailleTable.COMMON_DEFS_FILENAME_);});return tables;}
var url=chrome.extension.getURL(cvox.BrailleTable.TABLE_PATH);if(!url){throw'Invalid path: '+cvox.BrailleTable.TABLE_PATH;}
var xhr=new XMLHttpRequest();xhr.open('GET',url,true);xhr.onreadystatechange=function(){if(xhr.readyState==4){if(xhr.status==200){callback(appendCommonFilename((JSON.parse(xhr.responseText))));}}};xhr.send();};cvox.BrailleTable.forId=function(tables,id){return tables.filter(function(table){return table.id===id})[0]||null;};cvox.BrailleTable.getUncontracted=function(tables,table){function mostUncontractedOf(current,candidate){if(current.dots==='6'&&candidate.dots==='8'&&current.locale.lastIndexOf(candidate.locale,0)==0){return candidate;}
if(current.locale===candidate.locale&&current.dots===candidate.dots&&goog.isDef(current.grade)&&goog.isDef(candidate.grade)&&candidate.grade<current.grade){return candidate;}
return current;}
return tables.reduce(mostUncontractedOf,table);};cvox.BrailleTable.getDisplayName=function(table){var localeName=Msgs.getLocaleDisplayName(table.locale);if(!table.grade&&!table.variant){return localeName;}else if(table.grade&&!table.variant){return Msgs.getMsg('braille_table_name_with_grade',[localeName,table.grade]);}else if(!table.grade&&table.variant){return Msgs.getMsg('braille_table_name_with_variant',[localeName,table.variant]);}else{return Msgs.getMsg('braille_table_name_with_variant_and_grade',[localeName,table.variant,table.grade]);}};goog.provide('cvox.BrailleTranslatorManager');goog.require('cvox.BrailleTable');goog.require('cvox.ExpandingBrailleTranslator');goog.require('cvox.LibLouis');cvox.BrailleTranslatorManager=function(opt_liblouisForTest){this.liblouis_=opt_liblouisForTest||new cvox.LibLouis(chrome.extension.getURL('braille/liblouis_nacl.nmf'),chrome.extension.getURL('braille/tables'));this.changeListeners_=[];this.tables_=[];this.expandingTranslator_=null;this.defaultTranslator_=null;this.defaultTableId_=null;this.uncontractedTranslator_=null;this.uncontractedTableId_=null;if(!opt_liblouisForTest){document.addEventListener('DOMContentLoaded',this.loadLiblouis_.bind(this),false);}};cvox.BrailleTranslatorManager.prototype={addChangeListener:function(listener){this.changeListeners_.push(listener);},refresh:function(){var tables=this.tables_;if(tables.length==0)
return;var table=cvox.BrailleTable.forId(tables,localStorage['brailleTable']);if(!table){var currentLocale=chrome.i18n.getMessage('@@ui_locale').split(/[_-]/);var major=currentLocale[0];var minor=currentLocale[1];var firstPass=tables.filter(function(table){return table.locale.split(/[_-]/)[0]==major;});if(firstPass.length>0){table=firstPass[0];if(minor){var secondPass=firstPass.filter(function(table){return table.locale.split(/[_-]/)[1]==minor;});if(secondPass.length>0)
table=secondPass[0];}}}
if(!table)
table=cvox.BrailleTable.forId(tables,'en-US-comp8');localStorage['brailleTable']=table.id;if(!localStorage['brailleTable6'])
localStorage['brailleTable6']='en-US-g1';if(!localStorage['brailleTable8'])
localStorage['brailleTable8']='en-US-comp8';if(table.dots=='6'){localStorage['brailleTableType']='brailleTable6';localStorage['brailleTable6']=table.id;}else{localStorage['brailleTableType']='brailleTable8';localStorage['brailleTable8']=table.id;}
var table8Dot=cvox.BrailleTable.forId(tables,localStorage['brailleTable8']);var uncontractedTable=cvox.BrailleTable.getUncontracted(tables,table8Dot||table);var newDefaultTableId=table.id;var newUncontractedTableId=table.id===uncontractedTable.id?null:uncontractedTable.id;if(newDefaultTableId===this.defaultTableId_&&newUncontractedTableId===this.uncontractedTableId_){return;}
var finishRefresh=function(defaultTranslator,uncontractedTranslator){this.defaultTableId_=newDefaultTableId;this.uncontractedTableId_=newUncontractedTableId;this.expandingTranslator_=new cvox.ExpandingBrailleTranslator(defaultTranslator,uncontractedTranslator);this.defaultTranslator_=defaultTranslator;this.uncontractedTranslator_=uncontractedTranslator;this.changeListeners_.forEach(function(listener){listener();});}.bind(this);this.liblouis_.getTranslator(table.fileNames,function(translator){if(!newUncontractedTableId){finishRefresh(translator,null);}else{this.liblouis_.getTranslator(uncontractedTable.fileNames,function(uncontractedTranslator){finishRefresh(translator,uncontractedTranslator);});}}.bind(this));},getExpandingTranslator:function(){return this.expandingTranslator_;},getDefaultTranslator:function(){return this.defaultTranslator_;},getUncontractedTranslator:function(){return this.uncontractedTranslator_;},fetchTables_:function(){cvox.BrailleTable.getAll(function(tables){this.tables_=tables;this.refresh();}.bind(this));},loadLiblouis_:function(){this.liblouis_.attachToElement((document.body));this.fetchTables_();},getLibLouisForTest:function(){return this.liblouis_;},getTablesForTest:function(){return this.tables_;}};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.BrailleBackground');goog.require('ChromeVoxState');goog.require('cvox.BrailleDisplayManager');goog.require('cvox.BrailleInputHandler');goog.require('cvox.BrailleInterface');goog.require('cvox.BrailleKeyEvent');goog.require('cvox.BrailleTranslatorManager');cvox.BrailleBackground=function(opt_displayManagerForTest,opt_inputHandlerForTest,opt_translatorManagerForTest){this.translatorManager_=opt_translatorManagerForTest||new cvox.BrailleTranslatorManager();this.displayManager_=opt_displayManagerForTest||new cvox.BrailleDisplayManager(this.translatorManager_);this.displayManager_.setCommandListener(this.onBrailleKeyEvent_.bind(this));this.lastContent_=null;this.lastContentId_=null;this.inputHandler_=opt_inputHandlerForTest||new cvox.BrailleInputHandler(this.translatorManager_);this.inputHandler_.init();};cvox.BrailleBackground.prototype.write=function(params){this.setContent_(params,null);};cvox.BrailleBackground.prototype.getTranslatorManager=function(){return this.translatorManager_;};cvox.BrailleBackground.prototype.onBrailleMessage=function(msg){if(msg['action']=='write'){this.setContent_(cvox.NavBraille.fromJson(msg['params']),msg['contentId']);}};cvox.BrailleBackground.prototype.setContent_=function(newContent,newContentId){var updateContent=function(){this.lastContent_=newContentId?newContent:null;this.lastContentId_=newContentId;this.displayManager_.setContent(newContent,this.inputHandler_.getExpansionType());}.bind(this);this.inputHandler_.onDisplayContentChanged(newContent.text,updateContent);updateContent();};cvox.BrailleBackground.prototype.onBrailleKeyEvent_=function(brailleEvt,content){if(this.inputHandler_.onBrailleKeyEvent(brailleEvt)){return;}
if(ChromeVoxState.instance&&ChromeVoxState.instance.onBrailleKeyEvent(brailleEvt,content)){return;}
this.sendCommand_(brailleEvt,content);};cvox.BrailleBackground.prototype.sendCommand_=function(brailleEvt,content){var msg={'message':'BRAILLE','args':brailleEvt};if(content===this.lastContent_){msg.contentId=this.lastContentId_;}
cvox.ExtensionBridge.send(msg);};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('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.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.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.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.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.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.MathCompoundStore');goog.provide('cvox.MathSimpleStore');goog.require('cvox.MathStore');goog.require('cvox.SpeechRule');cvox.MathSimpleStore=function(){goog.base(this);};goog.inherits(cvox.MathSimpleStore,cvox.MathStore);cvox.MathSimpleStore.prototype.defineRulesFromMappings=function(name,str,mapping){for(var domain in mapping){for(var style in mapping[domain]){var content=mapping[domain][style];var cstr='self::text() = "'+str+'"';var rule=this.defineRule(name,domain+'.'+style,'[t] "'+content+'"','self::text()',cstr);}}};cvox.MathCompoundStore=function(){this.subStores_={};};goog.addSingletonGetter(cvox.MathCompoundStore);cvox.MathCompoundStore.prototype.defineRules=function(name,str,mappings){var store=new cvox.MathSimpleStore();store.defineRulesFromMappings(name,str,mappings);this.subStores_[str]=store;};cvox.MathCompoundStore.prototype.addSymbolRules=function(json){var key=cvox.MathSimpleStore.parseUnicode_(json['key']);this.defineRules(json['key'],key,json['mappings']);};cvox.MathCompoundStore.prototype.addFunctionRules=function(json){var names=json['names'];var mappings=json['mappings'];for(var j=0,name;name=names[j];j++){this.defineRules(name,name,mappings);}};cvox.MathCompoundStore.prototype.lookupRule=function(node,dynamic){var store=this.subStores_[node.textContent];if(store){return store.lookupRule(node,dynamic);}
return null;};cvox.MathCompoundStore.prototype.lookupString=function(text,dynamic){var textNode=document.createTextNode(text);var rule=this.lookupRule(textNode,dynamic);if(!rule){return'';}
return rule.action.components.map(function(comp){return comp.content.slice(1,-1);}).join(' ');};cvox.MathCompoundStore.prototype.getDynamicConstraintValues=function(){var newCstr={};for(var store in this.subStores_){var cstr=this.subStores_[store].getDynamicConstraintValues();for(var key in cstr){var set=newCstr[key];if(set){newCstr[key]=cvox.MathUtil.union(set,cstr[key]);}else{newCstr[key]=cstr[key];}}}
return newCstr;};cvox.MathSimpleStore.parseUnicode_=function(number){var keyValue=parseInt(number,16);if(keyValue<0x10000){return String.fromCharCode(keyValue);}
keyValue-=0x10000;var hiSurrogate=(keyValue>>10)+0xD800;var lowSurrogate=(keyValue&0x3FF)+0xDC00;return String.fromCharCode(hiSurrogate,lowSurrogate);};goog.provide('cvox.MathMap');goog.require('cvox.MathCompoundStore');goog.require('cvox.MathUtil');cvox.MathMap=function(){this.store=cvox.MathCompoundStore.getInstance();cvox.MathMap.parseFiles(cvox.MathMap.FUNCTIONS_FILES_.map(function(file){return cvox.MathMap.FUNCTIONS_PATH_+file;})).forEach(goog.bind(this.store.addFunctionRules,this.store));cvox.MathMap.parseFiles(cvox.MathMap.SYMBOLS_FILES_.map(function(file){return cvox.MathMap.SYMBOLS_PATH_+file;})).forEach(goog.bind(this.store.addSymbolRules,this.store));var cstrValues=this.store.getDynamicConstraintValues();this.allDomains=cstrValues.domain;this.allStyles=cstrValues.style;};cvox.MathMap.prototype.stringify=function(){return JSON.stringify(this);};cvox.MathMap.MATHMAP_PATH_='chromevox/background/mathmaps/';cvox.MathMap.SYMBOLS_PATH_=cvox.MathMap.MATHMAP_PATH_+'symbols/';cvox.MathMap.FUNCTIONS_PATH_=cvox.MathMap.MATHMAP_PATH_+'functions/';cvox.MathMap.SYMBOLS_FILES_=['greek-capital.json','greek-small.json','greek-scripts.json','greek-mathfonts.json','greek-symbols.json','hebrew_letters.json','latin-lower-double-accent.json','latin-lower-normal.json','latin-lower-phonetic.json','latin-lower-single-accent.json','latin-rest.json','latin-upper-double-accent.json','latin-upper-normal.json','latin-upper-single-accent.json','latin-mathfonts.json','math_angles.json','math_arrows.json','math_characters.json','math_delimiters.json','math_digits.json','math_geometry.json','math_harpoons.json','math_non_characters.json','math_symbols.json','math_whitespace.json','other_stars.json'];cvox.MathMap.FUNCTIONS_FILES_=['algebra.json','elementary.json','hyperbolic.json','trigonometry.json'];cvox.MathMap.loadFile=function(file){try{return cvox.MathMap.readJSON_(file);}catch(x){console.log('Unable to load file: '+file+', error: '+x);}};cvox.MathMap.loadFiles=function(files){return files.map(cvox.MathMap.loadFile);};cvox.MathMap.parseFiles=function(files){var strs=cvox.MathMap.loadFiles(files);return[].concat.apply([],strs.map(function(value){return JSON.parse(value);}));};cvox.MathMap.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;};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.TtsBackground');goog.require('PanelCommand');goog.require('cvox.AbstractTts');goog.require('cvox.ChromeTtsBase');goog.require('cvox.ChromeVox');goog.require('cvox.MathMap');goog.require('goog.i18n.MessageFormat');cvox.Utterance=function(textString,properties){this.textString=textString;this.properties=properties;this.id=cvox.Utterance.nextUtteranceId_++;};cvox.Utterance.nextUtteranceId_=1;cvox.TtsBackground=function(opt_enableMath){opt_enableMath=opt_enableMath==undefined?true:opt_enableMath;goog.base(this);this.ttsProperties['rate']=(parseFloat(localStorage['rate'])||this.propertyDefault['rate']);this.ttsProperties['pitch']=(parseFloat(localStorage['pitch'])||this.propertyDefault['pitch']);this.ttsProperties['volume']=(parseFloat(localStorage['volume'])||this.propertyDefault['volume']);if(this.ttsProperties['lang']==undefined){this.ttsProperties['lang']=chrome.i18n.getMessage('@@ui_locale').replace('_','-');}
this.lastEventType='end';this.currentPunctuationEcho_=parseInt(localStorage[cvox.AbstractTts.PUNCTUATION_ECHO]||1,10);this.punctuationEchoes_=[{name:'none',msg:'no_punctuation',regexp:/[-$#"()*;:<>\n\\\/+='~`@_]/g,clear:true},{name:'some',msg:'some_punctuation',regexp:/[$#"*<>\\\/\{\}+=~`%]/g,clear:false},{name:'all',msg:'all_punctuation',regexp:/[-$#"()*;:<>\n\\\/\{\}\[\]+='~`!@_.,?%]/g,clear:false}];this.retainPunctuation_=[';','?','!','\''];this.mathmap=opt_enableMath?new cvox.MathMap():null;this.timeoutId_;try{this.PHONETIC_MAP_=(JSON.parse(Msgs.getMsg('phonetic_map')));}catch(e){console.log('Error; unable to parse phonetic map msg.');}
this.capturingTtsEventListeners_=[];this.currentUtterance_=null;this.utteranceQueue_=[];if(localStorage['voiceName']){chrome.storage.local.set({voiceName:localStorage['voiceName']});delete localStorage['voiceName'];}
window.speechSynthesis.onvoiceschanged=function(){chrome.storage.local.get({voiceName:''},function(items){this.updateVoice_(items.voiceName);}.bind(this));}.bind(this);chrome.storage.onChanged.addListener(function(changes,namespace){if(changes.voiceName){this.updateVoice_(changes.voiceName.newValue);}}.bind(this));};goog.inherits(cvox.TtsBackground,cvox.ChromeTtsBase);cvox.TtsBackground.PHONETIC_DELAY_MS_=1000;cvox.TtsBackground.ALLOWED_PROPERTIES_=['desiredEventTypes','enqueue','extensionId','gender','lang','onEvent','pitch','rate','requiredEventTypes','voiceName','volume'];cvox.TtsBackground.prototype.speak=function(textString,queueMode,properties){goog.base(this,'speak',textString,queueMode,properties);if(!properties){properties={};}
var splitTextString=textString.replace(/([-\n\r.,!?;])(\s)/g,'$1$2|');splitTextString=splitTextString.split('|');if(splitTextString.length>2){var startCallback=properties['startCallback'];var endCallback=properties['endCallback'];var onEvent=properties['onEvent'];for(var i=0;i<splitTextString.length;i++){var propertiesCopy={};for(var p in properties){propertiesCopy[p]=properties[p];}
propertiesCopy['startCallback']=i==0?startCallback:null;propertiesCopy['endCallback']=i==(splitTextString.length-1)?endCallback:null;propertiesCopy['onEvent']=i==(splitTextString.length-1)?onEvent:null;this.speak(splitTextString[i],queueMode,propertiesCopy);queueMode=cvox.QueueMode.QUEUE;}
return this;}
textString=this.preprocess(textString,properties);textString=this.getNumberAsDigits_(textString);var mergedProperties=this.mergeProperties(properties);if(this.currentVoice){mergedProperties['voiceName']=this.currentVoice;}
if(queueMode==cvox.QueueMode.CATEGORY_FLUSH&&!mergedProperties['category']){queueMode=cvox.QueueMode.FLUSH;}
var utterance=new cvox.Utterance(textString,mergedProperties);this.speakUsingQueue_(utterance,queueMode);return this;};cvox.TtsBackground.prototype.speakUsingQueue_=function(utterance,queueMode){if(queueMode==cvox.QueueMode.FLUSH||queueMode==cvox.QueueMode.CATEGORY_FLUSH){(new PanelCommand(PanelCommandType.CLEAR_SPEECH)).send();if(this.shouldCancel_(this.currentUtterance_,utterance,queueMode)){this.cancelUtterance_(this.currentUtterance_);this.currentUtterance_=null;}
var i=0;while(i<this.utteranceQueue_.length){if(this.shouldCancel_(this.utteranceQueue_[i],utterance,queueMode)){this.cancelUtterance_(this.utteranceQueue_[i]);this.utteranceQueue_.splice(i,1);}else{i++;}}}
this.utteranceQueue_.push(utterance);if(utterance.properties&&utterance.properties['pitch']&&utterance.properties['pitch']<this.ttsProperties['pitch']){(new PanelCommand(PanelCommandType.ADD_ANNOTATION_SPEECH,utterance.textString)).send();}else{(new PanelCommand(PanelCommandType.ADD_NORMAL_SPEECH,utterance.textString)).send();}
this.startSpeakingNextItemInQueue_();};cvox.TtsBackground.prototype.startSpeakingNextItemInQueue_=function(){if(this.currentUtterance_){return;}
if(this.utteranceQueue_.length==0){return;}
if(!this.currentVoice){return;}
this.currentUtterance_=this.utteranceQueue_.shift();var utteranceId=this.currentUtterance_.id;this.currentUtterance_.properties['onEvent']=goog.bind(function(event){this.onTtsEvent_(event,utteranceId);},this);var validatedProperties={};for(var i=0;i<cvox.TtsBackground.ALLOWED_PROPERTIES_.length;i++){var p=cvox.TtsBackground.ALLOWED_PROPERTIES_[i];if(this.currentUtterance_.properties[p]){validatedProperties[p]=this.currentUtterance_.properties[p];}}
chrome.tts.speak(this.currentUtterance_.textString,validatedProperties);};cvox.TtsBackground.prototype.onTtsEvent_=function(event,utteranceId){this.lastEventType=event['type'];if(!this.currentUtterance_||utteranceId!=this.currentUtterance_.id){return;}
var utterance=this.currentUtterance_;switch(event.type){case'start':this.capturingTtsEventListeners_.forEach(function(listener){listener.onTtsStart();});if(utterance.properties['startCallback']){try{utterance.properties['startCallback']();}catch(e){}}
break;case'end':this.currentUtterance_=null;this.capturingTtsEventListeners_.forEach(function(listener){listener.onTtsEnd();});if(utterance.properties['endCallback']){try{utterance.properties['endCallback']();}catch(e){}}
this.startSpeakingNextItemInQueue_();break;case'interrupted':this.cancelUtterance_(utterance);this.currentUtterance_=null;for(var i=0;i<this.utteranceQueue_.length;i++){this.cancelUtterance_(this.utteranceQueue_[i]);}
this.utteranceQueue_.length=0;break;case'error':this.onError_(event['errorMessage']);this.startSpeakingNextItemInQueue_();break;}};cvox.TtsBackground.prototype.shouldCancel_=function(utteranceToCancel,newUtterance,queueMode){if(!utteranceToCancel){return false;}
if(utteranceToCancel.properties['doNotInterrupt']){return false;}
switch(queueMode){case cvox.QueueMode.QUEUE:return false;case cvox.QueueMode.FLUSH:return true;case cvox.QueueMode.CATEGORY_FLUSH:return(utteranceToCancel.properties['category']==newUtterance.properties['category']);}
return false;};cvox.TtsBackground.prototype.cancelUtterance_=function(utterance){if(utterance&&utterance.properties['endCallback']){try{utterance.properties['endCallback'](true);}catch(e){}}};cvox.TtsBackground.prototype.increaseOrDecreaseProperty=function(propertyName,increase){goog.base(this,'increaseOrDecreaseProperty',propertyName,increase);localStorage[propertyName]=this.ttsProperties[propertyName];};cvox.TtsBackground.prototype.isSpeaking=function(){goog.base(this,'isSpeaking');return this.lastEventType!='end';};cvox.TtsBackground.prototype.stop=function(){goog.base(this,'stop');this.cancelUtterance_(this.currentUtterance_);this.currentUtterance_=null;for(var i=0;i<this.utteranceQueue_.length;i++){this.cancelUtterance_(this.utteranceQueue_[i]);}
this.utteranceQueue_.length=0;(new PanelCommand(PanelCommandType.CLEAR_SPEECH)).send();chrome.tts.stop();};cvox.TtsBackground.prototype.addCapturingEventListener=function(listener){this.capturingTtsEventListeners_.push(listener);};cvox.TtsBackground.prototype.onError_=function(errorMessage){this.updateVoice_(this.currentVoice);};cvox.TtsBackground.prototype.preprocess=function(text,properties){properties=properties?properties:{};if(properties.math){text=this.preprocessMath_(text,properties.math);}
text=goog.base(this,'preprocess',text,properties);var pE=null;if(properties[cvox.AbstractTts.PUNCTUATION_ECHO]){for(var i=0;pE=this.punctuationEchoes_[i];i++){if(properties[cvox.AbstractTts.PUNCTUATION_ECHO]==pE.name){break;}}}else{pE=this.punctuationEchoes_[this.currentPunctuationEcho_];}
text=text.replace(pE.regexp,this.createPunctuationReplace_(pE.clear));if(properties.math||!properties['phoneticCharacters']||!this.pronouncePhonetically_(text)){this.clearTimeout_();}
if(!properties.math&&text.length==1&&this.mathmap){text=this.mathmap.store.lookupString(text.toLowerCase(),cvox.MathStore.createDynamicConstraint('default','short'))||text;}
text=text.replace(/\s+/g,' ').replace(/^\s+|\s+$/g,'');return text;};cvox.TtsBackground.prototype.cyclePunctuationEcho=function(){this.currentPunctuationEcho_=(this.currentPunctuationEcho_+1)%this.punctuationEchoes_.length;localStorage[cvox.AbstractTts.PUNCTUATION_ECHO]=this.currentPunctuationEcho_;return this.punctuationEchoes_[this.currentPunctuationEcho_].msg;};cvox.TtsBackground.prototype.preprocessMath_=function(text,math){if(!this.mathmap){return text;}
var result='';var dynamicCstr=cvox.MathStore.createDynamicConstraint(math['domain'],math['style']);result=this.mathmap.store.lookupString(text,dynamicCstr);if(result){return result;}
return text;};cvox.TtsBackground.prototype.getNumberAsDigits_=function(text){return text.replace(/\d+/g,function(num){if(num.length<=4){return num;}
return num.split('').join(' ');});};cvox.TtsBackground.prototype.createPunctuationReplace_=function(clear){return goog.bind(function(match){var retain=this.retainPunctuation_.indexOf(match)!=-1?match:' ';return clear?retain:' '+(new goog.i18n.MessageFormat(Msgs.getMsg(cvox.AbstractTts.CHARACTER_DICTIONARY[match]))).format({'COUNT':1})+retain+' ';},this);};cvox.TtsBackground.prototype.pronouncePhonetically_=function(text){if(!this.PHONETIC_MAP_){return false;}
text=text.toLowerCase();text=this.PHONETIC_MAP_[text];if(text){this.clearTimeout_();var self=this;this.timeoutId_=setTimeout(function(){self.speak(text,cvox.QueueMode.QUEUE);},cvox.TtsBackground.PHONETIC_DELAY_MS_);return true;}
return false;};cvox.TtsBackground.prototype.clearTimeout_=function(){if(goog.isDef(this.timeoutId_)){clearTimeout(this.timeoutId_);this.timeoutId_=undefined;}};cvox.TtsBackground.prototype.updateVoice_=function(voiceName){chrome.tts.getVoices(goog.bind(function(voices){var currentLocale=chrome.i18n.getMessage('@@ui_locale').replace('_','-');var newVoice=voices.find(function(v){return v.voiceName==voiceName;})||voices.find(function(v){return v.lang===currentLocale;})||voices.find(function(v){return currentLocale.startsWith(v.lang);})||voices[0];if(newVoice){this.currentVoice=newVoice.voiceName;this.startSpeakingNextItemInQueue_();}},this));};goog.provide('editing.TextEditHandler');goog.require('AutomationTreeWalker');goog.require('AutomationUtil');goog.require('Output');goog.require('Output.EventType');goog.require('cursors.Cursor');goog.require('cursors.Range');goog.require('cvox.ChromeVoxEditableTextBase');goog.scope(function(){var AutomationEvent=chrome.automation.AutomationEvent;var AutomationNode=chrome.automation.AutomationNode;var Cursor=cursors.Cursor;var Dir=AutomationUtil.Dir;var EventType=chrome.automation.EventType;var Range=cursors.Range;var RoleType=chrome.automation.RoleType;var Movement=cursors.Movement;var Unit=cursors.Unit;editing.TextEditHandler=function(node){this.node_=node;};editing.TextEditHandler.prototype={get node(){return this.node_;},onEvent:goog.abstractMethod,};function TextFieldTextEditHandler(node){editing.TextEditHandler.call(this,node);this.editableText_=new AutomationEditableText(node);}
TextFieldTextEditHandler.prototype={__proto__:editing.TextEditHandler.prototype,onEvent:function(evt){if(evt.type!==EventType.textChanged&&evt.type!==EventType.textSelectionChanged&&evt.type!==EventType.valueChanged&&evt.type!==EventType.focus)
return;if(!evt.target.state.focused||!evt.target.state.editable||evt.target!=this.node_)
return;this.editableText_.onUpdate();},};function AutomationEditableText(node){if(!node.state.editable)
throw Error('Node must have editable state set to true.');var start=node.textSelStart;var end=node.textSelEnd;cvox.ChromeVoxEditableTextBase.call(this,node.value,Math.min(start,end),Math.max(start,end),node.state.protected,cvox.ChromeVox.tts);this.multiline=node.state.multiline||false;this.node_=node;}
AutomationEditableText.prototype={__proto__:cvox.ChromeVoxEditableTextBase.prototype,onUpdate:function(){var newValue=this.node_.value;var textChangeEvent=new cvox.TextChangeEvent(newValue,this.node_.textSelStart,this.node_.textSelEnd,true);this.changed(textChangeEvent);this.outputBraille_();},getLineIndex:function(charIndex){if(!this.multiline)
return 0;var breaks=this.node_.lineStartOffsets||[];var index=0;while(index<breaks.length&&breaks[index]<=charIndex)
++index;return index;},getLineStart:function(lineIndex){if(!this.multiline||lineIndex==0)
return 0;var breaks=this.getLineBreaks_();return breaks[lineIndex-1]||this.node_.value.length;},getLineEnd:function(lineIndex){var breaks=this.getLineBreaks_();var value=this.node_.value;if(lineIndex>=breaks.length)
return value.length;var end=breaks[lineIndex];if(0<end&&value[end-1]=='\n')
return end-1;return end;},getLineBreaks_:function(){return this.node_.lineStartOffsets||[];},outputBraille_:function(){var isFirstLine=false;var output=new Output();var range;if(this.multiline){var lineIndex=this.getLineIndex(this.start);if(lineIndex==0){isFirstLine=true;output.formatForBraille('$name',this.node_);}
range=new Range(new Cursor(this.node_,this.getLineStart(lineIndex)),new Cursor(this.node_,this.getLineEnd(lineIndex)));}else{range=Range.fromNode(this.node_);}
output.withBraille(range,null,Output.EventType.NAVIGATE);if(isFirstLine)
output.formatForBraille('@tag_textarea');output.go();}};editing.TextEditHandler.createForNode=function(node){var rootFocusedEditable=null;var testNode=node;do{if(testNode.state.focused&&testNode.state.editable)
rootFocusedEditable=testNode;testNode=testNode.parent;}while(testNode);if(rootFocusedEditable)
return new TextFieldTextEditHandler(rootFocusedEditable);return null;};});goog.provide('BaseAutomationHandler');goog.scope(function(){var AutomationEvent=chrome.automation.AutomationEvent;var AutomationNode=chrome.automation.AutomationNode;var EventType=chrome.automation.EventType;BaseAutomationHandler=function(node){this.node_=node;this.listeners_={};};BaseAutomationHandler.prototype={addListener_:function(eventType,eventCallback){if(this.listeners_[eventType])
throw'Listener already added: '+eventType;var listener=this.makeListener_(eventCallback.bind(this));this.node_.addEventListener(eventType,listener,true);this.listeners_[eventType]=listener;},removeAllListeners:function(){for(var eventType in this.listeners_){this.node_.removeEventListener(eventType,this.listeners_[eventType],true);}},makeListener_:function(callback){return function(evt){if(this.willHandleEvent_(evt))
return;callback(evt);this.didHandleEvent_(evt);}.bind(this);},willHandleEvent_:function(evt){return false;},didHandleEvent_:function(evt){}};});goog.provide('AutomationObjectConstructorInstaller');AutomationObjectConstructorInstaller.init=function(node,callback){chrome.automation.AutomationNode=(node.constructor);node.addEventListener(chrome.automation.EventType.childrenChanged,function installAutomationEvent(e){chrome.automation.AutomationEvent=(e.constructor);node.removeEventListener(chrome.automation.EventType.childrenChanged,installAutomationEvent,true);callback();},true);};goog.provide('DesktopAutomationHandler');goog.require('AutomationObjectConstructorInstaller');goog.require('BaseAutomationHandler');goog.require('ChromeVoxState');goog.require('Stubs');goog.require('editing.TextEditHandler');goog.scope(function(){var AutomationEvent=chrome.automation.AutomationEvent;var AutomationNode=chrome.automation.AutomationNode;var Dir=constants.Dir;var EventType=chrome.automation.EventType;var RoleType=chrome.automation.RoleType;DesktopAutomationHandler=function(node){BaseAutomationHandler.call(this,node);this.textEditHandler_=null;this.lastValueChanged_=new Date(0);var e=EventType;this.addListener_(e.activedescendantchanged,this.onActiveDescendantChanged);this.addListener_(e.alert,this.onAlert);this.addListener_(e.ariaAttributeChanged,this.onAriaAttributeChanged);this.addListener_(e.autocorrectionOccured,this.onEventIfInRange);this.addListener_(e.checkedStateChanged,this.onCheckedStateChanged);this.addListener_(e.childrenChanged,this.onActiveDescendantChanged);this.addListener_(e.expandedChanged,this.onEventIfInRange);this.addListener_(e.focus,this.onFocus);this.addListener_(e.hover,this.onHover);this.addListener_(e.invalidStatusChanged,this.onEventIfInRange);this.addListener_(e.loadComplete,this.onLoadComplete);this.addListener_(e.menuEnd,this.onMenuEnd);this.addListener_(e.menuListItemSelected,this.onEventIfSelected);this.addListener_(e.menuStart,this.onMenuStart);this.addListener_(e.rowCollapsed,this.onEventIfInRange);this.addListener_(e.rowExpanded,this.onEventIfInRange);this.addListener_(e.scrollPositionChanged,this.onScrollPositionChanged);this.addListener_(e.selection,this.onSelection);this.addListener_(e.textChanged,this.onTextChanged);this.addListener_(e.textSelectionChanged,this.onTextSelectionChanged);this.addListener_(e.valueChanged,this.onValueChanged);AutomationObjectConstructorInstaller.init(node,function(){chrome.automation.getFocus((function(focus){if(ChromeVoxState.instance.mode!=ChromeVoxMode.FORCE_NEXT)
return;if(focus){this.onFocus(new chrome.automation.AutomationEvent(EventType.focus,focus,'page'));}}).bind(this));}.bind(this));};DesktopAutomationHandler.VMIN_VALUE_CHANGE_DELAY_MS=500;DesktopAutomationHandler.announceActions=false;DesktopAutomationHandler.prototype={__proto__:BaseAutomationHandler.prototype,willHandleEvent_:function(evt){return!cvox.ChromeVox.isActive;},onEventDefault:function(evt){var node=evt.target;if(!node)
return;var prevRange=ChromeVoxState.instance.currentRange;ChromeVoxState.instance.setCurrentRange(cursors.Range.fromNode(node));if(!this.shouldOutput_(evt))
return;if(prevRange&&evt.type=='focus'&&ChromeVoxState.instance.currentRange.equals(prevRange))
return;if(!DesktopAutomationHandler.announceActions&&evt.eventFrom=='action')
return;var output=new Output();output.withRichSpeech(ChromeVoxState.instance.currentRange,prevRange,evt.type);if(!this.textEditHandler_){output.withBraille(ChromeVoxState.instance.currentRange,prevRange,evt.type);}else{this.textEditHandler_.onEvent(evt);}
output.go();},onEventIfInRange:function(evt){if(!this.shouldOutput_(evt))
return;var prev=ChromeVoxState.instance.currentRange;if(prev.contentEquals(cursors.Range.fromNode(evt.target))||evt.target.state.focused){new Output().withRichSpeechAndBraille(cursors.Range.fromNode(evt.target),prev,Output.EventType.NAVIGATE).go();}},onEventIfSelected:function(evt){if(evt.target.state.selected)
this.onEventDefault(evt);},onEventWithFlushedOutput:function(evt){Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH);this.onEventDefault(evt);},onAriaAttributeChanged:function(evt){if(evt.target.state.editable)
return;this.onEventIfInRange(evt);},onHover:function(evt){if(ChromeVoxState.instance.currentRange&&evt.target==ChromeVoxState.instance.currentRange.start.node)
return;Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH);this.onEventDefault(evt);},onActiveDescendantChanged:function(evt){if(!evt.target.activeDescendant||!evt.target.state.focused)
return;this.onEventDefault(new chrome.automation.AutomationEvent(EventType.focus,evt.target.activeDescendant,evt.eventFrom));},onAlert:function(evt){var node=evt.target;if(!node||!this.shouldOutput_(evt))
return;var range=cursors.Range.fromNode(node);new Output().withSpeechAndBraille(range,null,evt.type).go();},onCheckedStateChanged:function(evt){if(!AutomationPredicate.checkable(evt.target))
return;this.onEventIfInRange(new chrome.automation.AutomationEvent(EventType.checkedStateChanged,evt.target,evt.eventFrom));},onFocus:function(evt){this.textEditHandler_=null;var node=evt.target;if(node.role==RoleType.embeddedObject)
return;this.createTextEditHandlerIfNeeded_(evt.target);if(evt.eventFrom=='')
Output.forceModeForNextSpeechUtterance(cvox.QueueMode.CATEGORY_FLUSH);if(!node.root)
return;var root=AutomationUtil.getTopLevelRoot(node.root);var prevRange=ChromeVoxState.instance.currentRange;var prevNode=prevRange?prevRange.start.node:null;if(prevNode){var prevRoot=AutomationUtil.getTopLevelRoot(prevNode);if(prevRoot&&prevRoot!==root)
ChromeVoxState.instance.focusRecoveryMap.set(prevRoot,prevRange);}
var savedRange=ChromeVoxState.instance.focusRecoveryMap.get(root);ChromeVoxState.instance.focusRecoveryMap.delete(root);if(savedRange){ChromeVoxState.instance.navigateToRange(savedRange,false);return;}
this.onEventDefault(new chrome.automation.AutomationEvent(EventType.focus,node,evt.eventFrom));},onLoadComplete:function(evt){chrome.automation.getFocus(function(focus){if(!focus||!AutomationUtil.isDescendantOf(focus,evt.target))
return;this.createTextEditHandlerIfNeeded_(focus);if(ChromeVoxState.instance.currentRange&&ChromeVoxState.instance.currentRange.start.node.root==focus.root)
return;var o=new Output();if(focus.role==RoleType.rootWebArea){var url=focus.docUrl;url=url.substring(0,url.indexOf('#'))||url;var pos=cvox.ChromeVox.position[url];if(pos){focus=AutomationUtil.hitTest(focus.root,pos)||focus;if(focus!=focus.root)
o.format('$name',focus.root);}}
ChromeVoxState.instance.setCurrentRange(cursors.Range.fromNode(focus));if(!this.shouldOutput_(evt))
return;Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH);o.withRichSpeechAndBraille(ChromeVoxState.instance.currentRange,null,evt.type).go();}.bind(this));},onTextChanged:function(evt){if(evt.target.state.editable)
this.onEditableChanged_(evt);},onTextSelectionChanged:function(evt){if(evt.target.state.editable)
this.onEditableChanged_(evt);},onEditableChanged_:function(evt){var topRoot=AutomationUtil.getTopLevelRoot(evt.target);if(!evt.target.state.focused||(topRoot&&topRoot.parent&&!topRoot.parent.state.focused))
return;if(!ChromeVoxState.instance.currentRange){this.onEventDefault(evt);ChromeVoxState.instance.setCurrentRange(cursors.Range.fromNode(evt.target));}
this.createTextEditHandlerIfNeeded_(evt.target);var anchorObject=evt.target.root.anchorObject;var anchorOffset=evt.target.root.anchorOffset;var focusObject=evt.target.root.focusObject;var focusOffset=evt.target.root.focusOffset;if(anchorObject&&focusObject){var selectedRange=new cursors.Range(new cursors.WrappingCursor(anchorObject,anchorOffset),new cursors.WrappingCursor(focusObject,focusOffset));ChromeVoxState.instance.setCurrentRange(selectedRange);}
if(this.textEditHandler_)
this.textEditHandler_.onEvent(evt);},onValueChanged:function(evt){if(evt.target.state.editable){this.onEditableChanged_(evt);return;}
if(!this.shouldOutput_(evt))
return;var t=evt.target;if(t.state.focused||t.root.role==RoleType.desktop||AutomationUtil.isDescendantOf(ChromeVoxState.instance.currentRange.start.node,t)){if(new Date()-this.lastValueChanged_<=DesktopAutomationHandler.VMIN_VALUE_CHANGE_DELAY_MS)
return;this.lastValueChanged_=new Date();var output=new Output();if(t.root.role==RoleType.desktop)
output.withQueueMode(cvox.QueueMode.FLUSH);output.format('$value',evt.target).go();}},onScrollPositionChanged:function(evt){var currentRange=ChromeVoxState.instance.currentRange;if(currentRange&&currentRange.isValid()&&this.shouldOutput_(evt))
new Output().withLocation(currentRange,null,evt.type).go();},onSelection:function(evt){chrome.automation.getFocus(function(focus){if(focus.role==RoleType.webView&&evt.target.role==RoleType.tab){ChromeVoxState.instance.setCurrentRange(cursors.Range.fromNode(focus.firstChild));return;}
var override=evt.target.role==RoleType.menuItem||(evt.target.root==focus.root&&focus.root.role==RoleType.desktop);Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH);if(override||AutomationUtil.isDescendantOf(evt.target,focus))
this.onEventDefault(evt);}.bind(this));},onMenuStart:function(evt){ChromeVoxState.instance.markCurrentRange();this.onEventDefault(evt);},onMenuEnd:function(evt){this.onEventDefault(evt);chrome.automation.getFocus(function(focus){if(focus){this.onFocus(new chrome.automation.AutomationEvent(EventType.focus,focus,'page'));}}.bind(this));},createTextEditHandlerIfNeeded_:function(node){if(!this.textEditHandler_||this.textEditHandler_.node!==node){this.textEditHandler_=editing.TextEditHandler.createForNode(node);}},shouldOutput_:function(evt){var mode=ChromeVoxState.instance.mode;return evt.target.root.role==RoleType.desktop||(mode==ChromeVoxMode.NEXT||mode==ChromeVoxMode.FORCE_NEXT||mode==ChromeVoxMode.CLASSIC_COMPAT);}};DesktopAutomationHandler.init_=function(){chrome.automation.getDesktop(function(desktop){ChromeVoxState.desktopAutomationHandler=new DesktopAutomationHandler(desktop);});};DesktopAutomationHandler.init_();});goog.provide('TabsAutomationHandler');goog.require('DesktopAutomationHandler');goog.scope(function(){var EventType=chrome.automation.EventType;var RoleType=chrome.automation.RoleType;TabsAutomationHandler=function(tabRoot){DesktopAutomationHandler.call(this,tabRoot);if(tabRoot.role!=RoleType.rootWebArea)
throw new Error('Expected rootWebArea node but got '+tabRoot.role);if(tabRoot.state.focused){this.onLoadComplete(new chrome.automation.AutomationEvent(EventType.loadComplete,tabRoot,'page'));}};TabsAutomationHandler.prototype={__proto__:DesktopAutomationHandler.prototype,didHandleEvent_:function(evt){evt.stopPropagation();},onLoadComplete:function(evt){var focused=evt.target.find({state:{focused:true}})||evt.target;this.onFocus(new chrome.automation.AutomationEvent(EventType.focus,focused,evt.eventFrom));}};});goog.provide('cvox.TabsApiHandler');goog.require('Stubs');goog.require('TabsAutomationHandler');goog.require('cvox.AbstractEarcons');goog.require('cvox.AbstractTts');goog.require('cvox.BrailleInterface');goog.require('cvox.ChromeVox');goog.require('cvox.NavBraille');cvox.TabsApiHandler=function(){this.msg_=Msgs.getMsg.bind(Msgs);this.lastActiveTabLoaded_=false;chrome.tabs.onCreated.addListener(this.onCreated.bind(this));chrome.tabs.onRemoved.addListener(this.onRemoved.bind(this));chrome.tabs.onActivated.addListener(this.onActivated.bind(this));chrome.tabs.onUpdated.addListener(this.onUpdated.bind(this));chrome.windows.onFocusChanged.addListener(this.onFocusChanged.bind(this));this.pageLoadIntervalID_=null;this.pageLoadTabID_=null;};cvox.TabsApiHandler.shouldOutputSpeechAndBraille=true;cvox.TabsApiHandler.prototype={onCreated:function(tab){if(!cvox.ChromeVox.isActive){return;}
if(cvox.TabsApiHandler.shouldOutputSpeechAndBraille){cvox.ChromeVox.tts.speak(this.msg_('chrome_tab_created'),cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(this.msg_('chrome_tab_created')));}
cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_OPEN);if(tab){this.refreshAutomationHandler_(tab.id);}},onRemoved:function(tab){if(!cvox.ChromeVox.isActive){return;}
cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_CLOSE);chrome.tabs.query({active:true},function(tabs){if(tabs.length==0&&this.isPlayingPageLoadingSound_()){cvox.ChromeVox.earcons.cancelEarcon(cvox.Earcon.PAGE_START_LOADING);this.cancelPageLoadTimer_();}}.bind(this));},onActivated:function(activeInfo){if(!cvox.ChromeVox.isActive){return;}
this.updateLoadingSoundsWhenTabFocusChanges_(activeInfo.tabId);chrome.tabs.get(activeInfo.tabId,function(tab){if(cvox.TabsApiHandler.shouldOutputSpeechAndBraille){var title=tab.title?tab.title:tab.url;cvox.ChromeVox.tts.speak(this.msg_('chrome_tab_selected',[title]),cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(this.msg_('chrome_tab_selected',[title])));}
cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_SELECT);this.refreshAutomationHandler_(tab.id);}.bind(this));},updateLoadingSoundsWhenTabFocusChanges_:function(tabId){chrome.tabs.get(tabId,function(tab){this.lastActiveTabLoaded_=tab.status=='complete';if(tab.status=='loading'&&!this.isPlayingPageLoadingSound_()){cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.PAGE_START_LOADING);this.startPageLoadTimer_(tabId);}else{cvox.ChromeVox.earcons.cancelEarcon(cvox.Earcon.PAGE_START_LOADING);this.cancelPageLoadTimer_();}}.bind(this));},onUpdated:function(tabId,selectInfo){if(!cvox.ChromeVox.isActive){return;}
chrome.tabs.get(tabId,function(tab){if(!tab.active){return;}
if(tab.status=='loading'){this.lastActiveTabLoaded_=false;if(!this.isPlayingPageLoadingSound_()){cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.PAGE_START_LOADING);this.startPageLoadTimer_(tabId);}}else if(!this.lastActiveTabLoaded_){this.lastActiveTabLoaded_=true;cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.PAGE_FINISH_LOADING);this.cancelPageLoadTimer_();}
this.refreshAutomationHandler_(tabId);}.bind(this));},onFocusChanged:function(windowId){if(!cvox.ChromeVox.isActive){return;}
if(windowId==chrome.windows.WINDOW_ID_NONE){return;}
chrome.windows.get(windowId,function(window){chrome.tabs.query({active:true,windowId:windowId},function(tabs){if(tabs[0])
this.updateLoadingSoundsWhenTabFocusChanges_(tabs[0].id);var tab=tabs[0]||{};if(cvox.TabsApiHandler.shouldOutputSpeechAndBraille){var msgId=window.incognito?'chrome_incognito_window_selected':'chrome_normal_window_selected';var title=tab.title?tab.title:tab.url;cvox.ChromeVox.tts.speak(this.msg_(msgId,[title]),cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOUNCEMENT);cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(this.msg_(msgId,[title])));}
cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.OBJECT_SELECT);this.refreshAutomationHandler_(tab.id);}.bind(this));}.bind(this));},refreshAutomationHandler_:function(tabId){if(!cvox.ChromeVox.isMac||ChromeVoxState.instance.mode==ChromeVoxMode.CLASSIC)
return;chrome.automation.getTree(tabId,function(node){if(this.handler_)
this.handler_.removeAllListeners();this.handler_=new TabsAutomationHandler(node);}.bind(this));},startPageLoadTimer_:function(tabId){if(this.pageLoadIntervalID_){if(tabId==this.pageLoadTabID_)
return;this.cancelPageLoadTimer_();}
this.pageLoadTabID_=tabId;this.pageLoadIntervalID_=window.setInterval(function(){if(this.pageLoadTabID_)
this.onUpdated(this.pageLoadTabID_,{});}.bind(this),1000);},cancelPageLoadTimer_:function(){if(this.pageLoadIntervalID_){window.clearInterval(this.pageLoadIntervalID_);this.pageLoadIntervalID_=null;this.pageLoadTabID_=null;}},isPlayingPageLoadingSound_:function(){return this.pageLoadIntervalID_!=null;}};goog.provide('cvox.ChromeVoxBackground');goog.require('ChromeVoxState');goog.require('Msgs');goog.require('cvox.AbstractEarcons');goog.require('cvox.BrailleBackground');goog.require('cvox.BrailleCaptionsBackground');goog.require('cvox.ChromeVox');goog.require('cvox.ChromeVoxEditableTextBase');goog.require('cvox.ChromeVoxPrefs');goog.require('cvox.ClassicEarcons');goog.require('cvox.CompositeTts');goog.require('cvox.ConsoleTts');goog.require('cvox.ExtensionBridge');goog.require('cvox.InjectedScriptLoader');goog.require('cvox.NavBraille');goog.require('cvox.PlatformFilter');goog.require('cvox.PlatformUtil');goog.require('cvox.QueueMode');goog.require('cvox.TabsApiHandler');goog.require('cvox.TtsBackground');cvox.ChromeVoxBackground=function(){};cvox.ChromeVoxBackground.setPref=function(pref,value,announce){if(pref=='active'&&value!=cvox.ChromeVox.isActive){if(cvox.ChromeVox.isActive){cvox.ChromeVox.tts.speak(Msgs.getMsg('chromevox_inactive'),cvox.QueueMode.FLUSH);chrome.accessibilityPrivate.setNativeAccessibilityEnabled(true);}else{chrome.accessibilityPrivate.setNativeAccessibilityEnabled(false);}}else if(pref=='earcons'){cvox.AbstractEarcons.enabled=!!value;}else if(pref=='sticky'&&announce){if(value){cvox.ChromeVox.tts.speak(Msgs.getMsg('sticky_mode_enabled'),cvox.QueueMode.FLUSH);}else{cvox.ChromeVox.tts.speak(Msgs.getMsg('sticky_mode_disabled'),cvox.QueueMode.FLUSH);}}else if(pref=='typingEcho'&&announce){var announceStr='';switch(value){case cvox.TypingEcho.CHARACTER:announceStr=Msgs.getMsg('character_echo');break;case cvox.TypingEcho.WORD:announceStr=Msgs.getMsg('word_echo');break;case cvox.TypingEcho.CHARACTER_AND_WORD:announceStr=Msgs.getMsg('character_and_word_echo');break;case cvox.TypingEcho.NONE:announceStr=Msgs.getMsg('none_echo');break;default:break;}
if(announceStr){cvox.ChromeVox.tts.speak(announceStr,cvox.QueueMode.QUEUE);}}else if(pref=='brailleCaptions'){cvox.BrailleCaptionsBackground.setActive(!!value);}else if(pref=='position'){cvox.ChromeVox.position=(JSON.parse((value)));}
window['prefs'].setPref(pref,value);cvox.ChromeVoxBackground.readPrefs();};cvox.ChromeVoxBackground.readPrefs=function(){if(!window['prefs']){return;}
var prefs=window['prefs'].getPrefs();cvox.ChromeVoxEditableTextBase.useIBeamCursor=(prefs['useIBeamCursor']=='true');cvox.ChromeVox.isActive=(prefs['active']=='true'||cvox.ChromeVox.isChromeOS);cvox.ChromeVox.isStickyPrefOn=(prefs['sticky']=='true');};cvox.ChromeVoxBackground.prototype.init=function(){if(cvox.ChromeVox.isChromeOS&&chrome.i18n.getMessage('@@extension_id')!='mndnfokpggljbaajbnioimlmbfngpief'){return;}
this.prefs=new cvox.ChromeVoxPrefs();cvox.ChromeVoxBackground.readPrefs();var consoleTts=cvox.ConsoleTts.getInstance();consoleTts.setEnabled(true);this.backgroundTts_=new cvox.TtsBackground();this.tts=new cvox.CompositeTts().add(this.backgroundTts_).add(consoleTts);this.addBridgeListener();this.backgroundBraille_=new cvox.BrailleBackground();this.tabsApiHandler_=new cvox.TabsApiHandler();cvox.ChromeVox.tts=this.tts;cvox.ChromeVox.braille=this.backgroundBraille_;if(!cvox.ChromeVox.earcons)
cvox.ChromeVox.earcons=new cvox.ClassicEarcons();if(cvox.ChromeVox.isChromeOS){chrome.accessibilityPrivate.onIntroduceChromeVox.addListener(this.onIntroduceChromeVox);}
chrome.extension.onMessage.addListener(function(request,sender,callback){if(request['srcFile']){var srcFile=request['srcFile'];cvox.InjectedScriptLoader.fetchCode([srcFile],function(code){callback({'code':code[srcFile]});});}
return true;});var self=this;chrome.windows.getAll({'populate':true},function(windows){for(var i=0;i<windows.length;i++){var tabs=windows[i].tabs;self.injectChromeVoxIntoTabs(tabs);}});if(localStorage['active']=='false'){this.tts.speak(Msgs.getMsg('chromevox_inactive'),cvox.QueueMode.QUEUE);}else if(cvox.PlatformUtil.matchesPlatform(cvox.PlatformFilter.WML)){this.tts.speak(Msgs.getMsg('chromevox_intro'),cvox.QueueMode.QUEUE);cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(Msgs.getMsg('intro_brl')));}};cvox.ChromeVoxBackground.prototype.injectChromeVoxIntoTabs=function(tabs){var listOfFiles;if(COMPILED){listOfFiles=['chromeVoxChromePageScript.js'];}else{listOfFiles=['closure/closure_preinit.js','closure/base.js','deps.js','chromevox/injected/loader.js'];}
var stageTwo=function(code){for(var i=0,tab;tab=tabs[i];i++){window.console.log('Injecting into '+tab.id,tab);var sawError=false;var executeScript=goog.bind(function(code){chrome.tabs.executeScript(tab.id,{'code':code,'allFrames':true},goog.bind(function(){if(!chrome.extension.lastError){return;}
if(sawError){return;}
sawError=true;console.error('Could not inject into tab',tab);this.tts.speak('Error starting ChromeVox for '+
tab.title+', '+tab.url,cvox.QueueMode.QUEUE);},this));},this);executeScript('try { window.disableChromeVox(); } catch(e) { }\n'+'window.INJECTED_AFTER_LOAD = true;\n'+'window.CLOSURE_NO_DEPS = true\n');listOfFiles.forEach(function(file){executeScript(code[file]);});}};cvox.InjectedScriptLoader.fetchCode(listOfFiles,stageTwo);};cvox.ChromeVoxBackground.prototype.onTtsMessage=function(msg){if(msg['action']=='speak'){this.tts.speak(msg['text'],msg['queueMode'],msg['properties']);}else if(msg['action']=='stop'){this.tts.stop();}else if(msg['action']=='increaseOrDecrease'){this.tts.increaseOrDecreaseProperty(msg['property'],msg['increase']);var property=msg['property'];var engine=this.backgroundTts_;var valueAsPercent=Math.round(this.backgroundTts_.propertyToPercentage(property)*100);var announcement;switch(msg['property']){case cvox.AbstractTts.RATE:announcement=Msgs.getMsg('announce_rate',[valueAsPercent]);break;case cvox.AbstractTts.PITCH:announcement=Msgs.getMsg('announce_pitch',[valueAsPercent]);break;case cvox.AbstractTts.VOLUME:announcement=Msgs.getMsg('announce_volume',[valueAsPercent]);break;}
if(announcement){this.tts.speak(announcement,cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOTATION);}}else if(msg['action']=='cyclePunctuationEcho'){this.tts.speak(Msgs.getMsg(this.backgroundTts_.cyclePunctuationEcho()),cvox.QueueMode.FLUSH);}};cvox.ChromeVoxBackground.prototype.onEarconMessage=function(msg){if(msg.action=='play'){cvox.ChromeVox.earcons.playEarcon(msg['earcon']);}};cvox.ChromeVoxBackground.prototype.addBridgeListener=function(){cvox.ExtensionBridge.addMessageListener(goog.bind(function(msg,port){var target=msg['target'];var action=msg['action'];switch(target){case'OpenTab':var destination={url:msg['url']};chrome.tabs.create(destination);break;case'KbExplorer':var explorerPage={url:'chromevox/background/kbexplorer.html'};chrome.tabs.create(explorerPage);break;case'HelpDocs':var helpPage={url:'http://chromevox.com/tutorial/index.html'};chrome.tabs.create(helpPage);break;case'Options':if(action=='open'){var optionsPage={url:'chromevox/background/options.html'};chrome.tabs.create(optionsPage);}
break;case'Data':if(action=='getHistory'){var results={};chrome.history.search({text:'',maxResults:25},function(items){items.forEach(function(item){if(item.url){results[item.url]=true;}});port.postMessage({'history':results});});}
break;case'Prefs':if(action=='getPrefs'){this.prefs.sendPrefsToPort(port);}else if(action=='setPref'){var pref=(msg['pref']);var announce=!!msg['announce'];cvox.ChromeVoxBackground.setPref(pref,msg['value'],announce);}
break;case'Math':if(msg['action']=='getDomains'){port.postMessage({'message':'DOMAINS_STYLES','domains':this.backgroundTts_.mathmap.allDomains,'styles':this.backgroundTts_.mathmap.allStyles});}
break;case'TTS':if(msg['startCallbackId']!=undefined){msg['properties']['startCallback']=function(opt_cleanupOnly){port.postMessage({'message':'TTS_CALLBACK','cleanupOnly':opt_cleanupOnly,'id':msg['startCallbackId']});};}
if(msg['endCallbackId']!=undefined){msg['properties']['endCallback']=function(opt_cleanupOnly){port.postMessage({'message':'TTS_CALLBACK','cleanupOnly':opt_cleanupOnly,'id':msg['endCallbackId']});};}
try{this.onTtsMessage(msg);}catch(err){console.log(err);}
break;case'EARCON':this.onEarconMessage(msg);break;case'BRAILLE':try{this.backgroundBraille_.onBrailleMessage(msg);}catch(err){console.log(err);}
break;}},this));};cvox.ChromeVoxBackground.prototype.isIncognito_=function(){var incognito=false;chrome.tabs.getCurrent(function(tab){incognito=tab?tab.incognito:true;});return incognito;};cvox.ChromeVoxBackground.prototype.onIntroduceChromeVox=function(){cvox.ChromeVox.tts.speak(Msgs.getMsg('chromevox_intro'),cvox.QueueMode.QUEUE,{doNotInterrupt:true});cvox.ChromeVox.braille.write(cvox.NavBraille.fromText(Msgs.getMsg('intro_brl')));};cvox.ChromeVoxBackground.prototype.getCurrentVoice=function(){return this.backgroundTts_.currentVoice;};(function(){var background=new cvox.ChromeVoxBackground();background.init();window['speak']=goog.bind(background.tts.speak,background.tts);ChromeVoxState.backgroundTts=background.backgroundTts_;window['prefs']=background.prefs;window['braille_translator_manager']=background.backgroundBraille_.getTranslatorManager();window['getCurrentVoice']=background.getCurrentVoice.bind(background);cvox.ChromeVox.injectChromeVoxIntoTabs=background.injectChromeVoxIntoTabs.bind(background);})();goog.provide('CommandHandler');goog.require('ChromeVoxState');goog.require('Output');goog.require('cvox.ChromeVoxBackground');goog.scope(function(){var AutomationNode=chrome.automation.AutomationNode;var Dir=constants.Dir;var EventType=chrome.automation.EventType;var RoleType=chrome.automation.RoleType;CommandHandler.onCommand=function(command){chrome.automation.getFocus(function(focusedNode){var cur=ChromeVoxState.instance.currentRange;if(cur&&!cur.isValid()){ChromeVoxState.instance.setCurrentRange(cursors.Range.fromNode(focusedNode));}
if(!focusedNode)
ChromeVoxState.instance.setCurrentRange(null);});switch(command){case'speakTimeAndDate':chrome.automation.getDesktop(function(d){var allTime=d.findAll({role:RoleType.time});allTime.filter(function(t){return t.root.role==RoleType.desktop;});var timeString='';allTime.forEach(function(t){if(t.name)timeString=t.name;});if(timeString){cvox.ChromeVox.tts.speak(timeString,cvox.QueueMode.FLUSH);}else{var output=new Output();var dateTime=new Date();output.withString(dateTime.toLocaleTimeString()+', '+
dateTime.toLocaleDateString()).go();}});return false;case'showOptionsPage':chrome.runtime.openOptionsPage();break;case'toggleChromeVox':if(cvox.ChromeVox.isChromeOS)
return false;cvox.ChromeVox.isActive=!cvox.ChromeVox.isActive;if(!cvox.ChromeVox.isActive){var msg=Msgs.getMsg('chromevox_inactive');cvox.ChromeVox.tts.speak(msg,cvox.QueueMode.FLUSH);return false;}
break;case'toggleStickyMode':cvox.ChromeVoxBackground.setPref('sticky',!cvox.ChromeVox.isStickyPrefOn,true);if(cvox.ChromeVox.isStickyPrefOn)
chrome.accessibilityPrivate.setKeyboardListener(true,true);else
chrome.accessibilityPrivate.setKeyboardListener(true,false);return false;case'passThroughMode':cvox.ChromeVox.passThroughMode=true;cvox.ChromeVox.tts.speak(Msgs.getMsg('pass_through_key'),cvox.QueueMode.QUEUE);return true;case'showKbExplorerPage':var explorerPage={url:'chromevox/background/kbexplorer.html'};chrome.tabs.create(explorerPage);break;case'decreaseTtsRate':CommandHandler.increaseOrDecreaseSpeechProperty_(cvox.AbstractTts.RATE,false);return false;case'increaseTtsRate':CommandHandler.increaseOrDecreaseSpeechProperty_(cvox.AbstractTts.RATE,true);return false;case'decreaseTtsPitch':CommandHandler.increaseOrDecreaseSpeechProperty_(cvox.AbstractTts.PITCH,false);return false;case'increaseTtsPitch':CommandHandler.increaseOrDecreaseSpeechProperty_(cvox.AbstractTts.PITCH,true);return false;case'decreaseTtsVolume':CommandHandler.increaseOrDecreaseSpeechProperty_(cvox.AbstractTts.VOLUME,false);return false;case'increaseTtsVolume':CommandHandler.increaseOrDecreaseSpeechProperty_(cvox.AbstractTts.VOLUME,true);return false;case'stopSpeech':cvox.ChromeVox.tts.stop();ChromeVoxState.isReadingContinuously=false;return false;case'toggleEarcons':cvox.AbstractEarcons.enabled=!cvox.AbstractEarcons.enabled;var announce=cvox.AbstractEarcons.enabled?Msgs.getMsg('earcons_on'):Msgs.getMsg('earcons_off');cvox.ChromeVox.tts.speak(announce,cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOTATION);return false;case'cycleTypingEcho':cvox.ChromeVox.typingEcho=cvox.TypingEcho.cycle(cvox.ChromeVox.typingEcho);var announce='';switch(cvox.ChromeVox.typingEcho){case cvox.TypingEcho.CHARACTER:announce=Msgs.getMsg('character_echo');break;case cvox.TypingEcho.WORD:announce=Msgs.getMsg('word_echo');break;case cvox.TypingEcho.CHARACTER_AND_WORD:announce=Msgs.getMsg('character_and_word_echo');break;case cvox.TypingEcho.NONE:announce=Msgs.getMsg('none_echo');break;}
cvox.ChromeVox.tts.speak(announce,cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOTATION);return false;case'cyclePunctuationEcho':cvox.ChromeVox.tts.speak(Msgs.getMsg(ChromeVoxState.backgroundTts.cyclePunctuationEcho()),cvox.QueueMode.FLUSH);return false;case'reportIssue':var url=Background.ISSUE_URL;var description={};description['Mode']=ChromeVoxState.instance.mode;description['Version']=chrome.app.getDetails().version;description['Reproduction Steps']='%0a1.%0a2.%0a3.';for(var key in description)
url+=key+':%20'+description[key]+'%0a';chrome.tabs.create({url:url});return false;case'toggleBrailleCaptions':cvox.BrailleCaptionsBackground.setActive(!cvox.BrailleCaptionsBackground.isEnabled());return false;case'toggleChromeVoxVersion':if(!ChromeVoxState.instance.toggleNext())
return false;if(ChromeVoxState.instance.currentRange){ChromeVoxState.instance.navigateToRange(ChromeVoxState.instance.currentRange);}
break;case'showNextUpdatePage':(new PanelCommand(PanelCommandType.TUTORIAL)).send();return false;default:break;}
if(!ChromeVoxState.instance.currentRange_)
return true;if(ChromeVoxState.instance.mode==ChromeVoxMode.CLASSIC||ChromeVoxState.instance.mode==ChromeVoxMode.NEXT_COMPAT)
return true;var current=ChromeVoxState.instance.currentRange_;var dir=Dir.FORWARD;var pred=null;var predErrorMsg=undefined;var rootPred=AutomationPredicate.root;var speechProps={};var skipSync=false;switch(command){case'nextCharacter':speechProps['phoneticCharacters']=true;current=current.move(cursors.Unit.CHARACTER,Dir.FORWARD);break;case'previousCharacter':speechProps['phoneticCharacters']=true;current=current.move(cursors.Unit.CHARACTER,Dir.BACKWARD);break;case'nextWord':current=current.move(cursors.Unit.WORD,Dir.FORWARD);break;case'previousWord':current=current.move(cursors.Unit.WORD,Dir.BACKWARD);break;case'forward':case'nextLine':current=current.move(cursors.Unit.LINE,Dir.FORWARD);break;case'backward':case'previousLine':current=current.move(cursors.Unit.LINE,Dir.BACKWARD);break;case'nextButton':dir=Dir.FORWARD;pred=AutomationPredicate.button;predErrorMsg='no_next_button';break;case'previousButton':dir=Dir.BACKWARD;pred=AutomationPredicate.button;predErrorMsg='no_previous_button';break;case'nextCheckbox':dir=Dir.FORWARD;pred=AutomationPredicate.checkBox;predErrorMsg='no_next_checkbox';break;case'previousCheckbox':dir=Dir.BACKWARD;pred=AutomationPredicate.checkBox;predErrorMsg='no_previous_checkbox';break;case'nextComboBox':dir=Dir.FORWARD;pred=AutomationPredicate.comboBox;predErrorMsg='no_next_combo_box';break;case'previousComboBox':dir=Dir.BACKWARD;pred=AutomationPredicate.comboBox;predErrorMsg='no_previous_combo_box';break;case'nextEditText':dir=Dir.FORWARD;pred=AutomationPredicate.editText;predErrorMsg='no_next_edit_text';break;case'previousEditText':dir=Dir.BACKWARD;pred=AutomationPredicate.editText;predErrorMsg='no_previous_edit_text';break;case'nextFormField':dir=Dir.FORWARD;pred=AutomationPredicate.formField;predErrorMsg='no_next_form_field';break;case'previousFormField':dir=Dir.BACKWARD;pred=AutomationPredicate.formField;predErrorMsg='no_previous_form_field';break;case'nextHeading':dir=Dir.FORWARD;pred=AutomationPredicate.heading;predErrorMsg='no_next_heading';break;case'nextHeading1':dir=Dir.FORWARD;pred=AutomationPredicate.makeHeadingPredicate(1);predErrorMsg='no_next_heading_1';break;case'nextHeading2':dir=Dir.FORWARD;pred=AutomationPredicate.makeHeadingPredicate(2);predErrorMsg='no_next_heading_2';break;case'nextHeading3':dir=Dir.FORWARD;pred=AutomationPredicate.makeHeadingPredicate(3);predErrorMsg='no_next_heading_3';break;case'nextHeading4':dir=Dir.FORWARD;pred=AutomationPredicate.makeHeadingPredicate(4);predErrorMsg='no_next_heading_4';break;case'nextHeading5':dir=Dir.FORWARD;pred=AutomationPredicate.makeHeadingPredicate(5);predErrorMsg='no_next_heading_5';break;case'nextHeading6':dir=Dir.FORWARD;pred=AutomationPredicate.makeHeadingPredicate(6);predErrorMsg='no_next_heading_6';break;case'previousHeading':dir=Dir.BACKWARD;pred=AutomationPredicate.heading;predErrorMsg='no_previous_heading';break;case'previousHeading1':dir=Dir.BACKWARD;pred=AutomationPredicate.makeHeadingPredicate(1);predErrorMsg='no_previous_heading_1';break;case'previousHeading2':dir=Dir.BACKWARD;pred=AutomationPredicate.makeHeadingPredicate(2);predErrorMsg='no_previous_heading_2';break;case'previousHeading3':dir=Dir.BACKWARD;pred=AutomationPredicate.makeHeadingPredicate(3);predErrorMsg='no_previous_heading_3';break;case'previousHeading4':dir=Dir.BACKWARD;pred=AutomationPredicate.makeHeadingPredicate(4);predErrorMsg='no_previous_heading_4';break;case'previousHeading5':dir=Dir.BACKWARD;pred=AutomationPredicate.makeHeadingPredicate(5);predErrorMsg='no_previous_heading_5';break;case'previousHeading6':dir=Dir.BACKWARD;pred=AutomationPredicate.makeHeadingPredicate(6);predErrorMsg='no_previous_heading_6';break;case'nextLink':dir=Dir.FORWARD;pred=AutomationPredicate.link;predErrorMsg='no_next_link';break;case'previousLink':dir=Dir.BACKWARD;pred=AutomationPredicate.link;predErrorMsg='no_previous_link';break;case'nextTable':dir=Dir.FORWARD;pred=AutomationPredicate.table;predErrorMsg='no_next_table';break;case'previousTable':dir=Dir.BACKWARD;pred=AutomationPredicate.table;predErrorMsg='no_previous_table';break;case'nextVisitedLink':dir=Dir.FORWARD;pred=AutomationPredicate.visitedLink;predErrorMsg='no_next_visited_link';break;case'previousVisitedLink':dir=Dir.BACKWARD;pred=AutomationPredicate.visitedLink;predErrorMsg='no_previous_visited_link';break;case'nextLandmark':dir=Dir.FORWARD;pred=AutomationPredicate.landmark;predErrorMsg='no_next_landmark';break;case'previousLandmark':dir=Dir.BACKWARD;pred=AutomationPredicate.landmark;predErrorMsg='no_previous_landmark';break;case'right':case'nextObject':current=current.move(cursors.Unit.NODE,Dir.FORWARD);break;case'left':case'previousObject':current=current.move(cursors.Unit.NODE,Dir.BACKWARD);break;case'previousGroup':skipSync=true;dir=Dir.BACKWARD;pred=AutomationPredicate.group;break;case'nextGroup':skipSync=true;dir=Dir.FORWARD;pred=AutomationPredicate.group;break;case'jumpToTop':var node=AutomationUtil.findNodePost(current.start.node.root,Dir.FORWARD,AutomationPredicate.leaf);if(node)
current=cursors.Range.fromNode(node);break;case'jumpToBottom':var node=AutomationUtil.findNodePost(current.start.node.root,Dir.BACKWARD,AutomationPredicate.leaf);if(node)
current=cursors.Range.fromNode(node);break;case'forceClickOnCurrentItem':if(ChromeVoxState.instance.currentRange_){var actionNode=ChromeVoxState.instance.currentRange_.start.node;if(actionNode.role==RoleType.inlineTextBox)
actionNode=actionNode.parent;actionNode.doDefault();}
return false;case'readFromHere':ChromeVoxState.isReadingContinuously=true;var continueReading=function(){if(!ChromeVoxState.isReadingContinuously||!ChromeVoxState.instance.currentRange_)
return;var prevRange=ChromeVoxState.instance.currentRange_;var newRange=ChromeVoxState.instance.currentRange_.move(cursors.Unit.NODE,Dir.FORWARD);var maybeDoc=newRange.start.node;if(maybeDoc.role==RoleType.rootWebArea&&maybeDoc.parent.root.role==RoleType.desktop){ChromeVoxState.isReadingContinuously=false;return;}
ChromeVoxState.instance.setCurrentRange(newRange);new Output().withRichSpeechAndBraille(ChromeVoxState.instance.currentRange_,prevRange,Output.EventType.NAVIGATE).onSpeechEnd(continueReading).go();}.bind(this);new Output().withRichSpeechAndBraille(ChromeVoxState.instance.currentRange_,null,Output.EventType.NAVIGATE).onSpeechEnd(continueReading).go();return false;case'contextMenu':if(ChromeVoxState.instance.currentRange_){var actionNode=ChromeVoxState.instance.currentRange_.start.node;if(actionNode.role==RoleType.inlineTextBox)
actionNode=actionNode.parent;actionNode.showContextMenu();return false;}
break;case'toggleKeyboardHelp':(new PanelCommand(PanelCommandType.OPEN_MENUS)).send();return false;case'showHeadingsList':(new PanelCommand(PanelCommandType.OPEN_MENUS,'role_heading')).send();return false;case'showFormsList':(new PanelCommand(PanelCommandType.OPEN_MENUS,'role_form')).send();return false;case'showLandmarksList':(new PanelCommand(PanelCommandType.OPEN_MENUS,'role_landmark')).send();return false;case'showLinksList':(new PanelCommand(PanelCommandType.OPEN_MENUS,'role_link')).send();return false;case'showTablesList':(new PanelCommand(PanelCommandType.OPEN_MENUS,'table_strategy')).send();return false;case'toggleSearchWidget':(new PanelCommand(PanelCommandType.SEARCH)).send();return false;case'readCurrentTitle':var target=ChromeVoxState.instance.currentRange_.start.node;var output=new Output();if(target.root.role==RoleType.rootWebArea){target=target.root;output.withString(target.name||target.docUrl);}else{while(target.role!=RoleType.window)target=target.parent;if(target)
output.withString(target.name||'');}
output.go();return false;case'readCurrentURL':var output=new Output();var target=ChromeVoxState.instance.currentRange_.start.node.root;output.withString(target.docUrl||'').go();return false;case'copy':window.setTimeout(function(){var textarea=document.createElement('textarea');document.body.appendChild(textarea);textarea.focus();document.execCommand('paste');var clipboardContent=textarea.value;textarea.remove();cvox.ChromeVox.tts.speak(Msgs.getMsg('copy',[clipboardContent]),cvox.QueueMode.FLUSH);ChromeVoxState.instance.pageSel_=null;},20);return true;case'toggleSelection':if(!ChromeVoxState.instance.pageSel_){ChromeVoxState.instance.pageSel_=ChromeVoxState.instance.currentRange;}else{var root=ChromeVoxState.instance.currentRange_.start.node.root;if(root&&root.anchorObject&&root.focusObject){var sel=new cursors.Range(new cursors.Cursor(root.anchorObject,root.anchorOffset),new cursors.Cursor(root.focusObject,root.focusOffset));var o=new Output().format('@end_selection').withSpeechAndBraille(sel,sel,Output.EventType.NAVIGATE).go();}
ChromeVoxState.instance.pageSel_=null;return false;}
break;case'fullyDescribe':var o=new Output();o.withContextFirst().withRichSpeechAndBraille(current,null,Output.EventType.NAVIGATE).go();return false;case'previousRow':dir=Dir.BACKWARD;var tableOpts={row:true,dir:dir};pred=AutomationPredicate.makeTableCellPredicate(current.start.node,tableOpts);predErrorMsg='no_cell_above';rootPred=AutomationPredicate.table;break;case'previousCol':dir=Dir.BACKWARD;var tableOpts={col:true,dir:dir};pred=AutomationPredicate.makeTableCellPredicate(current.start.node,tableOpts);predErrorMsg='no_cell_left';rootPred=AutomationPredicate.row;break;case'nextRow':dir=Dir.FORWARD;var tableOpts={row:true,dir:dir};pred=AutomationPredicate.makeTableCellPredicate(current.start.node,tableOpts);predErrorMsg='no_cell_below';rootPred=AutomationPredicate.table;break;case'nextCol':dir=Dir.FORWARD;var tableOpts={col:true,dir:dir};pred=AutomationPredicate.makeTableCellPredicate(current.start.node,tableOpts);predErrorMsg='no_cell_right';rootPred=AutomationPredicate.row;break;case'goToRowFirstCell':case'goToRowLastCell':var node=current.start.node;while(node&&node.role!=RoleType.row)
node=node.parent;if(!node)
break;var end=AutomationUtil.findNodePost(node,command=='goToRowLastCell'?Dir.BACKWARD:Dir.FORWARD,AutomationPredicate.leaf);if(end)
current=cursors.Range.fromNode(end);break;case'goToColFirstCell':dir=Dir.FORWARD;var node=current.start.node;while(node&&node.role!=RoleType.table)
node=node.parent;if(!node||!node.firstChild)
return false;var tableOpts={col:true,dir:dir,end:true};pred=AutomationPredicate.makeTableCellPredicate(current.start.node,tableOpts);current=cursors.Range.fromNode(node.firstChild);predErrorMsg='no_cell_above';rootPred=AutomationPredicate.table;break;case'goToColLastCell':dir=Dir.BACKWARD;var node=current.start.node;while(node&&node.role!=RoleType.table)
node=node.parent;if(!node||!node.lastChild)
return false;var tableOpts={col:true,dir:dir,end:true};pred=AutomationPredicate.makeTableCellPredicate(current.start.node,tableOpts);current=cursors.Range.fromNode(node.lastChild);predErrorMsg='no_cell_below';rootPred=AutomationPredicate.table;break;case'goToFirstCell':case'goToLastCell':node=current.start.node;while(node&&node.role!=RoleType.table)
node=node.parent;if(!node)
break;var end=AutomationUtil.findNodePost(node,command=='goToLastCell'?Dir.BACKWARD:Dir.FORWARD,AutomationPredicate.leaf);if(end)
current=cursors.Range.fromNode(end);break;default:return true;}
if(pred){var bound=current.getBound(dir).node;if(bound){var node=AutomationUtil.findNextNode(bound,dir,pred,{skipInitialAncestry:true});if(node&&!skipSync){node=AutomationUtil.findNodePre(node,Dir.FORWARD,AutomationPredicate.object)||node;}
if(node){current=cursors.Range.fromNode(node);}else{cvox.ChromeVox.earcons.playEarcon(cvox.Earcon.WRAP);var root=AutomationUtil.getTopLevelRoot(bound)||bound.root;if(dir==Dir.FORWARD){bound=root;}else{bound=AutomationUtil.findNodePost(root,dir,AutomationPredicate.leaf)||bound;}
node=AutomationUtil.findNextNode(bound,dir,pred,{skipInitialAncestry:true});if(node&&!skipSync){node=AutomationUtil.findNodePre(node,Dir.FORWARD,AutomationPredicate.object)||node;}
if(node){current=cursors.Range.fromNode(node);}else if(predErrorMsg){cvox.ChromeVox.tts.speak(Msgs.getMsg(predErrorMsg),cvox.QueueMode.FLUSH);return false;}}}}
if(current)
ChromeVoxState.instance.navigateToRange(current,undefined,speechProps);return false;};CommandHandler.onModeChanged=function(newMode,oldMode){if(!oldMode)
cvox.ChromeVoxKbHandler.commandHandler=CommandHandler.onCommand;var hasListener=chrome.commands.onCommand.hasListener(CommandHandler.onCommand);if(newMode==ChromeVoxMode.CLASSIC&&hasListener)
chrome.commands.onCommand.removeListener(CommandHandler.onCommand);else if(newMode==ChromeVoxMode.CLASSIC&&!hasListener)
chrome.commands.onCommand.addListener(CommandHandler.onCommand);};CommandHandler.increaseOrDecreaseSpeechProperty_=function(propertyName,increase){cvox.ChromeVox.tts.increaseOrDecreaseProperty(propertyName,increase);var announcement;var valueAsPercent=Math.round(cvox.ChromeVox.tts.propertyToPercentage(propertyName)*100);switch(propertyName){case cvox.AbstractTts.RATE:announcement=Msgs.getMsg('announce_rate',[valueAsPercent]);break;case cvox.AbstractTts.PITCH:announcement=Msgs.getMsg('announce_pitch',[valueAsPercent]);break;case cvox.AbstractTts.VOLUME:announcement=Msgs.getMsg('announce_volume',[valueAsPercent]);break;}
if(announcement){cvox.ChromeVox.tts.speak(announcement,cvox.QueueMode.FLUSH,cvox.AbstractTts.PERSONALITY_ANNOTATION);}};});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('BackgroundKeyboardHandler');goog.require('cvox.ChromeVoxKbHandler');BackgroundKeyboardHandler=function(){cvox.ChromeVoxKbHandler.handlerKeyMap=cvox.KeyMap.fromDefaults();this.passThroughKeyUpCount_=0;document.addEventListener('keydown',this.onKeyDown.bind(this),false);document.addEventListener('keyup',this.onKeyUp.bind(this),false);};BackgroundKeyboardHandler.prototype={onKeyDown:function(evt){evt.stickyMode=cvox.ChromeVox.isStickyModeOn()&&cvox.ChromeVox.isActive;if(cvox.ChromeVox.passThroughMode)
return false;if(ChromeVoxState.instance.mode!=ChromeVoxMode.CLASSIC&&ChromeVoxState.instance.mode!=ChromeVoxMode.NEXT_COMPAT&&!cvox.ChromeVoxKbHandler.basicKeyDownActionsListener(evt)){evt.preventDefault();evt.stopPropagation();}
Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH);return false;},onKeyUp:function(evt){if(cvox.ChromeVox.passThroughMode){if(this.passThroughKeyUpCount_>=3){cvox.ChromeVox.passThroughMode=false;this.passThroughKeyUpCount_=0;}else{this.passThroughKeyUpCount_++;}}
return false;},onModeChanged:function(newMode,oldMode){if(newMode==ChromeVoxMode.CLASSIC||newMode==ChromeVoxMode.NEXT_COMPAT){chrome.accessibilityPrivate.setKeyboardListener(false,false);}else{chrome.accessibilityPrivate.setKeyboardListener(true,cvox.ChromeVox.isStickyPrefOn);}
if(newMode===ChromeVoxMode.NEXT||newMode===ChromeVoxMode.FORCE_NEXT||newMode===ChromeVoxMode.NEXT_COMPAT){window['prefs'].switchToKeyMap('keymap_next');}else if(oldMode&&oldMode!=ChromeVoxMode.CLASSIC&&oldMode!=ChromeVoxMode.CLASSIC_COMPAT){window['prefs'].switchToKeyMap('keymap_classic');}}};goog.provide('Notifications');goog.require('PanelCommand');function UpdateNotification(){this.data={};this.data.type='basic';this.data.iconUrl='/images/chromevox-16.png';this.data.title=Msgs.getMsg('update_title');this.data.message=Msgs.getMsg('update_message_next');}
UpdateNotification.prototype={shouldShow:function(){return!localStorage['notifications_update_notification_shown']&&chrome.runtime.getManifest().version>='53'&&cvox.ChromeVox.isChromeOS;},show:function(){if(!this.shouldShow())
return;chrome.notifications.create('update',this.data);chrome.notifications.onClicked.addListener(this.onClicked);chrome.notifications.onClosed.addListener(this.onClosed);},onClicked:function(notificationId){(new PanelCommand(PanelCommandType.TUTORIAL)).send();},onClosed:function(id){localStorage['notifications_update_notification_shown']=true;},removeAllListeners:function(){chrome.notifications.onClicked.removeListener(this.onClicked);chrome.notifications.onClosed.removeListener(this.onClosed);}};Notifications.currentUpdate;Notifications.onModeChange=function(newMode,oldMode){if(document.location.href.indexOf('background.html')==-1)
return;if(newMode!==ChromeVoxMode.FORCE_NEXT)
return;if(oldMode)
Notifications.reset();Notifications.currentUpdate=new UpdateNotification();Notifications.currentUpdate.show();};Notifications.reset=function(){if(Notifications.currentUpdate)
Notifications.currentUpdate.removeAllListeners();delete localStorage['notifications_update_notification_shown'];};goog.provide('Background');goog.require('AutomationPredicate');goog.require('AutomationUtil');goog.require('BackgroundKeyboardHandler');goog.require('ChromeVoxState');goog.require('CommandHandler');goog.require('FindHandler');goog.require('LiveRegions');goog.require('NextEarcons');goog.require('Notifications');goog.require('Output');goog.require('Output.EventType');goog.require('PanelCommand');goog.require('Stubs');goog.require('constants');goog.require('cursors.Cursor');goog.require('cvox.BrailleKeyCommand');goog.require('cvox.ChromeVoxBackground');goog.require('cvox.ChromeVoxEditableTextBase');goog.require('cvox.ClassicEarcons');goog.require('cvox.ExtensionBridge');goog.require('cvox.NavBraille');goog.scope(function(){var AutomationNode=chrome.automation.AutomationNode;var Dir=constants.Dir;var EventType=chrome.automation.EventType;var RoleType=chrome.automation.RoleType;Background=function(){ChromeVoxState.call(this);this.whitelist_=['chromevox_next_test'];this.classicBlacklist_=new Set();this.classicBlacklistRegExp_=Background.globsToRegExp_(chrome.runtime.getManifest()['content_scripts'][0]['exclude_globs']);this.NextCompatRegExp_=Background.globsToRegExp_(['*docs.google.com*']);this.currentRange_=null;this.savedRange_=null;for(var func in this){if(typeof(this[func])=='function')
this[func]=this[func].bind(this);}
this.classicEarcons_=cvox.ChromeVox.earcons||new cvox.ClassicEarcons();this.nextEarcons_=new NextEarcons();Object.defineProperty(cvox.ChromeVox,'earcons',{get:(function(){if(this.mode===ChromeVoxMode.FORCE_NEXT||this.mode===ChromeVoxMode.NEXT||this.mode===ChromeVoxMode.NEXT_COMPAT){return this.nextEarcons_;}else{return this.classicEarcons_;}}).bind(this)});if(cvox.ChromeVox.isChromeOS){Object.defineProperty(cvox.ChromeVox,'modKeyStr',{get:function(){return(this.mode==ChromeVoxMode.CLASSIC||this.mode==ChromeVoxMode.CLASSIC_COMPAT)?'Search+Shift':'Search';}.bind(this)});Object.defineProperty(cvox.ChromeVox,'typingEcho',{get:function(){return parseInt(localStorage['typingEcho'],10);}.bind(this),set:function(v){localStorage['typingEcho']=v;}.bind(this)});}
Object.defineProperty(cvox.ChromeVox,'isActive',{get:function(){return localStorage['active']!=='false';},set:function(value){localStorage['active']=value;}});cvox.ExtensionBridge.addMessageListener(this.onMessage_);this.keyboardHandler_=new BackgroundKeyboardHandler();this.liveRegions_=new LiveRegions(this);this.inExcursion_=false;this.mode_=null;chrome.accessibilityPrivate.onAccessibilityGesture.addListener(this.onAccessibilityGesture_);this.focusRecoveryMap_=new WeakMap();};Background.ISSUE_URL='https://code.google.com/p/chromium/issues/entry?'+'labels=Type-Bug,Pri-2,cvox2,OS-Chrome&'+'components=UI>accessibility&'+'description=';Background.GESTURE_CLASSIC_COMMAND_MAP={'click':'forceClickOnCurrentItem','swipeUp1':'backward','swipeDown1':'forward','swipeLeft1':'left','swipeRight1':'right','swipeUp2':'jumpToTop','swipeDown2':'readFromHere',};Background.GESTURE_NEXT_COMMAND_MAP={'click':'forceClickOnCurrentItem','swipeUp1':'previousLine','swipeDown1':'nextLine','swipeLeft1':'previousObject','swipeRight1':'nextObject','swipeUp2':'jumpToTop','swipeDown2':'readFromHere',};Background.prototype={__proto__:ChromeVoxState.prototype,get focusRecoveryMap(){return this.focusRecoveryMap_;},getMode:function(){var useNext=localStorage['useNext']!=='false';var target;if(!this.getCurrentRange()){chrome.automation.getFocus(function(focus){target=focus;});}else{target=this.getCurrentRange().start.node;}
if(!target)
return useNext?ChromeVoxMode.FORCE_NEXT:ChromeVoxMode.CLASSIC;var topLevelRoot=AutomationUtil.getTopLevelRoot((target));if(!topLevelRoot)
return useNext?ChromeVoxMode.FORCE_NEXT:ChromeVoxMode.CLASSIC_COMPAT;var nextSite=this.isWhitelistedForNext_(topLevelRoot.docUrl);var nextCompat=this.NextCompatRegExp_.test(topLevelRoot.docUrl);var classicCompat=this.isWhitelistedForClassicCompat_(topLevelRoot.docUrl);if(nextCompat&&useNext)
return ChromeVoxMode.NEXT_COMPAT;else if(classicCompat&&!useNext)
return ChromeVoxMode.CLASSIC_COMPAT;else if(nextSite)
return ChromeVoxMode.NEXT;else if(!useNext)
return ChromeVoxMode.CLASSIC;else
return ChromeVoxMode.FORCE_NEXT;},onModeChanged_:function(newMode,oldMode){this.keyboardHandler_.onModeChanged(newMode,oldMode);CommandHandler.onModeChanged(newMode,oldMode);FindHandler.onModeChanged(newMode,oldMode);Notifications.onModeChange(newMode,oldMode);if(newMode==ChromeVoxMode.CLASSIC||newMode==ChromeVoxMode.NEXT_COMPAT)
chrome.accessibilityPrivate.setFocusRing([]);var cur=this.currentRange_;chrome.tabs.query({active:true,lastFocusedWindow:true},function(tabs){if(newMode==ChromeVoxMode.CLASSIC){if(oldMode==ChromeVoxMode.FORCE_NEXT){cvox.ChromeVox.injectChromeVoxIntoTabs(tabs);}}else if(newMode===ChromeVoxMode.FORCE_NEXT){this.disableClassicChromeVox_({forNextCompat:true});}else if(newMode!=ChromeVoxMode.NEXT_COMPAT){if(cur&&!cur.isWebRange())
return;this.disableClassicChromeVox_({tabs:tabs});}}.bind(this));if(oldMode===ChromeVoxMode.NEXT||oldMode===ChromeVoxMode.FORCE_NEXT){cvox.ChromeVox.earcons.cancelEarcon(cvox.Earcon.PAGE_START_LOADING);(new PanelCommand(PanelCommandType.DISABLE_MENUS)).send();}
if(newMode===ChromeVoxMode.NEXT||newMode===ChromeVoxMode.FORCE_NEXT){(new PanelCommand(PanelCommandType.ENABLE_MENUS)).send();if(cvox.TabsApiHandler)
cvox.TabsApiHandler.shouldOutputSpeechAndBraille=false;}else{if(cvox.TabsApiHandler)
cvox.TabsApiHandler.shouldOutputSpeechAndBraille=true;}},toggleNext:function(opt_setValue){var useNext;if(opt_setValue!==undefined)
useNext=opt_setValue;else
useNext=localStorage['useNext']!='true';localStorage['useNext']=useNext;if(useNext)
this.setCurrentRangeToFocus_();else
this.setCurrentRange(null);var announce=Msgs.getMsg(useNext?'switch_to_next':'switch_to_classic');cvox.ChromeVox.tts.speak(announce,cvox.QueueMode.FLUSH,{doNotInterrupt:true});return useNext;},getCurrentRange:function(){if(this.currentRange_&&this.currentRange_.isValid())
return this.currentRange_;return null;},setCurrentRange:function(newRange){if(!this.inExcursion_&&newRange)
this.savedRange_=new cursors.Range(newRange.start,newRange.end);if(newRange&&!newRange.isValid())
return;this.currentRange_=newRange;var oldMode=this.mode_;var newMode=this.getMode();if(oldMode!=newMode){this.onModeChanged_(newMode,oldMode);this.mode_=newMode;}
if(this.currentRange_){var start=this.currentRange_.start.node;start.makeVisible();var root=start.root;if(!root||root.role==RoleType.desktop)
return;var position={};var loc=start.location;position.x=loc.left+loc.width/2;position.y=loc.top+loc.height/2;var url=root.docUrl;url=url.substring(0,url.indexOf('#'))||url;cvox.ChromeVox.position[url]=position;}},navigateToRange:function(range,opt_focus,opt_speechProps){opt_focus=opt_focus===undefined?true:opt_focus;opt_speechProps=opt_speechProps||{};if(opt_focus){var actionNode=range.start.node;if(actionNode.role==RoleType.inlineTextBox)
actionNode=actionNode.parent;if(actionNode.role!=RoleType.iframe&&!actionNode.state.focused&&!AutomationPredicate.structuralContainer(actionNode))
actionNode.focus();}
var prevRange=this.currentRange_;this.setCurrentRange(range);var o=new Output();var selectedRange;if(this.pageSel_&&this.pageSel_.isValid()&&range.isValid()){var startDir=AutomationUtil.getDirection(this.pageSel_.start.node,(range.start.node));var endDir=AutomationUtil.getDirection(this.pageSel_.end.node,(range.end.node));var pageRootStart=this.pageSel_.start.node.root;var pageRootEnd=this.pageSel_.end.node.root;var curRootStart=range.start.node.root;var curRootEnd=range.end.node.root;if(startDir==Dir.BACKWARD||pageRootStart!=pageRootEnd||pageRootStart!=curRootStart||pageRootEnd!=curRootEnd){o.format('@end_selection');this.pageSel_=null;}else{var msg;if(endDir==Dir.FORWARD&&(this.pageSel_.end.node!=range.end.node||this.pageSel_.end.index<=range.end.index)){msg='@selected';}else{msg='@unselected';selectedRange=prevRange;}
this.pageSel_=new cursors.Range(this.pageSel_.start,range.end);if(this.pageSel_)
this.pageSel_.select();}}else{range.select();}
o.withRichSpeechAndBraille(selectedRange||range,prevRange,Output.EventType.NAVIGATE).withQueueMode(cvox.QueueMode.FLUSH);if(msg)
o.format(msg);for(var prop in opt_speechProps)
o.format('!'+prop);o.go();},showOptionsPage:function(){var optionsPage={url:'chromevox/background/options.html'};chrome.tabs.create(optionsPage);},onBrailleKeyEvent:function(evt,content){if(this.mode===ChromeVoxMode.CLASSIC)
return false;switch(evt.command){case cvox.BrailleKeyCommand.PAN_LEFT:CommandHandler.onCommand('previousObject');break;case cvox.BrailleKeyCommand.PAN_RIGHT:CommandHandler.onCommand('nextObject');break;case cvox.BrailleKeyCommand.LINE_UP:CommandHandler.onCommand('previousLine');break;case cvox.BrailleKeyCommand.LINE_DOWN:CommandHandler.onCommand('nextLine');break;case cvox.BrailleKeyCommand.TOP:CommandHandler.onCommand('jumpToTop');break;case cvox.BrailleKeyCommand.BOTTOM:CommandHandler.onCommand('jumpToBottom');break;case cvox.BrailleKeyCommand.ROUTING:this.brailleRoutingCommand_(content.text,(evt.displayPosition));break;default:return false;}
return true;},shouldEnableClassicForUrl_:function(url){return this.mode!=ChromeVoxMode.FORCE_NEXT&&!this.isBlacklistedForClassic_(url)&&!this.isWhitelistedForNext_(url);},isWhitelistedForClassicCompat_:function(url){return this.isBlacklistedForClassic_(url)||(this.getCurrentRange()&&!this.getCurrentRange().isWebRange()&&this.getCurrentRange().start.node.state.focused);},isBlacklistedForClassic_:function(url){if(this.classicBlacklistRegExp_.test(url))
return true;url=url.substring(0,url.indexOf('#'))||url;return this.classicBlacklist_.has(url);},isWhitelistedForNext_:function(url){return this.whitelist_.some(function(item){return url.indexOf(item)!=-1;});},disableClassicChromeVox_:function(params){var disableChromeVoxCommand={message:'SYSTEM_COMMAND',command:'killChromeVox'};if(params.forNextCompat){var reStr=this.NextCompatRegExp_.toString();disableChromeVoxCommand['excludeUrlRegExp']=reStr.substring(1,reStr.length-1);}
if(params.tabs){for(var i=0,tab;tab=params.tabs[i];i++)
chrome.tabs.sendMessage(tab.id,disableChromeVoxCommand);}else{cvox.ExtensionBridge.send(disableChromeVoxCommand);}},brailleRoutingCommand_:function(text,position){var actionNodeSpan=null;var selectionSpan=null;text.getSpans(position).forEach(function(span){if(span instanceof Output.SelectionSpan){selectionSpan=span;}else if(span instanceof Output.NodeSpan){if(!actionNodeSpan||text.getSpanLength(span)<=text.getSpanLength(actionNodeSpan)){actionNodeSpan=span;}}});if(!actionNodeSpan)
return;var actionNode=actionNodeSpan.node;if(actionNode.role===RoleType.inlineTextBox)
actionNode=actionNode.parent;actionNode.doDefault();if(selectionSpan){var start=text.getSpanStart(selectionSpan);var targetPosition=position-start+selectionSpan.offset;actionNode.setSelection(targetPosition,targetPosition);}},onMessage_:function(msg,port){var target=msg['target'];var action=msg['action'];switch(target){case'next':if(action=='getIsClassicEnabled'){var url=msg['url'];var isClassicEnabled=this.shouldEnableClassicForUrl_(url);port.postMessage({target:'next',isClassicEnabled:isClassicEnabled});}else if(action=='enableClassicCompatForUrl'){var url=msg['url'];this.classicBlacklist_.add(url);if(this.currentRange_&&this.currentRange_.start.node)
this.setCurrentRange(this.currentRange_);}else if(action=='onCommand'){CommandHandler.onCommand(msg['command']);}else if(action=='flushNextUtterance'){Output.forceModeForNextSpeechUtterance(cvox.QueueMode.FLUSH);}
break;}},markCurrentRange:function(){if(!this.currentRange)
return;var root=AutomationUtil.getTopLevelRoot(this.currentRange.start.node);if(root)
this.focusRecoveryMap_.set(root,this.currentRange);},onAccessibilityGesture_:function(gesture){if(this.mode==ChromeVoxMode.CLASSIC){if(this.handleClassicGesture_(gesture))
return;}
var command=Background.GESTURE_NEXT_COMMAND_MAP[gesture];if(command)
CommandHandler.onCommand(command);},handleClassicGesture_:function(gesture){var command=Background.GESTURE_CLASSIC_COMMAND_MAP[gesture];if(!command)
return false;var msg={'message':'USER_COMMAND','command':command};cvox.ExtensionBridge.send(msg);return true;},setCurrentRangeToFocus_:function(){chrome.automation.getFocus(function(focus){if(focus)
this.setCurrentRange(cursors.Range.fromNode(focus));else
this.setCurrentRange(null);}.bind(this));},};Background.globsToRegExp_=function(globs){return new RegExp('^('+globs.map(function(glob){return glob.replace(/[.+^$(){}|[\]\\]/g,'\\$&').replace(/\*/g,'.*').replace(/\?/g,'.');}).join('|')+')$');};new Background();});goog.require('Background');
