/* 
 * Copyright (C) 2008, Nokia gate5 GmbH Berlin 
 * 
 * These coded instructions, statements, and computer programs contain 
 * unpublished proprietary information of Nokia gate5 GmbH, and are 
 * copy protected by law. They may not be disclosed to third parties 
 * or copied or duplicated in any form, in whole or in part, without 
 * the specific, prior written permission of Nokia gate5 GmbH. 
 */

/*
 * $Revision$
 * $Date$
 */

if(this.top&&top.nokia&&top.nokia.aduno&&top.nokia.aduno.Ns){var nokia=top.nokia}else{(function(_root){var _firstRoot=_root;var getRoot=function(){return _root};var setRoot=function(aObject){_root=aObject};var resetRoot=function(){_root=_firstRoot};var Ns=function(aName){if(Ns._instances[aName]){return Ns.getObject(aName,Ns._instances[aName])}if((this._isNokiaNamespace)||!(this instanceof Ns)){return new Ns(aName)}if((aName==="")||(typeof aName!="string")){throw new TypeError("Ns constructor expects a string for an argument")}this._name=aName;this._importCode="";this._isNokiaNamespace=true;Ns._instances[aName]=Ns.getObject(aName,this);return Ns._instances[aName]};Ns.prototype={constructor:Ns,getName:function(){return this._name},addMembers:function(aHash){for(var memName in aHash){if(!this[memName]){this.addMemberName(memName)}this[memName]=aHash[memName]}return this},addMemberName:function(aName){this._importCode+="var "+aName+"="+this._name+"['"+aName+"'];\n";return this},getImportCode:function(){return this._importCode},addReadyHandler:function(aBind,aHandler,aParams){aHandler.call(aBind,this._name,true,aParams);return this}};Ns.getObject=function(aName,aMixin){var parentName=aName.replace(/(\.|^)[^\.]*$/g,"");var shortName=aName.replace(/.*[\.|^]([^\.]+)$/g,"$1");var parentObj=(parentName)?this.getObject(parentName):_root;var shortObj=parentObj[shortName];if(!(shortObj instanceof Object)&&!(shortObj instanceof _root.Object)){if(shortObj===undefined){parentObj[shortName]=aMixin||{}}else{throw TypeError("A non-object was already taking the space of name "+aName)}}if(parentObj[shortName]!=aMixin){for(var prop in aMixin){if(prop=="constructor"){continue}parentObj[shortName][prop]=aMixin[prop]}}return parentObj[shortName]};Ns.exists=function(aName){return(Ns._instances[aName]||false)};Ns._instances={};var ReadySource={_readyValue:undefined,_success:undefined,addReadyHandler:function(aBind,aHandler,aParams){if(!aHandler){throw new Error("A bind argument and handler should be passed")}if(this._readyValue!==undefined&&this._readyValue!==null){aHandler.call(aBind,this._readyValue,this._success,aParams)}else{this._loadHandlers=this._loadHandlers||[];this._loadHandlers.push({bind:aBind,handler:aHandler,params:aParams})}return this},getReadyValue:function(){if(typeof this._readyValue==="undefined"){return null}return this._readyValue},cleanReadyValue:function(){this._readyValue=true},_fireReady:function(aReadyValue,aSuccess){var hlrs=this._loadHandlers||[];this._readyValue=aReadyValue;this._success=aSuccess;for(var i=0,len=hlrs.length;i<len;i++){hlrs[i].handler.call(hlrs[i].bind,this._readyValue,aSuccess,hlrs[i].params)}this._loadHandlers=[];this._readyValue=aReadyValue;return this}};var NsLoader=function(aName,aBaseDir,aPlatform){if(typeof aName!="string"){throw new TypeError("NsLoader constructor expects a string for the name argument")}if(NsLoader._instances[aName]){return NsLoader._instances[aName]}this._newlineAdjustment=0;this._name=aName;this._baseDir=aBaseDir||NsLoader.baseDir;this._dir="";this._innerCode="";this._lineData=[];this._memberCodes={};this._platform=aPlatform||NsLoader.ALL;this._definition={name:null,requires:[],imports:[],classes:[],functions:[],subs:[],importsAs:{}};this._addMemberCode("    /* "+this._name+" */    \nnew function() {\nnew nokia.aduno.Ns('"+this._name+"');\n");this._pending=0;this._loadHandlers=[];this.setBaseDir();this._loadDefinition();NsLoader._instances[aName]=this;return this};NsLoader.prototype={constructor:NsLoader,addReadyHandler:ReadySource.addReadyHandler,getReadyValue:ReadySource.getReadyValue,_fireReady:ReadySource._fireReady,setBaseDir:function(aBaseDir){if(aBaseDir){this._baseDir=aBaseDir}this.dir=this._baseDir.replace(/\/*$/,"/")+this._name.replace(/\.|\.*$/g,"/");return this},_addMemberCode:function(aCode,aName){var diff,matches;var debug=aName&&_root.console&&_root.console.firebug;if(debug){matches=this._innerCode.match(/\n/g);diff=(matches)?matches.length:0}this._innerCode+=aCode+"\n";if(debug){var length=this._lineData.length;matches=this._innerCode.match(/\n/g);if(length===0){this._lineData.push({name:aName,startLineNumber:1,endLineNumber:((matches)?matches.length:0)-diff})}else{var lastItem=this._lineData[length-1];this._lineData.push({name:aName,startLineNumber:lastItem.endLineNumber+1,endLineNumber:lastItem.endLineNumber+((matches)?matches.length:0)-diff})}}},_getLineData:function(aLineNumber){var lData=this._lineData;for(var i=0,len=lData.length;i<len;i++){if(lData[i].startLineNumber>=aLineNumber){return{name:i===0?"<no name>":lData[i-1].name,lineNumber:i===0?aLineNumber:aLineNumber-lData[i-1].startLineNumber}}}return{name:i===0?"<no name>":lData[i-1].name,lineNumber:i===0?aLineNumber:aLineNumber-lData[i-1].startLineNumber}},_loadDefinition:function(){var uri=this.dir+"namespace.def";var loader=new Loader({uri:uri,bind:this,handler:this._onLoadDefinition,async:NsLoader.async})},_loadMembers:function(){var members=["functions"].concat(this._definition.classes);var loader=null;var len=members.length;for(var i=0;i<len;i++){var uri=this.dir+members[i]+".js";loader=new Loader({uri:uri,bind:this,handler:this._onLoadMember,async:NsLoader.async,params:members[i]})}},_loadRequired:function(aNames,aHandler){var nsLoader=null;var handler=aHandler||function(){};for(var i=0,len=aNames.length;i<len;i++){nsLoader=new NsLoader(aNames[i],this._baseDir,this._platform);nsLoader.addReadyHandler(this,handler)}},_onLoadDefinition:function(aCode,aSuccess){if(aSuccess){this._parseDefinition(aCode);var platform,platformString="platform_";var len=platformString.length;for(var member in this._definition){if(member.lastIndexOf(platformString)===0){platform=member.substring(len);if((this._platform===NsLoader.ALL)||(this._platform===platform)){this._definition.classes=this._definition.classes.concat(this._definition[member])}}}this._pending=this._definition.requires.length+this._definition.imports.length+this._definition.classes.length+1;this._loadRequired(this._definition.requires,this._onLoadRequired);this._loadRequired(this._definition.imports,this._onLoadImport);this._loadMembers()}else{if(aCode){this._fireReady(this._name+" ("+aCode+")",false)}else{this._fireReady(this._name,false)}}},_onLoadRequired:function(aName,aSuccess){this._pending--;if(this._pending===0){this._tryInnerCode()}},_onLoadImport:function(aName,aSuccess){var alias=this._definition.importsAs[aName];var before=this._innerCode.match(/\n/g).length;if(alias){this._addMemberCode("var "+alias+" = "+aName+";\n")}else{this._addMemberCode(new Ns(aName)._importCode)}this._newlineAdjustment-=this._innerCode.match(/\n/g).length-before;this._onLoadRequired(aName,aSuccess)},_onLoadMember:function(aCode,aSuccess,aMemName){if(aSuccess){this._memberCodes[aMemName]=aCode;this._onLoadRequired(aMemName,aSuccess)}else{if(aCode){this._fireReady(this._name+" ("+aCode+")",false)}else{this._fireReady(this._name,false)}}},_parseDefinition:function(aDef){var line;var items=[];var i;var len;var itemNames=[];while((line=NsLoader.LINE_RE.exec(aDef))!==null){this._definition[line[1]]=this._definition[line[1]]||[];items=line[2].split(",");for(i=0,len=items.length;i<len;i++){itemNames=NsLoader.ITEM_RE.exec(items[i]);if(itemNames){this._definition[line[1]].push(itemNames[1]);if(itemNames[2]){this._definition[line[1]+"As"]=this._definition[line[1]+"As"]||{};this._definition[line[1]+"As"][itemNames[1]]=itemNames[2]}}}}},_tryInnerCode:function(){var i=0;var len;var members;var memberNames="";members=this._definition.functions;this._addMemberCode(this._memberCodes.functions||"","functions");for(len=members.length;i<len;++i){memberNames+="\t"+members[i]+": "+members[i]+", \n"}members=this._definition.classes;for(i=0,len=members.length;i<len;++i){this._addMemberCode(this._memberCodes[members[i]],members[i]);memberNames+="\t"+members[i]+": "+members[i]+", \n"}if(memberNames){this._addMemberCode(this._name+".addMembers({\n"+memberNames.replace(/, \n$/,"")+"\n});\n")}this._addMemberCode("};");try{this._eval(this._innerCode,_root)}catch(e){delete Ns._instances[this._name];var ld=this._getLineData(e.lineNumber-nokia.aduno.NsLoader.numLines+this._newlineAdjustment);var msg="'"+e.message+"' in "+this._name+"."+ld.name+", line "+ld.lineNumber;throw new Error(msg,e.fileName,(e.lineNumber||e.line))}delete this._innerCode;delete this._memberCodes;delete this._newlineAdjustment;this._fireReady(this._name,true)}};NsLoader._instances={};NsLoader.baseDir="javascripts/";NsLoader.async=false;NsLoader.LINE_RE=/(?:\n|^)\s*(\w+)\s*:([\s\S]*?)(?=\n\w+:|$)/g;NsLoader.ITEM_RE=/^\s*([\w\.]+?)\s*(?:as\s+(\w+)|$)/;NsLoader.exists=function(aName){return(NsLoader._instances[aName]||false)};NsLoader.ALL="all";NsLoader.SNC="snc";NsLoader.TOUCH="touch";NsLoader.WEB="web";var XHttpRequest=function(aWindow){if(!aWindow){aWindow=_root}try{return(aWindow.ActiveXObject)?new aWindow.ActiveXObject("Microsoft.XMLHTTP"):new aWindow.XMLHttpRequest()}catch(e){throw new Error("nokia.aduno.Loader could not instantiate an XMLHttpRequest")}};var Loader=function(aOptions){if(typeof aOptions==="string"){this.uri=aOptions;aOptions={};aOptions.uri=this.uri}else{this.uri=aOptions.uri}if(aOptions.type=="css"&&nokia&&nokia.aduno&&nokia.aduno.utils){return new nokia.aduno.utils.CssLoader(aOptions)}if(aOptions.type=="script"&&nokia&&nokia.aduno&&nokia.aduno.utils){return new nokia.aduno.utils.ScriptLoader(aOptions)}this.type=aOptions.type||"text";this.async=(aOptions.async!==undefined)?aOptions.async:Loader.async;this.window=aOptions.window||_root;this.timeout=aOptions.timeout||Loader.TIMEOUT;if(aOptions.xmlHttpRequest&&this.uri.indexOf("http")===0){this.xhr=aOptions.xmlHttpRequest;this.specialXmlHttp=true}else{this.xhr=new XHttpRequest(this.window)}if(typeof this.uri!="string"){throw new TypeError("nokia.aduno.Loader expects a uri in the arguments or parameters")}if(typeof aOptions.handler=="function"){this.addReadyHandler(aOptions.bind||this,aOptions.handler,aOptions.params)}this._load()};Loader.prototype={constructor:Loader,addReadyHandler:ReadySource.addReadyHandler,getReadyValue:ReadySource.getReadyValue,_fireReady:ReadySource._fireReady,_load:function(){var myself=this;var xhr=this.xhr;this.xhr=null;if(this.async){xhr.onreadystatechange=function(aXhr){myself._readyState=xhr.readyState;if(xhr.readyState===Loader.STATE_DONE){if(xhr.status===404||!_root.ActiveXObject&&!myself.specialXmlHttp&&!(xhr.responseText)&&(_root.location.protocol=="file:")){myself.status=404}else{myself.status=xhr.status||200}myself._onLoad.call(myself,xhr)}}}try{if(this.specialXmlHttp){xhr.open("GET",this.uri,this.async,null,null)}else{xhr.open("GET",this.uri,this.async)}if(this.type=="binary"&&_root.navigator&&navigator.userAgent&&navigator.userAgent.indexOf("Gecko")>=0){xhr.overrideMimeType("text/plain; charset=x-user-defined");this._geckoBrowser=true}else{if(this.type!=="xml"&&xhr.overrideMimeType){xhr.overrideMimeType("text/text")}}this._xhr=xhr;xhr.send(null);if(!this.async){this.status=(xhr.status)?xhr.status:200;this._onLoad(xhr)}else{var cancelLoading=function(){myself._cancelTimeout=null;myself._cancelLoading(xhr,"Could not load "+myself.uri+", reason: timeout")};this._cancelTimeout=_root.setTimeout(cancelLoading,this.timeout)}}catch(ex){this._cancelLoading(xhr,"Could not load "+this.uri+", reason: "+ex.message)}},_cancelLoading:function(aXhr,aMessage){this.status=404;this._readyState=Loader.STATE_ERROR;this._errorMessage=aMessage;this._onLoad(aXhr)},_onLoad:function(aXhr){if(this._cancelTimeout){_root.clearTimeout(this._cancelTimeout)}if((this.status===200)&&(this._readyState!==Loader.STATE_ERROR)){switch(this.type){case"binary":if(this._geckoBrowser){this._returnValue=aXhr.responseText}else{this._returnValue=aXhr.responseBody}break;case"xml":if(this.specialXmlHttp&&!aXhr.responseXML){if(window.DOMParser){this._returnValue=new DOMParser().parseFromString(aXhr.responseText,"text/xml")}else{if(window.ActiveXObject){var parser=new ActiveXObject("Microsoft.XMLDOM");parser.async="false";parser.loadXML(aXhr.responseText);this._returnValue=parser.documentElement}else{this._returnValue=null}}}else{this._returnValue=aXhr.responseXML}break;default:this._returnValue=aXhr.responseText;break}this._xhr=null;delete aXhr;this._fireReady(this._returnValue,true)}else{this._xhr=null;delete aXhr;this._fireReady(this._errorMessage,false)}this._readyValue=true},abort:function(){if(this._xhr){this._xhr.abort()}}};Loader.async=true;Loader.TIMEOUT=10000;Loader.STATE_UNSENT=0;Loader.STATE_OPENED=1;Loader.STATE_HEADERS_RECEIVED=2;Loader.STATE_LOADING=3;Loader.STATE_DONE=4;Loader.STATE_ERROR=5;var NsManager=function(aBaseDir,aPlatform){this._pending=0;this._platform=aPlatform;this._unsuccessful=[];this.setBaseDir(aBaseDir)};NsManager.prototype={constructor:NsManager,addReadyHandler:ReadySource.addReadyHandler,_fireReady:ReadySource._fireReady,_onReady:function(aName,aSuccess){if(this._pending>0){this._pending--}if(!aSuccess){this._unsuccessful.push(aName)}if(this._pending===0){if(this._unsuccessful.length===0){this._fireReady(true,true)}else{this._fireReady("Could not load namespace(s) "+this._unsuccessful.join(", "),false)}}},addNs:function(aName,aBaseDir){var ns=Ns.exists(aName)&&new Ns(aName)||new NsLoader(aName,aBaseDir||this._baseDir,this._platform);this._pending++;var bind=this;var fn=function(){ns.addReadyHandler(bind,bind._onReady)};setTimeout(fn,1);return this},setBaseDir:function(aBaseDir){this._baseDir=aBaseDir||NsLoader.baseDir;return this}};var ns=new Ns("nokia.aduno");ns.addMembers({getRoot:getRoot,setRoot:setRoot,resetRoot:resetRoot,ns:Ns,Ns:Ns,Namespace:Ns,Loader:Loader,NsLoader:NsLoader,NsManager:NsManager,XHttpRequest:XHttpRequest})})(this);nokia.aduno.NsLoader.prototype._eval=function(aCode,aRoot){aRoot=aRoot||window;aRoot.eval(aCode)}}try{this._Something._That._Could._Not._Work()}catch(e){nokia.aduno.NsLoader.numLines=e.lineNumber-2}new function(){new nokia.aduno.Ns("nokia.aduno.utils");var type=function(aSomething){var s=typeof aSomething;if(s==="object"){if(aSomething){if(Object.prototype.toString.call(aSomething)==="[object Array]"){return"array"}else{if(typeof aSomething.length==="number"&&aSomething.callee){return"arguments"}else{if(aSomething.nodeType===1){return"node"}}}}else{if(aSomething===null){return"null"}else{return s}}}else{if(s==="function"){if(aSomething.constructor===nokia.aduno.utils.Class){return"class"}else{if(aSomething.initialize){return"instance"}else{return s}}}}return s};function clone(aObject){var cloned;switch(type(aObject)){case"object":cloned={};Collection.forEach(aObject,function(value,key){cloned[key]=clone(value)},this);break;case"array":cloned=[];for(var i=0,len=aObject.length;i<len;++i){cloned[i]=clone(aObject[i])}break;default:cloned=aObject;break}return cloned}function extend(target,source){for(var key in source){if(source.hasOwnProperty(key)){target[key]=source[key]}}return target}var inspect=function(aSomething){var t=type(aSomething);function __objectFormat(aObj){var s="{";var fr=true;Collection.forEach(aObj,function(value,key){if(typeof value!="function"){if(!fr){s+=", "}else{fr=false}s+=key+": "+String(value)}},this);return s+"}"}var result;switch(t){case"array":return"["+String(aSomething)+"]";case"string":return"'"+aSomething+"'";case"class":return"Class: "+aSomething.name;case"function":result=null;if(aSomething.constructor){if(aSomething.constructor.Name){result="Instance of "+aSomething.className+" "+__objectFormat(aSomething)}else{if(aSomething.initialize){result="Instance "+__objectFormat(aSomething)}}}if(result===null){result=String(aSomething)}return result;case"object":result=null;if(aSomething&&(aSomething.constructor===Object||(/object/i.test(String(aSomething))))){result=__objectFormat(aSomething)}else{result=String(aSomething)}return result;case"node":result="<"+aSomething.tagName.toLowerCase();if(aSomething.id){result+=' id="';result+=aSomething.id;result+='"'}result+=">";return result;case"arguments":result="(";for(var i=0,len=aSomething.length;i<len;++i){result+=aSomething[i];if(i+1<len){result+=", "}}return result+")";default:return String(aSomething)}};var splat=function(aObj){var objType=type(aObj);return(objType!="undefined")?((objType!="array"&&objType!="arguments")?[aObj]:aObj):[]};var cancelEvent=function(aEvent){if(aEvent.preventDefault){aEvent.preventDefault()}else{aEvent.returnValue=false}};var _addTimer=function(aIsTimeout,aPeriod,aBind,aHandler,aParams){if(typeof aPeriod!=="number"){throw new nokia.aduno.utils.ArgumentError("Missing time distance in milliseconds.")}if(typeof aBind==="function"){aParams=aHandler;aHandler=aBind}if(typeof aHandler!=="function"){throw new nokia.aduno.utils.ArgumentError("Missing handler function.")}if((typeof aBind!=="object")||(aBind===null)){aBind=this}var timer=function(){aHandler.apply(aBind,splat(aParams))};if(aIsTimeout){return window.setTimeout(timer,aPeriod)}return window.setInterval(timer,aPeriod)};var setPeriodical=function(aInterval,aBind,aHandler,aParams){return _addTimer(false,aInterval,aBind,aHandler,aParams)};var cancelPeriodical=function(aId){window.clearInterval(aId)};var setTimer=function(aDelay,aBind,aHandler,aParams){return _addTimer(true,aDelay,aBind,aHandler,aParams)};var cancelTimer=function(aId){window.clearTimeout(aId)};var _userAgent=navigator.userAgent.toLowerCase();var platform={windows:/Windows/.test(navigator.appVersion),mac:/MacIntel/.test(navigator.platform),linux:/X11/.test(navigator.appVersion)&&!(/tablet/.test(_userAgent))&&!(/armv7/.test(_userAgent)),maemo:(/armv7/.test(_userAgent))||(/tablet/.test(_userAgent)),s60_v3:/Series60\/3/.test(navigator.appVersion),s60_v5_touch:/Nokia5800|NokiaN97/.test(navigator.appVersion),s60_v5_snc:false};var browser={dom:String(document.appendChild).replace(/\s+/g,"")=="functionappendChild(){[nativecode]}",version:(_userAgent.match(/.+(?:rv|it|ra|ie)[\/: ]([\d.]+)/)||[])[1],safari:/safari/i.test(navigator.appVersion)&&(!(/SymbianOS/.test(navigator.appVersion))),opera:/opera/.test(_userAgent),msie:
/*@cc_on!@*/
!1,mozilla:/mozilla/.test(_userAgent)&&!(/(compatible|webkit)/.test(_userAgent)),s60:/series60/.test(_userAgent),s60_v3:platform.s60_v3,snc:platform.s60_v3||platform.s60_v5_snc,touch:platform.maemo||platform.s60_v5_touch,language:navigator.language||navigator.userLanguage};var throwError=function(aErrorClass,aMessage){throw new aErrorClass(aMessage)};var ArgumentError=function(aMessage){Error.call(this,aMessage);this.message=aMessage;this.name="ArgumentError"};ArgumentError.prototype=new Error();ArgumentError.prototype.constructor=ArgumentError;var UnsupportedError=function(aMessage){Error.call(this,aMessage);this.message=aMessage;this.name="UnsupportedError"};UnsupportedError.prototype=new Error();UnsupportedError.prototype.constructor=UnsupportedError;var AbstractMethodError=function(){var message="";if(arguments.length==1){message=arguments[0]}else{if(arguments.length>2){var className=arguments[0];var func=arguments[1];message=className+" does not override "+func}}Error.call(this,message);this.message=message;this.name="AbstractMethodError"};AbstractMethodError.prototype=new Error();AbstractMethodError.prototype.constructor=AbstractMethodError;var bind=function(aBind,aFunctor,aParameters){var bindArgs=splat(aParameters);return(function(){var args=[];args=args.concat(bindArgs);for(var i=0,len=arguments.length;i<len;++i){args=args.concat(arguments[i])}return aFunctor.apply(aBind,args)})};var getTimeStamp=function(){if(typeof Date.now==="function"){return Date.now()}else{return(new Date()).getTime()}};var generateId=function(aLength){aLength=Math.max(1,Math.min(256,aLength||20));var id="";while(id.length<aLength){id+=Math.round((Math.random()*10000000000000000)).toString(36)}return id.substr(0,aLength)};var _loggerUseCache=false;var _enableLogging=true;var _loggerCachePos=-1;var _loggerCacheSize=100;var _loggerCache=[];var _loggerLoggers=[];var _loggerFlushCache=function(aObject){var cache=_loggerCache;var len=_loggerCachePos+1;aObject.clearCache();for(var i=0;i<len;++i){aObject[cache[i].log](cache[i].msg)}};var _loggerCacheMsg=function(aMsg,aLogMember){if(_loggerUseCache){var msgObj={log:aLogMember,msg:aMsg};if(_loggerCachePos<(_loggerCacheSize-1)){_loggerCachePos++}else{_loggerCache.splice(0,1)}_loggerCache[_loggerCachePos]=msgObj}};var _logMsg=function(aMsg,aLogMember){if(_loggerUseCache&&(_loggerLoggers.length===0)){_loggerCacheMsg(aMsg,aLogMember);return}for(var i=_loggerLoggers.length-1;i>-1;--i){try{_loggerLoggers[i][aLogMember](aMsg)}catch(e){}}};var logger={isCacheEnabled:function(){return _loggerUseCache},enableCache:function(){_loggerUseCache=(_loggerCacheSize>0);return _loggerUseCache},disableCache:function(){_loggerUseCache=false},getCacheSize:function(){return _loggerCacheSize},setCacheSize:function(aSize){if(typeof aSize==="number"){_loggerCacheSize=(aSize>0)?aSize:0;_loggerUseCache=(aSize>0);if(_loggerCachePos>=_loggerCacheSize){_loggerCache.splice(0,_loggerCachePos+1-_loggerCacheSize);_loggerCachePos=_loggerCacheSize-1}}else{throw new ArgumentError("Invalid argument")}},clearCache:function(){_loggerCache=[];_loggerCachePos=-1},addLogger:function(aObject){if((aObject===null)||(typeof aObject!=="object")||(typeof aObject.debug!=="function")||(typeof aObject.info!=="function")||(typeof aObject.warn!=="function")||(typeof aObject.error!=="function")){throw new ArgumentError("Illegal logger object")}for(var i=_loggerLoggers.length-1;i>-1;--i){if(_loggerLoggers[i]===aObject){_logMsg("The logger is already attached","warn");return false}}if(typeof aObject.initLogger==="function"){aObject.initLogger()}_loggerLoggers.push(aObject);if(_loggerCachePos>-1){_loggerFlushCache(this)}return true},removeLogger:function(aObject){for(var i=_loggerLoggers.length-1;i>-1;--i){if(_loggerLoggers[i]===aObject){_loggerLoggers.splice(i,1);if(typeof aObject.cleanupLogger==="function"){aObject.cleanupLogger()}return true}}_logMsg("The passed logger wasn't attached","warn");return false},removeAllLoggers:function(){var loggers=_loggerLoggers;_loggerLoggers=[];for(var i=loggers.length-1;i>-1;--i){if(typeof loggers[i].cleanupLogger==="function"){try{loggers[i].cleanupLogger()}catch(e){}}}},isEnabled:function(){return _enableLogging},enable:function(){_enableLogging=true},disable:function(){_enableLogging=false},debug:function(aMsg){if(_enableLogging){_logMsg(aMsg,"debug")}},info:function(aMsg){if(_enableLogging){_logMsg(aMsg,"info")}},warn:function(aMsg){if(_enableLogging){_logMsg(aMsg,"warn")}},error:function(aMsg){if(_enableLogging){_logMsg(aMsg,"error")}}};var debug=logger.debug;var error=logger.error;var info=logger.info;var warn=logger.warn;var _noCaller=true;(function(){_noCaller=!arguments.callee.caller||browser.msie})();var _emptyFunction=function(){};var _classPerfectSuperFunction=function(){return arguments.callee.caller._superMethod.apply(this,arguments)};var _classSuperFunction=function(){var superCaller=this._superCaller;delete this._superCaller;return superCaller._superMethod.apply(this,arguments)};var _classWrapMethod=function(aMethod){return function(){var tmp=this._superCaller;this._superCaller=arguments.callee;var ret=aMethod.apply(this,arguments);this._superCaller=tmp;return ret}};var Class=function(aHash){aHash=aHash||{};if(this instanceof Class){var impl=splat(aHash.Implements);var key;var mixin;var initializers=[];for(var i=0,len=impl.length;i<len;++i){mixin=impl[i];if(typeof mixin=="function"){_emptyFunction.prototype=mixin.prototype;mixin=new _emptyFunction()}for(key in mixin){if(typeof mixin[key]=="function"){if(key!="initialize"){if(!aHash[key]){aHash[key]=mixin[key]}}else{initializers.push(mixin.initialize)}}}}var proto=null;var base=aHash.Extends;delete aHash.Extends;if(initializers.length>0){aHash._initMixins=function(){if(proto._initMixins._superMethod){proto._initMixins._superMethod.call(this)}for(var i=0,len=initializers.length;i<len;++i){initializers[i].call(this)}}}if(typeof base=="function"){_emptyFunction.prototype=base.prototype;proto=new _emptyFunction();for(key in aHash){if(proto[key]&&(typeof proto[key]=="function")&&(typeof aHash[key]=="function")){if(_noCaller){aHash[key]=_classWrapMethod(aHash[key])}aHash[key]._superMethod=proto[key]}proto[key]=aHash[key]}proto._super=(_noCaller)?_classSuperFunction:_classPerfectSuperFunction;proto._superClass=base}else{proto=aHash}if(aHash.Name!==undefined){proto.className=aHash.Name}delete proto.Name;var klass=function(){if(typeof this._initMixins=="function"){this._initMixins()}if(this.initialize){return this.initialize.apply(this,arguments)}else{return this}};klass.constructor=Class;klass.prototype=proto;klass.prototype.constructor=klass;klass.Name=proto.className;return klass}else{return new Class(aHash)}};try{if(typeof window.loadFirebugConsole==="function"){window.loadFirebugConsole()}}catch(e){}var _consoleLogger=null;var ConsoleLogger=function(){if(_consoleLogger!==null){return _consoleLogger}if(window&&window.console&&(/function/).test(window.console.log+"")){var that=this;for(var types=["info","debug","warn","error"],i=0,type;(type=types[i]);i++){(function(type){if(/function/.test(window.console[type]+"")){that[type]=function(aMsg){window.console[type](aMsg)}}else{that[type]=function(aMsg){window.console.log("["+type.toUpperCase()+"] "+aMsg)}}})(type)}}else{this.debug=this.info=this.warn=this.error=function(){}}return(_consoleLogger=this)};if(logger&&window&&window.console&&(/function/).test(window.console.log+"")){logger.addLogger(new ConsoleLogger())}var Collection=new Class({Name:"Collection",initialize:function(aIterable){this._iterable=aIterable},forEach:function(aEacher,aContext){return Collection.forEach(this._iterable,aEacher,aContext)},indexOf:function(aCompare,aFromIndex){return Collection.indexOf(this._iterable,aCompare,aFromIndex)},map:function(aMapper,aContext){return Collection.map(this._iterable,aMapper,aContext)},filter:function(aFilter,aContext){return Collection.filter(this._iterable,aFilter,aContext)},injectInto:function(aInject,aInjector,aContext){return Collection.injectInto(this._iterable,aInject,aInjector,aContext)},occurrencesOf:function(aChecker,aContext){return Collection.occurrencesOf(this._iterable,aChecker,aContext)},every:function(aChecker,aContext){return Collection.every(this._iterable,aChecker,aContext)},some:function(aChecker,aContext){return Collection.some(this._iterable,aChecker,aContext)},none:function(aChecker,aContext){return Collection.none(this._iterable,aChecker,aContext)},merge:function(aIterable){return Collection.merge(this._iterable,aIterable)}});Collection.NOT_FOUND=-1;Collection._asFunction=function(aObject){return typeof aObject==="function"?aObject:function(aValue){return aValue===aObject}};Collection._asNegatedFunction=function(aObject){return typeof aObject==="function"?function(aValue){return !aObject(aValue)}:function(aValue){return aValue!==aObject}};Collection.forEach=function(aIterable,aEacher,aContext){var type=nokia.aduno.utils.type(aIterable);var length,i;if(type==="array"){for(length=aIterable.length,i=0;i<length;i++){aEacher.call(aContext,aIterable[i],i,aIterable)}}else{if(type==="object"){for(i in aIterable){if(aIterable.hasOwnProperty(i)){aEacher.call(aContext,aIterable[i],i,aIterable)}}}}};Collection.indexOf=function(aIterable,aCompare,aFromIndex){var index=this.NOT_FOUND,length=aIterable.length,i=Math.max(aFromIndex||0,0),type=nokia.aduno.utils.type(aIterable),compare=this._asFunction(aCompare);if(type==="array"){for(;i<length;i++){if(compare(aIterable[i])){index=i;break}}}else{if(type==="object"){var filtered=aFromIndex!==undefined;for(i in aIterable){if(aIterable.hasOwnProperty(i)){if(filtered){if(i!=aFromIndex){continue}filtered=false}if(compare(aIterable[i])){index=i;break}}}}}return index};Collection.map=function(aIterable,aMapper,aContext){var mapped,eacher,type=nokia.aduno.utils.type(aIterable);if(type==="array"){mapped=[];eacher=function(value,key){mapped.push(aMapper.call(aContext,value,key,aIterable))}}else{if(type==="object"){mapped={};eacher=function(value,key){mapped[key]=aMapper.call(aContext,value,key,aIterable)}}}this.forEach(aIterable,eacher);return mapped};Collection.filter=function(aIterable,aFilter,aContext){aFilter=this._asFunction(aFilter);var filtered,eacher,type=nokia.aduno.utils.type(aIterable);if(type==="array"){filtered=[];eacher=function(value,key){if(aFilter.call(aContext,value,key,aIterable)){filtered.push(value)}}}else{if(type==="object"){filtered={};eacher=function(value,key){if(aFilter.call(aContext,value,key,aIterable)){filtered[key]=value}}}}this.forEach(aIterable,eacher);return filtered};Collection.injectInto=function(aIterable,aInject,aInjector,aContext){this.forEach(aIterable,function(aValue,aKey){aInject=aInjector.call(aContext,aInject,aValue,aKey,aIterable)});return aInject};Collection.occurrencesOf=function(aIterable,aChecker){aChecker=this._asFunction(aChecker);var occurences=0;this.each(aIterable,function(aValue,aKey){if(aChecker.call(aContext,aValue,aKey,aIterable)){occurences++}});return occurences};Collection.every=function(aIterable,aChecker){aChecker=this._asNegatedFunction(aChecker);return this.indexOf(aIterable,aChecker)===Collection.NOT_FOUND};Collection.some=function(aIterable,aChecker){return this.indexOf(aIterable,aChecker)!==Collection.NOT_FOUND};Collection.none=function(aIterable,aChecker){return this.indexOf(aIterable,aChecker)===Collection.NOT_FOUND};Collection.fromTo=function(aStartNumber,aEndNumber,aStepSize){var i,array=[];aStepSize=Math.abs(aStepSize||1);if(aStartNumber<aEndNumber){for(i=aStartNumber;i<=aEndNumber;i+=aStepSize){array.push(i)}}else{for(i=aStartNumber;i>=aEndNumber;i-=aStepSize){array.push(i)}}return new Collection(array)};Collection.merge=function(aIterable1,aIterable2){if(!aIterable1){return aIterable2}if(!aIterable2){return aIterable1}var type1=nokia.aduno.utils.type(aIterable1);var type2=nokia.aduno.utils.type(aIterable2);if(type1!=type2){throw new ArgumentError("Collections to merge must be of the same type. "+type1+" != "+type2)}if(type1==="array"){return aIterable1.concat(aIterable2)}else{if(type1==="object"){var rval={};function merger(aValue,aKey){rval[aKey]=aValue}Collection.forEach(aIterable1,merger);Collection.forEach(aIterable2,merger);return rval}}};var Options={initialize:function(){this._defaultOptions=(this._superClass&&this._superClass.prototype&&this._superClass.prototype.options&&(typeof this._superClass.prototype.options==="object"))?this._superClass.prototype.options:this.options;if(this.options&&(this._defaultOptions!==this.options)){for(var i in this.options){this._defaultOptions[i]=this.options[i]}}this._options={};Collection.map(this._defaultOptions,function(aValue,aKey){this._options[aKey]=aValue},this)},setOptions:function(aOptionsHash){if(typeof aOptionsHash=="object"){Collection.map(aOptionsHash,function(aValue,aKey){if(this._defaultOptions===undefined||aKey in this._defaultOptions){this._options[aKey]=aValue}},this)}},getOption:function(aKey){if(aKey in this._options){return this._options[aKey]}else{throw new ReferenceError("No option for key: "+aKey)}},hasOption:function(aKey){return(aKey in this._options)?true:false}};var Event=new Class({Name:"Event",initialize:function(aType,aData,aIsCancelable){this.type=String(aType);if(arguments.length>1){this.data=aData;if(aIsCancelable){this._isCancelable=true}}},_isCancelable:false,_preventDefault:false,isCancelable:function(){return this._isCancelable},preventDefault:function(){if(this._isCancelable){return(this._preventDefault=true)}else{nokia.aduno.utils.logger.warn("preventDefault() rejected: Event '"+this.type+"' not cancelable");return false}},isPreventDefault:function(){return this._preventDefault},getSource:function(){nokia.aduno.utils.warn("DEPRECATED nokia.aduno.utils.Event.getSource is used, use nokia.aduno.utils.Event.source instead");return this.source},getType:function(){nokia.aduno.utils.warn("DEPRECATED nokia.aduno.utils.Event.getType is used, use nokia.aduno.utils.Event.type instead");return this.type},getData:function(){if(this.data===undefined){this.data={}}return this.data}});var EventSource={addEventHandler:function(aType,aHandler,aContext){if(typeof aHandler!=="function"){throw new ArgumentError("Trying to use addEventHandler for '"+aType+"': aHandler is not a function")}var handlerList=this._getHandlerList(aType);if(this._indexOfEventHandler(handlerList,aHandler,aContext)>=0){nokia.aduno.utils.logger.warn('EventSource addEventHandler("'+aType+'") rejected: type/handler/context combination already registered.');return false}else{handlerList=handlerList||this._getHandlerList(aType,true);handlerList.push({_handler:aHandler,_context:aContext});return true}},removeEventHandler:function(aType,aHandler,aContext){var handlerList=this._getHandlerList(aType);var index=this._indexOfEventHandler(handlerList,aHandler,aContext);if(index<0){nokia.aduno.utils.logger.warn('EventSource removeEventHandler("'+aType+'") rejected: type/handler/context combination not registered.');return false}else{if(handlerList.length===1){delete this._eventHandlersMap[aType]}else{handlerList.splice(index,1)}return true}},fireEvent:function(aEvent){if(typeof aEvent==="string"){aEvent=new nokia.aduno.utils.Event(aEvent)}if((typeof aEvent.isCancelable!=="function")||(typeof aEvent.getData!=="function")){nokia.aduno.utils.warn("EventSource fireEvent - method called with DOM event as argument");return this}this._handleEvent(aEvent);return this},setParentEventSource:function(aParentEventSource){this._parentEventSource=aParentEventSource},_getHandlerList:function(aType,create){if(create){this._eventHandlersMap=this._eventHandlersMap||{};if(!this._eventHandlersMap[aType]){this._eventHandlersMap[aType]=[]}return this._eventHandlersMap[aType]}else{return this._eventHandlersMap?this._eventHandlersMap[aType]:null}},_indexOfEventHandler:function(aHandlerList,aHandler,aContext){if(aHandlerList){var i=0,length=aHandlerList.length,handler;for(;i<length;i++){handler=aHandlerList[i];if(handler._handler===aHandler&&handler._context===aContext){return i}}}return -1},_handleEvent:function(aEvent){var handlerList=this._getHandlerList(aEvent.type);var error=null;var cachedType=aEvent.type;if(handlerList){var handlerListSnapshot=handlerList.slice(0);var i=0,length=handlerListSnapshot.length,handler;for(;i<length;i++){handler=handlerListSnapshot[i];aEvent.source=this;aEvent.type=cachedType;try{handler._handler.call(handler._context,aEvent)}catch(e){error=error?error.push(e):[e];nokia.aduno.utils.error(e.name+" for event '"+aEvent.type+"' on an instance of "+this.className+": "+e.message+"\nErroneous handler: "+((typeof handler._handler=="function")?handler._handler.toString().substr(0,255):" not a function"))}}}if(this._parentEventSource){this._parentEventSource.fireEvent(aEvent)}}};var CssLoader=new Class({initialize:function(aOptions){var doc=(aOptions.window)?aOptions.window.document:document;var he=doc.getElementsByTagName("head")[0];this._node=doc.createElement("link");this._node.rel="stylesheet";this._node.type="text/css";this._node.href=aOptions.uri;he.appendChild(this._node);if(typeof aOptions.handler=="function"){aOptions.handler.call(aOptions.bind||this,aOptions.params)}},getNode:function(){return this._node}});var ScriptLoader=new Class({initialize:function(aOptions){var doc=(aOptions.window)?aOptions.window.document:document;var he=doc.getElementsByTagName("head")[0];var myself=this;this._node=doc.createElement("script");this._node.type="text/javascript";if(typeof aOptions.handler=="function"){this._node.onload=this._node.onreadystatechange=function(){if(!this.readyState||this.readyState=="loaded"||this.readyState=="complete"){aOptions.handler.call(aOptions.bind||myself,aOptions.params)}}}this._node.src=aOptions.uri;he.appendChild(this._node)},getNode:function(){return this._node}});var Observable=new Class({Name:"Observable",initialize:function(){this._observers=[]},addObserver:function(aObserver){if(this._indexOfObserver(this._observers,aObserver)===-1){this._observers.push(aObserver)}return this},removeObserver:function(aObserver){var index=this._indexOfObserver(this._observers,aObserver);if(index!==-1){this._observers.splice(index,1)}return this},removeAllObservers:function(){this._observers.splice(0);return this},_notifyAdded:function(aObject){this._notifyObservers("_objectAdded",aObject)},_notifyRemoved:function(aObject){this._notifyObservers("_objectRemoved",aObject)},_notifyUpdated:function(aObject){this._notifyObservers("_objectUpdated",aObject)},_indexOfObserver:function(aArray,aObject){for(var i=0,il=aArray.length;i<il;i++){if(aObject===aArray[i]){return i}}return -1},_notifyObservers:function(aMessage,aArgument){for(var il=this._observers.length,i=0;i<il;i++){if(typeof this._observers[i][aMessage]==="function"){this._observers[i][aMessage].apply(this._observers[i],[aArgument,this])}}}});var ListModel=new Class({Name:"ListModel",Implements:Observable,initialize:function(aArray){this._list=[];this._observers=[];if(aArray){this.addAll(aArray)}},add:function(aObject){this._list.push(aObject);this._notifyAdded(aObject);return this},addAll:function(aArray){for(var i=0,il=aArray.length;i<il;i++){this.add(aArray[i])}return this},remove:function(aObject){var index=this._indexOf(this._list,aObject);if(index!==-1){this._list.splice(index,1);this._notifyRemoved(aObject)}},removeAll:function(){for(var i=this._list.length-1;i>=0;i--){this.remove(this._list[i])}},replaceAll:function(aArray){this.removeAll();this._list=aArray;for(var i=0,il=aArray.length;i<il;i++){this._notifyAdded(aArray[i])}return this},update:function(aObject){var index=this._indexOf(this._list,aObject);if(index!==-1){this._notifyUpdated(aObject)}return this},updateAll:function(){var length=this._list.length;for(var i=0;i<length;i++){this._notifyUpdated(this._list[i])}return this},indexOf:function(aObject){return this._indexOf(this._list,aObject)},_indexOf:function(aArray,aObject){var length=aArray.length;for(var i=0;i<length;i++){if(aObject===aArray[i]){return i}}return -1},getAll:function(){return this._list.slice(0)},find:function(aData){var item,isMatch;var foundItem=null;var length=this._list.length;for(var i=0;i<length;i++){item=this._list[i];if(this._findInObject(this._list[i],aData)){return this._list[i]}}return null},_findInObject:function(aObject,aSearch){for(var key in aSearch){if(aSearch.hasOwnProperty(key)){if(nokia.aduno.utils.type(aObject[key])=="object"&&nokia.aduno.utils.type(aSearch[key])=="object"){if(!this._findInObject(aObject[key],aSearch[key])){return false}}else{if(aObject[key]!=aSearch[key]){return false}}}}return true}});var AssociationList=new Class({Name:"AssociationList",initialize:function(){this._associations=[];this._items=[]},set:function(aAssociation,aItem){if(aAssociation){var i=nokia.aduno.utils.Collection.indexOf(this._associations,aAssociation);if(i>=0){this._items[i]=aItem}else{i=this._associations.push(aAssociation);this._items[i-1]=aItem}}else{nokia.aduno.utils.error(this.className+".add: No association given.")}return this},get:function(aAssociation){var i=nokia.aduno.utils.Collection.indexOf(this._associations,aAssociation);if(i>=0){return this._items[i]}return null},remove:function(aAssociation){var item=null;var i=nokia.aduno.utils.Collection.indexOf(this._associations,aAssociation);if(i>=0){item=this._items[i];this._associations.splice(i,1);this._items.splice(i,1)}return item},removeAll:function(){this._associations=[];this._items=[];return this},size:function(){return this._associations.length},contains:function(aAssociation){return nokia.aduno.utils.Collection.indexOf(this._associations,aAssociation)>=0},getAssociations:function(){return this._associations.slice(0)},getItems:function(){return this._items.slice(0)}});nokia.aduno.utils.addMembers({type:type,inspect:inspect,splat:splat,setPeriodical:setPeriodical,cancelPeriodical:cancelPeriodical,setTimer:setTimer,cancelTimer:cancelTimer,platform:platform,browser:browser,throwError:throwError,ArgumentError:ArgumentError,UnsupportedError:UnsupportedError,AbstractMethodError:AbstractMethodError,bind:bind,getTimeStamp:getTimeStamp,extend:extend,clone:clone,generateId:generateId,logger:logger,debug:debug,error:error,info:info,warn:warn,Class:Class,ConsoleLogger:ConsoleLogger,Collection:Collection,Options:Options,Event:Event,EventSource:EventSource,CssLoader:CssLoader,ScriptLoader:ScriptLoader,Observable:Observable,ListModel:ListModel,AssociationList:AssociationList})};new function(){new nokia.aduno.Ns("nokia.aduno.dom");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var bindWithEvent=function(aBind,aFunctor){return(function(evt){var doc=this.document||this.ownerDocument||this;if(doc.defaultView||doc.parentWindow){var win=doc.defaultView||doc.parentWindow;var ev=new Event(evt||win.event,doc,win);return aFunctor.call(aBind,ev)}else{throw new TypeError("bindWithEvent used for a non-event")}})};var addCssClass=function(aHtmlNode,aCssClassName){if(aHtmlNode.className.indexOf(aCssClassName)===-1){aHtmlNode.className=(aHtmlNode.className||"");aHtmlNode.className=aHtmlNode.className+((aHtmlNode.className.length>0)?" ":"")+aCssClassName}return aHtmlNode.className};var removeCssClass=function(aHtmlNode,aCssClassName){var classesOut=aHtmlNode.className.split(" ");for(var i=classesOut.length-1;i>=0;i--){if(aCssClassName===classesOut[i]){classesOut.splice(i,1)}}aHtmlNode.className=classesOut.join(" ");return aHtmlNode.className};(function(){if(!nokia.aduno.dom.ELEMENT_NODE){var nodeIdx=1;nokia.aduno.utils.Collection.forEach(("ELEMENT,ATTRIBUTE,TEXT,CDATA_SECTION,ENTITY_REFERENCE,ENTITY,PROCESSING_INSTRUCTION,COMMENT,DOCUMENT,DOCUMENT_TYPE,DOCUMENT,NOTATION").split(","),function(aValue){nokia.aduno.dom[aValue+"_NODE"]=nodeIdx++})}})();var importNodeIe=function(aDocument,aNode){switch(aNode.nodeType){case nokia.aduno.dom.ELEMENT_NODE:var newNode=aDocument.createElement(aNode.nodeName);var attributeValue,attributeName;if(aNode.attributes&&aNode.attributes.length>0){for(var i=0,il=aNode.attributes.length;i<il;i++){attributeName=aNode.attributes[i].nodeName;attributeValue=aNode.getAttribute(aNode.attributes[i].nodeName);if(attributeName.toLowerCase()=="style"){(new XNode(newNode)).setStyle(attributeValue)}else{if(attributeName.toLowerCase()=="class"){(new XNode(newNode)).addCssClass(attributeValue)}else{newNode.setAttribute(attributeName,attributeValue)}}}}if(aNode.childNodes&&aNode.childNodes.length>0){for(var j=0,jl=aNode.childNodes.length;j<jl;j++){newNode.appendChild(importNodeIe(aDocument,aNode.childNodes[j]))}}return newNode;case nokia.aduno.dom.TEXT_NODE:case nokia.aduno.dom.CDATA_SECTION_NODE:case nokia.aduno.dom.COMMENT_NODE:return aDocument.createTextNode(aNode.nodeValue);default:return aDocument.createTextNode(aNode.nodeValue)}return null};var importNode=function(aDocument,aNode){if(aDocument.importNode){return aDocument.importNode(aNode,true)}else{return importNodeIe(aDocument,aNode)}};var getCssStyleNameAsCamelCase=function(aString){return aString=="float"?"cssFloat":aString.replace(/-\D/g,function(match){return match.charAt(1).toUpperCase()})};var getJavaScriptStyleNameAsHyphenated=function(aString){return aString.replace(/[A-Z]/g,function(match){return("-"+match.charAt(0).toLowerCase())})};var convertColorHexToRgb=function(aHexValue){if(!aHexValue){throw new ArgumentError("Fx._convertColorHexToRgb: aHexValue must be defined.")}var rgb=[];var matches=new RegExp("([0-9A-F]{2})([0-9A-F]{2})([0-9A-F]{2})").exec(aHexValue);var i;if(matches!==null){for(i=1;i<matches.length;i++){rgb.push(parseInt(matches[i],16))}return rgb}matches=new RegExp("([0-9A-F])([0-9A-F])([0-9A-F])").exec(aHexValue);if(matches!==null){for(i=1;i<matches.length;i++){rgb.push(parseInt(matches[i]+""+matches[i],16))}return rgb}throw new ArgumentError("convertColorHexToRgb: could not convert to rgb array: "+aHexValue)};var convertColorRgbToHex=function(){var rgbArray;if(arguments.length===1&&type(arguments[0])==="array"){rgbArray=arguments[0]}else{if(arguments.length===3){rgbArray=arguments}else{throw new ArgumentError("convertColorRgbToHex: arguments must be an array of colors or three colors")}}var hex="";for(var i=0;i<rgbArray.length;i++){var val=parseInt(rgbArray[i],10).toString(16);hex+=(val.length==2)?val:("0"+val)}return hex};var getChildIndex=function(aNode){var index=-1;if(aNode.parentNode){do{index++}while((aNode=aNode.previousSibling))}return index};var SimplePath=new nokia.aduno.utils.Class({Name:"SimplePath",initialize:function(aNode,aBaseNode){aBaseNode=aBaseNode||aNode.ownerDocument||aNode;this._path=[];while(aNode&&aNode!==aBaseNode){this._path.unshift(getChildIndex(aNode));aNode=aNode.parentNode}this._path=(aNode===aBaseNode)?this._path:null},evaluate:function(aNode){for(var len=this._path.length,i=0;i<len;i++){aNode=aNode.childNodes[this._path[i]]}return aNode}});var Parser=new nokia.aduno.utils.Class({initialize:function(){return this.constructor._singleton||(this.constructor._singleton=this)},parse:function(aText){var xmlDoc,parserError;if(window.DOMParser){this._parser=this._parser||new DOMParser();xmlDoc=this._parser.parseFromString(aText,"text/xml");if([xmlDoc.documentElement,xmlDoc.documentElement.firstChild,xmlDoc.body&&xmlDoc.getElementsByTagName("parsererror")[0]].filter(function(el){return el&&el.nodeName==="parsererror"}).length){var parserErrorEl=xmlDoc.getElementsByTagName("parsererror")[0];parserError=(parserErrorEl.childNodes[0].nodeType===3?parserErrorEl.childNodes[0].nodeValue+"\n":"")+parserErrorEl.childNodes[1].firstChild.nodeValue}}else{if(window.ActiveXObject){xmlDoc=new ActiveXObject("Microsoft.XMLDOM");xmlDoc.async=false;xmlDoc.resolveExternals=false;xmlDoc.validateOnParse=false;xmlDoc.loadXML(aText);if(xmlDoc.parseError.errorCode){parserError="error on line "+xmlDoc.parseError.line+": "+xmlDoc.parseError.reason}}}if(parserError){var ParserError=function(message){Error.call(this,message);this.message=message;this.name="ParserError"};throw new ParserError(parserError)}return xmlDoc||null}});var XHtmlParser=new nokia.aduno.utils.Class({initialize:function(){return this.constructor._singleton||(this.constructor._singleton=this)},parse:function(aText){var xmlDoc=(new Parser()).parse(['<nokia xmlns="http://www.w3.org/1999/xhtml">',aText,"</nokia>"].join(""));if(!xmlDoc){this._parseContainer=this._parseContainer||document.createElement("div");this._parseContainer.innerHTML=aText;var html=this._parseContainer}var root=xmlDoc&&xmlDoc.documentElement||html;return root.removeChild(root.firstChild)}});var Template=new Class({Name:"Template",initialize:function(aXHtmlMarkup){this._markup=String(aXHtmlMarkup)},replicate:function(aDocument){var idMap=Collection.map(this._getIdentifiableElementsMap(),this._identifiableElementsMapCopier);return new TemplateReplica(importNode(aDocument||document,this._getMaster()),idMap)},_identifiableElementsMapCopier:function(value){return{path:value.path,node:null}},_parseContainer:document.createElement("div"),_getMaster:function(){if(!this._master){this._master=new XHtmlParser().parse(this._markup)}return this._master},_collectNodesWithId:function(aNode,aNodeList){if(aNode.nodeType!==3&&aNode.getAttribute("id")){aNodeList.push(aNode)}var children=aNode.childNodes;for(var i=0,length=children.length;i<length;i++){var cur=children[i];if(cur.nodeType===nokia.aduno.dom.ELEMENT_NODE){this._collectNodesWithId(cur,aNodeList)}}},_identifiableElementsMap:null,_getIdentifiableElementsMap:function(){if(!this._identifiableElementsMap){var master=this._getMaster();var elements=[];this._collectNodesWithId(master,elements);this._identifiableElementsMap={};for(var i=elements.length-1;i>=0;i--){var element=elements[i];this._identifiableElementsMap[element.getAttribute("id")]={path:new SimplePath(element,master),node:null};element.removeAttribute("id")}}return this._identifiableElementsMap}});var TemplateReplica=new nokia.aduno.utils.Class({Name:"TemplateReplica",initialize:function(replicaElement,identifiableElementsMap){this._replicaElement=replicaElement;this._xnode=new XNode(this._replicaElement);this._identifiableElementsMap=identifiableElementsMap;this._eventHandlers={}},hasDOMSupport:function(){return true},getElement:function(aId){if(aId===TemplateReplica.ROOT_ID){return this._replicaElement}var mapItem=this._identifiableElementsMap[aId];if(!mapItem){return null}if(mapItem.path&&!mapItem.node){mapItem.node=mapItem.path.evaluate(this._replicaElement)}if(!mapItem.node){throw new Error("ID "+aId+" could not be evaluated.")}return mapItem.node},replaceElement:function(aId,aNode){var mapItem=this._identifiableElementsMap[aId];var replaced=null;if(!mapItem){return null}if(mapItem.path&&!mapItem.node){mapItem.node=mapItem.path.evaluate(this._replicaElement)}if(mapItem.node){if(mapItem.node.parentNode){replaced=mapItem.node.parentNode.replaceChild(aNode,mapItem.node);mapItem.node=aNode}else{warn("TemplateReplica: Cannot replace ID '"+aId+"' since it does not have a parent.");return null}}else{throw new Error("TemplateReplica: ID "+aId+" could not be evaluated in replaceElement.")}this._identifiableElementsMap[aId]=mapItem;return replaced},setAttribute:function(aId,attributeName,attributeValue){var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}try{if(attributeName.toLowerCase()=="style"){(new XNode(element)).setStyle(attributeValue)}else{element.setAttribute(attributeName,attributeValue)}}catch(e){throw new Error("Error "+e.message+" while setting attribute "+attributeName+" on id "+aId)}return this},getAttribute:function(aId,aAttributeName){var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}return element.getAttribute(aAttributeName)},removeAttribute:function(aId,aAttributeName){var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}element.removeAttribute(aAttributeName);return this},setValue:function(aId,aValue){var node=this.getElement(aId);if(!node){throw new ArgumentError("ID "+aId+" is not known.")}if(node.value===undefined){throw new TypeError('No support for property "value" on given node')}node.value=aValue;return this},getValue:function(aId){var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}return element.value},setText:function(aId,aText){var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}if(element.tagName.toLowerCase()==="input"){element.value=aText;return this}if(element.getElementsByTagName("*").length){throw new ArgumentError("Node with ID "+aId+" has child elements, setting the node text would erase them")}var child;while(null!==(child=element.firstChild)){element.removeChild(child)}try{element.appendChild(element.ownerDocument.createTextNode(String(aText)))}catch(e){throw new Error("Error "+e.message+" while setting text on id "+aId)}return this},getText:function(aId){var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}if(element.tagName.toLowerCase()==="input"){return element.value||""}return element.textContent||element.innerText||""},addCssClass:function(aId,aCssClassName){var element;if(!aCssClassName){element=this.getRootElement();aCssClassName=aId}else{element=this.getElement(aId)}if(!element){throw new ArgumentError("ID "+aId+" is not known.")}var classesToAdd=aCssClassName.split(" ");for(var i=classesToAdd.length-1;i>=0;--i){if(classesToAdd[i]){try{addCssClass(element,classesToAdd[i])}catch(e){throw new Error("Error "+e.message+" while adding CSS class "+classesToAdd[i]+" on id "+aId)}}}return this},removeCssClass:function(aId,aCssClassName){var element;if(!aCssClassName){element=this.getRootElement();aCssClassName=aId}else{element=this.getElement(aId)}if(!element){throw new ArgumentError("ID "+aId+" is not known.")}var classesToRemove=aCssClassName.split(" ");var cssClasses=[];for(var i=classesToRemove.length-1;i>=0;--i){if(classesToRemove[i]){try{removeCssClass(element,classesToRemove[i])}catch(e){throw new Error("Error "+e.message+" while removing CSS class "+classesToRemove[i]+" on id "+aId)}}}return this},setInnerHtml:function(aId,innerHtml){var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}try{element.innerHTML=innerHtml}catch(e){throw new Error("Error "+e+" while setting innerHtml to element "+aId)}},getInnerHtml:function(aId){var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}return element.innerHTML},getRootElement:function(){return this._replicaElement},addEventHandler:function(aId,aEventName,aBind,aHandler){if(arguments.length===3){aHandler=aBind;aBind=aEventName;aEventName=aId;aId=TemplateReplica.ROOT_ID}var domHandler=nokia.aduno.dom.bindWithEvent(aBind,aHandler);if(aId===TemplateReplica.ROOT_ID){this._xnode.addEventHandler(aEventName,domHandler)}else{var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}(new XNode(element)).addEventHandler(aEventName,domHandler)}this._eventHandlers[aId]=this._eventHandlers[aId]||{};this._eventHandlers[aId].handler=this._eventHandlers[aId].handler||[];this._eventHandlers[aId].handler.push([aEventName,aHandler,domHandler]);return aHandler},removeEventHandler:function(aId,aEventName,aHandler){if(arguments.length===2){aHandler=aEventName;aEventName=aId;aId=TemplateReplica.ROOT_ID}if(this._eventHandlers[aId]&&this._eventHandlers[aId].handler){var handler,handlers=this._eventHandlers[aId].handler;for(var i=handlers.length-1;i>-1;--i){handler=handlers[i];if((handler[0]===aEventName)&&(handler[1]===aHandler)){this._eventHandlers[aId].handler.splice(i,1);if(aId===TemplateReplica.ROOT_ID){this._xnode.removeEventHandler(aEventName,handler[2])}else{var element=this.getElement(aId);if(!element){throw new ArgumentError("ID "+aId+" is not known.")}(new XNode(element)).removeEventHandler(aEventName,handler[2])}return handler[1]}}}return null},setStyle:function(aId,aStyleName,aStyleValue){this.getElement(aId).style[getCssStyleNameAsCamelCase(aStyleName)]=aStyleValue;return this},removeStyle:function(aId,aStyle){this.getElement(aId).style[getCssStyleNameAsCamelCase(aStyle)]="";return this},getStyle:function(aId,aStyleName){var value=this.getElement(aId).style[getCssStyleNameAsCamelCase(aStyleName)];return nokia.aduno.utils.browser.msie&&aStyleName.indexOf("color")>-1?"rgb("+parseInt(value.slice(1,3),16)+", "+parseInt(value.slice(3,5),16)+", "+parseInt(value.slice(5),16)+")":value}});TemplateReplica.ROOT_ID="___root";var TemplateLibrary=new Class({Name:"TemplateLibrary",initialize:function(aTemplateMap,aLibraryPrototype){this._templateMap={};this.addTemplates(aTemplateMap);if(aLibraryPrototype){if(aLibraryPrototype instanceof TemplateLibrary){this._libraryPrototype=aLibraryPrototype}else{throw new ArgumentError("aLibraryPrototype not instance of TemplateLibrary")}}},addTemplate:function(aKey,aTemplate){if(!(aTemplate instanceof Template)){aTemplate=new Template(aTemplate)}this._templateMap[aKey]=aTemplate;return this._templateMap[aKey]},addTemplates:function(aTemplateMap){Collection.forEach(aTemplateMap,this._addTemplatesEacher,this)},_addTemplatesEacher:function(aValue,aKey){this.addTemplate(aKey,aValue)},removeTemplate:function(aKey){var template=this._templateMap[aKey];return(delete this._templateMap[aKey])?template:null},getTemplate:function(aKey){var template;if((typeof this._templateMap[aKey]!=="undefined")&&this._templateMap.hasOwnProperty(aKey)){template=this._templateMap[aKey]}else{if(this._libraryPrototype){template=this._libraryPrototype.getTemplate(aKey)}}return template||null},replicate:function(aKey,aDocument){var template=this.getTemplate(aKey);return template?template.replicate(aDocument):null}});var XNode=new nokia.aduno.utils.Class({Name:"XNode",initialize:function(aDomNode){if(aDomNode.constructor===XNode){return aDomNode}else{this.node=aDomNode;return this}},addEventHandler:function(aEventName,aHandler){if(aEventName===nokia.aduno.dom.XNode.DOM_MOUSE_SCROLL){return this._addMouseWheelHandler(aHandler)}if(this.node.addEventListener){if(XNode._DOM_EVENTS_FIX[aEventName]){((this._handlers=this._handlers||{})[aEventName]||(this._handlers[aEventName]=[])).push([aHandler,XNode._mouseEnter(aHandler)]);this.node.addEventListener(XNode._DOM_EVENTS_FIX[aEventName],this._handlers[aEventName][this._handlers[aEventName].length-1][1],false)}else{this.node.addEventListener(aEventName,aHandler,false)}}else{if(this.node.attachEvent){aEventName="on"+aEventName;this.node.detachEvent(aEventName,aHandler);this.node.attachEvent(aEventName,aHandler)}}return this},addLongClickHandler:function(aDelay,aHandler,aContext){var timerId;if(!this._handlers){this._handlers=[]}var downHandler=nokia.aduno.dom.bindWithEvent(this,function(aEvent){timerId=nokia.aduno.utils.setTimer(aDelay,this,function(){aHandler.call(aContext,aEvent)})});(this._handlers[XNode.DOM_MOUSE_DOWN]||(this._handlers[XNode.DOM_MOUSE_DOWN]=[])).push([aHandler,downHandler]);this.addEventHandler(XNode.DOM_MOUSE_DOWN,downHandler);var upHandler=nokia.aduno.dom.bindWithEvent(this,function(aEvent){nokia.aduno.utils.cancelTimer(timerId)});(this._handlers[XNode.DOM_MOUSE_UP]||(this._handlers[XNode.DOM_MOUSE_UP]=[])).push([aHandler,upHandler]);this.addEventHandler(XNode.DOM_MOUSE_UP,upHandler)},removeLongClickHandler:function(aHandler){for(var eventName in XNode._DOM_EVENTS_LONGCLICK){for(var i=0,cached;(cached=this._handlers[eventName][i]);i++){if(cached[0]===aHandler){this.removeEventHandler(eventName,cached[1]);break}}this._handlers[eventName].splice(i,1)}},_addMouseWheelHandler:function(aHandler){if(this.node.addEventListener){this.node.addEventListener(nokia.aduno.utils.browser.safari?"mousewheel":XNode.DOM_MOUSE_SCROLL,aHandler,false)}else{if(this.node.attachEvent){var eventName="onmousewheel";this.node.detachEvent(eventName,aHandler);this.node.attachEvent(eventName,aHandler)}}return this},removeEventHandler:function(aEventName,aHandler){if(aEventName===nokia.aduno.dom.XNode.DOM_MOUSE_SCROLL){return this._removeMouseWheelHandler(aHandler)}if(this.node.removeEventListener){if(XNode._DOM_EVENTS_FIX[aEventName]){for(var i=0,cached;(cached=this._handlers[aEventName][i]);i++){if(cached[0]===aHandler){this.node.removeEventListener(XNode._DOM_EVENTS_FIX[aEventName],cached[1],false);break}}this._handlers[aEventName].splice(i,1)}else{this.node.removeEventListener(aEventName,aHandler,false)}}else{if(this.node.detachEvent){this.node.detachEvent("on"+aEventName,aHandler)}}return this},_removeMouseWheelHandler:function(aHandler){if(this.node.addEventListener){this.node.removeEventListener(nokia.aduno.utils.browser.safari?"mousewheel":XNode.DOM_MOUSE_SCROLL,aHandler,false)}else{if(this.node.detachEvent){this.node.detachEvent("onmousewheel",aHandler)}}return this},isEqual:function(aXNode){return this.node===aXNode.node},setStyle:function(aStyleValue){XNode.setStyle(this.node,aStyleValue);return this},addCssClass:function(aCssClassName){XNode.addCssClass(this.node,aCssClassName);return this},removeCssClass:function(aCssClassName){XNode.removeCssClass(this.node,aCssClassName);return this}});XNode.DOM_CLICK="click";XNode.DOM_DRAG="drag";XNode.DOM_SCROLL="scroll";XNode.DOM_SELECT_START="selectstart";XNode.DOM_MOUSE_DOWN="mousedown";XNode.DOM_MOUSE_MOVE="mousemove";XNode.DOM_MOUSE_OUT="mouseout";XNode.DOM_MOUSE_OVER="mouseover";XNode.DOM_MOUSEENTER="mouseenter";XNode.DOM_MOUSELEAVE="mouseleave";XNode.DOM_MOUSE_SCROLL="DOMMouseScroll";XNode.DOM_MOUSE_UP="mouseup";XNode.DOM_FOCUS="focus";XNode.DOM_BLUR="blur";XNode.DOM_RESIZE="resize";XNode.DOM_UNLOAD="unload";XNode.DOM_LONGCLICK="longclick";XNode._DOM_EVENTS_LONGCLICK={};XNode._DOM_EVENTS_LONGCLICK[XNode.DOM_MOUSE_DOWN]=XNode.DOM_MOUSE_DOWN;XNode._DOM_EVENTS_LONGCLICK[XNode.DOM_MOUSE_UP]=XNode.DOM_MOUSE_UP;XNode.removeCssClass=function(aNode,aCssClassName){var regExp=new RegExp("(^|\\s)\\s*"+aCssClassName+"\\s*($|\\s)","g");aNode.className=aNode.className.replace(regExp,"$1");return aNode};XNode.addCssClass=function(aNode,aCssClassName){var regExp=new RegExp("(^|\\s)"+aCssClassName+"($|\\s)");if(!regExp.test(aNode.className)){aNode.className=(aNode.className||"")+(" "+aCssClassName)}return aNode};XNode.setStyle=function(aNode,aStyleValue){aNode.style.cssText=aStyleValue;return aNode};XNode._DOM_EVENTS_FIX={};XNode._DOM_EVENTS_FIX[XNode.DOM_MOUSEENTER]=XNode.DOM_MOUSE_OVER;XNode._DOM_EVENTS_FIX[XNode.DOM_MOUSELEAVE]=XNode.DOM_MOUSE_OUT;XNode._mouseEnter=function(fn){var _isDescendantOf=function(parent,child){if(parent===child){return false}while(child&&child!==parent){child=child.parentNode}return child===parent};return function(ev){var relatedTarget=ev.relatedTarget;if(this===relatedTarget||_isDescendantOf(this,relatedTarget)){return}fn.call(this,ev)}};function _getWindow(aElement){if(aElement&&(typeof aElement==="object")&&aElement.alert&&aElement.setTimeout){return aElement}var win=aElement.defaultView||aElement.parentWindow;if(!win){var doc=null;if(aElement.ownerDocument){doc=aElement.ownerDocument}else{if(aElement.document){doc=aElement.document}}if(doc){win=doc.defaultView||doc.parentWindow}}return win||null}function _getWindowSize(aWindow){if(aWindow.innerWidth){return{x:aWindow.innerWidth,y:aWindow.innerHeight}}var doc=aWindow.document;var elem=(!doc.compatMode||doc.compatMode=="CSS1Compat")?doc.html:doc.body;if(elem){return{x:elem.clientWidth,y:elem.clientHeight}}return{x:0,y:0}}function _getComputedStyle(aElement,aProperty){if(aElement.currentStyle){return aElement.currentStyle[getCssStyleNameAsCamelCase(aProperty)]}var win=_getWindow(aElement);var computed=win?win.getComputedStyle(aElement,null):null;return(computed)?computed.getPropertyValue(getJavaScriptStyleNameAsHyphenated(aProperty)):null}function _getStyleAsNumber(aElement,aStyle){return parseInt(_getComputedStyle(aElement,aStyle),10)||0}function _getBorderWidth(aSide,aElement){return _getStyleAsNumber(aElement,["border",aSide,"width"].join("-"))}function _isBody(aElement){return(/^(?:body|html)$/i).test(aElement.tagName)}function _hasBorderBoxStyle(aElement){return _getComputedStyle(aElement,"-moz-box-sizing")=="border-box"}var Dimensions={getOffsets:function(aElement){if(!aElement||((type(aElement)!=="node")&&(aElement!==_getWindow(aElement)))){throw new ArgumentError("Dimensions.getOffsets: Node or window is expected.")}var element=aElement,position={x:0,y:0};if(_isBody(aElement)){return position}var browser=nokia.aduno.utils.browser,isFixedPositioning=false,doc=element.ownerDocument,docElem=doc.documentElement,body=doc.body,defaultView=doc.defaultView;while(element&&!_isBody(element)){position.x+=element.offsetLeft;position.y+=element.offsetTop;isFixedPositioning=(element.currentStyle||defaultView&&defaultView.getComputedStyle(element,null)||{}).position==="fixed";if(browser.mozilla){if(!_hasBorderBoxStyle(element)){position.x+=_getBorderWidth("left",element);position.y+=_getBorderWidth("top",element)}var parent=element.parentNode;if(parent&&_getComputedStyle(parent,"overflow")!=="visible"){position.x+=_getBorderWidth("left",parent);position.y+=_getBorderWidth("top",parent)}}else{if(element!==aElement&&(browser.msie||browser.safari)){position.x+=_getBorderWidth("left",element);position.y+=_getBorderWidth("top",element)}}element=element.offsetParent;if(browser.msie){while(element&&!element.currentStyle.hasLayout){element=element.offsetParent}}}if(browser.msie&&!_hasBorderBoxStyle(aElement)){position.x-=_getBorderWidth("left",aElement);position.y-=_getBorderWidth("top",aElement)}if(isFixedPositioning){position.x+=Math.max(docElem.scrollLeft,body.scrollLeft);position.y+=Math.max(docElem.scrollTop,body.scrollTop)}return position},getPosition:function(aElement,aRelative){if(!aElement||((type(aElement)!=="node")&&(aElement!==_getWindow(aElement)))){throw new ArgumentError("Dimensions.getPosition: Node or window is expected.")}if(_isBody(aElement)){return{x:0,y:0}}var offset=this.getOffsets(aElement);var scroll=this.getScrolls(aElement);var position={x:offset.x-scroll.x,y:offset.y-scroll.y};var relativePosition=aRelative?this.getPosition(aRelative):{x:0,y:0};return{x:position.x-relativePosition.x,y:position.y-relativePosition.y}},getSize:function(aElement){if(!aElement||((type(aElement)!=="node")&&(aElement!==_getWindow(aElement)))){throw new ArgumentError("Dimensions.getSize: Node or window is expected.")}if(aElement==_getWindow(aElement)){return _getWindowSize(aElement)}else{if(_isBody(aElement)){var win=_getWindow(aElement);return _getWindowSize(win)}}return{x:aElement.offsetWidth,y:aElement.offsetHeight}},getCoordinates:function(aElement){if(!aElement||((type(aElement)!=="node")&&(aElement!==_getWindow(aElement)))){throw new ArgumentError("Dimensions.getCoordinates: Node or window is expected.")}if(_isBody(aElement)){return this.getCoordinates(_getWindow(aElement))}var position=this.getPosition(aElement);var size=this.getSize(aElement);var obj={left:position.x,top:position.y,width:size.x,height:size.y};obj.right=obj.left+obj.width;obj.bottom=obj.top+obj.height;return obj},getScrolls:function(aElement){if(!aElement||((type(aElement)!=="node")&&(aElement!==_getWindow(aElement)))){throw new ArgumentError("Dimensions.getScrolls: Node or window is expected.")}var element=aElement;var position={x:0,y:0};while(element&&!_isBody(element)){position.x+=element.scrollLeft||0;position.y+=element.scrollTop||0;element=element.parentNode}return position},getComputedOpacity:function(aElement){if(!aElement||((type(aElement)!=="node"))){throw new ArgumentError("Dimensions.getComputedOpacity: Node is expected.")}var opacity=1;for(element=aElement;element&&!_isBody(element);element=element.parentNode){opacity=opacity*this.getOpacity(element)}return opacity},getOpacity:function(aElement){if(!aElement||((type(aElement)!=="node"))){throw new ArgumentError("Dimensions.getOpacity: Node is expected.")}if(typeof aElement.filters!=="undefined"){var filter=_getComputedStyle(aElement,"filter");var matched=filter.match(/opacity\s*=\s*([0-9]{1,3})/i);if(matched!==null){return parseInt(matched[1],10)/100}}else{var style=_getComputedStyle(aElement,"opacity");if(style!==null){return parseFloat(style,10)}style=_getComputedStyle(aElement,"-moz-opacity");if(style!==null){return parseFloat(style,10)}}return 1}};var Event=new Class({Name:"Event",initialize:function(aEventToWrap,aDocument){this._originalEvent=aEventToWrap;if(this._originalEvent.timeStamp===undefined){this._originalEvent.timeStamp=getTimeStamp()}this._eventCopy=this._originalEvent;this.doc=aDocument},save:function(){var props=["altKey","attrChange","attrName","bubbles","button","cancelable","charCode","clientX","clientY","ctrlKey","currentTarget","data","detail","eventPhase","fromElement","handler","keyCode","metaKey","newValue","originalTarget","pageX","pageY","prevValue","relatedNode","relatedTarget","screenX","screenY","shiftKey","srcElement","target","timeStamp","toElement","type","view","wheelDelta","which"];this._eventCopy={};for(var i=0,len=props.length;i<len;++i){this._eventCopy[props[i]]=this._originalEvent[props[i]]}},preventDefault:function(){if(this._originalEvent.preventDefault){this._originalEvent.preventDefault()}this._originalEvent.returnValue=false},stopPropagation:function(){if(this._originalEvent.stopPropagation){this._originalEvent.stopPropagation()}this._originalEvent.cancelBubble=true},_getTarget:function(){var target=this._originalEvent.target;target=this._eventCopy.target||this._eventCopy.srcElement||this.doc;if(target.nodeType==3){target=target.parentNode}if(!target){target=this._eventCopy.srcElement||this.doc}if(target.nodeType==3){target=target.parentNode}return target},_getRelatedTarget:function(){if(!this._eventCopy.relatedTarget&&this._eventCopy.fromElement){return this._eventCopy.fromElement==this._getTarget()?this._eventCopy.toElement:this._eventCopy.fromElement}return this._eventCopy.relatedTarget},_getPageX:function(){if(!this._eventCopy.pageY&&this._eventCopy.clientY){var doc=this.doc.documentElement,body=this.doc.body;return this._eventCopy.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0)}else{return this._eventCopy.pageX}},_getPageY:function(){if(!this._eventCopy.pageY&&this._eventCopy.clientY){var doc=this.doc.documentElement,body=this.doc.body;return this._eventCopy.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0)}else{return this._eventCopy.pageY}},getKey:function(){return this._eventCopy.keyCode||this._eventCopy.charCode||this._eventCopy.which||null},getModifier:function(){var modifier=0;if(this._eventCopy.ctrlKey){modifier+=Event.MODIFIER_CTRL}if(this._eventCopy.shiftKey){modifier+=Event.MODIFIER_SHIFT}if(this._eventCopy.altKey){modifier+=Event.MODIFIER_ALT}if(this._eventCopy.metaKey){modifier+=Event.MODIFIER_META}return modifier},_getWhich:function(){if(this._eventCopy.which){return this._eventCopy.which}else{var which=(this._eventCopy.button&1?1:(this._eventCopy.button&2?3:(this._eventCopy.button&4?2:0)));return which}},_getWheelDelta:function(){var delta=0;if(this._eventCopy.wheelDelta){delta=this._eventCopy.wheelDelta/120;if(window.opera){delta=-delta}}else{if(this._eventCopy.detail){delta=-this._eventCopy.detail}}return delta},get:function(aPropName){switch(aPropName){case"pageX":return this._getPageX();case"pageY":return this._getPageY();case"which":return this._getWhich();case"target":return this._getTarget();case"relatedTarget":return this._getRelatedTarget();case"metaKey":return(!this._eventCopy.metaKey&&this._eventCopy.ctrlKey)?this._eventCopy.ctrlKey:this._eventCopy.metaKey;case"wheelDelta":return this._getWheelDelta();default:return this._eventCopy[aPropName]}}});Event.MODIFIER_NONE=0;Event.MODIFIER_ALT=1;Event.MODIFIER_SHIFT=2;Event.MODIFIER_CTRL=4;Event.MODIFIER_META=8;var _domLogger=null;var DomLogger=new Class({Name:"DomLogger",initialize:function(){if(_domLogger===null){_domLogger=this}return _domLogger},initLogger:function(aInverted){if(top.document.getElementById("_nokia_utils_console")){nokia.aduno.utils.warn("An instance of the DOM logger is already running")}else{this.isInverted=aInverted;var isSymbian=navigator.userAgent.match(/SymbianOs/i)!==null;var divNode=top.document.createElement("div");divNode.id="_nokia_utils_console";divNode.innerHTML="<div id='_nokia_utils_debug_toolbar'><div id='_nokia_utils_debug_toolbar_title'>ATLAS CONSOLE</div><div id='_nokia_utils_debug_toolbar_min'>-</div></div><div id='_nokia_utils_debug'></div>";top.document.body.appendChild(divNode);var div=top.document.getElementById("_nokia_utils_console");div.style.backgroundColor="#E0E0E0";div.style.border="1px solid #C0C0C0";div.style.bottom="0px";div.style.width="100%";div.style.height="180px";div.style.position="absolute";div.style.marginTop="10px";div=top.document.getElementById("_nokia_utils_debug_toolbar");div.style.borderBottom="2px solid #C0C0C0";div.style.top="0px";div.style.width="100%";div.style.height="20px";div.style.position="relative";div=top.document.getElementById("_nokia_utils_debug_toolbar_title");div.style.color="#000000";div.style.fontSize="1.2em";div.style.fontWeight="bold";div.style.left="5px";div.style.top="0px";div.style.position="absolute";div=top.document.getElementById("_nokia_utils_debug_toolbar_min");div.style.border="1px solid #C0C0C0";div.style.fontSize="1.2em";div.style.height="16px";div.style.width="16px";div.style.right="2px";div.style.top="1px";div.style.textAlign="center";div.style.position="absolute";if(isSymbian){div.style.display="none"}if(div.addEventListener){div.addEventListener("mousedown",this.minimizeDown,false);div.addEventListener("mouseup",this.minimizeUp,false)}else{if(div.attachEvent){div.attachEvent("onmousedown",this.minimizeDown);div.attachEvent("onmouseup",this.minimizeUp)}else{div.onmousedown=this.minimizeDown;div.onmouseup=this.minimizeUp}}div=top.document.getElementById("_nokia_utils_debug");div.style.width="100%";div.style.height="160px";div.style.overflowX="hidden";if(!isSymbian){div.style.overflowY="scroll"}}},cleanupLogger:function(){var console=top.document.getElementById("_nokia_utils_console");top.document.body.removeChild(console)},minimizeDown:function(){var button=top.document.getElementById("_nokia_utils_debug_toolbar_min");button.style.backgroundColor="#808080"},minimizeUp:function(){var button=top.document.getElementById("_nokia_utils_debug_toolbar_min");button.style.backgroundColor="#E0E0E0";var console=top.document.getElementById("_nokia_utils_console");var title=top.document.getElementById("_nokia_utils_debug_toolbar_title");var list=top.document.getElementById("_nokia_utils_debug");if(title.style.display!=="none"){title.style.display="none";list.style.display="none";console.style.height="20px";console.style.width="20px";console.style.top="0px";console.style.bottom="auto";button.firstChild.nodeValue="+"}else{title.style.display="block";list.style.display="block";console.style.height="120px";console.style.width="100%";console.style.bottom="0px";console.style.top="auto";button.firstChild.nodeValue="-"}},debug:function(aMsg){this._log(aMsg,"#000000")},info:function(aMsg){this._log(aMsg,"#000000")},warn:function(aMsg){this._log(aMsg,"#0000FF")},error:function(aMsg){this._log(aMsg,"#FF0000")},_log:function(aMsg,aColor){var list=top.document.getElementById("_nokia_utils_debug");var list_item=top.document.createElement("div");list_item.style.borderBottom="1px solid #C0C0C0";list_item.style.color=aColor;list_item.style.paddingLeft="5px";list_item.innerHTML=aMsg;if(this.isInverted){var children=[];if(list.firstChild){children.push(list.firstChild);var sibling=list.firstChild.nextSibling;while(sibling){children.push(sibling);sibling=sibling.nextSibling}}list.nodeValue="";list.appendChild(list_item);for(var i=0;i<children.length;i++){list.appendChild(children[i])}}else{list.appendChild(list_item)}}});var DummyReplica=new nokia.aduno.utils.Class({Name:"DummyReplica",_data:null,initialize:function(aTemplate){this._data={};this._template=aTemplate},hasDOMSupport:function(){return false},getTemplate:function(){return this._template},getAttribute:function(aId,aAttributeName){if(this._data[aId]&&this._data[aId].attributes){return this._data[aId].attributes[aAttributeName]||null}return null},setAttribute:function(aId,aAttributeName,aAttributeValue){this._data[aId]=this._data[aId]||{};this._data[aId].attributes=this._data[aId].attributes||{};this._data[aId].attributes[aAttributeName]=aAttributeValue;return this},removeAttribute:function(aId,aAttributeName){this._data[aId]=this._data[aId]||{};this._data[aId].attributes=this._data[aId].attributes||{};delete this._data[aId].attributes[aAttributeName];return this},getValue:function(aId){return this._data[aId]&&this._data[aId].value||null},setValue:function(aId,aValue){this._data[aId]=this._data[aId]||{};this._data[aId].value=aValue;return this},getText:function(aId){return this._data[aId]&&this._data[aId].text||""},setText:function(aId,aText){this._data[aId]=this._data[aId]||{};this._data[aId].text=aText;return this},addCssClass:function(aId,aCssClassName){if(!aCssClassName){aCssClassName=aId;aId=TemplateReplica.ROOT_ID}this._data[aId]=this._data[aId]||{};this._data[aId].className=this._data[aId].className||"";var classesToAdd=aCssClassName.split(" ");for(var i=classesToAdd.length-1;i>=0;--i){if(classesToAdd[i]){addCssClass(this._data[aId],classesToAdd[i])}}return this},removeCssClass:function(aId,aCssClassName){if(!aCssClassName){aCssClassName=aId;aId=TemplateReplica.ROOT_ID}this._data[aId]=this._data[aId]||{};this._data[aId].className=this._data[aId].className||"";var classesToRemove=aCssClassName.split(" ");var cssClasses=[];for(var i=classesToRemove.length-1;i>=0;--i){if(classesToRemove[i]){removeCssClass(this._data[aId],classesToRemove[i])}}return this},setStyle:function(aId,aStyleName,aStyleValue){this._data[aId]=this._data[aId]||{};this._data[aId].styles=this._data[aId].styles||{};this._data[aId].styles[aStyleName]=aStyleValue;return this},removeStyle:function(aId,aStyleName){this._data[aId]=this._data[aId]||{};this._data[aId].styles=this._data[aId].styles||{};delete this._data[aId].styles[aStyleName];return this},addEventHandler:function(aId,aEventName,aBind,aHandler){if(arguments.length===3){aHandler=aBind;aBind=aEventName;aEventName=aId;aId=TemplateReplica.ROOT_ID}this._data[aId]=this._data[aId]||{};this._data[aId].handler=this._data[aId].handler||[];this._data[aId].handler.push([aEventName,aBind,aHandler]);return aHandler},removeEventHandler:function(aId,aEventName,aHandler){if(arguments.length===2){aHandler=aEventName;aEventName=aId;aId=TemplateReplica.ROOT_ID}if(this._data[aId]&&this._data[aId].handler){for(var i=this._data[aId].handler.length-1;i>-1;--i){var handler=this._data[aId].handler[i];if((handler[0]===aEventName)&&(handler[2]===aHandler)){this._data[aId].handler.splice(i,1);return handler[2]}}}return null},setInnerHtml:function(aId,innerHTML){this._data[aId]=this._data[aId]||{};this._data[aId].innerHTML=innerHTML||"";return this},getInnerHtml:function(aId){return this._data[aId]&&this._data[aId].innerHTML||""},setData:function(aReplica,aTemplateData){aTemplateData=aTemplateData||this._data;Collection.forEach(aTemplateData,function(aData,aId){var element=aReplica.getElement(aId);if(element&&aData){if(aData.text){if(element.tagName.toLowerCase()==="input"){aReplica.setValue(aId,aData.text)}else{aReplica.setText(aId,aData.text)}}if(aData.value){aReplica.setValue(aId,aData.value)}if(aData.attributes){Collection.forEach(aData.attributes,function(aAttributeValue,aAttributeId){aReplica.setAttribute(aId,aAttributeId,aAttributeValue)},this)}if(aData.className){aReplica.addCssClass(aId,aData.className)}if(aData.styles){Collection.forEach(aData.styles,function(aStyleValue,aStyleName){aReplica.setStyle(aId,aStyleName,aStyleValue)},this)}if(aData.handler){for(var i=aData.handler.length-1;i>-1;--i){aReplica.addEventHandler(aId,aData.handler[i][0],aData.handler[i][1],aData.handler[i][2])}}if(aData.innerHTML){aReplica.setInnerHtml(aId,aData.innerHTML)}}})}});nokia.aduno.dom.addMembers({bindWithEvent:bindWithEvent,addCssClass:addCssClass,removeCssClass:removeCssClass,importNode:importNode,getCssStyleNameAsCamelCase:getCssStyleNameAsCamelCase,getJavaScriptStyleNameAsHyphenated:getJavaScriptStyleNameAsHyphenated,convertColorHexToRgb:convertColorHexToRgb,convertColorRgbToHex:convertColorRgbToHex,getChildIndex:getChildIndex,SimplePath:SimplePath,Parser:Parser,XHtmlParser:XHtmlParser,Template:Template,TemplateReplica:TemplateReplica,TemplateLibrary:TemplateLibrary,XNode:XNode,Dimensions:Dimensions,Event:Event,DomLogger:DomLogger,DummyReplica:DummyReplica})};new function(){new nokia.aduno.Ns("nokia.aduno.medosui");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var bindWithEvent=nokia.aduno.dom.bindWithEvent;var addCssClass=nokia.aduno.dom.addCssClass;var removeCssClass=nokia.aduno.dom.removeCssClass;var importNode=nokia.aduno.dom.importNode;var getCssStyleNameAsCamelCase=nokia.aduno.dom.getCssStyleNameAsCamelCase;var getJavaScriptStyleNameAsHyphenated=nokia.aduno.dom.getJavaScriptStyleNameAsHyphenated;var convertColorHexToRgb=nokia.aduno.dom.convertColorHexToRgb;var convertColorRgbToHex=nokia.aduno.dom.convertColorRgbToHex;var getChildIndex=nokia.aduno.dom.getChildIndex;var SimplePath=nokia.aduno.dom.SimplePath;var Parser=nokia.aduno.dom.Parser;var XHtmlParser=nokia.aduno.dom.XHtmlParser;var Template=nokia.aduno.dom.Template;var TemplateReplica=nokia.aduno.dom.TemplateReplica;var TemplateLibrary=nokia.aduno.dom.TemplateLibrary;var XNode=nokia.aduno.dom.XNode;var Dimensions=nokia.aduno.dom.Dimensions;var Event=nokia.aduno.dom.Event;var DomLogger=nokia.aduno.dom.DomLogger;var DummyReplica=nokia.aduno.dom.DummyReplica;function getDefaultTemplateLibrary(options){options=options||nokia.aduno.utils.browser;return nokia.aduno.medosui[{snc:"DefaultSnCTemplateLibrary",touch:"DefaultTouchTemplateLibrary",web:"DefaultWebTemplateLibrary"}[options.snc?"snc":options.touch?"touch":"web"]]}var layout=nokia.aduno.utils.browser.snc?"snc":nokia.aduno.utils.browser.touch?"touch":"web";function getLayout(){return layout}function loadAssets(aWindow,aLayout,aPath){aLayout=aLayout||layout;if(aPath.lastIndexOf("/")!==(aPath.length-1)){aPath+="/"}var doc=aWindow.document,cssCommon=doc.getElementById("medosui-common"),cssLayout=doc.getElementById("medosui-layout");if(cssCommon&&cssLayout){return}if(cssLayout){cssLayout.parentNode.removeChild(cssLayout)}var required=[aLayout];(!cssCommon&&required.unshift("common"));for(var i=0,css;(css=required[i]);i++){(new nokia.aduno.utils.CssLoader({window:aWindow,uri:aPath+css+".css"})).getNode().id="medosui-"+({common:"common"}[css]||"layout")}}var TemplateResolver=new Class({Name:"TemplateResolver",initialize:function(aTemplate){this._replica=new nokia.aduno.dom.DummyReplica(aTemplate)},getReplica:function(){return this._replica},_getTemplate:function(aTemplateName){return this._resolveTemplate(aTemplateName||this.className)},_resolveTemplate:function(aTemplateName){throw new AbstractMethodError(this.className,"_resolveTemplate")},getDomReplica:function(aControl){var template=this._replica.getTemplate();if(type(template)=="string"){template=aControl._getTemplate(template)}if(!template){template=aControl._getTemplate(aControl.className)}if(!template){if(template&&template!=aControl.className){throw new Error("Template '"+this._template+"' or '"+aControl.className+"' can't be resolved.")}else{throw new Error("Template '"+aControl.className+"' can't be resolved.")}}var replica=template.replicate(aControl.getOwnerDoc());this._replica.setData(replica);return replica},_changeReplica:function(){this._replica=this.getDomReplica(this)},getRootElement:function(){if(!(this._replica.getRootElement)){this._changeReplica()}return this._replica.getRootElement()},getElement:function(aId){if(!(this._replica.getElement)){this._changeReplica()}return this._replica.getElement(aId)}});var KeyEventManager=new Class({Name:"KeyEventManager",_specialKeysConfiguration:null,initialize:function(aWindow){this._windowNode=new XNode(aWindow.document);this._listenerKeyDown=nokia.aduno.dom.bindWithEvent(this,this.onKeyDown);this._listenerKeyUp=nokia.aduno.dom.bindWithEvent(this,this.onKeyUp);this._listenerKeyPress=nokia.aduno.dom.bindWithEvent(this,this.onKeyPress);this._detectKeySettings();this._attachListeners()},onKeyPress:function(aKeyEvent){this._doKeyHandling(aKeyEvent,"keyPress")},onKeyDown:function(aKeyEvent){this._doKeyHandling(aKeyEvent,"keyDown")},onKeyUp:function(aKeyEvent){this._doKeyHandling(aKeyEvent,"keyUp")},_doKeyHandling:function(aKeyEvent,aType){this._extendEvent(aKeyEvent);aKeyEvent[aType]=true;var focusedPage=nokia.aduno.medosui.Page.getFocusedPage();if(focusedPage&&focusedPage.handleKey(aKeyEvent)){aKeyEvent.stopPropagation()}},_attachListeners:function(){this._windowNode.addEventHandler("keypress",this._listenerKeyPress,true);this._windowNode.addEventHandler("keydown",this._listenerKeyDown,true);this._windowNode.addEventHandler("keyup",this._listenerKeyUp,true)},_detachListeners:function(){this._windowNode.removeEventHandler("keypress",this._listenerKeyPress,true);this._windowNode.removeEventHandler("keydown",this._listenerKeyDown,true);this._windowNode.removeEventHandler("keyup",this._listenerKeyUp,true)},_detectKeySettings:function(){if(nokia.aduno.utils.browser.s60){nokia.aduno.medosui.KeyEventManager.Configurations.S60()}else{nokia.aduno.medosui.KeyEventManager.Configurations.PC()}},_extendEvent:function(aKeyEvent){var keyCode=aKeyEvent.getKey();if(keyCode>=48&&keyCode<=90){aKeyEvent.isCharacter=true}else{aKeyEvent.isCharacter=false}}});KeyEventManager.Configurations={};KeyEventManager.Configurations.S60=function(){KeyEventManager.KEY_LEFT=63495;KeyEventManager.KEY_UP=63497;KeyEventManager.KEY_RIGHT=63496;KeyEventManager.KEY_DOWN=63498;KeyEventManager.KEY_CSK=63557;KeyEventManager.KEY_LSK=63554;KeyEventManager.KEY_RSK=63555;KeyEventManager.KEY_NUM_PLUS=42;KeyEventManager.KEY_NUM_MINUS=35;KeyEventManager.KEY_PLUS_IE=-1;KeyEventManager.KEY_PLUS_MOZ=-1;KeyEventManager.KEY_MINUS_IE=-1;KeyEventManager.KEY_CONTROL=-1;KeyEventManager.KEY_SHIFT=-1;KeyEventManager.KEY_0=48;KeyEventManager.KEY_1=49;KeyEventManager.KEY_2=50;KeyEventManager.KEY_3=51;KeyEventManager.KEY_4=52;KeyEventManager.KEY_5=53;KeyEventManager.KEY_6=54;KeyEventManager.KEY_7=55;KeyEventManager.KEY_8=56;KeyEventManager.KEY_9=57};KeyEventManager.Configurations.PC=function(){KeyEventManager.KEY_SHIFT=16;KeyEventManager.KEY_CONTROL=17;KeyEventManager.KEY_LEFT=37;KeyEventManager.KEY_UP=38;KeyEventManager.KEY_RIGHT=39;KeyEventManager.KEY_DOWN=40;KeyEventManager.KEY_LSK=45;KeyEventManager.KEY_CSK=36;KeyEventManager.KEY_RSK=33;KeyEventManager.KEY_NUM_PLUS=107;KeyEventManager.KEY_NUM_MINUS=109;KeyEventManager.KEY_PLUS_IE=187;KeyEventManager.KEY_PLUS_MOZ=61;KeyEventManager.KEY_MINUS_IE=189;KeyEventManager.KEY_0=48;KeyEventManager.KEY_1=49;KeyEventManager.KEY_2=50;KeyEventManager.KEY_3=51;KeyEventManager.KEY_4=52;KeyEventManager.KEY_5=53;KeyEventManager.KEY_6=54;KeyEventManager.KEY_7=55;KeyEventManager.KEY_8=56;KeyEventManager.KEY_9=57};var S60KeyEventManager=new nokia.aduno.utils.Class({Name:"S60KeyEventManager",Extends:KeyEventManager,initialize:function(aWindow){this._super(aWindow);this._keysPressed={}},onKeyPress:function(aKeyEvent){var code=aKeyEvent.getKey();if(code){if(!this._keysPressed[code]){var pressObj={event:aKeyEvent};aKeyEvent.save();pressObj.timer=setTimeout(nokia.aduno.utils.bind(this,this._fireLongPress,code),1000);this._keysPressed[code]=pressObj;this.onKeyDown(aKeyEvent,true)}else{this._super(aKeyEvent);aKeyEvent.keyPress=false}}},onKeyDown:function(aKeyEvent,aSuper){if(aSuper){this._super(aKeyEvent);aKeyEvent.keyDown=false}},onKeyUp:function(aKeyEvent,aSuper){if(aSuper){this._super(aKeyEvent);aKeyEvent.keyUp=false}else{Collection.forEach(this._keysPressed,function(value,key){this.onKeyUp(value.event,true);clearTimeout(value.timer)},this);this._keysPressed={}}},_fireLongPress:function(aCode){var pressObj=this._keysPressed[aCode];pressObj.event._originalEvent={};this._doKeyHandling(pressObj.event,"keyLongPress");pressObj.event.keyLongPress=false}});var FocusHandler={initialize:function(){this._focusedChild=null},requestFocus:function(aControl){if(!aControl||(this!==aControl._parent)){nokia.aduno.utils.warn(this.className+".requestFocus: the given argument is not a (child) control");return false}if(this._isFocused){if((this._focusedChild&&this._focusedChild.blur())||(!this._focusedChild)){this._focusedChild=aControl;return true}else{return false}}else{if(this._parent){if(this._parent.requestFocus(this)){this._isFocused=true;this._focusedChild=aControl;return true}else{return false}}else{return false}}},removeFocus:function(aControl){if(aControl===this._focusedChild){this._focusedChild=null}},handleKey:function(aKeyEvent){if(this._focusedChild===null||!this._focusedChild.isFocused()){return false}return this._focusedChild.handleKey(aKeyEvent)},getFocusedChild:function(){return this._focusedChild}};var Control=new Class({Extends:TemplateResolver,Implements:EventSource,Name:"Control",_parent:null,_behaviors:null,_replica:null,_isFocused:false,_isEnabled:false,_posId:null,_visible:true,_changeCssWithFocus:false,initialize:function(aTemplate,aTemplateLibrary){if(aTemplateLibrary){this.setTemplateLibrary(aTemplateLibrary)}this._super(aTemplate);this.enable()},accept:function(aVisitor){if(aVisitor["visit"+this.className]){aVisitor["visit"+this.className](this)}},setParent:function(aContainer){this._parent=aContainer},detachFromParent:function(){if(this._parent){this._parent.removeChild(this)}},getOwnerDoc:function(){return this._parent.getOwnerDoc()},focus:function(){if(!this._isFocused&&this._parent&&this._parent.requestFocus(this)){this._isFocused=true;this._doFocus()}return this._isFocused},blur:function(){if(this._isFocused){this._isFocused=false;this._doBlur()}return true},_doFocus:function(){if(this._changeCssWithFocus){this._replica.addCssClass("nm_Focused")}this.fireEvent("focused")},_doBlur:function(aEvent){if(this._changeCssWithFocus){this._replica.removeCssClass("nm_Focused")}this.fireEvent("blurred")},isFocused:function(){return this._isFocused},handleKey:function(aKeyEvent){return false},enable:function(){if(!this._isEnabled){this._isEnabled=true;this.fireEvent("enabled")}},disable:function(){if(this._isEnabled){this._isEnabled=false;this.fireEvent("disabled")}},isEnabled:function(){return this._isEnabled},getNode:function(){var node=this.getRootElement();(new Collection(this._behaviors||[]).forEach(function(aBhvr){var newNode=aBhvr.getNode(node);if(newNode){node=newNode}},this));return node},addBehavior:function(aBehavior){this._behaviors=this._behaviors||[];if(aBehavior instanceof Behavior){if(!this.getBehavior(aBehavior.className)){if(this._replica instanceof nokia.aduno.dom.TemplateReplica&&this.getRootElement().parentNode&&this.getRootElement().parentNode.tagName){var myRoot=this.getRootElement();var parentNode=myRoot.parentNode;for(var i=0,b;(b=this._behaviors[i]);i++){b.removeControl()}parentNode=myRoot.parentNode;var tmpObject=this.getOwnerDoc().createElement("span");parentNode.replaceChild(tmpObject,myRoot);this._behaviors.push(aBehavior);aBehavior.setControl(this);var newNode=this.getNode();parentNode.replaceChild(newNode,tmpObject)}else{this._behaviors.push(aBehavior);aBehavior.setControl(this)}return true}}return false},removeBehavior:function(aBehaviorClassName){if(aBehaviorClassName&&this._behaviors){for(var i=0,b;(b=this._behaviors[i]);i++){if(b.className===aBehaviorClassName){b.removeControl();this._behaviors.splice(i,1)}}}},getBehavior:function(aBehaviorClassName){for(var i=0,b;(b=(this._behaviors||[])[i]);i++){if(b.className===aBehaviorClassName){return b}}return null},_resolveTemplate:function(aTemplateName){var template=null;if(this._templateLib){template=this._templateLib.getTemplate(aTemplateName)}if(!template&&this._parent){template=this._parent._getTemplate(aTemplateName)}return template},removeFromBehaviors:function(){for(var i=0,b;(b=(this._behaviors||[])[i]);i++){b.removeControl()}return this},_removeNode:function(){this.removeFromBehaviors();try{if(this._replica.hasDOMSupport()&&this.getRootElement().parentNode&&this.getRootElement().parentNode.tagName){var myRoot=this.getRootElement();var parentNode=myRoot.parentNode;if(parentNode&&parentNode.tagName){parentNode.removeChild(myRoot)}}}catch(e){nokia.aduno.utils.warn(this.className+": could not find the node")}return this},setPosId:function(aDomPos){this._posId=aDomPos},getPosId:function(){return this._posId},setTemplateLibrary:function(aTmplLib){this._templateLib=aTmplLib;return this},getTemplateLibrary:function(){return this._templateLib||this._parent.getTemplateLibrary()},setCSSTrigger:function(aCSSTriggerType){switch(aCSSTriggerType){case Control.CSS_TRIGGER_OVER:this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSEENTER,this,this._cssTriggerOver);this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSELEAVE,this,this._cssTriggerOut);break;case Control.CSS_TRIGGER_DOWN:this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._cssTriggerDown);this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this,this._cssTriggerUp);break;case Control.CSS_TRIGGER_FOCUS:this._changeCssWithFocus=true;break;case Control.CSS_TRIGGER_DOMFOCUS:this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_FOCUS,this,this._cssTriggerDomFocus);this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_BLUR,this,this._cssTriggerDomBlur);break}return this},removeCSSTrigger:function(aCSSTriggerType){switch(aCSSTriggerType){case Control.CSS_TRIGGER_OVER:this._replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSEENTER,this._cssTriggerOver);this._replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSELEAVE,this._cssTriggerOut);break;case Control.CSS_TRIGGER_DOWN:this._replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this._cssTriggerDown);this._replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this._cssTriggerUp);break;case Control.CSS_TRIGGER_FOCUS:this._changeCssWithFocus=false;break;case Control.CSS_TRIGGER_DOMFOCUS:this._replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_FOCUS,this._cssTriggerDomFocus);this._replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_BLUR,this._cssTriggerDomBlur);break}return this},_addCssClass:function(aClass){this._replica.addCssClass(aClass)},_removeCssClass:function(aClass){this._replica.removeCssClass(aClass)},_cssTriggerOver:function(aEvent){this._addCssClass("nm_MouseOver")},_cssTriggerOut:function(aEvent){this._removeCssClass("nm_MouseOver");this._removeCssClass("nm_MouseDown")},_cssTriggerDown:function(){this._addCssClass("nm_MouseDown")},_cssTriggerUp:function(){this._removeCssClass("nm_MouseDown")},_cssTriggerDomFocus:function(){this._addCssClass("nm_DomFocus")},_cssTriggerDomBlur:function(){this._removeCssClass("nm_DomFocus")},show:function(){this._replica.removeCssClass("nm_Hidden");this._visible=true;this.fireEvent("shown")},hide:function(){this.blur();this._replica.addCssClass("nm_Hidden");this._visible=false;this.fireEvent("hidden")},isVisible:function(){return this._visible}});Control.CSS_TRIGGER_OVER=1;Control.CSS_TRIGGER_DOWN=2;Control.CSS_TRIGGER_FOCUS=3;Control.CSS_TRIGGER_DOMFOCUS=4;var Button=new Class({Extends:Control,Name:"Button",initialize:function(aTemplate,aText){this._super(aTemplate);this.enable();if(aText){this.setText(aText)}},enable:function(){this._super();if(!this._enabled){this._enabled=true;var replica=this.getReplica();replica.removeCssClass("nm_Disabled");if(!nokia.aduno.utils.browser.snc){this.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this.setCSSTrigger(Control.CSS_TRIGGER_OVER)}this.setCSSTrigger(Control.CSS_TRIGGER_DOMFOCUS);replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._onMouseDown);replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this,this._onMouseUp);replica.addEventHandler(nokia.aduno.dom.XNode.DOM_CLICK,this,this._onClick)}},disable:function(){this._super();if(this._enabled){this._enabled=false;var replica=this.getReplica();replica.addCssClass("nm_Disabled");if(!nokia.aduno.utils.browser.snc){this.removeCSSTrigger(Control.CSS_TRIGGER_DOWN);this.removeCSSTrigger(Control.CSS_TRIGGER_OVER)}this.removeCSSTrigger(Control.CSS_TRIGGER_DOMFOCUS);replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this._onMouseDown);replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this._onMouseUp);replica.removeEventHandler(nokia.aduno.dom.XNode.DOM_CLICK,this._onClick)}},getText:function(){return this.getReplica().getText("button")},setText:function(aText){this.getReplica().setText("button",aText);return this},_onClick:function(aEvent){this.fireEvent("selected");aEvent.stopPropagation();aEvent.preventDefault()},_onMouseDown:function(aEvent){this._pressedTarget=aEvent._getTarget();this.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSELEAVE,this,this._onMouseLeave)},_onMouseLeave:function(aEvent){delete this._pressedTarget;this.getReplica().removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSELEAVE,this._onMouseLeave)},_onMouseUp:function(aEvent){var releasedTarget=aEvent._getTarget(),e=aEvent._eventCopy;if(document.createEvent&&this._pressedTarget&&this._pressedTarget!==releasedTarget){setTimeout(function(){var click=document.createEvent("MouseEvents");click.initMouseEvent("click",true,true,window,1,e.screenX,e.screenY,e.clientX,e.clientY,e.ctrlKey,e.altKey,e.shiftKey,e.metaKey,0,null);releasedTarget.dispatchEvent(click)},0)}delete this._pressedTarget;this.getReplica().removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSELEAVE,this._onMouseLeave)}});var Container=new Class({Name:"Container",Extends:Control,Implements:FocusHandler,_children:null,_templateLib:null,initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._children=[];this._replacementBuffer={};this._collapseIds={}},focus:function(){if(this._focusedChild){return this._focusedChild.focus()}else{return this._super()}},blur:function(){var blurred=this._super();if(this._focusedChild&&blurred){return this._focusedChild.blur()}return blurred},getChildAt:function(aPosId){for(var i=0,len=this._children.length;i<len;++i){var child=this._children[i];if(child&&child.getPosId()===aPosId){return child}}return null},setChildAt:function(aControl,aPosId,aForceOverwrite,aDontReplace){var index=-1;var childWithPosId=null;var _getIndexes=function(child,key){if(child===aControl){index=key}if(child.getPosId()===aPosId){childWithPosId=child}};Collection.forEach(this._children,_getIndexes,this);if(childWithPosId){if(aForceOverwrite){this.removeChild(childWithPosId)}else{nokia.aduno.utils.warn("The posId you passed to setChildAt is already occupied: "+aPosId);return}}aControl.detachFromParent();this._children.push(aControl);aControl.setParent(this);aControl.setPosId(aPosId);this._collapseIds[aPosId]=!aDontReplace;if(this._replica&&this._replica instanceof nokia.aduno.dom.TemplateReplica&&this.getRootElement().parentNode&&this.getRootElement().parentNode.tagName){this._renderChild(aControl)}},removeChild:function(aControl){var index=Collection.indexOf(this._children,aControl);if(index>-1){aControl.blur();this.removeFocus(aControl);this._children.splice(index,1);var posId=aControl.getPosId();var helperNode=this._replacementBuffer[posId];delete this._replacementBuffer[posId];if(helperNode&&this._collapseIds[posId]){this.getReplica().replaceElement(posId,helperNode)}else{aControl._removeNode()}aControl.removeFromBehaviors();aControl.setParent(null);aControl.setPosId(null);return aControl}return null},getNode:function(){var node=this._super();for(var i=0,len=this._children.length;i<len;i++){this._renderChild(this._children[i])}return node},_renderChild:function(aControl){var controlNode=aControl.getNode();var posId=aControl.getPosId();var replace=this._collapseIds[posId];var element=this.getElement(posId);if(!element){throw new Error("no position for Control ID: "+posId)}if(!controlNode.parentNode||!controlNode.parentNode.tagName){if(element.parentNode&&element.parentNode.tagName&&replace){this._replacementBuffer[posId]=this.getReplica().replaceElement(posId,controlNode)}else{element.appendChild(controlNode)}}}});var Image=new Class({Extends:Control,Name:"Image",initialize:function(aTemplate,aUri){this._super(aTemplate);this.setSource(aUri);this._isShowing=true},show:function(){if(!this._isShowing){this._replica.removeCssClass("image","nm_Hidden")}this._isShowing=true},hide:function(){if(this._isShowing){this._replica.addCssClass("image","nm_Hidden")}this._isShowing=false},getSource:function(){return this._replica.getAttribute("image","src")},setSource:function(aURI){this._replica.setAttribute("image","src",aURI);return this},setHeight:function(aHeight){this._replica.setAttribute("image","height",aHeight);return this},setWidth:function(aWidth){this._replica.setAttribute("image","width",aWidth);return this}});var TextInput=new Class({Name:"TextInput",Extends:Control,Implements:Options,options:{maxSize:null,watermark:null},initialize:function(aTemplate,aValue,aOptions){this._super(aTemplate);this.setOptions(aOptions);if(this._options.maxSize){this.setMaxSize(this._options.maxSize)}this.setValue(aValue);this._replica.addEventHandler("input","change",this,this.onChange);this._replica.addEventHandler("input","select",this,this.onSelect);this._replica.addEventHandler("input","blur",this,this.onBlur);this._replica.addEventHandler("input","focus",this,this.onFocus);this.setCSSTrigger(Control.CSS_TRIGGER_FOCUS)},getValue:function(){return this._watermarked?"":this._replica.getValue("input")},setValue:function(aValue){this._updateValue(aValue);return this},_updateValue:function(aValue){if((aValue!==0)&&!aValue){aValue=""}if(this._watermarked){this._watermarked=false;this._replica.removeCssClass("input","nm_Watermarked")}if((aValue==="")&&!this.isFocused()&&this._options.watermark){this._watermarked=true;aValue=this._options.watermark;this._replica.addCssClass("input","nm_Watermarked")}var maxLength=this._options.maxSize;if(maxLength&&(aValue.length>maxLength)){aValue=aValue.substring(0,maxLength)}this._replica.setValue("input",aValue)},setMaxSize:function(aMaxSize){this._options.maxSize=aMaxSize||null;var maxlength=nokia.aduno.utils.browser.msie?"maxLength":"maxlength";if(!this._options.maxSize){this._replica.removeAttribute("input",maxlength)}else{this._replica.setAttribute("input",maxlength,this._options.maxSize)}this._updateValue(this._watermarked?"":this._replica.getValue("input"));return this},setWatermark:function(aWatermark){this._options.watermark=aWatermark||null;this._updateValue(this._watermarked?"":this._replica.getValue("input"));return this},onChange:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event("changed",{oldValue:null,newValue:this.getValue(),type:"blur"}));aEvent.stopPropagation()},onSelect:function(aEvent){this.fireEvent("selected");aEvent.stopPropagation()},onFocus:function(){this.focus()},onBlur:function(){this.blur()},_doFocus:function(){this._super();this._updateValue(this._watermarked?"":this._replica.getValue("input"));this.getElement("input").focus()},_doBlur:function(aEvent){this._super();this._updateValue(this._watermarked?"":this._replica.getValue("input"));this.getElement("input").blur()},handleKey:function(aKeyEvent){if(aKeyEvent.keyUp){this.fireEvent(new nokia.aduno.utils.Event("changed",{oldValue:null,newValue:this.getValue(),type:"key",key:aKeyEvent.getKey()}))}return !aKeyEvent.specialKey}});var Label=new Class({Extends:Control,Name:"Label",initialize:function(aTemplate,aText){this._super(aTemplate);if(aText){this.setText(aText)}},setText:function(aText){this._replica.setText("label",aText);return this},getText:function(){return this._replica.getText("label")}});var CheckButton=new Class({Extends:Button,Name:"CheckButton",_state:false,initialize:function(aTemplate,aText,aValue,aState){this._super(aTemplate,aText);if(aValue){this.setValue(aValue)}this.setState(aState)},getText:function(){return this.getReplica().getText("checkButtonText")},setText:function(aText){this.getReplica().setText("checkButtonText",aText);return this},getValue:function(){return this._value},setValue:function(aValue){this._value=aValue;return this},getState:function(){return this._state},setState:function(aState){this._state=aState;if(this._state){this._addCssClass("nam_Selected")}else{this._removeCssClass("nam_Selected")}if(this._replica&&this._replica.getElement){var elem=this._replica.getElement("checkButtonButton");if(elem){if(this._state){elem.checked="true"}else{elem.checked=""}}}return this},_findNodeWithChecked:function(parentNode){var returnNode=null;var len=parentNode.childNodes.length;if(len===0){return returnNode}for(var i=0;i<len;i++){if(parentNode.childNodes[i].checked!==undefined){returnNode=parentNode.childNodes[i];break}else{returnNode=this._findNodeWithChecked(parentNode.childNodes[i])}}return returnNode},_onClick:function(aEvent){if(this._isEnabled){this.setState(!this._state);this.fireEvent("selected");aEvent.stopPropagation()}},getNode:function(){var returnValue=this._super();this.setState(this._state);return returnValue},select:function(){this.setState(!this._state);this.fireEvent("selected")},enable:function(){this._super();this._replica.removeAttribute("checkButtonButton","disabled")},disable:function(){this._super();this._replica.setAttribute("checkButtonButton","disabled",true)}});var Behavior=new Class({Name:"Behavior",Extends:TemplateResolver,_control:null,_controlNode:null,initialize:function(aTemplate){this._super(aTemplate)},getNode:function(aControlNode){var myNode=this.getRootElement();this._controlNode=aControlNode;if(myNode){myNode.appendChild(aControlNode)}this._attachEvents(aControlNode,myNode);return myNode||aControlNode},setControl:function(aControl){this._control=aControl;return this},removeControl:function(){var myNode=this.getRootElement();var parentNode=myNode.parentNode;if(parentNode){this._removeEvents(this._controlNode);parentNode.replaceChild(this._controlNode,myNode)}else{warn("No parent for behavior")}return this},_attachEvents:function(aControlNode,aBehaviorRootNode){},_removeEvents:function(aControlNode){},fireEvent:function(aEvent){this._control.fireEvent(aEvent);return this},_resolveTemplate:function(aTemplateName){return this._control._resolveTemplate(aTemplateName)},getOwnerDoc:function(){return this._control.getOwnerDoc()}});var Scrollable=new Class({Name:"Scrollable",Extends:Behavior,_scrollNode:null,initialize:function(aTemplate){this._super(aTemplate)},scrollToPos:function(aXPos,aYPos){var rootElement=this.getRootElement();rootElement.scrollTop=aYPos;rootElement.scrollLeft=aXPos;return this},_attachEvents:function(aControlNode,aBehaviorRootNode){this._scrollNode=new XNode(aBehaviorRootNode).addEventHandler(nokia.aduno.dom.XNode.DOM_SCROLL,bindWithEvent(this,this._handleScroll))},_handleScroll:function(aDomEvent){this.fireEvent(new nokia.aduno.utils.Event("scrolled",{domEvent:aDomEvent}))}});var Page=new Class({Extends:Container,Name:"Page",_visible:false,initialize:function(aDomNode,aTemplate,aTemplateLibrary){if(type(aDomNode)!="node"){throw new ArgumentError(this.className+": Not a valid domnode: "+aDomNode)}if(!aTemplateLibrary){throw new ArgumentError(this.className+": No TemplateLibrary given")}this._isFocused=false;this._super(aTemplate,aTemplateLibrary);this._domNode=aDomNode;var that=this;if(this.getOwnerDoc()!==window.document){var unloadHandler=function(){Page.removePage(that)};if(this.getOwnerDoc().defaultView&&document.addEventListener){this.getOwnerDoc().defaultView.addEventListener("unload",unloadHandler,false)}else{if(this.getOwnerDoc().parentWindow&&document.attachEvent){this.getOwnerDoc().parentWindow.attachEvent("onunload",unloadHandler)}}}},getOwnerDoc:function(){return this._domNode.ownerDocument},requestFocus:function(aControl){if(!aControl||(this!==aControl._parent)){nokia.aduno.utils.warn(this.className+".requestFocus: the given argument is not a (child) control");return false}if(this._isFocused){if((this._focusedChild&&this._focusedChild.blur())||(!this._focusedChild)){this._focusedChild=aControl;return true}else{return false}}else{var focusedPage=Page.getFocusedPage();if(!focusedPage){this._isFocused=true;this._focusedChild=aControl;return true}else{if(focusedPage.blur()){this._isFocused=true;this._focusedChild=aControl;return true}else{return false}}}},show:function(){if(this._visible){return this}var parentNode=this.getRootElement().parentNode;if(!parentNode||!parentNode.tagName){this._domNode.appendChild(this.getNode())}Page.addPage(this);this.fireEvent("shown");this._visible=true;return this},hide:function(){if(!this._visible){return this}var parentNode=this.getRootElement().parentNode;if(parentNode&&parentNode.tagName){this._domNode.removeChild(this.getNode())}Page.removePage(this);this.fireEvent("hidden");this._visible=false;return this},_getTemplate:function(aTemplateName){return this._templateLib.getTemplate(aTemplateName)},focus:function(){var page=Page.getFocusedPage();if(page&&page!==this){return page.blur()}return(this._isFocused=true)},handleKey:function(aKeyEvent){var handled=this._super(aKeyEvent);if(!handled&&this.handleGlobalKeys){handled=this.handleGlobalKeys(aKeyEvent)}return handled},removeNode:function(){var instance=this._removeNode();this.fireEvent(new nokia.aduno.utils.Event("hidden"));return instance},getDomNode:function(){return this._domNode}});Page.pages=[];Page.getFocusedPage=function(){for(var i=Page.pages.length-1;i>-1;i--){if(Page.pages[i]._isFocused){return Page.pages[i]}}return null};Page.addPage=function(aPage,aPos){for(var i=0,len=Page.pages.length;i<len;i++){if(Page.pages[i]==aPage){nokia.aduno.utils.info("Page.addPage: Page is already included in the array");return false}}if(aPos){if(aPos>-1&&aPos<Page.pages.length){Page.pages.splice(aPos,0,Page);return true}}Page.pages.push(aPage);return true};Page.removePage=function(aPage){var index=Collection.indexOf(Page.pages,aPage);if(index>-1){aPage.blur();Page.pages.splice(index,1);if(Page.pages.length>0){Page.pages[0].focus()}return true}else{nokia.aduno.utils.info("Page.removePage: Page not found");return !aPage}};var Fx=new Class({Name:"Fx",Implements:EventSource,_interval:100,NORMAL:"normal",EASEIN:"easeIn",EASEOUT:"easeOut",CIRCULARIN:"circularIn",CIRCULAROUT:"circularOut",ELASTICOUT:"elasticOut",BACKSHOOT:"backShoot",OVERSHOOT:"overShoot",OVERSHOOT2:"overShoot2",initialize:function(aSubject){if(aSubject!==undefined&&aSubject!==null){this.chain=[];this.currentFx=null;this.subject=aSubject}else{throw new Error("no ui TemplateResolver or DOM node given in the Fx constructor")}return this},effect:function(aFxOptions){var myFx={id:this.chain.length,combineStyles:aFxOptions.combineStyles,transition:this.transitions.normal,duration:1000,fps:10};for(var elem in aFxOptions){if(elem=="styles"){var formattedStyles={};for(var styleElement in aFxOptions[elem]){var propertyName=nokia.aduno.utils.browser.msie&&styleElement.toLowerCase()=="opacity"?"filter":styleElement;formattedStyles[aFxOptions.combineStyles?propertyName:getCssStyleNameAsCamelCase(propertyName)]=this._convertStyles(propertyName,aFxOptions[elem][styleElement])}myFx.styles=formattedStyles}else{if(elem=="attributes"){myFx.attributes=aFxOptions[elem]}else{if(elem=="duration"){myFx.duration=aFxOptions[elem]}else{if(elem=="transition"){myFx.transition=this.transitions[aFxOptions[elem]]}else{if(elem=="end"){if(typeof aFxOptions[elem]==="function"){myFx.end=aFxOptions[elem];nokia.aduno.utils.warn("DEPRECATED nokia.aduno.medosui.Fx.effect: Please avoid the usage of the end function. Use the ended event instead")}else{nokia.aduno.utils.warn("end is not a function")}}else{if(elem=="step"){myFx.step=aFxOptions[elem]}else{if(elem=="fps"){myFx.fps=aFxOptions[elem]}else{if(elem=="start"){if(typeof aFxOptions[elem]==="function"){myFx.start=aFxOptions[elem];nokia.aduno.utils.warn("DEPRECATED nokia.aduno.medosui.Fx.effect: Please avoid the usage of the start function. Use the started event instead")}else{nokia.aduno.utils.warn("start is not a function")}}}}}}}}}}this.chain.push(myFx);return this},_preSuffixes:{left:["","px",true],right:["","px",true],top:["","px",true],bottom:["","px",true],height:["","px",true],width:["","px",true],"margin-top":["","px",true],"margin-bottom":["","px",true],"margin-left":["","px",true],"margin-right":["","px",true],margin:["","px",true],"padding-top":["","px",true],"padding-bottom":["","px",true],"padding-left":["","px",true],"padding-right":["","px",true],padding:["","px",true],filter:["Alpha(Opacity=",")",false]},_getPreSuffix:function(aStyleName){if(this._preSuffixes[aStyleName]!==undefined&&this._preSuffixes[aStyleName]!==null){return this._preSuffixes[aStyleName]}else{if(aStyleName.toLowerCase().indexOf("color")>-1){return["#","",false]}else{return["","",false]}}},_convertStyles:function(aStyleName,aValueArray){if(!aStyleName){throw new ArgumentError("Fx._convertStyles: aStyleName must be defined.")}if(!aValueArray||type(aValueArray)!=="array"||aValueArray.length!==2){throw new ArgumentError("Fx._convertStyles: aValueArray must be an two element array.")}var myStyleObject={};var preSuffix=this._getPreSuffix(aStyleName);if(aStyleName.indexOf("color")>-1){var startColor=convertColorHexToRgb(aValueArray[0]);var endColor=convertColorHexToRgb(aValueArray[1]);myStyleObject.startColor={};myStyleObject.endColor={};myStyleObject.startColor.r=startColor[0];myStyleObject.startColor.g=startColor[1];myStyleObject.startColor.b=startColor[2];myStyleObject.endColor.r=endColor[0];myStyleObject.endColor.g=endColor[1];myStyleObject.endColor.b=endColor[2]}else{if(aStyleName=="filter"){if(nokia.aduno.utils.browser.msie){preSuffix=this._getPreSuffix(aStyleName);myStyleObject.ieStartOpacity="Alpha(Opacity="+(parseFloat(aValueArray[0])*100)+")";myStyleObject.ieEndOpacity="Alpha(Opacity="+(parseFloat(aValueArray[1])*100)+")"}else{myStyleObject.startVal=parseFloat(aValueArray[0]);myStyleObject.endVal=parseFloat(aValueArray[1])}}else{myStyleObject.startVal=parseFloat(aValueArray[0]);myStyleObject.endVal=parseFloat(aValueArray[1])}}myStyleObject.prefix=preSuffix[0];myStyleObject.suffix=preSuffix[1];myStyleObject.isTransition=preSuffix[2];return myStyleObject},start:function(){if((this.currentFx!==null)&&(this.currentFx.elapsedTime<this.currentFx.duration)){this.currentFx.startTime=new Date().getTime()+this.currentFx.elapsedTime;this.currentFx.elapsedTime=0;this.currentFx.timer=setPeriodical(1000/this.currentFx.fps,this,this._run);this.fireEvent(new nokia.aduno.utils.Event("started",this.currentFx.id))}else{if(this.chain.length>0){this.currentFx=this.chain.shift();if(this.currentFx){this.currentFx.startTime=new Date().getTime();this.currentFx.timer=setPeriodical(1000/this.currentFx.fps,this,this._run);if(typeof this.currentFx.start==="function"){this.currentFx.start()}this.fireEvent(new nokia.aduno.utils.Event("started",this.currentFx.id))}else{this.currentFx=null}}}return this},stop:function(){if(this.currentFx){this.currentFx.elapsedTime=new Date().getTime()-this.currentFx.startTime;if(this.currentFx.timer){cancelPeriodical(this.currentFx.timer);this.currentFx.timer=null}this.fireEvent(new nokia.aduno.utils.Event("stopped",this.currentFx.id))}return this},cancel:function(){if(this.currentFx){if(this.currentFx.timer){cancelPeriodical(this.currentFx.timer)}var node=(this.subject.getReplica)?this.subject.getReplica().getRootElement():this.subject;var styles=this.currentFx.styles;var styleString="",value;for(var elems in styles){var currStyle=styles[elems];if(currStyle.startColor){var color=currStyle.startColor;value=convertColorRgbToHex(color.r,color.g,color.b)}else{if(currStyle.ieStartOpacity){value=currStyle.ieStartOpacity.split("=")[1].split(")")[0]}else{value=currStyle.startVal}}value=currStyle.prefix+value+currStyle.suffix;if(this.currentFx.combineStyles){styleString+="; "+elems+": "+value}else{node.style[elems]=value}}if(this.currentFx.combineStyles){node.setAttribute("style",styleString.slice(2))}var attributes=this.currentFx.attributes;for(var attr in attributes){node[attr]=attributes[attr][0].toFixed(0)}this.fireEvent(new nokia.aduno.utils.Event("cancelled",this.currentFx.id));this.chain=[];this.currentFx=null}return this},_run:function(){try{var deltaTime=new Date().getTime()-this.currentFx.startTime;var node=(this.subject.getReplica)?this.subject.getReplica().getRootElement():this.subject;var styles=this.currentFx.styles;var value,currStyleString="";for(var elems in styles){var currStyle=styles[elems];if(currStyle.startColor){value=convertColorRgbToHex(this.interpolate(currStyle.startColor.r,currStyle.endColor.r,deltaTime,this.currentFx.duration,currStyle.isTransition),this.interpolate(currStyle.startColor.g,currStyle.endColor.g,deltaTime,this.currentFx.duration,currStyle.isTransition),this.interpolate(currStyle.startColor.b,currStyle.endColor.b,deltaTime,this.currentFx.duration,currStyle.isTransition))}else{if(currStyle.ieStartOpacity){var elem1=currStyle.ieStartOpacity.split("=")[1].split(")")[0];var elem2=currStyle.ieEndOpacity.split("=")[1].split(")")[0];value=this.interpolate(parseFloat(elem1),parseFloat(elem2),deltaTime,this.currentFx.duration,currStyle.isTransition)}else{value=this.interpolate(currStyle.startVal,currStyle.endVal,deltaTime,this.currentFx.duration,currStyle.isTransition)}}value=currStyle.prefix+value+currStyle.suffix;if(this.currentFx.combineStyles){currStyleString+="; "+elems+": "+value}else{node.style[elems]=value}}if(this.currentFx.combineStyles){node.setAttribute("style",currStyleString.slice(2))}var attributes=this.currentFx.attributes;for(var attr in attributes){value=this.interpolate(attributes[attr][0],attributes[attr][1],deltaTime,this.currentFx.duration,true);node[attr]=value.toFixed(0)}if(deltaTime>=this.currentFx.duration){cancelPeriodical(this.currentFx.timer);if(typeof this.currentFx.end==="function"){this.currentFx.end()}this.fireEvent(new nokia.aduno.utils.Event("ended",this.currentFx.id));this.currentFx=null;if(this.chain.length>0){this.start()}}}catch(e){this.stop();nokia.aduno.utils.error(e.message)}},interpolate:function(aStart,aEnd,aDeltaTime,aDuration,aTransition){if(aDeltaTime<aDuration){if(aTransition){return((aEnd-aStart)*this.currentFx.transition(aDeltaTime/aDuration))+aStart}else{return((aEnd-aStart)*(aDeltaTime/aDuration))+aStart}}else{return aEnd}},clearAll:function(){this.subject=null;return this},transitions:{normal:function(x){return x},easeIn:function(x){return x*x},easeOut:function(x){return Math.pow(x,1/2)},circularIn:function(x){return(1-Math.sqrt(1-x*x))},circularOut:function(x){return Math.sqrt(1-(x-1)*(x-1))},elasticOut:function(x,d){return Math.pow(2,-10*x)*Math.sin((x*10-0.3/4)*(2*Math.PI)/0.3)+1},backShoot:function(t){var s=1.1;return t*t*((s+1)*t-s)},overShoot:function(t){return t+0.5*Math.sin(Math.PI*t)},overShoot2:function(t){return t+0.707*Math.sin(Math.PI*t)}}});var Collapsable=new Class({Extends:Behavior,Implements:Options,Name:"Collapsable",options:{duration:500,horizontal:false,vertical:true,startCollapsed:true},_collapsed:false,_collapseFx:null,_targetHeight:0,_targetWidth:0,initialize:function(aTemplate,aOptions){this._super(aTemplate);this.setOptions(aOptions);this._collapsed=this.getOption("startCollapsed");if(this._collapsed){this._replica.addCssClass("na_collapsed")}else{this._replica.removeCssClass("na_expanded")}},_calculateSize:function(){var currentSize=Dimensions.getSize(this._control.getRootElement());this._targetWidth=currentSize.x;this._targetHeight=currentSize.y},collapse:function(){if(!this._collapsed){var targetStyles={};this._calculateSize();if(this.getOption("horizontal")){targetStyles.width=[this._targetWidth,0]}if(this.getOption("vertical")){targetStyles.height=[this._targetHeight,0]}this._collapseFx.effect({duration:this.getOption("duration"),styles:targetStyles}).start();this._collapsed=true;this._replica.removeCssClass("na_expanded");this._replica.addCssClass("na_collapsed")}return this},expand:function(){if(this._collapsed){if(this.getOption("startCollapsed")){var node=this.getReplica().getRootElement();if(this.getOption("horizontal")){node.style.width=null}if(this.getOption("vertical")){node.style.height=null}this._calculateSize()}var targetStyles={};if(this.getOption("horizontal")){targetStyles.width=[0,this._targetWidth]}if(this.getOption("vertical")){targetStyles.height=[0,this._targetHeight]}this._collapseFx.effect({duration:this.getOption("duration"),styles:targetStyles}).start();this._collapsed=false;this._replica.addCssClass("na_expanded");this._replica.removeCssClass("na_collapsed")}return this},getNode:function(aControlNode){var node=this._super(aControlNode);if(this.getOption("startCollapsed")){if(this.getOption("horizontal")){node.style.width=0}if(this.getOption("vertical")){node.style.height=0}this._collapsed=true}this._collapseFx=new nokia.aduno.medosui.Fx(this);return node}});var Spinner=new Class({Extends:Control,Implements:FocusHandler,Name:"Spinner",initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._value=null;this._decreaseButton=new Button("decreaseButton");this._decreaseButton.setParent(this);this._decreaseButton.addEventHandler("selected",this.decreaseValue,this);this._inputField=new TextInput("input");this._inputField.setParent(this);this._inputField.addEventHandler("changed",this.valueChanged,this);this._increaseButton=new Button("increaseButton");this._increaseButton.setParent(this);this._increaseButton.addEventHandler("selected",this.increaseValue,this)},getNode:function(){var node=this._super();var decreaseNode=this._decreaseButton.getNode();if(!decreaseNode.parentNode||!decreaseNode.parentNode.tagName){this.getElement("decreaseButton").appendChild(this._decreaseButton.getNode());this.getElement("input").appendChild(this._inputField.getNode());this.getElement("increaseButton").appendChild(this._increaseButton.getNode())}return node},setMinimum:function(aNumber){this._minimum=aNumber;return this},setMaximum:function(aNumber){this._maximum=aNumber;return this},setDelta:function(aNumber){this._delta=aNumber;return this},setValue:function(aNumber){this._value=aNumber;this._inputField.setValue(aNumber);return this},getValue:function(){return this._value},decreaseValue:function(anEvent){if(this._value>=(this._minimum+this._delta)){var oldValue=this._value;this.setValue(Number(this._value)-this._delta);this.fireEvent(new nokia.aduno.utils.Event("selected",{oldValue:oldValue,newValue:this._value,Operation:null,Affected:null}))}return this},increaseValue:function(anEvent){if(this._value<=(this._maximum-this._delta)){var oldValue=this._value;this.setValue(Number(this._value)+this._delta);this.fireEvent(new nokia.aduno.utils.Event("selected",{oldValue:oldValue,newValue:this._value,Operation:null,Affected:null}))}return this},valueChanged:function(anEvent){var oldValue=this._value;var newValue=anEvent.getData().newValue;if(newValue>=this._minimum){if(newValue<=this._maximum){this.setValue(newValue)}else{this.setValue(this._maximum)}}else{this.setValue(this._minimum)}if(oldValue!==this._value){this.fireEvent(new nokia.aduno.utils.Event("selected",{oldValue:oldValue,newValue:this._value,Operation:null,Affected:null}))}return this}});var windowCount=0;var Window=new Class({Extends:Container,Name:"Window",initialize:function(aTemplate,aTemplateLibrary,aTitle){this._super(aTemplate,aTemplateLibrary);this.setTitle(aTitle);windowCount+=2;this.myCount=windowCount;this._replica.setStyle("window","position","absolute");this._replica.setStyle("window","zIndex",10000+this.myCount)},getTitle:function(){return this.getReplica().getText("title")},setTitle:function(aTitle){this.getReplica().setText("title",aTitle);return this},close:function(){this._removeNode();this.fireEvent("closed")}});var Dialog=new Class({Extends:Window,Name:"Dialog",initialize:function(aTemplate,aTemplateLibrary,aTitle,aModal){this._super(aTemplate,aTemplateLibrary,aTitle);this.setModal(!!aModal)},setModal:function(aModal){this._isModal=aModal;if(this._isModal){this._replica.setStyle("modal","position","absolute");this._replica.setStyle("modal","left","0px");this._replica.setStyle("modal","top","0px");this._replica.setStyle("modal","width","100%");this._replica.setStyle("modal","height","100%");this._replica.setStyle("modal","filter","alpha(opacity=50)");this._replica.setStyle("modal","opacity","0.50")}else{}},isModal:function(){return this._isModal}});var List=new Class({Extends:Control,Implements:FocusHandler,Name:"List",initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._children=[]},addChild:function(aControl){return this.addChildAt(this._children.length,aControl)},addChildAt:function(aIndex,aControl){aControl.setParent(this);this._children.splice(aIndex,0,aControl);if(this._replica.hasDOMSupport()&&this.getRootElement().parentNode&&this.getRootElement().parentNode.tagName){var root=this.getRootElement();var children=[];for(var i=0,c=root.childNodes.length;i<c;i++){if(root.childNodes[i].nodeType==1){children.push(root.childNodes[i])}}if(aIndex==children.length){root.appendChild(aControl.getNode())}else{root.insertBefore(aControl.getNode(),children[aIndex])}}this._updateChildCSSClasses(aIndex);this.fireEvent("changed");return aControl},moveChildTo:function(aIndexFrom,aIndexTo,aReplace){if(aIndexFrom==aIndexTo){return aIndexTo}var newIndex=aIndexTo;var child=this._children[aIndexFrom];if(!aReplace){this._children.splice(aIndexFrom,1);if(aIndexTo!==this._children.length){this._children.splice(aIndexTo,0,child)}else{this._children[this._children.length]=child}}else{this._children.splice(aIndexTo,1,child);this._children.splice(aIndexFrom,1)}if(newIndex===this._children.length){newIndex=newIndex-1}if(this._replica.hasDOMSupport()&&this.getRootElement().parentNode&&this.getRootElement().parentNode.tagName){var root=this.getRootElement();var children=[];for(var i=0,c=root.childNodes.length;i<c;i++){if(root.childNodes[i].nodeType==1){children.push(root.childNodes[i])}}if(!aReplace){if(aIndexFrom<aIndexTo){aIndexTo=aIndexTo+1}if(aIndexTo==children.length){root.appendChild(child.getNode())}else{root.insertBefore(child.getNode(),children[aIndexTo])}}else{root.replaceChild(child.getNode(),children[aIndexTo])}this._updateChildCSSClasses(aIndexTo)}this.fireEvent("changed");return newIndex},removeChild:function(aControl){if(!aControl||aControl._parent!==this){return null}var index=this.indexOf(aControl);return this.removeChildAt(index)},removeChildAt:function(aIndex){if((aIndex<0)||(aIndex>=this._children.length)){return null}var lastChild=this._children.length-1;var child=this._children[aIndex];if(child){var removed=this._children.splice(aIndex,1)[0];removed._removeNode();removed.setParent(null);this._updateChildCSSClasses(aIndex);this.fireEvent("changed");return removed}return null},removeAllChildren:function(){for(var i=(this._children.length-1);i>=0;i--){this.removeChildAt(i)}return this},getChildAt:function(aIndex){return this._children[aIndex]},indexOf:function(aControl){for(var index=0;index<this._children.length;index++){if(aControl===this._children[index]){return index}}return -1},getChildCount:function(){return this._children.length},getNode:function(){var node=this._super();for(var i=0,len=this._children.length;i<len;i++){var control=this._children[i];var childNode=control.getNode();this.getRootElement().appendChild(childNode)}return node},getFocusedChild:function(){for(var i=0,len=this._children.length;i<len;i++){if(this._children[i].isFocused()){return this._children[i]}}return null},_doBlur:function(aEvent){if(this._focusedChild){this._focusedChild.blur()}this._super()},_updateChildCSSClasses:function(aIndex){for(var i=this._children.length-1;i>=aIndex;--i){var replica=this._children[i].getReplica();replica.removeCssClass(i%2?"nam_odd":"nam_even");replica.addCssClass(i%2?"nam_even":"nam_odd")}if(aIndex===0){if(this._children[0]){this._children[0].getReplica().addCssClass("nam_first-child")}if(this._children[1]){this._children[1].getReplica().removeCssClass("nam_first-child")}}var lastIndex=this._children.length-1;if(aIndex===this._children.length||aIndex===lastIndex){if(lastIndex>=0){this._children[lastIndex].getReplica().addCssClass("nam_last-child")}if(lastIndex>0){this._children[lastIndex-1].getReplica().removeCssClass("nam_last-child")}}},_updateChildCSSClassesLastItem:function(){var lastIndex=this._children.length-1;var removeLastChild=lastIndex-1;while((removeLastChild>0)&&(!this._children[removeLastChild].isVisible())){--removeLastChild}if(removeLastChild>=0){this._children[removeLastChild].getReplica().removeCssClass("nam_last-child")}if(this._children[0]){this._children[0].getReplica().addCssClass("nam_first-child")}if(this._children[1]){this._children[1].getReplica().removeCssClass("nam_first-child")}if(this._children[lastIndex]){this._children[lastIndex].getReplica().addCssClass((lastIndex%2?"nam_even":"nam_odd")+" nam_last-child")}}});var SelectionList=new Class({Extends:List,Name:"SelectionList",initialize:function(aTemplate,aTemplateLibrary,aSelectedCssClass){this._super(aTemplate,aTemplateLibrary);this._selection=null;this._cssClass=aSelectedCssClass},addChildAt:function(aIndex,aControl){aControl.addEventHandler("selected",this._onSelected,this);return this._super(aIndex,aControl)},removeChildAt:function(aIndex){var control=this._super(aIndex);if(control){control.removeEventHandler("selected",this._onSelected,this)}return control},getSelectionIndex:function(){return this.indexOf(this._selection)},setSelectionIndex:function(aIndex){if(this._children.length>0){if(aIndex===this.getSelectionIndex()){return this._selection}if(aIndex<0){aIndex=0}if(aIndex>=this._children.length){aIndex=this._children.length-1}this.getChildAt(aIndex).fireEvent("selected")}return this._selection},getSelected:function(){return this._selection},clearSelection:function(){if(this._selection){if(this._selection._replica&&this._cssClass){this._selection._replica.removeCssClass(this._cssClass)}if(type(this._selection.deselected)==="function"){this._selection.deselected()}}this._selection=null},_onSelected:function(aEvent){var oldSelection=this._selection;var target=aEvent.source;if(target!==this._selection){this.clearSelection();this._selection=target;if(this._selection&&this._selection._replica&&this._cssClass){this._selection._replica.addCssClass(this._cssClass)}if((type(this._selection.selected)==="function")){this._selection.selected()}this.fireEvent(new nokia.aduno.utils.Event("selectionChanged",{selection:this._selection,previous:oldSelection,selectedIndex:this.getSelectionIndex(),itemData:aEvent.getData()}))}this.fireEvent(new nokia.aduno.utils.Event("selected",{selection:this._selection,previous:oldSelection,selectedIndex:this.getSelectionIndex(),itemData:aEvent.getData()}))}});var DropDown=new Class({Name:"DropDown",Extends:Container,initialize:function(aTemplate,aTemplateLibrary,aStringDataArray,aSelectedIndex){this._super(aTemplate,aTemplateLibrary);this._list=new SelectionList("DropDownList");var label="";this._dropDownButton=new CheckButton("DropDownButton",label,label,false);this._dropDownButton.addEventHandler("selected",this._toggleCollapse,this);this.setChildAt(this._dropDownButton,"dropDownButton");if(!aSelectedIndex){aSelectedIndex=0}if(aStringDataArray){label=aStringDataArray[0].text;this.setDataArray(aStringDataArray)}else{this.setDataArray([])}this.setChildAt(this._list,"dropDownList");this.setSelectionIndex(aSelectedIndex);this._list.addEventHandler("selected",this._selected,this);this._collapsable=new Collapsable("Collapsable",{duration:0,horizontal:false,vertical:true,startCollapsed:true});this._list.addBehavior(this._collapsable);this._collapsable.getReplica().addCssClass("na_DDCollaps");this._replica.addCssClass("dropDown","na_DDClose")},setSelectionByData:function(aData){for(var i=0,len=this._list.getChildCount();i<len;++i){if(this._list.getChildAt(i).data===aData){this.setSelectionIndex(i);return this}}return this},setSelectionIndex:function(aIndex){var elem=this._list.getChildAt(aIndex);if(elem){this._dropDownButton.setText(elem.getText());this._list.setSelectionIndex(aIndex)}return this},getSelectionIndex:function(){return this._list.getSelectionIndex()},getSelectionData:function(){return this._list.getSelected().data},setDataArray:function(aStringDataArray){for(var i=0,len=aStringDataArray.length;i<len;++i){var btn=this._list.getChildAt(i);if(!btn){btn=new Button("DropDownListElement");this._list.addChild(btn)}btn.setText(aStringDataArray[i].text);btn.data=aStringDataArray[i].data}var sel=this.getSelectionIndex();if(sel>=0){this._dropDownButton.setText(aStringDataArray[sel].text)}return this},addItem:function(aText,aData){var sel=this.getSelectionIndex();var btn=new Button("DropDownListElement");this._list.addChild(btn);btn.setText(aText);btn.data=aData;if(sel<0){this.setSelectionIndex(0)}return this},_toggleCollapse:function(){if(this._collapsable._collapsed){this._collapsable.expand();this._replica.addCssClass("dropDown","na_DDOpen");this._replica.removeCssClass("dropDown","na_DDClose")}else{this._collapsable.collapse();this._replica.removeCssClass("dropDown","na_DDOpen");this._replica.addCssClass("dropDown","na_DDClose")}},_collapse:function(){if(!this._collapsable._collapsed){this._collapsable.collapse();this._replica.removeCssClass("dropDown","na_DDOpen");this._replica.addCssClass("dropDown","na_DDClose")}},_selected:function(aEvent){var elem=this._list.getSelected();this.fireEvent(new nokia.aduno.utils.Event("selected",{data:elem.data}));this._dropDownButton.setText(elem.getText());this._collapse()}});var DefaultTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({Button:'<a class="nam_Btn" href="javascript:void(0)"><span id="button"></span></a>',CheckButton:'<div id="checkButton"><input type="checkbox" id="checkButtonButton"></input><span id="checkButtonText"></span></div>',RadioButton:'<div id="radioButton"><input type="radio" id="checkButtonButton"></input><span id="checkButtonText"></span></div>',RepeaterButton:'<button id="button"></button>',Collapsable:'<div id="collapsable" class="nam_Collapsable"></div>',Draggable:'<div id="draggable"></div>',Control:'<div id="control"></div>',Container:'<div id="container"></div>',Slider:'<div class="nam_Slid"><div id="sliderButton"></div></div>',SliderButton:'<div id="sliderButton" class="sliderbutton"></div>',ComboSlider:'<div id="comboSlider" class="nam_CombSlid"><div id="decreaseButton"></div><div id="slider"></div><div id="increaseButton"></div></div>',ComboSliderIncreaseButton:'<div id="increaseButton"><div class="nam_CombSlidBtnAdd"></div></div>',ComboSliderDecreaseButton:'<div id="decreaseButton"><div class="nam_CombSlidBtnSub"></div></div>',Dialog:'<div id="window"><div id="titlebar"><div id="title"></div></div><div id ="content"></div><div id="buttons"></div></div>',Image:'<img id="image" src="" alt=""></img>',Label:'<span id="label"></span>',Page:'<div id="page" class="nam_UserSelectNone"></div>',List:"<div></div>",SelectionList:'<div class="nam_List"></div>',POISelectionList:'<div class="nam_List"></div>',ListItem:'<div id="listitem" class="nam_ListItem"></div>',DropDown:'<div id="dropDown"><div id="dropDownButton"></div><div id="dropDownList"></div></div>',DropDownButton:'<div id="checkButton"><div id="checkButtonButton"><span id="checkButtonText"></span></div></div>',DropDownList:"<ul></ul>",DropDownListElement:'<li><a id="button"></a></li>',RadioGroup:'<div id="radiogroup"></div>',Scrollable:'<div id="scrollable"></div>',Spinner:'<span id="zoomSpinner"><span id="decreaseButton"></span><span id="input"></span><span id="increaseButton"></span></span>',TextInput:'<div class="nam_TextInput"><input id="input" type="text"></input><span></span></div>',Window:'<div id="window"><div id="titlebar"><div id="title"></div></div><div id="content"></div></div>',PluginControl:'<div id="pluginControl"></div>',PluginPage:'<div><div id="plugin"></div><div id="controls"></div></div>',ZoomIndicator:'<div class="zoomIndicator"><div id="zoomIndicator"></div></div>',Pagination:'<div class="nam_Pagination"><p id="previous"></p><ol id="list"></ol><p id="next"></p></div>',PagerList:"<ol></ol>",PagerItem:'<li id="listitem"></li>',Menu:'<div class="nam_Menu"><div id="list"></div></div>',MenuList:"<div></div>",MenuListItem:'<a class="nam_MenuListItem" href="javascript:void(0)"><span><em id="label"></em></span></a>',Modal:'<div id="modal" class="nam_Modal"></div>'});var Draggable=new Class({Name:"Draggable",Extends:Behavior,Implements:Options,options:{buttonMask:1,propagateMouseDown:false,allowTextHighlight:true},initialize:function(aTemplate,aOptions){this._super(aTemplate);this.setOptions(aOptions);this._isDragging=this._isOverElement=this._mouseDown=false},_attachEvents:function(aControlNode,aBehaviorRootNode){this._dragNode=new XNode(aBehaviorRootNode);var handlers={DOM_MOUSE_DOWN:this._handleMouseDown,DOM_MOUSE_OUT:this._handleMouseOut,DOM_MOUSE_OVER:this._handleMouseOver,DOM_SELECT_START:this._cancelEvents,DOM_DRAG:this._cancelEvents};for(var p in handlers){if(handlers.hasOwnProperty(p)){this._dragNode.addEventHandler(XNode[p],bindWithEvent(this,handlers[p]))}}},_removeEvents:function(){this._super();if(this._isDragging&&this._mouseMoveHandler){this._documentNode.removeEventHandler(XNode.DOM_MOUSE_MOVE,this._mouseMoveHandler)}if(this._mouseUpHandler){this._documentNode.removeEventHandler(XNode.DOM_MOUSE_UP,this._mouseUpHandler)}},_cancelEvents:function(aDomEvent){aDomEvent.preventDefault();aDomEvent.stopPropagation()},_handleMouseMove:function(aDomEvent){if(aDomEvent._originalEvent.target){if(aDomEvent._originalEvent.target.type!==undefined){if(this.getOption("allowTextHighlight")&&aDomEvent._originalEvent.target.type==="text"){return}}}if(this._mouseDown){this._isDragging=true}var pageX=aDomEvent.get("pageX"),pageY=aDomEvent.get("pageY");if(this._isDragging){this.fireEvent(new nokia.aduno.utils.Event("dragged",{deltaX:pageX-this._lastMouseX,deltaY:pageY-this._lastMouseY,mouseX:pageX,mouseY:pageY,domEvent:aDomEvent}))}this._lastMouseX=pageX;this._lastMouseY=pageY},_handleMouseUp:function(aDomEvent){if(this._mouseDown){this._documentNode.removeEventHandler(XNode.DOM_MOUSE_MOVE,this._mouseMoveHandler).removeEventHandler(XNode.DOM_MOUSE_UP,this._mouseUpHandler)}if(this._isDragging){this.fireEvent(new nokia.aduno.utils.Event("draggingEnded",{deltaX:0,deltaY:0,mouseX:aDomEvent.get("pageX"),mouseY:aDomEvent.get("pageY"),domEvent:aDomEvent}))}this._mouseDown=this._isDragging=false;this._updateState()},_handleMouseDown:function(aDomEvent){if(this._isOverElement&&aDomEvent._getWhich()===this.getOption("buttonMask")){this._mouseDown=true;this._lastMouseX=aDomEvent.get("pageX");this._lastMouseY=aDomEvent.get("pageY");if(!this.getOption("propagateMouseDown")){aDomEvent.preventDefault();aDomEvent.stopPropagation()}this._mouseMoveHandler=this._mouseMoveHandler||bindWithEvent(this,this._handleMouseMove);this._mouseUpHandler=this._mouseUpHandler||bindWithEvent(this,this._handleMouseUp);(this._documentNode=this._documentNode||new XNode(this.getOwnerDoc())).addEventHandler(XNode.DOM_MOUSE_MOVE,this._mouseMoveHandler).addEventHandler(XNode.DOM_MOUSE_UP,this._mouseUpHandler)}this._updateState();return false},_handleMouseOut:function(aDomEvent){this._isOverElement=false;this._updateState()},_handleMouseOver:function(aDomEvent){this._isOverElement=true;this._updateState()},_updateState:function(){this.getReplica()[this._isDragging&&this._isOverElement?"addCssClass":"removeCssClass"]("draggable","nm_Dragging")}});var RadioGroup=new Class({Extends:SelectionList,Name:"RadioGroup",initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary)},setSelectionIndex:function(aIndex){if(this._selection){this._selection.setState(false)}this._super(aIndex);if(this._selection){this._selection.setState(true)}return this},_onSelected:function(aEvent){if(this._selection){this._selection.setState(false)}this._super(aEvent);if(this._selection){this._selection.setState(true)}}});var Slider=new Class({Extends:Container,Name:"Slider",Implements:Options,options:{buttonMask:1,defaultSteps:3,defaultValue:0,size:{x:25,y:119},buttonSize:{x:25,y:17},updateDelay:100,updateTimeout:10000},initialize:function(aFlipFlowDirection,aSliderTemplate,aSliderButtonTemplate,aDraggableTemplate,aOptions){this._super(aSliderTemplate);this._doFlipFlowDirection=aFlipFlowDirection||false;this._isInitialized=false;this._stillDragging=false;this._min=0;this._max=1;this._delta=this._max-this._min;this._value=this._min;if(aOptions){this.setOptions(aOptions)}this.setSteps(this.getOption("defaultSteps"));this.setValue(this.getOption("defaultValue"));this._sliderButton=new Control(aSliderButtonTemplate||"SliderButton");this._sliderButton.addEventHandler("dragged",this._onDrag,this);this._sliderButton.addEventHandler("draggingEnded",this._onDragEnd,this);this.setChildAt(this._sliderButton,"sliderButton");this._sliderButtonDraggable=new Draggable(aDraggableTemplate);this._sliderButtonDraggable.getReplica().setStyle(TemplateReplica.ROOT_ID,"position","relative");this._sliderButton.addBehavior(this._sliderButtonDraggable);this._sliderButton.setCSSTrigger(Control.CSS_TRIGGER_OVER);this._sliderButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._onClick)},getNode:function(){var node=this._super();var sliderButtonNode=this._sliderButton.getNode();if(!sliderButtonNode.parentNode||!sliderButtonNode.parentNode.tagName){this.getElement("sliderButton").appendChild(sliderButtonNode)}if(!this._isInitialized&&!this.update(true)&&(typeof this.__updaterTimeout!=="number")){nokia.aduno.utils.debug("Slider: Started intialization");this.__updaterDelay=this.getOption("updateDelay");this.__updaterTimeout=this.getOption("updateTimeout");this.__updater=function(){this.update(true);if(!this._isInitialized){this.__updaterTimeout-=this.__updaterDelay;if(this.__updaterTimeout>0){this.__updaterId=setTimer(this.__updaterDelay,this,this.__updater);return}nokia.aduno.utils.warn("Slider: Intialization failed.")}else{nokia.aduno.utils.debug("Slider: intialized")}cancelTimer(this.__updaterId);delete this.__updater;delete this.__updaterId;delete this.__updaterDelay;delete this.__updaterTimeout};this.__updaterId=setTimer(this.__updaterDelay,this,this.__updater)}return node},setSteps:function(aSteps,aSuppressEvent){var maxStep=Math.round(aSteps)-1;if(maxStep>=2){this._max=maxStep;if(this._value>this._max){this._value=this._max}this._delta=this._max-this._min;if(!this._isInitialized){this.update(aSuppressEvent)}else{this._moveSliderToValue(aSuppressEvent)}}else{nokia.aduno.utils.warn("Slider.setSteps: Invalid number of steps. Must be greater than one.")}return this},setValue:function(aValue,aSuppressEvent){var step=Math.round(aValue);if(step<this._min){this._value=this._min;nokia.aduno.utils.warn("Slider.setValue: The passed value is less than the minimum and is set to the minimum.")}else{if(step>this._max){this._value=this._max;nokia.aduno.utils.warn("Slider.setValue: The passed value is greater than the maximum and is set to the maximum.")}else{this._value=step}}if(!this._isInitialized){this.update(aSuppressEvent)}else{this._moveSliderToValue(aSuppressEvent)}return this},getValue:function(){return this._value},getMinimum:function(){return this._min},getMaximum:function(){return this._max},getDelta:function(){return this._delta},isFlowDirectionFlipped:function(){return this._doFlipFlowDirection},update:function(aSuppressEvent){if(this._replica.setData){return}var element=this.getRootElement();this._buttonElement=this._sliderButton.getRootElement();this._size=nokia.aduno.dom.Dimensions.getSize(element);this._position=nokia.aduno.dom.Dimensions.getPosition(element);this._buttonSize=nokia.aduno.dom.Dimensions.getSize(this._buttonElement);this._buttonPosition=nokia.aduno.dom.Dimensions.getPosition(this._buttonElement);if(!this._size.x&&!this._size.y){this._size=this.getOption("size");this._buttonSize=this.getOption("buttonSize")}this._scrollWidth=this._size.x-this._buttonSize.x;this._scrollHeight=this._size.y-this._buttonSize.y;this._isHorizontal=(this._scrollWidth>0);this._scrollRange=this._isHorizontal?this._scrollWidth:this._scrollHeight;this._isInitialized=this._scrollRange>0;if(this._isInitialized){this._moveSliderToValue(aSuppressEvent)}return this._isInitialized},onShow:function(aSuppressEvent){nokia.aduno.utils.warn("DEPRECATED Slider.onShow: This function is deprecated and must not be called explicitly anymore. Please use the update function, if you need to update your values or set the proper options.");this.update(aSuppressEvent);return this},_checkBoundaries:function(){if(this._isHorizontal){if(this._buttonPosition.x<this._position.x){this._buttonPosition.x=this._position.x}if(this._buttonPosition.x>this._scrollWidth+this._position.x){this._buttonPosition.x=this._scrollWidth+this._position.x}}else{if(this._buttonPosition.y<this._position.y){this._buttonPosition.y=this._position.y}if(this._buttonPosition.y>this._scrollHeight+this._position.y){this._buttonPosition.y=this._scrollHeight+this._position.y}}return this},_mapPositionToValue:function(aButtonPositionX,aButtonPositionY){var tmpValue=0;if(this._isHorizontal){if(this._scrollWidth!==0){tmpValue=(this._delta*(aButtonPositionX-this._position.x))/this._scrollWidth}}else{if(this._scrollHeight!==0){tmpValue=(this._delta*(aButtonPositionY-this._position.y))/this._scrollHeight}}if(this._doFlipFlowDirection){tmpValue=this._delta-tmpValue}this._value=Math.round(tmpValue)+this._min;return this},_mapValueToPosition:function(aZeroBasedValue){var tmpx=Math.round(this._scrollWidth*aZeroBasedValue/this._delta);var tmpy=Math.round(this._scrollHeight*aZeroBasedValue/this._delta);if(this._doFlipFlowDirection){tmpx=this._scrollWidth-tmpx;tmpy=this._scrollHeight-tmpy}this._buttonPosition.x=tmpx+this._position.x;this._buttonPosition.y=tmpy+this._position.y;return this},_setSliderButtonPosition:function(){var dir=this._isHorizontal?"x":"y";this._sliderButtonDraggable.getReplica().setStyle(TemplateReplica.ROOT_ID,{x:"left",y:"top"}[dir],Math.floor(this._buttonPosition[dir]-this._position[dir])+"px");return this},_moveSliderToValue:function(aSuppressEvent){if(!this._isInitialized||this._stillDragging){return this}this._stillDragging=true;this._mapValueToPosition(this._value)._setSliderButtonPosition();if(!aSuppressEvent){this.fireEvent(new nokia.aduno.utils.Event("changed",{value:this._value}))}this._stillDragging=false;return this},_onDrag:function(aEvent){if(this._stillDragging||!aEvent||!aEvent.getData()){return}if(!this._isInitialized){this.update()}this._stillDragging=true;if(this._scrollRange!==0){var dir=this._isHorizontal?"x":"y";this._buttonPosition[dir]+=aEvent.getData()["delta"+dir.toUpperCase()]||0;this._checkBoundaries()}this._setSliderButtonPosition()._mapPositionToValue(this._buttonPosition.x,this._buttonPosition.y);this.fireEvent(new nokia.aduno.utils.Event("changed",{value:this._value}));this._stillDragging=false},_onDragEnd:function(){this.setValue(this._value)},_onClick:function(aDomEvent){var button=aDomEvent._getWhich();var targetButton=this.getOption("buttonMask");if(this._stillDragging||button!==targetButton){return}if(!this._isInitialized){this.update()}else{this._position=nokia.aduno.dom.Dimensions.getPosition(this.getRootElement())}this._stillDragging=true;if(this._scrollRange!==0){var dir=this._isHorizontal?"x":"y";this._buttonPosition[dir]=aDomEvent.get("page"+dir.toUpperCase());this._checkBoundaries()}this._mapPositionToValue(this._buttonPosition.x,this._buttonPosition.y);this._stillDragging=false;this._moveSliderToValue();aDomEvent.stopPropagation()}});var RepeaterButton=new Class({Name:"RepeaterButton",Extends:Button,Implements:Options,_repeatIntervalId:null,_removeNextClickEvent:false,options:{interval:100},initialize:function(aTemplate,aText,aOptions){this._super(aTemplate,aText);this.setOptions(aOptions);this._replica.addEventHandler(XNode.DOM_MOUSE_DOWN,this,this._enableInterval);this._replica.addEventHandler(XNode.DOM_MOUSE_UP,this,this._disableInterval);this._replica.addEventHandler(XNode.DOM_MOUSE_OUT,this,this._disableInterval)},_enableInterval:function(aEvent){this._switchInterval(aEvent,true)},_disableInterval:function(aEvent){this._switchInterval(aEvent,false)},_switchInterval:function(aEvent,aEnable){if(aEnable){this._repeatIntervalId=setPeriodical(this.getOption("interval"),this,this._fireSelected);this._mouseDownTime=getTimeStamp()}else{if(this._repeatIntervalId){cancelPeriodical(this._repeatIntervalId);if(getTimeStamp()-this._mouseDownTime>=this.getOption("interval")){this._removeNextClickEvent=true}}}aEvent.stopPropagation()},_fireSelected:function(){this.fireEvent("selected")},_onClick:function(aEvent){if(this._removeNextClickEvent){this._removeNextClickEvent=false;aEvent.stopPropagation();aEvent.preventDefault()}else{this._super(aEvent)}}});var ComboSlider=new Class({Extends:Container,Name:"ComboSlider",initialize:function(aFlipFlowDirection,aTemplate,aTemplateLibrary,aSliderOptions){this._super(aTemplate,aTemplateLibrary);this._slider=new Slider(aFlipFlowDirection,null,null,null,aSliderOptions);this.setChildAt(this._slider,"slider");this._increaseButton=new Button("ComboSliderIncreaseButton");this.setChildAt(this._increaseButton,"increaseButton");this._decreaseButton=new Button("ComboSliderDecreaseButton");this.setChildAt(this._decreaseButton,"decreaseButton");this._increaseButton.addEventHandler("selected",function(){this.changeValue(true)},this);this._decreaseButton.addEventHandler("selected",function(){this.changeValue(false)},this);this._slider.addEventHandler("changed",this._onSliderChange,this);this._increaseButton.setCSSTrigger(Control.CSS_TRIGGER_OVER);this._increaseButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._decreaseButton.setCSSTrigger(Control.CSS_TRIGGER_OVER);this._decreaseButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN)},setSteps:function(aSteps,aSuppressEvent){this._slider.setSteps(aSteps,aSuppressEvent);return this},getValue:function(){return this._slider.getValue()},getMinimum:function(){return this._slider.getMinimum()},getMaximum:function(){return this._slider.getMaximum()},changeValue:function(aIsIncrease,aSuppressEvent){var value=this._slider.getValue();if(aIsIncrease){if(value<this._slider.getMaximum()){this._slider.setValue(++value,aSuppressEvent)}}else{if(value>this._slider.getMinimum()){this._slider.setValue(--value,aSuppressEvent)}}return this},setValue:function(value,aSuppressEvent){this._slider.setValue(value,aSuppressEvent);return this},_onSliderChange:function(aEvent){var value=aEvent.getData().value;this.fireEvent(new nokia.aduno.utils.Event("changed",{value:value}))},_triggerOver:function(){this._addCssClass("nm_MouseOver")},_triggerOut:function(){this._removeCssClass("nm_MouseOver")},onShow:function(aSuppressEvent){this._slider.onShow(aSuppressEvent)}});var Static=new Class({Extends:Control,Name:"Static",initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary)},setTextAt:function(aText,aPositionId){this._replica.setText(aPositionId,aText);return this},getTextAt:function(aPositionId){return this._replica.getText(aPositionId)},setAttributeAt:function(aAttributeName,aAttributeValue,aId){this._replica.setAttribute(aId,aAttributeName,aAttributeValue);return this},getAttributeAt:function(aAttributeName,aId){return this._replica.getAttribute(aId,aAttributeName)}});var ListItem=new Class({Extends:Container,Implements:Options,Name:"ListItem",initialize:function(aTemplate,aTemplateLibrary,aOptions){this.setOptions(aOptions);if(this._options.isFlexible){this._isFlexible=true;this._collapsed=true}this._super(aTemplate,aTemplateLibrary);this._controls=null;this._model=null;this._updated=false;this.getReplica().addEventHandler("click",this,this._onClick);if(!nokia.aduno.utils.platform.maemo){this.setCSSTrigger(Control.CSS_TRIGGER_OVER);this.setCSSTrigger(Control.CSS_TRIGGER_DOMFOCUS)}else{this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this,this._cssTriggerOut)}this.setCSSTrigger(Control.CSS_TRIGGER_DOWN)},setModel:function(aModel){if(this._updated){this._updated=false;if(this._controls!==null){var nodes=this._controls;this._controls=null;for(var i=nodes.length-1;i>-1;--i){nodes[i].detachFromParent()}}}this._model=aModel},getModel:function(){return this._model},update:function(){if(!this._model||this._updated||this._isFlexible){return}this._updated=true;this._controls=[];var me=this;Collection.forEach(this._model,function(value,key){if(value===null||value===undefined){return}var control=/text|label/.test(key)?new Label(null,value):/image|icon/.test(key)?new Image(null,value):new Label(null,String(value));control.setParent(me);me._controls.push(control);(me.getElement(key)||me.getRootElement()).appendChild(control.getNode())})},addButtonWithHandler:function(aButton,aHandler,aArguments){if(nokia.aduno.utils.browser.touch||(/touch/i.test(location.search))){if(this._isFlexible){var realHandler=function(){this.collapse(!this._collapsed);aHandler.apply({},aArguments)}}else{var realHandler=function(){aHandler.apply({},aArguments)}}aButton.addEventHandler("selected",realHandler,this);this.setChildAt(aButton||new nokia.aduno.medosui.Button(null,"button"),"button",true,false)}},getNode:function(){if(this._isFlexible){if(!this._layouted){this._layoutModel();this._layouted=true}}else{this.update()}return this._super()},selected:function(){if(this._isFlexible){this.collapse(false)}},deselected:function(){if(this._isFlexible){this.collapse(true);this._removeCssClass("nm_DomFocus")}},_onClick:function(aEvent){if(this._isFlexible){this.collapse(!this._collapsed);this.fireEvent(new nokia.aduno.utils.Event("selected",this._model))}else{this.fireEvent("selected")}},collapse:function(aEnable){this._collapsed=aEnable;this.getReplica()[this._collapsed===true?"removeCssClass":"addCssClass"]("listitem","nam_FlexibleListItemExp")},setConnectMenu:function(aConnectMenu){this._connectMenu=aConnectMenu;this.setChildAt(this._connectMenu,"connect",true,true)},setNo:function(aNo){this._no=aNo;this.getReplica().setText("no",aNo)},getNo:function(){return this._no},_layoutModel:function(){this._model=this._options;if(!this._model){return}if(this._model.height){this.getReplica().setStyle("listitem","height",this._model.height)}if(this._model.title){this.setChildAt(new Label(null,this._model.title),"label",true,true)}if(this._model.iconUrl){this.image=new Image(null,this._model.iconUrl);this.setChildAt(this.image,"icon",true,true);this.getReplica().setStyle("icon","float",this._model.imageSide||"left");if(this._model.imageSize){this.image.getReplica().setStyle("image","height",this._model.imageSize.y);this.image.getReplica().setStyle("image","width",this._model.imageSize.x)}}if(this._model.addrStreetName){this.setChildAt(new Label(null,this._model.addrStreetName+" "+this._model.addrHouseNumber),"text1")}if(this._model.geoDistance){this.setChildAt(new Label(null,this._model.geoDistance),"text2")}if(this._model.details){this.setChildAt(new Label(null,this._model.details+", "+this._model.phoneNumber),"description")}}});var Pagination=new Class({Extends:Container,Name:"Pagination",initialize:function(aTemplate,aTemplateLibrary,aItemsTotal,aItemsPerPage){this._super(aTemplate||"Pagination",aTemplateLibrary);this._itemsTotal=aItemsTotal||0;this._itemsPerPage=aItemsPerPage||Pagination.ITEMS_PER_PAGE_DEFAULT;this.length=this._calculateLength();this._currentPageIndex=0;this._previousControl=null;this._nextControl=null;this._list=null;if(this.length>0){this._render();this._update(0)}},next:function(){if(this._currentPageIndex<this.length-1){this._update(this._currentPageIndex+1)}return this},previous:function(){if(this._currentPageIndex>0){this._update(this._currentPageIndex-1)}return this},getPageIndex:function(){return this._currentPageIndex},setPageIndex:function(aPageIndex){if(aPageIndex>=0&&aPageIndex<this.length){this._update(aPageIndex)}return this},getItemsTotal:function(){return this._itemsTotal},setItemsTotal:function(aItemsTotal){this._itemsTotal=aItemsTotal;this.length=this._calculateLength();if(this._render){this._render()}this._update(0);return this},getItemsPerPage:function(){return this._itemsPerPage},reset:function(){this._itemsTotal=0;this.length=this._calculateLength();delete this._currentPageIndex;this._previousControl.hide();this._nextControl.hide();return this},_update:function(aPageIndex){this._currentPageIndex=aPageIndex;var first=aPageIndex===0,last=aPageIndex===(this.length-1);this._previousControl[first?"disable":"enable"]();this._previousControl[first?"hide":"show"]();this._nextControl[last?"disable":"enable"]();this._nextControl[last?"hide":"show"]();var startRangeAt,endRangeAt,selectionListIndex,cutOff=(Pagination.PAGES_PER_RANGE-1)/2;if(this.length<=Pagination.PAGES_PER_RANGE){selectionListIndex=aPageIndex;startRangeAt=0;endRangeAt=this.length-1}else{if(aPageIndex<cutOff){selectionListIndex=aPageIndex;startRangeAt=0;endRangeAt=Pagination.PAGES_PER_RANGE-1}else{if(this.length-1-aPageIndex<cutOff){selectionListIndex=Pagination.PAGES_PER_RANGE-(this.length-aPageIndex);endRangeAt=this.length-1;startRangeAt=endRangeAt-Pagination.PAGES_PER_RANGE+1}else{selectionListIndex=cutOff;startRangeAt=aPageIndex-cutOff;endRangeAt=aPageIndex+cutOff}}}this._list.removeAllChildren();for(var i=startRangeAt;i<=endRangeAt;i++){listItem=new nokia.aduno.medosui.ListItem("PagerItem");listItem.setModel({text:i+1+""});this._list.addChild(listItem)}this._list.setSelectionIndex(selectionListIndex);this.fireEvent(new nokia.aduno.utils.Event("changed",{pageIndex:aPageIndex,offset:this._currentPageIndex*this._itemsPerPage,itemsPerPage:this._itemsPerPage}))},_calculateLength:function(){return Math.ceil(this._itemsTotal/this._itemsPerPage)},_render:function(){for(var i=0,buttons=["Previous","Next"],button;(button=buttons[i]);i++){var lowerCased=button.toLowerCase(),control=(this["_"+lowerCased+"Control"]=new nokia.aduno.medosui.Button("Pager"+button));this.setChildAt(control,lowerCased);control.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_CLICK,this,this[lowerCased])}this._list=new nokia.aduno.medosui.SelectionList("PagerList",null,"nam_selected");this._list.addEventHandler("selected",this._onSelected,this);this.setChildAt(this._list,"list");this._render=null},_onSelected:function(aEvent){var pageIndex=parseInt(aEvent.getData().selection.getModel().text,10)-1;if(pageIndex!==this._currentPageIndex){this._update(pageIndex)}}});Pagination.ITEMS_PER_PAGE_DEFAULT=8;Pagination.PAGES_PER_RANGE=9;var POIListItem=new Class({Extends:ListItem,Name:"POIListItem",initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._collapsed=true;nokia.aduno.utils.warn("DEPRECATED nokia.aduno.medosui.POIListItem Please avoid the usage of this class. Use the extended ListItem instead")},collapse:function(aEnable){this._collapsed=aEnable;this.getReplica()[this._collapsed===true?"removeCssClass":"addCssClass"]("listitem","nam_POIListItemExp")},selected:function(){this.collapse(false)},deselected:function(){this.collapse(true);this._removeCssClass("nm_DomFocus")},setConnectMenu:function(aConnectMenu){this._connectMenu=aConnectMenu;this.setChildAt(this._connectMenu,"connect",true,true)},setNo:function(aNo){this._no=aNo;this.getReplica().setText("no",aNo)},getNo:function(){return this._no},_layoutModel:function(){if(!this._model){return}if(this._model.height){this.getReplica().setStyle("listitem","height",this._model.height)}if(this._model.title){this.setChildAt(new Label(null,this._model.title),"label",true,true)}if(this._model.iconUrl){this.image=new Image(null,this._model.iconUrl);this.setChildAt(this.image,"icon",true,true);this.getReplica().setStyle("icon","float",this._model.imageSide||"left");if(this._model.imageSize){this.image.getReplica().setStyle("image","height",this._model.imageSize.y);this.image.getReplica().setStyle("image","width",this._model.imageSize.x)}}if(this._model.addrStreetName){this.setChildAt(new Label(null,this._model.addrStreetName+" "+this._model.addrHouseNumber),"text1")}if(this._model.geoDistance){this.setChildAt(new Label(null,this._model.geoDistance),"text2")}if(this._model.details){this.setChildAt(new Label(null,this._model.details+", "+this._model.phoneNumber),"description")}},addButtonWithHandler:function(aButton,aHandler,aArguments){if(nokia.aduno.utils.browser.touch||(/touch/i.test(location.search))){var realHandler=function(){this.collapse(!this._collapsed);aHandler.apply({},aArguments)};aButton.addEventHandler("selected",realHandler,this);this.setChildAt(aButton||new nokia.aduno.medosui.Button(null,"button"),"button",true,false)}},getNode:function(){if(!this._layouted){this._layoutModel();this._layouted=true}return this._super()},_onClick:function(){this.collapse(!this._collapsed);this.fireEvent(new nokia.aduno.utils.Event("selected",this._model))},update:function(){}});var Menu=new nokia.aduno.utils.Class({Extends:Container,Name:"Menu",initialize:function(aMenuListItems,aPosition,aFocusFirstChild,aListTemplate,aContainerTemplate,aTemplateLibrary){this._super(aContainerTemplate,aTemplateLibrary);this._focusFirstChild=aFocusFirstChild;this._list=new SelectionList(aListTemplate||"MenuList");this.setChildAt(this._list,"list");for(var i=0,item;(item=aMenuListItems[i]);i++){this._list.addChild(item)}this._position=aPosition||{top:0,left:0};this._list.addEventHandler("selected",this.hide,this)},getNode:function(){var node=this._super();for(var property in this._position){if(this._position.hasOwnProperty(property)){this.getReplica().getRootElement().style[property]=this._position[property]+(type(this._position[property])==="number"?"px":"")}}if(this._focusFirstChild){var firstChild=this._list.getChildAt(0);if(firstChild){firstChild.focus();setTimeout(function(){try{firstChild.getRootElement().focus()}catch(e){}},0)}}return node},insertBefore:function(aItem,aBefore){aItem.detachFromParent();var i=this._list.indexOf(aBefore);if(i!==-1){this._list.addChildAt(i,aItem)}else{this.add(aItem)}},add:function(aItem){aItem.detachFromParent();this._list.addChild(aItem)},remove:function(aItem){aItem.detachFromParent()}});var MenuListItem=new Class({Extends:ListItem,Name:"MenuListItem",initialize:function(aId,aIconUrl,aLabel,aHandler,aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._id=null;this._handler=aHandler||null;this.setModel({id:aId,icon:aIconUrl,label:aLabel})},setModel:function(aModel){if(this._updated){this._updated=false;if(this._childNodes!==null){var nodes=this._childNodes;this._childNodes=null;for(var i=nodes.length-1;i>-1;--i){nodes[i].detachFromParent()}}}this._id=aModel.id;this._model={icon:aModel.icon,label:aModel.label}},getId:function(){return this._id||-1},selected:function(){if(typeof this._handler==="function"){this._handler.apply({},[this.getId()])}}});var UIVisitor=new Class({Name:"UIVisitor",initialize:function(){},visitAll:function(aArray){for(var i=0,len=aArray.length;i<len;i++){aArray[i].accept(this)}},visitContainer:function(aContainer){this.visitAll(aContainer._children)},visitList:function(aList){this.visitAll(aList._children)},visitMenu:function(aMenu){this.visitContainer(aMenu)},visitPage:function(aPage){this.visitContainer(aPage)},visitRadioGroup:function(aRadioGroup){this.visitSelectionList(aRadioGroup)},visitSelectionList:function(aSelectionList){this.visitList(aSelectionList)}});var TranslationVisitor=new Class({Extends:UIVisitor,Name:"TranslationVisitor",initialize:function(aTranslator){this._translator=aTranslator},_translate:function(aString){return this._translator.translate(aString)},visitButton:function(aButton){aButton.setText(this._translate(aButton.getText()))},visitCheckButton:function(aButton){aButton.setText(this._translate(aButton.getText()))},visitDialog:function(aDialog){this.visitWindow(aDialog)},visitLabel:function(aLabel){aLabel.setText(this._translate(aLabel.getText()))},visitImage:function(aImage){aImage.setSource(this._translate(aImage.getSource()))},visitRepeaterButton:function(aRepeaterButton){this.visitButton(aRepeaterButton)},visitWindow:function(aWindow){aWindow.setTitle(this._translate(aWindow.getTitle()))}});var Modal=new Class({Extends:Behavior,Name:"Modal",initialize:function(aTemplate,aOptions){this._super(aTemplate);if(nokia.aduno.utils.browser.msie){document.getElementsByTagName("body")[0].style.height="100%"}if(!(aOptions||{}).stick){this.getReplica().addEventHandler("modal","click",this,function(){if(this._control){this._control.hide()}})}},setControl:function(aControl){var ret=this._super(aControl);this._control.addEventHandler("shown",function(){this.getReplica().setStyle("modal","display","block")},this);this._control.addEventHandler("hidden",function(){this.getReplica().setStyle("modal","display","none")},this);return ret}});var _factory;var Factory=new Class({Name:"Factory",initialize:function(){if(!_factory){var detectedFactory=Factory._detectFactory();_factory=(detectedFactory)?detectedFactory:this}return _factory},createBehavior:function(aTemplate){return new Behavior(aTemplate)},createButton:function(aTemplate,aText){return new Button(aTemplate,aText)},createCheckButton:function(aTemplate,aText,aValue,aState){return new CheckButton(aTemplate,aText,aValue,aState)},createCollapsable:function(aTemplate,aOptions){return new Collapsable(aTemplate,aOptions)},createDialog:function(aTemplate,aTemplateLibrary,aTitle,aModal){return new Dialog(aTemplate,aTemplateLibrary,aTitle,aModal)},createImage:function(aTemplate,aUri){return new Image(aTemplate,aUri)},createLabel:function(aTemplate,aText){return new Label(aTemplate,aText)},createList:function(aTemplate,aTemplateLibrary){return new List(aTemplate,aTemplateLibrary)},createPage:function(aDomNode,aTemplate,aTemplateLibrary){return new Page(aDomNode,aTemplate,aTemplateLibrary)},createScrollable:function(aTemplate){return new Scrollable(aTemplate)},createSpinner:function(aTemplate,aTemplateLibrary){return new Spinner(aTemplate,aTemplateLibrary)},createTextInput:function(aTemplate,aValue,aOptions){return new TextInput(aTemplate,aValue,aOptions)},createWindow:function(aTemplate,aTemplateLibrary,aTitle){return new Window(aTemplate,aTemplateLibrary,aTitle)}});Factory._detectFactory=function(){return null};Factory._reset=function(){_factory=null};var DefaultSnCTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({ListItem:'<a href="javascript:void(0)" id="listitem" class="nam_ListItem"></a>',POIListItem:'<a href="javascript:void(0)" id="listitem" class="nam_ListItem nam_POIListItem"><span id="no" class="count"></span><span id="icon" class="icon"></span><span id="infoArea" class="infoSmall"><span id="label" class="label"></span><span class="text1"><span id="text1"></span></span><span class="clearFloat"></span><div class="description1"><span id="description"></span></div></span><span class="text2"><span id="text2"></span></span></a>',PagerPrevious:'<a class="nam_Btn" href="javascript:void(0)"><span>Show previous results</span></a>',PagerNext:'<a class="nam_Btn" href="javascript:void(0)"><span>Show more results</span></a>',Search:'<div class="nam_TextInput nam_Search"><input id="input" type="text"></input><span></span></div>',FlexibleListItem:'<a href="javascript:void(0)" id="listitem" class="nam_ListItemFlexible nam_FlexibleListItem"><span id="no" class="count"></span><span id="icon" class="icon"></span><span id="infoArea" class="infoSmall"><span id="label" class="label"></span><span class="text1"><span id="text1"></span></span><span class="clearFloat"></span><div class="description1"><span id="description"></span></div></span><span class="text2"><span id="text2"></span></span></a>'},DefaultTemplateLibrary);var DefaultTouchTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({SelectionList:'<ul id="list" class="nam_List"></ul>',ListButton:'<a class="nam_Btn nam_LisBtn" href="javascript:void(0)"><span id="button"></span></a>',ListItem:'<a href="javascript:void(0)" id="listitem" class="nam_ListItem"><span id="button"></span></a>',POIListItem:'<a href="javascript:void(0)" id="listitem" class="nam_ListItem nam_POIListItem"><span id="no" class="nam_Num"></span><span id="icon" class="nam_Ico"></span><span id="infoArea" class="nam_POIObj"><span id="label" class="nam_POIObjLabel"></span><span class="nam_POIObjDesc"><span id="text1"></span></span><span class="nam_POIObjDescAdv"><span id="description"></span></span><span class="clearFloat" style="clear:both;"></span></span><div class="nam_POIButtonAndDistance"><span id="button"></span><span class="nam_POIObjDis"><span id="text2"></span></span></div></a>',Menu_Var2:'<div class="nam_Menu_Var2"><div id="list"></div></div>',MenuListItem:'<a class="nam_MenuListItem" href="javascript:void(0)"><span class="nam_MenuBG"><em id="label"></em></span></a>',PagerPrevious:'<a class="nam_PagBtnBg" href="javascript:void(0)"><span>Show previous results</span></a>',PagerNext:'<a class="nam_PagBtnBg" href="javascript:void(0)"><span class="nam_PagBtn"><span>Show more results</span></span></a>',CheckButton:'<div class="nam_CheckButton" id="checkButton"><input type="checkbox" id="checkButtonButton"></input><span class="nam_UserSelectNone" id="checkButtonText"></span></div>',FlexibleListItem:'<a href="javascript:void(0)" id="listitem" class="nam_ListItemFlexible nam_FlexibleListItem"><span id="no" class="nam_Num"></span><span id="icon" class="nam_Ico"></span><span id="infoArea" class="nam_POIObj"><span id="label" class="nam_POIObjLabel"></span><span class="nam_POIObjDesc"><span id="text1"></span></span><span class="nam_POIObjDescAdv"><span id="description"></span></span><span class="clearFloat" style="clear:both;"></span></span><div class="nam_POIButtonAndDistance"><span id="button"></span><span class="nam_POIObjDis"><span id="text2"></span></span></div></a>'},DefaultTemplateLibrary);var DefaultWebTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({SelectionList:'<ul id="list" class="nam_List"></ul>',ListItem:'<li id="listitem" class="nam_ListItem"></li>',POISelectionList:'<ul class="nam_List"></ul>',POIListItem:'<li id="listitem" class="nam_ListItem nam_POIListItem"><div id="no" class="count"></div><div id="icon" class="icon"></div><div id="infoArea" class="infoSmall"><div id="label" class="label"></div><div class="text1"><span id="text1"></span></div><div class="text2"><span id="text2"></span></div><div class="clearFloat"> </div><div class="description1"><span id="description"></span></div></div></li>',PagerNext:'<p class="nam_Next"><em>Next</em></p>',PagerPrevious:'<p class="nam_Previous"><em>Previous</em></p>',Search:'<div class="nam_TextInput nam_Search"><input id="input" type="text"></input><span></span></div>',FlexibleListItem:'<li id="listitem" class="nam_ListItemFlexible nam_FlexibleListItem"><div id="no" class="count"></div><div id="icon" class="icon"></div><div id="infoArea" class="infoSmall"><div id="label" class="label"></div><div class="text1"><span id="text1"></span></div><div class="text2"><span id="text2"></span></div><div class="clearFloat"> </div><div class="description1"><span id="description"></span></div></div></li>'},DefaultTemplateLibrary);nokia.aduno.medosui.addMembers({getDefaultTemplateLibrary:getDefaultTemplateLibrary,loadAssets:loadAssets,getLayout:getLayout,TemplateResolver:TemplateResolver,KeyEventManager:KeyEventManager,S60KeyEventManager:S60KeyEventManager,FocusHandler:FocusHandler,Control:Control,Button:Button,Container:Container,Image:Image,TextInput:TextInput,Label:Label,CheckButton:CheckButton,Behavior:Behavior,Scrollable:Scrollable,Page:Page,Fx:Fx,Collapsable:Collapsable,Spinner:Spinner,Window:Window,Dialog:Dialog,List:List,SelectionList:SelectionList,DropDown:DropDown,DefaultTemplateLibrary:DefaultTemplateLibrary,Draggable:Draggable,RadioGroup:RadioGroup,Slider:Slider,RepeaterButton:RepeaterButton,ComboSlider:ComboSlider,Static:Static,ListItem:ListItem,Pagination:Pagination,POIListItem:POIListItem,Menu:Menu,MenuListItem:MenuListItem,UIVisitor:UIVisitor,TranslationVisitor:TranslationVisitor,Modal:Modal,Factory:Factory,DefaultSnCTemplateLibrary:DefaultSnCTemplateLibrary,DefaultTouchTemplateLibrary:DefaultTouchTemplateLibrary,DefaultWebTemplateLibrary:DefaultWebTemplateLibrary})};new function(){new nokia.aduno.Ns("nokia.aduno.storage");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var json,JSON;JSON=window.JSON?window.JSON:{};json={parse:function(text,reviver){if(reviver===undefined){return JSON.parse(text,_dateReviver)}return JSON.parse(text,reviver)},stringify:function(value,replacer,space){return JSON.stringify(value,replacer,space)}};var _dateReviver=function(key,value){var a;if(typeof value==="string"){a=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value);if(a){return new Date(Date.UTC(+a[1],+a[2]-1,+a[3],+a[4],+a[5],+a[6],a[7]))}}return value};if(!window.JSON){(function(){function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z"};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 JSON.stringify!=="function"){JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else{if(typeof space==="string"){indent=space}}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}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")}}}())}var Persistence=new Class({Name:"Persistence",initialize:function(){this._registry={};this._storage=null;this._stringCodec=null},setStorage:function(aStorageStrategy){this._storage=aStorageStrategy;this._storageReady=false},setStringCodec:function(aCodec){this._stringCodec=aCodec},register:function(aObject,aPersistenceKey){if(!aObject){nokia.aduno.utils.warn("add Serializable - no parameter specified");return}var persistenceKey=(aPersistenceKey)?aPersistenceKey:Persistence.DEFAULT_STORAGE_KEY;if(this._registry[persistenceKey]){if(this._registry[persistenceKey]===aObject){nokia.aduno.utils.warn("attempt to register the same object again for key "+persistenceKey+". skipping...")}else{nokia.aduno.utils.warn("attempt to register a different object for already registered key "+persistenceKey+". skipping...")}return}this._registry[persistenceKey]=aObject},unregisterObject:function(aSerializable){for(var key in this._registry){if(aSerializable===this._registry[key]){this.unregisterKey(key);return}}},unregisterKey:function(aKey){delete this._registry[aKey]},storeAll:function(){this._storage.begin();for(var key in this._registry){this.storeObject(this._registry[key],key)}this._storage.commit()},restoreAll:function(){for(var key in this._registry){this.restoreObject(this._registry[key],key)}},storeObject:function(aObject,aPersistenceKey){if(!this._storageReady){this.begin()}this._currentPersistenceKey=(aPersistenceKey)?aPersistenceKey:Persistence.DEFAULT_STORAGE_KEY;if("function"===type(aObject.serialize)){aObject.serialize(this)}else{if(aObject&&type(aObject)=="object"){if(this._stringCodec){var objectString=this._stringCodec.encodeString(aObject);this.storeProperty("PLEncodedObject",objectString,this._currentPersistenceKey)}else{nokia.aduno.utils.error("Persistence>>storeObject(): cannot serialize object. It is not of type Serializable and no string codec is set")}}}delete this._currentPersistenceKey},restoreObject:function(aObject,aPersistenceKey){this._currentPersistenceKey=(aPersistenceKey)?aPersistenceKey:Persistence.DEFAULT_STORAGE_KEY;if("function"===type(aObject.deserialize)){aObject.deserialize(this)}else{if(aObject&&type(aObject)=="object"){if(this._stringCodec){var objectString=this.restoreProperty("PLEncodedObject",this._currentPersistenceKey);var deserializedObject=this._stringCodec.decodeString(objectString);for(var property in deserializedObject){aObject[property]=deserializedObject[property]}}}}delete this._currentPersistenceKey;return aObject},storeProperty:function(aProperty,aValue,aPersistenceKey){if(!this._storageReady){this.begin()}var persistenceKey=(aPersistenceKey)?aPersistenceKey:Persistence.DEFAULT_STORAGE_KEY;this._storage.store(aPersistenceKey,aProperty,aValue)},restoreProperty:function(aProperty,aPersistenceKey){var persistenceKey=(aPersistenceKey)?aPersistenceKey:Persistence.DEFAULT_STORAGE_KEY;return this._storage.restore(aPersistenceKey,aProperty)},begin:function(){this._storage.begin();this._storageReady=true},commit:function(){this._storage.commit();this._storageReady=false},_store:function(aProperty,aValue){this.storeProperty(aProperty,aValue,this._currentPersistenceKey)},_restore:function(aProperty){return this.restoreProperty(aProperty,this._currentPersistenceKey)}});Persistence.DEFAULT_STORAGE_KEY="adunoDefaultKey";var Serializable={Name:"Serializable",serialize:function(aPersistence){if(this._persistentProperties){for(var len=this._persistentProperties.length,i=0;i<len;i++){var property=this._persistentProperties[i];aPersistence._store(property,this[property])}}},deserialize:function(aPersistence){if(this._persistentProperties){for(var len=this._persistentProperties.length,i=0;i<len;i++){var property=this._persistentProperties[i];this[property]=aPersistence._restore(property)}}}};var StorageStrategy=new Class({Name:"StorageStrategy",begin:function(){},store:function(aPersistenceKey,aProperty,aValue){},restore:function(aPersistenceKey,aProperty){},commit:function(){},reset:function(){}});var CookieStorage=new Class({Name:"CookieStorage",Implements:Options,Extends:StorageStrategy,initialize:function(aCookieName,aOptions,aDocument){this._cookie=aCookieName;this._options=aOptions||{};this._document=aDocument||document;this._data=null;this._cookieData=null},begin:function(){this._data=[]},store:function(aPersistenceKey,aProperty,aValue){var triple=[encodeURIComponent(aPersistenceKey),encodeURIComponent(aProperty),encodeURIComponent(aValue)].join(":");this._data.push(triple);this._cookieData=null},commit:function(){this._setCookie(this._data.join(","),this._options);this._data=[];this._cookieData=null},_readCookie:function(){var cookie=this._getCookie();this._cookieData={};if(cookie){var deserializables=cookie.split("&");for(var i=0,deserializable;(deserializable=deserializables[i]);i++){var triples=deserializable.split(","),obj={};for(var j=0,triple;(triple=triples[j]);j++){var kv=triple.split(":",3);this._cookieData[decodeURIComponent(kv[0])+":"+decodeURIComponent(kv[1])]=decodeURIComponent(kv[2])}}}},restore:function(aPersistenceKey,aProperty){if(!this._cookieData){this._readCookie()}return this._cookieData[aPersistenceKey+":"+aProperty]},reset:function(){var options=nokia.aduno.utils.clone(this._options);options.expires=-1;this._setCookie("",options);this._data=[];this._cookieData=null},_setCookie:function(aValue,aOptions){var attributes=[this._cookie+"="+(this._getCookie()&&aValue?this._getCookie()+"&":"")+aValue];if(aOptions.expires){var date=new Date();date.setTime(date.getTime()+aOptions.expires*24*60*60*1000);attributes.push("expires="+date.toUTCString())}if(aOptions.path){attributes.push("path="+aOptions.path)}if(aOptions.domain){attributes.push("domain="+aOptions.domain)}if(aOptions.secure){attributes.push("secure")}this._document.cookie=attributes.join("; ")},_getCookie:function(){var a_all_cookies=this._document.cookie.split(";");var a_temp_cookie="";var cookie_name="";var cookie_value="";for(var i=0;i<a_all_cookies.length;i++){a_temp_cookie=a_all_cookies[i].split("=");cookie_name=a_temp_cookie[0].replace(/^\s+|\s+$/g,"");if(cookie_name==this._cookie){if(a_temp_cookie.length>1){cookie_value=a_temp_cookie[1].replace(/^\s+|\s+$/g,"")}return cookie_value}a_temp_cookie=null;cookie_name=""}return null}});var PluginStorage=new Class({Name:"PluginStorage",Extends:StorageStrategy,initialize:function(aPlugin){this._pluginPersistence=aPlugin.getPersistence()},store:function(aPersistenceKey,aProperty,aValue){this._pluginPersistence.set(aPersistenceKey,aProperty,aValue)},restore:function(aPersistenceKey,aProperty){this._pluginPersistence.prepare(aPersistenceKey,function(){});return this._pluginPersistence.get(aPersistenceKey,aProperty)}});var WebStorage=new Class({Extends:StorageStrategy,Name:"WebStorage",initialize:function(aURI,aSuccessHandler,aErrorHandler){this._uri=aURI;this._onError=aErrorHandler||this._onError;this._onSuccess=aSuccessHandler||this._onSuccess;this._cache={};this._data={}},store:function(aPersistenceKey,aKey,aValue){this._data[aPersistenceKey]=this._data[aPersistenceKey]||{};this._data[aPersistenceKey][aKey]=aValue},begin:function(){this._data=[]},commit:function(){var me=this;var xhr=new nokia.aduno.XHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState===4){if(xhr.status===200){me._onSuccess(xhr[(xhr.getResponseHeader("Content-Type")==="text/xml")?"responseXML":"responseText"])}else{me._onError(xhr)}}};for(var key in this._data){xhr.open("PUT",this._uri+"/"+encodeURIComponent(key),false);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");var obj=this._data[key];var sendData="";for(var prop in obj){sendData+='"'+encodeURIComponent(prop).replace(/%20/g,"+")+'":"'+encodeURIComponent(obj[prop]).replace(/%20/g,"+")+'"\n'}xhr.send(sendData)}},restore:function(aPersistenceKey,aProperty){if(!this._cache[aPersistenceKey]){var me=this;var xhr=new nokia.aduno.XHttpRequest();xhr.onreadystatechange=function(){if(xhr.readyState===4){if(xhr.status!==200){me._onError(xhr)}}};xhr.open("GET",this._uri+"/"+encodeURIComponent(aPersistenceKey),false);xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");xhr.send();var fields=xhr.responseText.split("\n");this._cache[aPersistenceKey]={};for(var i=0,len=fields.length;i<len;i++){var pair=fields[i].split(":");if(pair.length===2){var property=decodeURIComponent(pair[0].replace(/^"|"$/g,""));var value=decodeURIComponent(pair[1].replace(/^"|"$/g,""));this._cache[aPersistenceKey][property]=value}}}return this._cache[aPersistenceKey][aProperty]},_onSuccess:function(aResponse){},_onError:function(aRequest){}});var NetStringCodec=new Class({Name:"NetStringCodec",encodeString:function(aObject){var result="";for(var property in aObject){if(type(aObject[property])==="string"){result+=property.length+":"+property;result+=aObject[property].length+":"+aObject[property]}}return result},decodeString:function(aString){var string=aString;var result={};while(string.length){var stringLength=parseInt(string,10);var lengthLength=String(stringLength).length+1;var property=string.substring(lengthLength,lengthLength+stringLength);string=string.substring(lengthLength+stringLength);stringLength=parseInt(string,10);lengthLength=String(stringLength).length+1;var value=string.substring(lengthLength,lengthLength+stringLength);string=string.substring(lengthLength+stringLength);result[property]=value}return result}});var JSONCodec=new Class({Name:"JSONCodec",encodeString:function(aObject){return nokia.aduno.storage.json.stringify(aObject)},decodeString:function(aString){return nokia.aduno.storage.json.parse(aString)}});var Html5Storage=new Class({Name:"Html5Storage",Extends:StorageStrategy,Implements:nokia.aduno.utils.EventSource,initialize:function(aTableName){this._data=null;this._tableName=aTableName||"persValTbl";this._databaseName="AdunoHtml5Persistence";this.addEventHandler("initialized",this._onInitialized);this.addEventHandler("commited",this._onCommited);this.addEventHandler("restored",this._onRestored);this.addEventHandler("reset",this._onReset);if(window.openDatabase){this._database=window.openDatabase(this._databaseName,"");if(!this._database){nokia.aduno.utils.warn("Could not open "+this._databaseName+" database")}else{var that=this;this._database.transaction(function(tx){var query="CREATE TABLE IF NOT EXISTS "+that._tableName+"(id INTEGER PRIMARY KEY,persistenceKey TEXT NOT NULL,key TEXT NOT NULL,value TEXT)";tx.executeSql(query,[],function(tx,aResult){that.fireEvent("initialized",{result:aResult})},function(tx,error){nokia.aduno.utils.warn("Initialize: Transaction error. Error code: "+error.code)})})}}else{nokia.aduno.utils.warn("This browser does not support HTML5 storage")}},_onInitialized:function(aEvent){nokia.aduno.utils.info("Html5Storage initialized")},begin:function(){this._data=[]},store:function(aPersistenceKey,aKey,aValue){var triple=[encodeURIComponent(aPersistenceKey),encodeURIComponent(aKey),encodeURIComponent(aValue)].join(":");try{this._data.push(triple)}catch(e){nokia.aduno.utils.warn("Store: Error - "+e.message)}},commit:function(){if(!this._database){return}else{var that=this;this._database.transaction(function(tx){var tripleArray;len=that._data.length;var query;for(var i=0;i<len;++i){tripleArray=that._data[i].split(":");var sel="(SELECT id FROM "+that._tableName+" WHERE (persistenceKey='"+tripleArray[0]+"' AND key='"+tripleArray[1]+"'))";query="INSERT OR REPLACE INTO "+that._tableName+" VALUES("+sel+", ?, ?, ?)";tx.executeSql(query,[tripleArray[0],tripleArray[1],tripleArray[2]],function(tx,aResult){that._data=[];that.fireEvent("commited",{result:aResult})},function(tx,error){nokia.aduno.utils.warn("Commit: Transaction error. Error code: "+error.code)})}})}},_onCommited:function(aEvent){nokia.aduno.utils.info("Html5Storage commit method succeeded")},restore:function(aPersistenceKey,aKey){if(!this._database){return}else{var that=this;this._database.transaction(function(tx){var query="SELECT value FROM "+that._tableName+" WHERE ((persistenceKey = '"+aPersistenceKey+"') AND (key = '"+aKey+"'))";tx.executeSql(query,[],function(tx,aResult){that.fireEvent("restored",{result:aResult})},function(error){nokia.aduno.utils.warn("Restore: Transaction error. Error code: "+error.code)})})}},_onRestored:function(aEvent){nokia.aduno.utils.info("Html5Storage restore method succeeded")},reset:function(){if(!this._database){return}else{var that=this;this._database.transaction(function(tx){var query="DROP TABLE "+that._tableName;tx.executeSql(query,[],function(tx,aResult){that._data=[];that.fireEvent("reset",{resutl:aResult})},function(tx,error){nokia.aduno.utils.warn("Reset: Transaction error. Error code: "+error.code)})})}},_onReset:function(){nokia.aduno.utils.info("Html5Storage reset method succeeded")}});nokia.aduno.storage.addMembers({json:json,Persistence:Persistence,Serializable:Serializable,StorageStrategy:StorageStrategy,CookieStorage:CookieStorage,PluginStorage:PluginStorage,WebStorage:WebStorage,NetStringCodec:NetStringCodec,JSONCodec:JSONCodec,Html5Storage:Html5Storage})};new function(){new nokia.aduno.Ns("nokia.aduno.i18n");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var json=nokia.aduno.storage.json;var Persistence=nokia.aduno.storage.Persistence;var Serializable=nokia.aduno.storage.Serializable;var StorageStrategy=nokia.aduno.storage.StorageStrategy;var CookieStorage=nokia.aduno.storage.CookieStorage;var PluginStorage=nokia.aduno.storage.PluginStorage;var WebStorage=nokia.aduno.storage.WebStorage;var NetStringCodec=nokia.aduno.storage.NetStringCodec;var JSONCodec=nokia.aduno.storage.JSONCodec;var Html5Storage=nokia.aduno.storage.Html5Storage;var ResourceManager=new Class({Name:"ResourceManager",Implements:EventSource,initialize:function(aBase,aOptions){aOptions=aOptions||{};if(typeof aOptions==="string"){nokia.aduno.utils.warn("DEPRECATED nokia.aduno.i18n.ResourceManager.initialize - pass default locale within configuration object literal instead of as string");aOptions={defaultLocale:aOptions}}this._defaultFileName=aOptions.defaultFileName||"locale.json";this._base=aBase;this._window=aOptions.window||window;this._defaultLocale=aOptions.defaultLocale&&aOptions.defaultLocale.toLowerCase()||"en";this._localizations={}},require:function(aLocale){aLocale=aLocale.toLowerCase();var that=this,locales=[],required=[];if(aLocale.indexOf(this._defaultLocale)!==0&&!(this._defaultLocale in this._localizations)){locales.push(this._defaultLocale)}locales.push(aLocale);for(var k=0,locale;(locale=locales[k]);k++){if(locale.indexOf("-")>0){required.push(locale.split("-")[0])}required.push(locale)}var pending=required.length;for(var i=0,languageTag;(languageTag=required[i]);i++){if(!(languageTag in this._localizations)){var uri=[this._base,languageTag.replace("-","/"),this._defaultFileName].join("/");(new nokia.aduno.Loader({window:this._window,type:"json",uri:uri,handler:(function(languageTag){return function(response,success){var parsed;if(success){try{parsed=nokia.aduno.storage.json.parse(response)}catch(e){nokia.aduno.utils.error(e.name+" "+e.message+": "+uri)}}else{nokia.aduno.utils.error("Could not load resource: "+uri)}that._localizations[languageTag]=parsed||{};if(--pending===0){for(var i=0,l;(l=required[i]);i++){if(l.indexOf("-")>0){that._localizations[l]=extend(clone(that._localizations[required[i-1]]),that._localizations[l])}}var last=required[required.length-1];if(last!==that._defaultLocale){that._localizations[last]=extend(clone(that._localizations[that._defaultLocale]),that._localizations[last])}that._onReady(last)}}})(languageTag)}))}else{if(--pending===0){this._onReady(languageTag)}}}},get:function(aLocale){return this._localizations[aLocale.toLowerCase()]},_onReady:function(aLocale){this.fireEvent(new Event("ready",{locale:aLocale}))}});var Translator=new Class({Name:"Translator",initialize:function(aTranslationTable){this._allowedAttributes=["src","title","alt","href"];this._translationTable=aTranslationTable},setTranslationTable:function(aTranslationTable){this._translationTable=aTranslationTable},traverse:function(aElement){var ci=0;while(ci<aElement.childNodes.length){this.traverse(aElement.childNodes[ci++])}switch(aElement.nodeType){case 1:for(var i=0,len=this._allowedAttributes.length;i<len;i++){var allowed=this._allowedAttributes[i];var attr=aElement.getAttribute(allowed);if(attr&&!((allowed==="href")&&(aElement.nodeName==="IMG"))){aElement.setAttribute(allowed,this.translate(attr))}}break;case 3:aElement.nodeValue=this.translate(aElement.nodeValue);break}},translate:function(aString){var that=this;if(typeof aString==="string"){return aString.replace(/\b__I18N_([\w\[\].]+?)__\b/gi,function(aMatch,aSubmatch){return that._translationTable[aSubmatch]})}else{warn("Translator.translate: aString is udefined");return""}},translateTemplate:function(key,varValues){if(typeof key==="string"){var sTemplate=this._translationTable[key];if(!sTemplate){warn("Translator.translateTemplate: translation for key="+key+" was not found");return""}for(var transObj in varValues){sTemplate=sTemplate.replace("%{"+transObj+"}",varValues[transObj])}var reg=/\%\{([\w.]+?)\}/gi,execR;while(execR=reg.exec(sTemplate)){warn("Translator.translateTemplate: variable value for '"+execR[1]+"' was not found");sTemplate=sTemplate.replace(execR[0],"%"+execR[1].toUpperCase()+"%")}return sTemplate}else{warn("Translator.translateTemplate: key is undefined");return""}}});nokia.aduno.i18n.addMembers({ResourceManager:ResourceManager,Translator:Translator})};new function(){new nokia.aduno.Ns("nokia.maps.pfw");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var bindWithEvent=nokia.aduno.dom.bindWithEvent;var addCssClass=nokia.aduno.dom.addCssClass;var removeCssClass=nokia.aduno.dom.removeCssClass;var importNode=nokia.aduno.dom.importNode;var getCssStyleNameAsCamelCase=nokia.aduno.dom.getCssStyleNameAsCamelCase;var getJavaScriptStyleNameAsHyphenated=nokia.aduno.dom.getJavaScriptStyleNameAsHyphenated;var convertColorHexToRgb=nokia.aduno.dom.convertColorHexToRgb;var convertColorRgbToHex=nokia.aduno.dom.convertColorRgbToHex;var getChildIndex=nokia.aduno.dom.getChildIndex;var SimplePath=nokia.aduno.dom.SimplePath;var Parser=nokia.aduno.dom.Parser;var XHtmlParser=nokia.aduno.dom.XHtmlParser;var Template=nokia.aduno.dom.Template;var TemplateReplica=nokia.aduno.dom.TemplateReplica;var TemplateLibrary=nokia.aduno.dom.TemplateLibrary;var XNode=nokia.aduno.dom.XNode;var Dimensions=nokia.aduno.dom.Dimensions;var Event=nokia.aduno.dom.Event;var DomLogger=nokia.aduno.dom.DomLogger;var DummyReplica=nokia.aduno.dom.DummyReplica;var getDefaultTemplateLibrary=nokia.aduno.medosui.getDefaultTemplateLibrary;var loadAssets=nokia.aduno.medosui.loadAssets;var getLayout=nokia.aduno.medosui.getLayout;var TemplateResolver=nokia.aduno.medosui.TemplateResolver;var KeyEventManager=nokia.aduno.medosui.KeyEventManager;var S60KeyEventManager=nokia.aduno.medosui.S60KeyEventManager;var FocusHandler=nokia.aduno.medosui.FocusHandler;var Control=nokia.aduno.medosui.Control;var Button=nokia.aduno.medosui.Button;var Container=nokia.aduno.medosui.Container;var Image=nokia.aduno.medosui.Image;var TextInput=nokia.aduno.medosui.TextInput;var Label=nokia.aduno.medosui.Label;var CheckButton=nokia.aduno.medosui.CheckButton;var Behavior=nokia.aduno.medosui.Behavior;var Scrollable=nokia.aduno.medosui.Scrollable;var Page=nokia.aduno.medosui.Page;var Fx=nokia.aduno.medosui.Fx;var Collapsable=nokia.aduno.medosui.Collapsable;var Spinner=nokia.aduno.medosui.Spinner;var Window=nokia.aduno.medosui.Window;var Dialog=nokia.aduno.medosui.Dialog;var List=nokia.aduno.medosui.List;var SelectionList=nokia.aduno.medosui.SelectionList;var DropDown=nokia.aduno.medosui.DropDown;var DefaultTemplateLibrary=nokia.aduno.medosui.DefaultTemplateLibrary;var Draggable=nokia.aduno.medosui.Draggable;var RadioGroup=nokia.aduno.medosui.RadioGroup;var Slider=nokia.aduno.medosui.Slider;var RepeaterButton=nokia.aduno.medosui.RepeaterButton;var ComboSlider=nokia.aduno.medosui.ComboSlider;var Static=nokia.aduno.medosui.Static;var ListItem=nokia.aduno.medosui.ListItem;var Pagination=nokia.aduno.medosui.Pagination;var POIListItem=nokia.aduno.medosui.POIListItem;var Menu=nokia.aduno.medosui.Menu;var MenuListItem=nokia.aduno.medosui.MenuListItem;var UIVisitor=nokia.aduno.medosui.UIVisitor;var TranslationVisitor=nokia.aduno.medosui.TranslationVisitor;var Modal=nokia.aduno.medosui.Modal;var Factory=nokia.aduno.medosui.Factory;var DefaultSnCTemplateLibrary=nokia.aduno.medosui.DefaultSnCTemplateLibrary;var DefaultTouchTemplateLibrary=nokia.aduno.medosui.DefaultTouchTemplateLibrary;var DefaultWebTemplateLibrary=nokia.aduno.medosui.DefaultWebTemplateLibrary;var ResourceManager=nokia.aduno.i18n.ResourceManager;var Translator=nokia.aduno.i18n.Translator;var layout={snc:nokia.aduno.utils.browser.s60||nokia.aduno.utils.browser.s60_v3,web:!nokia.aduno.utils.browser.s60&&!nokia.aduno.utils.browser.s60_v3,touch:nokia.aduno.utils.platform.maemo||nokia.aduno.utils.platform.s60_v5_touch};eval(nokia.aduno.utils.getImportCode());eval(nokia.aduno.dom.getImportCode());eval(nokia.aduno.medosui.getImportCode());eval(nokia.aduno.i18n.getImportCode());var Serializable={Name:"Serializable",serialize:function(aPersistence){},deserialize:function(aPersistence){}};var Destroyable={Name:"Destroyable",destroyObject:function(){for(var i in this){if(this[i]&&typeof this[i].destroyObject==="function"){this[i].destroyObject()}this[i]=null}}};var MouseEventHandler={handleDragEvent:function(aDragData){return false},handleWheelEvent:function(aWheelEvent){return false},handleMouseClickEvent:function(aClickEvent){return false},handleMouseOverEvent:function(aMouseOverEvent){return false},handleMouseOutEvent:function(aMouseOutEvent){return false},handleMouseUpEvent:function(aMouseUpEvent){return false}};var PluginLogger=new Class({initialize:function(aPlugin){this._plugin=aPlugin},debug:function(aMessage){this._log(PluginLogger._DEBUG,aMessage)},info:function(aMessage){this._log(PluginLogger._INFO,aMessage)},warn:function(aMessage){this._log(PluginLogger._WARN,aMessage)},error:function(aMessage){this._log(PluginLogger._ERROR,aMessage)},_log:function(aLevel,aMessage){this._plugin.log(aLevel,aMessage)}});PluginLogger._DEBUG=3;PluginLogger._INFO=0;PluginLogger._WARN=1;PluginLogger._ERROR=2;var PluginControl=new Class({Extends:nokia.aduno.medosui.Control,Name:"PluginControl",Implements:[EventSource,Destroyable],initialize:function(aTemplate,aLoadJavascript,aMapPlayerPath,aToken,aHost){this._super(aTemplate);this._mapPlayerPath=aMapPlayerPath||"";this._isFullyInitialized=false;this._isJsPlugin=!!aLoadJavascript;this._jsPlugin=null;this._isStartupSet=false;this._token=aToken;this._host=aHost},initializeLogger:function(){if(!PluginControl.pluginLoggerInitialized){var plugin=this._getPlugin();nokia.aduno.utils.logger.addLogger(new PluginLogger(plugin));PluginControl.pluginLoggerInitialized=true}},getNode:function(){var node=this._super();var markup=this._getObjectTag();if(this._isJsPlugin){var options={genericIcon:this._mapPlayerPath+"images/genericIcon.gif",limpidImage:this._mapPlayerPath+"images/1x1.gif",token:this._token,host:this._host};this._jsPlugin=new nokia.maps.plugin.IPlugin(node,options)}return node},_getObjectTag:function(){if(this._isJsPlugin||(!browser.safari&&!browser.msie&&!browser.mozilla&&!browser.s60)){return""}return'<object width="100%" height="100%" type="application/x-'+(browser.msie?'oleobject" data="data:application/x-oleobject;base64,FmPuT297bEq9TkFXxZqenQAIAAAMZAAAWkUAAA==" classid="clsid:4FEE6316-7B6F-4A6C-BD4E-4157C59A9E9D"':'ovi-maps"')+"></object>"},setObjectTag:function(){this.getRootElement().innerHTML=this._getObjectTag()},isLoaded:function(){var plugin=this._getPlugin();return(plugin.getVersionPlugin()!==null&&plugin.getVersionPlugin()!==undefined)},getConnectivity:function(){var plugin=this._getPlugin();return plugin.getConnectivity()},setOnlineMode:function(aOnline){var plugin=this._getPlugin();plugin.setOnlineMode(aOnline)},getOnlineMode:function(){var plugin=this._getPlugin();return plugin.getOnlineMode()},setOnline:function(){var embed=this._getPlugin();try{if(typeof embed.getConnectivity=="function"){var connectivity=embed.getConnectivity();if(connectivity&&!connectivity.getActiveConnection()){connectivity.setOnAccessPointsUpdated(bind(this,this._onListAccessPointsDone));connectivity.setOnConnectivityChange(bind(this,this._onConnectivityChanged));connectivity.updateAccessPoints()}}}catch(e){info("PluginControl.setOnline failed because of "+e.description)}},_onListAccessPointsDone:function(aConnectivity){var accessPoints=aConnectivity.getAccessPoints();if(accessPoints&&accessPoints.getLength()){aConnectivity.connect(accessPoints.at(0))}},_onConnectivityChanged:function(aConnectivity){var ac=aConnectivity.getActiveConnection();if(ac){var type="UNKNOWN";if(ac.getType()==ac.TYPE_CELLULAR){type="CELLULAR"}else{if(ac.getType()==ac.TYPE_WIFI){type="WIFI"}}var signalQuality=ac.getSignalQuality();nokia.aduno.utils.info("Changed Connection: "+ac.getName()+" "+type+", "+signalQuality)}else{nokia.aduno.utils.info("No connection")}},initializePlugin:function(aCallback){if(!this._isFullyInitialized){var plugin=this._getPlugin();try{plugin.setup(plugin.MAP_INTERNATIONAL_VARIANT);try{if(nokia.aduno.utils.platform.maemo&&aCallback){plugin.setOnStartup(aCallback);this._isStartupSet=true}}catch(e){nokia.aduno.utils.warn("on startup callback setting failed")}this._isFullyInitialized=true}catch(err){var message=err.description?err.description:err.message;nokia.aduno.utils.error("Plugin initialization failed: "+message+".\n\n"+plugin.errorDescription)}}return this},_delegateNotImplementedEvent:function(anEvent){this.fireEvent(anEvent)},getMapSize:function(){if(this._isJsPlugin){var coord=nokia.aduno.dom.Dimensions.getCoordinates(this.getRootElement());return{height:coord.height,width:coord.width}}else{var size={width:0,height:0};var appearance=this.getAppearance();size.height=appearance.getHeight();size.width=appearance.getWidth();return size}},getMap:function(){return this._getPlugin().getMap()},getAppearance:function(){var plugin=this._getPlugin();return plugin.getAppearance()},createPositionProvider:function(){try{var plugin=this._getPlugin();return plugin.getPositionProvider()}catch(e){error("PluginControl.createPositionProvider could not fetch the position provider")}},getGuidance:function(){var plugin=this._getPlugin();return plugin.getGuidance()},getPersistence:function(){var plugin=this._getPlugin();return plugin.getPersistence()},getDeviceManager:function(){try{var plugin=this._getPlugin();return plugin.getDeviceManager()}catch(e){warn("PluginControl.getDeviceManager could not fetch the device manager");return null}},getVersionApi:function(){var plugin=this._getPlugin();return plugin.getVersionAPI()},getVersionPlugin:function(){var plugin=this._getPlugin();return plugin.getVersionPlugin()},_getPlugin:function(){if(this._jsPlugin){return this._jsPlugin}else{return this.getRootElement().firstChild}},setEnableMouseEvents:function(aBoolean){warn("DEPRECATED PluginControl.setEnableMouseEvents since plugin version 2.0");return this},createArray:function(){var plugin=this._getPlugin();return plugin.createArray()},createFinder:function(){var plugin=this._getPlugin();return plugin.createFinder()},createWaypoint:function(){var plugin=this._getPlugin();return plugin.createWaypoint()},createRouteOptions:function(){var plugin=this._getPlugin();return plugin.createRouteOptions()},createRouter:function(){var plugin=this._getPlugin();return plugin.createRouter()},createRoutePlan:function(aStopovers){var plugin=this._getPlugin();if(aStopovers){return plugin.createRoutePlan(aStopovers)}else{return plugin.createRoutePlan()}},createGeoCoordinates:function(aLatitude,aLongitude){var plugin=this._getPlugin();if((aLatitude||aLatitude===0)&&(aLongitude||aLongitude===0)){return plugin.createGeoCoordinates(aLatitude,aLongitude)}else{return plugin.createGeoCoordinates(0,0)}},createIconFromUrl:function(aUrl,aCallback){var plugin=this._getPlugin();plugin.createIconFromUrl(aUrl,aCallback)},createIconFromFile:function(aUrl){var plugin=this._getPlugin();try{return plugin.createIconFromFile(aUrl)}catch(e){error("PluginControl.createIconFromFile is not implemented")}},createIconFromSvg:function(aData){var plugin=this._getPlugin();try{return plugin.createIconFromSvg(aData)}catch(e){error("PluginControl.createIconFromSvg is not implemented")}},createLayer:function(){var plugin=this._getPlugin();return plugin.createLayer()},createLocation:function(){var plugin=this._getPlugin();return plugin.createLocation()},createManeuver:function(){var plugin=this._getPlugin();return plugin.createManeuver()},createMapIcon:function(){var plugin=this._getPlugin();return plugin.createMapIcon()},createMapComposite:function(){var plugin=this._getPlugin();return plugin.createMapComposite()},shutdown:function(){var plugin=this._getPlugin();plugin.shutdown();return this},createMapPolygon:function(aPoints,aLineColor,aWidth,aFillColor){var plugin=this._getPlugin();return plugin.createMapPolygon(aPoints,aLineColor,aWidth,aFillColor)},createMapPolyline:function(aPoints,aColor,aWidth){var plugin=this._getPlugin();return plugin.createMapPolyline(aPoints,aColor,aWidth)},createPixelCoordinates:function(aX,aY){var plugin=this._getPlugin();return plugin.createPixelCoordinates(aX,aY)},createColor:function(aRed,aGreen,aBlue,aAlpha){var plugin=this._getPlugin();return plugin.createColor(aRed,aGreen,aBlue,aAlpha)},createHttpRequest:function(){var plugin=this._getPlugin();return plugin.createHttpRequest()},getPoiCategoryNames:function(){var list=[];var count=this.getMap().poiCategoryCount;for(var i=0;i<count;++i){list.push(this.getMap().getPoiCategoryName(i))}return list},getGeoCoordinates:function(aPosition){var coords=this.createGeoCoordinates();if(aPosition){if((aPosition.longitude===0||aPosition.longitude)&&(aPosition.latitude===0||aPosition.latitude)){coords.setLatitude(aPosition.latitude);coords.setLongitude(aPosition.longitude)}}return coords},getUUID:function(){if(this._isFullyInitialized){var plugin=this._getPlugin();var uuid=null;try{uuid=plugin.getUUID()||null}catch(e){}return uuid}return null},convertToIArray:function(aArray){var array=splat(aArray);var rval=this.createArray();for(var i=0,len=array.length;i<len;i++){rval.push(array[i])}return rval},isFullyInitialized:function(){return this._isFullyInitialized},getLanguage:function(){if(nokia.aduno.utils.platform.maemo){return"en"}var conv={ENG:"en",FRA:"fr",GER:"de",SPA:"es",DEF:"en",ITA:"it"};var plugin=this._getPlugin();var language=plugin.getLanguage();return conv[language]||"en"},setLanguage:function(aLanguage){if(nokia.aduno.utils.platform.maemo){return}var conv={en:"ENG",fr:"FRA",de:"GER",es:"SPA",it:"ITA"};var lang=conv[aLanguage.substr(0,2)]||"ENG";var plugin=this._getPlugin();return plugin.setLanguage(lang)},detach:function(){this._isFullyInitialized=false},isPluginInUse:function(){return !this._isJsPlugin},isStartupSet:function(){return this._isStartupSet},log:function(aMessage){var plugin=this._getPlugin();if(plugin){plugin.log(plugin.LOG_INFO,aMessage)}}});var Location=new Class({Name:"Location",initialize:function(aILocation){if(aILocation){this._ensureFields(aILocation);Collection.forEach(this._fields,function(field,key){if(field!==undefined&&field!==null){var val=aILocation.getField(this._fields[key]);if(val){this[key]=val}}},this);var coords=aILocation.getGeoCoordinates();if(coords){this.latitude=coords.getLatitude();this.longitude=coords.getLongitude();this.altitude=coords.getAltitude()}}},copyToNative:function(aNativeLocation){this._ensureFields(aNativeLocation);for(var i in this._fields){if(this.hasOwnProperty(i)&&this[i]){aNativeLocation.setField(aNativeLocation[i],this[i])}}var geo=aNativeLocation.getGeoCoordinates();geo.setLatitude(this.latitude);geo.setLongitude(this.longitude);if(this.altitude){}else{}aNativeLocation.setGeoCoordinates(geo)},setField:function(aField,aValue){this[aField]=aValue},getField:function(aField){return this[aField]},_fields:{SEARCH_STRING:null,USER_DATA:null,ADDR_COUNTRY_CODE:null,ADDR_COUNTRY_NAME:null,ADDR_PROVINCE_NAME:null,ADDR_COUNTY_NAME:null,ADDR_CITY_NAME:null,ADDR_DISTRICT_NAME:null,ADDR_POSTAL_CODE:null,ADDR_STREET_NAME:null,ADDR_HOUSE_NUMBER:null,ADDR_BUILDING_NAME:null,ADDR_BUILDING_FLOOR:null,ADDR_BUILDING_ROOM:null,ADDR_BUILDING_ZONE:null,PLACE_NAME:null,PLACE_CATEGORY:null,PLACE_DESCRIPTION:null,PLACE_PHONE_NUMBER:null,PLACE_URL:null,PLACE_UID:null,OTHER_DATA:null},_ensureFields:function(aILocation){if(!this._fields.PLACE_NAME){for(var i in this._fields){if(this._fields.hasOwnProperty(i)){this._fields[i]=aILocation[i]}}}},toString:function(){var text=this.ADDR_STREET_NAME;if(this.ADDR_HOUSE_NUMBER!==undefined){text=text+" "+this.ADDR_HOUSE_NUMBER}text=text+", "+this.ADDR_CITY_NAME;var endText="";for(var i=0;i<text.length;i++){if(text[i]&&text.charCodeAt(i)!==0){endText+=text[i]}}return endText}});var MapObject=new Class({Name:"MapObject",Implements:Destroyable,initialize:function(){this._id=""+MapObject._id++;this._isClickable=false;this._nativeObject=null;this._hasOwnInfoBubble=false},getId:function(){return this._id},getType:function(){switch(this.className){case"MapMarker":return"marker";case"MapPolyline":return"polyline";case"MapPolygon":return"polygon";case"TrafficMapObject":return"traffic";default:return"unknown"}},setClickable:function(aClickable){aClickable=!!aClickable;if(aClickable!=this._isClickable){this._isClickable=aClickable;this.fireEvent(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,{property:"clickable",value:aClickable})}},isClickable:function(){return this._isClickable},getZIndex:function(){return this._nativeObject.getZIndex()},setZIndex:function(aIndex){if(aIndex<0){aIndex=0}else{if(aIndex>65536){aIndex=65536}}this._nativeObject.setZIndex(aIndex)},removeFromMap:function(){if(this._layer){this._layer.removeMapObjects(this)}},setHasOwnInfoBubble:function(aParam){this._hasOwnInfoBubble=!!aParam},hasOwnInfoBubble:function(){return this._hasOwnInfoBubble},destroyObject:function(){for(var i in this){this[i]=null}}});MapObject._id=0;MapObject.EVENT_OBJECT_PROPERTY_CHANGED="mapObjectPropertyChanged";var MapMarker=new Class({Name:"MapMarker",Extends:MapObject,Implements:nokia.aduno.utils.EventSource,initialize:function(aCategory,aPosition,aIconUri,aInfoIconUri){this._super();this._position=aPosition?{longitude:aPosition.longitude,latitude:aPosition.latitude}:{longitude:0,latitude:0};this._category=aCategory;this._location=null;this._locationStructure=null;this._visible=false;this._hovered=false;this._iconUri=aIconUri;this._infoIconUri=aInfoIconUri?aInfoIconUri:this.getCategoryIconUri(aCategory);this._infoTitle=null;this._infoDescription=null;this._defaultTitle=false;this._defaultDescription=false},setIconUri:function(aIconUri){warn("DEPRECATED: use setIcon() instead setIconUri()");this.setIcon(aIconUri)},getIconUri:function(){warn("DEPRECATED: use getIcon() instead getIconUri()");return this.getIcon()},getIcon:function(){return this._iconUri||""},setIcon:function(aIconUri){if(!aIconUri||(typeof aIconUri=="string"&&aIconUri.length>0)){this._iconUri=aIconUri;if((aIconUri===undefined||aIconUri==="")&&this.getCategory()!==""){this._iconUri="poi://"+this.getCategory()}this._nativeObject=this._layer.updateMarkerIcon(this);return true}return false},getInfoIcon:function(){return this._infoIconUri||""},setInfoIcon:function(aInfoIconUri){if(!aInfoIconUri||(typeof aInfoIconUri=="string"&&aInfoIconUri.length>0)){this._infoIconUri=aInfoIconUri;if((aInfoIconUri===undefined||aInfoIconUri==="")&&this.getCategory()!==""){this._iconInfoUri=this.getCategoryIconUri(this.getCategory());aInfoIconUri=this._iconInfoUri}this.fireEvent(new nokia.aduno.utils.Event(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,{property:"infoIconUri",value:aInfoIconUri}));return true}return false},getNativeIcon:function(){warn("DEPRECATED: MapMarker.getNativeIcon. Use MapMarker.getNativeObject instead");return this.getNativeObject()},getNativeObject:function(){return this._nativeObject},setNativeObject:function(aNativeIcon){this._nativeObject=aNativeIcon;this._nativeObject.setVisibility(this.isVisible())},setPosition:function(aPosition){if(this.wasAddedToMap()&&this.isVisible()){var loc=new Location(this._nativeObject.getLocation());loc.longitude=aPosition.longitude;loc.latitude=aPosition.latitude;loc.altitude=100000;this.setLocation(loc)}this._position.longitude=aPosition.longitude;this._position.latitude=aPosition.latitude;this.fireEvent(new nokia.aduno.utils.Event(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,{property:"position",value:aPosition}));return true},getPosition:function(){if(this.wasAddedToMap()){var geo=this._nativeObject.getLocation().getGeoCoordinates();return{longitude:geo.getLongitude(),latitude:geo.getLatitude()}}else{return{longitude:this._position.longitude,latitude:this._position.latitude}}},setLocation:function(aLocation){if(aLocation&&this.wasAddedToMap()){var newLocation=this._pluginControl.createLocation();newLocation.setGeoCoordinates(this._pluginControl.createGeoCoordinates());aLocation.copyToNative(newLocation);newLocation.setField(newLocation.OTHER_DATA,this._id);this._nativeObject.setLocation(newLocation);if(this._visible&&this._nativeLayer){this._nativeLayer.addMapIcon(this._nativeObject)}this.fireEvent(new nokia.aduno.utils.Event(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,{property:"location",value:aLocation}));return true}return false},getLocation:function(){if(!this._location&&this.wasAddedToMap()){return new Location(this._nativeObject.getLocation())}return null},getCategory:function(){return this._category||""},setCategory:function(aCategoryName){if(!aCategoryName||(typeof aCategoryName=="string"&&aCategoryName.length>0)){var isInfoCategory=(this.getInfoIcon()===this.getCategoryIconUri(this._category));var isIconCategory=(this.getIcon()===("poi://"+this._category));var noCategory=(aCategoryName===undefined||aCategoryName==="");this._category=aCategoryName;if(this.getInfoIcon()===""||isInfoCategory){this.setInfoIcon(!noCategory?this.setInfoIcon(this.getCategoryIconUri(aCategoryName)):"")}if(this.getIcon()===""||isIconCategory){this.setIcon(!noCategory?"poi://"+aCategoryName:"")}this.fireEvent(new nokia.aduno.utils.Event(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,{property:"category",value:aCategoryName}));return true}return false},getCategoryIconUri:function(aCategory,aThumbnail){if(typeof player==="undefined"){return MapMarker.PoiImages[aCategory]?"images/spices/poiCategories/icons/"+MapMarker.PoiImages[aCategory]+".png":null}else{return MapMarker.PoiImages[aCategory]?MapMarker.PATH+"images/spices/poiCategories/icons/"+MapMarker.PoiImages[aCategory]+".png":null}},addedToMap:function(aPluginControl,aLayer){this._layer=aLayer;this._pluginControl=aPluginControl;this._visible=true;return this},getLayer:function(){return this._layer},setDefaultInfoTitle:function(aTitle){this.setInfoTitle(aTitle);this._defaultTitle=true},setDefaultInfoDescription:function(aDescription){this.setInfoDescription(aDescription);this._defaultDescription=true},getInfoTitle:function(){return !this._defaultTitle?this._infoTitle:""},setInfoTitle:function(aTitle){if(typeof aTitle=="string"){this._infoTitle=aTitle;this._defaultTitle=false;this.fireEvent(new nokia.aduno.utils.Event(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,{property:"infoTitle",value:aTitle}));return true}return false},getInfoDescription:function(){return !this._defaultDescription?this._infoDescription:""},setInfoDescription:function(aDescription){if(typeof aDescription=="string"){this._infoDescription=aDescription;this._defaultDescription=false;this.fireEvent(new nokia.aduno.utils.Event(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,{property:"infoDescription",value:aDescription}));return true}return false},removedFromMap:function(){this._pluginControl=null;this._layer=null;this._nativeObject=null;this._visible=false;this.destroyObject();return this},wasAddedToMap:function(){return(this._layer&&this._nativeObject)?true:false},isVisible:function(){return this._visible&&this._layer.isVisible()},isSame:function(aMarker){return(this===aMarker)||(aMarker&&aMarker._position&&aMarker._position.latitude==this._position.latitude&&aMarker._position.longitude==this._position.longitude&&aMarker._category==this._category)},toString:function(){return this._category+" <"+this._position.latitude+" "+this._position.longitude+">"},onMouseOver:function(){if(!this._hovered){this._hovered=true;this.fireEvent("over")}},onMouseOut:function(){if(this._hovered){this._hovered=false;this.fireEvent("out")}},hide:function(){if(this._visible&&this.wasAddedToMap()){if(!nokia.aduno.utils.browser.s60){this._layer.getNativeLayer().removeMapObject(this._nativeObject)}else{this._layer.getNativeLayer().removeObject(this._nativeObject)}this._nativeObject.setVisibility(false)}this._visible=false;return this},show:function(){if(!this._visible&&this.wasAddedToMap()){this._layer.getNativeLayer().addMapObject(this._nativeObject);this._nativeObject.setVisibility(this._layer.isVisible());if(this._size){try{this._nativeObject.setSize(this._size.width,this._size.height)}catch(e){warn("IMapIcon.setSize supports svg only")}}this.setPosition(this._position)}this._visible=true;return this},setIconSize:function(aWidth,aHeight){if(aWidth&&aHeight){this._size={width:aWidth,height:aHeight};if(this.wasAddedToMap()){try{this._nativeObject.setSize(aWidth,aHeight)}catch(e){warn("IMapIcon.setSize supports svg only")}}}return this},setIconAnchorPoint:function(xPos,yPos){if(xPos!==undefined&&xPos!==null&&yPos!==undefined&&yPos!==null){if(this.wasAddedToMap()){this._nativeObject.setAnchorPoint(this._pluginControl.createPixelCoordinates(xPos,yPos))}}},setLocationStructure:function(aLocation){this._locationStructure=aLocation},getLocationStructure:function(){return this._locationStructure}});MapMarker.parse=function(aDesc){var marker=new MapMarker(aDesc.category,{longitude:aDesc.longitude,latitude:aDesc.latitude},aDesc.icon,aDesc.infoIcon);marker.setInfoTitle(aDesc.infoTitle||"");marker.setInfoDescription(aDesc.infoDescription||"");marker.setClickable(aDesc.clickable);var handler=aDesc.handler;if(aDesc.bind&&handler){handler=nokia.aduno.utils.bind(aDesc.bind,handler)}if(handler){marker.addEventHandler("selected",handler)}return marker};MapMarker.parseMapMarker=function(aDesc){warn("Using deprecated method MapMarker.parseMapMarker, use MapMarker.parse instead.");return MapMarker.parse(aDesc)};MapMarker.PoiImages={AMUSEMENT_PARK:"AMUSEMENT_PARK",BARS_CAFES:false,BAR_DISCO:false,BEACH:false,CAMPING:false,CAR_DEALER:"PARKING",CAR_REPAIR:"PARKING",CASH_DISPENSER:false,CASINO:false,CINEMA:false,COMPANY:false,CONCERT_HALL:false,CONGRESS:false,COURTHOUSE:false,CULTURAL_CENTRE:false,EDUCATION:"EDUCATION",EMBASSY:false,EXHIBITION_CENTRE:"FAIR",FRONTIER_CROSSING:false,GOLF_COURSE:false,GOVERNMENT_OFFICE:false,HOLIDAY_PARK:false,HOSPITAL:"HOSPITAL",HOTEL:"HOTEL",LIBRARY:"LIBRARY",MOUNTAIN_PASS:false,MOUNTAIN_PEAK:false,MUSEUM:"MUSEUM",OPERA:false,PARKING:"PARKING",PARKING_AREA:"PARKING",PARKING_GARAGE:"PARKING",PARK_RECREATION:"REST_AREA",PETROL_STATION:"PETROL_STATION",PHARMACY:"HOSPITAL",PLACE_OF_WORSHIP:false,POLICE:false,POST_OFFICE:"POST_OFFICE",RENT_A_CAR_FACILITY:"PARKING",RESTAURANT:"RESTAURANT",REST_AREA:"REST_AREA",SHOP:false,SHOPPING_CENTRE:false,SPORT_OUTDOOR:false,STADIUM:false,THEATRE:false,TOURIST_ATTRACTION:"AMUSEMENT_PARK",TOURIST_INFORMATION_CENTRE:false,UNIVERSITY:"EDUCATION",ZOO:false};MapMarker.PATH="";var Layer=new Class({Name:"Layer",Implements:[EventSource,Destroyable],initialize:function(aMapModel,aOptions,aId){this._mapModel=aMapModel;this._pluginControl=aMapModel.getPluginControl();this._menuEnabled=true;this._nativeLayer=this._pluginControl.createLayer();this._isVisible=true;this._id=aId;this._name=aOptions.name;this._category=aOptions.category||null;this._iconUri=aOptions.icon||null;this._entryName=aOptions.title||null;this._mapModel.addLayer(this);this._mapObjects={};this._hasOwnInfoBubble=aOptions.hasOwnInfoBubble||false},_addObject:function(aObject){for(var id in this._mapObjects){if(aObject.getId()===id){return false}}this._mapObjects[aObject.getId()]=aObject;return true},getId:function(){return this._id},getCategory:function(){return this._category||null},setCategory:function(aCategory){this._category=aCategory;this._mapModel.onLayerChanged(this,Layer.ON_CATEGORY_CHANGED)},getIcon:function(){return this._iconUri||null},setIcon:function(aIconUri){this._iconUri=aIconUri;this._mapModel.onLayerChanged(this,Layer.ON_ICON_CHANGED)},getEntryName:function(){if(!this._entryName){if(this._id>0){return"Custom Layer "+this._id}return this._name}return this._entryName},setEntryName:function(aMenuTitle){this._entryName=aMenuTitle;this._mapModel.onLayerChanged(this,Layer.ON_TITLE_CHANGED)},updateMarkerIcon:function(aMapMarker){var icon=aMapMarker.getNativeObject();if(icon){this._nativeLayer.removeMapObject(icon)}var iconUri=aMapMarker.getIcon();if(iconUri===undefined||iconUri===""){iconUri=0}icon=this._mapModel.addMapIcon(aMapMarker,iconUri,false);return icon},isVisible:function(){return this._isVisible},setVisible:function(aIsVisible){warn("DEPRECATED: use hide/show() instead setVisible()");if(aIsVisible){this.show()}else{this.hide()}},hide:function(){if(this._isVisible===true){this._isVisible=false;for(var i in this._mapObjects){if(this._mapObjects.hasOwnProperty(i)){var obj=this._mapObjects[i];obj.getNativeObject().setVisibility(false);if(this._mapModel.getSelectedMapObject()===i){this._mapModel.unselectMapObject()}}}this._mapModel.onLayerChanged(this,Layer.ON_HIDE)}},show:function(){if(this._isVisible===false){this._isVisible=true;for(var i in this._mapObjects){if(this._mapObjects.hasOwnProperty(i)){var obj=this._mapObjects[i];obj.getNativeObject().setVisibility(obj.isVisible())}}this._mapModel.onLayerChanged(this,Layer.ON_SHOW)}},removeLayer:function(){var allObjects=[];for(var i in this._mapObjects){allObjects.push(this._mapObjects[i])}this.hide();this.removeMapObjects(allObjects);this._nativeLayer.removeAllMapObjects();this._mapModel._map.removeLayer(this._nativeLayer);delete this._mapModel._layers[this._name];delete this._mapObjects;this.disableLayerMenuEntry();this._mapModel.onLayerChanged(this,Layer.ON_LAYER_REMOVED);this.destroyObject();return this},getNativeLayer:function(){return this._nativeLayer},isMenuEnabled:function(){warn("DEPRECATED: use isLayerEntryEnabled() instead isMenuEnabled()");return this.isLayerEntryEnabled()},setMenuEnabled:function(aMenuEntryEnabled){warn("DEPRECATED: use enable/disableLayerEntry() instead setMenuEnabled()");if(aMenuEntryEnabled){this.enableLayerMenuEntry()}else{this.disableLayerMenuEntry()}},isLayerEntryEnabled:function(){return this._menuEnabled},enableLayerMenuEntry:function(){if(!this.isLayerEntryEnabled()){this._menuEnabled=true;this._mapModel.onLayerChanged(this,Layer.ON_ENABLE_ENTRY)}return this},disableLayerMenuEntry:function(){if(this.isLayerEntryEnabled()){this._menuEnabled=false;this._mapModel.onLayerChanged(this,Layer.ON_DISABLE_ENTRY)}return this},getName:function(){return this._name},addMapIcon:function(aNativeIcon){if(!nokia.aduno.utils.browser.s60){this._nativeLayer.addMapObject(aNativeIcon)}else{this._nativeLayer.removeObject(aNativeIcon);this._nativeLayer.addMapObject(aNativeIcon)}},removeMapObject:function(aMapObject){warn("DEPRECATED: use removeMapObjects instead removeMapObject");this.removeMapObjects(aMapObject)},removeMapObjects:function(aMapObjects){aMapObjects=splat(aMapObjects);for(var i=0,length=aMapObjects.length;i<length;i++){if(aMapObjects[i]===undefined||aMapObjects[i]===null){continue}var id=aMapObjects[i].getId();if(this._mapObjects.hasOwnProperty(id)){aMapObjects[i].hide();var nativeObject=aMapObjects[i].getNativeObject();this._nativeLayer.removeMapObject(nativeObject);aMapObjects[i].removedFromMap();delete this._mapObjects[id]}this._mapModel.onLayerChanged(this,Layer.ON_OBJECT_REMOVED)}},addMapObjects:function(aObjectOrObjects){var objects=splat(aObjectOrObjects);if(!(objects[0].className&&(objects[0].className==="MapObject"||objects[0].className==="MapMarker"||objects[0].className==="MapPolygon"||objects[0].className==="MapPolyline"))){objects=this._mapModel.createMapObjects(objects)}for(var i=0,length=objects.length;i<length;i++){if(objects[i]===undefined||objects[i]===null){continue}var obj=objects[i];if(obj.className==="MapMarker"){obj.addedToMap(this._pluginControl,this);var iconUri=obj.getIcon()?obj.getIcon():(obj.getCategory()?"poi://"+obj.getCategory():0);var icon=this._mapModel.addMapIcon(obj,iconUri,false);if(icon!==null&&icon!==undefined){obj.setNativeObject(icon)}}else{var nativeObject=obj.createNativeObject(this._pluginControl);this._nativeLayer.addMapObject(nativeObject);obj.addedToMap(this)}this._addObject(obj);this._mapModel.onLayerChanged(this,Layer.ON_OBJECT_ADDED)}return objects},getMapObjects:function(aHaveToBeVisible){var foundObjects=[];for(var id in this._mapObjects){if(this._mapObjects.hasOwnProperty(id)){var obj=this._mapObjects[id];if(aHaveToBeVisible||obj.isVisible()){foundObjects.push(obj)}}}return foundObjects},setZIndex:function(aZIndex){this._nativeLayer.setZIndex(aZIndex)},getZIndex:function(){return this._nativeLayer.getZIndex()},setHasOwnInfoBubble:function(aParam){this._hasOwnInfoBubble=!!aParam},hasOwnInfoBubble:function(){return this._hasOwnInfoBubble},destroyObject:function(){for(var i in this){this[i]=null}}});Layer.ON_SHOW="shown";Layer.ON_HIDE="hidden";Layer.ON_ENABLE_ENTRY="entryEnabled";Layer.ON_DISABLE_ENTRY="entryDisabled";Layer.ON_CATEGORY_CHANGED="categoryChanged";Layer.ON_ICON_CHANGED="iconChanged";Layer.ON_TITLE_CHANGED="manuTitleChanged";Layer.ON_OBJECT_ADDED="addedMapObject";Layer.ON_OBJECT_REMOVED="removedMapObject";Layer.ON_LAYER_CREATED="createLayer";Layer.ON_LAYER_REMOVED="removedLayer";Layer.getEnabledLayerEntries=function(){var ret={};for(var i in Layer.layers){ret[Layer.layers[i]]=Layer.layers[i].isVisible()}return ret};var MapPolyline=new Class({Name:"MapPolyline",Extends:MapObject,Implements:nokia.aduno.utils.EventSource,initialize:function(){this._super();this._visible=true;this._points=[];this._color={alpha:255,red:0,blue:0,green:0}},removedFromMap:function(){this.destroyObject();return this},getLayer:function(){return this._layer},getPoints:function(){return this._points},setPoints:function(aPoints){this._points=[];return this.addPoints(aPoints)},addPointAtIndex:function(aPoint,aIndex){if(aIndex===undefined||aIndex>this._points.length){aIndex=this._points.length}else{if(aIndex<0){aIndex=0}}if(aPoint){this._points.splice(aIndex,0,aPoint);this._update(MapPolyline.CONFIG_POINTS)}},removePointAtIndex:function(aIndex){if(aIndex!==undefined&&aIndex!==null&&this._points&&aIndex<this._points.length&&aIndex>=0){this._points.splice(aIndex,1);this._update(MapPolyline.CONFIG_POINTS)}return this},addPoints:function(aPoints){if(aPoints===null||aPoints===undefined){info("MapPolyline.addPoints: points not given")}var points=splat(aPoints);for(var x in points){var p=points[x];if(p.latitude!=null&&p.longitude!=null){this._points.push({longitude:p.longitude,latitude:p.latitude})}else{if(p.className&&p.className=="MapMarker"&&p.getPosition){this._points.push(p.getPosition())}else{info("MapPolyline.addPoints: couldn't add point")}}}this._update(MapPolyline.CONFIG_POINTS);return this},setVisible:function(aVisible){warn("DEPRECATED: use hide/show instead setVisible");if(aVisible){this.show()}else{this.hide()}},hide:function(){if(this._visible){this._visible=false;this._update(MapPolyline.CONFIG_VISIBLE)}},show:function(){if(!this._visible){this._visible=true;this._update(MapPolyline.CONFIG_VISIBLE)}},getColor:function(){warn("DEPRECATED: use getLineColor instead getColor");return this._color},setColor:function(aAlpha,aRed,aGreen,aBlue){warn("DEPRECATED: use setLineColor instead setColor");this.setLineColor(aAlpha,aRed,aGreen,aBlue)},getLineColor:function(){return this._color},setLineColor:function(aAlpha,aRed,aGreen,aBlue){this._color={alpha:aAlpha,red:aRed,blue:aBlue,green:aGreen};this._update(MapPolyline.CONFIG_COLOR);return this},setWidth:function(aWidth){warn("DEPRECATED: use setLineWidth instead setWidth");this.setLineWidth(aWidth)},getWidth:function(){warn("DEPRECATED: use getLineWidth instead getWidth");return this._width},setLineWidth:function(aWidth){if(aWidth){this._width=aWidth;this._update(MapPolyline.CONFIG_WIDTH)}return this},getLineWidth:function(){return this._width},isVisible:function(){return(this._layer!=null&&this._layer.isVisible()&&this._visible)},getLength:function(){if(this._nativeObject){return this._nativeObject.length}return -1},createNativeObject:function(aPluginControl){if(this._points.length<2){debug("MapPolyline.getNativeObject: not enough points for creating a MapPolyline");return null}this._pluginControl=aPluginControl;var points=this._pluginControl.createArray();for(var x in this._points){var geo=this._pluginControl.createGeoCoordinates();geo.setLatitude(this._points[x].latitude);geo.setLongitude(this._points[x].longitude);points.push(geo)}var color=this._pluginControl.createColor(this._color.red,this._color.green,this._color.blue,this._color.alpha);this._nativeObject=this._pluginControl.createMapPolyline(points,color,10);this._update(MapPolyline.CONFIG_ALL);return this._nativeObject},getNativeObject:function(){return this._nativeObject},addedToMap:function(aLayer){this._layer=aLayer;this._nativeObject.setVisibility(this.isVisible());return this},_update:function(aChangedConfig){if(this._pluginControl){if(aChangedConfig==MapPolyline.CONFIG_ALL||aChangedConfig==MapPolyline.CONFIG_POINTS){if(this._points&&this._points.length>1){var points=this._pluginControl.createArray();for(var x in this._points){var geo=this._pluginControl.createGeoCoordinates();geo.setLatitude(this._points[x].latitude);geo.setLongitude(this._points[x].longitude);points.push(geo)}this._nativeObject.setPoints(points);if(this.isVisible()){this._nativeObject.setVisibility(true)}}else{this._nativeObject.setVisibility(false)}}if(aChangedConfig==MapPolyline.CONFIG_ALL||aChangedConfig==MapPolyline.CONFIG_COLOR){var color=this._pluginControl.createColor(this._color.red,this._color.green,this._color.blue,this._color.alpha);this._nativeObject.setLineColor(color)}if(aChangedConfig==MapPolyline.CONFIG_ALL||aChangedConfig==MapPolyline.CONFIG_VISIBLE){if(this._nativeObject&&this._nativeObject.getPoints().getLength()>1){this._nativeObject.setVisibility(this._visible)}}if(aChangedConfig==MapPolyline.CONFIG_ALL||aChangedConfig==MapPolyline.CONFIG_WIDTH){this._nativeObject.setLineWidth(this._width)}}}});MapPolyline.parse=function(aDesc){var polyline=new MapPolyline();if(!aDesc.points||!polyline.addPoints(aDesc.points)){return null}var visible=(aDesc.visible===true);if(visible){polyline.show()}else{polyline.hide()}polyline.setLineWidth(aDesc.width||1);var col=aDesc.color;if(col){polyline.setLineColor(col.alpha,col.red,col.green,col.blue)}else{polyline.setLineColor(255,255,255,255)}return polyline};MapPolyline.CONFIG_ALL=0;MapPolyline.CONFIG_VISIBLE=1;MapPolyline.CONFIG_COLOR=2;MapPolyline.CONFIG_WIDTH=3;MapPolyline.CONFIG_POINTS=4;var MapPolygon=new Class({Name:"MapPolygon",Extends:MapPolyline,initialize:function(){this._super();this._fillColor={alpha:128,red:0,blue:0,green:0}},createNativeObject:function(aPluginControl){if(this._points.length<3){debug("MapPolygon.getNativeObject: not enough points for creating a MapPolygon");return null}this._pluginControl=aPluginControl;var points=this._pluginControl.createArray();for(var x in this._points){var geo=this._pluginControl.createGeoCoordinates();geo.setLatitude(this._points[x].latitude);geo.setLongitude(this._points[x].longitude);points.push(geo)}var lineColor=this._pluginControl.createColor(this._color.red,this._color.green,this._color.blue,this._color.alpha);var fillColor=this._pluginControl.createColor(this._fillColor.red,this._fillColor.green,this._fillColor.blue,this._fillColor.alpha);this._nativeObject=this._pluginControl.createMapPolygon(points,lineColor,1,fillColor);this._update(MapPolygon.CONFIG_ALL);return this._nativeObject},getNativeObject:function(){return this._nativeObject},getFillColor:function(){return this._fillColor},setFillColor:function(aAlpha,aRed,aGreen,aBlue){this._fillColor={alpha:aAlpha,red:aRed,blue:aBlue,green:aGreen};this._update(MapPolygon.CONFIG_FILLCOLOR)},_update:function(aChangedConfig){if(this._pluginControl){if(aChangedConfig==MapPolygon.CONFIG_ALL||aChangedConfig==MapPolygon.CONFIG_POINTS){if(this._points&&this._points.length>1){var points=this._pluginControl.createArray();for(var x in this._points){var geo=this._pluginControl.createGeoCoordinates();geo.setLatitude(this._points[x].latitude);geo.setLongitude(this._points[x].longitude);points.push(geo)}this._nativeObject.setPoints(points);if(this.isVisible()){this._nativeObject.setVisibility(true)}}else{this._nativeObject.setVisibility(false)}}if(aChangedConfig==MapPolygon.CONFIG_ALL||aChangedConfig==MapPolygon.CONFIG_COLOR){var color=this._pluginControl.createColor(this._color.red,this._color.green,this._color.blue,this._color.alpha);this._nativeObject.setLineColor(color)}if(aChangedConfig==MapPolygon.CONFIG_ALL||aChangedConfig==MapPolygon.CONFIG_VISIBLE){if(this._nativeObject&&this._nativeObject.getPoints().getLength()>1){this._nativeObject.setVisibility(this._visible)}}if(aChangedConfig==MapPolygon.CONFIG_ALL||aChangedConfig==MapPolygon.CONFIG_WIDTH){this._nativeObject.setLineWidth(this._width)}if(aChangedConfig==MapPolygon.CONFIG_ALL||aChangedConfig==MapPolygon.CONFIG_FILLCOLOR){var fillColor=this._pluginControl.createColor(this._fillColor.red,this._fillColor.green,this._fillColor.blue,this._fillColor.alpha);this._nativeObject.setFillColor(fillColor)}}}});MapPolygon.parse=function(aDesc){var polygon=new MapPolygon();if(!aDesc.points||!polygon.addPoints(aDesc.points)){return null}var visible=(aDesc.visible===true);if(visible){polygon.show()}else{polygon.hide()}polygon.setLineWidth(aDesc.width||1);var col=aDesc.color;if(col){polygon.setLineColor(col.alpha,col.red,col.green,col.blue)}var fillColor=aDesc.fillColor;if(fillColor){polygon.setFillColor(fillColor.alpha,fillColor.red,fillColor.green,fillColor.blue)}return polygon};MapPolygon.CONFIG_ALL=0;MapPolygon.CONFIG_VISIBLE=1;MapPolygon.CONFIG_COLOR=2;MapPolygon.CONFIG_WIDTH=3;MapPolygon.CONFIG_POINTS=4;MapPolygon.CONFIG_FILLCOLOR=5;var Spice=new Class({Name:"Spice",Implements:Destroyable,_publicMethods:[],initialize:function(aSpiceManager,aTranslator){this._spiceManager=aSpiceManager;this._spiceControl=null;this._translator=aTranslator},getUi:function(){if(!this._spiceControl){this._spiceControl=this._createUi();if(this._spiceControl){this._spiceControl._replica.addEventHandler("contextmenu",this,this._onContextMenu)}}return this._spiceControl},_createUi:function(){return null},onAttach:function(){},onDetach:function(){},_onContextMenu:function(aEvent){aEvent.preventDefault();aEvent.stopPropagation()},serialize:function(aPersistence){},getPublicMethods:function(){return this._publicMethods},translateUi:function(aDefaultTranslationVisitor,aLanguage){var ui=this.getUi();if(ui){var translationVisitor=this._translator?new PlayerTranslationVisitor(this._translator):aDefaultTranslationVisitor;try{ui.accept(translationVisitor)}catch(err){warn("Error occured when translating spice "+this.className+": "+err)}}},translateString:function(aString){if(this._translator){return this._translator.translate(aString)}var translations=this._spiceManager._resources.get(this._spiceManager._language);if(!translations){warn("Could not translate '"+aString+"', SpiceManager has no translations for "+this._spiceManager._language+" at all.");return aString}if(!translations[aString]){warn("Could not translate '"+aString+"', key is missing in the translation table.");return aString}return translations[aString]},destroyObject:function(){for(var i in this){if(this[i]&&typeof this[i].destroyObject!=="function"){this[i]=null}}}});var Player=new Class({Name:"Player",Implements:[Options,EventSource,Destroyable],options:{pfwPath:"pfw/",templateLibrary:null,fixedPluginSize:null,minimalSpiceSize:{x:0,y:0},jsPlugin:"supported",token:null},_unhideableSpices:{},_topMenuSpices:{},initialize:function(aNode,aTemplateLibray,aOptions){this._options.templateLibrary=aTemplateLibray;this.setOptions(aOptions);this._isFullyInitialized=false;this.isAttached=false;this.isPostPrestartCalled=false;this._page=this._createPage(aNode);this._pluginSize={x:0,y:0};this._spiceManager=new SpiceManager(this._pluginSize,aOptions);this._spiceMethods={};PlayerManager.register(this);if(nokia.maps.pfw.MapMarker){nokia.maps.pfw.MapMarker.PATH=this.getOption("pfwPath")}this.postInitialize();this.addEventHandler("attached",this._onAttach,this);this.addEventHandler("detached",this._onDetach,this);if(!PlayerManager.getAttachedPlayer(aNode)){if(nokia.aduno.utils.platform.maemo){var callBack=bind(this,this._afterPreStart);this.attach(callBack)}else{this.attach()}}},postInitialize:function(){},postPreStart:function(){},postAttach:function(){},postDetach:function(){},_afterPreStart:function(){var plugin=this._page.getChildAt("plugin");if(plugin&&plugin.isStartupSet()){this.postAttach();this.isAttached=true}},_onAttach:function(){if(!this.isPostPrestartCalled){this.isPostPrestartCalled=true;this.postPreStart()}var plugin=this._page.getChildAt("plugin");if(plugin&&!plugin.isStartupSet()){this.postAttach();this.isAttached=true}},_onDetach:function(){this.postDetach();this.isAttached=false;this.isPostPrestartCalled=false},addSpice:function(aSpice,aSlotName){if(!aSlotName){aSlotName=aSpice.className}this._spiceManager.addSpice(aSpice,aSlotName,this._unhideableSpices[aSlotName]);var ui=aSpice.getUi();var pubMethods=aSpice.getPublicMethods();if(ui){this._page.setChildAt(ui,aSlotName,false,true);aSpice.onAttach()}else{aSpice.onAttach()}if(pubMethods&&pubMethods.length){this._spiceMethods[aSpice.className]={spice:aSpice,methods:pubMethods}}return this},hideAllSpices:function(){warn('DEPRECATED: use hideGUI("all") instead hideAllSpices()');this._hideAllGUI()},showAllSpices:function(){warn('DEPRECATED: use showGUI("all") instead showAllSpices()');this._showAllGUI()},_hideTopMenu:function(){var hideContainer=true;for(var i in this._topMenuSpices){if(this._unhideableSpices[i]){hideContainer=false}else{this._page.getReplica().addCssClass(i,"nm_Hidden")}}if(hideContainer){this._page.getReplica().addCssClass("TopMenuSpice","nm_Hidden")}},_showTopMenu:function(){var showContainer=false;for(var i in this._topMenuSpices){if(this._topMenuSpices[i]){showContainer=true;this._page.getReplica().removeCssClass(i,"nm_Hidden")}}if(showContainer){this._page.getReplica().removeCssClass("TopMenuSpice","nm_Hidden")}},_hideAllGUI:function(){var slots=this._spiceManager.getRegisteredSpiceSlots();this._hideTopMenu();for(var i in slots){if(slots.hasOwnProperty(i)){var ui=this._spiceManager.getSpice(slots[i]).getUi();if(!this._topMenuSpices[slots[i]]&&slots[i]!=="TopMenuSpice"){if(ui&&!this._unhideableSpices[slots[i]]){this._page.getReplica().addCssClass(slots[i],"nm_Hidden")}}}}},_showAllGUI:function(){var slots=this._spiceManager.getRegisteredSpiceSlots();for(var i in slots){if(slots.hasOwnProperty(i)){var ui=this._spiceManager.getSpice(slots[i]).getUi();if(ui){this._page.getReplica().removeCssClass(slots[i],"nm_Hidden")}}}},hideSpice:function(aSpiceOrName){warn("DEPRECATED: use hideGUI() instead hideSpice()");return this.hideGUI(aSpiceOrName)},showSpice:function(aSpiceOrName){warn("DEPRECATED: use showGUI() instead showSpice()");return this.showGUI(aSpiceOrName)},hideGUI:function(aSpiceOrName){var name=aSpiceOrName;if(type(aSpiceOrName)==="object"){name=aSpiceOrName.className}if(this._unhideableSpices&&this._unhideableSpices[name]){return false}if(name==="TopMenuSpice"){this._hideTopMenu();return true}if(name===Player.ALL_SPICES){this._hideAllGUI();return true}var elem=this._page.getElement(name);if(elem){if(this._topMenuSpices.hasOwnProperty(name)&&this._topMenuSpices[name]){this._topMenuSpices[name]=false}this._page.getReplica().addCssClass(name,"nm_Hidden");return true}return false},isGuiVisible:function(aSpiceOrName){var name=type(aSpiceOrName)==="object"?aSpiceOrName.className:aSpiceOrName;var elem=this._page.getElement(name);return elem&&!/nm_Hidden/.test(elem.className)},isSpiceVisible:function(aSpiceOrName){warn("DEPRECATED: use isGuiVisible() instead isSpiceVisible()");return this.isGuiVisible(aSpiceOrName)},showGUI:function(aSpiceOrName){var name=aSpiceOrName;if(type(aSpiceOrName)==="object"){name=aSpice.className}if(name==="TopMenuSpice"){this._showTopMenu();return true}if(name===Player.ALL_SPICES){this._showAllGUI();return true}var elem=this._page.getElement(name);if(elem){if(this._topMenuSpices.hasOwnProperty(name)&&!this._topMenuSpices[name]){this._topMenuSpices[name]=true}this._page.getReplica().removeCssClass(name,"nm_Hidden");return true}return false},setLayerMenuTitle:function(aTitle){var spice=this._spiceManager.getSpice("LayerListSpice");spice.setListTitle(aTitle)},getLayerMenuTitle:function(){var spice=this._spiceManager.getSpice("LayerListSpice");return spice.getListTitle()},_createPage:function(aNode){var library=this.getOption("templateLibrary");var page=new nokia.aduno.medosui.Page(aNode,library.getTemplate("PluginPage"),library);page.handleGlobalKeys=bind(this,this.handleGlobalKeys);var resizeHandler=bindWithEvent(this,this._windowResized);var unloadHandler=bindWithEvent(this,this._windowUnloaded);var blurHandler=bindWithEvent(this,this._windowBlur);var windowNode=new nokia.aduno.dom.XNode(window);windowNode.addEventHandler(nokia.aduno.dom.XNode.DOM_RESIZE,resizeHandler);windowNode.addEventHandler(nokia.aduno.dom.XNode.DOM_UNLOAD,unloadHandler);windowNode.addEventHandler(nokia.aduno.dom.XNode.DOM_BLUR,blurHandler);if(nokia.aduno.utils.browser.s60){var clickHandler=bindWithEvent(this,this.injectCenterSoftkey);windowNode.addEventHandler(nokia.aduno.dom.XNode.DOM_CLICK,clickHandler)}return page},injectCenterSoftkey:function(aClickEvent){var keyEvent=document.createEvent("UIEvents");keyEvent.initUIEvent("keypress",true,true,document.defaultView,0);var domEvent=new nokia.aduno.dom.Event(keyEvent,document);domEvent.save();domEvent._eventCopy.keyCode=nokia.aduno.medosui.KeyEventManager.KEY_CSK;domEvent._originalEvent=domEvent._eventCopy;var handled=PlayerManager.keyEventManager.onKeyPress(domEvent);if(handled){aClickEvent.preventDefault()}},handleGlobalKeys:function(aKeyEvent){return this._spiceManager.handleKeyEvent(aKeyEvent)},getPage:function(){return this._page},setPluginControl:function(aPluginControl){this._page.setChildAt(aPluginControl,"plugin",true,true);this._windowResized();this._getPlugin().addEventHandler(Player.EVENT_NATIVE_PLUGIN_NOT_AVAILABLE,this._delegateNotImplementedEvent,this);if(nokia.aduno.utils.browser.s60||nokia.aduno.utils.browser.maemo){var devMgr=aPluginControl.getDeviceManager();if(devMgr){devMgr.onOrientationChange=bindWithEvent(this,this._windowResized)}}return this},_delegateNotImplementedEvent:function(anEvent){this.fireEvent(anEvent)},_getPlugin:function(){return this._page.getChildAt("plugin")},_windowResized:function(){var size=this.getOption("fixedPluginSize");var plugin=this._getPlugin();if(!size&&plugin){size=nokia.aduno.dom.Dimensions.getSize(plugin.getRootElement())}if(!size||size.x===0||size.y===0){size=nokia.aduno.dom.Dimensions.getSize(this._page.getDomNode())}if(size.y===0&&size.x>0){size.y=Math.round(size.x*0.5)}if(plugin){var replica=plugin.getReplica();replica.setStyle("pluginControl","width","100%");replica.setStyle("pluginControl","height","100%")}this._pluginSize.x=size.x;this._pluginSize.y=size.y;this._spiceManager.setSize(size);var minSize=this.getOption("minimalSpiceSize");if(minSize){if((size.x<minSize.x||size.y<minSize.y)&&!this._spicesHidden){this.hideGUI("all");this._spicesHidden=true}else{if(size.x>=minSize.x&&size.y>=minSize.y&&this._spicesHidden){this.showGUI("all");this._spicesHidden=false}}}this.fireEvent(new nokia.aduno.utils.Event(Player.EVENT_SIZE_CHANGED,size))},onResized:function(){this._windowResized()},getSize:function(){warn("DEPRECATED: use getPlayerSize() instead getSize()");return this.getPlayerSize()},getPlayerSize:function(){var size,plugin=this._getPlugin();if(plugin){size=nokia.aduno.dom.Dimensions.getSize(plugin.getRootElement())}if(!size||size.x===0||size.y===0){size=nokia.aduno.dom.Dimensions.getSize(this._page.getDomNode())}return size},_windowUnloaded:function(aEvent){this._spiceManager.fireEvent(new nokia.aduno.utils.Event(SpiceManager.EVENT_UNLOADED))},detach:function(){this._page.hide();PlayerManager.detachPlayer(this);return this},attach:function(aCallback){this._page.show();PlayerManager.attachPlayer(this,aCallback);this._page.focus();return this},destroy:function(){this._page.removeNode();PlayerManager.unregister(this)},callSpice:function(aSpiceName,aMethodName,aParameters){if(aSpiceName){var obj=this._spiceMethods[aSpiceName];if(obj&&obj.methods&&obj.methods.length){for(var x in obj.methods){if(obj.methods[x]===aMethodName){var params=[];if(aParameters!==null&&aParameters!==undefined){params=splat(aParameters)}return obj.spice[aMethodName].apply(obj.spice,params)}}debug(this.className+".callSpice: no public method found - "+aMethodName)}else{debug(this.className+".callSpice: no public method found - "+aMethodName)}}else{debug(this.className+".callSpice: spice not found - "+aSpiceName)}return null},_windowBlur:function(){this._spiceManager.fireEvent(new nokia.aduno.utils.Event(SpiceManager.EVENT_BLUR))},getPluginVersion:function(){if(navigator.mimeTypes&&navigator.mimeTypes.length){var mimeType=navigator.mimeTypes["application/x-ovi-maps"];if(!mimeType){return null}return mimeType.description}else{try{var ax=new ActiveXObject("Nokia.OviMaps.NPlugin");var versionPlugin=ax.getVersionPlugin();ax=null;return versionPlugin}catch(err){return null}}},isPluginInUse:function(){plugin=this._getPlugin();return plugin?plugin.isPluginInUse():false},isPluginAvailable:function(){var _supportJS=(this.getOption("jsPlugin")===Player.JS_PLUGIN_SUPPORTED);var _pluginAvailable=this.getPluginVersion();return !(_supportJS&&!_pluginAvailable)},useJsPlugin:function(){warn("DEPRECATED: use !isPluginAvailable() instead useJsPlugin()");return !this.isPluginAvailable()},isPluginForbiddenOnPage:function(){return(this.getOption("jsPlugin")===Player.JS_PLUGIN_FORCED)},forceJsPlugin:function(){warn("DEPRECATED: use isPluginForbiddenOnPage() instead forceJsPlugin()");return this.isPluginForbiddenOnPage()},_loadCssFiles:function(){var baseCssPath=this.getOption("pfwPath")+"stylesheets/";var cssLoader=new nokia.aduno.Loader({uri:baseCssPath+"import_pfw.css",type:"css",window:self})},getToken:function(){var _token=this.getOption("token");if(_token===undefined||_token===null||_token===""){return""}return _token},getHost:function(){if(location!==undefined&&location!==null){return(location.hostname||"localhost")}else{return""}}});Player.EVENT_SIZE_CHANGED="playerSizeChanged";Player.EVENT_INITIALIZATION_DONE="playerInitializationDone";Player.EVENT_NATIVE_PLUGIN_NOT_AVAILABLE="playerNativePluginNotAvailable";Player.ALL_SPICES="all";Player.REQUIRED_PLUGIN_VERSION="2.2.30.1";Player.DOWNLOAD_PLUGIN_VERSION="2.2.30.1";Player.JS_PLUGIN_NONE="none";Player.JS_PLUGIN_SUPPORTED="supported";Player.JS_PLUGIN_FORCED="forced";var PlayerManager={_nodes:[],_plugins:[],_pluginPlayers:[],_attachedPlayers:[],_modelRepository:[],keyEventManager:null,register:function(aPlayer){var index=-1;for(var i=0,len=this._plugins.length;i<len;++i){if(this._nodes[i]===aPlayer.getPage().getDomNode()){index=i;break}}if(index<0){index=this._plugins.length;var plugin=new PluginControl(null,aPlayer.isPluginForbiddenOnPage()||!aPlayer.isPluginAvailable(),aPlayer.hasOption("mapplayerPath")?aPlayer.getOption("mapplayerPath"):null,aPlayer.getToken(),aPlayer.getHost());this._nodes.push(aPlayer.getPage().getDomNode());this._plugins.push(plugin);this._pluginPlayers[index]=[];this._attachedPlayers[index]=null;this._modelRepository[index]={}}this._pluginPlayers[index].push(aPlayer)},unregister:function(aPlayer){var index=Collection.indexOf(this._nodes,aPlayer.getPage().getDomNode());var players=this._pluginPlayers[index];var pIndex=Collection.indexOf(players,aPlayer);if(pIndex<0){throw new ArgumentError("Player given to unregister was not registered")}else{if(this._attachedPlayers[index]===aPlayer){aPlayer.detach()}if(players.length>1){players.splice(pIndex,1)}else{this._pluginPlayers.splice(index,1);this._nodes.splice(index,1);this._plugins.splice(index,1);this._attachedPlayers.splice(index,1);this._modelRepository.splice(index,1)}}},getFocusedPagePlayer:function(){var page=nokia.aduno.medosui.Page.getFocusedPage();if(page){return this.getAttachedPlayer(page)}return null},getAttachedPlayer:function(aDomNode){var index=Collection.indexOf(this._nodes,aDomNode);return this._attachedPlayers[index]},attachPlayer:function(aPlayer,aCallback){var index=Collection.indexOf(this._nodes,aPlayer.getPage().getDomNode());var attached=this._attachedPlayers[index];if(this._attachedPlayers[index]===aPlayer){return}if(attached){this._attachedPlayers[index].detach()}this._attachedPlayers[index]=aPlayer;aPlayer.setPluginControl(this._plugins[index]);if(this._plugins[index].isFullyInitialized()){aPlayer.fireEvent("attached")}else{this._doAttachPlayer(aPlayer,index,aCallback)}if(!PlayerManager.keyEventManager){if(nokia.aduno.utils.browser.s60){PlayerManager.keyEventManager=new nokia.aduno.medosui.S60KeyEventManager(window)}else{PlayerManager.keyEventManager=new nokia.aduno.medosui.KeyEventManager(window)}}},_doAttachPlayer:function(aPlayer,aIndex,aCallback){this._plugins[aIndex].setObjectTag();var self=this;setTimeout(function(){self._doAttachCallback(aPlayer,aIndex,aCallback)},2000)},_doAttachCallback:function(aPlayer,aIndex,aCallback){var plugin=this._plugins[aIndex];plugin.initializePlugin(aCallback);if(this._plugins[aIndex].isPluginInUse()){this._plugins[aIndex].initializeLogger()}if(!nokia.aduno.utils.browser.s60){var plugNode=new XNode(this._plugins[aIndex].getRootElement().firstChild);plugNode.addEventHandler("focus",function(){plugNode.node.blur()})}aPlayer.fireEvent("attached")},detachPlayer:function(aPlayer){var index=Collection.indexOf(this._nodes,aPlayer.getPage().getDomNode());if(this._attachedPlayers[index]===aPlayer){if(aPlayer._plugin){aPlayer._plugin.detach()}aPlayer.fireEvent("detached");this._attachedPlayers[index]=null}},getModelInstance:function(aPlugin,aModelClassName){var index=Collection.indexOf(this._plugins,aPlugin);if(index>=0){var models=this._modelRepository[index];if(models){return models[aModelClassName]}}return null},addModelInstance:function(aPlugin,aModelClassName,aModel){var index=Collection.indexOf(this._plugins,aPlugin);if(index>=0){var models=this._modelRepository[index];if(!models[aModel.className]){models[aModel.className]=aModel}else{nokia.aduno.utils.warn("A model "+aModel.className+"' for plugin '"+index+"' was already registered in PlayerManager.")}}}};var MapModel=new Class({Name:"MapModel",Implements:[EventSource,MouseEventHandler,Serializable,Destroyable],_ROTATIONS:{north:0,south:180,west:90,east:270,northwest:45,southwest:135,southeast:225,northeast:315},MAPTYPES:[],_COLORS:[],TILT_3D:69,MAX_TILT:74,_moveToParameter:{},_reverseGeoCodeQueue:[],_iconCache:[],_cacheSize:0,_cacheLTU:0,_cacheEnabled:true,initialize:function(aPluginControl,aS60Flag,aSnapDistance){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}if(aSnapDistance||aSnapDistance===0){this._snapDistance=+aSnapDistance}else{error("No proper value given for parameter aSnapDistance!")}this._pluginControl=aPluginControl;this._map=this._pluginControl.getMap();this._customLayerId=1;this._layers={};this._categories={};this._transportCategories={};this._initTransportCategories();this._placeModel=new PlacesModel(this);this._moveToEvents=[];if(this.MAPTYPES.length===0){this.MAPTYPES[this._map.TYPE_UNDEFINED]="undefined";this.MAPTYPES[this._map.TYPE_NORMAL]="normal";this.MAPTYPES[this._map.TYPE_HYBRID]="hybrid";this.MAPTYPES[this._map.TYPE_SATELLITE]="satellite";this.MAPTYPES[this._map.TYPE_TERRAIN]="terrain"}if(this._COLORS.length===0){this._COLORS[this._map.COLORS_UNDEFINED]="undefined";this._COLORS[this._map.COLORS_AUTOMATIC]="auto";this._COLORS[this._map.COLORS_DAY]="day";this._COLORS[this._map.COLORS_NIGHT]="night"}MapModel.DETAIL_LEVEL_LOW=this._map.DETAIL_LEVEL_LEAST;MapModel.DETAIL_LEVEL_MID=this._map.DETAIL_LEVEL_LESS;MapModel.DETAIL_LEVEL_HIGH=this._map.DETAIL_LEVEL_FULL;this._isS60=aS60Flag;this._useImperialUnits=false},registerPluginHandlers:function(aIsJS){this._map.setOnScaleChange(nokia.aduno.utils.bind(this,this._onScaleChange));this._map.setOnAnimationDone(nokia.aduno.utils.bind(this,this._onAnimationDone));this._map.setOnMoveDone(nokia.aduno.utils.bind(this,this._onMoveDone));if(!aIsJS){for(var key in this._layers){if(this._layers.hasOwnProperty(key)){var layer=this._layers[key];if(layer.isVisible()){this._map.addLayer(layer.getNativeLayer())}}}}},unregisterPluginHandlers:function(){this._map.setOnScaleChange(null);this._map.setOnAnimationDone(null);this._map.setOnMoveDone(null);for(var key in this._layers){if(this._layers.hasOwnProperty(key)){var layer=this._layers[key];this._map.removeLayer(layer.getNativeLayer())}}},setExternalConnectionsReady:function(){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_EXTERNAL_CONNECTIONS_READY))},_onScaleChange:function(){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_ZOOMSCALE,this._map.getZoomScale()))},_onAnimationDone:function(){this._moveToParameter={};this._fireMoveToEvents();this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_ANIMATION_DONE))},onDragDone:function(){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_DRAG_DONE))},onDragStart:function(){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_DRAG_START))},_getAllMapObjects:function(){var allObjects={};for(var i in this._layers){if(this._layers.hasOwnProperty(i)){var obj=this._layers[i].getMapObjects();for(var x in obj){if(obj.hasOwnProperty(x)){allObjects[obj[x].getId()]=obj[x]}}}}return allObjects},toPixel:function(aPosition){if(aPosition&&typeof aPosition=="object"){if(aPosition.className=="Event"){aPosition=aPosition.getData()}if((aPosition.longitude===0||aPosition.longitude)&&(aPosition.latitude===0||aPosition.latitude)){var coords=this._pluginControl.createGeoCoordinates();coords.setLatitude(aPosition.latitude);coords.setLongitude(aPosition.longitude);var screen=this._map.convertToScreen(coords);return screen===undefined?null:screen}else{if((aPosition.x===0||aPosition.x)&&(aPosition.y===0||aPosition.y)){var pxcoords=this._pluginControl.createPixelCoordinates(aPosition.x,aPosition.y);return pxcoords}}}return this._map.convertToScreen(this.toGeo())},pixelToGeo:function(aX,aY){var geo=this.toGeo({x:aX,y:aY});return{longitude:geo.getLongitude(),latitude:geo.getLatitude()}},geoToPixel:function(aPosition){var coords=this._pluginControl.createGeoCoordinates();coords.setLatitude(aPosition.latitude);coords.setLongitude(aPosition.longitude);var pixels=this._map.convertToScreen(coords);if(pixels===null||pixels===undefined){return null}return{x:pixels.getX(),y:pixels.getY()}},distanceTo:function(aFirstPosition,aSecondPosition){var first=this.toGeo(aFirstPosition);var second=this.toGeo(aSecondPosition);return first.distance(second)},toGeo:function(aPosition){var t=type(aPosition);if("object"===t){if(aPosition.className=="Event"){aPosition=aPosition.getData()}if((aPosition.longitude===0||aPosition.longitude)&&(aPosition.latitude===0||aPosition.latitude)){var coords=this._pluginControl.createGeoCoordinates();coords.setLatitude(aPosition.latitude);coords.setLongitude(aPosition.longitude);return coords}else{if((aPosition.x===0||aPosition.x)&&(aPosition.y===0||aPosition.y)){var pxcoords=this._pluginControl.createPixelCoordinates(aPosition.x,aPosition.y);return this._map.convertToGeo(pxcoords)}else{if(type(aPosition.getPosition)==="function"){var rcoords=this._pluginControl.createGeoCoordinates();rcoords.setLatitude(aPosition.getPosition().latitude);rcoords.setLongitude(aPosition.getPosition().longitude);return rcoords}}}}return this._map.getCenter()},moveTo:function(aPosition){var what=type(aPosition);var map=this._map;var coordinates=null;var scale=map.PRESERVE_SCALE;var orientation=map.PRESERVE_ORIENTATION;var animationMode=map.ANIMATION_BOW;var tilt=map.PRESERVE_PERSPECTIVE;for(var x in aPosition){if(aPosition.hasOwnProperty[x]&&this._moveToParameter.hasOwnProperty[x]&&this._moveToParameter[x]!==undefined&&this._moveToParameter!==null){aPosition[x]=(this._moveToParameter[x]!==aPosition[x])?this._moveToParameter[x]:aPosition[x]}}this._moveToParameter=aPosition;this._moveToEvents=[];if(what=="object"){if(aPosition.className=="Event"){aPosition=aPosition.getData()}if(aPosition.scale&&aPosition.scale!=this._map.getZoomScale()){scale=aPosition.scale;this._moveToEvents.push(MapModel.EVENT_ZOOMSCALE)}if(aPosition.points!==undefined){var a=this._pluginControl.createArray();for(var i=0,len=aPosition.points.length;i<len;++i){a.push(this.toGeo(aPosition.points[i]))}scale=a;this._moveToEvents.push(MapModel.EVENT_ZOOMSCALE)}if(aPosition.orientation!==undefined&&aPosition.orientation!=this._map.getOrientation()){if(typeof aPosition.orientation=="string"){orientation=this._ROTATIONS[aPosition.orientation]}else{orientation=(aPosition.orientation+360)%360}this._moveToEvents.push(MapModel.EVENT_ORIENTATION);if((orientation!==0)!=(this._map.getOrientation()!==0)){this._moveToEvents.push(MapModel.EVENT_MAXZOOM)}}if(aPosition.tilt!==undefined&&this._map.getPerspective()!=aPosition.tilt){tilt=aPosition.tilt;this._moveToEvents.push(MapModel.EVENT_TILT);if((this._map.getPerspective()>0)!=(aPosition.tilt>0)){this._moveToEvents.push(MapModel.EVENT_MAXZOOM)}}if(aPosition.animationMode!==undefined){var val=aPosition.animationMode;if(typeof val=="string"){if(val=="linear"){animationMode=map.ANIMATION_LINEAR}else{if(val=="arc"){animationMode=map.ANIMATION_BOW}else{animationMode=map.ANIMATION_NONE}}}else{animationMode=val}}if((aPosition.longitude!==undefined&&aPosition.latitude!==undefined)||(aPosition.x!==undefined&&aPosition.y!==undefined)){this._moveToEvents.push(MapModel.EVENT_POSITION_CHANGED);coordinates=this.toGeo(aPosition);var positionPixel=this.toPixel(aPosition);var centerPixel=this.toPixel(this.getMapCenterPosition());if(positionPixel&&centerPixel&&(positionPixel.getX()===centerPixel.getX()&&positionPixel.getY()===centerPixel.getY())){animationMode=map.ANIMATION_NONE}}else{if(aPosition.position!==undefined){this._moveToEvents.push(MapModel.EVENT_POSITION_CHANGED);coordinates=this.toGeo(aPosition.position);var positionPixel=this.toPixel(aPosition.position);var centerPixel=this.toPixel(this.getMapCenterPosition());if(positionPixel&&positionPixel.getX()===centerPixel.getX()&&positionPixel.getY()===centerPixel.getY()){animationMode=map.ANIMATION_NONE}}}if(this._moveToEvents.length){map.moveTo(coordinates,animationMode,scale,orientation,tilt);if(animationMode==map.ANIMATION_NONE){this._fireMoveToEvents()}else{this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_ANIMATION_START,aPosition))}}}return this},_fireMoveToEvents:function(){for(var i=0,len=this._moveToEvents.length;i<len;++i){var ev=this._moveToEvents[i];switch(ev){case MapModel.EVENT_ZOOMSCALE:this.fireEvent(new nokia.aduno.utils.Event(ev,this._map.getZoomScale()));break;case MapModel.EVENT_ORIENTATION:this.fireEvent(new nokia.aduno.utils.Event(ev,this._map.getOrientation()));break;case MapModel.EVENT_POSITION_CHANGED:this.fireEvent(new nokia.aduno.utils.Event(ev,this.getMapCenterPosition()));break;case MapModel.EVENT_TILT:this.fireEvent(new nokia.aduno.utils.Event(ev,this._map.getPerspective()));break;case MapModel.EVENT_MAXZOOM:this.fireEvent(new nokia.aduno.utils.Event(ev,this._map.getMaxZoomScale()));break;default:break}}this._moveToEvents=[];return this},createLayer:function(aDescription){var highestZIndex=-1;var layers=this._layers;nokia.aduno.utils.Collection.forEach(layers,function(aItem){var tmpIndex=aItem.getZIndex();if(tmpIndex>highestZIndex){highestZIndex=tmpIndex}});highestZIndex++;if(aDescription){if(aDescription.name===undefined||aDescription.name===""){return null}}else{var id=-1;if(aDescription===undefined){aDescription={};id=this._customLayerId++;aDescription.name="CustomLayer"+id}}if(this._layers.hasOwnProperty(aDescription.name)&&this._layers[aDescription.name]){return this._layers[aDescription.name]}this._layers[aDescription.name]=new nokia.maps.pfw.Layer(this,aDescription,id);this._layers[aDescription.name].setZIndex(highestZIndex);this._map.addLayer(this._layers[aDescription.name].getNativeLayer());this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_LAYERS_CHANGED,{layer:this._layers[aDescription.name],type:"createLayer"}));return this._layers[aDescription.name]},_getLayer:function(){warn("DEPRECATED: use getLayer() instead _getLayer()");return this.getLayer()},getLayer:function(aLayerName){if(aLayerName===undefined){return this.createLayer()}if(!this._layers[aLayerName]){this.createLayer({name:aLayerName})}return this._layers[aLayerName]},hasLayer:function(aLayerName){return !!this._layers[aLayerName]},addLayer:function(aLayer){for(var i in this._layers){if(aLayer.getName()===this._layers[i].getName()){return false}}this._layers[aLayer.getName()]=aLayer;return true},getLayers:function(){var list=[];for(var key in this._layers){if(this._layers.hasOwnProperty(key)){list.push(key)}}return list},hideAllLayers:function(){for(var i in this._layers){this.getLayer(i).hide()}},showAllLayers:function(){for(var i in this._layers){this.getLayer(i).show()}},hideLayer:function(aLayerName){warn("DEPRECATED: nokia.maps.pfw.Layer#hide instead hideLayer()");var layer=this._layers[aLayerName];if(layer){layer.hide()}return !!layer},showLayer:function(aLayerName){warn("DEPRECATED: nokia.maps.pfw.Layer#show instead showLayer()");var layer=this._layers[aLayerName];if(layer){layer.show()}return !!layer},isLayerVisible:function(aLayerName){warn("DEPRECATED: nokia.maps.pfw.Layer#isVisible instead isLayerVisible()");var layer=this._layers[aLayerName];return layer&&layer.isVisible()},getVisibleLayers:function(){var list=[];for(key in this._layers){if(this._layers[key].isVisible()){list.push(key)}}return list},enableLayerEntry:function(aName){warn("DEPRECATED: Layer#enableLayerEntry instead MapPlayer#enableLayerEntry()");var foundLayer=this._layers[aName];if(foundLayer){return foundLayer.enableLayerMenuEntry()}},disableLayerEntry:function(aName){warn("DEPRECATED: Layer#disableLayerEntry instead MapPlayer#disableLayerEntry()");var foundLayer=this._layers[aName];if(foundLayer){return foundLayer.disableLayerMenuEntry()}},isLayerEntryEnabled:function(aName){warn("DEPRECATED: Layer#isLayerEntryEnabled instead MapPlayer#isLayerEntryEnabled()");return(this._layers[aName]?this._layers[aName].isLayerEntryEnabled():false)},getEnabledLayerEntries:function(){var ret={};var layers=this.getLayers();for(var i=0;i<layers.length;i++){if(this.isLayerEntryEnabled(layers[i])){ret[layers[i]]=this.isLayerVisible(layers[i])}}return ret},removeLayer:function(aLayerName){var layer=this._layers[aLayerName];if(layer){layer.removeLayer()}return this},_getMapObjectsAt:function(aPosition){var pixel=this.toPixel(aPosition);if(pixel===null){return[]}var objects;if(nokia.aduno.utils.platform.maemo){var _pixelTL=this.getPluginControl().createPixelCoordinates(pixel.getX()-this._snapDistance,pixel.getY()-this._snapDistance);var _pixelBR=this.getPluginControl().createPixelCoordinates(pixel.getX()+this._snapDistance,pixel.getY()+this._snapDistance);objects=this._map.getMapObjectsIn(_pixelTL,_pixelBR)}else{objects=this._map.getMapObjects(pixel)}var foundObjects=[];var c=objects?objects.getLength():0;for(var i=0;i<c;i++){var obj=objects.at(i);if(nokia.aduno.utils.browser.mozilla&&objects.objectType){obj.QueryInterface(eval(objects.objectType))}foundObjects.push(obj)}return foundObjects},getClosestPoi:function(aPosition,aPoiArray){if(!aPoiArray||!aPoiArray.length){return null}var length=aPoiArray.length;if(length>0){var center=this.toGeo(aPosition);var smallestDistance=-1,closestIndex=0,currentDistance;for(var i=0;i<length;i++){currentDistance=center.distance(this.toGeo(aPoiArray[i].getPosition()));if(smallestDistance===-1||currentDistance<smallestDistance){closestIndex=i;smallestDistance=currentDistance}}return aPoiArray[closestIndex]}return null},onLayerChanged:function(aLayer,aType){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_LAYERS_CHANGED,{layer:aLayer,type:aType}))},getMapObjectsFromLayer:function(aLayerName,aHaveToBeVisible){warn("DEPRECATED: Layer#getMapObjects instead MapPlayer#getMapObjectsFromLayer");var layer=this._layers[aLayerName];if(layer){return layer.getMapObjects(aHaveToBeVisible)}},addToLayer:function(aObjectOrObjects,aOptionalLayer){warn("DEPRECATED: Layer#addMapObjects instead MapPlayer#addToLayer");var layer=this.getLayer(aOptionalLayer);return layer.addMapObjects(aObjectOrObjects)},removeMapObject:function(aMapObjectOrMapObjects){warn("DEPRECATED: use Layer.removeMapObject() MapModel.removeMapObject()");var objects=splat(aMapObjectOrMapObjects);for(var i=objects.length-1;i>=0;i--){var obj=objects[i];var mapObject=this._getAllMapObjects()[obj.getId()];if(mapObject){if(mapObject===this._selectedMapObject){this.unselectMapObject()}var layer=obj.getLayer();layer.removeMapObject(obj)}}},removeFromLayer:function(aMapObjectOrMapObjects){warn("DEPRECATED: use removeMapObject() removeFromLayer()");this.removeMapObject(aMapObjectOrMapObjects)},getMapMarkersAt:function(aPosition){var nativeObjects=this._getMapObjectsAt(aPosition);var foundObjects=[];for(var i=nativeObjects.length-1;i>=0;i--){var obj=nativeObjects[i];switch(obj.getType()){case obj.MAPICON:var loc=new Location(obj.getLocation());var mapObjects=this._getAllMapObjects();var mapMarker=mapObjects[loc.OTHER_DATA];if(mapMarker){mapMarker.setLocationStructure(loc);foundObjects.push(mapMarker)}else{if(loc.PLACE_NAME){var newMarker=MapMarker.parse({category:loc.PLACE_CATEGORY,type:"marker",clickable:true,latitude:loc.latitude,longitude:loc.longitude,infoTitle:loc.PLACE_NAME,infoDescription:loc.PLACE_DESCRIPTION||null});newMarker.setLocationStructure(loc);foundObjects.push(newMarker)}}break;case obj.POLYGON:break;case obj.POLYLINE:break;case obj.TRAFFICEVENT:var position={};if(aPosition.latitude!==null&&aPosition.latitude!==undefined&&aPosition.longitude!=null&&aPosition.longitude!==undefined){position.longitude=aPosition.longitude;position.latitude=aPosition.latitude}else{if(aPosition.x!==null&&aPosition.x!==undefined&&aPosition.y!==null&&aPosition.y!==undefined){position=this.pixelToGeo(aPosition.x,aPosition.y)}}foundObjects.push(new TrafficMapObject(obj,position));break;default:break}}return foundObjects},createMapObjects:function(aObjectDescriptions){var retArray=[];aObjectDescriptions=splat(aObjectDescriptions);for(var i=0;i<aObjectDescriptions.length;i++){var desc=aObjectDescriptions[i];var obj=null;switch(desc.type){case"marker":var coordinates=this.toGeo(desc);desc.longitude=coordinates.getLongitude();desc.latitude=coordinates.getLatitude();obj=MapMarker.parse(desc);break;case"polygon":obj=MapPolygon.parse(desc);break;case"polyline":obj=MapPolyline.parse(desc);break;default:nokia.aduno.utils.warn("Unhandled map object type: "+desc.type);continue}obj.setClickable(!!desc.clickable);obj.setHasOwnInfoBubble(!!desc.hasOwnInfoBubble);retArray.push(obj)}return retArray},addMapIcon:function(aObject,aIcon,aAnimate){var mapicon=this._createMapIcon(aObject.getPosition(),aObject.getId());var type=nokia.aduno.utils.type(aIcon);if(type!=="string"){if(type!=="number"||(aIcon<0||aIcon>=this._map.getPoiCategories().getLength())){aIcon=0}var cat=this._map.getPoiCategories().at(aIcon);try{mapicon.setIcon(this._map.getPoiIcon(cat));this._addIcon(mapicon,aObject.getLayer(),aAnimate)}catch(e){return null}}else{if(aIcon.indexOf("poi://")===0){try{mapicon.setIcon(this._map.getPoiIcon(aIcon.substr(6)));this._addIcon(mapicon,aObject.getLayer(),aAnimate)}catch(e){return null}}else{if((aIcon.indexOf("<?xml")===0)||(aIcon.indexOf("<svg")===0)){var svgIcon=this._getIconFromCache(aIcon);if(!svgIcon){svgIcon=this._pluginControl.createIconFromSvg(aIcon);this._addIconToCache(aIcon,svgIcon)}mapicon.setIcon(svgIcon);mapicon.setSize(svgIcon.getWidth(),svgIcon.getHeight());aObject.getLayer().addMapIcon(mapicon)}else{var icon=this._getIconFromCache(aIcon);if(icon){this._onIconLoaded(icon,mapicon,aObject.getLayer(),aAnimate)}else{var bind=this;this._pluginControl.createIconFromUrl(aIcon,function(aIIcon){if(aObject.getLayer!==null&&aObject.getLayer!==undefined){bind._addIconToCache(aIcon,aIIcon);bind._onIconLoaded.apply(bind,[aIIcon,mapicon,aObject.getLayer(),aAnimate])}})}}}}return mapicon},_getIconFromCache:function(aUrl){if(!this._cacheEnabled){return null}if(this._iconCache[aUrl]){this._iconCache[aUrl].ltu=this._cacheLTU++;return this._iconCache[aUrl].icon}return null},_addIconToCache:function(aUrl,aIIcon){if(!this._cacheEnabled){return}if(this._cacheSize<MapModel.ICON_CACHE_SIZE){this._iconCache[aUrl]={ltu:this._cacheLTU++,icon:aIIcon};this._cacheSize++}else{if(this._iconCache.hasOwnProperty(aUrl)){this._iconCache[aUrl].ltu=this._cacheLTU++}else{var amountToClean=Math.ceil(MapModel.ICON_CACHE_SIZE/5);if(amountToClean<1){amountToClean=1}var tmpArr=[];var oldest=this._cacheLTU;for(var i in this._iconCache){if(this._iconCache[i].ltu<oldest){oldest=this._iconCache[i].ltu;tmpArr.unshift(i)}}for(var ii=0;(ii<amountToClean&&ii<tmpArr.length);ii++){delete this._iconCache[tmpArr[ii]]}this._iconCache[aUrl]={ltu:this._cacheLTU++,icon:aIIcon}}}},_onIconLoaded:function(aIIcon,aMapIcon,aLayer,aAnimate){if(aIIcon&&aIIcon.isValid()){this.onIconLoaded();aMapIcon.setIcon(aIIcon);this._addIcon(aMapIcon,aLayer,aAnimate)}else{nokia.aduno.utils.warn("Could not load image from url")}},onIconLoaded:function(){},setCacheEnabled:function(aFlag){this._cacheEnabled=aFlag},_createMapIcon:function(aPosition,aUserDataIdentifier){var mapicon=this._pluginControl.createMapIcon();var loc=this._pluginControl.createLocation();loc.setGeoCoordinates(this.toGeo(aPosition));if(aUserDataIdentifier===0||aUserDataIdentifier){loc.setField(loc.OTHER_DATA,aUserDataIdentifier)}mapicon.setLocation(loc);mapicon.setVisibility(true);return mapicon},_addIcon:function(aMapIcon,aLayer,aAnimateFlag){aLayer=aLayer||this.getLayer();if(aAnimateFlag){this._startIconAnimation(aMapIcon,70,200)}aLayer.addMapIcon(aMapIcon);var height=aMapIcon.getIcon().getHeight();var width=aMapIcon.getIcon().getWidth();var maxSize=64;var minSize=1;var tmp;if(height>width){tmp=Math.max(minSize,Math.min(aMapIcon.getIcon().getHeight(),maxSize));width=(width/height)*tmp;height=tmp}else{tmp=Math.max(minSize,Math.min(aMapIcon.getIcon().getWidth(),maxSize));height=(height/width)*tmp;width=tmp}try{aMapIcon.setSize(width,height)}catch(e){warn("IMapIcon.setSize supports svg only")}return this},_startIconAnimation:function(aMapIcon,aTargetSize,aTime){var ft=25;var animator={};animator.step=0;animator.width=aMapIcon.getIcon().getWidth();animator.height=aMapIcon.getIcon().getHeight();animator.targetSize=aTargetSize;animator.icon=aMapIcon;animator.steps=aTime/ft;animator.animation=nokia.aduno.utils.setPeriodical(ft,this,this._onAnimationStep,animator)},_onAnimationStep:function(aAnimator){var val=Math.floor(this._overShoot2(1-aAnimator.step/aAnimator.steps)*aAnimator.targetSize);if(val>0){try{aAnimator.icon.setSize(val,val)}catch(e){warn("IMapIcon.setSize supports svg only")}}aAnimator.step+=1;if(aAnimator.step>=aAnimator.steps){nokia.aduno.utils.cancelPeriodical(aAnimator.animation);try{aAnimator.icon.setSize(aAnimator.width,aAnimator.height)}catch(e){warn("IMapIcon.setSize supports svg only")}}},jumpByPixel:function(aDeltaX,aDeltaY){this._map.jumpByPixel(aDeltaX,aDeltaY);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_POSITION_CHANGED,this.getMapCenterPosition()))},setMode3d:function(aFlag){this.setTilt(aFlag?this.TILT_3D:0)},getMode3d:function(){return this._map.getPerspective()!==0},setMapCenterPosition:function(aPosition){var center=this._map.getCenter();if(aPosition.longitude!=center.getLongitude()&&aPosition.latitude!=center.getLatitude()){var coords=this._pluginControl.createGeoCoordinates();coords.setLatitude(aPosition.latitude);coords.setLongitude(aPosition.longitude);this._map.moveTo(coords,this._map.ANIMATION_NONE,this._map.getZoomScale(),this._map.getOrientation(),this._map.getPerspective());this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_POSITION_CHANGED,this.getMapCenterPosition()))}return this},setPosition:function(aPosition){warn("DEPRECATED: use setMapCenterPosition() instead setPosition()");this.setMapCenterPosition(aPosition)},getMapCenterPosition:function(){var center=this._map.getCenter();return{longitude:center.getLongitude(),latitude:center.getLatitude()}},getPosition:function(){warn("DEPRECATED: use getMapCenterPosition() instead getPosition()");return this.getMapCenterPosition()},getCurrentMapProperties:function(){var result={};var center=this._map.getCenter();result.longitude=center.getLongitude();result.latitude=center.getLatitude();result.language=this.getMapLanguage();result.orientation=this._map.getOrientation();result.scale=this._map.getZoomScale();result.tilt=this._map.getPerspective();result.color=this.getColor();result.mapType=this.getMapType();return result},getCurrentValues:function(){warn("DEPRECATED: use getCurrentMapProperties() instead getCurrentValues()");this.getCurrentMapProperties()},setLanguage:function(aLanguage){warn("DEPRECATED: use setMapLanguage() or setUiLanguage() instead setLanguage()");this.setUiLanguage(aLanguage);this.setMapLanguage(aLanguage)},setUiLanguage:function(aLanguage){if(aLanguage){for(var key in MapModel.SUPPORTED_LANGUAGES){if(MapModel.SUPPORTED_LANGUAGES[key].toUpperCase()==aLanguage.toUpperCase()){this._uiLanguage=aLanguage;this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_UI_LANGUAGE,aLanguage));return true}}}return false},setMapLanguage:function(aLanguage){try{this._pluginControl.setLanguage(aLanguage);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_LANGUAGE,this.getMapLanguage()))}catch(err){return false}return true},getLanguage:function(){warn("DEPRECATED: use MapModel.getMapLanguage() or MapPlayer.getGUILanguage() instead setLanguage()");return this.getMapLanguage()},getUiLanguage:function(){return this._uiLanguage},getMapLanguage:function(){return this._pluginControl.getLanguage()},setMapType:function(aMapType){var numberType=aMapType;if(typeof aMapType=="string"){switch(aMapType){case"normal":numberType=this._map.TYPE_NORMAL;break;case"satellite":numberType=this._map.TYPE_SATELLITE;break;case"hybrid":numberType=this._map.TYPE_HYBRID;break;case"terrain":numberType=this._map.TYPE_TERRAIN;break;default:warn("Unknown map type: "+aMapType);return false}}if(numberType!=-1){this._map.setMapType(numberType);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_MAPTYPE,this.getMapType()));return true}return false},getMapType:function(){return this.MAPTYPES[this._map.getMapType()]},setTilt:function(aTilt){aTilt=Math.max(Math.min(+aTilt,this.MAX_TILT),0);var currentPerspective=this._map.getPerspective();if(currentPerspective!=aTilt){var modeSwitched=(currentPerspective>0)!=(aTilt>0);this._map.setPerspective(aTilt?aTilt:0);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_TILT,this._map.getPerspective()));if(modeSwitched){var binding=this;execFunc=function(){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_MAXZOOM))};window.setTimeout(function(){execFunc.apply(binding)},500)}}},getTilt:function(){return this._map.getPerspective()},setZoomScale:function(aZoomScale){this._map.setZoomScale(aZoomScale)},getZoomScale:function(){return this._map.getZoomScale()},getMinZoomScale:function(){return this._map.getMinZoomScale()},getMaxZoomScale:function(){return this._map.getMaxZoomScale()},setOrientation:function(aOrientation){var lastMapOrientation=this._map.getOrientation();if(typeof aOrientation=="string"){this._map.setOrientation(this._ROTATIONS[aOrientation])}else{this._map.setOrientation(aOrientation)}this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_ORIENTATION,this._map.getOrientation()));if((lastMapOrientation!==0)!=(this._map.getOrientation()!==0)){var binding=this;var execFunc=function(){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_MAXZOOM))};window.setTimeout(function(){execFunc.apply(binding)},500)}},getOrientation:function(){return this._map.getOrientation()},setColor:function(aColorScheme){for(var i=0,len=this._COLORS.length;i<len;++i){if(this._COLORS[i]==aColorScheme){this._map.setColorScheme(i);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_COLOR,this.getColor()));return true}}return false},getColor:function(){return this._COLORS[this._map.getColorScheme()]},setTrafficInfoVisible:function(aVisible){this._map.setTrafficInfoVisibility(!!aVisible);if(this.getPluginControl().isPluginInUse()){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_TRAFFIC_INFO,!!aVisible?"visible":"hidden"))}},getTrafficInfoVisible:function(){return this._map.getTrafficInfoVisibility()},setLandmarksVisible:function(aVisible){this._map.set3DLandmarksVisibility(!!aVisible);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_LANDMARKS,!!aVisible?"visible":"hidden"))},getLandmarksVisible:function(){return this._map.get3DLandmarksVisibility()},_convertReverseResult:function(aResults){var result=[];for(var i=0,len=aResults.getLength();i<len;++i){var loc=aResults.at(i);result.push(new nokia.maps.pfw.Location(loc))}return result},getSelectedMapObject:function(){return this._selectedMapObject},selectMapObject:function(aMapObject){if(!aMapObject){if(this._selectedMapObject){this.unselectMapObject();this._selectedMapObject=null}return}if(aMapObject!==this._selectedMapObject){this.unselectMapObject();this._selectedMapObject=aMapObject;this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_MAPOBJECT_SELECTED,this._selectedMapObject))}else{this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_MAPOBJECT_SELECTED,this._selectedMapObject))}},unselectMapObject:function(){var mapObject=this._selectedMapObject;if(this._selectedMapObject){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_MAPOBJECT_UNSELECTED,this._selectedMapObject));this._selectedMapObject=null}return mapObject},reverseGeoCode:function(aPosition,aNonBlockingHandler,aBind){var self=this;var finder=this._reverseGeoCodingFinder;if(!finder){finder=this._pluginControl.createFinder();var searchType=nokia.aduno.utils.platform.maemo?finder.SEARCH_TYPE_OFFLINE:finder.SEARCH_TYPE_ONLINE;finder.setOnGeoCodeDone(function(){var list=null;if(finder.getStatus()==finder.STATUS_OK){list=self._convertReverseResult(finder.getResults());list=self._fixWrongResults(list)}else{list=[]}if(self._reverseGeoCodeQueue.length>0){var item=self._reverseGeoCodeQueue.splice(0,1)[0];var firstElement=self._reverseGeoCodeQueue[0];if(firstElement){window.setTimeout(function(){finder.reverseGeoCode(searchType,firstElement.position)},0)}item.handler.call(item.bind||self,list)}});self._reverseGeoCodingFinder=finder}self._reverseGeoCodeQueue.push({position:this.toGeo(aPosition),handler:aNonBlockingHandler,bind:aBind});if(finder&&finder.getStatus()!=finder.STATUS_BUSY){var searchType=nokia.aduno.utils.platform.maemo?finder.SEARCH_TYPE_OFFLINE:finder.SEARCH_TYPE_ONLINE;if(self._reverseGeoCodeQueue.length>0){finder.reverseGeoCode(searchType,self._reverseGeoCodeQueue[0].position)}}},_fixWrongResults:function(aList){if(aList){for(var i=0;i<aList.length;i++){var p=aList[i];if(3.5265<=p.latitude&&p.latitude<=10.9519&&-9.1424<=p.longitude&&p.longitude<=-2.1407&&p.ADDR_COUNTRY_NAME==="VIRGIN ISLANDS, BRITISH"){p.ADDR_COUNTRY_NAME="C\u00d4TE D'IVOIRE"}if(37.0804<=p.latitude&&p.latitude<=43.2678&&123.5104<=p.longitude&&p.longitude<=131.0764&&p.ADDR_COUNTRY_NAME==="ZIMBABWE"){p.ADDR_COUNTRY_NAME="KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF KOREA"}if(28.9768<=p.latitude&&p.latitude<=35.2825&&33.454<=p.longitude&&p.longitude<=39.4899&&p.ADDR_COUNTRY_NAME==="GRENADA"){p.ADDR_COUNTRY_NAME="PALESTINIAN TERRITORIES"}if(28.9768<=p.latitude&&p.latitude<=35.2825&&33.454<=p.longitude&&p.longitude<=39.4899&&p.ADDR_COUNTRY_NAME==="MEXICO"){p.ADDR_COUNTRY_NAME="SYRIAN ARAB REPUBLIC"}}}return aList},geoCode:function(aSearchStringOrSearchStringBuilder,aResultsSize,aNonBlockingHandler,aBind){var search,finder=this._pluginControl.createFinder();if(typeof aSearchStringOrSearchStringBuilder=="string"){search=new SearchStringBuilder().setMaxResults(aResultsSize).setGeoPosition(this.getMapCenterPosition()).setOneboxText(aSearchStringOrSearchStringBuilder).makeString()}else{search=aSearchStringOrSearchStringBuilder.setMaxResults(aResultsSize).setGeoPosition(this.getMapCenterPosition()).setOneboxText(aSearchStringOrSearchStringBuilder.getOneBoxText()).makeString()}if(aNonBlockingHandler){var callback=function(aFinder){if(aFinder.getStatus()==aFinder.STATUS_OK){var results=aFinder.getResults();var list=this._convertReverseResult(results);aNonBlockingHandler.call(aBind||this,list)}else{nokia.aduno.utils.error("Geo coding failed, status: "+finder.getStatus())}aFinder.setOnGeoCodeDone(null)};finder.setOnGeoCodeDone(nokia.aduno.utils.bind(this,callback));finder.geoCode(finder.SEARCH_TYPE_ONLINE,search)}else{nokia.aduno.utils.error("No callback handler given to geoCode")}return[]},getPlacesModel:function(){return this._placeModel},serialize:function(aPersistence){aPersistence.addData("orientation",this.getOrientation());aPersistence.addData("tilt",this.getTilt());aPersistence.addData("mapType",this.getMapType());aPersistence.addData("scale",this.getZoomScale());aPersistence.addData("trafficInfo",this.getTrafficInfoVisible()?"visible":"hidden");var pos=this.getMapCenterPosition();aPersistence.addData("longitude",pos.longitude);aPersistence.addData("latitude",pos.latitude);aPersistence.addData("measurement",this.getMeasurementType()?1:0)},deserialize:function(aPersistence){try{var orientation=aPersistence.getData("orientation");if(orientation!==null){orientation=parseInt(orientation,10)}var tilt=aPersistence.getData("tilt");if(tilt!==null){tilt=parseInt(tilt,10)}var scale=aPersistence.getData("scale");if(scale!==null){scale=parseInt(scale,10)}var longitude=aPersistence.getData("longitude");if(longitude!==null){longitude=parseFloat(longitude)}var latitude=aPersistence.getData("latitude");if(latitude!==null){latitude=parseFloat(latitude)}var mapType=aPersistence.getData("mapType");if(mapType){this.setMapType(mapType)}this.moveTo({orientation:orientation,tilt:tilt,scale:scale,longitude:longitude,latitude:latitude,animationMode:"none"});var trafficInfo=aPersistence.getData("trafficInfo");if(trafficInfo){this.setTrafficInfoVisible(trafficInfo=="visible")}var measurement=parseInt(aPersistence.getData("measurement"));this.setMeasurementType(measurement===1)}catch(err){debug("Cannot deserialize MapModel: "+err)}},handleMouseClickEvent:function(aClickEvent){var eve=new nokia.aduno.utils.Event(MapModel.EVENT_MAP_CLICKED,aClickEvent.getData?aClickEvent.getData():null,true);this.fireEvent(eve);return eve.isPreventDefault()},_initTransportCategories:function(){var categories=this._map.getPoiCategories();var count=categories.getLength();var transportRegExp=/AIRPORT|AIRLINE|METRO|UNDERGROUND|RAILWAY|FERRY|SBAHN|RER_/;for(var i=0;i<count;++i){var catName=categories.at(i);if(catName.match(transportRegExp)){this._transportCategories[catName]={visible:true,menuEntry:false,isProtected:true};this._categories[catName]={visible:false,menuEntry:false,isProtected:true};this._map.showPoiCategory(catName,true);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_CATEGORIES_CHANGED,{category:catName,type:"shown"}))}}this._categories.ALL={visible:false,menuEntry:false,isProtected:true}},getCategories:function(){var count=this._map.getPoiCategories().getLength();var result=[];for(var i=0;i<count;++i){var catName=this._map.getPoiCategories().at(i);if(this._transportCategories[catName]||catName==="ALL"){continue}result.push(catName)}return result},_setCategoryVisible:function(aName,aVisible){if(!this._categories[aName]){this._categories[aName]={visible:false,menuEntry:true,isProtected:false}}if(this._categories[aName].visible!=aVisible&&!this._categories[aName].isProtected){this._map.showPoiCategory(aName,aVisible);this._categories[aName].visible=aVisible;this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_CATEGORIES_CHANGED,{category:aName,type:aVisible?"shown":"hidden"}))}return this},hideCategory:function(aCategoryName){try{this._setCategoryVisible(aCategoryName,false)}catch(err){return false}return true},showCategory:function(aCategoryName){try{this._setCategoryVisible(aCategoryName,true)}catch(err){return false}return true},isCategoryVisible:function(aName){return this._categories[aName]?this._categories[aName].visible:false},_setCategoryEntryEnabled:function(aName,aEnabled){if(!this._categories[aName]){this._categories[aName]={visible:false,menuEntry:true,isProtected:false}}if(this._categories[aName].menuEntry!=aEnabled&&!this._categories[aName].isProtected){this._categories[aName].menuEntry=aEnabled;this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_CATEGORIES_CHANGED,{category:aName,type:aEnabled?"entryEnabled":"entryDisabled"}))}return this},enableCategoryEntry:function(aName){return this._setCategoryEntryEnabled(aName,true)},disableCategoryEntry:function(aName){return this._setCategoryEntryEnabled(aName,false)},isCategoryEntryEnabled:function(aName){return(this._categories[aName]?this._categories[aName].menuEntry:true)},getEnabledCategoryEntries:function(){var ret={};var cats=this.getCategories();for(var i=0;i<cats.length;i++){if(this.isCategoryEntryEnabled(cats[i])){ret[cats[i]]=this.isCategoryVisible(cats[i])}}return ret},getVisibleCategories:function(){var ret=[];var cats=this.getCategories();for(var i=0;i<cats.length;i++){if(this.isCategoryVisible(cats[i])){ret.push(cats[i])}}return ret},getMapSize:function(){return this._pluginControl.getMapSize()},setTransformCenter:function(aDeltaX,aDeltaY){var center=this._map.getTransformCenter();var newX=center.getX();if(aDeltaX!==null&&aDeltaX!==undefined){newX+=aDeltaX}var newY=center.getY();if(aDeltaY!==null&&aDeltaY!==undefined){newY+=aDeltaY}var pixCoord=this._pluginControl.createPixelCoordinates(newX,newY);this._map.setTransformCenter(pixCoord)},setTransformAbsoluteCenter:function(newX,newY){var pixCoord=this._pluginControl.createPixelCoordinates(newX,newY);this._map.setTransformCenter(pixCoord)},getTransformCenter:function(){var center=this._map.getTransformCenter();return{x:center.getX(),y:center.getY()}},setMeasurementType:function(aUseImperialUnits){this._useImperialUnits=!!aUseImperialUnits;this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_MEASUREMENT_TYPE_CHANGED,{useImperialUnits:this._useImperialUnits}))},getMeasurementType:function(){return this._useImperialUnits},getCopyright:function(){return this._map.getCopyright()},getPluginControl:function(){return this._pluginControl},setDetailLevel:function(aDetailLevel){if(this.getPluginControl().isPluginInUse()){this._map.setDetailLevel(aDetailLevel)}},getDetailLevel:function(){if(this.getPluginControl().isPluginInUse()){return this._map.getDetailLevel()}return null},showDownload:function(){this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_SHOW_DOWNLOAD))},getAutoTracking:function(){try{return this._map.getAutoTracking()}catch(e){info("PluginControl.getAutoTracking is not supported on this device");return false}},setAutoTracking:function(aFlag){try{this._map.setAutoTracking(aFlag?true:false);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_AUTO_TRACKING_CHANGED))}catch(e){info("PluginControl.setAutoTracking is not supported on this device")}},getUUID:function(){return this.getPluginControl().getUUID()},_onMoveDone:function(){this._moveToParameter={};this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_MOVE_DONE))},showPoints:function(aPoints,aCenterPoint,aOrientation,aPerspective,aAnimationMode){warn("DEPRECATED: use MapModel#moveToPoints() instead MapModel#showPoints()");function pointillize(obj){if(obj.className=="MapMarker"){obj=obj.getPosition();return plugin.createGeoCoordinates(obj.latitude,obj.longitude)}else{if(obj.className=="IGeoCoordinates"){return obj}else{if(typeof obj.getLatitude=="function"){return plugin.createGeoCoordinates(obj.getLatitude(),obj.getLongitude())}}}return plugin.createGeoCoordinates(obj.latitude,obj.longitude)}if(!aPoints||aPoints.length===0||(aPoints.getLength&&aPoints.getLength()===0)){return false}var plugin=this.getPluginControl();var points=plugin.createArray();var center=aCenterPoint?pointillize(aCenterPoint):null;if(type(aPoints)==="array"||aPoints.className){aPoints=splat(aPoints);for(var i=0,c=aPoints.length;i<c;i++){if(!aPoints[i]){continue}if(aPoints[i].className=="MapPolyline"||aPoints[i].className=="MapPolygon"){var subpoints=aPoints[i].getPoints();for(var j=0,d=subpoints.length;j<d;j++){points.push(pointillize(subpoints[j]))}}else{points.push(pointillize(aPoints[i]))}}}else{points=aPoints}var animation=aAnimationMode||this._map.ANIMATION_BOW;var orientation=typeof aOrientation=="number"?aOrientation:this.getOrientation();var perspective=typeof aPerspective=="number"?aPerspective:this.getTilt();if(points.getLength()<2){var geoCoord=points.at(0);this.moveTo({latitude:geoCoord.getLatitude(),longitude:geoCoord.getLongitude(),scale:2000})}else{this._map.showPoints(points,center,animation,orientation,perspective)}},moveToPoints:function(aPointSpec){if(aPointSpec.points===null||aPointSpec.points===undefined){return}var plugin=this.getPluginControl();var points=plugin.createArray();aPointSpec.points=splat(aPointSpec.points);for(var i in aPointSpec.points){var pos,geo;var obj=aPointSpec.points[i];if(obj.className){if(obj.className==="MapMarker"){pos=obj.getPosition();geo=plugin.createGeoCoordinates(pos.latitude,pos.longitude);points.push(geo)}else{if(obj.className==="MapPolyline"||obj.className==="MapPolygon"){var pointsArray=obj.getPoints();for(var j in pointsArray){pos=pointsArray[j];geo=plugin.createGeoCoordinates(pos.latitude,pos.longitude);points.push(geo)}}}}else{if(obj.hasOwnProperty("latitude")&&obj.hasOwnProperty("longitude")){geo=plugin.createGeoCoordinates(obj.latitude,obj.longitude);points.push(geo)}}}var animation=aPointSpec.animationMode;var orientation=typeof aPointSpec.orientation=="number"?aPointSpec.orientation:this.getOrientation();var tilt=typeof aPointSpec.tilt=="number"?aPointSpec.tilt:this.getTilt();if(animation&&typeof animation=="string"){if(animation=="linear"){animation=this._map.ANIMATION_LINEAR}else{if(animation=="none"){animation=this._map.ANIMATION_NONE}else{animation=this._map.ANIMATION_BOW}}}else{animation=this._map.ANIMATION_BOW}var center=null;if(aPointSpec.centerPoint){var cp=aPointSpec.centerPoint;center=plugin.createGeoCoordinates(cp.latitude,cp.longitude)}if(points.getLength()<2){var geoCoord=points.at(0);this.moveTo({latitude:geoCoord.getLatitude(),longitude:geoCoord.getLongitude(),orientation:orientation,tilt:tilt,animationMode:animation})}else{this._map.showPoints(points,center,animation,orientation,tilt)}if(animation!==this._map.ANIMATION_NONE){aPointSpec.latitude=center?center.getLatitude():points.at(0).getLatitude();aPointSpec.longitude=center?center.getLongitude():points.at(0).getLongitude();this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_ANIMATION_START,aPointSpec))}},destroyObject:function(){if(this._reverseGeoCodingFinder&&this.getPluginControl().isPluginInUse()){this._reverseGeoCodingFinder.setOnGeoCodeDone(null)}for(var i in this){if(this[i]&&typeof this[i].destroyObject==="function"){this[i].destroyObject()}this[i]=null}}});MapModel.EVENT_EXTERNAL_CONNECTIONS_READY="externalConnectionsReady";MapModel.EVENT_ANIMATION_START="animationStart";MapModel.EVENT_ANIMATION_DONE="animationDone";MapModel.EVENT_POSITION_CHANGED="positionChanged";MapModel.EVENT_LANGUAGE="languageChanged";MapModel.EVENT_UI_LANGUAGE="uiLanguageChanged";MapModel.EVENT_MAPTYPE="mapTypeChanged";MapModel.EVENT_TILT="tiltChanged";MapModel.EVENT_MAXZOOM="maxZoomChanged";MapModel.EVENT_ZOOMSCALE="zoomScaleChanged";MapModel.EVENT_ORIENTATION="orientationChanged";MapModel.EVENT_COLOR="colorChanged";MapModel.EVENT_MAPOBJECT_SELECTED="mapObjectSelected";MapModel.EVENT_MAPOBJECT_UNSELECTED="mapObjectUnselected";MapModel.EVENT_MAP_CLICKED="mapClicked";MapModel.EVENT_LAYERS_CHANGED="layersChanged";MapModel.EVENT_CATEGORIES_CHANGED="categoriesChanged";MapModel.EVENT_TRAFFIC_INFO="trafficInfoChanged";MapModel.EVENT_LANDMARKS="landmarksChanged";MapModel.EVENT_MOVE_START="moveStart";MapModel.EVENT_MOVE_DONE="moveDone";MapModel.EVENT_DRAG_START="dragStart";MapModel.EVENT_DRAG_DONE="dragDone";MapModel.EVENT_SHOW_DOWNLOAD="showDownload";MapModel.EVENT_AUTO_TRACKING_CHANGED="autoTrackingChanged";MapModel.EVENT_MEASUREMENT_TYPE_CHANGED="measurementTypeChanged";MapModel.EVENT_TILT_START="tiltChangeStarted";MapModel.ICON_CACHE_SIZE=30;MapModel.CATEGORY_GROUP={"Amusement park":["AMUSEMENT_PARK","CASINO"],"Tourist Attraction":["TOURIST_ATTRACTION"],"Car dealer":["CAR_DEALER"],"Car rental":["RENT_A_CAR_FACILITY"],"Car repair":["CAR_REPAIR"],"Cash dispenser/ATM":["CASH_DISPENSER"],Cinema:["CINEMA"],Education:["UNIVERSITY"],"Exhibition/conference centre":["EXHIBITION_CENTRE"],"Government office":["GOVERNMENT_OFFICE"],Hospital:["HOSPITAL"],Hotel:["HOTEL"],Library:["LIBRARY"],Museum:["MUSEUM"],Parking:["PARKING","PARKING_AREA","PARKING_GARAGE"],"Petrol station":["PETROL_STATION"],Pharmacy:["PHARMACY"],Police:["POLICE"],"Post office":["POST_OFFICE"],"Religious Place":["PLACE_OF_WORSHIP"],"Rest area":["REST_AREA"],Restaurant:["RESTAURANT"],Shopping:["SHOPPING_CENTRE","SHOP"],"Sport and Outdoor":["SPORT_OUTDOOR"],Theatre:["THEATRE"],"Tourist information":["TOURIST_INFORMATION_CENTRE"]};MapModel.CATEGORY_TO_NAME={AMUSEMENT_PARK:"Amusement park",CASINO:"Amusement park",TOURIST_ATTRACTION:"Tourist Attraction",CAR_DEALER:"Car dealer",RENT_A_CAR_FACILITY:"Car rental",CAR_REPAIR:"Car repair",CASH_DISPENSER:"Cash dispenser/ATM",CINEMA:"Cinema",UNIVERSITY:"Education",EXHIBITION_CENTRE:"Exhibition/conference centre",GOVERNMENT_OFFICE:"Government office",HOSPITAL:"Hospital",HOTEL:"Hotel",LIBRARY:"Library",MUSEUM:"Museum",PARKING:"Parking",PARKING_AREA:"Parking",PARKING_GARAGE:"Parking",PETROL_STATION:"Petrol station",PHARMACY:"Pharmacy",POLICE:"Police",POST_OFFICE:"Post office",PLACE_OF_WORSHIP:"Religious Place",REST_AREA:"Rest area",RESTAURANT:"Restaurant",SHOP:"Shopping",SHOPPING_CENTRE:"Shopping",SPORT_OUTDOOR:"Sport and Outdoor",THEATRE:"Theatre",TOURIST_INFORMATION_CENTRE:"Tourist information"};MapModel.SUPPORTED_LANGUAGES={English:"en-GB",French:"fr-FR",German:"de-DE",Spanish:"es-ES",Italian:"it-IT",Portuguese:"pt-PT",Turkish:"tr-TR",Czech:"cs-CZ",Slovak:"sk-SK",Polish:"pl-PL",Chinese:"zh-HK",Thai:"th-TH",Croatian:"hr-HR",Greek:"el-GR",Romanian:"ro-RO"};var ZoomModel=new Class({Name:"ZoomModel",Implements:[EventSource,Destroyable],initialize:function(aPluginControl,aMapModel,aSteps){this._stepCount=+aSteps;if(nokia.aduno.utils.platform.maemo||nokia.aduno.utils.browser.touch){this._stepCount=19}this._map=aPluginControl.getMap();this._mapModel=aMapModel;this._scaleArray=[];this._limitedZoomScale=false;this.setRange(this._map.getMinZoomScale(),this._map.getMaxZoomScale());this._calculateLogarithmicScale(aSteps);this._mapModel.addEventHandler(MapModel.EVENT_MAXZOOM,this._onMaxZoomChange,this)},_onMaxZoomChange:function(aEvent){this.setRange(this._map.getMinZoomScale(),this._map.getMaxZoomScale());this._calculateLogarithmicScale(this._stepCount)},_calculateLogarithmicScale:function(aSteps){var zoomscales=this._map.getZoomLevels();var i=0;if(zoomscales!==undefined&&zoomscales!==null){var length=zoomscales.getLength();if(this._scaleArray.length==0){for(i=length-1;i>=0;i--){this._scaleArray[length-i-1]=zoomscales.at(i)}}if(length==14){this._limitedZoomScale=true;this.setRange(this._scaleArray[2],this._scaleArray[15])}else{this._limitedZoomScale=false;this.setRange(this._scaleArray[0],this._scaleArray[length-1])}}else{if(aSteps&&aSteps>1){this._scaleArray=[];var factor=1/Math.pow((this._max/this._min),1/(aSteps-1));this._scaleArray[0]=this._min;this._scaleArray[aSteps-1]=this._max;for(i=aSteps-2;i>0;i--){this._scaleArray[i]=this._max*Math.pow(factor,aSteps-1-i)}}else{throw'ZoomModel: Unable to calculate logarithmic scale for "'+aSteps+'" steps'}}},setRange:function(aMin,aMax){if(aMin>=aMax){this._min=aMax;this._max=aMin}else{this._min=aMin;this._max=aMax}if(this._min===this._max){this._max++}},getRange:function(){return{min:this._min,max:this._max}},convertStepToValue:function(aStep){return this._scaleArray[+aStep]||NaN},getZoomScale:function(){return this._map.getZoomScale()},getMinZoomScale:function(){return this._map.getMinZoomScale()},getMaxZoomScale:function(){return this._map.getMaxZoomScale()},convertValueToStep:function(aValue){for(var i=this._scaleArray.length-1;i>0;i--){if(aValue>=(this._scaleArray[i]+this._scaleArray[i-1])/2){return i}}return 0},getStep:function(){return this.convertValueToStep(this._map.getZoomScale())},setStep:function(aStep){if(this._limitedZoomScale){if(aStep>=2&&aStep<=15){var value=this.convertStepToValue(aStep);if(value!=NaN){this._mapModel.moveTo({scale:value,animationMode:"linear"})}return true}}else{if(aStep>=0&&aStep<this._stepCount){var value=this.convertStepToValue(aStep);if(value!=NaN){if(nokia.aduno.utils.browser.s60){this._mapModel.setZoomScale(value)}else{this._mapModel.moveTo({scale:value,animationMode:"linear"})}}return true}}return false},getStepCount:function(){return this._stepCount},destroyObject:function(){this._map=null;for(var i in this){if(this[i]&&typeof this[i].destroyObject==="function"){this[i].destroyObject()}this[i]=null}}});var PersistenceModel=new Class({Name:"PersistenceModel",Implements:Destroyable,initialize:function(aPluginControl){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}this._objects=[];this._pluginControl=aPluginControl;this._persistence=this._pluginControl.getPersistence()},_bind:function(aFunction){var myself=this;return function(){return aFunction.apply(myself,arguments)}},addSerializable:function(aSerializable){if(!aSerializable){warn("PersistenceModel: Argument was null.");return false}if(typeof aSerializable.serialize!="function"||typeof aSerializable.deserialize!="function"){return false}if(aSerializable.className===undefined){warn("PersistenceModel.pushSerializable : does not have className");return false}for(var i in this._objects){if(aSerializable===this._objects[i]){warn("PersistenceModel.addSerializable : serializable object is already in array");return false}}this._objects.push(aSerializable);return true},serialize:function(){if(!this._persistence){warn("PersistenceModel: plug-in doesn't support serialization.");return}for(var i=0,c=this._objects.length;i<c;i++){var obj=this._objects[i];this._currentClassName=obj.className;try{obj.serialize(this)}catch(err){debug("PersistenceModel: Failed to serialize "+obj.className+", reason: "+err)}self._currentClassName=null}},deserialize:function(){if(!this._persistence){warn("PersistenceModel: plug-in doesn't support serialization.");return}var self=this;function deserializeObject(){var obj=self._objects[self._index];self._persistence.prepare(obj.className,function(aData){self._currentClassName=obj.className;try{obj.deserialize(self)}catch(err){warn("PersistenceModel: Failed to deserialize "+obj.className+", reason: "+err)}self._index++;self._currentClassName=null;if(self._index<self._objects.length){deserializeObject()}})}if(this._objects.length>0){this._index=0;deserializeObject()}},addData:function(aKey,aData){this._persistence.set(this._currentClassName,aKey,aData)},getData:function(aKey){var val=this._persistence.get(this._currentClassName,aKey);if(browser.msie){return val.replace(/,/,".")}return val},addString:function(aClassName,aKey,aData){this._persistence.set(aClassName,aKey,aData)},getString:function(aClassName,aKey){return this._persistence.get(aClassName,aKey)},addStringList:function(aClassName,aKey,aList){if(aList.length>0){var combined="[";for(var i=0,len=aList.length-1;i<len;++i){combined+='"'+String(aList[i].replace(/\"/,'\\"'))+'",'}combined+='"'+String(aList[i].replace(/\"/,'\\"'))+'"]';this._persistence.set(aClassName,aKey,combined)}},getStringList:function(aClassName,aKey){var result=[];var items=this._persistence.get(aClassName,aKey).split('","');for(var i=0,len=items.length;i<len;++i){result.push(items[i].replace(/^\[?\"/,"").replace(/\"\]$/,"").replace(/\\\"/,'"'))}return result},addBoolean:function(aClassName,aKey,aValue){if(typeof(aValue)==="boolean"){aValue=aValue?"true":"false";this._persistence.set(aClassName,aKey,aValue)}},getBoolean:function(aClassName,aKey){var value=this._persistence.get(aClassName,aKey);if(value=="true"){return true}return false},addNumber:function(aClassName,aKey,aValue){if(typeof(aValue)==="number"){this._persistence.set(aClassName,aKey,aValue)}},getNumber:function(aClassName,aKey){var value=this._persistence.get(aClassName,aKey);return parseInt(value)},addDouble:function(aClassName,aKey,aValue){if(typeof(aValue)==="number"){this._persistence.set(aClassName,aKey,aValue)}},getDouble:function(aClassName,aKey){var value=this._persistence.get(aClassName,aKey);return parseFloat(value)},removeEntry:function(aClassName,aKey){this._persistence.remove(aClassName,aKey)},removeEntriesWithPrefix:function(aClassName,aKeyPrefix){this._persistence.removeAll(aClassName,aKeyPrefix)},removeAllEntries:function(aClassName){this._persistence.removeAll(aClassName,"")}});var ConnectivityModel=new Class({Name:"ConnectivityModel",Implements:[EventSource,Destroyable],initialize:function(aPluginControl){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}this._plugin=aPluginControl;this._connectivity=null;this._hasConnection=false},registerPluginHandlers:function(){this._connectivity=this._plugin.getConnectivity();if(this._connectivity){this._connectivity.setOnAccessPointsUpdated(bind(this,this._onListAccessPointsDone));this._connectivity.setOnConnectivityChange(bind(this,this._onConnectivityChanged))}else{warn("Plugin does not support connectivity on this platform")}},unregisterPluginHandlers:function(){if(this._connectivity){this._connectivity.setOnAccessPointsUpdated(null);this._connectivity.setOnConnectivityChange(null);this._connectivity=null}},getConnectionType:function(){var connectionType=ConnectivityModel.NONE;var activeConnection;if(this._connectivity&&(activeConnection=this._connectivity.getActiveConnection())){var type=activeConnection.getType();if(type==activeConnection.TYPE_CELLULAR||type==activeConnection.AP_TYPE_CELLULAR){connectionType=ConnectivityModel.CELLULAR}else{if(type==activeConnection.TYPE_WIFI||type==activeConnection.AP_TYPE_WIFI){connectionType=ConnectivityModel.WIFI}else{if(type==activeConnection.TYPE_DESTINATION||type==activeConnection.AP_TYPE_DESTINATION){connectionType=ConnectivityModel.DESTINATION}else{connectionType=ConnectivityModel.UNKNOWN;warn("Unknown connection type in nokia.maps.pfw.ConnectivityModel type:"+type)}}}}return connectionType},getSignalQuality:function(){var signalQuality=-1;var activeConnection;if(this._connectivity&&(activeConnection=this._connectivity.getActiveConnection())){signalQuality=activeConnection.getSignalQuality()}return signalQuality},getConnectionName:function(){var name=null;var activeConnection;if(this._connectivity&&(activeConnection=this._connectivity.getActiveConnection())){name=activeConnection.getName()}return name},isOnline:function(){var connType=this.getConnectionType();return connType!=ConnectivityModel.NONE&&connType!=ConnectivityModel.UNKNOWN},updateAccessPoints:function(){if(this._connectivity){this._connectivity.updateAccessPoints();nokia.aduno.utils.info("Setting up connection")}},_onListAccessPointsDone:function(){if(this._connectivity){var accessPoints=this._connectivity.getAccessPoints();if(accessPoints&&accessPoints.getLength()){var ac=accessPoints.at(0);nokia.aduno.utils.info("Connecting: "+ac.getName()+" "+ac.getType()+", "+ac.getSignalQuality());this._connectivity.connect(ac)}this.fireEvent(new nokia.aduno.utils.Event(ConnectivityModel.EVENT_ACCESS_POINTS_FOUND));this._onConnectivityChanged()}},_onConnectivityChanged:function(){if(this._connectivity){var ac=this._connectivity.getActiveConnection();if(ac){this._hasConnection=true;nokia.aduno.utils.info("Changed Connection: "+ac.getName()+" "+ac.getType()+", "+ac.getSignalQuality());this._plugin.setOnlineMode(true)}else{if(this._hasConnection){nokia.aduno.utils.info("Lost Connection: "+ac.getName()+" "+ac.getType()+", "+ac.getSignalQuality());this._hasConnection=false;this._plugin.setOnlineMode(false)}}}this.fireEvent(new nokia.aduno.utils.Event(ConnectivityModel.EVENT_CONNECTIVITY_CHANGED,{name:this.getConnectionName(),type:this.getConnectionType(),quality:this.getSignalQuality()}))}});ConnectivityModel.EVENT_CONNECTIVITY_CHANGED="connectivityChanged";ConnectivityModel.EVENT_ACCESS_POINTS_FOUND="accessPointsFound";ConnectivityModel.DESTINATION="DESTINATION";ConnectivityModel.CELLULAR="CELLULAR";ConnectivityModel.WIFI="WIFI";ConnectivityModel.NONE="NONE";ConnectivityModel.UNKNOWN="UNKNOWN";var PositionModel=new Class({Name:"PositionModel",Implements:[EventSource,Destroyable],initialize:function(aPluginControl,aPositionProvider,aIsDemo){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}this._pluginControl=aPluginControl;if(aPositionProvider){this._setPositionProvider(aPositionProvider)}else{this._setPositionProvider(this._pluginControl.createPositionProvider())}},setEnabled:function(aEnabled){warn("DEPRECATED: use enable/disablePositioning() instead setEnabled()");if(aEnabled){this.enablePositioning()}else{this.disablePositioning()}},enablePositioning:function(){this._positionProvider.setEnabled(true)},disablePositioning:function(){this._positionProvider.setEnabled(false)},isValidPosition:function(){warn("DEPRECATED: use isLivePositioningData() instead isValidPosition()");return this.isLivePositioningData()},isLivePositioningData:function(){try{return this._positionProvider.hasValidPosition()}catch(e){warn("PositionModel.isLivePositioningData is not supported on this device!")}return false},getPositionMethod:function(){warn("DEPRECATED: use getPositioningTechnologyID() instead getPositionMethod()");return this.getPositioningTechnologyID()},getPositioningTechnologyID:function(){if(this._positionProvider){return this._positionProvider.getPositionMethod()}else{return this._currentDemoProvider}},getProviderName:function(){warn("DEPRECATED: use getPositioningTechnologyName() instead getProviderName()");return this.getPositioningTechnologyName()},getPositioningTechnologyName:function(){var providerId=this.getPositioningTechnologyID();return PositionModel.PROVIDER_NAME[providerId]||"unknown"},isPositionEnabled:function(){warn("DEPRECATED: use isPositioningEnabled() instead isPositionEnabled()");return this.isPositioningEnabled()},isPositioningEnabled:function(){return this._positionProvider&&this._positionProvider.getEnabled()},getPosition:function(){if(this._positionProvider){var retValue={};try{var position=this._positionProvider.getPosition();if(position){retValue.longitude=position.getLongitude();retValue.latitude=position.getLatitude();retValue.altitude=position.getAltitude()}if(retValue.altitude===position.UNKNOWN_ALTITUDE&&this._isDemo()){return PositionModel.DEMO_POSITIONS[0]}}catch(e){warn("PositionModel.getPosition failed on getting current position!")}return retValue}else{if(this._isDemo()){return PositionModel.DEMO_POSITIONS[0]}}},getSpeed:function(){warn("DEPRECATED: use getMovementSpeed() instead getSpeed()");return this.getMovementSpeed()},getMovementSpeed:function(){return this._positionProvider.getSpeed()},getDirection:function(){warn("DEPRECATED: use getMovementDirection() instead getDirection()");this.getMovementDirection()},getMovementDirection:function(){return this._positionProvider.getDirection()},getAccuracy:function(){warn("DEPRECATED: use getPositioningAccuracy() instead getAccuracy()");return this.getPositioningAccuracy()},getPositioningAccuracy:function(){return this._positionProvider.getAccuracy()},getAccuracyAltitude:function(){warn("DEPRECATED: use getAltitudeAccuracy() instead getAccuracyAltitude()");return this.getAltitudeAccuracy()},getAltitudeAccuracy:function(){return this._positionProvider.getAltitudeAccuracy()},_onPositionChanged:function(aEvent){var data={position:this.getPosition(),speed:this.getMovementSpeed(),direction:this.getMovementDirection()};if(!this._isDemo()){this.fireEvent(new nokia.aduno.utils.Event(PositionModel.EVENT_POSITION,data))}},_onStatusChanged:function(){if(!this._isDemo()){this.fireEvent(new nokia.aduno.utils.Event(PositionModel.EVENT_PROVIDER,this.getPositioningTechnologyID()))}},_setPositionProvider:function(aPositionProvider){if(!aPositionProvider){aPositionProvider=this._pluginControl.createPositionProvider()}if(this._positionProvider){this.disablePositioning();try{this._positionProvider.setOnPositionChange(null)}catch(e){}try{this._positionProvider.setOnStatusChange(null)}catch(e){}}this._positionProvider=aPositionProvider;if(!this._positionProvider){info("No Provision Provider found... only DEMO Mode available")}else{try{this._positionProvider.setOnPositionChange(bind(this,this._onPositionChanged))}catch(e){}try{this._positionProvider.setOnStatusChange(bind(this,this._onStatusChanged))}catch(e){}this.enablePositioning()}},_demoStep:function(){var nextPosition=this._currentDemoStart+1;if(nextPosition>=PositionModel.DEMO_POSITIONS.length){nextPosition=0}this._currentDemoStep++;if(this._currentDemoStep<50){var factorVal=this._currentDemoStep/50;this._currentDemoPosition.longitude=PositionModel.DEMO_POSITIONS[this._currentDemoStart].longitude+(PositionModel.DEMO_POSITIONS[nextPosition].longitude-PositionModel.DEMO_POSITIONS[this._currentDemoStart].longitude)*factorVal;this._currentDemoPosition.latitude=PositionModel.DEMO_POSITIONS[this._currentDemoStart].latitude+(PositionModel.DEMO_POSITIONS[nextPosition].latitude-PositionModel.DEMO_POSITIONS[this._currentDemoStart].latitude)*factorVal;this._currentDemoPosition.altitude=PositionModel.DEMO_POSITIONS[this._currentDemoStart].altitude+(PositionModel.DEMO_POSITIONS[nextPosition].altitude-PositionModel.DEMO_POSITIONS[this._currentDemoStart].altitude)*factorVal}else{this._currentDemoStep=0;this._currentDemoStart=nextPosition;this._currentDemoProvider=(this._currentDemoProvider+1)%PositionModel.NUMBER_OF_PROVIDERS;this.fireEvent(new nokia.aduno.utils.Event(PositionModel.EVENT_PROVIDER,this._currentDemoProvider));this._currentDemoPosition.longitude=PositionModel.DEMO_POSITIONS[nextPosition].longitude;this._currentDemoPosition.latitude=PositionModel.DEMO_POSITIONS[nextPosition].latitude;this._currentDemoPosition.altitude=PositionModel.DEMO_POSITIONS[nextPosition].altitude}this.fireEvent(new nokia.aduno.utils.Event(PositionModel.EVENT_POSITION,{position:this._currentDemoPosition,speed:0,direction:0}))},_startDemo:function(){debug("STARTING DEMO");if(!this._currentDemoStep){this._currentDemoStep=0;this._currentDemoStart=0;this._currentDemoProvider=PositionModel.PROVIDER_NONE;this.fireEvent(new nokia.aduno.utils.Event(PositionModel.EVENT_PROVIDER,this._currentDemoProvider));this._currentDemoPosition={longitude:PositionModel.DEMO_POSITIONS[0].longitude,latitude:PositionModel.DEMO_POSITIONS[0].latitude,altitude:PositionModel.DEMO_POSITIONS[0].altitude}}if(!this._demoTimer){this._demoTimer=nokia.aduno.utils.setPeriodical(100,this,this._demoStep,{})}},_stopDemo:function(){nokia.aduno.utils.cancelPeriodical(this._demoTimer);this._demoTimer=null},_isDemo:function(){return this._demoTimer!=null},destroyObject:function(){if(this._positionProvider){this._positionProvider.setOnPositionChange(null);this._positionProvider.setOnStatusChange(null)}for(var i in this){if(this[i]&&typeof this[i].destroyObject==="function"){this[i].destroyObject()}this[i]=null}}});PositionModel.EVENT_POSITION="positioningPositionChanged";PositionModel.EVENT_PROVIDER="positioningProviderChanged";PositionModel.PROVIDER_NONE=0;PositionModel.PROVIDER_GPS=1;PositionModel.PROVIDER_CELL=2;PositionModel.PROVIDER_WIFI=3;PositionModel.PROVIDER_IP=4;PositionModel.NUMBER_OF_PROVIDERS=5;PositionModel.MAX_VALID_ACCURACY=300;PositionModel.DEMO_POSITIONS=[];PositionModel.DEMO_POSITIONS[0]={longitude:10,latitude:50,altitude:100};PositionModel.DEMO_POSITIONS[1]={longitude:10.01,latitude:50,altitude:100};PositionModel.DEMO_POSITIONS[2]={longitude:10.01,latitude:50.01,altitude:100};PositionModel.DEMO_POSITIONS[3]={longitude:10,latitude:50.01,altitude:100};PositionModel.PROVIDER_NAME=[];PositionModel.PROVIDER_NAME[PositionModel.PROVIDER_NONE]="No provider";PositionModel.PROVIDER_NAME[PositionModel.PROVIDER_GPS]="GPS";PositionModel.PROVIDER_NAME[PositionModel.PROVIDER_CELL]="Cellular Positioning";PositionModel.PROVIDER_NAME[PositionModel.PROVIDER_WIFI]="WiFi Positioning";PositionModel.PROVIDER_NAME[PositionModel.PROVIDER_IP]="IP Positioning";var RoutingModel=new Class({Name:"RoutingModel",Implements:[EventSource,Destroyable],_pluginControl:null,_map:null,_currentRoute:null,_internalRoutes:null,_waypointMarkerMap:[],_maneuverMarkerMap:[],_pfwPath:"",_maneuverSvg:"",_maneuverLayer:null,_waypointMarkers:[],_visibleWaypointMarkers:[],initialize:function(aPluginControl,aMapModel,aPfwPath){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}this._pluginControl=aPluginControl;this._map=this._pluginControl.getMap();this._mapModel=aMapModel;this._internalRoutes={};this._pfwPath=aPfwPath;if(!this._ROUTE_MODES){var routeOptions=this._pluginControl.createRouteOptions();this._ROUTE_MODES={};this._ROUTE_MODES[routeOptions.MODE_CAR]=Route.TRANSPORTATION_MODE_CAR;this._ROUTE_MODES[routeOptions.MODE_BICYCLE]=Route.TRANSPORTATION_MODE_BICYCLE;this._ROUTE_MODES[routeOptions.MODE_PEDESTRIAN]=Route.TRANSPORTATION_MODE_PEDESTRIAN;this._ROUTE_MODES[routeOptions.MODE_TRACK]=Route.TRANSPORTATION_MODE_TRACK;this._ROUTE_TYPES={};this._ROUTE_TYPES[routeOptions.TYPE_FASTEST]=Route.ROUTE_TYPE_FASTEST;this._ROUTE_TYPES[routeOptions.TYPE_SHORTEST]=Route.ROUTE_TYPE_SHORTEST;this._ROUTE_TYPES[routeOptions.TYPE_ECONOMIC]=Route.ROUTE_TYPE_OPTIMIZED;routeOptions=null}if(!this._ROUTING_CALCULATION_ERROR){var router=this._pluginControl.createRouter();this._ROUTING_CALCULATION_ERROR={};this._ROUTING_CALCULATION_ERROR[router.CAUSE_CANNOT_DO_PEDESTRIAN]=RoutingModel.ERROR_CAUSE_CANNOT_DO_PEDESTRIAN;this._ROUTING_CALCULATION_ERROR[router.CAUSE_ROUTE_USES_DISABLED_ROADS]=RoutingModel.ERROR_CAUSE_ROUTE_USES_DISABLED_ROADS;this._ROUTING_CALCULATION_ERROR[router.CAUSE_NO_ERROR]=RoutingModel.ERROR_CAUSE_NO_ERROR;this._ROUTING_CALCULATION_ERROR[router.CAUSE_GRAPH_DISCONNECTED]=RoutingModel.ERROR_CAUSE_GRAPH_DISCONNECTED;this._ROUTING_CALCULATION_ERROR[router.CAUSE_GRAPH_DISCONNECTED_CHECK_OPTIONS]=RoutingModel.ERROR_CAUSE_GRAPH_DISCONNECTED_CHECK_OPTIONS;this._ROUTING_CALCULATION_ERROR[router.CAUSE_NO_START_POINT]=RoutingModel.ERROR_CAUSE_NO_START_POINT;this._ROUTING_CALCULATION_ERROR[router.CAUSE_NO_END_POINT]=RoutingModel.ERROR_CAUSE_NO_END_POINT;this._ROUTING_CALCULATION_ERROR[router.CAUSE_NO_END_POINT_CHECK_OPTIONS]=RoutingModel.ERROR_CAUSE_NO_END_POINT_CHECK_OPTIONS;this._ROUTING_STATUS={};this._ROUTING_STATUS[router.STATUS_OK]=RoutingModel.STATUS_OK;this._ROUTING_STATUS[router.STATUS_ERROR]=RoutingModel.STATUS_ERROR;this._ROUTING_STATUS[router.STATUS_BUSY]=RoutingModel.STATUS_BUSY;this._ROUTING_STATUS[router.STATUS_NOTRUN]=RoutingModel.STATUS_NOTRUN;this._ROUTING_STATUS[router.STATUS_CANCELED]=RoutingModel.STATUS_CANCELLED;router=null}if(nokia.maps.pfw.layout.web&&this._pfwPath){try{var svg=this.getSvgFromServer(this._pfwPath+"images/ui/web/small_dot.svg");this._maneuverSvg=this._pluginControl.createIconFromSvg(svg)}catch(ex){this._maneuverSvg=null}}},_createWaypoint:function(aWaypoint){var geoCoordinates=this._pluginControl.createGeoCoordinates(aWaypoint.getPosition().latitude,aWaypoint.getPosition().longitude);return geoCoordinates},calculateRoute:function(aRoute){aRoute.clearCalculation();this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_ROUTE_CALCULATION_STARTED,{route:aRoute}),false);if(!this._irouter){this._irouter=this._pluginControl.createRouter();this._irouter.setMode(this._irouter.MODE_DEFAULT);this._irouter.setOnRoutingDone(nokia.aduno.utils.bind(this,this._onRouteCalculationDone));this._irouter.setOnProgress(nokia.aduno.utils.bind(this,this._onRouteCalculationProgress))}if(this._irouter.getStatus()===this._irouter.STATUS_BUSY){this._irouter.cancel()}var oldRoute=this.getCurrentRoute();if(oldRoute){this.clearRoute(oldRoute)}var iroutePlan=this._createRoutePlan(aRoute);var bindObj=this;var irouter=this._irouter;window.setTimeout(function(){try{if(irouter.getStatus()===irouter.STATUS_BUSY){irouter.cancel()}if(iroutePlan.getStopoverCount()>1){irouter.calculate(iroutePlan)}bindObj.setCurrentRoute(aRoute)}catch(e){error("Error in Route calculation: "+e)}},0)},isRouteCalculationInProgress:function(){return this._irouter&&this._irouter.getStatus()===this._irouter.STATUS_BUSY},_onRouteCalculationDone:function(aRouter){var route=this.getCurrentRoute();if(!route){return}var eventData={route:route};if(aRouter.getStatus()===aRouter.STATUS_OK){if(aRouter.getErrorCause()===aRouter.CAUSE_ROUTE_USES_DISABLED_ROADS){eventData.error=true;eventData.errorCause=this._ROUTING_CALCULATION_ERROR[aRouter.getErrorCause()];this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,eventData),false)}else{var iroute=aRouter.getCalculatedRoute();this._addInternalRoute(route,iroute);route.setRoutePlan(iroute.getRoutePlan());this._applyRouteCalculationResult(iroute,route);this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,eventData),false)}}else{if(aRouter.getStatus()===aRouter.STATUS_ERROR){eventData.error=true;eventData.errorCause=this._ROUTING_CALCULATION_ERROR[aRouter.getErrorCause()];this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,eventData),false)}else{if(aRouter.getStatus()===aRouter.STATUS_CANCELED){this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_ROUTE_CALCULATION_CANCELLED,eventData),false)}else{eventData.error=true;this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,eventData),false)}}}},_applyRouteCalculationResult:function(aInternalRoute,aRoute){aRoute.setLength(aInternalRoute.getLength());aRoute.setDuration(aInternalRoute.getDuration());var maneuvers=[];var irouteManeuvers=aInternalRoute.getManeuvers();if(irouteManeuvers){var currentWaypointIndex=1;for(var i=0,len=irouteManeuvers.getLength();i<len;i++){var maneuver=new Maneuver(irouteManeuvers.at(i));if(i===0){maneuver.setWaypointIndex(0)}else{if(maneuver.getAction()==Maneuver.ACTION_STOPOVER){maneuver.setWaypointIndex(currentWaypointIndex);currentWaypointIndex++}else{if(i===len-1){maneuver.setWaypointIndex(currentWaypointIndex)}}}maneuvers[maneuvers.length]=maneuver}}aRoute._maneuvers=maneuvers;var jscol=aRoute.getColor();try{var nativeColor=this._pluginControl.createColor(jscol.red,jscol.green,jscol.blue,jscol.alpha);aInternalRoute.setColor(nativeColor)}catch(ex){warn("Could not set route color")}},setCurrentRoute:function(aRoute){if(aRoute!==this._currentRoute){var oldRoute=this._currentRoute;if(oldRoute){this.clearRoute(oldRoute);this.removeWaypointsFromMap(oldRoute)}this._currentRoute=aRoute;this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,{oldRoute:oldRoute,newRoute:aRoute}),false)}},_getInternalRoute:function(aRoute){return this._internalRoutes[aRoute]},_addInternalRoute:function(aRoute,aInternalRoute){this._internalRoutes[aRoute]=aInternalRoute},getCurrentRoute:function(){return this._currentRoute},getWaypointFromMapObjectId:function(aMapObjectId){return this._waypointMarkerMap[aMapObjectId]},hideRoutePath:function(aRoute){var iroute=this._getInternalRoute(aRoute);if(iroute){this._map.removeRoute(iroute)}},showRoutePath:function(aRoute){var iroute=this._getInternalRoute(aRoute);if(iroute){this._map.addRoute(iroute)}},showWaypointsOnMap:function(aRoute,aWaypointIcons){if(aRoute.hasDefinedWaypoints()){var len=aRoute.getWaypointCount();for(var i=0;i<len;i++){var waypoint=aRoute.getWaypoint(i);this._showWaypointMarker(i,waypoint,aWaypointIcons)}var remainingMarkersCount=this._visibleWaypointMarkers.length-aRoute.getWaypointCount();if(remainingMarkersCount>0){for(var j=this._visibleWaypointMarkers.length-1;j>=aRoute.getWaypointCount();j--){this._removeWaypointMarkerFromMap(j)}}}else{this.removeWaypointsFromMap()}},removeWaypointsFromMap:function(){var len=this._visibleWaypointMarkers.length;if(len>0){for(var i=len-1;i>=0;i--){this._removeWaypointFromMap(i)}}},_removeWaypointFromMap:function(aIndex){var marker=this._visibleWaypointMarkers[aIndex];if(marker){this._visibleWaypointMarkers[aIndex].hide()}this._visibleWaypointMarkers.splice(aIndex,1)},_showWaypointMarker:function(aIndex,aWaypoint,aWaypointIcons){var position=null;if(aWaypoint.getPosition()){position=aWaypoint.getPosition()}else{position={latitude:0,longitude:0}}var layer=this._getWaypointsLayer();var marker=this._waypointMarkers[aIndex];if(!marker){marker=new MapMarker(null,null,aWaypointIcons[aIndex]);marker.setClickable(true);marker.addEventHandler("selected",this._onWaypointSelected,this);layer.addMapObjects(marker);this._waypointMarkers[aIndex]=marker}marker.show();marker.setPosition(position);marker.setInfoTitle(aWaypoint.getPlace());marker.setInfoDescription(aWaypoint.getDescription());if(nokia.maps.pfw.layout.touch){marker.setIconSize(36.8,32)}this._waypointMarkerMap[marker.getId()]=aWaypoint;if(!aWaypoint.getPosition()){marker.hide();this._visibleWaypointMarkers.splice(aIndex,1)}else{if(aWaypoint.getPosition()){marker.show();this._visibleWaypointMarkers[aIndex]=marker}}},_getWaypointsLayer:function(){var layer=null;if(!this._mapModel.hasLayer("Waypoint_Layer")){layer=this._mapModel.createLayer({name:"Waypoint_Layer"});var layerNames=this._mapModel.getLayers();var highestZIndex=0;for(var j=0,wlen=layerNames.length;j<wlen;j++){var tmpLayer=this._mapModel.getLayer(layerNames[j]);var tmpIndex=tmpLayer.getZIndex();if(tmpIndex>highestZIndex){highestZIndex=tmpIndex}}highestZIndex++;layer.setZIndex(highestZIndex)}else{layer=this._mapModel.getLayer("Waypoint_Layer")}return layer},addManeuverSpots:function(aRoute){var maneuvers=null;if(aRoute){maneuvers=aRoute.getManeuvers()}if(maneuvers&&this._maneuverSvg){var len=maneuvers.length;if(!this._maneuverLayer){this._maneuverLayer=this._pluginControl.createLayer();var waypointLayer=this._getWaypointsLayer();this._maneuverLayer.setZIndex(waypointLayer.getZIndex()+1)}var loc=this._pluginControl.createLocation();for(var i=1;i<len;i++){var maneuver=maneuvers[i];if(!maneuver.getWaypointIndex()){var mapicon=this._pluginControl.createMapIcon();loc.setGeoCoordinates(this._mapModel.toGeo(maneuver.getPosition()));mapicon.setLocation(loc);mapicon.setIcon(this._maneuverSvg);mapicon.setSize(5,5);this._maneuverLayer.addMapObject(mapicon);this._maneuverMarkerMap[i]=maneuver}}this._map.addLayer(this._maneuverLayer)}},removeManeuverSpots:function(){if(this._maneuverLayer){this._map.removeLayer(this._maneuverLayer);this._maneuverLayer=null}},clearRoute:function(aRoute){if(!aRoute){aRoute=this.getCurrentRoute()}if(nokia.maps.pfw.layout.web){this.removeManeuverSpots()}this.hideRoutePath(aRoute)},zoomToRoute:function(aRoute,aVisibleAreaRestriction){var iroute=this._getInternalRoute(aRoute);if(iroute){if(iroute.getRoutePlan().getStopoverCount()===0){return}var bbox=null;if(aVisibleAreaRestriction){try{var visibleArea={left:0+aVisibleAreaRestriction.left,top:0+aVisibleAreaRestriction.top,right:this._pluginControl.getAppearance().getWidth()-aVisibleAreaRestriction.right,bottom:this._pluginControl.getAppearance().getHeight()-aVisibleAreaRestriction.bottom};bbox=this._rescaleRouteBoundingBox(iroute.getBoundingBox(),visibleArea)}catch(ex){bbox=null;warn("Bounding box of the route could not be estimated: "+ex)}}if(bbox===null){bbox=iroute.getBoundingBox()}this._map.showPoints(bbox,null,this._map.ANIMATION_LINEAR,this._map.PRESERVE_ORIENTATION,this._map.PRESERVE_PERSPECTIVE)}},_rescaleRouteBoundingBox:function(aGeoBoundBox,aPixelBoundBox){var g1x=aGeoBoundBox.at(0).getLongitude();var g1y=aGeoBoundBox.at(0).getLatitude();var g2x=aGeoBoundBox.at(1).getLongitude();var g2y=aGeoBoundBox.at(1).getLatitude();var p1PrimeX=0;var p1PrimeY=0;var p2PrimeX=this._pluginControl.getAppearance().getWidth();var p2PrimeY=this._pluginControl.getAppearance().getHeight();var p1x=aPixelBoundBox.left;var p1y=aPixelBoundBox.top;var p2x=aPixelBoundBox.right;var p2y=aPixelBoundBox.bottom;var deltaP1PrimeX=Math.abs(p1x-p1PrimeX);var deltaP1PrimeY=Math.abs(p1PrimeY-p1y);var deltaP2PrimeX=Math.abs(p2x-p2PrimeX);var deltaP2PrimeY=Math.abs(p2PrimeY-p2y);var deltaPX=Math.abs(p2x-p1x);var deltaPY=Math.abs(p1y-p2y);var deltaGX=Math.abs(g2x-g1x);var deltaGY=Math.abs(g1y-g2y);var deltaG1PrimeY=(deltaP1PrimeY/deltaPY)*deltaGY;var deltaG1PrimeX=(deltaP1PrimeX/deltaPX)*deltaGX;var deltaG2PrimeY=(deltaP2PrimeY/deltaPY)*deltaGY;var deltaG2PrimeX=(deltaP2PrimeX/deltaPX)*deltaGX;var g1PrimeY=g1y+deltaG1PrimeY;var g1PrimeX=g1x-deltaG1PrimeX;var g2PrimeY=g2y-deltaG2PrimeY;var g2PrimeX=g2x+deltaG2PrimeX;var geocoordsNewNorthWest=this._pluginControl.createGeoCoordinates();var geocoordsNewSouthEast=this._pluginControl.createGeoCoordinates();geocoordsNewNorthWest.setLongitude(g1PrimeX);geocoordsNewNorthWest.setLatitude(g1PrimeY);geocoordsNewSouthEast.setLongitude(g2PrimeX);geocoordsNewSouthEast.setLatitude(g2PrimeY);aGeoBoundBox=this._pluginControl.createArray();aGeoBoundBox.push(geocoordsNewNorthWest);aGeoBoundBox.push(geocoordsNewSouthEast);return(aGeoBoundBox)},_onRouteCalculationProgress:function(aRoute){var event=new nokia.aduno.utils.Event(RoutingModel.EVENT_ROUTE_CALCULATION_PROGRESS,{route:this._currentRoute,percentage:aRoute.getProgress()});this.fireEvent(event,false)},_getObjectFromIArray:function(arrObjects,aIndex){if(arrObjects.getLength()<=aIndex){throw"The given index is greater than the array has elements"}var objectType=eval(arrObjects.objectType);var obj=arrObjects.at(aIndex);if(nokia.aduno.utils.browser.mozilla&&objectType){obj.QueryInterface(objectType)}return obj},createRouteOptions:function(aRoute){var options=this._pluginControl.createRouteOptions();if(aRoute.getRouteType()==Route.ROUTE_TYPE_STRAIGHT_LINE){options.setRouteMode(options.MODE_TRACK)}else{var valid=false;Collection.forEach(this._ROUTE_MODES,function(aValue,aKey){if(aValue==aRoute._transportationMode){options.setRouteMode(aKey);valid=true}});if(!valid){warn("Used unknown transportation mode "+aRoute._transportationMode)}if(aRoute.getTransportationMode()==Route.TRANSPORTATION_MODE_CAR){valid=false;Collection.forEach(this._ROUTE_TYPES,function(aValue,aKey){if(aValue==aRoute._routeType){options.setRouteType(aKey);valid=true}});if(!valid){warn("Used unknown route type "+aRoute._routeType)}options.setAllowHighways(aRoute._allowHighways);options.setAllowTollRoads(aRoute._allowTollroads);options.setAllowTunnels(aRoute._allowTunnels)}options.setAllowFerries(aRoute._allowFerries);aRoute._refreshRouteOptions=false}return options},_createRoutePlan:function(aRoute){var iroutePlan=aRoute.getRoutePlan();if(!iroutePlan){var iarrStopovers=this._pluginControl.createArray();var arrWaypoints=aRoute.getWaypoints();for(var i=0,len=arrWaypoints.length;i<len;++i){var waypoint=this._createWaypoint(arrWaypoints[i]);iarrStopovers.push(waypoint)}iroutePlan=this._pluginControl.createRoutePlan(iarrStopovers);if(iroutePlan.getStopoverCount()===0){iroutePlan.addStopovers(iarrStopovers)}}if(aRoute.refreshRouteOptions()){iroutePlan.setAllRouteOptions(this.createRouteOptions(aRoute))}return iroutePlan},cancelRouteCalculation:function(){var canceled=false;if(this._irouter){var status=this._ROUTING_STATUS[this._irouter.getStatus()];if(status===RoutingModel.STATUS_BUSY){this._irouter.cancel();this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_ROUTE_CALCULATION_CANCELLED,null),false);canceled=true}}return canceled},getSvgFromServer:function(urlDef){var queryResponse=null;var loader=new nokia.aduno.Loader({uri:urlDef,async:false,handler:function(value,success){if(!success){throw new Error("Failed to load: "+urlDef+", reason: "+value)}queryResponse=value}});return queryResponse},_onWaypointSelected:function(aEvent){var data=aEvent.getData();var waypoint=this._waypointMarkerMap[data.getId()];this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_WAYPOINT_CLICKED,{waypoint:waypoint,markerId:data.getId()}),false)},_onManeuverSelected:function(aEvent){var data=aEvent.getData();var maneuver=this._maneuverMarkerMap[data.getId()];this.fireEvent(new nokia.aduno.utils.Event(RoutingModel.EVENT_MANEUVER_CLICKED,{maneuver:maneuver,markerId:data.getId()}),false)}});RoutingModel.STATUS_OK="ok";RoutingModel.STATUS_ERROR="error";RoutingModel.STATUS_BUSY="busy";RoutingModel.STATUS_NOTRUN="didn't run";RoutingModel.STATUS_CANCELLED="cancelled";RoutingModel.EVENT_ROUTE_CALCULATION_STARTED="route calculation started";RoutingModel.EVENT_ROUTE_CALCULATION_DONE="route calculated";RoutingModel.EVENT_ROUTE_CALCULATION_ERROR="route calculation error";RoutingModel.EVENT_ROUTE_CALCULATION_CANCELLED="route calculation cancelled";RoutingModel.EVENT_ROUTE_CALCULATION_PROGRESS="route calculating progress";RoutingModel.EVENT_CURRENT_ROUTE_CHANGED="current route changed";RoutingModel.EVENT_CLEAR_CURRENT_ROUTE="clear current route";RoutingModel.EVENT_PRINT_CURRENT_ROUTE="print current route";RoutingModel.EVENT_WAYPOINT_CLICKED="waypoint on map clicked";RoutingModel.EVENT_MANEUVER_CLICKED="maneuver on map clicked";RoutingModel.EVENT_NEXT_MANEUVER="next maneuver";RoutingModel.EVENT_PREVIOUS_MANEUVER="previous maneuver";RoutingModel.ERROR_CAUSE_ROUTE_USES_DISABLED_ROADS="route uses disabled roads";RoutingModel.ERROR_CAUSE_CANNOT_DO_PEDESTRIAN="pedestrian route not calculable";RoutingModel.ERROR_CAUSE_NO_ERROR="no error";RoutingModel.ERROR_CAUSE_GRAPH_DISCONNECTED="graph disconnected";RoutingModel.ERROR_CAUSE_GRAPH_DISCONNECTED_CHECK_OPTIONS="graph disconnected check options";RoutingModel.ERROR_CAUSE_NO_START_POINT="no start point defined";RoutingModel.ERROR_CAUSE_NO_END_POINT="no end point defined";RoutingModel.ERROR_CAUSE_NO_END_POINT_CHECK_OPTIONS="no end point defined check options";RoutingModel.MAX_WAYPOINTS=26;RoutingModel.OBJECT_CATEGORY_WAYPOINT="waypoint";var Route=new Class({Name:"Route",Implements:EventSource,_waypoints:null,_length:0,_duration:0,_allowHighways:true,_allowTollroads:true,_allowTunnels:true,_allowFerries:true,_allowUnpavedRoads:true,_allowMotorailTrain:true,_transportationMode:null,_routeType:null,_color:null,_maneuvers:null,_dummyWaypoint:-1,_routeName:"",_pluginControl:null,_routePlan:null,_refreshRouteOptions:true,initialize:function(aWaypoints,aPluginControl){if(aWaypoints){this._waypoints=aWaypoints}else{this._waypoints=[]}this._transportationMode=Route.TRANSPORTATION_MODE_CAR;this._routeType=Route.ROUTE_TYPE_OPTIMIZED;this._pluginControl=aPluginControl;this.setColor({red:138,green:35,blue:98,alpha:255})},getWaypoints:function(){return[].concat(this._waypoints)},removeWaypointAt:function(aIndex){var removedWaypoint=null;if(aIndex>=0&&aIndex<this._waypoints.length){removedWaypoint=this._waypoints[aIndex];this._waypoints.splice(aIndex,1);for(var i=0,len=this._waypoints.length;i<len;i++){this._waypoints[i].setIndex(i)}this._dummyWaypoint=-1;if(this._routePlan){this._routePlan.removeStopover(aIndex)}this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_REMOVED,index:aIndex})}return removedWaypoint},removeWaypoint:function(aWaypoint){for(var i=0;i<this._waypoints.length;i++){if(aWaypoint==this._waypoints[i]){return this.removeWaypointAt(i)}}},addWaypoint:function(aWaypoint){if(this._waypoints.length===RoutingModel.MAX_WAYPOINTS){nokia.aduno.utils.error("A route can not have more than "+RoutingModel.MAX_WAYPOINTS+" stopovers.")}else{var index=0;if(this._dummyWaypoint!==-1){this.insertWaypointAt(this._dummyWaypoint,aWaypoint);this._dummyWaypoint=-1}else{aWaypoint.setIndex(this._waypoints.length);this._waypoints.push(aWaypoint);index=this._waypoints.length-1;if(this._pluginControl&&this._routePlan){var waypoint=this._pluginControl.createGeoCoordinates(aWaypoint.getPosition().latitude,aWaypoint.getPosition().longitude);this._routePlan.addStopover(waypoint)}this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_ADDED,index:index})}}},getWaypointCount:function(){return this._waypoints.length},addDummyWaypoint:function(aIndex){if(this._waypoints.length===RoutingModel.MAX_WAYPOINTS){nokia.aduno.utils.error("A route can not have more than "+RoutingModel.MAX_WAYPOINTS+" stopovers.")}else{this._dummyWaypoint=aIndex}},insertWaypointAt:function(aIndex,aWaypoint){if(this._waypoints.length===RoutingModel.MAX_WAYPOINTS){nokia.aduno.utils.error("A route can not have more than "+RoutingModel.MAX_WAYPOINTS+" stopovers.");return}if(aIndex>this._waypoints.length||aIndex<0){nokia.aduno.utils.error("Invalid index for setting a waypoint in a route!");return}aWaypoint.setIndex(aIndex);if(this._pluginControl&&this._routePlan){var waypoint=this._pluginControl.createGeoCoordinates(aWaypoint.getPosition().latitude,aWaypoint.getPosition().longitude);this._routePlan.insertStopover(waypoint,aIndex)}if(aIndex===this._waypoints.length){this._waypoints[aIndex]=aWaypoint}else{this._waypoints.splice(aIndex,0,aWaypoint);if(aIndex===this._dummyWaypoint){this._dummyWaypoint=-1}}this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_ADDED,index:aIndex})},replaceWaypointAt:function(aIndex,aWaypoint){if(aIndex>=0&&aIndex<this._waypoints.length){aWaypoint.setIndex(aIndex);this._waypoints.splice(aIndex,1,aWaypoint);if(this._pluginControl&&this._routePlan){var waypoint=this._pluginControl.createGeoCoordinates(aWaypoint.getPosition().latitude,aWaypoint.getPosition().longitude);this._routePlan.removeStopover(aIndex);this._routePlan.insertStopover(waypoint,aIndex)}this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_REPLACED,index:aIndex})}else{if(aIndex===this._waypoints.length){aWaypoint.setIndex(aIndex);this._waypoints[aIndex]=aWaypoint;if(this._pluginControl&&this._routePlan){var waypoint2=this._pluginControl.createGeoCoordinates(aWaypoint.getPosition().latitude,aWaypoint.getPosition().longitude);this._routePlan.addStopover(waypoint2)}this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_REPLACED,index:aIndex})}else{nokia.aduno.utils.error("Invalid index for replacing a waypoint in a route!")}}},moveWaypoint:function(aIndexFrom,aIndexTo){if(aIndexFrom<0||aIndexFrom>this._waypoints.length||aIndexTo<0||aIndexTo>this._waypoints.length){nokia.aduno.utils.error("Invalid parameters for moving a waypoint to another position.");return}if(aIndexFrom===aIndexTo){return}var waypoint=this.getWaypoint(aIndexFrom);this._waypoints.splice(aIndexFrom,1);this._waypoints.splice(aIndexTo,0,waypoint);for(var i=0,len=this._waypoints.length;i<len;i++){this._waypoints[i].setIndex(i)}if(this._pluginControl&&this._routePlan){var iwaypoint=this._routePlan.getStopoverAt(aIndexFrom);this._routePlan.removeStopover(aIndexFrom);this._routePlan.insertStopover(iwaypoint,aIndexTo)}this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_MOVED,index_from:aIndexFrom,index_to:aIndexTo})},getPrintView:function(aTranslator,aSpice,aMap){if(this._maneuvers&&this._waypoints){var myWindow=window.open(aSpice.getOption("printPagePath"),"printView","status=0,toolbar=0,location=0,menubar=1,directories=0,resizable=0,scrollbars=1,height=800,width=600");myWindow.route=this;myWindow.map=aMap;myWindow.translator=aTranslator;myWindow.spice=aSpice}},clear:function(){if(this._waypoints){this._waypoints.splice(0,0);this._waypoints=[]}if(this._maneuvers){this._maneuvers.splice(0,0);this._maneuvers=[]}this._routePlan=null;this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_CLEARED,index:0})},getRoutePlan:function(){return this._routePlan},setRoutePlan:function(aRoutePlan){if(this._pluginControl){this._routePlan=aRoutePlan}},refreshRouteOptions:function(){return this._refreshRouteOptions},getWaypoint:function(aIndex){return this._waypoints[aIndex]},setStartWaypoint:function(aWaypoint){this._waypoints[0]=aWaypoint;this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_ADDED,index:0})},setDestinationWaypoint:function(aWaypoint){if(this._waypoints.length===0){this._waypoints[1]=aWaypoint}else{this._waypoints[this._waypoints.length]=aWaypoint}this._notifyObservers(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,{action:Route.ROUTE_WAYPOINT_ADDED,index:this._waypoints.length-1})},getStartPosition:function(){if(this._waypoints&&this._waypoints.length>0&&this._waypoints[0]){return this._waypoints[0].getPosition()}return null},getDestinationPosition:function(){if(this._waypoints&&this._waypoints.length>1){return this._waypoints[this._waypoints.length-1].getPosition()}return null},getColor:function(){return this._color},setColor:function(aColor){this._color=aColor},getLength:function(){return this._length},getDuration:function(){return this._duration},getManeuvers:function(){return this._maneuvers},setTransportationMode:function(aMode){this._transportationMode=aMode;this._refreshRouteOptions=true;this._notifyObservers(Route.EVENT_ROUTE_OPTIONS_CHANGED);return this},getTransportationMode:function(){return this._transportationMode},setRouteType:function(aType){this._routeType=aType;this._refreshRouteOptions=true;this._notifyObservers(Route.EVENT_ROUTE_OPTIONS_CHANGED);return this},getRouteType:function(){return this._routeType},setLength:function(aLength){this._length=aLength},setDuration:function(aDuration){this._duration=aDuration},setAllowHighways:function(aAllow){this._allowHighways=aAllow;this._refreshRouteOptions=true;this._notifyObservers(Route.EVENT_ROUTE_OPTIONS_CHANGED);return this},setAllowTollroads:function(aAllow){this._allowTollroads=aAllow;this._refreshRouteOptions=true;this._notifyObservers(Route.EVENT_ROUTE_OPTIONS_CHANGED);return this},setAllowTunnels:function(aAllow){this._allowTunnels=aAllow;this._refreshRouteOptions=true;this._notifyObservers(Route.EVENT_ROUTE_OPTIONS_CHANGED);return this},setAllowFerries:function(aAllow){this._allowFerries=aAllow;this._refreshRouteOptions=true;this._notifyObservers(Route.EVENT_ROUTE_OPTIONS_CHANGED);return this},setAllowUnpavedRoads:function(aAllow){this._allowUnpavedRoads=aAllow;this._refreshRouteOptions=true;this._notifyObservers(Route.EVENT_ROUTE_OPTIONS_CHANGED);return this},setAllowMotorailTrain:function(aAllow){this._allowMotorailTrain=aAllow;this._refreshRouteOptions=true;this._notifyObservers(Route.EVENT_ROUTE_OPTIONS_CHANGED);return this},setName:function(aRouteName){this._routeName=aRouteName;return this},getAllowHighways:function(){return this._allowHighways},getAllowTollroads:function(){return this._allowTollroads},getAllowTunnels:function(){return this._allowTunnels},getAllowFerries:function(){return this._allowFerries},getAllowUnpavedRoads:function(){return this._allowUnpavedRoads},getAllowMotorailTrain:function(){return this._allowMotorailTrain},getName:function(){return this._routeName},isValidOptionValue:function(aRouteOptionType,aNewValue){var isValid=true;if(Route.OPTION_MODE===aRouteOptionType){if(Route.TRANSPORTATION_MODE_PEDESTRIAN===aNewValue&&this._length>50000){isValid=false}}else{if(Route.OPTION_TYPE===aRouteOptionType){}else{if(Route.OPTION_AVOID===aRouteOptionType){}}}return isValid},isValid:function(){if(this._waypoints.length<=1){return false}for(var i=0;i<this._waypoints.length;i++){if(!this._waypoints[i]||!this._waypoints[i].getPosition()){return false}}return true},hasDefinedWaypoints:function(){if(this._waypoints.length<=0){return false}if(this._waypoints.length==1&&this._waypoints[0]&&this._waypoints[0].isGpsPosition()){return false}return true},_notifyObservers:function(aCategory,aData){if(aCategory===Route.EVENT_ROUTE_WAYPOINTS_CHANGED){var bindObj=this;setTimeout(function(){bindObj.fireEvent(new nokia.aduno.utils.Event(aCategory,aData))},0)}else{this.fireEvent(new nokia.aduno.utils.Event(aCategory,aData))}},getRestoreInformation:function(){var waypoints=this.getWaypoints();var position;var location;var waypointInfo;var positionArray=[];for(var i=0;i<waypoints.length;i++){position=waypoints[i].getPosition();location=waypoints[i].getLocation();waypointInfo={};if(position){waypointInfo.latitude=position.latitude;waypointInfo.longitude=position.longitude;if(location){waypointInfo.ADDR_CITY_NAME=location.getField("ADDR_CITY_NAME");waypointInfo.ADDR_STREET_NAME=location.getField("ADDR_STREET_NAME");waypointInfo.ADDR_HOUSE_NUMBER=location.getField("ADDR_HOUSE_NUMBER");waypointInfo.ADDR_DISTRICT_NAME=location.getField("ADDR_DISTRICT_NAME");waypointInfo.ADDR_POSTAL_CODE=location.getField("ADDR_POSTAL_CODE");waypointInfo.PLACE_NAME=location.getField("PLACE_NAME")}else{waypointInfo.PLACE=waypoints[i].getPlace();waypointInfo.DESCRIPTION=waypoints[i].getDescription()}positionArray.push(waypointInfo)}}return positionArray},isCalculated:function(){var isCalculated=false;if(this._length>0){isCalculated=true}return isCalculated},clearCalculation:function(){if(this._maneuvers){this._maneuvers.splice(0,0);this._maneuvers=[]}this.setDuration(0);this.setLength(0)}});Route.OPTION_MODE="mode";Route.OPTION_TYPE="type";Route.OPTION_AVOID="avoid";Route.TRANSPORTATION_MODE_CAR="car";Route.TRANSPORTATION_MODE_BICYCLE="bicycle";Route.TRANSPORTATION_MODE_PEDESTRIAN="pedestrian";Route.ROUTE_TYPE_FASTEST="fastest";Route.ROUTE_TYPE_SHORTEST="shortest";Route.ROUTE_TYPE_OPTIMIZED="optimised";Route.ROUTE_TYPE_STREET="streets";Route.ROUTE_TYPE_STRAIGHT_LINE="straightline";Route.ROUTE_BLOCKER_FERRIES="Ferries";Route.ROUTE_BLOCKER_TUNNELS="Tunnels";Route.ROUTE_BLOCKER_MOTORWAYS="Motorways";Route.ROUTE_BLOCKER_TOLLROADS="TollRoads";Route.ROUTE_BLOCKER_UNPAVEDROADS="UnpavedRoads";Route.ROUTE_BLOCKER_MOTORAILTRAINS="MotorailTrains";Route.EVENT_ROUTE_OPTIONS_CHANGED="routeOptionsChanged";Route.EVENT_ROUTE_WAYPOINTS_CHANGED="routeWaypointsChanged";Route.ROUTE_WAYPOINT_ADDED="added";Route.ROUTE_WAYPOINT_REMOVED="removed";Route.ROUTE_WAYPOINT_REPLACED="replaced";Route.ROUTE_WAYPOINT_MOVED="moved";Route.ROUTE_WAYPOINT_CLEARED="cleared";var RouteSettingsModel=new Class({Name:"RouteSettingsModel",Implements:[EventSource,Destroyable],_transportationMode:Route.TRANSPORTATION_MODE_CAR,_routeType:Route.ROUTE_TYPE_OPTIMIZED,_useImperialUnits:false,_allowHighways:true,_allowTollroads:true,_allowFerries:true,_allowTunnels:true,_allowUnpavedRoads:true,_allowMotorailTrain:true,_cancelTimeout:null,initialize:function(){},setTransportationMode:function(aMode,aType){if(aMode!=this._transportationMode){this._transportationMode=aMode;switch(aMode){case Route.TRANSPORTATION_MODE_CAR:if(aType){this._routeType=aType}else{this._routeType=Route.ROUTE_TYPE_OPTIMIZED}break;case Route.TRANSPORTATION_MODE_PEDESTRIAN:if(aType){this._routeType=aType}else{this._routeType=Route.ROUTE_TYPE_STREET}break;case Route.TRANSPORTATION_MODE_BICYCLE:if(aType){this._routeType=aType}else{this._routeType=Route.ROUTE_TYPE_STREET}break}this._notifyObservers(RouteSettingsModel.EVENT_TRANSPORTATION_MODE)}return this},getTransportationMode:function(){return this._transportationMode},setRouteType:function(aType){if(this._routeType!==aType){if(this.canSetRouteType(aType)){this._routeType=aType;this._notifyObservers(RouteSettingsModel.EVENT_ROUTE_TYPE)}else{warn("Can't set route type '"+aType+"' in transportation mode '"+this._transportationMode)}return this}},getRouteType:function(){return this._routeType},getAllowTollroads:function(){return this._allowTollroads},getAllowHighways:function(){return this._allowHighways},getAllowTunnels:function(){return this._allowTunnels},getAllowMotorailTrain:function(){return this._allowMotorailTrain},getAllowFerries:function(){return this._allowFerries},getAllowUnpavedRoads:function(){return this._allowUnpavedRoads},setAllowHighways:function(aAllow){this._allowHighways=aAllow;this._notifyObservers(RouteSettingsModel.EVENT_BLOCKERS,[Route.ROUTE_BLOCKER_MOTORWAYS]);return this},setAllowTollroads:function(aAllow){this._allowTollroads=aAllow;this._notifyObservers(RouteSettingsModel.EVENT_BLOCKERS,[Route.ROUTE_BLOCKER_TOLLROADS]);return this},setAllowMotorailTrain:function(aAllow){this._allowMotorailTrain=aAllow;this._notifyObservers(RouteSettingsModel.EVENT_BLOCKERS,[Route.ROUTE_BLOCKER_MOTORAILTRAINS]);return this},setAllowTunnels:function(aAllow){this._allowTunnels=aAllow;this._notifyObservers(RouteSettingsModel.EVENT_BLOCKERS,[Route.ROUTE_BLOCKER_TUNNELS]);return this},setAllowFerries:function(aAllow){this._allowFerries=aAllow;this._notifyObservers(RouteSettingsModel.EVENT_BLOCKERS,[Route.ROUTE_BLOCKER_FERRIES]);return this},setAllowUnpavedRoads:function(aAllow){this._allowUnpavedRoads=aAllow;this._notifyObservers(RouteSettingsModel.EVENT_BLOCKERS,[Route.ROUTE_BLOCKER_UNPAVEDROADS]);return this},_notifyObservers:function(aCategory,aValue){this.fireEvent(new nokia.aduno.utils.Event(aCategory,{value:aValue}))},applySettings:function(aRoute){aRoute.setTransportationMode(this.getTransportationMode());aRoute.setAllowFerries(this.getAllowFerries());aRoute.setAllowUnpavedRoads(this.getAllowUnpavedRoads());aRoute.setAllowTunnels(this.getAllowTunnels());aRoute.setAllowMotorailTrain(this.getAllowMotorailTrain());aRoute.setAllowTollroads(this.getAllowTollroads());aRoute.setAllowHighways(this.getAllowHighways());aRoute.setRouteType(this.getRouteType())},canSetRouteType:function(aRouteType){switch(this._transportationMode){case Route.TRANSPORTATION_MODE_CAR:return aRouteType==Route.ROUTE_TYPE_FASTEST||aRouteType==Route.ROUTE_TYPE_SHORTEST||aRouteType==Route.ROUTE_TYPE_OPTIMIZED;case Route.TRANSPORTATION_MODE_PEDESTRIAN:return aRouteType==Route.ROUTE_TYPE_STRAIGHT_LINE||aRouteType==Route.ROUTE_TYPE_STREET}return aRouteType==Route.ROUTE_TYPE_SHORTEST},canSetAllowFerries:function(){return true},canSetAllowUnpavedRoads:function(){return this._transportationMode==Route.TRANSPORTATION_MODE_CAR},canSetAllowTunnels:function(){return this._transportationMode==Route.TRANSPORTATION_MODE_CAR},canSetAllowMotorailTrain:function(){return this._transportationMode==Route.TRANSPORTATION_MODE_CAR},canSetAllowTollroads:function(){return this._transportationMode==Route.TRANSPORTATION_MODE_CAR},canSetAllowHighways:function(){return this._transportationMode==Route.TRANSPORTATION_MODE_CAR},hasEqualSettings:function(aRoute){if(aRoute.getAllowHighways()!==this.getAllowHighways()){return false}if(aRoute.getAllowTollroads()!==this.getAllowTollroads()){return false}if(aRoute.getAllowTunnels()!==this.getAllowTunnels()){return false}if(aRoute.getAllowFerries()!==this.getAllowFerries()){return false}if(aRoute.getAllowUnpavedRoads()!==this.getAllowUnpavedRoads()){return false}if(aRoute.getAllowMotorailTrain()!==this.getAllowMotorailTrain()){return false}if(aRoute.getRouteType()!==this.getRouteType()){return false}if(aRoute.getTransportationMode()!==this.getTransportationMode()){return false}return true},setAllowedRoadTypes:function(aAllowHighways,aAllowTollrads,aAllowFerries,aAllowTunnels,aAllowUnpavedRoads,aAllowMotorailTrain){var changed=[];if(aAllowHighways!==undefined&&aAllowHighways!==null){this._allowHighways=aAllowHighways;changed.push(Route.ROUTE_BLOCKER_MOTORWAYS)}if(aAllowTollrads!==undefined&&aAllowTollrads!==null){this._allowTollroads=aAllowTollrads;changed.push(Route.ROUTE_BLOCKER_TOLLROADS)}if(aAllowFerries!==undefined&&aAllowFerries!==null){this._allowFerries=aAllowFerries;changed.push(Route.ROUTE_BLOCKER_FERRIES)}if(aAllowTunnels!==undefined&&aAllowTunnels!==null){this._allowTunnels=aAllowTunnels;changed.push(Route.ROUTE_BLOCKER_TUNNELS)}if(aAllowUnpavedRoads!==undefined&&aAllowUnpavedRoads!==null){this._allowUnpavedRoads=aAllowUnpavedRoads;changed.push(Route.ROUTE_BLOCKER_UNPAVEDROADS)}if(aAllowMotorailTrain!==undefined&&aAllowMotorailTrain!==null){this._allowMotorailTrain=aAllowMotorailTrain;changed.push(Route.ROUTE_BLOCKER_MOTORAILTRAINS)}this._notifyObservers(RouteSettingsModel.EVENT_BLOCKERS,changed)},reset:function(){this._transportationMode=Route.TRANSPORTATION_MODE_CAR;this._routeType=Route.ROUTE_TYPE_OPTIMIZED;this._allowHighways=true;this._allowTollroads=true;this._allowFerries=true;this._allowTunnels=true;this._allowUnpavedRoads=true;this._allowMotorailTrain=true;this._notifyObservers(RouteSettingsModel.EVENT_RESET)}});RouteSettingsModel.EVENT_BLOCKERS="blockers";RouteSettingsModel.EVENT_ROUTE_TYPE="route type";RouteSettingsModel.EVENT_TRANSPORTATION_MODE="transportation mode";RouteSettingsModel.EVENT_RESET="route settings are reset";RouteSettingsModel.EVENT_DISTANCE_UNIT="distance unit";var SpiceManager=new Class({Name:"SpiceManager",Implements:[EventSource,Options,MouseEventHandler,Destroyable],_unremovableSpices:{},initialize:function(aSize,aOptions){this.setOptions(aOptions);this._spices={};this._dragHandler=null;this._wheelHandler=null;this._mouseOverHandler=null;this._mouseOutHandler=null;this._mouseClickHandlers={};this._keyHandlers={};this._lastKeys={};this._keyModified=false;this._draggingDelegationControls=[];this._size=aSize||{x:0,y:0};if(typeof nokiaMapLoader!="undefined"&&nokiaMapLoader!==null&&nokiaMapLoader.options!==undefined&&nokiaMapLoader.options!==null&&nokiaMapLoader.options.uiLanguage!==undefined&&nokiaMapLoader.options.uiLanguage!==null){this._resources=new nokia.aduno.i18n.ResourceManager(this.getOption("internationalizationPath"),{defaultLocale:nokiaMapLoader.options.uiLanguage});if(__locale!==undefined&&__locale!==null){this._resources.set(nokiaMapLoader.options.uiLanguage,__locale)}}else{this._resources=new nokia.aduno.i18n.ResourceManager(this.getOption("internationalizationPath"),{});this._resources.addEventHandler("ready",function(aReadyEvent){this._language=aReadyEvent.getData().locale;this._localizer=new nokia.aduno.i18n.Translator(this._resources.get(this._language));this._translator=new nokia.maps.pfw.PlayerTranslationVisitor(this._localizer);Collection.forEach(this._spices,function(aSpice,aName){aSpice.translateUi(this._translator,this._language)},this);this.fireEvent(SpiceManager.EVENT_UI_TRANSLATED,{language:this._language})},this)}},addSpice:function(aSpice,aSlotName,aRemovable){if(this._spices[aSlotName]){warn("A spice for the slot "+aSlotName+" was already registered.");return false}this._spices[aSlotName]=aSpice;if(arguments.length>=3&&aRemovable){this._unremovableSpices[aSlotName]=true}if(this._translator){aSpice.translateUi(this._translator,this._language)}return true},getSpice:function(aSlotName){return this._spices[aSlotName]},getRegisteredSpiceSlots:function(){var spices=[];for(var slot in this._spices){if(this._spices.hasOwnProperty(slot)){spices.push(slot)}}return spices},removeSpice:function(aSpiceOrName){var spice=aSpiceOrName;if(type(aSpiceOrName)==="string"){spice=this._spices[aSpiceOrName]}if(!spice||this._unremovableSpices[spice.className]){return false}var ui=spice.getUi();if(ui){ui.hide()}delete this._spices[spice.className];return true},setDragHandler:function(aHandler){if(!this._dragHandler){this._dragHandler=aHandler;return true}else{warn("A drag handler was already registered");return false}},addDraggingDelegationControl:function(aControl){var size=this._draggingDelegationControls.length;for(var i=0;i<size;i++){if(this._draggingDelegationControls[i]===aControl){return false}}aControl.addBehavior(new Draggable());aControl.addEventHandler("dragged",this._handleDragDelegation,this);return true},_handleDragDelegation:function(aDragEvent){var data=aDragEvent.getData();this.fireEvent(new nokia.aduno.utils.Event(SpiceManager.EVENT_DRAGGING_DELEGATED,data))},setMouseUpHandler:function(aHandler){if(!this._mouseUpHandler){this._mouseUpHandler=aHandler;return true}else{warn("A mouse up handler was already registered");return false}},removeMouseUpHandler:function(aHandler){if(this._mouseUpHandler&&this._mouseUpHandler==aHandler){this._mouseUpHandler=null;return true}else{return false}},setWheelHandler:function(aHandler){if(!this._wheelHandler){this._wheelHandler=aHandler;return true}else{warn("A wheel handler was already registered");return false}},setMouseClickHandler:function(aButton,aClickCount,aHandler){var key=aButton+"_"+aClickCount;if(!this._mouseClickHandlers[key]){this._mouseClickHandlers[key]=aHandler;return true}else{warn("A mouse click handler for ["+aButton+", "+aClickCount+"] was already registered");return false}},removeMouseClickHandler:function(aButton,aClickCount){var key=aButton+"_"+aClickCount;if(this._mouseClickHandlers[key]){delete this._mouseClickHandlers[key];return true}return false},setMouseOverHandler:function(aHandler){if(aHandler!==null&&typeof aHandler!="function"){warn("SpiceManager.setMouseOverHandler: Invalid argument aHandler, expecting function.");return false}if(!this._mouseOverHandler){this._mouseOverHandler=aHandler;return true}else{warn("A mouse over handler was already registered");return false}},setMouseOutHandler:function(aHandler){if(aHandler!==null&&typeof aHandler!="function"){warn("SpiceManager.setMouseOutHandler: Invalid argument aHandler, expecting function.");return false}if(!this._mouseOutHandler){this._mouseOutHandler=aHandler;return true}else{warn("A mouse out handler was already registered");return false}},_getKeyHandlerDictKey:function(aKeyCode,aModifier){if(nokia.aduno.utils.browser.s60){return aKeyCode}else{return aKeyCode+"_"+aModifier}},setKeyHandler:function(aKeyCode,aModifier,aHandler){var key=this._getKeyHandlerDictKey(aKeyCode,aModifier);if(typeof aHandler!="function"){error("setKeyHandler: The handler to set for ["+aKeyCode+", "+aModifier+"] was not a function.");return false}else{if(!this._keyHandlers[key]){this._keyHandlers[key]=aHandler;return true}}warn("setKeyHandler: A handler for ["+aKeyCode+", "+aModifier+"] was already registered.");return false},getKeyHandler:function(aKeyCode,aModifier){return this._keyHandlers[this._getKeyHandlerDictKey(aKeyCode,aModifier)]},removeKeyHandler:function(aKeyCode,aModifier){var key=this._getKeyHandlerDictKey(aKeyCode,aModifier);var handler=this._keyHandlers[key];if(handler){this._keyHandlers[key]=null}return handler},handleDragEvent:function(aDragData){if(this._dragHandler){return this._dragHandler(aDragData)}},handleWheelEvent:function(aWheelEvent){if(this._wheelHandler){return this._wheelHandler(aWheelEvent)}return false},handleMouseClickEvent:function(aClickEvent){var data=aClickEvent.getData();var key=data.button+"_"+data.clickCount;if(this._mouseClickHandlers[key]){this._mouseClickHandlers[key](aClickEvent)}},handleKeyEvent:function(aKeyEvent){var key=null;if(nokia.aduno.utils.browser.s60){key=aKeyEvent.getKey()}else{var currentKey=aKeyEvent.getKey();var currentKeyModifier=aKeyEvent.getModifier();key=currentKey+"_"+currentKeyModifier;if(aKeyEvent.keyUp){if(this._lastKeys[currentKey]){delete this._lastKeys[currentKey]}}else{if(aKeyEvent.keyDown){if((currentKeyModifier>0)!=this._keyModified){for(var i in this._lastKeys){var k=this._lastKeys[i];k.keyDown=false;k.keyUp=true;this._keyHandlers[k.getKey()+"_"+k.getModifier()](k)}this._lastKeys={};this._keyModified=(currentKey==KeyEventManager.KEY_CONTROL)||(currentKeyModifier>0)}if(this._keyHandlers[key]){aKeyEvent.save();this._lastKeys[currentKey]=aKeyEvent}}}this._lastKeyModifier=currentKeyModifier}if(this._keyHandlers[key]){this._keyHandlers[key](aKeyEvent);return true}return false},handleMouseOverEvent:function(aMouseOverEvent){return this._mouseOverHandler&&this._mouseOverHandler(aMouseOverEvent)},handleMouseUpEvent:function(aMouseUpEvent){if(this._mouseUpHandler){return this._mouseUpHandler(aMouseUpEvent)}return false},handleMouseOutEvent:function(aMouseOutEvent){return this._mouseOutHandler&&this._mouseOutHandler(aMouseOutEvent)},handleModalSpiceOpened:function(aNotifyingSpice){for(var name in this._spices){var spice=this._spices[name];if(spice!=aNotifyingSpice&&typeof spice.onOtherSpiceReceivedFocus=="function"){spice.onOtherSpiceReceivedFocus()}}},getSize:function(){return this._size},setSize:function(aSize){this._size=aSize;this.fireEvent(new nokia.aduno.utils.Event(SpiceManager.EVENT_SIZE_CHANGED,aSize))},setSpiceLanguage:function(aLanguage){this._language=aLanguage;this._resources.require(aLanguage)},translateSpices:function(aLanguage){if(aLanguage){aLanguage=aLanguage.toLowerCase();if(aLanguage!==this._language){this._language=aLanguage;this._resources.require(aLanguage)}}},translateExternal:function(aLanguage){this._localizer=new nokia.aduno.i18n.Translator(this._resources.get(aLanguage));this._translator=new nokia.maps.pfw.PlayerTranslationVisitor(this._localizer);Collection.forEach(this._spices,function(aSpice,aName){aSpice.translateUi(this._translator,aLanguage)},this);this.fireEvent(SpiceManager.EVENT_UI_TRANSLATED,{language:aLanguage})},destroyObject:function(){for(var i in this._spices){if(this._spices[i].destroyObject&&type(this._spices[i].destroyObject)==="function"){this._spices[i].destroyObject()}}for(var x in this){this[x]=null}}});SpiceManager.EVENT_SIZE_CHANGED="sizeChanged";SpiceManager.EVENT_UNLOADED="unloaded";SpiceManager.EVENT_UI_TRANSLATED="translationDone";SpiceManager.EVENT_DRAGGING_DELEGATED="draggingDelegated";SpiceManager.EVENT_BLUR="blur";SpiceManager.MOUSE_BUTTON_LEFT=1;SpiceManager.MOUSE_BUTTON_MIDDLE=2;SpiceManager.MOUSE_BUTTON_RIGHT=3;SpiceManager.MOUSE_CLICK_SINGLE=1;SpiceManager.MOUSE_CLICK_DOUBLE=2;var MouseEventHandling=new Class({_dragButton:1,_clickDistance:10,_maemoDraggingIgnoredDistance:20,_targetControl:null,_clickSpeed:300,_clickDuration:1000,_clickTimer:null,_maxClickCount:2,_mouseOverDelay:100,_mouseOverTimer:null,_wasMouseOver:false,_isOverElement:undefined,_draggingEventFired:false,initialize:function(aHandlers){this._eventHandlers=splat(aHandlers);this._clickDatas={}},attachEventHandlers:function(aTargetControl){this._targetControl=aTargetControl;this._mouseUpHandler=nokia.aduno.dom.bindWithEvent(this,this._handleMouseUp);this._mouseMoveHandler=nokia.aduno.dom.bindWithEvent(this,this._handleMouseMove);this._mouseDownHandler=nokia.aduno.dom.bindWithEvent(this,this._handleMouseDown);this._mouseOutHandler=nokia.aduno.dom.bindWithEvent(this,this._handleMouseOut);this._mouseOverHandler=nokia.aduno.dom.bindWithEvent(this,this._handleMouseOver);this._cancelHandler=nokia.aduno.dom.bindWithEvent(this,this._cancelEvents);this._wheelHandler=nokia.aduno.dom.bindWithEvent(this,this._handleMouseWheel);this._windowNode=new nokia.aduno.dom.XNode(this._targetControl.getOwnerDoc());this._dragNode=new nokia.aduno.dom.XNode(this._targetControl.getRootElement());this._windowNode.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this._mouseUpHandler);this._windowNode.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_MOVE,this._mouseMoveHandler);this._dragNode.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this._mouseDownHandler);this._dragNode.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this._mouseOutHandler);this._dragNode.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OVER,this._mouseOverHandler);this._dragNode.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_SCROLL,this._wheelHandler);this._dragNode.addEventHandler(nokia.aduno.dom.XNode.DOM_SELECT_START,this._cancelHandler);this._dragNode.addEventHandler(nokia.aduno.dom.XNode.DOM_DRAG,this._cancelHandler);this._dragNode.addEventHandler("contextmenu",this._cancelHandler);this._draggingCounterMinimum=nokia.aduno.utils.platform.maemo?1:0},removeEventHandlers:function(){this._windowNode.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this._mouseUpHandler);this._windowNode.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_MOVE,this._mouseMoveHandler);this._dragNode.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this._mouseDownHandler);this._dragNode.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this._mouseOutHandler);this._dragNode.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OVER,this._mouseOverHandler);this._dragNode.removeEventHandler(nokia.aduno.dom.XNode.DOM_SELECT_START,this._cancelHandler);this._dragNode.removeEventHandler(nokia.aduno.dom.XNode.DOM_DRAG,this._cancelHandler);this._dragNode.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_SCROLL,this._wheelHandler);this._dragNode.removeEventHandler("contextmenu",this._cancelHandler)},_cancelEvents:function(aDomEvent){aDomEvent.preventDefault();aDomEvent.stopPropagation();return false},_handleMouseMove:function(aDomEvent){var pageX=aDomEvent.get("pageX");var pageY=aDomEvent.get("pageY");if(this._mouseOverTimer){nokia.aduno.utils.cancelPeriodical(this._mouseOverTimer);this._mouseOverTimer=null}if(this._wasMouseOver){this._fireMouseOut({x:pageX,y:pageY})}if(!this._isOverElement){return}if(this._isDragging){var dist=this._draggingEventFired?this._maemoDraggingIgnoredDistance+1:Math.abs(pageX-this._dragOriginX)+Math.abs(pageY-this._dragOriginY);if(dist>this._maemoDraggingIgnoredDistance||!nokia.aduno.utils.platform.maemo){var deltaX=pageX-this._lastMouseX;var deltaY=pageY-this._lastMouseY;this._distance+=Math.abs(deltaX)+Math.abs(deltaY);var data={deltaX:deltaX,deltaY:deltaY,button:aDomEvent.get("which")};this.notifyDragEvent(data);this._draggingEventFired=true}else{if(!this._isDraggingIgnored){this._isDraggingIgnored=true}}}else{this._mouseOverTimer=nokia.aduno.utils.setPeriodical(this._mouseOverDelay,this,this._fireMouseOver)}this._lastMouseX=pageX;this._lastMouseY=pageY},_fireMouseOver:function(){var pos=nokia.aduno.dom.Dimensions.getPosition(this._targetControl.getRootElement());this._wasMouseOver=this.notifyMouseOverEvent({x:(this._lastMouseX-pos.x),y:(this._lastMouseY-pos.y)});nokia.aduno.utils.cancelPeriodical(this._mouseOverTimer);this._mouseOverTimer=null},_fireMouseOut:function(aData){var pos=nokia.aduno.dom.Dimensions.getPosition(this._targetControl.getRootElement());aData.x=aData.x-pos.x;aData.y=aData.y-pos.y;nokia.aduno.utils.cancelPeriodical(this._mouseOverTimer);this._mouseOverTimer=null;this._wasMouseOver=this.notifyMouseOutEvent(aData)},_checkOverElement:function(aDomEvent){var coords=nokia.aduno.dom.Dimensions.getCoordinates(this._dragNode.node);var pageX=aDomEvent.get("pageX");var pageY=aDomEvent.get("pageY");if(pageX>=coords.left&&pageX<=coords.right&&pageY>=coords.top&&pageY<=coords.bottom){this._isOverElement=true}else{this._isOverElement=false}},_handleMouseDown:function(aDomEvent){var button=aDomEvent.get("which");if(nokia.aduno.utils.browser.safari){var ctrl=aDomEvent.get("ctrlKey");var plugin=this._targetControl.isPluginInUse();if(!plugin){if(button==SpiceManager.MOUSE_BUTTON_LEFT&&ctrl){button=SpiceManager.MOUSE_BUTTON_RIGHT}else{if(button==SpiceManager.MOUSE_BUTTON_RIGHT){var self=this;window.setTimeout(function(){self._handleMouseUp(aDomEvent)},101)}}}}if(this._isOverElement===undefined){this._checkOverElement(aDomEvent)}if(this._isOverElement){if(button==this._dragButton){this._isDragging=true;this._lastMouseX=aDomEvent.get("pageX");this._lastMouseY=aDomEvent.get("pageY");this._dragOriginX=this._lastMouseX;this._dragOriginY=this._lastMouseY}aDomEvent.preventDefault();aDomEvent.stopPropagation();this._distance=0}this._updateState();this._mouseDownTimestamp=new Date().getTime();return false},_handleMouseUp:function(aDomEvent){var button=aDomEvent.get("which");if(this._clickTimer){clearTimeout(this._clickTimer);this._clickTimer=null}if(nokia.aduno.utils.browser.safari){var ctrl=aDomEvent.get("ctrlKey");var plugin=this._targetControl.isPluginInUse();if(plugin){if(button==SpiceManager.MOUSE_BUTTON_RIGHT){this._handleMouseDown(aDomEvent)}}else{if(button==SpiceManager.MOUSE_BUTTON_LEFT&&ctrl){button=SpiceManager.MOUSE_BUTTON_RIGHT;this._handleMouseDown(aDomEvent)}}}this._isDragging=false;if(this._distance!==null&&this._distance<this._clickDistance&&this._isOverElement&&!this._draggingEventFired){if(this._clickTimer){clearTimeout(this._clickTimer);this._clickTimer=null}var pos=nokia.aduno.dom.Dimensions.getPosition(this._targetControl.getRootElement());var data=this._clickDatas[button];if(data){data.clickCount++}else{data={x:aDomEvent.get("pageX")-pos.x,y:aDomEvent.get("pageY")-pos.y,button:button,clickCount:1};this._clickDatas[button]=data}var forceClick=this._isDraggingIgnored;if(data.clickCount>=this._maxClickCount){if(forceClick||this._clickDuration>new Date().getTime()-this._mouseDownTimestamp){this._fireClickEvent()}else{this._clickDatas={}}}else{if(!this._clickCallback){var binder=this;this._clickCallback=function(){if(forceClick||binder._clickDuration>new Date().getTime()-binder._mouseDownTimestamp){binder._fireClickEvent()}else{this._clickDatas={}}}}this._clickTimer=setTimeout(this._clickCallback,this._clickSpeed)}}else{this.notifyMouseUpEvent(aDomEvent)}this._draggingEventFired=false;this._isDraggingIgnored=false;if(!data||data.clickCount>1){this._distance=null}else{this._distance=0}this._updateState();return false},_fireClickEvent:function(){for(var i in this._clickDatas){if(this._clickDatas.hasOwnProperty(i)){this.notifyMouseClickEvent(new nokia.aduno.utils.Event("selected",this._clickDatas[i],true))}}if(this._clickTimer){clearTimeout(this._clickTimer);this._clickTimer=null}this._clickDatas={}},_handleMouseOut:function(aDomEvent){this._isOverElement=false;this._updateState()},_handleMouseOver:function(aDomEvent){this._isOverElement=true;this._updateState()},_handleMouseWheel:function(aWheelEvent){this.notifyWheelEvent(aWheelEvent)},_updateState:function(){if(this._isDragging&&this._isOverElement){this._targetControl.getReplica().addCssClass("nm_Dragging")}else{this._targetControl.getReplica().removeCssClass("nm_Dragging")}},notifyMouseUpEvent:function(aMouseUpEvent){var button=aMouseUpEvent.get("which");var handled=false;for(var i=0,len=this._eventHandlers.length;i<len&&!handled;i++){handled=this._eventHandlers[i].handleMouseUpEvent(button)}},notifyDragEvent:function(aDragData){var len=this._eventHandlers.length;var handled=false;for(var i=0;i<len&&!handled;i++){handled=this._eventHandlers[i].handleDragEvent(aDragData)}},notifyWheelEvent:function(aWheelEvent){var len=this._eventHandlers.length;var handled=false;for(var i=0;i<len&&!handled;i++){handled=this._eventHandlers[i].handleWheelEvent(aWheelEvent)}if(handled){aWheelEvent.preventDefault();aWheelEvent.stopPropagation()}},notifyMouseClickEvent:function(aClickEvent){var len=this._eventHandlers.length;var handled=false;for(var i=0;i<len&&!handled;i++){handled=this._eventHandlers[i].handleMouseClickEvent(aClickEvent)}},notifyMouseOverEvent:function(aMouseOverEvent){var len=this._eventHandlers.length;var wasOverAnObject=false;for(var i=0;i<len&&!wasOverAnObject;i++){wasOverAnObject=this._eventHandlers[i].handleMouseOverEvent(aMouseOverEvent)}return wasOverAnObject},notifyMouseOutEvent:function(aMouseOutEvent){var len=this._eventHandlers.length;var handled=false;for(var i=0;i<len&&!handled;i++){handled=this._eventHandlers[i].handleMouseOutEvent(aMouseOutEvent)}},prependHandler:function(aHandler){this._eventHandlers.splice(0,0,aHandler);return this}});var GuidanceMockup=null;var GuidanceSimulatorPositionProvider=null;var FfSimulatorPositionProvider=null;var GuidanceModel=new Class({Name:"GuidanceModel",Implements:[EventSource,Destroyable],_currentRoute:null,_MANEUVER_ICONS:null,_guidance:null,initialize:function(aPluginControl,aRoutingModel,aPositionModel,aMapModel){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}this._pluginControl=aPluginControl;try{this._guidance=this._pluginControl.getGuidance()}catch(ex){this._guidance=null}if(!this._guidance){this._guidance=new GuidanceMockup()}this._guidance.setOnGuidanceDone(bind(this,this._onGuidanceDone));this._guidance.setManeuverEvent(bind(this,this._onNextManeuverChanged));this._routeModel=aRoutingModel;this._mapModel=aMapModel;this._positionModel=aPositionModel},isGuidanceSupported:function(){return this._guidance!==null&&this._guidance!==undefined&&this._guidance.className!=="GuidanceMockup"},startNavigation:function(aRoute,aSimulate){var simulate=aSimulate===true;var iroute=this._routeModel._getInternalRoute(aRoute);window.setTimeout(bind(this,function(){this._guidance.start(iroute,simulate);this.fireEvent(new nokia.aduno.utils.Event(GuidanceModel.EVENT_GUIDANCE_STARTED,{route:aRoute,simulate:simulate}))}),100);if(simulate){if(!nokia.aduno.utils.platform.maemo){if(!this._positionChangeSimulator){if(browser.s60){this._positionChangeSimulator=new GuidanceSimulatorPositionProvider(this._mapModel)}else{this._positionChangeSimulator=new FfSimulatorPositionProvider(this._mapModel,this._guidance)}}this._positionModel._setPositionProvider(this._positionChangeSimulator);this._positionChangeSimulator.activate(aRoute)}}},stopNavigation:function(){this._guidance.stop();this.fireEvent(new nokia.aduno.utils.Event(GuidanceModel.EVENT_GUIDANCE_STOPPED));if(this._positionChangeSimulator){this._positionModel._setPositionProvider(null);this._positionChangeSimulator.deactivate()}},pauseNavigation:function(aPause){if(aPause===true||aPause===undefined){this._guidance.pause()}else{this._guidance.resume()}},repeatLastVoiceCommand:function(){this._guidance.repeat()},isNavigationRunning:function(){if(this._guidance){return this._guidance.isRunning()}return false},getNextManeuver:function(){if(this._guidance.className!=="GuidanceMockup"){return this._guidance._nextManeuver}else{return new Maneuver(this._guidance.getNextManeuver())}},getAfterNextManeuver:function(){if(this._guidance.className!=="GuidanceMockup"){return this._guidance._afterNextManeuver}else{return new Maneuver(this._guidance.getAfterNextManeuver())}},getNextManeuverDistance:function(){return this._guidance.getNextManeuverDistance()},getAfterNextManeuverDistance:function(){return this._guidance.getAfterNextManeuverDistance()},getTimeToArrival:function(){return this._guidance.getTimeToArrival()},getDistanceToDestination:function(){return this._guidance.getDestinationDistance()},getElapsedDistance:function(){return this._guidance.getElapsedDistance()},getAvailableVoiceSkins:function(){var ivoiceskins=this._guidance.getVoiceSkins();info("Available voice skins: ");var voiceNames=[];for(var i=0,len=ivoiceskins.getLength();i<len;++i){var name=ivoiceskins.at(i).getDescription();voiceNames.push(name);info("   "+name)}return voiceNames},setActiveVoiceSkin:function(aVoiceSkin){var ivoiceskins=this._guidance.getVoiceSkins();var success=false;for(var i=0,len=ivoiceskins.getLength();i<len;++i){var cur=ivoiceskins.at(i);if(cur.getDescription()==aVoiceSkin){this._guidance.setVoiceSkin(cur);success=true}}if(!success){warn("Could not find voice skin "+aVoiceSkin)}},_onGuidanceDone:function(){this.fireEvent(new nokia.aduno.utils.Event(GuidanceModel.EVENT_GUIDANCE_DONE))},_onNextManeuverChanged:function(){this.fireEvent(new nokia.aduno.utils.Event(GuidanceModel.EVENT_ON_NEXT_MANEUVER_CHANGED))}});GuidanceModel.EVENT_GUIDANCE_STARTED="guidanceStarted";GuidanceModel.EVENT_GUIDANCE_STOPPED="guidanceStopped";GuidanceModel.EVENT_GUIDANCE_DONE="guidanceDone";GuidanceModel.EVENT_ON_NEXT_MANEUVER_CHANGED="guidanceOnManeuver";var PositionMockup=new Class({Name:"PositionMockup",_longitude:0,_latitude:0,_altitude:0,initialize:function(aLongitude,aLatitude,aAltitude){if(aLongitude&&aLatitude===undefined&&aAltitude===undefined){var obj=aLongitude;aLongitude=obj.longitude;aLatitude=obj.latitude;aAltitude=obj.altitude}this._longitude=aLongitude;this._latitude=aLatitude;if(aAltitude!==undefined){this._altitude=aAltitude}},getLongitude:function(){return this._longitude},getLatitude:function(){return this._latitude},getAltitude:function(){return this._altitude},getPosition:function(){return{latitude:this._latitude,longitude:this._longitude}}});GuidanceSimulatorPositionProvider=new Class({Name:"GuidanceSimulatorPositionProvider",INTERVAL:100,_direction:0,_position:null,_speed:40/3.6,hasValidPosition:true,initialize:function(aMapModel){this._mapModel=aMapModel;this._position=new PositionMockup(aMapModel.getMapCenterPosition());this._lastPosition=new PositionMockup({latitude:0,longitude:0})},_onSimulatedPositionChange:function(){this._position=new PositionMockup(this._mapModel.getMapCenterPosition());this.firePositionChanged()},firePositionChanged:function(){if(this._lastPosition._longitude){this._direction=this._calculateBearing(this._lastPosition,this._position)}if(this._positionChangedEvent){this._positionChangedEvent.call()}this._lastPosition._latitude=this._position._latitude;this._lastPosition._longitude=this._position._longitude},activate:function(){this._simulatedPositionTimer=window.setInterval(bind(this,this._onSimulatedPositionChange),this.INTERVAL)},deactivate:function(){window.clearInterval(this._simulatedPositionTimer);this._simulatedPositionTimer=null},_calculateBearing:function(aGeoPosition1,aGeoPosition2){var lat1=aGeoPosition1._latitude?aGeoPosition1._latitude:aGeoPosition1.latitude;var lon1=aGeoPosition1._longitude?aGeoPosition1._longitude:aGeoPosition1.longitude;var lat2=aGeoPosition2._latitude?aGeoPosition2._latitude:aGeoPosition2.latitude;var lon2=aGeoPosition2._longitude?aGeoPosition2._longitude:aGeoPosition2.longitude;var dLon=lon1-lon2;if(dLon===0&&lat1==lat2){return 0}var y=Math.sin(dLon)*Math.cos(lat2);var x=Math.cos(lat1)*Math.sin(lat2)-Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);var angle=Math.atan2(y,x);return((angle*180/Math.PI)+360)%360},setOnPositionChange:function(aHandler){this._positionChangedEvent=aHandler},setEnabled:function(aEnable){},getSpeed:function(){return this._speed},getDirection:function(){return this._direction},getPosition:function(){return this._position},hasValidPosition:function(){return true},getPositionMethod:function(){return 1},getAccuracy:function(){return 1}});FfSimulatorPositionProvider=new Class({Name:"FfSimulatorPositionProvider",Extends:GuidanceSimulatorPositionProvider,UPDATE_INTERVAL:100,MANEUVER_DURATION:10000,initialize:function(aMapModel,aGuidanceMockup){this._super(aMapModel);this._guidance=aGuidanceMockup;this._speed=0},activate:function(aRoute){this._route=aRoute;this._position=new PositionMockup(this._mapModel.getMapCenterPosition());this._setNextManeuver(0);this._timer=window.setInterval(bind(this,this._progressGuidance),this.UPDATE_INTERVAL)},deactivate:function(){window.clearInterval(this._timer)},_setNextManeuver:function(aIndex){var maneuvers=this._route.getManeuvers();this._guidance._elapsedDistance=this._route.getLength()*aIndex/maneuvers.length;this._guidance._destinationDistance=this._route.getLength()-this._guidance._elapsedDistance;this._guidance._tta=(maneuvers.length-aIndex)*this.MANEUVER_DURATION/1000;if(maneuvers&&aIndex<maneuvers.length){this._nextManeuverIndex=aIndex;var targetPosition=maneuvers[aIndex].getPosition();this._guidance._nextManeuver=maneuvers[aIndex];this._positionStep={longitude:(targetPosition.longitude-this._position._longitude)*this.UPDATE_INTERVAL/this.MANEUVER_DURATION,latitude:(targetPosition.latitude-this._position._latitude)*this.UPDATE_INTERVAL/this.MANEUVER_DURATION};if(this._guidance.nextManeuverEvent){this._guidance.nextManeuverEvent.call()}}else{this._guidance._nextManeuver=null;this.deactivate();this._guidance.stop()}},_progressGuidance:function(){if(this._positionStep){var oldPosition=this._mapModel.toGeo(this._position);this._position._latitude+=this._positionStep.latitude;this._position._longitude+=this._positionStep.longitude;var nextManeuver=this._route.getManeuvers()[this._nextManeuverIndex];var targetPosition=nextManeuver.getPosition();if(Math.abs(this._position._latitude-targetPosition.latitude)<0.00002&&Math.abs(this._position._longitude-targetPosition.longitude)<0.00002){this._setNextManeuver(this._nextManeuverIndex+1)}var maneuverPosition=this._mapModel.toGeo(nextManeuver.getPosition());var currentPosition=this._mapModel.toGeo(this._position);this._guidance._nextManeuverDistance=maneuverPosition.distance(currentPosition);this._speed=oldPosition.distance(currentPosition)*1000/this.UPDATE_INTERVAL}this.firePositionChanged()}});GuidanceMockup=new Class({Name:"GuidanceMockup",_nextManeuverDistance:0,_nextManeuver:null,_running:false,_tta:0,_destinationDistance:0,_elapsedDistance:0,initialize:function(){warn("Plugin does not support guidance on this platform.")},start:function(aRoute){warn("IGuidance.start not supported by plugin on this platform. Doing a kind of simulation.");this._running=true},stop:function(){warn("IGuidance.stop not supported by plugin on this platform.");this._running=false;if(this.guidanceDoneEvent){this.guidanceDoneEvent.call()}},pause:function(){warn("IGuidance.pause not supported by plugin on this platform.")},resume:function(){warn("IGuidance.resume not supported by plugin on this platform.")},repeat:function(){warn("IGuidance.repeat not supported by plugin on this platform.")},setOnGuidanceDone:function(aFunctor){this.guidanceDoneEvent=aFunctor},setManeuverEvent:function(aFunctor){this.nextManeuverEvent=aFunctor},getNextManeuver:function(){return this._nextManeuver},getNextManeuverDistance:function(){return this._nextManeuverDistance},getDestinationDistance:function(){return this._destinationDistance},getElapsedDistance:function(){return this._elapsedDistance},getAverageSpeed:function(){return 0},getTimeToArrival:function(){return this._tta},isRunning:function(){return this._running},getVoiceSkins:function(){return{getLength:function(){return 0},at:function(aIndex){return null}}},setVoiceSkin:function(aIVoiceSkin){},getVoiceSkin:function(){return null}});var Maneuver=new Class({Name:"Maneuver",_action:null,_turn:null,_icon:null,_signpost:null,_distanceFromPrevious:null,_streetName:null,_routeName:null,_nextStreetName:null,_position:null,_waypointIndex:null,_iManeuver:null,initialize:function(aIManeuver){if(aIManeuver){this._id=++Maneuver._id+"";this._iManeuver=aIManeuver;if(!Maneuver._MANEUVER_ICONS){this._createManeuverIconMap(aIManeuver)}if(!Maneuver._MANEUVER_TURNS){this._createManeuverTurnMap(aIManeuver)}if(!Maneuver._MANEUVER_ACTIONS){this._createManeuverActionMap(aIManeuver)}this._action=Maneuver._MANEUVER_ACTIONS[aIManeuver.getAction()];this._turn=Maneuver._MANEUVER_TURNS[aIManeuver.getTurn()];this._icon=Maneuver._MANEUVER_ICONS[aIManeuver.getIcon()];this._iconIndex=Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.getIcon()];this._signpost=aIManeuver.getSignPost();this._distanceFromPrevious=aIManeuver.getDistanceFromPreviousManeuver();this._distanceFromStart=aIManeuver.getDistanceFromStart();this._routeName=aIManeuver.getRouteName();this._streetName=aIManeuver.getStreetName();this._nextStreetName=aIManeuver.getNextStreetName();this._position={longitude:aIManeuver.getGeoCoordinates().getLongitude(),latitude:aIManeuver.getGeoCoordinates().getLatitude()};if(aIManeuver.getAction()==aIManeuver.ACTION_END){this._displayStreetName=this._streetName}else{this._displayStreetName=this._nextStreetName}if(aIManeuver.getAction()==aIManeuver.ACTION_ENTER_HIGHWAY_FROM_RIGHT&&aIManeuver.getIcon()==aIManeuver.ICON_ENTER_MOTORWAY_LEFT_LANE){this._icon=Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ENTER_MOTORWAY_RIGHT_LANE]}if(aIManeuver.getAction()==aIManeuver.ACTION_ENTER_HIGHWAY_FROM_LEFT&&aIManeuver.getIcon()==aIManeuver.ICON_ENTER_MOTORWAY_RIGHT_LANE){this._icon=Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ENTER_MOTORWAY_LEFT_LANE]}}},_translatePart:function(aTranslator,aPartString,aUseStreet){var str=aUseStreet?aTranslator.translate("__I18N_"+aPartString+".street__"):aTranslator.translate("__I18N_"+aPartString+"__");if(str=="undefined"){return""}else{return str}},getDescription:function(aTranslator,aUseStreet,aFormat){var streetPlaceholder="{0}";var signpostPlaceholder="{1}";var formatPlaceholder="{0}";var descriptions=[];var description;var street=this._displayStreetName;var signpost=this._signpost;if(street&&signpost&&street==signpost){signpost=""}switch(this._iManeuver.getAction()){case this._iManeuver.ACTION_ROUNDABOUT:descriptions.push(this._translatePart(aTranslator,this._action,false));descriptions.push(this._translatePart(aTranslator,this._turn,aUseStreet));description=descriptions.join(" ");break;case this._iManeuver.ACTION_JUNCTION:description=this._translatePart(aTranslator,this._turn,aUseStreet);break;case this._iManeuver.ACTION_ENTER_HIGHWAY:case this._iManeuver.ACTION_ENTER_HIGHWAY_FROM_LEFT:case this._iManeuver.ACTION_ENTER_HIGHWAY_FROM_RIGHT:case this._iManeuver.ACTION_LEAVE_HIGHWAY:case this._iManeuver.ACTION_CONTINUE_HIGHWAY:case this._iManeuver.ACTION_CHANGE_HIGHWAY:if(aTranslator.translate("__I18N_"+this._turn+"__")){descriptions.push(aTranslator.translate("__I18N_"+this._turn+"__"))}descriptions.push(this._translatePart(aTranslator,this._action,aUseStreet));description=descriptions.join(" "+aTranslator.translate("__I18N_nokia.maps.pfw.maneuver.joiner__")+" ");break;default:descriptions.push(this._translatePart(aTranslator,this._action,aUseStreet));var turnTrans=this._translatePart(aTranslator,this._turn,aUseStreet);if(turnTrans){descriptions.push(turnTrans)}if(descriptions.length){description=descriptions.join(" "+aTranslator.translate("__I18N_nokia.maps.pfw.maneuver.joiner__")+" ")}else{nokia.aduno.utils.warn("Empty maneuver description");description=""}}if(description){description=description.charAt(0).toUpperCase()+description.substring(1)}else{nokia.aduno.utils.warn("Localization texts missing for maneuver descriptions");return""}if(aUseStreet){if(aFormat&&aFormat.street){street=aFormat.street.replace(formatPlaceholder,street)}if(description.indexOf(streetPlaceholder)!=-1){description=description.replace(streetPlaceholder,street)}else{description+=" "+street}if(description.indexOf(signpostPlaceholder)!=-1){if(signpost&&aFormat&&aFormat.signpost){signpost=aFormat.signpost.replace(formatPlaceholder,signpost)}description=description.replace(signpostPlaceholder,signpost)}}return description},getId:function(){return this._id},getAction:function(){return this._action},getTurn:function(){return this._turn},getIcon:function(){return this._icon},getIconIndex:function(){return this._iconIndex},getSignpost:function(){return this._signpost},getDistanceFromStart:function(){return this._distanceFromStart},getDistanceFromPrevious:function(){return this._distanceFromPrevious},getStreetName:function(){return this._streetName},getRouteName:function(){return this._routeName},getNextStreetName:function(){return this._nextStreetName},getPosition:function(){return this._position},getWaypointIndex:function(){return this._waypointIndex},setWaypointIndex:function(aIndex){this._waypointIndex=aIndex},_createManeuverTurnMap:function(aIManeuver){Maneuver._MANEUVER_TURNS=[];Maneuver._MANEUVER_TURNS[aIManeuver.TURN_UNDEFINED]=Maneuver.TURN_UNDEFINED;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_NO_TURN]=Maneuver.TURN_NO_TURN;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_KEEP_MIDDLE]=Maneuver.TURN_KEEP_MIDDLE;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_KEEP_RIGHT]=Maneuver.TURN_KEEP_RIGHT;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_LIGHT_RIGHT]=Maneuver.TURN_LIGHT_RIGHT;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_QUITE_RIGHT]=Maneuver.TURN_QUITE_RIGHT;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_HEAVY_RIGHT]=Maneuver.TURN_HEAVY_RIGHT;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_KEEP_LEFT]=Maneuver.TURN_KEEP_LEFT;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_LIGHT_LEFT]=Maneuver.TURN_LIGHT_LEFT;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_QUITE_LEFT]=Maneuver.TURN_QUITE_LEFT;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_HEAVY_LEFT]=Maneuver.TURN_HEAVY_LEFT;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_RETURN]=Maneuver.TURN_RETURN;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_1]=Maneuver.TURN_ROUNDABOUT_1;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_2]=Maneuver.TURN_ROUNDABOUT_2;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_3]=Maneuver.TURN_ROUNDABOUT_3;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_4]=Maneuver.TURN_ROUNDABOUT_4;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_5]=Maneuver.TURN_ROUNDABOUT_5;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_6]=Maneuver.TURN_ROUNDABOUT_6;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_7]=Maneuver.TURN_ROUNDABOUT_7;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_8]=Maneuver.TURN_ROUNDABOUT_8;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_9]=Maneuver.TURN_ROUNDABOUT_9;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_10]=Maneuver.TURN_ROUNDABOUT_10;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_11]=Maneuver.TURN_ROUNDABOUT_11;Maneuver._MANEUVER_TURNS[aIManeuver.TURN_ROUNDABOUT_12]=Maneuver.TURN_ROUNDABOUT_12},_createManeuverIconMap:function(aIManeuver){Maneuver._MANEUVER_ICONS=[];Maneuver._MANEUVER_ICONS[aIManeuver.ICON_GO_STRAIGHT]=Maneuver.ICON_GO_STRAIGHT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_UNDEFINED]=Maneuver.ICON_UNDEFINED;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_UTURN_RIGHT]=Maneuver.ICON_UTURN_RIGHT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_UTURN_LEFT]=Maneuver.ICON_UTURN_LEFT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_KEEP_RIGHT]=Maneuver.ICON_KEEP_RIGHT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_KEEP_LEFT]=Maneuver.ICON_KEEP_LEFT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_LIGHT_RIGHT]=Maneuver.ICON_LIGHT_RIGHT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_LIGHT_LEFT]=Maneuver.ICON_LIGHT_LEFT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_QUITE_RIGHT]=Maneuver.ICON_QUITE_RIGHT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_QUITE_LEFT]=Maneuver.ICON_QUITE_LEFT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_HEAVY_RIGHT]=Maneuver.ICON_HEAVY_RIGHT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_HEAVY_LEFT]=Maneuver.ICON_HEAVY_LEFT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ENTER_MOTORWAY_RIGHT_LANE]=Maneuver.ICON_ENTER_MOTORWAY_RIGHT_LANE;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ENTER_MOTORWAY_LEFT_LANE]=Maneuver.ICON_ENTER_MOTORWAY_LEFT_LANE;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_LEAVE_MOTORWAY_RIGHT_LANE]=Maneuver.ICON_LEAVE_MOTORWAY_RIGHT_LANE;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_LEAVE_MOTORWAY_LEFT_LANE]=Maneuver.ICON_LEAVE_MOTORWAY_LEFT_LANE;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_MOTORWAY_KEEP_RIGHT]=Maneuver.ICON_MOTORWAY_KEEP_RIGHT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_MOTORWAY_KEEP_LEFT]=Maneuver.ICON_MOTORWAY_KEEP_LEFT;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_1]=Maneuver.ICON_ROUNDABOUT_1;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_2]=Maneuver.ICON_ROUNDABOUT_2;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_3]=Maneuver.ICON_ROUNDABOUT_3;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_4]=Maneuver.ICON_ROUNDABOUT_4;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_5]=Maneuver.ICON_ROUNDABOUT_5;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_6]=Maneuver.ICON_ROUNDABOUT_6;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_7]=Maneuver.ICON_ROUNDABOUT_7;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_8]=Maneuver.ICON_ROUNDABOUT_8;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_9]=Maneuver.ICON_ROUNDABOUT_9;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_10]=Maneuver.ICON_ROUNDABOUT_10;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_11]=Maneuver.ICON_ROUNDABOUT_11;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_12]=Maneuver.ICON_ROUNDABOUT_12;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_1_LH]=Maneuver.ICON_ROUNDABOUT_1_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_2_LH]=Maneuver.ICON_ROUNDABOUT_2_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_3_LH]=Maneuver.ICON_ROUNDABOUT_3_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_4_LH]=Maneuver.ICON_ROUNDABOUT_4_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_5_LH]=Maneuver.ICON_ROUNDABOUT_5_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_6_LH]=Maneuver.ICON_ROUNDABOUT_6_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_7_LH]=Maneuver.ICON_ROUNDABOUT_7_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_8_LH]=Maneuver.ICON_ROUNDABOUT_8_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_9_LH]=Maneuver.ICON_ROUNDABOUT_9_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_10_LH]=Maneuver.ICON_ROUNDABOUT_10_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_11_LH]=Maneuver.ICON_ROUNDABOUT_11_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_ROUNDABOUT_12_LH]=Maneuver.ICON_ROUNDABOUT_12_LH;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_END]=Maneuver.ICON_END;Maneuver._MANEUVER_ICONS[aIManeuver.ICON_FERRY]=Maneuver.ICON_FERRY;Maneuver._MANEUVER_ICON_INDEXES=[];Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_GO_STRAIGHT]=Maneuver.ICON_INDEX_GO_STRAIGHT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_UNDEFINED]=Maneuver.ICON_INDEX_UNDEFINED;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_UTURN_RIGHT]=Maneuver.ICON_INDEX_UTURN_RIGHT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_UTURN_LEFT]=Maneuver.ICON_INDEX_UTURN_LEFT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_KEEP_RIGHT]=Maneuver.ICON_INDEX_KEEP_RIGHT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_KEEP_LEFT]=Maneuver.ICON_INDEX_KEEP_LEFT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_LIGHT_RIGHT]=Maneuver.ICON_INDEX_LIGHT_RIGHT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_LIGHT_LEFT]=Maneuver.ICON_INDEX_LIGHT_LEFT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_QUITE_RIGHT]=Maneuver.ICON_INDEX_QUITE_RIGHT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_QUITE_LEFT]=Maneuver.ICON_INDEX_QUITE_LEFT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_HEAVY_RIGHT]=Maneuver.ICON_INDEX_HEAVY_RIGHT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_HEAVY_LEFT]=Maneuver.ICON_INDEX_HEAVY_LEFT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ENTER_MOTORWAY_RIGHT_LANE]=Maneuver.ICON_INDEX_ENTER_MOTORWAY_RIGHT_LANE;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ENTER_MOTORWAY_LEFT_LANE]=Maneuver.ICON_INDEX_ENTER_MOTORWAY_LEFT_LANE;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_LEAVE_MOTORWAY_RIGHT_LANE]=Maneuver.ICON_INDEX_LEAVE_MOTORWAY_RIGHT_LANE;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_LEAVE_MOTORWAY_LEFT_LANE]=Maneuver.ICON_INDEX_LEAVE_MOTORWAY_LEFT_LANE;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_MOTORWAY_KEEP_RIGHT]=Maneuver.ICON_INDEX_MOTORWAY_KEEP_RIGHT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_MOTORWAY_KEEP_LEFT]=Maneuver.ICON_INDEX_MOTORWAY_KEEP_LEFT;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_1]=Maneuver.ICON_INDEX_ROUNDABOUT_1;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_2]=Maneuver.ICON_INDEX_ROUNDABOUT_2;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_3]=Maneuver.ICON_INDEX_ROUNDABOUT_3;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_4]=Maneuver.ICON_INDEX_ROUNDABOUT_4;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_5]=Maneuver.ICON_INDEX_ROUNDABOUT_5;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_6]=Maneuver.ICON_INDEX_ROUNDABOUT_6;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_7]=Maneuver.ICON_INDEX_ROUNDABOUT_7;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_8]=Maneuver.ICON_INDEX_ROUNDABOUT_8;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_9]=Maneuver.ICON_INDEX_ROUNDABOUT_9;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_10]=Maneuver.ICON_INDEX_ROUNDABOUT_10;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_11]=Maneuver.ICON_INDEX_ROUNDABOUT_11;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_12]=Maneuver.ICON_INDEX_ROUNDABOUT_12;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_1_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_1_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_2_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_2_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_3_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_3_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_4_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_4_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_5_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_5_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_6_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_6_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_7_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_7_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_8_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_8_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_9_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_9_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_10_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_10_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_11_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_11_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_ROUNDABOUT_12_LH]=Maneuver.ICON_INDEX_ROUNDABOUT_12_LH;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_END]=Maneuver.ICON_INDEX_END;Maneuver._MANEUVER_ICON_INDEXES[aIManeuver.ICON_FERRY]=Maneuver.ICON_INDEX_FERRY},_createManeuverActionMap:function(aIManeuver){Maneuver._MANEUVER_ACTIONS=[];Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_UNDEFINED]=Maneuver.ACTION_UNDEFINED;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_NO_ACTION]=Maneuver.ACTION_NO_ACTION;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_END]=Maneuver.ACTION_END;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_STOPOVER]=Maneuver.ACTION_STOPOVER;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_JUNCTION]=Maneuver.ACTION_JUNCTION;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_ROUNDABOUT]=Maneuver.ACTION_ROUNDABOUT;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_UTURN]=Maneuver.ACTION_UTURN;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_ENTER_HIGHWAY]=Maneuver.ACTION_ENTER_HIGHWAY;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_ENTER_HIGHWAY_FROM_RIGHT]=Maneuver.ACTION_ENTER_HIGHWAY_FROM_RIGHT;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_ENTER_HIGHWAY_FROM_LEFT]=Maneuver.ACTION_ENTER_HIGHWAY_FROM_LEFT;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_PASS_JUNCTION]=Maneuver.ACTION_PASS_JUNCTION;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_LEAVE_HIGHWAY]=Maneuver.ACTION_LEAVE_HIGHWAY;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_CHANGE_HIGHWAY]=Maneuver.ACTION_CHANGE_HIGHWAY;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_CONTINUE_HIGHWAY]=Maneuver.ACTION_CONTINUE_HIGHWAY;Maneuver._MANEUVER_ACTIONS[aIManeuver.ACTION_FERRY]=Maneuver.ACTION_FERRY}});Maneuver._id=0;Maneuver.TURN_UNDEFINED="nokia.maps.pfw.turn.undefined";Maneuver.TURN_NO_TURN="nokia.maps.pfw.turn.noturn";Maneuver.TURN_KEEP_MIDDLE="nokia.maps.pfw.turn.keepmiddle";Maneuver.TURN_KEEP_RIGHT="nokia.maps.pfw.turn.keepright";Maneuver.TURN_LIGHT_RIGHT="nokia.maps.pfw.turn.lightright";Maneuver.TURN_QUITE_RIGHT="nokia.maps.pfw.turn.quiteright";Maneuver.TURN_HEAVY_RIGHT="nokia.maps.pfw.turn.heavyright";Maneuver.TURN_KEEP_LEFT="nokia.maps.pfw.turn.keepleft";Maneuver.TURN_LIGHT_LEFT="nokia.maps.pfw.turn.lightleft";Maneuver.TURN_QUITE_LEFT="nokia.maps.pfw.turn.quiteleft";Maneuver.TURN_HEAVY_LEFT="nokia.maps.pfw.turn.heavyleft";Maneuver.TURN_RETURN="nokia.maps.pfw.turn.return";Maneuver.TURN_ROUNDABOUT_1="nokia.maps.pfw.turn.roundabout1";Maneuver.TURN_ROUNDABOUT_2="nokia.maps.pfw.turn.roundabout2";Maneuver.TURN_ROUNDABOUT_3="nokia.maps.pfw.turn.roundabout3";Maneuver.TURN_ROUNDABOUT_4="nokia.maps.pfw.turn.roundabout4";Maneuver.TURN_ROUNDABOUT_5="nokia.maps.pfw.turn.roundabout5";Maneuver.TURN_ROUNDABOUT_6="nokia.maps.pfw.turn.roundabout6";Maneuver.TURN_ROUNDABOUT_7="nokia.maps.pfw.turn.roundabout7";Maneuver.TURN_ROUNDABOUT_8="nokia.maps.pfw.turn.roundabout8";Maneuver.TURN_ROUNDABOUT_9="nokia.maps.pfw.turn.roundabout9";Maneuver.TURN_ROUNDABOUT_10="nokia.maps.pfw.turn.roundabout10";Maneuver.TURN_ROUNDABOUT_11="nokia.maps.pfw.turn.roundabout11";Maneuver.TURN_ROUNDABOUT_12="nokia.maps.pfw.turn.roundabout12";Maneuver.ICON_GO_STRAIGHT="IconGoStraight";Maneuver.ICON_UNDEFINED="IconUndefined";Maneuver.ICON_UTURN_RIGHT="IconUturnRight";Maneuver.ICON_UTURN_LEFT="IconUturnLeft";Maneuver.ICON_KEEP_RIGHT="IconKeepRight";Maneuver.ICON_KEEP_LEFT="IconKeepLeft";Maneuver.ICON_LIGHT_RIGHT="IconLightRight";Maneuver.ICON_LIGHT_LEFT="IconLightLeft";Maneuver.ICON_QUITE_RIGHT="IconQuiteRight";Maneuver.ICON_QUITE_LEFT="IconQuiteLeft";Maneuver.ICON_HEAVY_RIGHT="IconHeavyRight";Maneuver.ICON_HEAVY_LEFT="IconHeavyLeft";Maneuver.ICON_ENTER_MOTORWAY_RIGHT_LANE="IconEnterMotorwayRightLane";Maneuver.ICON_ENTER_MOTORWAY_LEFT_LANE="IconEnterMotorwayLeftLane";Maneuver.ICON_LEAVE_MOTORWAY_RIGHT_LANE="IconLeaveMotorwayRightLane";Maneuver.ICON_LEAVE_MOTORWAY_LEFT_LANE="IconLeaveMotorwayLeftLane";Maneuver.ICON_MOTORWAY_KEEP_RIGHT="IconMotorwayKeepRight";Maneuver.ICON_MOTORWAY_KEEP_LEFT="IconMotorwayKeepLeft";Maneuver.ICON_ROUNDABOUT_1="IconRoundabout1";Maneuver.ICON_ROUNDABOUT_2="IconRoundabout2";Maneuver.ICON_ROUNDABOUT_3="IconRoundabout3";Maneuver.ICON_ROUNDABOUT_4="IconRoundabout4";Maneuver.ICON_ROUNDABOUT_5="IconRoundabout5";Maneuver.ICON_ROUNDABOUT_6="IconRoundabout6";Maneuver.ICON_ROUNDABOUT_7="IconRoundabout7";Maneuver.ICON_ROUNDABOUT_8="IconRoundabout8";Maneuver.ICON_ROUNDABOUT_9="IconRoundabout9";Maneuver.ICON_ROUNDABOUT_10="IconRoundabout10";Maneuver.ICON_ROUNDABOUT_11="IconRoundabout11";Maneuver.ICON_ROUNDABOUT_12="IconRoundabout12";Maneuver.ICON_ROUNDABOUT_1_LH="IconRoundabout1Lh";Maneuver.ICON_ROUNDABOUT_2_LH="IconRoundabout2Lh";Maneuver.ICON_ROUNDABOUT_3_LH="IconRoundabout3Lh";Maneuver.ICON_ROUNDABOUT_4_LH="IconRoundabout4Lh";Maneuver.ICON_ROUNDABOUT_5_LH="IconRoundabout5Lh";Maneuver.ICON_ROUNDABOUT_6_LH="IconRoundabout6Lh";Maneuver.ICON_ROUNDABOUT_7_LH="IconRoundabout7Lh";Maneuver.ICON_ROUNDABOUT_8_LH="IconRoundabout8Lh";Maneuver.ICON_ROUNDABOUT_9_LH="IconRoundabout9Lh";Maneuver.ICON_ROUNDABOUT_10_LH="IconRoundabout10Lh";Maneuver.ICON_ROUNDABOUT_11_LH="IconRoundabout11Lh";Maneuver.ICON_ROUNDABOUT_12_LH="IconRoundabout12Lh";Maneuver.ICON_END="IconEnd";Maneuver.ICON_START="IconStart";Maneuver.ICON_FERRY="IconFerry";Maneuver.ICON_INDEX_GO_STRAIGHT=0;Maneuver.ICON_INDEX_UNDEFINED=1;Maneuver.ICON_INDEX_UTURN_RIGHT=2;Maneuver.ICON_INDEX_UTURN_LEFT=3;Maneuver.ICON_INDEX_KEEP_RIGHT=4;Maneuver.ICON_INDEX_KEEP_LEFT=5;Maneuver.ICON_INDEX_LIGHT_RIGHT=6;Maneuver.ICON_INDEX_LIGHT_LEFT=7;Maneuver.ICON_INDEX_QUITE_RIGHT=8;Maneuver.ICON_INDEX_QUITE_LEFT=9;Maneuver.ICON_INDEX_HEAVY_RIGHT=10;Maneuver.ICON_INDEX_HEAVY_LEFT=11;Maneuver.ICON_INDEX_ENTER_MOTORWAY_RIGHT_LANE=14;Maneuver.ICON_INDEX_ENTER_MOTORWAY_LEFT_LANE=15;Maneuver.ICON_INDEX_LEAVE_MOTORWAY_RIGHT_LANE=16;Maneuver.ICON_INDEX_LEAVE_MOTORWAY_LEFT_LANE=17;Maneuver.ICON_INDEX_MOTORWAY_KEEP_RIGHT=20;Maneuver.ICON_INDEX_MOTORWAY_KEEP_LEFT=21;Maneuver.ICON_INDEX_ROUNDABOUT_1=22;Maneuver.ICON_INDEX_ROUNDABOUT_2=23;Maneuver.ICON_INDEX_ROUNDABOUT_3=24;Maneuver.ICON_INDEX_ROUNDABOUT_4=25;Maneuver.ICON_INDEX_ROUNDABOUT_5=26;Maneuver.ICON_INDEX_ROUNDABOUT_6=27;Maneuver.ICON_INDEX_ROUNDABOUT_7=28;Maneuver.ICON_INDEX_ROUNDABOUT_8=29;Maneuver.ICON_INDEX_ROUNDABOUT_9=30;Maneuver.ICON_INDEX_ROUNDABOUT_10=31;Maneuver.ICON_INDEX_ROUNDABOUT_11=32;Maneuver.ICON_INDEX_ROUNDABOUT_12=33;Maneuver.ICON_INDEX_ROUNDABOUT_1_LH=34;Maneuver.ICON_INDEX_ROUNDABOUT_2_LH=35;Maneuver.ICON_INDEX_ROUNDABOUT_3_LH=36;Maneuver.ICON_INDEX_ROUNDABOUT_4_LH=37;Maneuver.ICON_INDEX_ROUNDABOUT_5_LH=38;Maneuver.ICON_INDEX_ROUNDABOUT_6_LH=39;Maneuver.ICON_INDEX_ROUNDABOUT_7_LH=40;Maneuver.ICON_INDEX_ROUNDABOUT_8_LH=41;Maneuver.ICON_INDEX_ROUNDABOUT_9_LH=42;Maneuver.ICON_INDEX_ROUNDABOUT_10_LH=43;Maneuver.ICON_INDEX_ROUNDABOUT_11_LH=44;Maneuver.ICON_INDEX_ROUNDABOUT_12_LH=45;Maneuver.ICON_INDEX_END=46;Maneuver.ICON_INDEX_START=47;Maneuver.ICON_INDEX_FERRY=48;Maneuver.ACTION_UNDEFINED="nokia.maps.pfw.action.undefined";Maneuver.ACTION_NO_ACTION="nokia.maps.pfw.action.noaction";Maneuver.ACTION_END="nokia.maps.pfw.action.end";Maneuver.ACTION_STOPOVER="nokia.maps.pfw.action.stopover";Maneuver.ACTION_JUNCTION="nokia.maps.pfw.action.junction";Maneuver.ACTION_ROUNDABOUT="nokia.maps.pfw.action.roundabout";Maneuver.ACTION_UTURN="nokia.maps.pfw.action.uturn";Maneuver.ACTION_ENTER_HIGHWAY="nokia.maps.pfw.action.enterhighway";Maneuver.ACTION_ENTER_HIGHWAY_FROM_RIGHT="nokia.maps.pfw.action.enterhighwayfromright";Maneuver.ACTION_ENTER_HIGHWAY_FROM_LEFT="nokia.maps.pfw.action.enterhighwayfromleft";Maneuver.ACTION_PASS_JUNCTION="nokia.maps.pfw.action.passjunction";Maneuver.ACTION_LEAVE_HIGHWAY="nokia.maps.pfw.action.leavehighway";Maneuver.ACTION_CHANGE_HIGHWAY="nokia.maps.pfw.action.changehighway";Maneuver.ACTION_CONTINUE_HIGHWAY="nokia.maps.pfw.action.continuehighway";Maneuver.ACTION_FERRY="nokia.maps.pfw.action.ferry";Maneuver.SHOW_MANEUVER_ON_MAP="Show maneuver icon on map";Maneuver.HIDE_MANEUVER_ON_MAP="Hide maneuver icon on map";var PlacesModel=new Class({Name:"PlacesModel",Implements:EventSource,initialize:function(aMapModel){this._mapModel=aMapModel;this._places={};this._numberOfPlaces=0},_createPlace:function(aName,aCategory,aResultList,aPlaceId){var place=null;if(aResultList&&aResultList[0]){var _address={};var _position={};var first=aResultList[0];var addAddressParts=function(value,key){if(first[key]){_address[key]=first[key]}};nokia.aduno.utils.Collection.forEach(first,addAddressParts);_position.latitude=first.latitude;_position.longitude=first.longitude;place={name:aName,category:aCategory,address:_address,position:_position,id:aPlaceId}}return place},createPlaceByLocation:function(aName,aCategory,aPosition,aNonBlockingHandler,aBind){this._dummy={name:aName,category:aCategory,callback:aNonBlockingHandler,context:aBind};this._mapModel.reverseGeoCode(aPosition,this._createPlaceHandler,this)},_createPlaceHandler:function(aList){var place=null;if(aList&&this._dummy){place=this._createPlace(this._dummy.name,this._dummy.category,aList,this._numberOfPlaces++);this._places[place.id]=place}this._dummy.callback.call(this._dummy.context||this,place);delete this._dummy},createPlaceByAddress:function(aName,aCategory,aAddress,aNonBlockingHandler,aBind){this._dummy={name:aName,category:aCategory,callback:aNonBlockingHandler,context:aBind};this._mapModel.geoCode(aAddress,1,this._createPlaceHandler,this)},getPlaceById:function(aPlaceId){return(this._places[aPlaceId]||null)},getNumberOfPlaces:function(){return this._numberOfPlaces}});var SearchModel=new Class({Name:"SearchModel",Implements:[EventSource,Options],options:{resultsPerPage:5,dfwPath:"../../dfw/",resultListWidth:192},_dfwc:{},initialize:function(aAppPath,aConfiguration,aPluginControl,aNumDFW){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}var myConfiguration={rootView:90100010,suggestionView:7140000,c:this.getOption("resultsPerPage"),maxSuggestions:this.getOption("resultsPerPage"),url:"http://nsp.desktop.tst.nose.gate5.de/nsp",suggestionUrl:"http://nsp.desktop.tst.nose.gate5.de/nsp",suggestionListOn:false,dynamicSearch:true};aAppPath=aAppPath||this.getOption("dfwPath");aConfiguration=aConfiguration||myConfiguration;var aPlayerDependencies={createXmlHttpRequest:bind(aPluginControl,aPluginControl.createHttpRequest)};try{if(!aNumDFW){this._dfwc[0]=new nokia.maps.dfw.core.DiscoveryFrameworkCore(aAppPath,aConfiguration,aPlayerDependencies)}else{for(var i=0;i<aNumDFW;i++){this._dfwc[i]=new nokia.maps.dfw.core.DiscoveryFrameworkCore(aAppPath,aConfiguration,aPlayerDependencies)}}}catch(err){error("Initializing DiscoveryFrameWorkCore failed, reason: "+err);this._dfwc=null}},isReady:function(aIndex){var i=0;if(aIndex){i=aIndex}return this._dfwc&&this._dfwc[i]&&this._dfwc[i].isReady()},getDiscoveryFrameworkCore:function(aIndex){var i=0;if(aIndex){i=aIndex}return this._dfwc[i]},serialize:function(aPersistence,aIndex){var i=0;if(aIndex){i=aIndex}if(this.isReady()){aPersistence.addData("dfw_search_history",this._dfwc[i].getSearchHistory().getValue())}},deserialize:function(aPersistence,aIndex){var i=0;if(aIndex){i=aIndex}this._dfwc[i].getSearchHistory().setValue(aPersistence.getData("dfw_search_history").dfw_search_history)}});var SearchStringBuilder=new Class({initialize:function(){this._items=[]},_escape:function(aString){var str=""+aString;str=str.replace(/\&/g,"&amp;");str=str.replace(/\"/g,"&quot;");str=str.replace(/\'/g,"&apos;");str=str.replace(/\</g,"&lt;");str=str.replace(/\>/g,"&gt;");return str},setCountry:function(aCountry){this._items.country=aCountry;return this},setState:function(aState){this._items.state=aState;return this},setCity:function(aCity){this._items.city=aCity;return this},setStreet:function(aStreet){this._items.street=aStreet;return this},setHouseNumber:function(aHouseNumber){this._items.house_number=aHouseNumber;return this},setPlaceName:function(aPlaceName){this._items.place_name=aPlaceName;return this},setCategory:function(aCategory){this._items.category=aCategory;return this},setOneboxText:function(aOneBoxText){this._items.onebox_text=aOneBoxText;return this},setCityPrefix:function(aCityPrefix){this._items.city_prefix=aCityPrefix;return this},setStreetPrefix:function(aStreetPrefix){this._items.street_prefix=aStreetPrefix;return this},setGeoPosition:function(aGeoPosition){this._items.geopos=aGeoPosition.latitude+";"+aGeoPosition.longitude+";";return this},setLanguage:function(aLanguage){this._items.language=aLanguage;return this},setMaxResults:function(aCount){this._items.max_results=aCount;return this},setRadius:function(aRadius){this._items.radius=aRadius;return this},setPostCode:function(aPostCode){this._items.postal_code=aPostCode;return this},makeString:function(){var result="";for(var key in this._items){if(this._items.hasOwnProperty(key)){var value=this._items[key];result+=("<"+key+">"+this._escape(value)+"</"+key+">")}}return result+"<type>0</type>"},getOneBoxText:function(){var result="";var first=true;for(var key in this._items){if((key!="geopos")&&(key!="max_results")&&(key!="radius")){if(this._items.hasOwnProperty(key)){var value=this._items[key];if(first){first=false}else{result+=","}result+=this._escape(value)}}}return result}});var Waypoint=new Class({Name:"Waypoint",_position:null,_location:null,_address:null,_index:null,_isGpsPosition:false,initialize:function(aPosition,aLocation,aAddress){this._id=++Waypoint._id+"";if(aPosition){this._position=aPosition}if(aLocation){this._location=aLocation}else{if(aAddress){this._address=aAddress}}this._update()},getId:function(){return this._id},getAddress:function(){return this._address},getPosition:function(){return this._position},getLocation:function(){return this._location},setPosition:function(aPosition){this._position=aPosition;this._isGpsPosition=false;this._update()},setGpsPosition:function(aPosition){this._position=aPosition;this._isGpsPosition=true;this._update()},isGpsPosition:function(){return this._isGpsPosition},setLocation:function(aLocation){this._location=aLocation;this._update()},setIndex:function(aIndex){this._index=aIndex},getDescription:function(){return this._description},setDescription:function(aDescription){this._description=aDescription},getPlace:function(){return this._place},setPlace:function(aPlace){this._place=aPlace},getIndex:function(aIndex){return this._index},isReverseGeocoded:function(){if((this._location&&this._location.ADDR_STREET_NAME)||(this._place&&this._description)){return true}return false},_update:function(){this._description=this._generateDescription();this._place=this._generatePlace()},_generateDescription:function(){var address=null;if(this._location){if(this._location.PLACE_NAME){if(nokia.aduno.utils.browser.s60){address=this._location.toString()}else{if(this._location.ADDR_STREET_NAME){address=this._location.ADDR_STREET_NAME;if(this._location.ADDR_HOUSE_NUMBER!==undefined){address=address+" "+this._location.ADDR_HOUSE_NUMBER}}if(this._location.ADDR_CITY_NAME){if(adress){address=address+", "+this._location.ADDR_CITY_NAME}else{address=this._location.ADDR_CITY_NAME+(this._location.ADDR_DISTRICT_NAME?("/"+this._location.ADDR_DISTRICT_NAME):"")+" "+this._location.ADDR_POSTAL_CODE}}}}else{if(this._location.ADDR_CITY_NAME){address=this._location.ADDR_CITY_NAME+(this._location.ADDR_DISTRICT_NAME?("/"+this._location.ADDR_DISTRICT_NAME):"")+" "+this._location.ADDR_POSTAL_CODE}}}else{if(this._address){address=this._address}}return address},_generatePlace:function(){if(this._location){var text;if(this._location.PLACE_NAME){text=this._location.PLACE_NAME}else{if(this._place){text=this._place}else{text=this._location.ADDR_STREET_NAME;if(this._location.ADDR_HOUSE_NUMBER){text+=" "+this._location.ADDR_HOUSE_NUMBER}}}if(nokia.aduno.utils.browser.s60){var endText="";for(var i=0,len=text.length;i<len;i++){if(text[i]&&text.charCodeAt(i)!==0){endText+=text[i]}}return endText}else{return text}}return""}});Waypoint._id=0;var ReverseGeoCodingModel=new Class({Name:"ReverseGeoCodingModel",Implements:[EventSource,Destroyable],_finder:null,_queue:null,_currentObject:null,initialize:function(aPluginControl){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}this._pluginControl=aPluginControl;this._queue=[]},_createFinder:function(){if(this._finder){return}try{this._finder=this._pluginControl.createFinder();this._finder.setOnGeoCodeDone(bind(this,this._onReverseGeoCodeDone))}catch(ex){}},findLocation:function(aObject){this._createFinder();var entry={object:aObject};if(this._finder){entry.searchType=this._finder.SEARCH_TYPE_OFFLINE}this._queue.push(entry);if(this._queue.length===1){this._findNextObject()}},_findNextObject:function(){if(this._queue.length>0){this._createFinder();if(this._finder){var entry=this._queue[0];var position=entry.object.getPosition();var igeocoords=this._pluginControl.createGeoCoordinates(position.latitude,position.longitude);var timeout=1;if(platform.snc){timeout=75}else{if(platform.maemo){timeout=50}}var binder=this;window.setTimeout(function(){var searchType=entry.searchType;try{binder._finder.reverseGeoCode(searchType,igeocoords)}catch(ex){binder._queue.splice(0,1);if(binder._queue.length>0){binder._queue.push(entry);binder._findNextObject()}}},timeout)}}},_onReverseGeoCodeDone:function(aFinder){var entry=this._queue[0];var searchResults=aFinder.getResults();if(entry&&aFinder.getStatus()==this._finder.STATUS_OK&&searchResults.getLength()>0){this._queue.splice(0,1);var ilocation=searchResults.at(0);entry.object.setLocation(new Location(ilocation));this.fireEvent(new nokia.aduno.utils.Event(ReverseGeoCodingModel.EVENT_REVERSE_GEOCODE_DONE,entry.object))}else{if(entry.searchType===this._finder.SEARCH_TYPE_OFFLINE){entry.searchType=this._finder.SEARCH_TYPE_ONLINE}else{this._queue.splice(0,1);this.fireEvent(new nokia.aduno.utils.Event(ReverseGeoCodingModel.EVENT_REVERSE_GEOCODE_DONE,null))}}this._findNextObject()}});ReverseGeoCodingModel.EVENT_REVERSE_GEOCODE_DONE="reverse geocode done";var ApplicationModel=new Class({Name:"ApplicationModel",Implements:[EventSource],_title:"",_titlebarEnabled:true,_settingsStack:null,_visibleAreaRestrictionControls:null,_modalDialogs:null,MAEMO_VISIBLE_AREA_RESTRICTION_TOP:88,initialize:function(){this._settingsStack=[];this._visibleAreaRestrictionControls=[];this._modalDialogs={}},selectPosition:function(aTitle,aSelectedHandler,aCancelHandler,aHandlerContext,aData,aInitialPosition){this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_SELECT_POSITION,{title:aTitle,selectHandler:aSelectedHandler,cancelHandler:aCancelHandler,handlerContext:aHandlerContext,data:aData,initialPosition:aInitialPosition}))},setTitle:function(aTitle){this._title=aTitle;this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_TITLE_CHANGED,{title:aTitle}))},getTitle:function(){return this._title},setTitlebarEnabled:function(aEnable){this._titlebarEnabled=aEnable;this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_TITLEBAR_VISIBILTIY_CHANGED,{titlebarEnabled:aEnable}))},getTitlebarEnabled:function(){return this._titlebarEnabled},pushSettings:function(){this._settingsStack.push(this.getSettings())},popSettings:function(){if(this._settingsStack.length>0){var settings=this._settingsStack.pop();this.setSettings(settings)}else{}},getSettings:function(){return{title:this._title,titlebarEnabled:this._titlebarEnabled}},setSettings:function(aSettings){this.setTitle(aSettings.title);this.setTitlebarEnabled(aSettings.titlebarEnabled)},showMessageBox:function(aTitle,aText,aCloseHandler,aHandlerContext,aItems,aData){this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_SHOW_MESSAGEBOX,{title:aTitle,text:aText,handler:aCloseHandler,handlerContext:aHandlerContext,data:aData,items:aItems}))},showContextMenu:function(aItems,aSelectionHandler,aHandlerContext,aData){this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_SHOW_CONTEXT_MENU,{items:aItems,handler:aSelectionHandler,handlerContext:aHandlerContext,data:aData}))},getVisibleAreaRestriction:function(maxWidth,maxHeight){var leftRestriction=0;var topRestriction=0;var rightRestriction=0;var bottomRestriction=0;if(!nokia.maps.pfw.layout.touch&&!nokia.aduno.utils.platform.maemo){Collection.forEach(this._visibleAreaRestrictionControls,function(aControl,aKey){var element=aControl.getReplica().getRootElement();if(aControl.isVisible()){switch(aControl.restrictionPosition){case ("left"):var left=Dimensions.getPosition(element).x+Dimensions.getSize(element).x;if(left>leftRestriction){leftRestriction=left}break;case ("top"):var top=Dimensions.getPosition(element).y+Dimensions.getSize(element).y;if(top>topRestriction){topRestriction=top}break;case ("right"):var right=maxWidth-Dimensions.getPosition(element).x;if(right>rightRestriction){rightRestriction=right}break;case ("bottom"):var bottom=maxHeight-Dimensions.getPosition(element).y;if(bottom>bottomRestriction){bottomRestriction=bottom}break}}})}else{topRestriction=this.MAEMO_VISIBLE_AREA_RESTRICTION_TOP}return{left:leftRestriction,top:topRestriction,right:rightRestriction,bottom:bottomRestriction}},addVisibleAreaRestrictionControl:function(aControl,aRestriction){if(aRestriction.left){aControl.restrictionPosition="left"}else{if(aRestriction.top){aControl.restrictionPosition="top"}else{if(aRestriction.right){aControl.restrictionPosition="right"}else{if(aRestriction.bottom){aControl.restrictionPosition="bottom"}}}}this._visibleAreaRestrictionControls.push(aControl)},removeVisibleAreaRestrictionControl:function(aControlToRemove){Collection.forEach(this._visibleAreaRestrictionControls,function(aControlToRemove,aKey){if(aElement===aElementToRemove){this._visibleAreaRestrictionControls.splice(aKey,1)}})},registerModalDialog:function(aId,aImage,aLabel,aDialog,aShowInSelector){var dialogEntry={id:aId,label:aLabel,image:aImage,dialog:aDialog,showInSelector:aShowInSelector};this._modalDialogs[aId]=dialogEntry;this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_REGISTER_MODAL_DIALOG,dialogEntry))},getAllModalDialogs:function(){return this._modalDialogs},getOpenModalDialog:function(){return this._openModalDialog},switchSelectorDialog:function(aId){this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_SWITCH_SELECTOR_DIALOG,{id:aId}))},openModalDialog:function(aId){var dialog=this._modalDialogs[aId].dialog;this._openModalDialog=aId;this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_SHOW_MODAL_DIALOG,{id:aId,dialog:dialog}))},closeModalDialog:function(aId){var dialog=this._modalDialogs[aId].dialog;this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_CLOSE_MODAL_DIALOG,{id:aId,dialog:dialog}))},_onModalDialogClosed:function(aEvent){if(this._openModalDialog){var id=this._openModalDialog;this._openModalDialog=null;var dialog=this._modalDialogs[id].dialog;dialog.removeEventHandler("closed",this._onModalDialogClosed,this);this.closeModalDialog(id)}},start:function(){this.fireEvent(new nokia.aduno.utils.Event(ApplicationModel.EVENT_APPLICATION_START,null))}});ApplicationModel.EVENT_TITLE_CHANGED="titleChanged";ApplicationModel.EVENT_TITLEBAR_VISIBILTIY_CHANGED="titleBarVisibilityChanged";ApplicationModel.EVENT_SHOW_CONTEXT_MENU="showContextMenu";ApplicationModel.EVENT_SHOW_MESSAGEBOX="showMessageBox";ApplicationModel.EVENT_SELECT_POSITION="select a position";ApplicationModel.EVENT_REGISTER_MODAL_DIALOG="register modal dialog";ApplicationModel.EVENT_SHOW_MODAL_DIALOG="show modal dialog";ApplicationModel.EVENT_CLOSE_MODAL_DIALOG="close modal dialog";ApplicationModel.EVENT_APPLICATION_START="application started";ApplicationModel.EVENT_SWITCH_SELECTOR_DIALOG="switch selector dialog";var AppearanceModel=new Class({Name:"AppearanceModel",Implements:[EventSource],initialize:function(aIAppearance){this._appear=aIAppearance;if(this._appear===null){debug("no appearance got");return}this.POSITION_TOPLEFT=this._appear.POS_NW;this.POSITION_BOTTOMLEFT=this._appear.POS_SW;this.POSITION_TOPRIGHT=this._appear.POS_NE;this.POSITION_BOTTOMRIGHT=this._appear.POS_SE;this.setPosition(this.POSITION_BOTTOMRIGHT)},showMiniMap:function(){this._appear.setOverviewMapVisibility(true);return this},hideMiniMap:function(){this._appear.setOverviewMapVisibility(false);return this},setPosition:function(aPosition){switch(aPosition){case this.POSITION_TOPLEFT:case this.POSITION_BOTTOMLEFT:case this.POSITION_TOPRIGHT:case this.POSITION_BOTTOMRIGHT:this._appear.setOverviewMapPosition(aPosition);break;default:debug("AppearanceModel.setPosition: unknown position")}return this},getPosition:function(){return this._appear.getOverviewMapPosition()},getTop:function(){return this._appear.getTop()||0},getWidth:function(){return this._appear.getWidth()||0},getHeight:function(){return this._appear.getHeight()||0},getLeft:function(){return this._appear.getLeft()||0}});var PlayerTranslationVisitor=new Class({Extends:nokia.aduno.medosui.TranslationVisitor,Name:"PlayerTranslationVisitor",initialize:function(aTranslator){this._super(aTranslator)},visitContainer:function(aContainer){this._visitIterable(aContainer)},visitList:function(aList){this._visitIterable(aList)},visitComboSlider:function(aComboSlider){this._visitIterable(aComboSlider)},visitTouchDialog:function(aTouchDialog){aTouchDialog.setTitle(this._translate(aTouchDialog.getTitle()));this.visitContainer(aTouchDialog)},visitTouchRouteSummary:function(aTouchRouteSummary){this.visitContainer(aTouchRouteSummary)},visitKeyControlledList:function(aKeyControlledList){this.visitList(aKeyControlledList)},visitWaypointListItem:function(aWaypointListItem){this.visitContainer(aWaypointListItem)},visitSpiceTranslationAdapter:function(aSpiceTranslationAdapter){var children=aSpiceTranslationAdapter.getChildren();for(var i=0,c=children.length;i<c;i++){children[i].accept(this)}},visitEnableButton:function(aEnableButton){this.visitButton(aEnableButton)},_visitIterable:function(aIterable){if(aIterable._children){for(var i=0,c=aIterable._children.length;i<c;i++){aIterable._children[i].accept(this)}}}});var Units={};UNIT_METERS="__I18N_nokia.maps.pfw.unit.meter__";UNIT_YARDS="__I18N_nokia.maps.pfw.unit.yard__";UNIT_KILOMETERS="__I18N_nokia.maps.pfw.unit.kilometer__";UNIT_MILES="__I18N_nokia.maps.pfw.unit.mile__";UNIT_MILESPERHOUR="__I18N_nokia.maps.pfw.unit.milesperhour__";UNIT_KILOMETERSPERHOUR="__I18N_nokia.maps.pfw.unit.kilometersperhour__";UNIT_SECOND="__I18N_nokia.maps.pfw.unit.second__";UNIT_MINUTE="__I18N_nokia.maps.pfw.unit.minute__";UNIT_HOUR="__I18N_nokia.maps.pfw.unit.hour__";Units.getReadableDistance=function(aDistance,aUseImperialUnits){var readableDistance={value:"0",unit:""};if(aDistance===undefined||aDistance===null){return readableDistance}var distance=aDistance;if(aUseImperialUnits){var yards=distance/0.9144;if(yards===0){readableDistance.value=0;readableDistance.unit=UNIT_YARDS}else{if(yards<176){readableDistance.value=Math.ceil(yards*10)/10;readableDistance.unit=UNIT_YARDS}else{if(yards<1760){readableDistance.value=Math.ceil(yards);readableDistance.unit=UNIT_YARDS}else{if(yards<176000){readableDistance.value=Math.round(yards/176)/10;readableDistance.unit=UNIT_MILES}else{readableDistance.value=Math.round(yards/1760);readableDistance.unit=UNIT_MILES}}}}}else{if(distance===0){readableDistance.value=0;readableDistance.unit=UNIT_KILOMETERS}else{if(distance<100){readableDistance.value=Math.round(distance);readableDistance.unit=UNIT_METERS}else{if(distance<1000){readableDistance.value=Math.round(distance/10)*10;readableDistance.unit=UNIT_METERS}else{if(distance<100000){readableDistance.value=Math.round(distance/100)/10;readableDistance.unit=UNIT_KILOMETERS}else{readableDistance.value=Math.round(distance/1000);readableDistance.unit=UNIT_KILOMETERS}}}}}return readableDistance};Units.getReadableDistanceUnit=function(aUseImperialUnits){var unit="";if(aUseImperialUnits){unit=UNIT_MILES}else{unit=UNIT_KILOMETERS}return unit};Units.getReadableSpeed=function(aSpeed,aUseImperialUnits){if(!aSpeed){return""}var speed={value:"0",unit:""};if(aUseImperialUnits){speed.unit=UNIT_MILESPERHOUR;speed.value=Math.round(aSpeed*2.23693629)}else{speed.unit=UNIT_KILOMETERSPERHOUR;speed.value=Math.round(aSpeed*3.6)}return speed};Units.getReadableTime=function(aTime){var readableTime={value:"0",unit:UNIT_MINUTE};if(aTime===null||aTime===undefined){return readableTime}if(aTime===0){readableTime.value=0;readableTime.unit=UNIT_MINUTE}else{if(aTime<60){readableTime.value=aTime;readableTime.unit=UNIT_SECOND}else{if(aTime<3600){readableTime.value=Math.round(aTime/60);readableTime.unit=UNIT_MINUTE}else{var hours=Math.floor(aTime/3600);var min=Math.floor((aTime%3600)/60);if(min>0){if(min<10){readableTime.value=hours+":0"+min}else{readableTime.value=hours+":"+min}readableTime.unit=UNIT_HOUR}else{readableTime.value=hours;readableTime.unit=UNIT_HOUR}}}}return readableTime};Units.setDefaultTranslator=function(aTranslator){Units._defaultTranslator=aTranslator};Units.toString=function(aObjectWithUnit){return aObjectWithUnit.value+" "+Units._defaultTranslator.translate(aObjectWithUnit.unit)};Units.convertDecimal2Degree=function(aDecimalAngle){var deg=0;var min=0;var sec=0;if(aDecimalAngle<0){aDecimalAngle=Math.abs(aDecimalAngle)}var v=aDecimalAngle+"";var tmp=v.split(".");if(tmp[0]===""){tmp[0]="0"}deg=tmp[0];if(deg.length<2){deg="0"+deg}if(!tmp[1]){tmp[1]=0}v=parseFloat("."+tmp[1])*60+"";tmp=v.split(".");min=tmp[0];if(min.length<2){min="0"+min}if(!tmp[1]){tmp[1]=0}v=parseFloat("."+tmp[1])*60+"";tmp=v.split(".");sec=tmp[0];if(sec.length<2){sec="0"+sec}return{deg:deg,min:min,sec:sec}};Units.getReadableLatLonPosition=function(aPosition){var degSign=String.fromCharCode(176);var readablePosition="--"+degSign+"--'--\" N, --"+degSign+"--'--\" E";if(aPosition){var lat=Units.convertDecimal2Degree(aPosition.latitude);var lon=Units.convertDecimal2Degree(aPosition.longitude);var directionLat=(aPosition.latitude>=0)?"N":"S";var directionLon=(aPosition.longitude>=0)?"E":"W";readablePosition=lat.deg+degSign+lat.min+"'"+lat.sec+'" '+directionLat+", "+lon.deg+degSign+lon.min+"'"+lon.sec+'" '+directionLon}return readablePosition};var TrafficMapObject=new Class({Name:"TrafficMapObject",Extends:MapMarker,initialize:function(aIMapTrafficEvent,aPosition){this._super();this._nativeObject=aIMapTrafficEvent;this._isClickable=true;this._position={longitude:aPosition.longitude,latitude:aPosition.latitude}},setClickable:function(aClickable){aClickable=!!aClickable;if(aClickable!=this._isClickable){this._isClickable=aClickable;this.fireEvent(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,{property:"clickable",value:aClickable})}},getAffectedStreets:function(){if(this._nativeObject!==undefined&&this._nativeObject!==null){var streets=this._nativeObject.getAffectedStreets();if(streets!==null&&streets!==undefined){return streets}else{return""}}},getTrafficInfoText:function(){if(this._nativeObject!==undefined&&this._nativeObject!==null){var info=this._nativeObject.getTrafficInfoText();if(info!==null&&info!==undefined){return info}else{return""}}},getActivationDate:function(){if(this._nativeObject!==undefined&&this._nativeObject!==null){var date=this._nativeObject.getActivationDate();if(date!==null&&date!==undefined){return date}else{return""}}},getTrafficIconUrl:function(aIconType,aIconWidth,aIconHeight){if(this._nativeObject!==undefined&&this._nativeObject!==null){var type=this._nativeObject.ICON_TYPE_PNG;var width=45;var height=45;if(aIconType!==undefined&&aIconType!==null){if(aIconType==TrafficMapObject.ICON_TYPE_SVG){type=this._nativeObject.ICON_TYPE_SVG}}if(aIconWidth!==undefined&&aIconWidth!==null){width=aIconWidth}if(aIconHeight!==undefined&&aIconHeight!==null){height=aIconHeight}try{return this._nativeObject.getTrafficIconUrl(type,width,height)}catch(e){return null}}return null},getPosition:function(){return{longitude:this._position.longitude,latitude:this._position.latitude}},isSame:function(aMapObject){return(this==aMapObject)||(aMapObject.getType()=="traffic"&&aMapObject&&aMapObject._position&&aMapObject._position.latitude==this._position.latitude&&aMapObject._position.longitude==this._position.longitude)},removeFromMap:function(){},setDefaultInfoTitle:function(){}});TrafficMapObject.ICON_TYPE_PNG=0;TrafficMapObject.ICON_TYPE_SVG=1;var ReferencePrinter=new Class({initialize:function(aPage){this._page=aPage;this._printedObjects=[]},printReferences:function(aFilter){var window=null;if(this._page.getOwnerDoc().defaultView&&document.addEventListener){window=this._page.getOwnerDoc().defaultView}else{if(this._page.getOwnerDoc().parentWindow&&document.attachEvent){window=this._page.getOwnerDoc().parentWindow}}this._doPrintReferences(window,aFilter,[])},_doPrintReferences:function(aObject,aFilter,aParents,aIndentation,aName){if(!aObject){return}if(this._isAlreadyPrinted(aObject)){return}this._printedObjects.push(aObject);if(!aIndentation){aIndentation=""}if(aObject.className){var doPrint;if(aFilter){doPrint=false;for(var i2=0,len=aFilter.length;i2<len;++i2){if(aFilter[i2]==aObject.className){doPrint=true;break}}}else{doPrint=true}if(doPrint){info(aIndentation+this._getOutput(aObject,aName,aParents))}}for(var i in aObject){if(aObject.hasOwnProperty(i)){switch(type(aObject[i])){case"array":case"instance":case"object":this._doPrintReferences(aObject[i],aFilter,aObject,aIndentation+"  ",i);break;case"node":case"class":break;default:break}}}},_getOutput:function(aObject,aName,aParents){var objStr="";if(aObject.className){if(aParents){for(var i=0,len=aParents.length;i<len;++i){objStr+=aParents[i].className+">"}objStr+=": "}objStr+=aObject.className}else{return null}return aName?aName+"="+objStr:objStr},_isAlreadyPrinted:function(aObject){for(var i=0,len=this._printedObjects.length;i<len;++i){if(this._printedObjects[i]===aObject){return true}}return false}});var DeviceModel=new Class({Name:"DeviceModel",Implements:[EventSource],initialize:function(aPluginControl){var modelInstance=nokia.maps.pfw.PlayerManager.getModelInstance(aPluginControl,this.className);if(modelInstance){return modelInstance}else{nokia.maps.pfw.PlayerManager.addModelInstance(aPluginControl,this.className,this)}this._deviceManager=aPluginControl.getDeviceManager()},setDisableBacklightDimming:function(aDisabled){if(this._deviceManager){this._deviceManager.setDisableBacklightDimming(aDisabled)}},isBacklightDimmingDisabled:function(){if(this._deviceManager){return this._deviceManager.getDisableBacklightDimming()}}});var SncApplicationModel=new Class({Extends:ApplicationModel,_buttonLabels:null,_buttonbarEnabled:true,initialize:function(){this._super();this._buttonLabels={lsk:"",rsk:""}},setButtonLabels:function(aLskLabel,aRskLabel){this._buttonLabels.lsk=aLskLabel;this._buttonLabels.rsk=aRskLabel;this.fireEvent(new nokia.aduno.utils.Event(SncApplicationModel.EVENT_BUTTONS_CHANGED,{lsk:aLskLabel,rsk:aRskLabel}))},getButtonLabels:function(){return{lsk:this._buttonLabels.lsk,rsk:this._buttonLabels.rsk}},setButtonbarEnabled:function(aEnable){this._buttonbarEnabled=aEnable;this.fireEvent(new nokia.aduno.utils.Event(SncApplicationModel.EVENT_BUTTONBAR_VISIBILTIY_CHANGED,{buttonbarEnabled:aEnable}))},getButtonbarEnabled:function(){return this._buttonbarEnabled},getSettings:function(){var settings=this._super();settings.lsk=this._buttonLabels.lsk;settings.rsk=this._buttonLabels.rsk;settings.buttonbarEnabled=this._buttonbarEnabled;return settings},setSettings:function(aSettings){this._super(aSettings);this.setButtonbarEnabled(settings.buttonbarEnabled);this.setButtonLabels(aSettings.lsk,aSettings.rsk)}});SncApplicationModel.EVENT_BUTTONBAR_VISIBILTIY_CHANGED="buttonBarVisibilityChanged";SncApplicationModel.EVENT_BUTTONS_CHANGED="buttonsChanged";var TouchApplicationModel=new Class({Name:"TouchApplicationModel",Implements:[EventSource],Extends:ApplicationModel,_lastState:null,setTitlebarButton:function(aButtonHandler,aButtonHandlerContext,aButtonType){this.fireEvent(new nokia.aduno.utils.Event(TouchApplicationModel.EVENT_CHANGE_TITLEBAR_BUTTON,{handler:aButtonHandler,handlerContext:aButtonHandlerContext,buttonType:aButtonType}))},showSelector:function(aAnimation,aOpenDialogAfterAnimation){var openDialogAfterAnimation=!!aOpenDialogAfterAnimation;this.fireEvent(new nokia.aduno.utils.Event(TouchApplicationModel.EVENT_SHOW_SELECTOR,{animation:aAnimation,openDialog:openDialogAfterAnimation}))},setLastUiState:function(aState){this._lastState=aState},getLastUiState:function(){return this._lastState},setStandbyRoute:function(aRoute){this._standByRoute=aRoute},getStandbyRoute:function(){return this._standByRoute},getVisibleAreaRestriction:function(maxWidth,maxHeight){if(nokia.maps.pfw.layout.touch||nokia.aduno.utils.platform.maemo){nokia.aduno.utils.info("TouchApplicationModel.getVisibleAreaRestriction touch + maemo");return{left:20,top:108,right:60,bottom:20}}else{return this._super.getVisibleAreaRestriction(maxWidth,maxHeight)}},changeWaypointsDialogView:function(aNewView){this.fireEvent(new nokia.aduno.utils.Event(TouchApplicationModel.EVENT_WAYPOINTS_VIEW_CHANGED,{newView:aNewView}))},showContextMenu:function(){this.fireEvent(new nokia.aduno.utils.Event(TouchApplicationModel.EVENT_SHOW_CONTEXT_MENU))},configureContextMenu:function(aHeaderCaption,aHeaderSubtitle,aHeaderIcon,aItemList,aOnSelectedItemHandler,aHandlerBinder){this.fireEvent(new nokia.aduno.utils.Event(TouchApplicationModel.EVENT_CONFIGURE_CONTEXT_MENU,{onSelectedItemHandler:aOnSelectedItemHandler,handlerBinder:aHandlerBinder,headerCaption:aHeaderCaption,headerSubtitle:aHeaderSubtitle,headerIcon:aHeaderIcon,itemList:aItemList}))}});TouchApplicationModel.EVENT_SHOW_SELECTOR="show selector";TouchApplicationModel.EVENT_HIDE_SELECTOR="hide selector";TouchApplicationModel.EVENT_CHANGE_TITLEBAR_BUTTON="touchUpdateMenubar";TouchApplicationModel.EVENT_WAYPOINTS_VIEW_CHANGED="waypoints view changed";TouchApplicationModel.EVENT_SHOW_CONTEXT_MENU="show context menu";TouchApplicationModel.EVENT_CONFIGURE_CONTEXT_MENU="config context menu";TouchApplicationModel.STATE_ROUTE_SETTINGS="route settings";TouchApplicationModel.STATE_DIRECTIONS="directions";TouchApplicationModel.STATE_WAYPOINTS="waypoints";TouchApplicationModel.STATE_SELECTOR="selector";TouchApplicationModel.STATE_POSITION_SELECTION="position selection";TouchApplicationModel.STATE_MAP_VIEW="map view";TouchApplicationModel.MAEMO_VISIBLE_AREA_RESTRICTION_TOP=88;var TouchApplicationPlayer=new Class({Name:"TouchApplicationPlayer",Extends:Player,map:null,position:null,routing:null,route:null,routeSettings:null,reverseGeoCoding:null,zoom:null,guidance:null,persistence:null,application:null,connectivity:null,spiceMode:0,_createdSpices:false,_screens:null,options:{templateLibrary:null,dfwPath:"dfw/",pfwPath:"pfw/",internationalizationPath:"mapplayer/i18n",navigationPlayerInternationalizationPath:"navigationplayer/i18n",mapplayerPath:"mapplayer/",uiLanguage:"en-GB",resultsPerPage:10,sliderSteps:18,resultListWidth:192,fixedPluginSize:null,minimalSpiceSize:{x:250,y:250},debug:{console:false,consoleId:null,layerList:false},spices:{},jsPlugin:"none",maemoClickDelta:20,snapDistance:35,positionModel:null,testMode:false},ApplicationPlayerTemplateLibrary:new nokia.aduno.dom.TemplateLibrary({PluginPage:'<div class="nmm_mapPlayer"><div id="plugin"></div><div class="nmm_Spices" id="spices"><div id="TouchRouteInfoSpice"></div><div id="TouchRouteSettingsSpice"></div><div id="TouchWaypointSpice"></div><div id="TouchDirectionSpice"></div><div id="ZoomSpice"></div><div id="MaemoInfoBarSpice"></div><div id="MaemoPositionSpice"></div><div id="MaemoSettingsSpice"></div><div id="CenterCursorSpice"></div><div id="OrientationTiltSpice"></div><div id="ConsoleSpice"></div><div id="CopyrightSpice"></div><div id="TouchStartGuidanceSpice"></div><div id="NextManeuverSpice"></div><div id="GuidanceProgressSpice"></div><div id="TouchTestRouteSpice"></div></div></div>',PluginControl:'<div id="pluginControl" class="nmm_plugControl"></div>',KeyControlledList:"<div></div>"},nokia.aduno.medosui.DefaultTouchTemplateLibrary),initialize:function(aNode,aApplicationModel,aOptions){this._super(aNode,this.ApplicationPlayerTemplateLibrary,aOptions);this.application=aApplicationModel},postInitialize:function(){this._mouseEventHandling=new nokia.maps.pfw.MouseEventHandling(this._spiceManager);var language=nokia.aduno.utils.browser.language;this._spiceManager.setSpiceLanguage(language);var navPlayerResources=new nokia.aduno.i18n.ResourceManager(this.getOption("navigationPlayerInternationalizationPath"));navPlayerResources.require(language);navPlayerResources.addEventHandler("ready",function(){this._navigationPlayerTranslator=new nokia.aduno.i18n.Translator(navPlayerResources.get(language));nokia.maps.pfw.Units.setDefaultTranslator(this._navigationPlayerTranslator)},this)},postAttach:function(){this._pluginControl=this._page.getChildAt("plugin");this._mouseEventHandling.attachEventHandlers(this._pluginControl);this.map=new nokia.maps.pfw.MapModel(this._pluginControl,nokia.aduno.utils.browser.s60,this.getOption("snapDistance"));this.map.setAutoTracking(false);this.map.registerPluginHandlers(false);if(this.hasOption("positionModel")&&this.getOption("positionModel")){warn(nokia.maps);this.position=this.getOption("positionModel")}else{this.position=new nokia.maps.pfw.PositionModel(this._pluginControl)}this.position.enablePositioning();this.routing=new nokia.maps.pfw.RoutingModel(this._pluginControl,this.map,this.getOption("pfwPath"));this.routeSettings=new nokia.maps.pfw.RouteSettingsModel();this.reverseGeoCoding=new nokia.maps.pfw.ReverseGeoCodingModel(this._pluginControl);this.zoom=new nokia.maps.pfw.ZoomModel(this._pluginControl,this.map,this.getOption("sliderSteps"));this.guidance=new nokia.maps.pfw.GuidanceModel(this._pluginControl,this.routing,this.position,this.map);this.persistence=new nokia.maps.pfw.PersistenceModel(this._pluginControl);this.connectivity=new nokia.maps.pfw.ConnectivityModel(this._pluginControl);this.connectivity.registerPluginHandlers();this.connectivity.updateAccessPoints();this.device=new nokia.maps.pfw.DeviceModel(this._pluginControl);var searchConfiguration={appContextName:"rv",rootView:"where",c:this.options.resultsPerPage,maxSuggestions:this.options.resultsPerPage,url:"http://where.s2g.gate5.de/nsp",searchTermMinLength:3,dynamicSearch:true,progressIconUrl:"../../"+this.getOption("pfwPath")+"images/ui/touch/loader_30px_light.gif",categories:[{id:"where",name:"Where",icon:0}],pagesPerFetch:1};this.search=new nokia.maps.pfw.SearchModel(this.getOption("dfwPath"),searchConfiguration,this._pluginControl,1);if(this._createdSpices===false){this._createTouchSpices();this._createdSpices=true;this._mouseEventHandling.prependHandler(this.map)}this.fireEvent(TouchApplicationPlayer.ATTACH_READY)},postDetach:function(){if(this._createdSpices){this.map.unregisterPluginHandlers();this.connectivity.unregisterPluginHandlers()}this._mouseEventHandling.removeEventHandlers();this._pluginControl=null;info("player detached")},_windowUnloaded:function(aEvent){},_createTouchSpices:function(){var routeInfoSpice=new nokia.maps.pfw.spices.TouchRouteInfoSpice(this._spiceManager,this._navigationPlayerTranslator,this);var waypointSpice=new nokia.maps.pfw.spices.TouchWaypointSpice(this._spiceManager,this._navigationPlayerTranslator,this,this._page,this.getOption("pfwPath"));var directionSpice=new nokia.maps.pfw.spices.TouchDirectionSpice(this._spiceManager,this._navigationPlayerTranslator,this,this.getOption("pfwPath"));var routeSettingsSpice=new nokia.maps.pfw.spices.TouchRouteSettingsSpice(this._spiceManager,this._navigationPlayerTranslator,this,this.getOption("pfwPath"));var showRouteOnMapSpice=new nokia.maps.pfw.spices.ShowRouteOnMapSpice(this._spiceManager,this,this.getOption("pfwPath"));var positionSpice=new nokia.maps.pfw.spices.PositionSpice(this._spiceManager,this.map,this.position,this.zoom);this.addSpice(new nokia.maps.pfw.spices.TouchStartGuidanceSpice(this._spiceManager,this._navigationPlayerTranslator,this,true));this.addSpice(new nokia.maps.pfw.spices.GuidanceMapSpice(this._spiceManager,this));this.addSpice(new nokia.maps.pfw.spices.GuidanceProgressSpice(this._spiceManager,this._navigationPlayerTranslator,this));this.addSpice(new nokia.maps.pfw.spices.NextManeuverSpice(this._spiceManager,this._navigationPlayerTranslator,this));this.addSpice(showRouteOnMapSpice);this.addSpice(waypointSpice);this.addSpice(directionSpice);this.addSpice(routeInfoSpice);this.addSpice(routeSettingsSpice);this.addSpice(positionSpice);var maemoZoomSpice=new nokia.maps.pfw.spices.MaemoZoomSpice(this._spiceManager,this.map,this.zoom);this.addSpice(new nokia.maps.pfw.spices.KeyMapPanSpice(this._spiceManager,this.map));this.addSpice(new nokia.maps.pfw.spices.MouseSpice(this._spiceManager,this.map));this.addSpice(maemoZoomSpice,"ZoomSpice");this._infoBarSpice=new nokia.maps.pfw.spices.MaemoInfoBarSpice(this._spiceManager,this.map,this.zoom,this.position);this.addSpice(this._infoBarSpice);this.addSpice(new nokia.maps.pfw.spices.MaemoSettingsSpice(this._spiceManager,this.map,this.getOption("pfwPath")));this.addSpice(new nokia.maps.pfw.spices.CenterCursorSpice(this._spiceManager,this.map));this.addSpice(new nokia.maps.pfw.spices.CopyrightSpice(this._spiceManager,this.map));this.addSpice(new nokia.maps.pfw.spices.MaemoOrientationSpice(this._spiceManager,this.map,this.getOption("maemoClickDelta")),"OrientationTiltSpice");this.addSpice(new nokia.maps.pfw.spices.MaemoPositionSpice(this._spiceManager,this.map,this.position,this.zoom));var debugOptions=this.getOption("debug");if(debugOptions&&debugOptions.console){this.addSpice(new nokia.maps.pfw.spices.ConsoleSpice(this._spiceManager,debugOptions.consoleId))}this.setSpiceMode(TouchApplicationPlayer.MAP_SPICES_SHOWN);if(this.getOption("testMode")){this.addSpice(new nokia.maps.pfw.spices.TouchTestRouteSpice(this._spiceManager,this))}},setSpiceMode:function(aMode){var hideSpices,showSpices;switch(aMode){case TouchApplicationPlayer.NAVIGATION_SPICES_SHOWN:showSpices=["TouchRouteInfoSpice","TouchRouteSettingsSpice","TouchWaypointSpice","TouchDirectionSpice","ZoomSpice","ConsoleSpice","CopyrightSpice","OrientationTiltSpice","MaemoInfoBarSpice","CenterCursorSpice","PositionSpice","TouchStartGuidanceSpice","NextManeuverSpice","GuidanceProgressSpice","MaemoSettingsSpice"];if(this.getOption("testMode")){showSpices.push("TouchTestRouteSpice")}hideSpices=[];break;default:showSpices=["ZoomSpice","MaemoInfoBarSpice","MaemoSettingsSpice","CenterCursorSpice","OrientationTiltSpice","ConsoleSpice","CopyrightSpice"];hideSpices=["TouchRouteInfoSpice","TouchRouteSettingsSpice","TouchWaypointSpice","TouchDirectionSpice","PositionSpice","TouchStartGuidanceSpice","NextManeuverSpice","GuidanceProgressSpice"];if(this.getOption("testMode")){hideSpices.push("TouchTestRouteSpice")}break}this.spiceMode=aMode;var i,l;for(i=0,l=hideSpices.length;i<l;i++){this.hideGUI(hideSpices[i])}for(i=0,l=showSpices.length;i<l;i++){this.showGUI(showSpices[i])}},getInfoBar:function(){return this._infoBarSpice},getTranslator:function(){return this._navigationPlayerTranslator}});TouchApplicationPlayer.MAP_SPICES_SHOWN=1;TouchApplicationPlayer.NAVIGATION_SPICES_SHOWN=2;TouchApplicationPlayer.ATTACH_READY="attachReady";nokia.maps.pfw.addMembers({layout:layout,Serializable:Serializable,Destroyable:Destroyable,MouseEventHandler:MouseEventHandler,PluginLogger:PluginLogger,PluginControl:PluginControl,Location:Location,MapObject:MapObject,MapMarker:MapMarker,Layer:Layer,MapPolyline:MapPolyline,MapPolygon:MapPolygon,Spice:Spice,Player:Player,PlayerManager:PlayerManager,MapModel:MapModel,ZoomModel:ZoomModel,PersistenceModel:PersistenceModel,ConnectivityModel:ConnectivityModel,PositionModel:PositionModel,RoutingModel:RoutingModel,Route:Route,RouteSettingsModel:RouteSettingsModel,SpiceManager:SpiceManager,MouseEventHandling:MouseEventHandling,GuidanceModel:GuidanceModel,Maneuver:Maneuver,PlacesModel:PlacesModel,SearchModel:SearchModel,SearchStringBuilder:SearchStringBuilder,Waypoint:Waypoint,ReverseGeoCodingModel:ReverseGeoCodingModel,ApplicationModel:ApplicationModel,AppearanceModel:AppearanceModel,PlayerTranslationVisitor:PlayerTranslationVisitor,Units:Units,TrafficMapObject:TrafficMapObject,ReferencePrinter:ReferencePrinter,DeviceModel:DeviceModel,SncApplicationModel:SncApplicationModel,TouchApplicationModel:TouchApplicationModel,TouchApplicationPlayer:TouchApplicationPlayer})};new function(){new nokia.aduno.Ns("nokia.maps.dfw.utils");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;eval(nokia.aduno.utils.getImportCode());extractInteger=function(aString){var patt=/-?\d+/;var result=patt.exec(aString);if(!result){return null}else{return parseInt(result,10)}};indexOf=function(aArray,aItem){var len=aArray.length;for(var i=0;i<len;i++){if(aArray[i]===aItem){return i}}return -1};contains=function(aArray,aItem){return nokia.maps.dfw.utils.utils.indexOf(aArray,aItem)!=-1};trim=function(aString){return aString.replace(/^\s+|\s+$/g,"")};var EventController=new Class({Implements:EventSource,initialize:function(eventRegistry){this.eventRegistry=eventRegistry},addListener:function(jsObj){for(var eventKey in this.eventRegistry){if(jsObj[this.eventRegistry[eventKey]]){this.addEventHandler(this.eventRegistry[eventKey],jsObj[this.eventRegistry[eventKey]],jsObj)}}}});var StringBuilder=new Class({Name:"StringBuilder",initialize:function(){this._stringCache=[]},append:function(aValue){if(typeof(aValue)!="undefined"&&aValue!==null){this._stringCache[this._stringCache.length]=aValue}return this},injectToStart:function(aValue){if(typeof(aValue)!="undefined"&&aValue!==null){this._stringCache=[aValue,this.toString()]}return this},clear:function(){this._stringCache.length=0;return this},toString:function(){return this._stringCache.join("")}});var DFWEventConfiguration={AddressForm_SearchTriggered:"onAddressFormSearchTriggered",Category_Clicked:"onCategoryClicked",Category_Toggled:"onCategoryToggled",CategoryListBrowser_ShowAddressForm:"onCategoryListBrowserShowAddressForm",CategoryTree_CategoryHitCountsUpdated:"onCategoryTreeCategoryHitCountsUpdated",Context_CategoryChanged:"onContextCategoryChanged",Context_ToggleCategorySelected:"onContextToggleCategorySelected",Context_UnitChanged:"onContextUnitChanged",DFW_Error:"onDFWError",LocalizationManager_LocaleLoaded:"onLocalizationManagerLocaleLoaded",NSPQuery_ClearResults:"onNSPQueryClearResults",NSPQuery_InvalidAddressSearch:"onNSPQueryInvalidAddressSearch",NSPQuery_SearchStarted:"onNSPQuerySearchStarted",NSPQuery_TermCleared:"onNSPQueryTermCleared",NSPQuery_ValidAddressSearch:"onNSPQueryValidAddressSearch",NSPQueryHandler_CategoryHitCountsChanged:"onNSPQueryHandlerCategoryHitCountsChanged",NSPQueryHandler_SearchAborted:"onNSPQueryHandlerSearchAborted",NSPQueryHandler_SearchEnded:"onNSPQueryHandlerSearchEnded",NSPQueryHandler_SuggestionsUpdated:"onNSPQueryHandlerSuggestionsUpdated",NSPQueryHandler_UpdatePaging:"onNSPQueryHandlerUpdatePaging",PagingFrame_NextPage:"onPagingFrameNextPage",PagingFrame_PreviousPage:"onPagingFramePreviousPage",RefineByCategoryButton_HideCategories:"onRefineByCategoryButtonHideCategories",RefineByCategoryButton_ShowCategories:"onRefineByCategoryButtonShowCategories",ResultList_Error:"onResultListError",ResultList_NoError:"onResultListNoError",ResultList_ResultCountChanged:"onResultListResultCountChanged",ResultList_ResultItemSelected:"onResultListResultItemSelected",ResultList_ResultItemButtonClicked:"onResultListResultItemButtonClicked",ResultListDecorator_AnimationFinished:"onResultListDecoratorAnimationFinished",ResultService_NewResultsAvailable:"onResultServiceNewResultsAvailable",ResultService_ResultsCleared:"onResultServiceResultsCleared",SearchBox_ContentsCleared:"onSearchBoxContentsCleared",SearchBox_KeyUpEvent:"onSearchBoxKeyUpEvent",SearchBox_LostFocus:"onSearchBoxLostFocus",SearchBox_RequestSuggestions:"onSearchBoxRequestSuggestions",SearchBox_ResetSearchTerm:"onSearchBoxResetSearchTerm",SearchBox_SearchTermCleared:"onSearchBoxSearchTermCleared",SearchBox_SearchTriggered:"onSearchBoxSearchTriggered",SearchBox_SuggestionTriggered:"onSearchBoxSuggestionTriggered",ServiceLayer_UserLoggedIn:"onServiceLayerUserLoggedIn",ServiceLayer_UserLoggedOut:"onServiceLayerUserLoggedOut",SortingControl_SortChanged:"onSortingControlSortChanged",SuggestionList_LostFocus:"onSuggestionListLostFocus",SuggestionList_SuggestionSelected:"onSuggestionListSuggestionSelected",SuggestionList_SuggestionTriggered:"onSuggestionListSuggestionTriggered"};var Benchmark=new new Class({Name:"Benchmark",setBenchmark:function(aName){if(nokia.maps.dfw.globalConf.benchmarkingLogOn){this._items=this._items||{};this._items[aName]=this._getTime()}},getBenchmark:function(aName){if(nokia.maps.dfw.globalConf.benchmarkingLogOn){this._items=this._items||{};if(this._items[aName]){return this._getTime()-this._items[aName]}}return 0},log:function(aMessage,aName){if(nokia.maps.dfw.globalConf.benchmarkingLogOn){var mes=aMessage+this.getBenchmark(aName)+"ms";nokia.aduno.utils.info(mes);if((nokia.maps.dfw.globalConf.s60benchmarking)){nokia.maps.dfw.s60_benchmark+=mes+"\n"}}},_getTime:function(){return(new Date()).getTime()}});var TemplateLoader=function(aTemplateUrl){this._hash=null;this._templateUrl=aTemplateUrl;this.getHash=function(){if(!this._hash){this._hash=this._loadTemplate(this._templateUrl)}return this._hash};this.getJSCode=function(){var h=this.getHash();var s=[];for(var i in h){if(h.hasOwnProperty(i)){s.push("    "+i+": '"+h[i].replace(/\'/g,"\\'")+"'")}}return"{\n"+s.join(",\n")+"\n}"};this._loadTemplate=function(aTemplateUrl){var templateHash={};new nokia.aduno.Loader({uri:aTemplateUrl,async:false,bind:this,handler:function(template,success){if(!success){return}template=template.replace(/\r|\n|\r\n/g," ").replace(/\s{2,}/g," ");var v=template.match(/<!-- tmpl\.\w*?\.start -->/g);var masterRegexTemplate="<!-- tmpl\\.property\\.start .*? tmpl\\.property\\.end -->";for(var i=0;i<v.length;i++){var name=v[i].replace(/<!-- tmpl\.|\.start -->/g,""),reString=masterRegexTemplate.replace(/property/g,name),re=new RegExp(reString,"gmi"),snippet=template.match(re).toString().replace(/<!-- tmpl\.\w*?\.start --> *| *<!-- tmpl\.\w*?\.end -->/g,"");templateHash[name]=snippet}}});return templateHash}};nokia.maps.dfw.utils.addMembers({extractInteger:extractInteger,indexOf:indexOf,contains:contains,trim:trim,EventController:EventController,StringBuilder:StringBuilder,DFWEventConfiguration:DFWEventConfiguration,Benchmark:Benchmark,TemplateLoader:TemplateLoader})};new function(){new nokia.aduno.Ns("nokia.maps.dfw.core.resulttypes");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;eval(nokia.aduno.utils.getImportCode());var todo="This is an issue in namespace loading, please leave it in.";var ResultItem=new Class({Name:"ResultItem",itemType:"ResultItem"});nokia.maps.dfw.core.resulttypes.addMembers({todo:todo,ResultItem:ResultItem})};new function(){new nokia.aduno.Ns("nokia.maps.dfw.core.nspquery");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var extractInteger=nokia.maps.dfw.utils.extractInteger;var indexOf=nokia.maps.dfw.utils.indexOf;var contains=nokia.maps.dfw.utils.contains;var trim=nokia.maps.dfw.utils.trim;var EventController=nokia.maps.dfw.utils.EventController;var StringBuilder=nokia.maps.dfw.utils.StringBuilder;var DFWEventConfiguration=nokia.maps.dfw.utils.DFWEventConfiguration;var Benchmark=nokia.maps.dfw.utils.Benchmark;var TemplateLoader=nokia.maps.dfw.utils.TemplateLoader;var todo=nokia.maps.dfw.core.resulttypes.todo;var ResultItem=nokia.maps.dfw.core.resulttypes.ResultItem;eval(nokia.aduno.utils.getImportCode());eval(nokia.maps.dfw.utils.getImportCode());eval(nokia.maps.dfw.core.resulttypes.getImportCode());var todo="This is an issue in namespace loading, please leave it in.";var Parser=new Class({initialize:function(iconRepository){if(!iconRepository){throw new ArgumentError("iconRepository is required")}this._iconRepository=iconRepository},parse:null,parseSuggestions:null,_n2p:{"37":"placesId"},_getProp:function(properties,propname){var prop=properties[propname];return typeof(prop)!="undefined"?prop:""},_determineType:function(nodeView,node){var item=new ResultItem();if(this._getProp(node,this._SYN_CLASS)){item.itemType="SyncShareResultItem"}else{if(nodeView==8050000||(nodeView>=9000000&&nodeView<10000000)||nodeView==90100010){item.itemType="MapsResultItem"}else{if(nodeView>=4000000&&nodeView<5000000){item.itemType="MusicResultItem"}else{if(this._getProp(node,this._TYPE)=="place"){item.itemType="PlacesResultItem"}else{item.itemType="MapsResultItem"}}}}return item},_toCamelCase:function(str){var first=true;return str.toString().replace(/([A-Z]+)/g,function(m,l){if(first){first=false;return l.toLowerCase()}return l.substr(0,1).toUpperCase()+l.toLowerCase().substr(1,l.length)}).replace(/[\-_\s](.)/g,function(m,l){return l.toUpperCase()})},_populateItem:function(resultItem,node,validate,index,offset,firstResultIndex,categoryTree,nodeView,itemId,tagId){var propertyName;for(var i in node){if(node.hasOwnProperty(i)){propertyName=this._n2p[i];if(propertyName){resultItem[propertyName]=node[i]}else{resultItem[this._toCamelCase(i)]=node[i]}}}resultItem.streetAddress=(resultItem.streetName||resultItem.addrStreetName||"")+" "+(resultItem.houseNumber||resultItem.addrHouseNumber||"");if(!resultItem.latitude){resultItem.latitude=resultItem.geoLatitude}if(!resultItem.longitude){resultItem.longitude=resultItem.geoLongitude}if(!resultItem.distance){resultItem.distance=resultItem.geoDistance}if(!itemId||itemId=="0"){itemId="DFW"+Math.floor(1000000*Math.random())}resultItem.id=itemId;resultItem.category=categoryTree.find(nodeView)||categoryTree.getRootNode();var url;if(tagId){url=this._iconRepository.getIconByTag(tagId)}else{if(resultItem.iconId){url=this._iconRepository.getIcon(resultItem.iconId)}else{url=resultItem.category.iconUrl}}resultItem.iconUrl=url;if(validate&&(!resultItem.latitude||resultItem.latitude=="0.0")&&(!resultItem.longitude||resultItem.longitude=="0.0")){return null}else{if(resultItem.latitude){resultItem.latitude=Number(resultItem.latitude)}if(resultItem.longitude){resultItem.longitude=Number(resultItem.longitude)}}var j=function(s){var values=[];for(var i=1;i<arguments.length;i++){var v=resultItem[arguments[i]];if(v&&v!=="0"&&typeof(v)!=="undefined"){values.push(v)}}return values.join(s)};switch(resultItem.type){case"Street":resultItem.shortTitle=j(" ","addrStreetName","addrHouseNumber")+", "+j(" ","addrCityName","addrPostalNumber");resultItem.title=j(" ","addrStreetName","addrHouseNumber")+", "+j(" ","addrCityName","addrPostalCode")+", "+resultItem.addrCountryName;resultItem.row1=j(" ","addrStreetName","addrHouseNumber");resultItem.row2=j(" ","addrCityName","addrPostalCode")+", "+resultItem.addrCountryName;break;case"ZIP":resultItem.shortTitle=j(", ","addrPostalCode","addrCityName","addrCountryName");resultItem.title=j(", ","addrPostalCode","addrCityName","addrStateName","addrCountryName");resultItem.row1=resultItem.addrPostalCode;resultItem.row2=j(", ","addrCityName","addrCountryName");break;case"District":resultItem.shortTitle=j(", ","addrDistrictName","addrCityName","addrCountryName");resultItem.title=j(", ","addrDistrictName","addrCityName","addrCountryName","addrStateName","addrCountyName");resultItem.row1=resultItem.addrDistrictName;resultItem.row2=j(", ","addrCityName","addrCountryName");break;case"City":resultItem.shortTitle=j(", ","addrCityName","addrStateName","addrCountryName");resultItem.title=j(", ","addrCityName","addrCountyName","addrStateName","addrCountryName");resultItem.row1=resultItem.addrCityName;resultItem.row2=j(", ","addrStateName","addrCountryName");break;case"Township":resultItem.shortTitle=j(", ","addrTownshipName","addrStateName","addrCountryName");resultItem.title=j(", ","addrTownshipName","addrCountyName","addrStateName","addrCountryName");resultItem.row1=resultItem.addrTownshipName;resultItem.row2=j(", ","addrStateName","addrCountryName");break;case"County":resultItem.shortTitle=j(", ","addrCountyName","addrCountryName");resultItem.title=j(", ","addrCountyName","addrStateName","addrCountryName");resultItem.row1=resultItem.addrCountyName;resultItem.row2=j(", ","addrStateName","addrCountryName");break;case"State":resultItem.shortTitle=j(", ","addrStateName","addrCountryName");resultItem.title=j(", ","addrStateName","addrCountryName");resultItem.row1=resultItem.addrStateName;resultItem.row2=j(", ","addrStateName","addrCountryName");break;case"Country":resultItem.shortTitle=resultItem.addrCountryName;resultItem.title=resultItem.addrCountryName;resultItem.row1=resultItem.addrCountryName;resultItem.row2="";break;case"Other":resultItem.shortTitle=j(", ","addrAreaotherName","addrStateName","addrCountryName");resultItem.title=j(", ","addrAreaotherName","addrCountyName","addrStateName","addrCountryName");resultItem.row1=resultItem.addrAreaotherName;resultItem.row2=j(", ","addrStateName","addrCountryName");break;default:resultItem.shortTitle=resultItem.title;resultItem.title=resultItem.title;resultItem.row1=resultItem.title;resultItem.row2="";break}if(resultItem.title===", "){resultItem.title=null}return resultItem}});var XMLParser=new Class({Name:"XMLParser",Extends:Parser,parse:function(aXmlObject,extraOffset,firstResultIndex,categoryTree,selectedCategoryId){if(!aXmlObject){return{categories:[],resultItems:[]}}var offset=isNaN(extraOffset)?0:extraOffset,parsedResultItems=[],parsedCategories=[],results=aXmlObject.getElementsByTagName("results").item(0);if(results){var resultItems=results.getElementsByTagName("item"),properties,node=null;for(var n=0,resultItemIndex=0,len=resultItems.length;n<len;++n){node=resultItems.item(n);properties=this._extractProperties(node);var resultItem=this._parseResultItem(node,properties,true,resultItemIndex,offset,firstResultIndex,categoryTree,selectedCategoryId);if(resultItem){var tags=node.getElementsByTagName("tag");if(tags.length>0&&(this._getAttribute(tags.item(1),"id")==="0"||this._getAttribute(tags.item(1),"id")==="9000282")){resultItem.isSearchCenter=true}parsedResultItems.push(resultItem);++resultItemIndex}}var nodes=results.childNodes;for(var i=0;i<nodes.length;++i){node=nodes.item(i);if("view"!=node.nodeName){continue}var category=this._parseCategory(node);if(category){parsedCategories.push(category)}}}return{categories:parsedCategories,resultItems:parsedResultItems}},parseSuggestions:function(aXmlObject,maxSuggestions,categoryTree,selectedCategoryId){if(!aXmlObject||(aXmlObject.parsed===false)||!aXmlObject.getElementsByTagName("results")||!aXmlObject.getElementsByTagName("results").item(0)){return{term:[],direct:[],didYouMean:[]}}var suggestions=aXmlObject.getElementsByTagName("results").item(0).getElementsByTagName("item"),termSuggestions=[],directSuggestions=[],didYouMeanSuggestions=[];if(suggestions){var node=null,resultItem,suggestionType,suggestionText,len=Math.min(suggestions.length,maxSuggestions),properties;for(var n=0;n<len;n++){node=suggestions.item(n);properties=this._extractProperties(node);if(properties.TITLE){suggestionText=properties.TITLE}else{if(properties.ADDR_STREET_NAME){suggestionText=properties.ADDR_STREET_NAME}}resultItem=this._parseResultItem(node,properties,false,0,0,0,categoryTree,selectedCategoryId);suggestionType=(resultItem&&resultItem.latitude)?"direct":"term";switch(suggestionType){case"term":termSuggestions[termSuggestions.length]={suggestionType:suggestionType,suggestionText:suggestionText,resultItem:null};break;case"direct":directSuggestions[directSuggestions.length]={suggestionType:suggestionType,suggestionText:suggestionText,resultItem:resultItem};break;case"didYouMean":didYouMeanSuggestions[didYouMeanSuggestions.length]={suggestionType:suggestionType,suggestionText:suggestionText,resultItem:null};break;default:nokia.aduno.utils.info("XMLParser: unknown suggestion type: "+suggestionType);break}}}return{term:termSuggestions,direct:directSuggestions,didYouMean:didYouMeanSuggestions}},_parseResultItem:function(node,properties,validate,index,offset,firstResultIndex,categoryTree,selectedCategoryId){var itemId=node.getAttribute("id"),resultItem,nodeView,tagId;nodeView=this._getAttribute(node.getElementsByTagName("view").item(0),"id");if(typeof(nodeView)=="undefined"||!nodeView){nodeView=selectedCategoryId}resultItem=this._determineType(this._getAttribute(node.getElementsByTagName("view").item(0),"id"),properties);tagId=this._getAttribute(node.getElementsByTagName("tag").item(0),"id");return this._populateItem(resultItem,properties,validate,index,offset,firstResultIndex,categoryTree,nodeView,itemId,tagId)},_parseCategory:function(node){var categoryId=this._getAttribute(node,"id"),hitCount=parseInt(this._getAttribute(node,"hitcount"),10),hitCountExceeded=this._getAttribute(node,"hitcountExceeded");hitCount=(hitCountExceeded&&!hitCount)?999999:hitCount;return{id:categoryId,hitcount:hitCount,hitcountExceeded:hitCountExceeded}},_extractProperties:function(node){var properties={},propertyNodes=node.getElementsByTagName("property"),resultItem;for(var i=0,len=propertyNodes.length;i<len;++i){var propertyNode=propertyNodes.item(i),name=this._getAttribute(propertyNode,"name");if(name){properties[name]=this._getNodeValue(propertyNode)}}return properties},_getNodeValue:function(node){return node&&node.firstChild&&node.firstChild.nodeValue||null},_getAttribute:function(parentNode,attributeName){return parentNode?parentNode.getAttribute(attributeName):null}});var NSPQueryHandlerError=new Class({initialize:function(message){Error.call(this,message);this.message=message;this.name="NSPQueryHandlerError"},toString:function(){return this.name+': "'+this.message+'"'}});var ResultCache=new Class({initialize:function(conf){this._useCache=conf.useCache},_cachedObjects:null,_useCache:false,_numberOfCachedObjects:0,put:function(aKey,aObject){if(this._useCache&&aKey&&aObject){if(!this._cachedObjects){this._cachedObjects={}}this._cachedObjects[aKey]=aObject;this._numberOfCachedObjects++;return true}return false},get:function(aKey){if(this._useCache&&this._cachedObjects&&this._cachedObjects[aKey]){return this._cachedObjects[aKey]}return null},getObjectCount:function(){return this._numberOfCachedObjects},getAll:function(){if(this._useCache){return this._cachedObjects||(this._cachedObjects={})}return null}});var ResultCacheItem=new Class({initialize:function(conf){this._resultLimit=conf.resultLimit},_categories:null,_resultItems:null,_incomplete:false,_resultLimit:100,hasResultItems:function(aOffset,aCount){return((this._resultItems&&this._resultItems[aOffset])&&(this._incomplete||this._resultItems[aOffset+aCount-1]))?true:false},getSelectedResultItems:function(aOffset,aCount){if(this._resultItems){return this._resultItems.slice(aOffset,aOffset+aCount)}return[]},getCategories:function(){return this._categories},setSelectedResultItems:function(aResultItemArray,aOffset,aCount){var i,len=aResultItemArray.length;if(!this._resultItems){this._resultItems=[]}for(i=0;i<len;i++){this._resultItems[aOffset+i]=aResultItemArray[i]}if(aResultItemArray.length<aCount){this._incomplete=true}},setCategories:function(aCategoryArray){this._categories=aCategoryArray},hasMorePages:function(aOffset,itemsPerPage){return(aOffset+itemsPerPage<this._resultLimit)&&this._resultItems&&(this._resultItems.length>aOffset+itemsPerPage)}});var NSPQueryHandler=new Class({Name:"NSQPQueryHandler",initialize:function(eventController,context,resultService,categoryTree,iconRepository,searchHistory,conf){if(!eventController){throw new ArgumentError("eventController is required")}if(!context){throw new ArgumentError("context is required")}if(!resultService){throw new ArgumentError("resultService is required")}if(!categoryTree){throw new ArgumentError("categoryTree is required")}if(!iconRepository){throw new ArgumentError("iconRepository is required")}if(!searchHistory){throw new ArgumentError("searchHistory is required")}if(!conf){throw new ArgumentError("conf is required")}this._parser=new XMLParser(iconRepository);this._context=context;this._resultService=resultService;this._eventController=eventController;this._categoryTree=categoryTree;this._searchHistory=searchHistory;this._loaders=[];this._conf=conf},fetch:function(aSearchUrl,aManualSearch,aStartOffset,aItemCount,aPageIndex,aCacheKey){var resultCacheItem=this._resultService.findFromCache(aCacheKey);if(resultCacheItem&&resultCacheItem.hasResultItems(aStartOffset,aItemCount)){this._fetchResultsFromCache(aManualSearch,aStartOffset,aItemCount,aPageIndex,resultCacheItem);return}try{this._fetchResultsFromServer(aSearchUrl,aManualSearch,aStartOffset,aItemCount,aPageIndex,aCacheKey,resultCacheItem);return}catch(e){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.DFW_Error,{message:"Failed to execute search!",error:e}))}},fetchSuggestions:function(aSearchUrl,aTerm){var callback=function(value,success){if(!success){this._serverError(aSearchUrl,success);return}var suggestions=this._parser.parseSuggestions(value,this._conf.maxSuggestions,this._categoryTree,this._context.selectedCategory.categoryId);suggestions.searchHistory=this._searchHistory.getSuggestions(aTerm);this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQueryHandler_SuggestionsUpdated,{suggestingFor:aTerm,suggestions:suggestions}))};this._loaders.push(new nokia.aduno.Loader({uri:aSearchUrl,async:true,type:this._conf.dataFormat,bind:this,handler:callback,xmlHttpRequest:nokia.maps.dfw.core.createXmlHttpRequest()}))},getHasMorePages:function(aResultItemCount,aStartOffset,aItemCount){if(aStartOffset+aItemCount<this._conf.resultLimit){return(aResultItemCount>aItemCount)}return false},abortAllXhr:function(){var requestAborted=false;for(var i=0;i<this._loaders.length;i++){this._loaders[i]._loadHandlers=[];this._loaders[i].abort();requestAborted=true}if(requestAborted){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQueryHandler_SearchAborted))}this._loaders=[]},_fetchResultsFromServer:function(aSearchUrl,aManualSearch,aStartOffset,aItemCount,aPageIndex,aCacheKey,aResultCacheItem){var callback=function(value,success){if(!success){this._serverError(aSearchUrl,aManualSearch);return}var parsedResults=this._parser.parse(value,0,aStartOffset,this._categoryTree,this._context.selectedCategory.categoryId);var resultItems=this._limitResultCount(parsedResults.resultItems,aItemCount);var categories=parsedResults.categories;this._resultService.setResultsToCache(resultItems,categories,aStartOffset,aItemCount,aCacheKey,aResultCacheItem);var hasMorePages=this.getHasMorePages(resultItems.length,aStartOffset,aItemCount);if(hasMorePages){this._resultService.setResults(resultItems.slice(0,aItemCount),categories,aPageIndex,hasMorePages,aManualSearch)}else{this._resultService.setResults(resultItems,categories,aPageIndex,hasMorePages,aManualSearch)}};this._loaders.push(new nokia.aduno.Loader({uri:aSearchUrl,async:true,bind:this,type:this._conf.dataFormat,handler:callback,xmlHttpRequest:nokia.maps.dfw.core.createXmlHttpRequest()}))},_fetchResultsFromCache:function(aManualSearch,aStartOffset,aItemCount,aPageIndex,aResultCacheItem){Benchmark.setBenchmark("resultTime");var results=aResultCacheItem.getSelectedResultItems(aStartOffset,aItemCount);var hasMorePages=aResultCacheItem.hasMorePages(aStartOffset,aItemCount);this._resultService.setResults(results,aResultCacheItem.getCategories(),aPageIndex,hasMorePages,aManualSearch)},_serverError:function(aUrl,aManualSearch){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQueryHandler_SearchEnded,{manual:aManualSearch}));var e=new NSPQueryHandlerError("HTTP request failed! URL: '"+aUrl+"'");this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.DFW_Error,{message:"Error in callback!",error:e}))},_limitResultCount:function(resultItems,aItemCount){var categorySilos={},i,len,item,categoryId,categoryCount,targetCount,excess,limited={},categoryIds=[],result=[];len=resultItems.length;for(i=0;i<len;i++){item=resultItems[i];categoryId=item.category.categoryId;if(!categorySilos[categoryId]){categorySilos[categoryId]=[];limited[categoryId]=0;categoryIds.push(categoryId)}categorySilos[categoryId].push(item)}categoryCount=categoryIds.length;excess=aItemCount%categoryCount;targetCount=(aItemCount-excess)/categoryCount;for(categoryId in categorySilos){if(categorySilos.hasOwnProperty(categoryId)){len=categorySilos[categoryId].length;if(len>targetCount){limited[categoryId]=targetCount}else{limited[categoryId]=len;excess+=targetCount-len}}}for(i=0;i<excess;i++){limited[categoryIds[i%categoryCount]]++}for(i=0;i<categoryCount;i++){result=result.concat(categorySilos[categoryIds[i]].slice(0,limited[categoryIds[i]]))}return result}});var JSON=new Class({f:function(n){return n<10?"0"+n:n},initialize:function(){if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(key){return this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z"};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}},cx:/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapeable:/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap:null,indent:null,meta:{"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep:null,quote:function(string){this.escapeable.lastIndex=0;return this.escapeable.test(string)?'"'+string.replace(this.escapeable,function(a){var c=this.meta[a];if(typeof c==="string"){return c}return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'},str:function(key,holder){var i,k,v,length,mind=this.gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof this.rep==="function"){value=this.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"}this.gap+=this.indent;partial=[];if(typeof value.length==="number"&&!value.propertyIsEnumerable("length")){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":this.gap?"[\n"+this.gap+partial.join(",\n"+this.gap)+"\n"+mind+"]":"["+partial.join(",")+"]";this.gap=mind;return v}if(this.rep&&typeof this.rep==="object"){length=this.rep.length;for(i=0;i<length;i+=1){k=this.rep[i];if(typeof k==="string"){v=str(k,value);if(v){partial.push(quote(k)+(this.gap?": ":":")+v)}}}}else{for(k in value){if(Object.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(this.gap?": ":":")+v)}}}}v=partial.length===0?"{}":this.gap?"{\n"+this.gap+partial.join(",\n"+this.gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";this.gap=mind;return v;default:return null}},stringify:function(value,replacer,space){var i;this.gap="";this.indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){this.indent+=" "}}else{if(typeof space==="string"){this.indent=space}}this.rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})},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)}this.cx.lastIndex=0;if(this.cx.test(text)){text=text.replace(this.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")}});var ResultService=new Class({initialize:function(eventController,conf){if(!eventController){throw new ArgumentError("eventController is required")}if(!conf){throw new ArgumentError("conf is required")}this._eventController=eventController;this._conf=conf;this._eventController.addListener(this)},_results:null,_cache:null,find:function(aItemId){for(var i=0,thisSize=this._getSize();i<thisSize;++i){if(this._results[i] instanceof ResultItem){if(this._results[i].id==aItemId){return this._results[i]}}}return null},get:function(aIndex){if(typeof(aIndex)!="undefined"&&aIndex>=0&&this._getSize()>aIndex){return this._results[aIndex]}return null},setResults:function(aResultArray,aCategoryArray,aPageIndex,aHasMorePages,aManualSearch){this._results=aResultArray;this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQueryHandler_CategoryHitCountsChanged,{hitCounts:aCategoryArray}));this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.ResultService_NewResultsAvailable,{results:this._results}));this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQueryHandler_SearchEnded,{manual:aManualSearch}));this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQueryHandler_UpdatePaging,{currentPage:aPageIndex,hasMorePages:aHasMorePages,resultCount:this._getSize()}))},getResults:function(){return this._results},clearResults:function(){if(!this._results){return false}this._results=null;this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.ResultService_ResultsCleared,{nonBlockable:true}));return true},setResultsToCache:function(aResultArray,aCategoryArray,aStartOffset,aItemCount,aCacheKey,aResultCacheItem){if(aResultArray&&aResultArray.length>0){if(!aResultCacheItem){aResultCacheItem=new ResultCacheItem(this._conf)}aResultCacheItem.setSelectedResultItems(aResultArray,aStartOffset,aItemCount);aResultCacheItem.setCategories(aCategoryArray);return this._putToCache(aCacheKey,aResultCacheItem)}},findFromCache:function(aKey){if(this._cache){return this._cache.get(aKey)}return null},_getSize:function(){if(this._results&&this._results.length){return this._results.length}return 0},_putToCache:function(aKey,aItem){if(!this._cache){this._cache=new ResultCache(this._conf)}return this._cache.put(aKey,aItem)},_suggestionTriggered:function(params){if(params.suggestionItem.suggestionType==="direct"){this.setResults([params.suggestionItem.resultItem])}},onSearchBoxSearchTermCleared:function(){this.clearResults()},onNSPQueryClearResults:function(){this.clearResults()},onSearchBoxSuggestionTriggered:function(aEvent){this._suggestionTriggered(aEvent.getData())},onSuggestionListSuggestionTriggered:function(aEvent){this._suggestionTriggered(aEvent.getData())}});var SearchHistory=new Class({initialize:function(persistentValue){this.persistentValue=persistentValue||"[]"},getValue:function(){return this.persistentValue},setValue:function(value){this.persistentValue=value},add:function(searchTerm){var history=this._getHistory();searchTerm=encodeURIComponent(searchTerm);if(Collection.none(history,searchTerm)){history.push(searchTerm)}this.persistentValue='["'+history.join('","')+'"]'},getValues:function(searchTerm){var history=this._getHistory(),len=searchTerm.length;return Collection.filter(history,function(aValue){if(aValue.length>=len&&aValue.toLowerCase().substring(0,len)===searchTerm.toLowerCase()){return true}return false},this)},getSuggestions:function(searchTerm){searchTerm=encodeURIComponent(searchTerm);return Collection.map(this.getValues(searchTerm),function(aValue){return{suggestionType:"searchHistory",suggestionText:decodeURIComponent(aValue),resultItem:null}},this)},_getHistory:function(){var history=[];if(typeof(this.persistentValue)==="string"){history=nokia.maps.dfw.core.evaluate(this.persistentValue)}return history}});nokia.maps.dfw.core.nspquery.addMembers({todo:todo,Parser:Parser,XMLParser:XMLParser,NSPQueryHandlerError:NSPQueryHandlerError,ResultCache:ResultCache,ResultCacheItem:ResultCacheItem,NSPQueryHandler:NSPQueryHandler,JSON:JSON,ResultService:ResultService,SearchHistory:SearchHistory})};new function(){new nokia.aduno.Ns("nokia.maps.dfw.core.nspquerysender");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var extractInteger=nokia.maps.dfw.utils.extractInteger;var indexOf=nokia.maps.dfw.utils.indexOf;var contains=nokia.maps.dfw.utils.contains;var trim=nokia.maps.dfw.utils.trim;var EventController=nokia.maps.dfw.utils.EventController;var StringBuilder=nokia.maps.dfw.utils.StringBuilder;var DFWEventConfiguration=nokia.maps.dfw.utils.DFWEventConfiguration;var Benchmark=nokia.maps.dfw.utils.Benchmark;var TemplateLoader=nokia.maps.dfw.utils.TemplateLoader;eval(nokia.aduno.utils.getImportCode());eval(nokia.maps.dfw.utils.getImportCode());var todo="This is an issue in namespace loading, please leave it in.";var QueryParamHandler=new Class({Name:"QueryParamHandler",initialize:function(context,conf){this.term="";this.firstResult=1;this.itemCount=conf.c;this.otherParams={};this._context=context;this._conf=conf;this.publicationId=null;this.ensurePublicationId()},isTermActive:function(){return this.term&&this.term.length&&this.term.length>0},reset:function(){this.term="";this.firstResult=1},clearTerm:function(){this.term=""},getCurrentPage:function(){return Math.floor(this.firstResult/this.itemCount)+1},getFetchCount:function(){var pagesPerFetch=1;if(this._conf&&this._conf.pagesPerFetch){pagesPerFetch=this._conf.pagesPerFetch}return(this.itemCount*pagesPerFetch)+1},getSearchURL:function(extraOffset){var firstRes=this.firstResult-1,urlBuilder=new StringBuilder();if(extraOffset&&!isNaN(extraOffset)){firstRes+=extraOffset}this.ensurePublicationId();urlBuilder.append(this._getBasicURL(this._conf.url,this.getViewIdString())).append("&to=").append(this.getFetchCount()).append("&of=").append(firstRes);if(this._conf.appContextName.length>0){urlBuilder.append("&dv=").append(this._conf.appContextName)}urlBuilder.append(this._getCommonParameters(this.term));return urlBuilder.toString()},getSuggestionURL:function(aTerm){var urlBuilder=new StringBuilder();urlBuilder.append(this._getBasicURL(this._conf.suggestionUrl,this._conf.suggestionView)).append(this._getCommonParameters(aTerm));return urlBuilder.toString()},_getBasicURL:function(url,viewId){var urlBuilder=new StringBuilder();urlBuilder.append(url);if(url.indexOf("?")<0){urlBuilder.append("?")}else{urlBuilder.append("&")}urlBuilder.append("vi=").append(viewId);return urlBuilder.toString()},_getCommonParameters:function(aTerm){var urlBuilder=new StringBuilder();if(this._conf.languageInSearch){if(this._context.currentLocaleCode.length>0){urlBuilder.append("&la=").append(this._context.currentLocaleCode)}else{urlBuilder.append("&la=en")}}urlBuilder.append("&q=").append(encodeURIComponent(aTerm)).append("&lat=").append(this.otherParams.lat||this.otherParams.lat===0?this.otherParams.lat:"").append("&lon=").append(this.otherParams.lon||this.otherParams.lon===0?this.otherParams.lon:"").append("&fo=1&re=1");if(this.otherParams.loc!==undefined){urlBuilder.append("&loc=").append(this.otherParams.loc)}if(this.otherParams.tpv!==undefined){urlBuilder.append("&tpv=").append(this.otherParams.tpv)}return urlBuilder.toString()},getCacheKey:function(){var keyBuilder=new StringBuilder();keyBuilder.append(this.getViewIdString()).append("&").append(this.itemCount).append("&").append(this.term).append("&").append(this.otherParams.lat?this.otherParams.lat:"").append("&").append(this.otherParams.lon?this.otherParams.lon:"").append("&").append(this._context.currentLocaleCode).append("&").append(this._context.sort);return keyBuilder.toString()},getViewIdString:function(){return this.getCategoryIds().join(",")},getCategoryIds:function(){var categories=[],len;if(this._conf.categoryMode==="browsing"){categories.push(this.publicationId)}else{if(this._conf.categoryMode==="selecting"){len=this._context.selectedCategories.length;if(len<=0){categories.push(this.publicationId)}else{for(var i=0;i<len;i++){categories.push(this._context.selectedCategories[i].categoryId)}}}else{if(this._conf.categoryMode==="predefined"){if(this.publicationId!=="0"){categories.push(this.publicationId)}else{len=this._conf.categories.length;for(i=0;i<len;i++){if(this._conf.categories[i].id!=="0"){categories.push(this._conf.categories[i].id)}}}}else{nokia.aduno.utils.error("Invalid category mode.")}}}return categories},pageUp:function(){this.firstResult+=this.itemCount;this.firstResult-=(this.firstResult-1)%this.itemCount},pageDown:function(){if(this.firstResult<=1){nokia.aduno.utils.info("nokia.maps.dfw.core.NSPQuerySender.pageDown(): paging mixed up.");return false}this.firstResult-=this.itemCount;this.firstResult-=(this.firstResult-1)%this.itemCount;if(this.firstResult<=1){this.firstResult=1}},ensurePublicationId:function(){var selected=this._context.selectedCategory;if(selected){this.publicationId=selected.categoryId}else{nokia.aduno.utils.error("NSPQuery: ensurePublicationId was called but publicationId was not set properly!")}},getCategoryCount:function(){return this.getCategoryIds().length}});var NSPQuery=new Class({Name:"NSPQuery",initialize:function(eventController,context,nspQueryHandler,categoryTree,searchHistory,conf){if(!eventController){throw new ArgumentError("eventController is required")}if(!context){throw new ArgumentError("context is required")}if(!nspQueryHandler){throw new ArgumentError("nspQueryHandler is required")}if(!categoryTree){throw new ArgumentError("categoryTree is required")}if(!searchHistory){throw new ArgumentError("searchHistory is required")}this.queryParams=new QueryParamHandler(context,conf);this._context=context;this._eventController=eventController;this._eventController.addListener(this);this._nspQueryHandler=nspQueryHandler;this._searchHistory=searchHistory;this._conf=conf},executeSearch:function(aManualSearch){this._nspQueryHandler.abortAllXhr();this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQuery_SearchStarted,{nonBlockable:true}));this._searchHistory.add(this.queryParams.term);this._nspQueryHandler.fetch(this.queryParams.getSearchURL(),aManualSearch||false,this.queryParams.firstResult,this.queryParams.itemCount,this.queryParams.getCurrentPage(),this.queryParams.getCacheKey(),this.queryParams.getCategoryCount())},executeSuggestionSearch:function(aTerm){this._nspQueryHandler.abortAllXhr();this._nspQueryHandler.fetchSuggestions(this.queryParams.getSuggestionURL(aTerm),aTerm)},executeAddressSearch:function(aCountry,aCity,aStreet,aHouseNumber){if((!aCountry)||(!aCity)){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQuery_InvalidAddressSearch));return}var addressBuilder=new StringBuilder();addressBuilder.append(aCountry).append(" ").append(aCity).append(" ").append(aStreet).append(" ").append(aHouseNumber);var addressString=trim(addressBuilder.toString());this.queryParams.term=addressString;this.queryParams.firstResult=1;this.queryParams.itemCount=this._conf.cWhenInLeafNode;this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQuery_ValidAddressSearch,{addressString:addressString}));this.executeSearch()},isTermActive:function(){return this.queryParams.isTermActive()},getTerm:function(){return this.queryParams.term},_clearTerm:function(){this.queryParams.clearTerm();this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQuery_TermCleared))},onSearchBoxSearchTriggered:function(aEvent){var params=aEvent.getData();this.queryParams.term=params.searchTerm;this.queryParams.firstResult=1;this.executeSearch(params.manual)},onSearchBoxResetSearchTerm:function(){this._clearTerm()},onSearchBoxContentsCleared:function(){this._clearTerm()},onContextCategoryChanged:function(){this.queryParams.firstResult=1;if(this._context.selectedCategory.isLeaf()||this.isTermActive()){this.executeSearch()}else{this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.NSPQuery_ClearResults))}},onResultServiceResultsCleared:function(){var selectedCat=this._context.selectedCategory;if(!selectedCat.isRoot()&&selectedCat.isLeaf()){this.executeSearch()}},onPagingFramePreviousPage:function(){this.queryParams.pageDown();this.executeSearch()},onPagingFrameNextPage:function(){this.queryParams.pageUp();this.executeSearch()},onAddressFormSearchTriggered:function(aEvent){var params=aEvent.getData();this.executeAddressSearch(params.country,params.city,params.street,params.number)},onSearchBoxRequestSuggestions:function(aEvent){this.executeSuggestionSearch(aEvent.getData().query)},onLocalizationManagerLocaleLoaded:function(){if((!this._context.selectedCategory.isRoot()&&this._context.selectedCategory.isLeaf())||this.isTermActive()){this.executeSearch()}},onContextToggleCategorySelected:function(){if((!this._conf.fetchOnCategoryToggle)||(!this.isTermActive())){return}var categoryToggledFunction=function(){nokia.aduno.utils.info("NSPQuery: categoryToggleFunction");delete this._fetchOnCategoryToggle;this.executeSearch()};cancelTimer(this._fetchOnCategoryToggle);this._fetchOnCategoryToggle=setTimer(4*this._conf.searchExecutionDelay,this,categoryToggledFunction)},onSortingControlSortChanged:function(){if(this._context.selectedCategory.isLeaf()||this.isTermActive()){this.executeSearch()}}});var SearchHelper=new Class({Name:"SearchHelper",Implements:EventSource,initialize:function(eventController,context,nspQuery,conf,searchHistory){if(!eventController){throw new ArgumentError("eventController is required")}if(!context){throw new ArgumentError("context is required")}if(!nspQuery){throw new ArgumentError("nspQuery is required")}if(!conf){throw new ArgumentError("conf is required")}this._conf=conf;this.lat=50;this.lon=50;this.term="";this.firstResult=1;this.itemCount=this._conf.c;this._context=context;this.category=this._context.selectedCategory;this._eventController=eventController;this._eventController.addListener(this);this._nspQuery=nspQuery;this._searchHistory=searchHistory;this._localSuggestions=[];this._loadCategoryNames()},onResultServiceNewResultsAvailable:function(aEvent){var data=aEvent.getData();var params={};params.results=data.results;this.fireEvent(new Event("NewResultsAvailable",params))},onNSPQueryHandlerCategoryHitCountsChanged:function(){this.fireEvent(new Event("CategoryHitCountsChanged"))},onNSPQueryHandlerUpdatePaging:function(aEvent){var data=aEvent.getData();var params={};params.currentPage=data.currentPage;params.hasMorePages=data.hasMorePages;params.resultCount=data.resultCount;this.fireEvent(new Event("PageCountChanged",params))},onDFWError:function(aEvent){var data=aEvent.getData();var params={};params.message=data.message;params.error=data.error;this.fireEvent(new Event("Error",params))},onLocalizationManagerLocaleLoaded:function(){this._loadCategoryNames()},_loadCategoryNames:function(){var cats=[],loc=this._context.locale;if(loc){for(var i=1;loc["sc"+i];i++){cats.push(loc["sc"+i])}}this._categoryNames=cats},search:function(aTerm,aCategory,firstResult,itemCount,aLatitude,aLongitude,aTotalPerView){this.term=aTerm;if(aCategory&&aCategory.length){this._context.selectedCategories=aCategory}else{this._context.selectedCategory=aCategory}this.firstResult=firstResult;this.itemCount=itemCount;this.lat=aLatitude;this.lon=aLongitude;this.totalPerView=aTotalPerView;this._searchHistory.add(aTerm);this._execute()},getSelectedCategory:function(){return this._context.selectedCategory},nextPage:function(){this.firstResult+=this.itemCount;this._execute()},previousPage:function(){this.firstResult-=this.itemCount;this._execute()},fetchSuggestions:function(aTerm){var terms=this._categoryNames,len=aTerm.length,lowerTerm=aTerm.toLowerCase();function toSuggestion(anArray,aType){return Collection.map(anArray,function(aValue){return{type:aType,value:aValue}})}function filterSuggestions(aValue){if(aValue.length>=len&&aValue.toLowerCase().substring(0,len)===lowerTerm){return true}return false}var categorySuggestions=toSuggestion(Collection.filter(terms,filterSuggestions),"category");var historySuggestions=toSuggestion(Collection.map(this._searchHistory.getValues(aTerm),function(aValue){return decodeURIComponent(aValue)}),"history");var localSuggestion=toSuggestion(Collection.filter(this._localSuggestions,filterSuggestions),"localSuggestion");return Collection.merge(Collection.merge(categorySuggestions,historySuggestions),localSuggestion)},_execute:function(){this._nspQuery.queryParams.term=this.term;this._nspQuery.queryParams.firstResult=this.firstResult;this._nspQuery.queryParams.itemCount=this.itemCount;this._nspQuery.queryParams.otherParams.lat=this.lat;this._nspQuery.queryParams.otherParams.lon=this.lon;this._nspQuery.queryParams.otherParams.tpv=this.totalPerView;this._nspQuery.executeSearch()},getPersistenceValue:function(){return this._searchHistory.getValue()},setPersistenceValue:function(aPersistenceValue){this._searchHistory.setValue(aPersistenceValue)},setLocalSuggestions:function(aArray){this._localSuggestions=aArray||[]},addLocalSuggestions:function(aArray){this._localSuggestions=this._localSuggestions.concat(aArray)},abortSearch:function(aArray){this._nspQuery._nspQueryHandler.abortAllXhr()}});nokia.maps.dfw.core.nspquerysender.addMembers({todo:todo,NSPQuery:NSPQuery,SearchHelper:SearchHelper})};new function(){new nokia.aduno.Ns("nokia.maps.dfw.core.context");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var extractInteger=nokia.maps.dfw.utils.extractInteger;var indexOf=nokia.maps.dfw.utils.indexOf;var contains=nokia.maps.dfw.utils.contains;var trim=nokia.maps.dfw.utils.trim;var EventController=nokia.maps.dfw.utils.EventController;var StringBuilder=nokia.maps.dfw.utils.StringBuilder;var DFWEventConfiguration=nokia.maps.dfw.utils.DFWEventConfiguration;var Benchmark=nokia.maps.dfw.utils.Benchmark;var TemplateLoader=nokia.maps.dfw.utils.TemplateLoader;eval(nokia.aduno.utils.getImportCode());eval(nokia.maps.dfw.utils.getImportCode());var todo="This is an issue in namespace loading, please leave it in.";var Context=new Class({Name:"Context",initialize:function(eventController,aPath){if(!eventController){throw new ArgumentError("eventController is required")}this._eventController=eventController;this._eventController.addListener(this);this.appPath=aPath},selectedCategory:null,selectedCategories:null,sort:null,userLoggedIn:false,path:"",imperialUnits:false,onSearchBoxSearchTriggered:function(aEvent){this.selectedCategory.clearHitCountsOnChildren();if(this.selectedCategory.isLeaf()&&this.selectedCategory.parent){this.selectedCategory.parent.clearHitCountsOnChildren()}},onResultServiceResultsCleared:function(){this.numberOfAvailableResults=0},onCategoryClicked:function(aEvent){var params={},previous=this.selectedCategory;this.selectedCategory=aEvent.getData().category;if(!this.selectedCategory.isLeaf()){previous.clearHitCountsOnChildren()}if(!previous.isLeaf()&&!this.selectedCategory.isRoot){this.selectedCategory.clearHitCountsOnChildren()}this.selectedCategories=[];params.previous=previous;params.current=this.selectedCategory;this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.Context_CategoryChanged,params))},onCategoryToggled:function(aEvent){var cat=aEvent.getData().category;if(!this.selectedCategories){this.selectedCategories=[]}var indexOfCategory=nokia.maps.dfw.utils.indexOf(this.selectedCategories,cat);if(indexOfCategory<0){this.selectedCategories.push(cat)}else{this.selectedCategories.splice(indexOfCategory,1)}this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.Context_ToggleCategorySelected,{selectedCategories:this.selectedCategories}))},currentCategoryPath:function(){var path=[],cat=this.selectedCategory;while(cat){path.push(cat);cat=cat.getParent()}return path.reverse()}});var DiscoveryCaretaker=new Class({Name:"DiscoveryCaretaker",_inputArray:null,_arrayIndex:-1,getMemento:function(){var value=null;if(this._inputArray&&this._inputArray.length>-1){value=this._inputArray[this._arrayIndex];if(this._arrayIndex>=0){--this._arrayIndex}}return value},addMemento:function(aMemento){if(aMemento instanceof DiscoveryMemento){if(!this._inputArray){this._inputArray=[]}++this._arrayIndex;this._inputArray[this._arrayIndex]=aMemento}}});var DiscoveryMemento=new Class({Name:"DiscoveryMemento",getMementoValue:function(){var sb=new StringBuilder(),i,value;for(i in this){if(this.hasOwnProperty(i)){value=this[i];if(typeof(value)!="function"){sb.append(i);sb.append(":");sb.append(value);sb.append(",")}}}return sb.toString()}});nokia.maps.dfw.core.context.addMembers({todo:todo,Context:Context,DiscoveryCaretaker:DiscoveryCaretaker,DiscoveryMemento:DiscoveryMemento})};new function(){new nokia.aduno.Ns("nokia.maps.dfw.core.categorytree");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var extractInteger=nokia.maps.dfw.utils.extractInteger;var indexOf=nokia.maps.dfw.utils.indexOf;var contains=nokia.maps.dfw.utils.contains;var trim=nokia.maps.dfw.utils.trim;var EventController=nokia.maps.dfw.utils.EventController;var StringBuilder=nokia.maps.dfw.utils.StringBuilder;var DFWEventConfiguration=nokia.maps.dfw.utils.DFWEventConfiguration;var Benchmark=nokia.maps.dfw.utils.Benchmark;var TemplateLoader=nokia.maps.dfw.utils.TemplateLoader;eval(nokia.aduno.utils.getImportCode());eval(nokia.maps.dfw.utils.getImportCode());var todo="This is an issue in namespace loading, please leave it in.";var IconRepository=new Class({Name:"IconRepository",initialize:function(conf){if(!conf){throw new ArgumentError("conf is required")}this._conf=conf;this._icons={};this._iconCount=0;this._categoryIconIds={};this._imgType="png";if(nokia.aduno.utils.browser.msie&&nokia.aduno.utils.browser.version=="6"){this._imgType="gif"}this._parseIconUrls(IconDefinitions)},getIcon:function(aItemId){var url=this._icons[aItemId];if(url&&url.length>0){return url}return this._conf.defaultIcon},_parseIconUrls:function(aIconDefinitionArray){for(var i in aIconDefinitionArray){if(aIconDefinitionArray.hasOwnProperty(i)){var iconName=aIconDefinitionArray[i][0],categories=aIconDefinitionArray[i][1];if(iconName&&(typeof(iconName)=="string"||typeof(iconName)=="number")){this._icons[i]=this._conf.iconUrl.replace(/%t/g,this._imgType).replace(/%n/g,iconName);++this._iconCount;for(var j=0;j<categories.length;j++){this._categoryIconIds[categories[j]]=i}}}}},getIconByTag:function(tagId){var retval="",index;if(tagId){tagId=Number(tagId);tagId-=9000000;index=this._categoryIconIds[tagId];if(index&&this._icons[index]){retval=this._icons[index]}}return retval}});var IconDefinitions={"131":["EatDrink",[22,33,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,179,199,238]],"132":["GoingOut",[3,4,6,9,15,26,178,181,182,203,237]],"133":["SightsMuseums",[14,18,27,147,150,153,158,163,183,184,185,211,213,236]],"134":["Transport",[0,35,41,43,42,57,58,59,216,235]],"135":["Accomodation",[32,38,170,171,172,173,174,234]],"136":["Shopping",[23,24,49,60,119,142,143,189,190,191,192,193,194,195,196,197,198,205,225,233]],"137":["BusinessServices",[2,17,19,20,28,40,46,47,48,51,52,54,55,56,112,113,114,115,118,122,137,180,208,210,215,217,218,219,232]],"138":["Facility",[8,11,12,25,29,34,36,37,106,109,111,128,131,132,133,136,156,159,160,164,168,169,175,176,177,186,187,200,201,202,204,214,224,231]],"139":["Leisure",[1,13,21,30,48,162,188,230]],"140":["AreasInfrastructure",[104,105,116,117,207,220,221,226,229]],"141":["NatureGeography",[44,45,50,161,222,223,225,228]]};var CategoryTreeLoader=new Class({Name:"CategoryTreeLoader",initialize:function(eventController,context,iconRepository,conf){if(!eventController){throw new ArgumentError("eventController is required")}if(!context){throw new ArgumentError("context is required")}if(!iconRepository){throw new ArgumentError("iconRepository is required")}if(!conf){throw new ArgumentError("conf is required")}this._root=0;this._loadedCategories=[];this._rootNode=null;this._tree=null;this._categories=null;this._eventController=eventController;this._context=context;this._iconRepository=iconRepository;this._addressSearchId="9010001";this._conf=conf},loadCategoryTree:function(aRootCat,callback){if(this._conf.categories){this._categories=this._conf.categories;this._parseCategoriesFromStaticFile();this._establishRelationships();callback(this._tree)}else{this._loadCategoriesFromServer(aRootCat,bind(this,function(categories){if(this._conf.dataFormat=="xml"){this._parseCategoriesFromXML(categories)}else{if(this._conf.dataFormat=="json"){this._categories=categories;this._parseCategoriesFromStaticFile()}else{nokia.aduno.utils.warn("Unknown data format '"+this._conf.dataFormat+"'");return null}}this._establishRelationships();callback(this._tree)}))}},_loadCategoriesFromServer:function(aRootCat,callback){var url=this._conf.url,urlBuilder=new StringBuilder(),view,categoryConfPath;if(!aRootCat){aRootCat=9000012}view="view:"+aRootCat+"+";urlBuilder.append(url).append("?re=1");if(this._conf.appContextName){urlBuilder.append("&dv=").append(this._conf.appContextName)}urlBuilder.append("&vi=").append(aRootCat);urlBuilder.append("&res=").append(encodeURIComponent(view));categoryConfPath=urlBuilder.toString();Benchmark.setBenchmark("categoryTime");nokia.maps.dfw.core.getDocFromServer("GET",categoryConfPath,true,this._conf.dataFormat,callback)},_parseCategoriesFromXML:function(aCategoryDefinition){if(!aCategoryDefinition&&typeof(aCategoryDefinition)=="object"){return false}if(!this._categories){var viewsNode=aCategoryDefinition.getElementsByTagName("views")[0];if(!viewsNode){return false}this._categories=viewsNode.getElementsByTagName("view")}for(var categoriesLength=this._categories.length,i=0;i<categoriesLength;++i){var id=this._categories[i].getAttribute("id");var name=this._categories[i].getAttribute("name");if((!id)||(!name)){continue}var iconId=this._parseIconId(this._categories[i].getElementsByTagName("defitem").item(0));var node=this._createNode(id,name,this._iconRepository.getIcon(iconId),this._conf);node.childIds=this._parseChildIds(this._categories[i].getElementsByTagName("defframe").item(0));this._addToLoaded(node)}return true},_parseCategoriesFromStaticFile:function(){if(!this._categories){throw new Error("No local categories available!\nThe application can not be run.")}for(var categoriesLength=this._categories.length,i=0;i<categoriesLength;++i){var catdata=this._categories[i],node;node=this._createNode(catdata.id,decodeURIComponent(catdata.name),this._iconRepository.getIcon(catdata.icon),this._conf);node.childIds=catdata.childs;this._addToLoaded(node)}return true},_establishRelationships:function(){var categoriesLength=this._loadedCategories.length,i,j;if(categoriesLength<=0){return false}for(i=0;i<categoriesLength;++i){if(!this._loadedCategories[i].childIds){continue}for(j=0;j<this._loadedCategories[i].childIds.length;++j){var child=this._findFromLoaded(this._loadedCategories[i].childIds[j]);if(child){this._loadedCategories[i].add(child)}}}for(i=0;i<categoriesLength;++i){if(this._loadedCategories[i].uiName=="root"&&this._loadedCategories[i].childCount===0){for(j=0;j<categoriesLength;++j){if(i==j){continue}if(!this._loadedCategories[j].parent){this._loadedCategories[i].add(this._loadedCategories[j])}}break}}return true},_findFromLoaded:function(aCategoryId){for(var loadedCategoriesLength=this._loadedCategories.length,i=0;i<loadedCategoriesLength;++i){if(this._loadedCategories[i].categoryId==aCategoryId){return this._loadedCategories[i]}}return false},_addToLoaded:function(aNode){if(this._loadedCategories.length===0){this._rootNode=aNode;this._tree=new CategoryTree(aNode,this._eventController,this._context,this._conf)}this._loadedCategories.push(aNode);aNode.tree=this._tree},_createNode:function(aId,aName,aIconUrl,aConf){if(aId==this._addressSearchId){return new AddressCategoryTreeNode(aId,aName,aIconUrl,aConf)}return new CategoryTreeNode(aId,aName,aIconUrl,aConf)},_parseIconId:function(aDefitem){if(!aDefitem){return null}var defchilds=aDefitem.getElementsByTagName("property");for(var defChildsLength=defchilds.length,k=0;k<defChildsLength;++k){if(defchilds[k].getAttribute("name")=="ICON_ID"){try{return defchilds[k].firstChild.nodeValue}catch(e){nokia.aduno.utils.warn("Failed to parse icon!")}}}return null},_parseChildIds:function(aDefframe){var ids=[];if(aDefframe){var childNodes=aDefframe.getElementsByTagName("subview");for(var childNodesLength=childNodes.length,j=0;j<childNodesLength;++j){ids.push(childNodes[j].getAttribute("id"))}}return ids}});var CategoryTree=new Class({Name:"CategoryTree",initialize:function(aRootNode,eventController,context,conf){if(!(aRootNode instanceof CategoryTreeNode)){throw new ArgumentError("aRootNode is not a CategoryTreeNode")}this._rootNode=aRootNode;this._context=context;this._eventController=eventController;this._conf=conf;eventController.addListener(this)},onNSPQueryHandlerCategoryHitCountsChanged:function(aEvent){var params=aEvent.getData();if(this._conf.categoryMode!=="selecting"){this._updateHitCounts(params.hitCounts)}},onResultServiceResultsCleared:function(aEvent){var params=aEvent.getData();if(this._conf.categoryMode!=="selecting"){this._context.selectedCategory.clearHitCountsOnChildren();this._updateHitCounts(params.hitCounts)}},getRootNode:function(){return this._rootNode},find:function(aObjectId){return this._doFind(this._rootNode,aObjectId)},_doFind:function(aNode,aObjectId){if(aNode.oid=="OID"+aObjectId){return aNode}else{if(aNode.hasChilds()){var childs=aNode.getChilds();for(var key in childs){if(childs.hasOwnProperty(key)){var tempKid=this._doFind(childs[key],aObjectId);if(tempKid){return tempKid}}}}}return null},_updateHitCounts:function(aHitCountArray){if(!aHitCountArray){return}var updated=false;for(var len=aHitCountArray.length,i=0;i<len;i++){var categoryHitCount=aHitCountArray[i];var node=this.find(categoryHitCount.id);if(node){if(node.hitCount!=categoryHitCount.hitcount){node.hitCount=categoryHitCount.hitcount;updated=true}}}if(updated){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.CategoryTree_CategoryHitCountsUpdated))}}});var CategoryTreeNode=new Class({Name:"CategoryTreeNode",initialize:function(aObjectId,aName,myIconUrl,conf){this.oid="OID"+aObjectId;this.categoryId=aObjectId;this.uiName=aName;this.iconUrl=myIconUrl||conf.defaultIcon||"";this.parent=null;this.childs=null;this.childCount=0;this.childIds=[];this.tree=null;this.hitCount=undefined},hasChilds:function(){return(this.childCount>0)?true:false},getChildCount:function(){return this.childCount},add:function(aNode){if(!(aNode instanceof CategoryTreeNode)){return false}if(!this.childs){this.childs={}}this.childs[aNode.oid]=aNode;this.childCount++;aNode.parent=this;if(this.tree){aNode.tree=this.tree}return true},isParentOf:function(aNode){if(!(aNode instanceof CategoryTreeNode)){return false}if(this.childs&&this.childCount>0){for(var key in this.childs){if(this.childs.hasOwnProperty(key)){if(this.childs[key].categoryId==aNode.categoryId){return true}if(this.childs[key].isParentOf(aNode)){return true}}}}return false},deleteNode:function(){if(this.parent.childs[this.oid]){this.parent.childs[this.oid]=false}},getChilds:function(){return this.childs},isLeaf:function(){if(this.hasChilds()){return false}return true},isRoot:function(){if(!this.parent){return true}return false},getParent:function(){return this.parent},getSiblings:function(){return this.parent.childs},clearHitCountsOnChildren:function(){if(this.hasChilds()){for(var key in this.childs){if(this.childs.hasOwnProperty(key)){this.childs[key].hitCount=undefined}}}}});var AddressCategoryTreeNode=new Class({Extends:CategoryTreeNode,Name:"AddressCategoryTreeNode"});nokia.maps.dfw.core.categorytree.addMembers({todo:todo,IconRepository:IconRepository,CategoryTreeLoader:CategoryTreeLoader,CategoryTree:CategoryTree,CategoryTreeNode:CategoryTreeNode,AddressCategoryTreeNode:AddressCategoryTreeNode})};new function(){new nokia.aduno.Ns("nokia.maps.dfw.core");var type=nokia.aduno.utils.type;var inspect=nokia.aduno.utils.inspect;var splat=nokia.aduno.utils.splat;var setPeriodical=nokia.aduno.utils.setPeriodical;var cancelPeriodical=nokia.aduno.utils.cancelPeriodical;var setTimer=nokia.aduno.utils.setTimer;var cancelTimer=nokia.aduno.utils.cancelTimer;var platform=nokia.aduno.utils.platform;var browser=nokia.aduno.utils.browser;var throwError=nokia.aduno.utils.throwError;var ArgumentError=nokia.aduno.utils.ArgumentError;var UnsupportedError=nokia.aduno.utils.UnsupportedError;var AbstractMethodError=nokia.aduno.utils.AbstractMethodError;var bind=nokia.aduno.utils.bind;var getTimeStamp=nokia.aduno.utils.getTimeStamp;var extend=nokia.aduno.utils.extend;var clone=nokia.aduno.utils.clone;var generateId=nokia.aduno.utils.generateId;var logger=nokia.aduno.utils.logger;var debug=nokia.aduno.utils.debug;var error=nokia.aduno.utils.error;var info=nokia.aduno.utils.info;var warn=nokia.aduno.utils.warn;var Class=nokia.aduno.utils.Class;var ConsoleLogger=nokia.aduno.utils.ConsoleLogger;var Collection=nokia.aduno.utils.Collection;var Options=nokia.aduno.utils.Options;var Event=nokia.aduno.utils.Event;var EventSource=nokia.aduno.utils.EventSource;var CssLoader=nokia.aduno.utils.CssLoader;var ScriptLoader=nokia.aduno.utils.ScriptLoader;var Observable=nokia.aduno.utils.Observable;var ListModel=nokia.aduno.utils.ListModel;var AssociationList=nokia.aduno.utils.AssociationList;var extractInteger=nokia.maps.dfw.utils.extractInteger;var indexOf=nokia.maps.dfw.utils.indexOf;var contains=nokia.maps.dfw.utils.contains;var trim=nokia.maps.dfw.utils.trim;var EventController=nokia.maps.dfw.utils.EventController;var StringBuilder=nokia.maps.dfw.utils.StringBuilder;var DFWEventConfiguration=nokia.maps.dfw.utils.DFWEventConfiguration;var Benchmark=nokia.maps.dfw.utils.Benchmark;var TemplateLoader=nokia.maps.dfw.utils.TemplateLoader;var todo=nokia.maps.dfw.core.nspquery.todo;var Parser=nokia.maps.dfw.core.nspquery.Parser;var XMLParser=nokia.maps.dfw.core.nspquery.XMLParser;var NSPQueryHandlerError=nokia.maps.dfw.core.nspquery.NSPQueryHandlerError;var ResultCache=nokia.maps.dfw.core.nspquery.ResultCache;var ResultCacheItem=nokia.maps.dfw.core.nspquery.ResultCacheItem;var NSPQueryHandler=nokia.maps.dfw.core.nspquery.NSPQueryHandler;var JSON=nokia.maps.dfw.core.nspquery.JSON;var ResultService=nokia.maps.dfw.core.nspquery.ResultService;var SearchHistory=nokia.maps.dfw.core.nspquery.SearchHistory;var todo=nokia.maps.dfw.core.nspquerysender.todo;var NSPQuery=nokia.maps.dfw.core.nspquerysender.NSPQuery;var SearchHelper=nokia.maps.dfw.core.nspquerysender.SearchHelper;var todo=nokia.maps.dfw.core.context.todo;var Context=nokia.maps.dfw.core.context.Context;var DiscoveryCaretaker=nokia.maps.dfw.core.context.DiscoveryCaretaker;var DiscoveryMemento=nokia.maps.dfw.core.context.DiscoveryMemento;var todo=nokia.maps.dfw.core.categorytree.todo;var IconRepository=nokia.maps.dfw.core.categorytree.IconRepository;var CategoryTreeLoader=nokia.maps.dfw.core.categorytree.CategoryTreeLoader;var CategoryTree=nokia.maps.dfw.core.categorytree.CategoryTree;var CategoryTreeNode=nokia.maps.dfw.core.categorytree.CategoryTreeNode;var AddressCategoryTreeNode=nokia.maps.dfw.core.categorytree.AddressCategoryTreeNode;eval(nokia.aduno.utils.getImportCode());eval(nokia.maps.dfw.utils.getImportCode());eval(nokia.maps.dfw.core.nspquery.getImportCode());eval(nokia.maps.dfw.core.nspquerysender.getImportCode());eval(nokia.maps.dfw.core.context.getImportCode());eval(nokia.maps.dfw.core.categorytree.getImportCode());var getDocFromServer=function(postType,urlDef,sync,type,callback){var queryResponse=null;new nokia.aduno.Loader({uri:urlDef,async:sync,type:type,handler:function(value,success){if(!success){throw new Error("Failed to load: "+urlDef+", reason: "+value)}if(type==="json"){queryResponse=evaluate(value)}else{queryResponse=value}if(typeof(callback)=="function"){callback(queryResponse)}},xmlHttpRequest:(typeof(nokia.maps.dfw.core.createXmlHttpRequest)=="function"?nokia.maps.dfw.core.createXmlHttpRequest():null)});return queryResponse};var evaluate=function(json){if(json===""){return""}return(new nokia.maps.dfw.core.nspquery.JSON()).parse(json)};var getValueFromServer=function(urlDef){var queryResponse;new nokia.aduno.Loader({uri:urlDef,async:false,handler:function(value,success){queryResponse=value}});return queryResponse};var DiscoveryFrameworkCore=new Class({Name:"DiscoveryFrameworkCore",initialize:function(appPath,configuration,playerDependencies,onLoadedCallback){this._isReady=false;playerDependencies=Collection.merge(DependenciesInterface,playerDependencies);nokia.maps.dfw.core.createXmlHttpRequest=playerDependencies.createXmlHttpRequest;this._conf=Collection.merge(DefaultConf,configuration);if(!nokia.maps.dfw.globalConf){nokia.maps.dfw.globalConf=this._conf}this._onLoadedCallback=onLoadedCallback;this._playerDependencies=playerDependencies;nokia.maps.dfw.serviceLayer=this;this._eventController=new EventController(DFWEventConfiguration);this._context=new Context(this._eventController);this._resultService=new ResultService(this._eventController,this._conf);this._context.appPath=appPath||"";this._context.locale={};this._resourceManager=new nokia.aduno.i18n.ResourceManager(appPath+"assets/i18n");this._resourceManager.addEventHandler("ready",this._resourceLoaded,this);this._resourceManager.require(nokia.aduno.utils.browser.language);this._resourceManager.require(this._conf.localeCode);if(this._conf.iconUrl.indexOf("http")!=0){this._conf.iconUrl=appPath+"/"+this._conf.iconUrl}var binder=this;var waitForResources=function(){if(binder._resourcesLoaded){binder._initDataLayer()}else{setTimeout(waitForResources,100)}};waitForResources()},getSearchHelper:function(){if(!this.isReady()){throw new Error("DiscoveryFramework core has not been fully initialized")}if(!this._searchHelper){this._searchHelper=new SearchHelper(this._eventController,this._context,this._nspQuery,this._conf,this._searchHistory)}return this._searchHelper},getCategoryTree:function(){if(!this.isReady()){throw new Error("DiscoveryFramework core has not been fully initialized")}return this._categoryTree},getSearchHistory:function(){if(!this.isReady()){throw new Error("DiscoveryFramework core has not been fully initialized")}return this._searchHistory},isReady:function(){return this._isReady},_initDataLayer:function(callback){this._iconRepository=new IconRepository(this._conf);var catloader=new CategoryTreeLoader(this._eventController,this._context,this._iconRepository,this._conf);var rootcat=(typeof(searchall)=="undefined"||!searchall)?this._conf.rootView:0;catloader.loadCategoryTree(rootcat,bind(this,function(catTree){if(!catTree){throw new Error(this._context.locale.errorBackEndUnavailable)}this._categoryTree=catTree;this._context.selectedCategory=catTree.getRootNode();this._dataLayerInitialized()}))},_dataLayerInitialized:function(){this._searchHistory=new SearchHistory();this._nspQueryHandler=new NSPQueryHandler(this._eventController,this._context,this._resultService,this._categoryTree,this._iconRepository,this._searchHistory,this._conf);this._nspQuery=new NSPQuery(this._eventController,this._context,this._nspQueryHandler,this._categoryTree,this._searchHistory,this._conf);this._nspQuery.queryParams.otherParams.lat=50;this._nspQuery.queryParams.otherParams.lon=50;this._isReady=true;if(typeof(this._onLoadedCallback)=="function"){this._onLoadedCallback(this);this._onLoadedCallback=null}},_resourceLoaded:function(aReadyEvent){this._context.currentLocaleCode=aReadyEvent.getData().locale;this._context.locale=this._resourceManager.get(this._context.currentLocaleCode);this._resourcesLoaded=true;this._eventController.fireEvent(new nokia.a