/* 
 * 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.aduno.utils.Event(DFWEventConfiguration.LocalizationManager_LocaleLoaded))}});var DefaultConf={url:"/nsearchproxy/",iconUrl:"graphics/%t_20x20/%n.%t",defaultIcon:"http://download.s2g.gate5.de/ovi_icons/v1/gif_25x25/station_myplaces.gif",appContextName:"oviMaps",dataFormat:"xml",categoryMode:"browsing",c:10,localeCode:"en-GB",localeUrl:"res/locale/",progressIconUrl:"graphics/small_progress_20x18.gif",manualProgressIconUrl:"res/images/maps/progress_%n.gif",progressIconSpeed:500,resultLimit:100,suggestionListOn:true,dynamicSearch:false,searchTermMinLength:1,searchExecutionDelay:100,suggestionUrl:"/nsearchproxy/",maxSuggestions:10,suggestionView:"where",rootView:"where",benchmarkingLogOn:false,pagesPerFetch:3,sbUseClearButton:false,sbClearButtonImage:false,sbSearchButtonImage:true,sbSearchButtonProgressAppearance:true,sbSearchButtonProgressClassName:"nmd_searchBtnProgress",fetchOnCategoryToggle:true,useCache:true,languageInSearch:true};var DependenciesInterface={persistence:{_cache:{},addData:function(aKey,aValue){this._cache[aKey]=aValue},getData:function(aKey){var obj={};obj[aKey]=this._cache[aKey];return obj},removeData:function(aKey){this._cache[aKey]=null}},createXmlHttpRequest:function(){return new XMLHttpRequest()}};nokia.maps.dfw.core.addMembers({getDocFromServer:getDocFromServer,evaluate:evaluate,getValueFromServer:getValueFromServer,DiscoveryFrameworkCore:DiscoveryFrameworkCore,DefaultConf:DefaultConf,DependenciesInterface:DependenciesInterface})};new function(){new nokia.aduno.Ns("nokia.maps.dfw.ui");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 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 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;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.aduno.dom.getImportCode());eval(nokia.aduno.medosui.getImportCode());eval(nokia.maps.dfw.core.resulttypes.getImportCode());eval(nokia.maps.dfw.core.categorytree.getImportCode());var todo="This is an issue in namespace loading, please leave it in.";var DFWTemplateLibraryHash={SortingControl:'<div class="nmd_SortingControl"><div id="dropdown"></div><div id="rbGroup"></div></div>',RadioButton:'<div id="checkButton"><span id="checkButtonButton" class="checkbutton"></span><span id="checkButtonText" class="checklabel" ></span></div>',SearchBox:'<div id="searchBox" class="nmd_searchBox"><span id="termBox"></span><span id="searchButton"></span></div>',termBox:'<input id="input" type="text"></input>',clearButton:'<button id="button" class="nmd_clearBtn"></button>',searchButton:'<button id="button" class="nmd_searchBtn"></button>',progressIndicator:'<div id="indicator" class="nmd_ProgressIndicator"></div>',SuggestionList:'<div id="root" class="nmd_SuggestionCon"><h1 class="nmd_SuggestionTitle">Suggestions</h1><div id="list"></div></div>',SuggestionInnerList:'<ul id="list" class="nmd_SuggestionLis"></ul>',SuggestionItem:'<li id="item" class="nmd_SuggestionLisElm"><span id="suggestionItemWrapper"><span class="nmd_SuggestionItem" id="suggestionItem"></span></span></li>',PagingFrame:'<div id="pagingFrame" class="nmd_PagingCon"><span id="previousLabel" class="nmd_PagingPreviousBtn"></span><span id="nextLabel" class="nmd_PagingNextBtn"></span></div>',ErrorPresenter:'<div id="errorPresenter" class="nmd_ErrorPresenter"></div>',AddressSearchButton:'<input id="button" class="nmd_AddressSubmitBtn" name="nmd_submit" type="button"/>',AddressForm:'<div id="root" class="nmd_AddressFormCon"><div class="nmd_AddressFormFrame"><form action="" method="get"><h3 id="addressCountryLabel">Country / Region *</h3><div class="nmd_TextInWrap"><div id="addressCountryInput"></div></div><h3 id="addressCityLabel">City / Zip *</h3><div class="nmd_TextInWrap"><div id="addressCityInput"></div></div><h3 id="addressStreetLabel">Street</h3><div class="nmd_TextInWrap"><div id="addressStreetInput"></div></div><h3 id="addressNumberLabel">Number</h3><div class="nmd_TextInWrap"><div id="addressNumberInput"></div></div><div class="nmd_LabAddressHelp" id="addressHelpLabel"></div><div class="nmd_LabAddressError" id="addressError"></div><div id="addressSearchButton"></div></form></div><div class="nmd_AddressFormFooter"><div></div></div></div>',AddressCountryInput:'<input id="input" class="nmd_TextInCountry" name="nmd_TextInCountry" type="text"/>',AddressCityInput:'<input id="input" class="nmd_TextInCity" name="nmd_TextInCity" type="text"/>',AddressStreetInput:'<input id="input" class="nmd_TextInStreet" name="nmd_TextInStreet" type="text"/>',AddressNumberInput:'<input id="input" class="nmd_TextInNumber" name="nmd_TextInNumber" type="text"/>',AddressError:'<div id="error"></div>',RefineByCategoryButton:'<a id="button" class="nmd_CategoryToggleBtn">Refine by Categories</a>',ResultListBrowser:'<div id="browser" class="nmd_ResultLisBrowser"></div>',ResultList:'<ul id="list" class="nmd_ResultLis"></ul>',ResultListItem:'<li id="item" class="nmd_ResultLisElm"><span class="nmd_ResultNumber" id="resultNumber"></span><span id="resultLine1Wrapper"><span class="nmd_ResultLine1" id="resultLine1"></span></span><span id="resultLine2Wrapper"><span class="nmd_ResultLine2" id="resultLine2"></span></span><span class="nmd_ResultDistance" id="resultDistance"></span><span class="nmd_ResultIcon" id="resultIcon"></span></li>',CategoryListBrowser:'<div id="browser" class="nmd_CategoryLisBrowser"></div>',CategoryList:'<dl id="list" class="nmd_CategoryLis"></dl>',CategoryListHeader:'<dt id="categoryHeader" class="nmd_CategoryLisHeader"></dt>',CategoryListItem:'<dd id="item" class="nmd_CategoryLisElm"><span id="categoryNameWrapper"><span class="nmd_CategoryName" id="categoryName"></span></span><span class="nmd_CategoryIcon" id="categoryIcon"></span><span class="nmd_CategoryNext"></span></dd>',IconCategoryListBrowser:'<div id="browser" class="nmd_IconCategoryLisBrowser"></div>',IconCategoryList:'<dl id="list" class="nmd_IconCategoryLis"></dl>',BreadCrumb:'<ul id="breadCrumb" class="nmd_BreadCrumbLis"></ul>',BreadCrumbNodeText:'<li class="nmd_BreadCrumbLisElmText"><span id="breadCrumbNodeWrapper"><span class="nmd_BreadCrumbLisElmName" id="breadCrumbNode" ></span></span></li>',BreadCrumbNodeLink:'<li class="nmd_BreadCrumbLisElmLink"><span id="breadCrumbNodeWrapper"><span class="nmd_BreadCrumbLisElmName" id="breadCrumbNode"></span></span></li>',BreadCrumbNodeSeparator:'<li id="breadCrumbNode" class="nmd_BreadCrumbLisElmSeparator"> &#187; </li>'};var DFWTemplateLibrary=new nokia.aduno.dom.TemplateLibrary(DFWTemplateLibraryHash,DefaultTemplateLibrary);var DFWListElement=new Class({Extends:Control,Name:"DFWListElement",initialize:function(aTemplate,eventController){if(!eventController){throw new ArgumentError("DFWListElement: eventController is required")}this._super(aTemplate);this._eventController=eventController;this.getReplica().addEventHandler("click",this,function(aEvent){this._onSelected();if(this._onClickFireSelected){this.fireEvent("selected")}})},_onClickFireSelected:true,_onSelected:function(){},handleKey:function(aKeyEvent){var handled=false;if(aKeyEvent.keyUp){if(aKeyEvent.specialKey==KeyEventManager.KEY_OK){this._onSelected();handled=true}aKeyEvent.preventDefault()}return handled},truncateToWidth:function(idList){var i,obj,id,wrapperId,eleParWidth,eleWidth,ellipsisWidth,minWidth;for(i in idList){if(idList.hasOwnProperty(i)){obj=idList[i];id=obj[0];wrapperId=id+"Wrapper";eleParWidth=obj[1];if(this.getReplica().getElement(id)===null){continue}eleWidth=nokia.aduno.dom.Dimensions.getSize(this.getReplica().getElement(id)).x;ellipsisWidth=30;minWidth=15;if(nokia.aduno.utils.browser.mozilla||nokia.aduno.utils.browser.opera){ellipsisWidth=40;minWidth=1}if((eleWidth===0)||(eleParWidth<=0)||(eleWidth<eleParWidth)){continue}this.getReplica().setStyle(id,"width",Math.max(minWidth,eleParWidth-ellipsisWidth)+"px");if((nokia.aduno.utils.browser.msie&&parseInt(nokia.aduno.utils.browser.version,10)>6)||nokia.aduno.utils.browser.safari){continue}this.getReplica().addCssClass(wrapperId,"nmd_ellipsis")}}}});var DFWList=new Class({Extends:SelectionList,Name:"DFWList",initialize:function(aTemplate,aTemplateLibrary,eventController,context){if(!eventController){throw new ArgumentError("DFWList: eventController is required")}if(!context){throw new ArgumentError("DFWList: context is required")}this._super(aTemplate,aTemplateLibrary,"nmd_selected");this._eventController=eventController;this._context=context;this._eventController.addListener(this);this.getReplica().addEventHandler("click",this,function(){this.focus()});this.hide()},handleKey:function(aKeyEvent){var handled=false;if(this.getSelected()){handled=this.getSelected().handleKey(aKeyEvent)}if(!handled&&aKeyEvent.keyUp){var selectionIndex=this.getSelectionIndex();switch(aKeyEvent.getKey()){case KeyEventManager.KEY_UP:if(selectionIndex>0){--selectionIndex;this.setSelectionIndex(selectionIndex);handled=true}break;case KeyEventManager.KEY_DOWN:if(selectionIndex+1<this.getChildCount()){++selectionIndex;this.setSelectionIndex(selectionIndex);handled=true}break;default:break}aKeyEvent.preventDefault()}return handled},focus:function(){if(this.getSelected()||this.setSelectionIndex(0)){this.getSelected().focus();this._isFocused=true}return true},blur:function(){if(this.getSelected()||this.setSelectionIndex(0)){this.getSelected().blur()}this._isFocused=false;return true}});var DFWListBrowser=new Class({Extends:SelectionList,Name:"DFWListBrowser",initialize:function(aTemplate,aTemplateLibrary,eventController,context,lists){if(!eventController){throw new ArgumentError("DFWListBrowser: eventController is required")}if(!context){throw new ArgumentError("DFWListBrowser: context is required")}this._super(aTemplate,aTemplateLibrary,"nmd_selected");this._eventController=eventController;this._context=context;this._eventController.addListener(this);this.getReplica().addEventHandler("click",this,function(){this.focus()});if(lists&&(type(lists)=="array")){for(var i=0;i<lists.length;i++){this._addList(lists[i])}}else{nokia.aduno.utils.warn("DFWListBrowser: no lists given");this.hide()}},handleKey:function(aKeyEvent){var handled=false;if(this.getSelected()){handled=this.getSelected().handleKey(aKeyEvent)}return handled},focus:function(){if(!this._isFocused){if(this._parent.requestFocus(this)&&this.getSelected()){this.getSelected().focus();this._isFocused=true}}return true},blur:function(){if(this.getSelected()){this.getSelected().blur()}this._isFocused=false;return true},browse:function(){if(this.getChildCount()==1){return{current:this.getSelected(),past:null}}else{if(this.getChildCount()>1){var pastIndex=this.getSelectionIndex();var currentIndex=pastIndex+1;if(currentIndex==this.getChildCount()){currentIndex=0}this.setSelectionIndex(currentIndex);return{past:this.getChildAt(pastIndex),current:this.getSelected()}}}return{current:null,past:null}},setDecorator:function(aDecorator){if(typeof aDecorator!=="function"){throw new ArgumentError(this._className+": given paramter is not a function")}this._decorator=aDecorator},_invokeDecorator:function(browsingInfo){if(this._decorator&&typeof(this._decorator)==="function"){browsingInfo.animationDirection=this._chooseAnimationDirection();this._decorator(browsingInfo)}},_chooseAnimationDirection:function(){return"right"},_addList:function(aList){this.addChild(aList);if(this.getChildCount()==1){this.setSelectionIndex(0)}}});var SortingControl=new Class({Extends:Container,Name:"SortingControl",initialize:function(aTemplate,aTemplateLibrary,eventController,context){if(!eventController){throw new ArgumentError("SearchBox: eventController is required")}if(!context){throw new ArgumentError("SearchBox: context is required")}this._super(aTemplate,aTemplateLibrary);this._eventController=eventController;this._context=context;this._sortOptions=this._getSortOptions();this._dropdown=new DropDown("DropDown",aTemplateLibrary,this._sortOptions,0);this.setChildAt(this._dropdown,"dropdown",true);this._dropdown.addEventHandler("selected",this._onViewSelected,this);this._rbGroup=new RadioGroup("radioGroup");this._buttons=[];for(var i=0;i<this._sortOptions.length;i++){var rb=new CheckButton("RadioButton",this._sortOptions[i].text,this._sortOptions[i].value,false);rb.addEventHandler("selected",this._onRbViewSelected,this);rb.data=this._sortOptions[i].data;this._rbGroup.addChild(rb);this._buttons.push(rb)}this._buttons[0].setState(true);this.setChildAt(this._rbGroup,"rbGroup");this._eventController.addListener(this)},_getSortOptions:function(){var locale=this._context.locale;return[{text:locale.distance,data:"dis"},{text:locale.importance,data:"imp"}]},_onViewSelected:function(aSelectEvent){var val=aSelectEvent.getData().data;this._viewSelected(val);this._dropdown._toggleCollapse()},_onRbViewSelected:function(aSelectEvent){var val=aSelectEvent.get("target").data;this._viewSelected(val)},_viewSelected:function(aVal){if(aVal!==this.lastValue){this.lastValue=aVal;this._context.sort=aVal;this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SortingControl_SortChanged,{value:aVal}))}},onLocalizationManagerLocaleLoaded:function(){this._sortOptions=this._getSortOptions();for(var i=0;i<this._sortOptions.length;i++){this._buttons[i].setText(this._sortOptions[i].text)}this._dropdown.setDataArray(this._sortOptions)},onSortingControlSortChanged:function(params){var value=params.value;for(var i=0;i<this._sortOptions.length;i++){if(this._sortOptions[i].data===value){this._dropdown.setSelectionIndex(i);this._buttons[i].setState(true)}else{this._buttons[i].setState(false)}}}});var SearchBox=new Class({Extends:Container,Name:"SearchBox",Implements:Options,options:{useClearButton:true,clearButtonImage:false,searchButtonImage:false,searchButtonProgressAppearance:false,searchButtonProgressClassName:"nmd_searchBtnProgress"},initialize:function(aTemplate,aTemplateLibrary,eventController,context,options,conf){if(!eventController){throw new ArgumentError("SearchBox: eventController is required")}if(!context){throw new ArgumentError("SearchBox: context is required")}this.setOptions(options);this._super(aTemplate,aTemplateLibrary);this._eventController=eventController;this._context=context;this._conf=conf;this.termBox=new TextInput("termBox","",{watermark:context.locale.defaultSearchTerm});this.termBox.addEventHandler("blurred",this._blurHandler,this);this.termBox.addEventHandler("focused",this._focusHandler,this);this.termBox.getReplica().addEventHandler("input","keyup",this,this._changedHandler);this.setChildAt(this.termBox,"termBox");if(this.getOption("useClearButton")){this.clearButton=new Button("clearButton");this.clearButton.addEventHandler("selected",this._onClearButtonSelected,this);this.setChildAt(this.clearButton,"clearButton");this._turnOffClearButton()}this.searchButton=new Button("searchButton");this.searchButton.addEventHandler("selected",this._onSearchButtonSelected,this);this.setChildAt(this.searchButton,"searchButton");this._setTexts();this._eventController.addListener(this)},_setTexts:function(){this.termBox.setWatermark(this._context.locale.defaultSearchTerm);if(this.getOption("useClearButton")){if(this.getOption("searchButtonImage")){this.clearButton.getReplica().setAttribute("button","title",this._context.locale.clear)}else{this.clearButton.setText(this._context.locale.clear)}}if(this.getOption("searchButtonImage")){this.searchButton.getReplica().setAttribute("button","title",this._context.locale.search)}else{this.searchButton.setText(this._context.locale.search)}},_onClearButtonSelected:function(){this.clearBox()},_onSearchButtonSelected:function(){if(this.searchButton.isEnabled()){this._fireSearch()}},_fireSearch:function(){var searchTerm=trim(this.termBox.getValue());if(searchTerm.length>0){this.prevSearchTerm=searchTerm;this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_SearchTriggered,{searchTerm:searchTerm,nonBlockable:true,manual:true}))}},_blurHandler:function(){this._termBoxChanged();this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_LostFocus))},_focusHandler:function(){},_changedHandler:function(aEvent){this._termBoxChanged();var keyCode=aEvent.getKey();if(this.hasDefaultOrEmptyValue()){if(this.prevSearchTerm!==""){cancelTimer(this._liveSearchTimer);cancelTimer(this._requestSuggestionTimer);this.prevSearchTerm="";this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_ContentsCleared));this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_SearchTermCleared))}return}if(this._conf.dynamicSearch){if((keyCode==13)||(keyCode==40)||(keyCode==38)){var params={e:{keyCode:keyCode},handled:false};this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_KeyUpEvent,params));if(keyCode==13&&!params.handled){this._fireSearch()}return}cancelTimer(this._liveSearchTimer);this._liveSearchTimer=setTimer(this._conf.searchExecutionDelay,this,function(){var searchTerm=trim(this.termBox.getValue());if(this.prevSearchTerm!==searchTerm){this.prevSearchTerm=searchTerm;if(searchTerm.length>=this._conf.searchTermMinLength){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_SearchTriggered,{searchTerm:searchTerm,nonBlockable:true,manual:false}))}}})}else{if(keyCode==13){if((this.currentSuggestionItem)&&(this.currentSuggestionItem.suggestionType==="direct")){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_SuggestionTriggered,{suggestionItem:this.currentSuggestionItem}));return}this._fireSearch()}else{if((keyCode==40)||(keyCode==38||(keyCode==27))){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_KeyUpEvent,{event:{keyCode:keyCode}}));return}var value=this.termBox.getValue();if(this.prevSearchTerm===value){return}this.currentSuggestionItem=null;this.prevSearchTerm=value;if(this._conf.suggestionListOn){var requestSuggestionsFunction=function(){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_RequestSuggestions,{query:value,nonBlockable:true}))};cancelTimer(this._requestSuggestionTimer);if(value.length>=this._conf.searchTermMinLength){this._requestSuggestionTimer=setTimer(this._conf.searchExecutionDelay,this,requestSuggestionsFunction)}}}}},_termBoxChanged:function(){if(this.termBox.getValue()===""){this._turnOffClearButton()}else{this._turnOnClearButton()}},_turnOnClearButton:function(){if(this.getOption("useClearButton")){this.clearButton.getReplica().getElement("button").removeAttribute("disabled")}},_turnOffClearButton:function(){if(this.getOption("useClearButton")){this.clearButton.getReplica().setAttribute("button","disabled","disabled")}},clearBox:function(){this.setValue("");this.prevSearchTerm="";this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_ResetSearchTerm));this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_SearchTermCleared));this._termBoxChanged()},setValue:function(aValue){this.termBox.setValue(aValue);this.prevSearchTerm=aValue;this._termBoxChanged()},hasDefaultValue:function(){return this.termBox.getValue()===this._context.locale.defaultSearchTerm},hasEmptyValue:function(){return this.termBox.getValue()===""},hasDefaultOrEmptyValue:function(){return this.hasDefaultValue()||this.hasEmptyValue()},enableSearchButton:function(){this.getReplica().getElement("searchButton").removeAttribute("disabled");if(this.getOption("searchButtonProgressClassName")){this.getReplica().removeCssClass("searchButton",this.getOption("searchButtonProgressClassName"))}else{throw new Error("Search button progress style class name not specified.")}this.searchButton.enable()},disableSearchButton:function(){this.getReplica().setAttribute("searchButton","disabled","true");if(this.getOption("searchButtonProgressClassName")){this.getReplica().addCssClass("searchButton",this.getOption("searchButtonProgressClassName"))}else{throw new Error("Search button progress style class name not specified.")}this.searchButton.disable()},fireSearch:function(){this._fireSearch()},onNSPQueryValidAddressSearch:function(aEvent){this.termBox.setValue(aEvent.getData().addressString)},onSuggestionListSuggestionTriggered:function(aEvent){var params=aEvent.getData();this.currentSuggestionItem=null;if(params.suggestionItem.suggestionType==="term"||params.suggestionItem.suggestionType==="searchHistory"){this.termBox.setValue(params.suggestionItem.suggestionText);this.prevSearchTerm=params.suggestionItem.suggestionText;this.termBox.focus();this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SearchBox_SearchTriggered,{searchTerm:params.suggestionItem.suggestionText}))}else{if(params.suggestionItem.suggestionType==="direct"){this.termBox.setValue(params.suggestionItem.suggestionText);this.prevSearchTerm=params.suggestionItem.suggestionText;this.termBox.focus()}}},onSuggestionListSuggestionSelected:function(aEvent){var params=aEvent.getData();this.currentSuggestionItem=params.suggestionItem;this.termBox.setValue(params.suggestionItem.suggestionText)},onSuggestionListLostFocus:function(aEvent){var params=aEvent.getData();this.termBox.setValue(this.prevSearchTerm);this.currentSuggestionItem=null},onLocalizationManagerLocaleLoaded:function(){this._setTexts()},onNSPQuerySearchStarted:function(){if(this.getOption("searchButtonProgressAppearance")){this.disableSearchButton()}},onNSPQueryHandlerSearchAborted:function(){if(this.getOption("searchButtonProgressAppearance")){this.enableSearchButton()}},onNSPQueryHandlerSearchEnded:function(){if(this.getOption("searchButtonProgressAppearance")){this.enableSearchButton()}}});var PagingFrame=new Class({Extends:Container,Name:"PagingFrame",initialize:function(aTemplate,aTemplateLibrary,eventController,context){if(!eventController){throw new ArgumentError("PagingFrame: eventController is required")}if(!context){throw new ArgumentError("PagingFrame: context is required")}this._super(aTemplate,aTemplateLibrary);this._eventController=eventController;this._context=context;this.previousLabel=new Label("previousLabel","Previous");this.previousLabel.getReplica().addEventHandler("click",this,this._onPreviousLabelClick);this.setChildAt(this.previousLabel,"previousLabel",true);this.nextLabel=new Label("nextLabel","Next");this.nextLabel.getReplica().addEventHandler("click",this,this._onNextLabelClick);this.setChildAt(this.nextLabel,"nextLabel",true);this._setTexts();this._update();this._eventController.addListener(this)},_hasMorePages:false,_currentPage:null,_resultCount:0,_onPreviousLabelClick:function(){if(this.previousLabel.isEnabled()){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.PagingFrame_PreviousPage))}},_onNextLabelClick:function(){if(this.nextLabel.isEnabled()){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.PagingFrame_NextPage))}},_update:function(){if(this._resultCount===0){this.hide();this._disableNext();this._disablePrevious();return}if(this._currentPage>1){this._enablePrevious()}else{this._disablePrevious()}if(this._hasMorePages){this._enableNext()}else{this._disableNext()}this.show()},_enablePrevious:function(){this.previousLabel.enable();this.previousLabel.getReplica().removeCssClass("nmd_PagingPreviousBtnDisabled");this.previousLabel.getReplica().addCssClass("nmd_PagingPreviousBtn")},_disablePrevious:function(){this.previousLabel.disable();this.previousLabel.getReplica().removeCssClass("nmd_PagingPreviousBtn");this.previousLabel.getReplica().addCssClass("nmd_PagingPreviousBtnDisabled")},_enableNext:function(){this.nextLabel.enable();this.nextLabel.getReplica().removeCssClass("nmd_PagingNextBtnDisabled");this.nextLabel.getReplica().addCssClass("nmd_PagingNextBtn")},_disableNext:function(){this.nextLabel.disable();this.nextLabel.getReplica().removeCssClass("nmd_PagingNextBtn");this.nextLabel.getReplica().addCssClass("nmd_PagingNextBtnDisabled")},_setTexts:function(){this.previousLabel.setText(this._context.locale.previousTitle);this.nextLabel.setText(this._context.locale.nextTitle)},onNSPQueryHandlerUpdatePaging:function(aEvent){var params=aEvent.getData();this._currentPage=params.currentPage;this._hasMorePages=params.hasMorePages;this._resultCount=params.resultCount;this._update()},onResultServiceResultsCleared:function(){this._resultCount=0;this._update()},onLocalizationManagerLocaleLoaded:function(){this._setTexts()}});var ProgressIndicator=new Class({Extends:Control,Name:"ProgressIndicator",initialize:function(aTemplate,aTemplateLibrary,eventController,context,manual,conf){if(!eventController){throw new ArgumentError("ProgressIndicator: eventController is required")}if(!context){throw new ArgumentError("ProgressIndicator: context is required")}this._conf=conf;this._super(aTemplate,aTemplateLibrary);this._eventController=eventController;this._context=context;this._manual=manual;this.defaultIconPath=conf.progressIndicatorDefaultPath?"url("+this._context.appPath+"/"+conf.progressIndicatorDefaultPath+")":"";this._setBgImage(this.defaultIconPath);this._eventController.addListener(this)},_setBgImage:function(aUrl){this._replica.setAttribute("indicator","style","background-image: "+aUrl)},setManual:function(aValue){this._manual=aValue},start:function(){if(this._manual){var startManual=function(state){state=(state%8)+1;this._setBgImage("url("+this._context.appPath+"/"+this._conf.manualProgressIconUrl.replace(/%n/g,state)+")");this._timer=setTimer(this._conf.progressIconSpeed,this,startManual,state)};this._timer=setTimer(0,this,startManual,0)}else{this._setBgImage("url("+this._context.appPath+"/"+this._conf.progressIconUrl+")")}},stop:function(){if(this._timer){cancelTimer(this._timer)}this._setBgImage(this.defaultIconPath)},onNSPQuerySearchStarted:function(){this.start()},onNSPQueryHandlerSearchAborted:function(){this.stop()},onNSPQueryHandlerSearchEnded:function(){this.stop()}});var SuggestionListItem=new Class({Extends:DFWListElement,Name:"SuggestionListItem",initialize:function(aTemplate,eventController,aSuggestionItem,aCssClass){if(!aSuggestionItem){throw new ArgumentError("SuggestionListItem: aSuggestionItem is required")}this._super(aTemplate,eventController);this._suggestionItem=aSuggestionItem;this._setTexts();this._setStyle(aCssClass)},_onSelected:function(){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SuggestionList_SuggestionTriggered,{suggestionItem:this._suggestionItem}))},_setTexts:function(){this.getReplica().setText("suggestionItem",this._suggestionItem.suggestionText);this.getReplica().setAttribute("item","title",this._suggestionItem.suggestionText)},_setStyle:function(aCssClass){this.getReplica().addCssClass("item",aCssClass)}});var SuggestionList=new Class({Extends:Container,Name:"SuggestionList",_active:false,initialize:function(aTemplate,aTemplateLibrary,eventController){if(!eventController){throw new ArgumentError("SuggestionList: eventController is required")}this._super(aTemplate,aTemplateLibrary);this._eventController=eventController;this._eventController.addListener(this);this._list=new SelectionList("SuggestionInnerList",aTemplateLibrary,"nmd_selected");this.setChildAt(this._list,"list");this._list.show();this.hide()},_update:function(aSuggestionArray){if(!aSuggestionArray||aSuggestionArray.length<1){nokia.aduno.utils.warn("SuggestionList.updateSuggestions(): no suggestions available");this.hide()}var childCount=this._generateList(aSuggestionArray);if(childCount===0){this.hide();return}Benchmark.log("rendering suggestions took: ","resultTime");this.show();this._truncateChildren()},_generateList:function(aSuggestionArray){this._list.removeAllChildren();var suggestionArray,n,len,totalSuggestionCount=0,suggestionItem;suggestionArray=aSuggestionArray.term||[];for(n=0,len=suggestionArray.length;n<len;n++,totalSuggestionCount++){suggestionItem=new SuggestionListItem("SuggestionItem",this._eventController,suggestionArray[n],"nmd_SuggestionTerm");this._list.addChild(suggestionItem).setCSSTrigger(Control.CSS_TRIGGER_OVER)}suggestionArray=aSuggestionArray.direct||[];for(n=0,len=suggestionArray.length;n<len;n++,totalSuggestionCount++){suggestionItem=new SuggestionListItem("SuggestionItem",this._eventController,suggestionArray[n],"nmd_SuggestionDirect");this._list.addChild(suggestionItem).setCSSTrigger(Control.CSS_TRIGGER_OVER)}suggestionArray=aSuggestionArray.didYouMean||[];for(n=0,len=suggestionArray.length;n<len;n++,totalSuggestionCount++){suggestionItem=new SuggestionListItem("SuggestionItem",this._eventController,suggestionArray[n],"nmd_SuggestionDidYouMean");this._list.addChild(suggestionItem).setCSSTrigger(Control.CSS_TRIGGER_OVER)}suggestionArray=aSuggestionArray.searchHistory||[];for(n=0,len=suggestionArray.length;n<len;n++,totalSuggestionCount++){suggestionItem=new SuggestionListItem("SuggestionItem",this._eventController,suggestionArray[n],"nmd_SuggestionSearchHistory");this._list.addChild(suggestionItem).setCSSTrigger(Control.CSS_TRIGGER_OVER)}return this._list.getChildCount()},_clear:function(){this._active=false;this.hide()},_lostFocus:function(){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SuggestionList_LostFocus));this.hide()},_truncateChildren:function(){Benchmark.setBenchmark("suggestionListTruncation");var parentWidth=nokia.aduno.dom.Dimensions.getSize(this.getNode()).x;if(parentWidth<=0){nokia.aduno.utils.info("aborting truncation");return}for(var len=this._list.getChildCount(),i=0;i<len;i++){if(parentWidth<=0){nokia.aduno.utils.info("aborting truncation");continue}this._list.getChildAt(i).truncateToWidth([["suggestionItem",parentWidth]])}Benchmark.log("result list truncation took: ","suggestionListTruncation")},onNSPQueryHandlerSuggestionsUpdated:function(aEvent){if(this._active){this._update(aEvent.getData().suggestions)}},onSearchBoxKeyUpEvent:function(aEvent){if(this._list.getChildCount()===0){return}var params=aEvent.getData();var event=params.event,suggestionItem;switch(event.keyCode){case 38:if(!this.isVisible()){return}if(this._list.getSelectionIndex()===0){this._lostFocus()}this._list.setSelectionIndex(this._list.getSelectionIndex()-1);this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SuggestionList_SuggestionSelected,{suggestionItem:this._list.getSelected()._suggestionItem}));break;case 40:if(!this.isVisible()){this.show();return}if(this._list.getSelectionIndex()==this._list.getChildCount()-1){return}this._list.setSelectionIndex(this._list.getSelectionIndex()+1);this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.SuggestionList_SuggestionSelected,{suggestionItem:this._list.getSelected()._suggestionItem}));break;case 27:this._lostFocus();this._list.setSelectionIndex(0);break;default:break}},onSearchBoxSearchTriggered:function(){this._clear()},onSuggestionListSuggestionTriggered:function(){this._clear()},onSearchBoxSuggestionTriggered:function(){this._clear()},onSearchBoxSearchTermCleared:function(){this._clear()},onSearchBoxContentsCleared:function(){this._clear()},onSearchBoxLostFocus:function(){setTimer(100,this,this._clear)},onSearchBoxRequestSuggestions:function(){this._active=true}});var ErrorPresenter=new Class({Extends:Control,Name:"ErrorPresenter",initialize:function(aTemplate,aTemplateLibrary,eventController,context,nspQuery){if(!eventController){throw new ArgumentError("ErrorPresenter: eventController is required")}if(!context){throw new ArgumentError("ErrorPresenter: context is required")}this._super(aTemplate,aTemplateLibrary);this._context=context;this._nspQuery=nspQuery;eventController.addListener(this);this.hide()},_addressSearchId:9010001,_setErrorText:function(aErrorText){this.getReplica().setInnerHtml("errorPresenter",aErrorText);this.show()},_clearErrorText:function(){this.getReplica().setInnerHtml("errorPresenter","");this.hide()},onSearchBoxSearchTermCleared:function(){this._clearErrorText()},onResultListNoError:function(){this._clearErrorText()},onResultListError:function(){var locale=this._context.locale;var errormsg;if(this._context.selectedCategory.isRoot()){errormsg=locale.errorMsg}else{if(this._context.selectedCategory.categoryId==this._addressSearchId){errormsg=locale.errorMsgCategory+locale.errorMsgAddress}else{errormsg=locale.errorMsgCategory}}if(this._nspQuery.isTermActive()){errormsg+=locale.errorMsgTerm.replace(/%term/g,this._nspQuery.getTerm())}this._setErrorText(errormsg)}});var RefineByCategoryButton=new Class({Extends:Button,Name:"RefineByCategoryButton",initialize:function(aTemplate,eventController,context,nspQuery){if(!eventController){throw new ArgumentError("RefineByCategoryButton: eventController is required")}if(!context){throw new ArgumentError("RefineByCategoryButton: context is required")}this._super(aTemplate);this._eventController=eventController;this._context=context;this._nspQuery=nspQuery;this._setTexts();this.addEventHandler("selected",this._onButtonSelected,this);this._eventController.addListener(this)},_categoriesHidden:false,_setTexts:function(){if(this._categoriesHidden){this.setText(this._context.locale.showCategories)}else{this.setText(this._context.locale.hideCategories)}},_onButtonSelected:function(){var notification="RefineByCategoryButton_"+(this._categoriesHidden?"Show":"Hide")+"Categories";this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration[notification]))},onRefineByCategoryButtonShowCategories:function(){this._categoriesHidden=false;this._setTexts()},onRefineByCategoryButtonHideCategories:function(){this._categoriesHidden=true;this._setTexts()},onLocalizationManagerLocaleLoaded:function(){this._setTexts()},onCategoryListBrowserShowAddressForm:function(){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.RefineByCategoryButton_HideCategories));this.hide()}});var AddressForm=new Class({Extends:Container,Name:"AddressForm",initialize:function(aTemplate,aTemplateLibrary,eventController,context,conf){if(!eventController){throw new ArgumentError("AddressForm: eventController is required")}if(!context){throw new ArgumentError("AddressForm: context is required")}this._super(aTemplate,aTemplateLibrary);this._eventController=eventController;this._context=context;this.submitButton=new Button("AddressSearchButton");this.submitButton.addEventHandler("selected",this._onSubmitButtonSelected,this);this.setChildAt(this.submitButton,"addressSearchButton");this.countryInput=new TextInput("AddressCountryInput");this.setChildAt(this.countryInput,"addressCountryInput");this.cityInput=new TextInput("AddressCityInput");this.setChildAt(this.cityInput,"addressCityInput");this.streetInput=new TextInput("AddressStreetInput");this.setChildAt(this.streetInput,"addressStreetInput");this.numberInput=new TextInput("AddressNumberInput");this.setChildAt(this.numberInput,"addressNumberInput");this._setTexts();this._eventController.addListener(this);this._conf=conf},_setTexts:function(){this.getReplica().setText("addressCountryLabel",this._context.locale.addressCountry);this.getReplica().setText("addressCityLabel",this._context.locale.addressCity);this.getReplica().setText("addressStreetLabel",this._context.locale.addressStreet);this.getReplica().setText("addressNumberLabel",this._context.locale.addressNumber);this.getReplica().setText("addressHelpLabel",this._context.locale.addressHelp);this.submitButton.setText(this._context.locale.addressSearch);this._clearErrorText()},_setErrorText:function(){this.getReplica().setText("addressError",this._context.locale.addressError)},_clearErrorText:function(){this.getReplica().setText("addressError","")},_onSubmitButtonSelected:function(aSelectEvent){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.AddressForm_SearchTriggered,{country:trim(this.countryInput.getValue()),city:trim(this.cityInput.getValue()),street:trim(this.streetInput.getValue()),number:trim(this.numberInput.getValue())}))},onCategoryListBrowserShowAddressForm:function(){this.countryInput.setValue("");this.cityInput.setValue("");this.streetInput.setValue("");this.numberInput.setValue("");this.show()},onContextCategoryChanged:function(){if(this._conf.showCategoriesInLeafNode){this.hide()}},onCategoryTreeCategoryHitCountsUpdated:function(){this.onContextCategoryChanged()},onNSPQueryInvalidAddressSearch:function(){this._setErrorText()},onLocalizationManagerLocaleLoaded:function(){this._setTexts()},onNSPQueryValidAddressSearch:function(){this._clearErrorText()}});var ResultListItem=new Class({Extends:DFWListElement,Name:"ResultListItem",initialize:function(aTemplate,eventController,aResultItem,aSearchTerm,context){if(!aResultItem){throw new ArgumentError("ResultListItem: aResultItem is required")}this._context=context;this._super(aTemplate,eventController);eventController.addListener(this);this._resultItem=aResultItem;this._setTexts(aSearchTerm);this._setStyle();this._setButtons()},_onSelected:function(){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.ResultList_ResultItemSelected,{resultItem:this._resultItem}))},_setTexts:function(aSearchTerm){this.getReplica().setInnerHtml("resultLine1",this._formatTitle(this._resultItem.row1||this._resultItem.title,aSearchTerm));this.getReplica().setAttribute("item","title",this._resultItem.title);this.getReplica().setInnerHtml("resultNumber",this._resultItem.index);this.getReplica().setInnerHtml("resultLine2",this._resultItem.row2);this._updateDistance()},_setStyle:function(){this.getReplica().setAttribute("resultIcon","style","background-image: url("+this._resultItem.iconUrl+");")},_formatTitle:function(aTitle,aSearchTerm){if(aSearchTerm){var tRegExp=this._searchTermToRE(aSearchTerm);return(aTitle||"").replace(tRegExp,"<strong>$1</strong>")}return aTitle},_formatDistance:function(aDistance){var imperialUnits=this._context.imperialUnits;if(typeof(aDistance)=="string"){aDistance=parseInt(aDistance,10)}if(typeof(aDistance)!="number"||isNaN(aDistance)||aDistance<0){return""}if(imperialUnits){var FEET_IN_METER=3.2808399;var FEET_IN_MILE=5280;aDistance=Math.round(aDistance*FEET_IN_METER);if(aDistance<FEET_IN_MILE){modulo=aDistance%10;if(modulo===0){}else{if(modulo<5){aDistance-=modulo}else{aDistance=aDistance-modulo+10}}return aDistance+"&nbsp;ft"}else{if(aDistance<100*FEET_IN_MILE){return(aDistance/FEET_IN_MILE).toFixed(1)+"&nbsp;mi"}else{return Math.round(aDistance/FEET_IN_MILE)+"&nbsp;mi"}}}else{if(aDistance<1000){modulo=aDistance%10;if(modulo===0){}else{if(modulo<5){aDistance-=modulo}else{aDistance=aDistance-modulo+10}}return aDistance+"&nbsp;m"}else{if(aDistance<100000){aDistance/=1000;return aDistance.toFixed(1)+"&nbsp;km"}else{aDistance/=1000;return Math.round(aDistance)+"&nbsp;km"}}}},_searchTermToRE:function(aSearchTerm){var str=aSearchTerm.replace(/ /gim,"|");str=str.replace(/([\/\\\*\.\[\]\{\}\(\)\?\$\^])/gm,"\\$1");return new RegExp("("+str+")","gim")},_setButtons:function(){var i,element,replica=this.getReplica(),NUM_OF_BUTTONS;for(i=0;i<10;i++){replica.addEventHandler("button"+i,"click",this,bind(this,this._buttonClicked,i))}},_buttonClicked:function(buttonId,aEvent){aEvent.stopPropagation();this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.ResultList_ResultItemButtonClicked,{resultItem:this._resultItem,buttonId:buttonId}))},_updateDistance:function(){this.getReplica().setInnerHtml("resultDistance",this._formatDistance(this._resultItem.distance))},onContextUnitChanged:function(){this._updateDistance()}});var ResultListBrowser=new Class({Extends:DFWListBrowser,Name:"ResultListBrowser",_currentIndex:0,_lastIndex:0,initialize:function(aTemplate,aTemplateLibrary,eventController,context,lists,nspQuery){this._super(aTemplate,aTemplateLibrary,eventController,context,lists);this._nspQuery=nspQuery;this._clearResults()},_update:function(aResultArray){var browsingInfo=this.browse();if(!aResultArray||aResultArray.length<1){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.ResultList_Error));this.getSelected().hide();return}var childCount=this._generateList(aResultArray,this._nspQuery.getTerm());if(childCount===0){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.ResultList_Error));this.getSelected().hide();return}this.getSelected().setSelectionIndex(0);this.getSelected().show();this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.ResultList_NoError));this._currentIndex=aResultArray[0].index;if(this._parent){this.show();this._truncateChildren();this._invokeDecorator(browsingInfo)}Benchmark.log("rendering results took: ","resultTime")},updateHeight:function(){var height=nokia.aduno.dom.Dimensions.getSize(this.getReplica().getRootElement().parentNode).y,itemHeight=nokia.aduno.dom.Dimensions.getSize(this.getSelected().getChildAt(0).getNode()).y,resultCount=1;if(itemHeight){resultCount=Math.max(1,((height-(height%itemHeight))/itemHeight))}this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.ResultList_ResultCountChanged,{resultCount:resultCount}))},_generateList:function(aResultArray,aSearchTerm){this.getSelected().removeAllChildren();for(var i=0,resultsLength=aResultArray.length;i<resultsLength;i++){var resultItemData=aResultArray[i];var resultListItem=new ResultListItem("ResultListItem",this._eventController,resultItemData,aSearchTerm,this._context);this.getSelected().addChild(resultListItem).setCSSTrigger(Control.CSS_TRIGGER_OVER)}return this.getSelected().getChildCount()},_chooseAnimationDirection:function(){var last=this._lastIndex;this._lastIndex=this._currentIndex;if(last>this._currentIndex){return"right"}return"left"},_truncateChildren:function(){Benchmark.setBenchmark("resultListTruncation");var parentWidth=nokia.aduno.dom.Dimensions.getSize(this.getNode()).x-10;if(parentWidth<=0){nokia.aduno.utils.info("aborting truncation");return}for(var len=this.getSelected().getChildCount(),i=0;i<len;i++){this.getSelected().getChildAt(i).truncateToWidth([["resultLine1",parentWidth],["resultLine2",parentWidth-50]])}Benchmark.log("result list truncation took: ","resultListTruncation")},_clearResults:function(){this.getSelected().removeAllChildren();var dummy=new ResultItem();dummy.title=dummy.row1=dummy.row2=dummy.shortTitle="";this._update([dummy])},onResultServiceNewResultsAvailable:function(aEvent){this._update(aEvent.getData().results)},onResultServiceResultsCleared:function(){this.getSelected().hide();this._clearResults()}});var CategoryListItem=new Class({Extends:DFWListElement,Name:"CategoryListItem",initialize:function(aTemplate,eventController,aCategory,owner,conf){if(!aCategory){throw new ArgumentError("CategoryListItem: aCategory is required")}this._conf=conf;this._super(aTemplate,eventController);this._eventController.addListener(this);this._category=aCategory;this._owner=owner;this._setTexts();this._setStyle()},_onSelected:function(){if(this._conf.categoryMode==="browsing"){this._onClickFireSelected=true;this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.Category_Clicked,{category:this._category,parent:this._owner}))}else{if(this._conf.categoryMode==="selecting"){this._onClickFireSelected=false;this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.CategoryToggled,{category:this._category}))}}},_setTexts:function(){this.getReplica().setText("categoryName",this._category.uiName);this.getReplica().setAttribute("item","title",this._category.uiName)},_setStyle:function(){this.getReplica().setAttribute("categoryIcon","style","background-image: url("+this._category.iconUrl+")")},onCategoryToggled:function(aEvent){if(this._category==aEvent.getData().category){if(!this._toggled){this.getReplica().addCssClass("item","nmd_toggled");return(this._toggled=true)}else{this.getReplica().removeCssClass("item","nmd_toggled");return(this._toggled=false)}}}});var CategoryListHeader=new Class({Extends:Control,Name:"CategoryListHeader",initialize:function(aTemplate,aTitle){this._super(aTemplate);this._replica.setText("categoryHeader",aTitle)}});var CategoryListBrowser=new Class({Extends:DFWListBrowser,Name:"CategoryListBrowser",_browsingForward:true,initialize:function(aTemplate,aTemplateLibrary,eventController,context,lists,nspQuery,truncatingEnabled,conf){this._super(aTemplate,aTemplateLibrary,eventController,context,lists);this._nspQuery=nspQuery;this._conf=conf;this._update(this._context.selectedCategory.getChilds());this._tmpl=aTemplate;this._truncatingEnabled=truncatingEnabled},_update:function(aCategoryArray){Benchmark.setBenchmark("browsingTime");if(!aCategoryArray||aCategoryArray.length<1){return}var browsingInfo=this.browse();browsingInfo.eventController=this._eventController;var childCount=this._generateList(aCategoryArray);if(childCount===0){this.getSelected().hide();return}this.getSelected().setSelectionIndex(1);this.getSelected().show();this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.CategoryList_Rendered));if(this._parent){this.focus();this._truncateChildren();this._invokeDecorator(browsingInfo)}Benchmark.log("browsing took: ","browsingTime")},_truncateChildren:function(){if(!this._truncatingEnabled){return}Benchmark.setBenchmark("categoryListTruncation");var parentWidth=nokia.aduno.dom.Dimensions.getSize(this.getNode()).x-30;if(parentWidth<=0){nokia.aduno.utils.info("aborting truncation");return}for(var len=this.getSelected().getChildCount(),i=0;i<len;i++){var child=this.getSelected().getChildAt(i);if(child instanceof CategoryListHeader){continue}child.truncateToWidth([["categoryName",parentWidth]])}Benchmark.log("category list truncation took: ","categoryListTruncation")},_generateList:function(aCategoryArray){this.getSelected().removeAllChildren();var addedCategoryCount=0;var categoryNameChecker=function(category){if(category.uiName.indexOf("My ")===0){return true}return false};var favoriteChecker=function(category){if(category.uiName.indexOf("My ")===0){return false}return true};if(this._context.selectedCategory.isRoot()&&this._context.userLoggedIn){this.getSelected().addChild(new CategoryListHeader("CategoryListHeader",this._context.locale.favourites));addedCategoryCount+=this._addCategories(aCategoryArray,favoriteChecker)}this.getSelected().addChild(new CategoryListHeader("CategoryListHeader",this._context.locale.byCategory));addedCategoryCount+=this._addCategories(aCategoryArray,categoryNameChecker);return addedCategoryCount},_addCategories:function(aCategoryArray,validityCheckerFn){var addedCategoryCount=0,i;for(i in aCategoryArray){if(aCategoryArray.hasOwnProperty(i)){var category=aCategoryArray[i];if(category instanceof CategoryTreeNode){if(validityCheckerFn(category)){continue}var hitCount=category.hitCount;var catName=category.uiName;if((hitCount===0||typeof(hitCount)=="undefined")&&(this._nspQuery.isTermActive())&&(this._conf.categoryMode!=="selecting")){continue}addedCategoryCount++;var categoryItem=new CategoryListItem("CategoryListItem",this._eventController,category,this,this._conf);this.getSelected().addChild(categoryItem).setCSSTrigger(Control.CSS_TRIGGER_OVER)}}}return addedCategoryCount},_chooseAnimationDirection:function(){if(this._browsingForward){return"left"}return"right"},onServiceLayerUserLoggedIn:function(){this._update(this._context.selectedCategory.getChilds())},onServiceLayerUserLoggedOut:function(){this._update(this._context.selectedCategory.getChilds())},onLocalizationManagerLocaleLoaded:function(){this._update(this._context.selectedCategory.getChilds())},onCategoryListBrowserShowAddressForm:function(){this.getSelected().hide()},onCategoryTreeCategoryHitCountsUpdated:function(){if(this._context.selectedCategory.isLeaf()&&this._nspQuery.isTermActive()){this._update(this._context.selectedCategory.parent.getChilds());return}this._update(this._context.selectedCategory.getChilds())},onRefineByCategoryButtonShowCategories:function(){this.getSelected().show()},onRefineByCategoryButtonHideCategories:function(){this.getSelected().hide()},onContextCategoryChanged:function(aEvent){var cat=aEvent.getData().current,previous=aEvent.getData().previous;if(previous.isParentOf(cat)){this._browsingForward=true}else{this._browsingForward=false}if(cat instanceof AddressCategoryTreeNode){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.CategoryListBrowser_ShowAddressForm))}else{if(!this._nspQuery.isTermActive()&&((!cat.isLeaf()&&!previous.isLeaf())||cat.isRoot())){this._update(cat.getChilds())}}}});var BreadCrumbNode=new Class({Extends:DFWListElement,Name:"BreadCrumbNode",initialize:function(aTemplate,eventController,aLabelText,aCategory,clickable){this._super(aTemplate,eventController);this._category=aCategory;this.getReplica().setText("breadCrumbNode",aLabelText);this.getReplica().setAttribute("breadCrumbNodeWrapper","title",aLabelText);this._clickable=clickable},_onSelected:function(){if(this._clickable){this._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.Category_Clicked,{category:this._category}))}}});var BreadCrumb=new Class({Extends:List,Name:"BreadCrumb",initialize:function(aTemplate,aTemplateLibrary,eventController,context){if(!eventController){throw new ArgumentError("BreadCrumb: eventController is required")}if(!context){throw new ArgumentError("BreadCrumb: context is required")}this._super(aTemplate,aTemplateLibrary);this._eventController=eventController;this._context=context;this._eventController.addListener(this);this._update(this._context.currentCategoryPath())},_hasCustomActiveNode:false,_customActiveNodeTitle:null,_customActiveNodeHandler:null,setCustomNode:function(aTitle,aHandler){if(typeof("nodeTitle")=="string"){this._customActiveNodeTitle=aTitle}if(typeof(nodeHandler)=="function"){this._customActiveNodeHandler=aHandler}this._hasCustomActiveNode=true;this._update(this._context.currentCategoryPath())},hasCustomActiveNode:function(){return this._hasCustomActiveNode},resetCustomNode:function(){this._hasCustomActiveNode=false;this._customActiveNodeTitle=null;this._customActiveNodeHandler=null;this._update(this._context.currentCategoryPath())},_update:function(aCategoryArray){Benchmark.setBenchmark("breadCrumbTime");if(!aCategoryArray||aCategoryArray.length<1){this.hide();return}this._generateList(aCategoryArray);if(this._parent){this._truncateChildren()}Benchmark.log("rendering breadcrumb took: ","breadCrumbTime")},_generateList:function(aCategoryArray){this.removeAllChildren();var categoryCount=aCategoryArray.length;if(categoryCount>1){for(var i=0;i<categoryCount-1;++i){this.addChild(this._createBrowseNode(aCategoryArray[i])).setCSSTrigger(Control.CSS_TRIGGER_OVER);this.addChild(new Label("BreadCrumbNodeSeparator"))}}this.addChild(this._createTextNode(aCategoryArray[categoryCount-1]));if(this.hasCustomActiveNode()){this.addChild(new Label("BreadCrumbNodeSeparator"));this.addChild(this._createCustomNode())}},_createBrowseNode:function(aCategory){var breadCrumbNodeTitle=this._nodeTitleChooser(aCategory.uiName,aCategory.isRoot());return new BreadCrumbNode("BreadCrumbNodeLink",this._eventController,breadCrumbNodeTitle,aCategory,true)},_createTextNode:function(aCategory){var breadCrumbNodeTitle=this._nodeTitleChooser(aCategory.uiName,aCategory.isRoot());return new BreadCrumbNode("BreadCrumbNodeText",this._eventController,breadCrumbNodeTitle,false)},_createCustomNode:function(){var customBreadCrumbNode=new BreadCrumbNode("BreadCrumbNodeLink",this._eventController,this._customActiveNodeTitle,true);if(this._customActiveNodeHandler&&typeof(this._customActiveNodeHandler)=="function"){customBreadCrumbNode._onSelected=this._customActiveNodeHandler}return customBreadCrumbNode},_nodeTitleChooser:function(aTitle,isRoot){if(isRoot){return this._context.locale.breadCrumbHome}if(aTitle=="My Collections"){return"Collections"}if(aTitle=="My Routes"){return"Routes"}return aTitle},_truncateChildren:function(){var parentWidth=nokia.aduno.dom.Dimensions.getSize(this.getNode()).x,childCount=this.getChildCount(),separatorCount=0,separatorWidth=0,titleCount=0,i,child,width,titleWidth;for(i=0;i<childCount;i++){child=this.getChildAt(i);if(child instanceof Label){separatorCount++;separatorWidth=nokia.aduno.dom.Dimensions.getSize(child.getNode()).x}}titleCount=childCount-separatorCount;titleWidth=Math.round(((parentWidth-(separatorCount*separatorWidth))/titleCount)-1);for(i=0;i<childCount;i++){child=this.getChildAt(i);if(child instanceof Label){continue}width=nokia.aduno.dom.Dimensions.getSize(child.getNode()).x;if(width<titleWidth){titleWidth+=titleWidth-width;continue}child.truncateToWidth([["breadCrumbNode",titleWidth]])}},onContextCategoryChanged:function(){this._update(this._context.currentCategoryPath())},onCategoryListBrowserShowAddressForm:function(){this._update(this._context.currentCategoryPath())},onSearchBoxSearchTriggered:function(){this._update(this._context.currentCategoryPath())},onNSPQueryTermCleared:function(){this._update(this._context.currentCategoryPath())},onLocalizationManagerLocaleLoaded:function(){this._update(this._context.currentCategoryPath())}});var ResultListDecorator=new Class({Name:"ResultListDecorator",initialize:function(aCenter,aListWidth){this._center=aCenter;this._listWidth=aListWidth},_duration:400,_fps:25,getDecorator:function(){var that=this;return function(info){that._decorator.call(that,info)}},_decorator:function(info){if(info.past===null||info.current===null||info.past._children.length===0||info.current._children.length===0){return}info.past.getNode();info.current.getNode();var startPos=(info.animationDirection==="right")?this._listWidth:-this._listWidth;var pastOptions={duration:this._duration,fps:this._fps,styles:{left:[this._center,this._center+startPos]}};var currOptions={duration:this._duration,fps:this._fps,styles:{left:[this._center-startPos,this._center]}};cancelTimer(this._timer);this._timer=setTimer(1,this,function(){var fx=new nokia.aduno.medosui.Fx(info.past);fx.addEventHandler("started",function(){info.past.show()});fx.addEventHandler("ended",function(){info.past.hide()});fx.effect(pastOptions).start();fx=new nokia.aduno.medosui.Fx(info.current);fx.addEventHandler("started",function(){info.current.show()});fx.effect(currOptions).start()})}});var DiscoveryFrameworkUI=new Class({Name:"DiscoveryFramework",Implements:EventSource,initialize:function(aDiscoveryFrameworkCore,page){this._dfwc=aDiscoveryFrameworkCore;this._dfwc._eventController.addListener(this);this._page=page},getSearchBox:function(){if(!this._searchBox){var c=this._dfwc._conf,options={useClearButton:c.sbUseClearButton,clearButtonImage:c.sbClearButtonImage,searchButtonImage:c.sbSearchButtonImage,searchButtonProgressAppearance:c.sbSearchButtonProgressAppearance,searchButtonProgressClassName:c.sbSearchButtonProgressClassName};this._searchBox=new SearchBox("SearchBox",null,this._dfwc._eventController,this._dfwc._context,options,this._dfwc._conf)}return this._searchBox},getAddressForm:function(){if(!this._addressForm){this._addressForm=new AddressForm("AddressForm",null,this._dfwc._eventController,this._dfwc._context,this._dfwc._conf)}return this._addressForm},getResultList:function(){if(!this._resultList){var lists=[new DFWList("ResultList",null,this._dfwc._eventController,this._dfwc._context)];var resultList=new ResultListBrowser("ResultListBrowser",null,this._dfwc._eventController,this._dfwc._context,lists,this._dfwc._nspQuery);this._resultList=resultList;if(this._page){this._page.addEventHandler("shown",function(){resultList.updateHeight()})}}return this._resultList},getProgressIndicator:function(){if(!this._progressIndicator){this._progressIndicator=new ProgressIndicator("progressIndicator",null,this._dfwc._eventController,this._dfwc._context,false,this._dfwc._conf)}return this._progressIndicator},getPagingFrame:function(){if(!this._pagingFrame){this._pagingFrame=new PagingFrame("PagingFrame",null,this._dfwc._eventController,this._dfwc._context)}return this._pagingFrame},getSuggestionList:function(){if(!this._suggestionList){this._suggestionList=new SuggestionList("SuggestionList",null,this._dfwc._eventController)}return this._suggestionList},getCategoryList:function(){if(!this._categoryList){var lists=[new DFWList("CategoryList",null,this._dfwc._eventController,this._dfwc._context),new DFWList("CategoryList",null,this._dfwc._eventController,this._dfwc._context)];var categoryList=new CategoryListBrowser("CategoryListBrowser",null,this._dfwc._eventController,this._dfwc._context,lists,this._dfwc._nspQuery,true,this._dfwc._conf);this._categoryList=categoryList;if(this._page){this._page.addEventHandler("shown",function(){categoryList.onCategoryTreeCategoryHitCountsUpdated()})}}return this._categoryList},getIconCategoryList:function(){if(!this._iconCategoryList){var lists=[new DFWList("IconCategoryList",null,this._dfwc._eventController,this._dfwc._context)];this._iconCategoryList=new CategoryListBrowser("IconCategoryListBrowser",null,this._dfwc._eventController,this._dfwc._context,lists,this._dfwc._nspQuery,false,this._dfwc._conf)}return this._iconCategoryList},getSortingControl:function(){if(!this._sortingControl){this._sortingControl=new SortingControl("SortingControl",null,this._dfwc._eventController,this._dfwc._context)}return this._sortingControl},getErrorPresenter:function(){if(!this._errorPresenter){this._errorPresenter=new ErrorPresenter("ErrorPresenter",null,this._dfwc._eventController,this._dfwc._context,this._dfwc._nspQuery)}return this._errorPresenter},getRefineByCategoryButton:function(){if(!this._refineByCategoryButton){this._refineByCategoryButton=new RefineByCategoryButton("RefineByCategoryButton",this._dfwc._eventController,this._dfwc._context,this._dfwc._nspQuery)}return this._refineByCategoryButton},getBreadCrumb:function(){if(!this._breadCrumb){this._breadCrumb=new BreadCrumb("BreadCrumb",null,this._dfwc._eventController,this._dfwc._context)}return this._breadCrumb},onResultListResultItemSelected:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event("ResultSelected",aEvent.getData().resultItem))},onResultServiceNewResultsAvailable:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event("ResultsReceived",aEvent.getData().results))},onResultServiceResultsCleared:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event("ResultsCleared"))},onSearchBoxSuggestionTriggered:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event("SuggestionSelected",aEvent.getData().suggestionItem))},onSuggestionListSuggestionTriggered:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event("SuggestionSelected",aEvent.getData().suggestionItem))},onResultListResultItemButtonClicked:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event("ResultButtonSelected",aEvent.getData()))},setLatLon:function(aLatitude,aLongitude){this._dfwc._nspQuery.queryParams.otherParams.lat=aLatitude;this._dfwc._nspQuery.queryParams.otherParams.lon=aLongitude;return this},setLocationHint:function(aLocation){this._dfwc._nspQuery.queryParams.otherParams.loc=aLocation;return this},changeLocale:function(aLocaleCode){this._dfwc._resourceManager.require(aLocaleCode);return this},setImperialUnits:function(aBoolean){this._dfwc._context.imperialUnits=aBoolean;this._dfwc._eventController.fireEvent(new nokia.aduno.utils.Event(DFWEventConfiguration.Context_UnitChanged))}});nokia.maps.dfw.ui.addMembers({DFWTemplateLibraryHash:DFWTemplateLibraryHash,DFWTemplateLibrary:DFWTemplateLibrary,DFWListElement:DFWListElement,DFWList:DFWList,DFWListBrowser:DFWListBrowser,SortingControl:SortingControl,SearchBox:SearchBox,PagingFrame:PagingFrame,ProgressIndicator:ProgressIndicator,SuggestionList:SuggestionList,ErrorPresenter:ErrorPresenter,RefineByCategoryButton:RefineByCategoryButton,AddressForm:AddressForm,ResultListBrowser:ResultListBrowser,CategoryListBrowser:CategoryListBrowser,BreadCrumb:BreadCrumb,ResultListDecorator:ResultListDecorator,DiscoveryFrameworkUI:DiscoveryFrameworkUI})};new function(){new nokia.aduno.Ns("nokia.maps.dfw");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 getDocFromServer=nokia.maps.dfw.core.getDocFromServer;var evaluate=nokia.maps.dfw.core.evaluate;var getValueFromServer=nokia.maps.dfw.core.getValueFromServer;var DiscoveryFrameworkCore=nokia.maps.dfw.core.DiscoveryFrameworkCore;var DefaultConf=nokia.maps.dfw.core.DefaultConf;var DependenciesInterface=nokia.maps.dfw.core.DependenciesInterface;var DFWTemplateLibraryHash=nokia.maps.dfw.ui.DFWTemplateLibraryHash;var DFWTemplateLibrary=nokia.maps.dfw.ui.DFWTemplateLibrary;var DFWListElement=nokia.maps.dfw.ui.DFWListElement;var DFWList=nokia.maps.dfw.ui.DFWList;var DFWListBrowser=nokia.maps.dfw.ui.DFWListBrowser;var SortingControl=nokia.maps.dfw.ui.SortingControl;var SearchBox=nokia.maps.dfw.ui.SearchBox;var PagingFrame=nokia.maps.dfw.ui.PagingFrame;var ProgressIndicator=nokia.maps.dfw.ui.ProgressIndicator;var SuggestionList=nokia.maps.dfw.ui.SuggestionList;var ErrorPresenter=nokia.maps.dfw.ui.ErrorPresenter;var RefineByCategoryButton=nokia.maps.dfw.ui.RefineByCategoryButton;var AddressForm=nokia.maps.dfw.ui.AddressForm;var ResultListBrowser=nokia.maps.dfw.ui.ResultListBrowser;var CategoryListBrowser=nokia.maps.dfw.ui.CategoryListBrowser;var BreadCrumb=nokia.maps.dfw.ui.BreadCrumb;var ResultListDecorator=nokia.maps.dfw.ui.ResultListDecorator;var DiscoveryFrameworkUI=nokia.maps.dfw.ui.DiscoveryFrameworkUI;eval(nokia.aduno.utils.getImportCode());eval(nokia.aduno.dom.getImportCode());eval(nokia.aduno.medosui.getImportCode());eval(nokia.maps.dfw.utils.getImportCode());eval(nokia.maps.dfw.core.resulttypes.getImportCode());eval(nokia.maps.dfw.core.categorytree.getImportCode());eval(nokia.maps.dfw.core.getImportCode());eval(nokia.maps.dfw.ui.getImportCode());var todo="This is an issue in namespace loading, please leave it in.";var DiscoveryFramework=new Class({Name:"DiscoveryFramework",initialize:function(appPath,page,configuration,playerDependencies,onInitializedCallback){var f;this.core=new DiscoveryFrameworkCore(appPath,configuration,playerDependencies,bind(this,function(core){this.core=core;this.ui=new DiscoveryFrameworkUI(this.core,page);for(f in this.core){if(f!=="initialize"&&typeof(this.core[f])=="function"){this[f]=bind(this.core,this.core[f])}}for(f in this.ui){if(f!=="initialize"&&typeof(this.ui[f])=="function"){this[f]=bind(this.ui,this.ui[f])}}if(typeof(onInitializedCallback)=="function"){onInitializedCallback(this)}}))}});nokia.maps.dfw.addMembers({DiscoveryFramework:DiscoveryFramework})};new function(){new nokia.aduno.Ns("nokia.maps.pfw.ui");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 DiscoveryFramework=nokia.maps.dfw.DiscoveryFramework;var layout=nokia.maps.pfw.layout;var Serializable=nokia.maps.pfw.Serializable;var Destroyable=nokia.maps.pfw.Destroyable;var MouseEventHandler=nokia.maps.pfw.MouseEventHandler;var PluginLogger=nokia.maps.pfw.PluginLogger;var PluginControl=nokia.maps.pfw.PluginControl;var Location=nokia.maps.pfw.Location;var MapObject=nokia.maps.pfw.MapObject;var MapMarker=nokia.maps.pfw.MapMarker;var Layer=nokia.maps.pfw.Layer;var MapPolyline=nokia.maps.pfw.MapPolyline;var MapPolygon=nokia.maps.pfw.MapPolygon;var Spice=nokia.maps.pfw.Spice;var Player=nokia.maps.pfw.Player;var PlayerManager=nokia.maps.pfw.PlayerManager;var MapModel=nokia.maps.pfw.MapModel;var ZoomModel=nokia.maps.pfw.ZoomModel;var PersistenceModel=nokia.maps.pfw.PersistenceModel;var ConnectivityModel=nokia.maps.pfw.ConnectivityModel;var PositionModel=nokia.maps.pfw.PositionModel;var RoutingModel=nokia.maps.pfw.RoutingModel;var Route=nokia.maps.pfw.Route;var RouteSettingsModel=nokia.maps.pfw.RouteSettingsModel;var SpiceManager=nokia.maps.pfw.SpiceManager;var MouseEventHandling=nokia.maps.pfw.MouseEventHandling;var GuidanceModel=nokia.maps.pfw.GuidanceModel;var Maneuver=nokia.maps.pfw.Maneuver;var PlacesModel=nokia.maps.pfw.PlacesModel;var SearchModel=nokia.maps.pfw.SearchModel;var SearchStringBuilder=nokia.maps.pfw.SearchStringBuilder;var Waypoint=nokia.maps.pfw.Waypoint;var ReverseGeoCodingModel=nokia.maps.pfw.ReverseGeoCodingModel;var ApplicationModel=nokia.maps.pfw.ApplicationModel;var AppearanceModel=nokia.maps.pfw.AppearanceModel;var PlayerTranslationVisitor=nokia.maps.pfw.PlayerTranslationVisitor;var Units=nokia.maps.pfw.Units;var TrafficMapObject=nokia.maps.pfw.TrafficMapObject;var ReferencePrinter=nokia.maps.pfw.ReferencePrinter;var DeviceModel=nokia.maps.pfw.DeviceModel;var SncApplicationModel=nokia.maps.pfw.SncApplicationModel;var TouchApplicationModel=nokia.maps.pfw.TouchApplicationModel;var TouchApplicationPlayer=nokia.maps.pfw.TouchApplicationPlayer;eval(nokia.aduno.utils.getImportCode());eval(nokia.aduno.dom.getImportCode());eval(nokia.aduno.medosui.getImportCode());eval(nokia.aduno.i18n.getImportCode());var SettingsMenu=new Class({Extends:Container,Name:"SettingsMenu",_tabList:null,_optionList:null,_selectedIndex:0,initialize:function(aTemplate,aTemplateLibrary,aApplicationModel){this._super(aTemplate,aTemplateLibrary);this._optionList=[];this._selectedIndex=0;this._application=aApplicationModel;this._tabList=new List();this.setChildAt(this._tabList,"tabHeaders");this._popupListContainer=new List();this.setChildAt(this._popupListContainer,"popupLists",false,true);this._menuOptionList=new List();this.setChildAt(this._menuOptionList,"options",false,true);this.hide()},addOptionMenu:function(aOptionMenu){aOptionMenu.setApplicationModel(this._application);this._popupListContainer.addChild(aOptionMenu.getPopupList());this._tabList.addChild(aOptionMenu.createTabIcon());this._menuOptionList.addChild(aOptionMenu);this._optionList.push(aOptionMenu);aOptionMenu.update();aOptionMenu.addEventHandler(SettingsMenuOption.EVENT_POPUPLIST,this._onPopupList,this)},removeOptionMenu:function(aOptionMenu){this._popupListContainer.removeChild(aOptionMenu.getPopupList());this._tabList.removeChild(aOptionMenu.createTabIcon());var menu=this;Collection.forEach(this._optionList,function(aValue,aKey){if(aOptionMenu===aValue){menu._optionList.splice(aKey,1)}})},_getSelectedTab:function(){return this._tabList._children[this._selectedIndex]},_getSelectedOption:function(){return this._optionList[this._selectedIndex]},setSelectedOption:function(aIndex){this._getSelectedOption().hide();this._selectedIndex=aIndex;this._getSelectedTab().focus();this._getSelectedOption().show()},_onPopupList:function(aEvent){var eventData=aEvent.getData();if(eventData.opened){this.hideSettingsMenu()}else{if(eventData.closed){this.showSettingsMenu()}}},hideSettingsMenu:function(){this._tabList.hide();this._optionList[this._selectedIndex].hide();this._addCssClass("nmp_RouteSettingsMenuHidden")},showSettingsMenu:function(){this.show();this._tabList.show();this._optionList[this._selectedIndex].show();this._removeCssClass("nmp_RouteSettingsMenuHidden");this.focus();this.focusOnActive()},focusOnActive:function(){this._getSelectedTab().focus();this._getSelectedOption().show()},handleKey:function(aKeyEvent){var handled=this._super(aKeyEvent);if(!handled&&aKeyEvent.keyDown){switch(aKeyEvent.getKey()){case KeyEventManager.KEY_LEFT:if(this._selectedIndex>0){this.setSelectedOption(this._selectedIndex-1)}else{this.setSelectedOption(this._optionList.length-1)}handled=true;break;case KeyEventManager.KEY_RIGHT:if(this._selectedIndex<this._optionList.length-1){this.setSelectedOption(this._selectedIndex+1)}else{this.setSelectedOption(0)}handled=true;break;case KeyEventManager.KEY_RSK:this.fireEvent(new nokia.aduno.utils.Event("closed",{cancel:true}));handled=true;break;case KeyEventManager.KEY_UP:case KeyEventManager.KEY_DOWN:case KeyEventManager.KEY_CSK:handled=this._getSelectedOption().handleKey(aKeyEvent);break;case KeyEventManager.KEY_LSK:this.fireEvent(new nokia.aduno.utils.Event("closed",{cancel:false}));handled=true;break;default:break}}return handled}});var SettingsMenuOption=new Class({Extends:Container,Name:"SettingsMenuOption",_name:null,_items:[],_selectedIndex:0,_popupList:null,_itemList:null,initialize:function(aTemplate,aTemplateLibrary,aSettingsOption){this._super(aTemplate,aTemplateLibrary);this._name=aSettingsOption.name;this._items=aSettingsOption.items;this.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._replica.setText("label",aSettingsOption.label);var itemList=new SelectionList();this._tabIcon=new Control("SettingsMenuOptionsTab");Collection.forEach(this._items,function(aItem,aId){var label=new Label(null,aItem.caption);label.hide();itemList.addChild(label)});this.setChildAt(itemList,"items",false,true);this._itemList=itemList;this._popupList=this._createPopupList();this._itemList._children[0].show();this.hide()},_createPopupList:function(){var popupList=new KeyControlledList("SettingsMenuOptionsPopupList");popupList.addEventHandler(KeyControlledList.EVENT_SELECTED,this._onPopupListSelected,this);popupList.addEventHandler(KeyControlledList.EVENT_CLOSE,this._closePopupList,this);Collection.forEach(this._items,function(aItem,aId){var itemContainer=new Container("SettingsMenuOptionsPopupListItem");itemContainer._replica.addCssClass("popupListItemIcon",aItem.css);itemContainer._replica.setText("popupListItemLabel",aItem.caption);itemContainer.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);popupList.addChild(itemContainer)});popupList.hide();return popupList},getPopupList:function(){return this._popupList},createTabIcon:function(){this._tabIcon.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._tabIcon._addCssClass(this.getCurrentTabCss());return this._tabIcon},setApplicationModel:function(aApplicationModel){this._application=aApplicationModel},handleKey:function(aKeyEvent){var handled=this._super(aKeyEvent);var oldOptionItem=null;if(!handled&&aKeyEvent.keyDown){switch(aKeyEvent.getKey()){case KeyEventManager.KEY_UP:if(this._selectedIndex>0){this._setSelectionIndex(this._selectedIndex-1)}else{this._setSelectionIndex(this._itemList._children.length-1)}handled=true;break;case KeyEventManager.KEY_DOWN:if(this._selectedIndex<(this._itemList._children.length-1)){this._setSelectionIndex(this._selectedIndex+1)}else{this._setSelectionIndex(0)}handled=true;break;case KeyEventManager.KEY_CSK:this._popupList.focusChild(this._selectedIndex);this._openPopupList();handled=true;break;default:break}}return handled},_setSelectionIndex:function(aIndex){if(aIndex===this._selectedIndex){return}var newItem=this._items[aIndex];this._updateUi(this._items,newItem.css,aIndex);this.changeValue(newItem.value,true);this._selectedIndex=aIndex},_openPopupList:function(){this._popupList.focus();this._popupList.show();this._application.pushSettings();this._application.setButtonLabels("smo.btnselect","smo.btncancel");this.fireEvent(new nokia.aduno.utils.Event(SettingsMenuOption.EVENT_POPUPLIST,{opened:true},false))},_closePopupList:function(){this._application.popSettings();this._popupList.hide();this.fireEvent(new nokia.aduno.utils.Event(SettingsMenuOption.EVENT_POPUPLIST,{closed:true},false))},_onPopupListSelected:function(aEvent){var index=aEvent.getData().selectedIndex;if(index!==this._selectedIndex){this._setSelectionIndex(index)}this._closePopupList()},_updateUi:function(aOptionItems,aNewCssClass,aNewSelectionIndex){if(aNewSelectionIndex<0||aNewSelectionIndex>=this._itemList._children.length){nokia.aduno.utils.warn("Used invalid index for setting an option.");return}for(var i=0,len=aOptionItems.length;i<len;i++){var cssClass=aOptionItems[i].css;if(cssClass!=aNewCssClass){this._tabIcon._removeCssClass(cssClass)}}this._tabIcon._addCssClass(aNewCssClass);this._itemList._children[this._selectedIndex].hide();this._itemList._children[aNewSelectionIndex].show();this._selectedIndex=aNewSelectionIndex},update:function(){},changeValue:function(aValue){}});SettingsMenuOption.EVENT_OPTION_CHANGE="currentOptionChanged";SettingsMenuOption.EVENT_POPUPLIST="popupList";var SettingsMenuOptionMulti=new Class({Extends:Container,Name:"SettingsMenuOptionMulti",_name:null,_label:null,_items:null,_selectedIndex:0,_popupList:null,_checkButtons:[],_popupListCheckButtons:[],initialize:function(aTemplate,aTemplateLibrary,aSettingsOption){this._super(aTemplate,aTemplateLibrary);this._name=aSettingsOption.name;this._items=aSettingsOption.items;this._tabIcon=new Control("SettingsMenuOptionsTab");var itemList=new SelectionList();Collection.forEach(this._items,function(aItem,aId){var iconOptionMulti=new CheckButton("Control");iconOptionMulti._addCssClass(aItem.cssChild);itemList.addChild(iconOptionMulti);this._checkButtons[aItem.value]=iconOptionMulti},this);this._popupList=this._createPopupList();this.setChildAt(itemList,"items",false,true);this.hide()},getPopupList:function(){return this._popupList},_createPopupList:function(){var popupListMulti=new KeyControlledList("SettingsMenuOptionsPopupList",null);popupListMulti.addEventHandler(KeyControlledList.EVENT_SELECTED,this._onPopupListSelected,this);popupListMulti.addEventHandler(KeyControlledList.EVENT_FOCUSED_CHILD,this._onPopupListFocusedChild,this);popupListMulti.addEventHandler(KeyControlledList.EVENT_CLOSE,this._closePopupList,this);Collection.forEach(this._items,function(aItem,aId){var checkBox=new CheckButton("SettingsMenuOptionsPopupListItemMultiCheck",aItem.caption,"checkBoxAvoid",false);checkBox._addCssClass(aItem.cssChild);checkBox.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);popupListMulti.addChild(checkBox);this._popupListCheckButtons[aItem.value]=checkBox},this);popupListMulti.hide();popupListMulti.focusChild(0);return popupListMulti},createTabIcon:function(){this._tabIcon.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._tabIcon._addCssClass(this.getCurrentTabCss());return this._tabIcon},setApplicationModel:function(aApplicationModel){this._application=aApplicationModel},handleKey:function(aKeyEvent){var handled=this._super(aKeyEvent);if(!handled&&aKeyEvent.keyDown){switch(aKeyEvent.getKey()){case KeyEventManager.KEY_LSK:case KeyEventManager.KEY_CSK:this._openPopupList();handled=true;break;default:handled=true;break}}return handled},_openPopupList:function(){this._popupList.focus();this._popupList.show();this._application.pushSettings();this.updateButtons(null,this._popupList._focusedChild.getState());this.fireEvent(new nokia.aduno.utils.Event(SettingsMenuOption.EVENT_POPUPLIST,{opened:true}))},_closePopupList:function(){this._popupList.hide();this._application.popSettings();this.fireEvent(new nokia.aduno.utils.Event(SettingsMenuOption.EVENT_POPUPLIST,{closed:true}))},_onPopupListFocusedChild:function(aEvent){var index=aEvent.getData().selectedIndex;var aState=aEvent.getData().selection.getState();this._selectedIndex=index;this.updateButtons(this._items[index],aState)},_onPopupListSelected:function(aEvent){var index=aEvent.getData().selectedIndex;var item=this._items[index];var popupCheckButton=aEvent.getData().selection;var aNewState=!popupCheckButton.getState();popupCheckButton.setState(aNewState);this._checkButtons[item.value].setState(aNewState);this.changeSettings(item.value,aNewState);this.updateButtons(this._items[index],aNewState)},setItemState:function(aItemName,aState){this._checkButtons[aItemName].setState(aState);this._popupListCheckButtons[aItemName].setState(aState)},update:function(){if(this._popupList.isVisible()){this._popupList.focus()}},updateButtons:function(aValue,aState){}});var TransportationModeSettings=new Class({Extends:SettingsMenuOption,initialize:function(aRouteSettingsModel,aRouteModel){this._options={name:Route.OPTION_MODE,items:[{value:Route.TRANSPORTATION_MODE_CAR,caption:"sms.captiondrive",css:"nmp_SettingsIconCar"},{value:Route.TRANSPORTATION_MODE_PEDESTRIAN,caption:"sms.captionwalk",css:"nmp_SettingsIconWalk"}],label:"sms.lbltransportation"};this._super("RouteSettingsMenuOption",null,this._options);this._model=aRouteSettingsModel;this._model.addEventHandler(RouteSettingsModel.EVENT_TRANSPORTATION_MODE,this.update,this);this._routing=aRouteModel},getCurrentTabCss:function(){switch(this._model.getTransportationMode()){case Route.TRANSPORTATION_MODE_CAR:return"nmp_SettingsIconCar";case Route.TRANSPORTATION_MODE_PEDESTRIAN:return"nmp_SettingsIconWalk"}nokia.aduno.utils.warn("Used unknown route type");return""},changeValue:function(aValue){this._model.setTransportationMode(aValue)},update:function(){var index=-1;switch(this._model.getTransportationMode()){case Route.TRANSPORTATION_MODE_CAR:index=0;break;case Route.TRANSPORTATION_MODE_PEDESTRIAN:index=1;break;default:return index}this._updateUi(this._options.items,this.getCurrentTabCss(),index);return index}});var RouteTypeSettings=new Class({Extends:SettingsMenuOption,initialize:function(aRouteSettingsModel,aRouteModel){this._options={name:Route.OPTION_TYPE,items:[{value:Route.ROUTE_TYPE_FASTEST,caption:"rts.fastest",css:"nmp_SettingsIconFastest"},{value:Route.ROUTE_TYPE_SHORTEST,caption:"rts.shortest",css:"nmp_SettingsIconShortest"},{value:Route.ROUTE_TYPE_OPTIMIZED,caption:"rts.optimized",css:"nmp_SettingsIconOptimized"}],label:"rts.lblmain",template:"RouteSettingsMenuOption"};this._super("RouteSettingsMenuOption",null,this._options);this._model=aRouteSettingsModel;this._model.addEventHandler(RouteSettingsModel.EVENT_ROUTE_TYPE,this.update,this);this._routing=aRouteModel},getCurrentTabCss:function(){switch(this._model.getRouteType()){case Route.ROUTE_TYPE_FASTEST:return"nmp_SettingsIconFastest";case Route.ROUTE_TYPE_SHORTEST:return"nmp_SettingsIconShortest";case Route.ROUTE_TYPE_OPTIMIZED:return"nmp_SettingsIconOptimized"}warn("Used unknown route type");return""},changeValue:function(aValue){this._model.setRouteType(aValue)},update:function(){var index=-1;switch(this._model.getRouteType()){case Route.ROUTE_TYPE_FASTEST:index=0;break;case Route.ROUTE_TYPE_SHORTEST:index=1;break;case Route.ROUTE_TYPE_OPTIMIZED:index=2;break}this._updateUi(this._options.items,this.getCurrentTabCss(),index);return index}});var BlockersSettings=new Class({Extends:SettingsMenuOptionMulti,initialize:function(aModel){var options={name:Route.OPTION_AVOID,items:[{value:Route.ROUTE_BLOCKER_MOTORWAYS,caption:"bs.motorways",css:"nmp_SettingsIconAvoid",cssChild:"nmp_SettingsIconAvoidAll nmp_SettingsIconAvoidMotorways"},{value:Route.ROUTE_BLOCKER_FERRIES,caption:"bs.ferries",css:"nmp_SettingsIconAvoid",cssChild:"nmp_SettingsIconAvoidAll  nmp_SettingsIconAvoidFerries"},{value:Route.ROUTE_BLOCKER_TUNNELS,caption:"bs.tunnels",css:"nmp_SettingsIconAvoid",cssChild:"nmp_SettingsIconAvoidAll nmp_SettingsIconAvoidTunnels"},{value:Route.ROUTE_BLOCKER_TOLLROADS,caption:"bs.tollroads",css:"nmp_SettingsIconAvoid",cssChild:"nmp_SettingsIconAvoidAll nmp_SettingsIconAvoidTollRoads"},{value:Route.ROUTE_BLOCKER_UNPAVEDROADS,caption:"bs.dirtroads",css:"nmp_SettingsIconAvoid",cssChild:"nmp_SettingsIconAvoidAll nmp_SettingsIconAvoidDirtroads"},{value:Route.ROUTE_BLOCKER_MOTORAILTRAINS,caption:"bs.motorails",css:"nmp_SettingsIconAvoid",cssChild:"nmp_SettingsIconAvoidAll nmp_SettingsIconAvoidMotorailTrains"}],label:"",template:"",optionType:1};this._super("RouteSettingsMenuOptionMulti",null,options);this._model=aModel;aModel.addEventHandler(RouteSettingsModel.EVENT_BLOCKERS,this.update,this);aModel.addEventHandler(RouteSettingsModel.EVENT_TRANSPORTATION_MODE,this.update,this)},getCurrentTabCss:function(){return"nmp_SettingsIconAvoid"},changeSettings:function(aSetting,aBlocked){var enabled=!aBlocked;switch(aSetting){case Route.ROUTE_BLOCKER_MOTORWAYS:this._model.setAllowHighways(enabled);break;case Route.ROUTE_BLOCKER_FERRIES:this._model.setAllowFerries(enabled);break;case Route.ROUTE_BLOCKER_TUNNELS:this._model.setAllowTunnels(enabled);break;case Route.ROUTE_BLOCKER_FERRIES:this._model.setAllowFerries(enabled);break;case Route.ROUTE_BLOCKER_TOLLROADS:this._model.setAllowTollroads(enabled);break;case Route.ROUTE_BLOCKER_UNPAVEDROADS:this._model.setAllowUnpavedRoads(enabled);break;case Route.ROUTE_BLOCKER_MOTORAILTRAINS:this._model.setAllowMotorailTrain(enabled);break}},update:function(aEvent){if(aEvent&&aEvent.getData().value){var blockers=aEvent.getData().value;switch(blockers){case Route.ROUTE_BLOCKER_MOTORWAYS:this.setItemState(Route.ROUTE_BLOCKER_MOTORWAYS,!this._model.getAllowHighways());break;case Route.ROUTE_BLOCKER_TUNNELS:this.setItemState(Route.ROUTE_BLOCKER_TUNNELS,!this._model.getAllowTunnels());break;case Route.ROUTE_BLOCKER_FERRIES:this.setItemState(Route.ROUTE_BLOCKER_FERRIES,!this._model.getAllowFerries());break;case Route.ROUTE_BLOCKER_TOLLROADS:this.setItemState(Route.ROUTE_BLOCKER_TOLLROADS,!this._model.getAllowTollroads());break;case Route.ROUTE_BLOCKER_UNPAVEDROADS:this.setItemState(Route.ROUTE_BLOCKER_UNPAVEDROADS,!this._model.getAllowUnpavedRoads());break;case Route.ROUTE_BLOCKER_MOTORAILTRAINS:this.setItemState(Route.ROUTE_BLOCKER_MOTORAILTRAINS,!this._model.getAllowMotorailTrain());break}}else{this.setItemState(Route.ROUTE_BLOCKER_MOTORWAYS,!this._model.getAllowHighways());this.setItemState(Route.ROUTE_BLOCKER_TUNNELS,!this._model.getAllowTunnels());this.setItemState(Route.ROUTE_BLOCKER_FERRIES,!this._model.getAllowFerries());this.setItemState(Route.ROUTE_BLOCKER_TOLLROADS,!this._model.getAllowTollroads());this.setItemState(Route.ROUTE_BLOCKER_UNPAVEDROADS,!this._model.getAllowUnpavedRoads());this.setItemState(Route.ROUTE_BLOCKER_MOTORAILTRAINS,!this._model.getAllowMotorailTrain())}this._super()},updateButtons:function(aValue,aState){if(aState){this._application.setButtonLabels("bs.btnunblock","bs.btnclose")}else{this._application.setButtonLabels("bs.btnblock","bs.btnclose")}}});var KeyControlledList=new Class({Name:"KeyControlledList",Extends:SelectionList,_maxScrollItems:0,_currentScroll:0,initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._focusedChildIndex=-1},handleKey:function(aKeyEvent){var handled=false;if(this._focusedChild&&this._focusedChild._isFocused){handled=this._focusedChild.handleKey(aKeyEvent)}if(!handled&&aKeyEvent.keyDown){switch(aKeyEvent.getKey()){case KeyEventManager.KEY_UP:this.moveChildFocus(-1,true);this.scrollList(false);handled=true;break;case KeyEventManager.KEY_DOWN:this.moveChildFocus(1,true);this.scrollList(true);handled=true;break;case KeyEventManager.KEY_CSK:case KeyEventManager.KEY_LSK:this.fireEvent(new nokia.aduno.utils.Event(KeyControlledList.EVENT_SELECTED,{selectedIndex:this._focusedChildIndex,selection:this._focusedChild},false));handled=true;break;case KeyEventManager.KEY_RSK:this.fireEvent(new nokia.aduno.utils.Event(KeyControlledList.EVENT_CLOSE,null,false));handled=true;break;default:handled=true;break}}return handled},moveChildFocus:function(aDelta,aRollOver){this._focusedChildIndex+=aDelta;if(aRollOver){if(this._focusedChildIndex>=this._children.length){this._focusedChildIndex-=this._children.length}else{if(this._focusedChildIndex<0){this._focusedChildIndex+=this._children.length}}}else{if(this._focusedChildIndex>=this._children.length){this._focusedChildIndex=this._children.length-1}else{if(this._focusedChildIndex<0){this._focusedChildIndex=0}}}this.focusChild(this._focusedChildIndex);this.fireEvent(new nokia.aduno.utils.Event(KeyControlledList.EVENT_FOCUSED_CHILD,{selectedIndex:this._focusedChildIndex,selection:this._focusedChild},false))},focusChild:function(aIndex){this._focusedChildIndex=aIndex;this._children[aIndex].focus();this._focusedChild=this._children[aIndex];return true},focus:function(){var focused=this._super();if(focused&&this._children.length>0&&this._focusedChildIndex>=0){this._children[this._focusedChildIndex].focus();this._focusedChild=this._children[this._focusedChildIndex]}return focused},blur:function(){var blurred=this._super();if(blurred&&this._children.length>0&&this._focusedChildIndex>=0&&this._children[this._focusedChildIndex]._isFocused){this._children[this._focusedChildIndex].blur()}return blurred},focusFirst:function(){if(this._children.length>0){this._focusedChildIndex=0;return this.focus()}return false}});KeyControlledList.EVENT_SELECTED="selected";KeyControlledList.EVENT_FOCUSED_CHILD="focusedChild";KeyControlledList.EVENT_CLOSE="closed";var PrintView=new Class({Name:"PrintView",Extends:Container,_route:null,_map:null,_translator:null,_spice:null,_waypointList:null,_printViewMainContainer:null,initialize:function(aRoute,aTranslator,aSpice,aTemplate,aTemplateLibrary,aMap){if(!aTemplate||!aTemplateLibrary){aTemplate="PrintView";aTemplateLibrary=PrintView.PrintViewTemplateLibrary}this._super(aTemplate,aTemplateLibrary);this._route=aRoute;this._map=aMap;this._translator=aTranslator;this._spice=aSpice;Units.setDefaultTranslator(this._translator);printViewMainContainer=new Container("MainWayPointsContainer",aTemplateLibrary);headerImage=new Image("HeaderImage",this._spice.getOption("pfwPath")+"images/ui/web/print-hdr.png");topCurveImage=new Image("TopCurveImage",this._spice.getOption("pfwPath")+"images/ui/web/content-top-curve.png");bottomCurveImage=new Image("BottomCurveImage",this._spice.getOption("pfwPath")+"images/ui/web/bottom-curve.png");routeTitleContainer=new Container("RouteTitle",aTemplateLibrary);printButton=new Button("PrintButton",this._translator.translate("__I18N_nokia.maps.pfw.spices.routing.btnprint__"));printButton.addEventHandler("selected",this._printWindow,this);this._routeName=new Label("routeName",this._getRouteName());this._routeInfo=new Label("",this._getRouteInfo());routeTitleContainer.setChildAt(this._routeName,"routeName",false,false);routeTitleContainer.setChildAt(this._routeInfo,"routeInfo",false,false);this._barImage=new Image("barImage",this._spice.getOption("pfwPath")+"images/ui/web/title-bottom-border.png");routeTitleContainer.setChildAt(this._barImage,"barImage",false,false);if(this._route){this._waypointList=new List("WaypointList",aTemplateLibrary);this._createManeuverList();printViewMainContainer.setChildAt(this._waypointList,"waypoints",false,false)}else{var imageTest=new Image("ImageTest","");printViewMainContainer.setChildAt(imageTest,"waypoints",false,false)}var bottom=new Container("Bottom",aTemplateLibrary);bottom.setChildAt(printButton,"printButton",false,false);bottom.setChildAt(bottomCurveImage,"bottomCurve",false,false);this.setChildAt(headerImage,"logo",false,false);this.setChildAt(topCurveImage,"topCurve",false,false);this.setChildAt(bottom,"bottom",false,false);this.setChildAt(bottomCurveImage,"bottomCurve",false,false);this.setChildAt(routeTitleContainer,"titleContainer",false,false);this.setChildAt(printViewMainContainer,"mainContainer",false,false)},_printWindow:function(){window.print()},_getRouteDistance:function(){var routeLength=0;if(this._route){routeLength=this._route.getLength()}var routeLengthTxt="";if(routeLength>0){routeLengthTxt=Units.toString(Units.getReadableDistance(routeLength,this._map.getMeasurementType()))}else{if(this._map.getMeasurementType()){routeLengthTxt="0 yrds"}else{routeLengthTxt="0 km"}}return(routeLengthTxt)},_getRouteInfo:function(){var routeInfo=this._getRouteDistance()+" | "+this._getRouteDuration();return(routeInfo)},_getRouteDuration:function(){var routeDuration=0;if(this._route){routeDuration=this._route.getDuration()}var routeDurationTxt="";if(routeDuration>0){routeDurationTxt=Units.toString(Units.getReadableTime(routeDuration))}else{routeDurationTxt="0 min"}return(routeDurationTxt)},_getRouteName:function(){var routeName="";if(this._route.getName()){routeName=this._route.getName()}else{routeName=this._translator.translate("__I18N_nokia.maps.pfw.spices.webwaypointspice.totaldistanceandtime__")}return(routeName)},_getIconLetter:function(aIndex){var letter="";var i=65+aIndex;if(i>90){var remainder=String.fromCharCode(i%91+65);letter=String.fromCharCode(i/91+64)+""+remainder}else{letter=String.fromCharCode(i)}return letter.toLowerCase()},_createManeuverList:function(){var maneuvers=this._route.getManeuvers();var waypoints=this._route.getWaypoints();if(maneuvers||waypoints){var currentWaypointIndex=0;var maneuverIndex=0;var waypointIndex=1;var waypointNativeIndex=0;var testindex=0;for(var j=0,leng=waypoints.length;j<leng;j++){index=waypointIndex+j;var waypoint=waypoints[j];var waypointListItem=new WaypointListItem(waypoint,index,"WaypointItem",PrintView.PrintViewTemplateLibrary,this._spice);waypointListItem.removeCSSTrigger(Control.CSS_TRIGGER_OVER);this._waypointList.addChildAt(index,waypointListItem);var imageIconWay=new Image("WaypointIcon",this._spice.getOption("pfwPath")+"images/ui/web/waypointsicons/endwayicon_"+this._getIconLetter(j)+".png");waypointListItem.setChildAt(imageIconWay,"waypoint",false,false)}for(var i=0,len=maneuvers.length;i<len;i++){index=waypointIndex+i+testindex;maneuverIndex++;var maneuver=maneuvers[i];if(maneuver.getWaypointIndex()!==null&&index!==1){testindex++}var maneuverListItem=new ManeuverListItem(maneuver,"ManeuverItem",PrintView.PrintViewTemplateLibrary,this._map,this._translator);maneuverListItem.removeCSSTrigger(Control.CSS_TRIGGER_OVER);maneuverListItem.setIndex(maneuverIndex+".");var imageIcon=new Image("ManeuverIcon",this._spice.getOption("pfwPath")+"images/ui/web/maneuvericons/"+maneuver.getIcon()+".gif");maneuverListItem.setChildAt(imageIcon,"maneuver",false,false);this._waypointList.addChildAt(index,maneuverListItem)}}}});PrintView.PrintViewTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({PrintView:'<div class="nmp_PrintView"><div id="logo" class="nmp_logo"></div><div id="topCurve" class="nmp_topCurve"></div><div id="titleContainer"></div><div id="mainContainer"></div><div id="bottom"></div><div id="bottomCurve"></div><div id="disclaimer" class="nmp_bottomText"></div></div>',MainWayPointsContainer:'<div class="test"><div id="waypoints" class="waypointsListTest2"></div></div>',WaypointList:'<div class="nmp_WaypointListPrint"></div>',WaypointItem:'<div id="item" class="nmp_WaypointsItem_Container"><div class="nmp_WaypointsItem"><div  id="waypoint" class="nmp_WaypointPrintIcon"><span id="icon"></span></div><div id="place" class="nmp_Label nmp_WaypointsItem_Place"></div><div id="street" class="nmp_WaypointsItem_Label nmp_WaypointsItem_Street"></div><div id="button" class="nmp_WaypointsItem_Delete"></div></div><div class="nmp_WaypointSwitchContainer"><div id="switch"></div></div></div>',ManeuverItem:'<div class="nmp_ManeuverContainer"><div class="nmp_ManeuverItem"><div id="maneuver" class="nmp_IconPrint"></div><div class="nmp_ManeuverItem_Label"><span id="index" class="nmp_ManeuverItem_Index"></span><span id="description" class="nmp_ManeuverItem_Description"></span></div><div id="distance" class="nmp_ManeuverItem_Distance"><span id="distanceFromPrevious" class="nmp_ManeuverItem_DistanceFromPrevious"></span><span id="distanceFromStart" class="nmp_ManeuverItem_DistanceFromStart"></span></div></div><div class="nmp_ManeuverItemFooter"></div></div>',ManeuverIcon:'<div class="nmp_imageManeuver"><img id="image" width="30" height="30"></img></div>',WaypointIcon:'<div class="nmp_imageWaypoint"><img id="image" width="40" height="40"></img></div>',HeaderImage:'<div class="nmp_headerImage"><img id="image"></img></div>',TopCurveImage:'<div class="nmp_topCurveImage"><img id="image"></img></div>',Bottom:'<div class="nmp_Bottom"><div id="printButton"></div></div>',BottomCurveImage:'<div class="nmp_bottomCurveImage"><img id="image"></img></div>',LeftRouteTitleImage:'<div class="nmp_leftRouteTitleImage"><img id="image"></img></div>',RightRouteTitleImage:'<div class="nmp_rightRouteTitleImage"><img id="image"></img></div>',RouteTitle:'<div class="nmp_routeTitleContainer"><div class="nmp_routePrint"><div class="nmp_routeInfos" id="routeTitleContainer"><div class="nmp_routeNamePrint"><div id="routeName"></div></div><div class="nmp_routeInfoPrint"><div id="routeInfo"></div></div></div><div class="nmp_barImageRoutePrint"><div id="barImage"></div></div></div></div>',RouteName:'<div class="nmp_routeNamePrint"></div>',RouteInfo:'<div class="nmp_routeInfoPrint"></div>',PrintButton:'<div id="PrintButton" class="nmp_PrintButton"><span id="button"></span></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var ProgressBar=new Class({Name:"ProgressBar",Extends:Control,_vertical:false,_maximum:1,_value:0,initialize:function(aTemplate,aTemplateLibrary,aVertical){this._super(aTemplate,aTemplateLibrary);if(aVertical===true){this._vertical=true}},setMaximum:function(aMaximum){this._maximum=aMaximum;this._updateUi()},setValue:function(aValue){this._value=aValue;this._updateUi()},_updateUi:function(){var percentage=this._value*100/this._maximum;if(percentage<0){percentage=0}else{if(percentage>100){percentage=100}}if(this._vertical){this._replica.setStyle("progress","height",percentage+"%")}else{this._replica.setStyle("progress","width",percentage+"%")}}});var SncApplicationUi=new Class({Name:"SncApplicationUi",_currentContextMenuHandler:null,_currentDialogHandler:null,_applicationModel:null,initialize:function(aPage,aApplicationModel){this._applicationModel=aApplicationModel;this._currentContextMenuHandler={};this._currentDialogHandler={};this._page=aPage;this._titleBar=new Label("TitleBar");aPage.setChildAt(this._titleBar,"titlebar",false,false);aApplicationModel.addVisibleAreaRestrictionControl(this._titleBar,{top:true});this._bottomBar=new Container("BottomBar");aPage.setChildAt(this._bottomBar,"bottombar",false,false);aApplicationModel.addVisibleAreaRestrictionControl(this._bottomBar,{bottom:true});this._leftButton=new Button("LeftButton");this._centerButton=new Button("CenterButton");this._rightButton=new Button("RightButton");this._bottomBar.setChildAt(this._leftButton,"leftButton",true);this._bottomBar.setChildAt(this._centerButton,"centerButton",true);this._bottomBar.setChildAt(this._rightButton,"rightButton",true);aApplicationModel.addEventHandler(ApplicationModel.EVENT_BUTTONS_CHANGED,this._onButtonsChanged,this);aApplicationModel.addEventHandler(ApplicationModel.EVENT_TITLE_CHANGED,this._onTitleChanged,this);aApplicationModel.addEventHandler(ApplicationModel.EVENT_SHOW_MESSAGEBOX,this._onShowMessageBox,this);aApplicationModel.addEventHandler(ApplicationModel.EVENT_SHOW_CONTEXT_MENU,this._onShowContextMenu,this);aApplicationModel.addEventHandler(ApplicationModel.EVENT_TITLEBAR_VISIBILTIY_CHANGED,this._onTitlebarChanged,this);this._contextMenuContainer=new Container("ContextMenuContainer");this._contextMenu=new KeyControlledList("ContextMenu");this._contextMenu.addEventHandler("selected",this._onContextMenuClosed,this);this._contextMenu.addEventHandler("closed",this._onContextMenuClosed,this);this._contextMenuContainer.hide();this._contextMenuContainer.setChildAt(this._contextMenu,"contextMenuContainer",true);aPage.setChildAt(this._contextMenuContainer,"ContextMenu",true);this._dialog=new KeyControlledDialog("ModalDialog");this._dialog.addEventHandler("closed",this._onDialogClosed,this);this._dialog.hide();aPage.setChildAt(this._dialog,"ModalDialog",true);this._attachButtonClickHandlers()},_onTitleChanged:function(aTitleEvent){var titleData=aTitleEvent.getData();this._titleBar.setText(titleData.title)},_onButtonsChanged:function(aButtonEvent){var buttonData=aButtonEvent.getData();this._leftButton.setText(buttonData.lsk);this._rightButton.setText(buttonData.rsk)},_onTitlebarChanged:function(aTitlebarEvent){if(aTitlebarEvent.getData().titlebarEnabled){this._page.getReplica().removeCssClass("nmp_HiddenTitleBar")}else{this._page.getReplica().addCssClass("nmp_HiddenTitleBar")}},_onButtonbarChanged:function(aButtonbarEvent){if(aButtonbarEvent.getData().buttonbarEnabled){this._page.getReplica().removeCssClass("nmp_HiddenButtonBar")}else{this._page.getReplica().addCssClass("nmp_HiddenButtonBar")}},_onShowMessageBox:function(aDialogEvent){var dialogData=aDialogEvent.getData();this._currentDialogHandler.handler=dialogData.handler;this._currentDialogHandler.handlerContext=dialogData.handlerContext;this._currentDialogHandler.data=dialogData.data;this._applicationModel.pushSettings();if(dialogData.items&&dialogData.items.length>=2){this._applicationModel.setButtonLabels(dialogData.items[0],dialogData.items[1])}else{this._applicationModel.setButtonLabels("scnui.btnclose","")}this._dialog.setTitle(dialogData.text);this._dialog.show();this._dialog.focus()},_onDialogClosed:function(aEvent){var eventData={data:this._currentDialogHandler.data,cancel:aEvent.getData().cancel};this._applicationModel.popSettings();this._dialog.hide();this._currentDialogHandler.handler.apply(this._currentDialogHandler.handlerContext,[new nokia.aduno.utils.Event("closed",eventData)])},_onShowContextMenu:function(aContextMenuEvent){var contextMenuData=aContextMenuEvent.getData();this._currentContextMenuHandler.handler=contextMenuData.handler;this._currentContextMenuHandler.handlerContext=contextMenuData.handlerContext;this._currentContextMenuHandler.data=contextMenuData.data;for(var i=0,len=contextMenuData.items.length;i<len;i++){var curItem=contextMenuData.items[i];var menuItem=new MenuListItem(i,curItem.icon,curItem.label,null,"ContextMenuItem");menuItem.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._contextMenu.addChild(menuItem)}this._contextMenu.focusChild(0);this._applicationModel.pushSettings();this._applicationModel.setButtonLabels("sncui.btnselect","sncui.btncancel");this._contextMenuContainer.show()},_onContextMenuClosed:function(aEvent){this._contextMenuContainer.hide();this._contextMenu.removeAllChildren();this._applicationModel.popSettings();if(this._currentContextMenuHandler.handler){var eventData={data:this._currentContextMenuHandler.data};if(aEvent.getType()=="selected"){eventData.cancel=false;eventData.selectedIndex=aEvent.getData().selectedIndex;eventData.selectedId=aEvent.getData().selection.getId()}else{eventData.selectedIndex=-1;eventData.cancel=true}this._currentContextMenuHandler.handler.apply(this._currentContextMenuHandler.handlerContext,[new nokia.aduno.utils.Event("closed",eventData)]);this._currentContextMenuHandler.handler=null;this._currentContextMenuHandler.handlerContext=null}},_attachButtonClickHandlers:function(){this._leftButton.addEventHandler("selected",this._leftButtonClicked,this);this._centerButton.addEventHandler("selected",this._centerButtonClicked,this);this._rightButton.addEventHandler("selected",this._rightButtonClicked,this)},_leftButtonClicked:function(aClickEvent){this._injectKeyDownEvent(aClickEvent,KeyEventManager.KEY_LSK)},_centerButtonClicked:function(aClickEvent){this._injectKeyDownEvent(aClickEvent,KeyEventManager.KEY_CSK)},_rightButtonClicked:function(aClickEvent){this._injectKeyDownEvent(aClickEvent,KeyEventManager.KEY_RSK)},_injectKeyDownEvent:function(aClickEvent,aKeyCode){var keyEvent=document.createEvent("UIEvents");keyEvent.initUIEvent("keydown",true,true,document.defaultView,0);var domEvent=new nokia.dom.Event(keyEvent,document);domEvent.save();domEvent._eventCopy.keyCode=aKeyCode;domEvent._originalEvent=domEvent._eventCopy;var handled=PlayerManager.keyEventManager.onKeyDown(domEvent);if(handled){aClickEvent.preventDefault()}}});var KeyControlledDialog=new Class({Extends:Dialog,Name:"KeyControlledDialog",initialize:function(aTemplate,aTemplateLibrary,aTitle){this._super(aTemplate,aTemplateLibrary,aTitle,true)},handleKey:function(aKeyEvent){var handled=false;if(!handled&&aKeyEvent.keyDown){switch(aKeyEvent.getKey()){case KeyEventManager.KEY_LSK:this.fireEvent(new nokia.aduno.utils.Event(KeyControlledDialog.EVENT_CLOSE,{cancel:false}));handled=true;break;case KeyEventManager.KEY_RSK:this.fireEvent(new nokia.aduno.utils.Event(KeyControlledDialog.EVENT_CLOSE,{cancel:true}));handled=true;break;default:handled=true;break}}return handled}});KeyControlledDialog.EVENT_CLOSE="closed";var DropDownList=new Class({Extends:SelectionList,Name:"DropDownList",initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._focusedChildIndex=-1},_onSelected:function(aEvent){var target=aEvent.source;if(target===this._selection){return}var oldSelection=this._selection;this.clearSelection();this._selection=target;if(this._selection&&this._selection._replica){this._selection._replica.setAttribute(TemplateReplica.ROOT_ID,"selected","selected")}this.fireEvent(new nokia.aduno.utils.Event("selected",{selection:this._selection,previous:oldSelection,selectedIndex:this.getSelectionIndex(),itemData:aEvent.getData()}))},clearSelection:function(){if(this._selection){if(this._selection._replica){this._selection._replica.removeAttribute(TemplateReplica.ROOT_ID,"selected")}}this._selection=null}});var ManeuverListItem=new Class({Name:"ManeuverListItem",Extends:ListItem,_maneuver:null,_currentIconCss:null,_showManeuverOnMouseOver:false,_index:null,initialize:function(aManeuver,aTemplate,aTemplateLibrary,aMapModel,aTranslator){if(!aTemplate||!aTemplateLibrary){aTemplate="ManeuverItem";aTemplateLibrary=ManeuverListItem.ManeuverListItemTemplateLibrary}this._super(aTemplate,aTemplateLibrary);this.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_CLICK,this,this._onItemClick);this.setManeuver(aManeuver,aMapModel,aTranslator)},setManeuver:function(aManeuver,aMapModel,aTranslator){this._maneuver=aManeuver;this._updateNextManeuverIcon(this._maneuver._icon);var description;var distanceData=Units.getReadableDistance(this._maneuver._distanceFromPrevious,aMapModel.getMeasurementType());var totalDistanceData=Units.getReadableDistance(this._maneuver._distanceFromStart,aMapModel.getMeasurementType());var format={street:'<span class="nmp_ManeuverItem_Street">{0}</span>',signpost:'<span class="nmp_ManeuverItem_Signpost">{0}</span>'};if(this._maneuver._displayStreetName){description=this._maneuver.getDescription(aTranslator,true,format);this.getReplica().setInnerHtml("description",description)}else{description=this._maneuver.getDescription(aTranslator);this.getReplica().setText("description",description)}this.getReplica().setText("distanceFromPrevious",distanceData.value+" "+aTranslator.translate(distanceData.unit));if(nokia.maps.pfw.layout.web&&totalDistanceData){this.getReplica().setText("distanceFromStart",aTranslator.translate("__I18N_nokia.maps.pfw.maneuver.totaldistance__")+" "+totalDistanceData.value+" "+aTranslator.translate(totalDistanceData.unit))}return this},setIndex:function(aIndex){this._index=aIndex;this.getReplica().setText("index",aIndex)},_updateNextManeuverIcon:function(aIcon){var newIconCss="nmp_"+aIcon;if(this._currentIconCss!==null){this._container.getReplica().removeCssClass("maneuver",this._currentIconCss)}this.getReplica().addCssClass("maneuver",newIconCss);this._currentIconCss=newIconCss},setShowManeuverOnMouseOver:function(aShow){this._showManeuverOnMouseOver=aShow},_cssTriggerOver:function(aEvent){this._addCssClass("nmp_ManeuverMouseOver");if(this._showManeuverOnMouseOver){this.fireEvent(new nokia.aduno.utils.Event(Maneuver.SHOW_MANEUVER_ON_MAP,{maneuver:this._maneuver},false))}},_cssTriggerOut:function(aEvent){this._super(aEvent);this._removeCssClass("nmp_ManeuverMouseOver");if(this._showManeuverOnMouseOver){this.fireEvent(new nokia.aduno.utils.Event(Maneuver.HIDE_MANEUVER_ON_MAP,{maneuver:this._maneuver},false))}},_onItemClick:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event(ManeuverListItem.EVENT_MANEUVER_SELECTED,{maneuver:this._maneuver}),false)}});ManeuverListItem.EVENT_MANEUVER_SELECTED="maneuverListItemSelected";ManeuverListItem.ManeuverListItemTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({ManeuverItem:'<div class="nmp_ManeuverItem"><div id="maneuver" class="nmp_Icon"></div><div class="nmp_ManeuverItem_Label nmp_ManeuverItem_TurnAndStreet"><span class="nmp_ManeuverItem_Label nmp_ManeuverItem_Description" id="description"></span></div><div id="distanceFromPrevious" class="nmp_ManeuverItem_Label nmp_ManeuverItem_Distance"></div></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var WaypointListItem=new Class({Name:"WaypointListItem",Extends:ListItem,Implements:EventSource,_waypoint:null,_index:null,_spice:null,initialize:function(aWaypoint,aIndex,aTemplate,aTemplateLibrary,aSpice,aAddCssTriggers,aIsDraggable){if(!aTemplate||!aTemplateLibrary){aTemplate="WaypointItem";aTemplateLibrary=WaypointListItem.WaypointListItemTemplateLibrary}this._super(aTemplate,aTemplateLibrary);this._waypoint=aWaypoint;this._index=aIndex;this._currentSlot=aIndex;this._oldSlot=aIndex;this._spice=aSpice;this.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_CLICK,this,this._onItemClick);if(aAddCssTriggers===false){this.removeCSSTrigger(Control.CSS_TRIGGER_DOWN)}else{this.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this.setCSSTrigger(Control.CSS_TRIGGER_DOWN)}this._updateUi(aWaypoint,aIndex)},_updateUi:function(aWaypoint,aIndex){if(nokia.maps.pfw.layout.snc||nokia.maps.pfw.layout.touch){if(aWaypoint.isGpsPosition()){this._updateGpsWaypointItemText(aWaypoint)}else{this._updateWaypointItemText(aWaypoint)}var indexText=String.fromCharCode(65+aIndex);this.getReplica().setText("icon",indexText)}else{this._updateWebWaypointItemText(aWaypoint)}},_updateGpsWaypointItemText:function(aWaypoint){var place=null;var description=null;if(aWaypoint.getPosition()===null){place=this._spice.translateString("__I18N_nokia.maps.pfw.ui.waypointlistitem.lookuptext__");description=this._spice.translateString("__I18N_nokia.maps.pfw.ui.waypointlistitem.lookupdesc__");this.getReplica().addCssClass("spinner","nmp_WaypointsItem_Spinner")}else{place=this._spice.translateString("__I18N_nokia.maps.pfw.ui.waypointlistitem.gpsposition__");if(aWaypoint.getPlace()){description=aWaypoint.getPlace()+", "+aWaypoint.getDescription()}else{description=aWaypoint.getDescription()}if(!description){description=Units.getReadableLatLonPosition(aWaypoint.getPosition())}}this.getReplica().setText("place",place);this.getReplica().setText("street",description)},_updateWaypointItemText:function(aWaypoint){var place=aWaypoint.getPlace();var description=aWaypoint.getDescription();if(place&&description){this.getReplica().setText("place",place);this.getReplica().setText("street",description)}else{if(!place&&description){this.getReplica().setText("place",Units.getReadableLatLonPosition(aWaypoint.getPosition()));this.getReplica().setText("street",description)}else{if(place&&!description){this.getReplica().setText("place",place);this.getReplica().setText("street","")}else{if(!place&&!description){this.getReplica().setText("place",Units.getReadableLatLonPosition(aWaypoint.getPosition()));this.getReplica().setText("street","")}}}}this.getReplica().removeCssClass("spinner","nmp_WaypointsItem_Spinner")},_updateWebWaypointItemText:function(aWaypoint){this.getReplica().setText("place",aWaypoint.getPlace());this.getReplica().setText("street",aWaypoint.getAddress())},updateItem:function(){this._updateUi(this._waypoint,this._index)},_onItemClick:function(aEvent){if(!this._dragging){this.fireEvent(new nokia.aduno.utils.Event(WaypointListItem.EVENT_WAYPOINT_SELECTED,{waypoint:this._waypoint,index:this._index}),false)}},setIndex:function(aIndex){this._index=aIndex}});WaypointListItem.EVENT_WAYPOINT_SELECTED="waypointListItemSelected";WaypointListItem.EVENT_DRAG_END="waypointListItemDragEnd";WaypointListItem.WaypointListItemTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({WaypointItem:'<div class="nmp_WaypointsItem"><p id="icon" class="nmp_Icon"></p><div id="place" class="nmp_Label nmp_WaypointsItem_Place"></div><div id="street" class="nmp_Label nmp_WaypointsItem_Street"></div><div id="spinner"></div></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var SearchListItem=new Class({Name:"SearchListItem",Extends:Container,Implements:EventSource,_index:null,_spice:null,initialize:function(aIndex,aTemplate,aTemplateLibrary,aSpice,aAddCssTriggers){if(!aTemplate||!aTemplateLibrary){aTemplate="WaypointSearch";aTemplateLibrary=SearchListItem.SearchListItemTemplateLibrary}this._super(aTemplate,aTemplateLibrary);this._index=aIndex;this._spice=aSpice;if(aAddCssTriggers===false){this.removeCSSTrigger(Control.CSS_TRIGGER_DOWN)}else{this.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this.setCSSTrigger(Control.CSS_TRIGGER_DOWN)}},setIndex:function(aIndex){this._index=aIndex}});SearchListItem.SearchListItemTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({WaypointSearch:'<div id="item" class="nmp_WaypointSearch_Container"><div class="nmp_WaypointSearch"><div id="icon" class="nmp_WaypointIcon nmp_WaypointSearchIcon"></div><div class="nmp_WaypointSearch_BoxContainer"><div id="searchBox"></div></div><div id="suggestionList"></div></div><div class="nmp_WaypointSwitchContainer"><div id="switch"></div></div></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var TouchDialog=new Class({Extends:Container,Name:"TouchDialog",initialize:function(aTemplate,aTemplateLibrary,aTitle){this._super(aTemplate,aTemplateLibrary);this.setTitle(aTitle);this._closeButton=new Button("CloseButton");this._closeButton.addEventHandler("selected",this._onClose,this);this.setChildAt(this._closeButton,"closeButton");this._cancelButton=new Button("CancelButton");this._cancelButton.addEventHandler("selected",this._onCancel,this);this.setChildAt(this._cancelButton,"cancelButton");this._cancelButton.hide()},_onClose:function(aEvent){var bindObj=this;setTimeout(function(){bindObj.fireEvent(new nokia.aduno.utils.Event(TouchDialog.EVENT_CLOSE,bindObj),false)},0)},_onCancel:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event(TouchDialog.EVENT_CANCEL,this),false)},setTitle:function(aTitle){this.getReplica().setText("title",aTitle)},getTitle:function(){return this.getReplica().getText("title")},setCancelButton:function(aEnableCancelButton){if(aEnableCancelButton){this._closeButton.hide();this._cancelButton.show()}else{this._closeButton.show();this._cancelButton.hide()}},expand:function(){this.show()},collapse:function(){this.hide()},close:function(aNoAnimation){if(aNoAnimation){this.fireEvent(new nokia.aduno.utils.Event(TouchDialog.EVENT_CLOSE,{source:this,noAnimation:true}),false)}else{this.fireEvent(new nokia.aduno.utils.Event(TouchDialog.EVENT_CLOSE,this),false)}}});TouchDialog.TouchDialogTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({TouchDialog:'<div class="nmp_TouchDialog"><div id="modal" class="nmp_Background"></div><div class="nmp_Frame"><div id="window" class="nmp_Window"><div id="titlebar" class="nmp_Titlebar"><div class="nmp_LeftCorner"></div><div id="title" class="nmp_Title"></div><div id="closeButton"></div><div id="cancelButton"></div></div><div id="summaryBarContainer"></div><div id="content" class="nmp_TouchDialog_Content"></div><div id="bottom" class="nmp_Bottombar"><div class="nmp_LeftCorner"></div><div class="nmp_Center"></div><div class="nmp_RightCorner"></div></div></div><div class="nmp_BottomLeft"></div><div class="nmp_Bottom"></div><div class="nmp_BottomRight"></div></div></div>',CloseButton:'<div id="button" class="nmp_CloseButton"></div>',CancelButton:'<div id="button" class="nmp_CancelButton"></div>'},nokia.aduno.medosui.DefaultTouchTemplateLibrary);TouchDialog.EVENT_CLOSE="closed";TouchDialog.EVENT_CANCEL="touchDialogCancel";var TouchApplicationUi=new Class({Name:"TouchApplicationUi",_currentContextMenuHandler:null,_currentDialogHandler:null,_touchApplicationModel:null,_positionSelectorHandler:null,_menubarButtonHandler:null,_menuBar:null,_spiceManager:null,_mapModel:null,initialize:function(aPage,aTouchApplicationModel,aMapModel,aSpiceManager,aRoutingModel){this._touchApplicationModel=aTouchApplicationModel;this._mapModel=aMapModel;this._spiceManager=aSpiceManager;this._routingModel=aRoutingModel;this._currentContextMenuHandler={};this._currentDialogHandler={};this._positionSelectorHandler={};this._menubarButtonHandler={};this._page=aPage;this._screen=aPage.getChildAt("screen");this._selector=new Selector(this._touchApplicationModel,this._mapModel,{fps:10},null,null);this._selector.addEventHandler(Selector.EVENT_SELECTOR_HIDE_STARTED,this._onMapShow,this);this._selector.addEventHandler(Selector.EVENT_SELECTOR_SHOW_STARTED,this._onMapHide,this);this._screen.setChildAt(this._selector,"selector",false,false);this._menuBar=new Container("MenuBar");aPage.setChildAt(this._menuBar,"menubar",false,false);this._menubarButton=new Button("MenuBarButton");this._menubarButton.addEventHandler("selected",this._onMenuBarButtonClicked,this);this._menuBar.setChildAt(this._menubarButton,"menubarbutton",false,false);this._touchApplicationModel.addVisibleAreaRestrictionControl(this._menuBar,{top:true});this._menuBar.hide();var closeApplicationButton=new Button("CloseApplicationButton");closeApplicationButton.addEventHandler("selected",this._onCloseApplicationButtonClicked,this);aPage.setChildAt(closeApplicationButton,"closeApplicationButton",true,true);this._touchApplicationModel.addEventHandler(ApplicationModel.EVENT_SELECT_POSITION,this._onStartPositionSelector,this);this._touchApplicationModel.addEventHandler(ApplicationModel.EVENT_TITLEBAR_VISIBILTIY_CHANGED,this._onMenuBarVisible,this);this._touchApplicationModel.addEventHandler(ApplicationModel.EVENT_TITLE_CHANGED,this._onTitlebarTextUpdate,this);this._touchApplicationModel.addEventHandler(TouchApplicationModel.EVENT_CHANGE_TITLEBAR_BUTTON,this._onTitlebarButtonUpdate,this);this._touchApplicationModel.addEventHandler(TouchApplicationModel.EVENT_SHOW_SELECTOR,this._onShowSelector,this);this._touchApplicationModel.addEventHandler(ApplicationModel.EVENT_REGISTER_MODAL_DIALOG,this._onRegisterModalDialog,this);this._touchApplicationModel.addEventHandler(ApplicationModel.EVENT_SHOW_MODAL_DIALOG,this._onShowModalDialog,this);this._touchApplicationModel.addEventHandler(ApplicationModel.EVENT_CLOSE_MODAL_DIALOG,this._onCloseModalDialog,this);this._touchApplicationModel.addEventHandler(ApplicationModel.EVENT_APPLICATION_START,this._onStartRoutePlanning,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculationStopped,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._onRouteCalculationStopped,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_CANCELLED,this._onRouteCalculationStopped,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_PROGRESS,this._onRouteCalculationProgress,this)},_onStartPositionSelector:function(aEvent){this._setLeftClickingBehaviorEnabled(false);var eventData=aEvent.getData();this._selector.hide(false,true);this._positionSelectorHandler.handler=eventData.selectHandler;this._positionSelectorHandler.handlerContext=eventData.handlerContext;this._positionSelectorHandler.data=eventData.data;this._mapModel.addEventHandler(MapModel.EVENT_MAP_CLICKED,this._onPositionOnMapSelected,this);this._touchApplicationModel.setTitle(eventData.title);this._touchApplicationModel.setTitlebarButton(eventData.cancelHandler,eventData.handlerContext,"back");this._touchApplicationModel.setTitlebarEnabled(true)},_onPositionOnMapSelected:function(aEvent){var data=aEvent.getData();var geoCoordinates=this._mapModel.pixelToGeo(data.x,data.y);this._mapModel.removeEventHandler(MapModel.EVENT_MAP_CLICKED,this._onPositionOnMapSelected,this);if(this._positionSelectorHandler.handler){var eventData={position:geoCoordinates,data:this._positionSelectorHandler.data};this._positionSelectorHandler.handler.apply(this._positionSelectorHandler.handlerContext,[new nokia.aduno.utils.Event("positionSelected",eventData)]);this._positionSelectorHandler={}}this._routingModel.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_SHOWN,this._onCurrentRouteShown,this)},_onShowSelector:function(aEvent){var animation=aEvent.getData().animation;var openDialog=aEvent.getData().openDialog;this._selector.show(animation,openDialog)},_onCloseSelectorClicked:function(aEvent){this._selector.hide(true,false)},_onMenuBarVisible:function(aMenuBarEvent){var menuData=aMenuBarEvent.getData();var visible=menuData.menuBarEnabled;if(visible){this._menuBar.show()}else{this._menuBar.hide()}},_setLeftClickingBehaviorEnabled:function(aEnabled){var mouseSpice=this._spiceManager.getSpice("MouseSpice");if(mouseSpice){mouseSpice.setLeftClickingBehaviorEnabled(aEnabled)}else{nokia.aduno.utils.error("Left mouse click behavior could not be switched since there is no MouseSpice")}},_onTitlebarTextUpdate:function(aMenuBarEvent){var menuData=aMenuBarEvent.getData();this._menuBar.getReplica().setText("title",menuData.title);this._menuBar.getReplica().setText("subtitle",menuData.subTitle)},_onTitlebarButtonUpdate:function(aMenuBarEvent){var menuData=aMenuBarEvent.getData();if(this._menubarButtonCss){this._menubarButton.getReplica().removeCssClass("button",this._menubarButtonCss)}if(menuData.buttonType==="cancel"){this._menubarButton.getReplica().addCssClass("button","nmp_Cancel");this._menubarButtonCss="nmp_Cancel"}else{if(menuData.buttonType==="back"){this._menubarButton.getReplica().addCssClass("button","nmp_Back");this._menubarButtonCss="nmp_Back"}}this._menubarButtonHandler.handler=menuData.handler;this._menubarButtonHandler.handlerContext=menuData.handlerContext},_onMenuBarButtonClicked:function(aEvent){if(this._menubarButtonHandler.handler){this._menubarButtonHandler.handler.apply(this._menubarButtonHandler.handlerContext,[new nokia.aduno.utils.Event("menuButtonClicked",aEvent.getData())]);this._menubarButtonHandler.handler=null;this._menubarButtonHandler.handlerContext=null}this._positionSelectorHandler={}},_onCloseApplicationButtonClicked:function(){this._routingModel._pluginControl.shutdown()},_onShowModalDialog:function(aDialogEvent){aDialogEvent.getData().dialog.show()},_onCloseModalDialog:function(aEvent){warn("TODO: Do something with the selector");this._setLeftClickingBehaviorEnabled(true)},_onRegisterModalDialog:function(aEvent){var eventData=aEvent.getData();this._selector.addItem(eventData.id,eventData.image,eventData.label,eventData.dialog,eventData.index)},_onStartRoutePlanning:function(aEvent){this._selector.show(true,true)},_onCurrentRouteShown:function(aEvent){var touchAppUi=this;this._routingModel.removeEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_SHOWN,this._onCurrentRouteShown,this);setTimeout(function(){touchAppUi._touchApplicationModel.showSelector(true,true)},1000)},_onMapHide:function(aEvent){var zoomSpice=this._spiceManager.getSpice("ZoomSpice");zoomSpice.getUi().hide()},_onMapShow:function(aEvent){var zoomSpice=this._spiceManager.getSpice("ZoomSpice");zoomSpice.getUi().show()},_onRouteCalculationStopped:function(){this._menuBar.getReplica().removeCssClass("spinner","nmp_MenuBar_Spinner")},_onRouteCalculationProgress:function(){this._menuBar.getReplica().addCssClass("spinner","nmp_MenuBar_Spinner")}});var SpiceTranslationAdapter=new Class({Name:"SpiceTranslationAdapter",Extends:Control,initialize:function(aControlsToTranslate){this._super("Control");if(aControlsToTranslate){this._controlsToTranslate=[].concat(aControlsToTranslate)}else{this._controlsToTranslate=[]}},addChild:function(aChild){this._controlsToTranslate.push(aChild)},getChildren:function(){return this._controlsToTranslate},show:function(){error("Trying to show the spice translation adapter.")},hide:function(){error("Trying to show the spice translation adapter.")}});var Selector=new Class({Name:"Selector",Extends:Container,Implements:[Options,EventSource],_isSelected:false,_maxSelectorItemIndex:2,_selectorItems:[],_dialogs:null,_map:null,_centralSelectorItemWidth:252,_secondarySelectorWidth:252,_marginLeft:28,_selectorAnimationContainerRelativeDone:false,_selectorAnimationSlideDone:false,_animationDuration:300,options:{fps:25,animationDuration:300},initialize:function(aApplication,aMapModel,aOptions,aTemplateLibrary,aTemplate){if(aOptions){this.setOptions(aOptions)}if(!aTemplate||!aTemplateLibrary){aTemplate="Selector";aTemplateLibrary=Selector.SelectorTemplateLibrary}this._super(aTemplate,aTemplateLibrary);this._application=aApplication;this._dialogs={};this._map=aMapModel;this._selectorContainer=new List("SelectorContainer",aTemplateLibrary);this._backSelector=new Button("BackSelector");this._backSelector.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this,this.hide);this.setChildAt(this._selectorContainer,"selectorContainer",false,false);this.setChildAt(this._backSelector,"backSelector",false,false);this._animation=new Container("Animations",aTemplateLibrary);this._application.registerModalDialog("animation","","animation",this._animation,false);this._fps=this.getOption("fps");this._animationDuration=this.getOption("animationDuration")},getDefaultSelectorItem:function(){return(this._selectorItems[0])},clearItems:function(){if(this._selectorItems){this._selectorItems=[]}},addItem:function(aId,aImage,aLabel,aDialog){var selectorItem=new SelectorItem("SelectorItem",null,this._selectorItems.length,aId,aImage,aLabel);selectorItem.addEventHandler("selected",this._onItemSelected,this);this._isSelectorToBeClosed=false;if(aDialog){this._dialogs[aId]=aDialog;this._dialogs[aId].addEventHandler(TouchDialog.EVENT_CLOSE,this._onCloseModalDialog,this)}this._selectorItems.push(selectorItem)},_onItemSelected:function(aEvent){var dialog=aEvent.source;if(dialog){this._openDialog(dialog)}},_openDialog:function(aSelectorItem){this._application.openModalDialog("animation");this._animation.getReplica().addCssClass("nm_Hidden");this._animation.removeChild(this._animationImage);this._animationImage=new Container();this._animationImage.getReplica().addCssClass("nmn_SelectorItemImage");this._animation.setChildAt(this._animationImage,"animImage",false,false);var currentSelectedItemPosition=nokia.aduno.dom.Dimensions.getPosition(aSelectorItem.getNode());var currentSelectedItemSize=nokia.aduno.dom.Dimensions.getSize(aSelectorItem.getNode());this._animation.getReplica().setStyle("anim","height",currentSelectedItemSize.y+"px");this._animation.getReplica().setStyle("anim","width",currentSelectedItemSize.x+"px");this._animation.getReplica().setStyle("anim","left",currentSelectedItemPosition.x+"px");this._animation.getReplica().setStyle("anim","top",currentSelectedItemPosition.y+"px");this._animation.getReplica().removeCssClass("nm_Hidden");var dialogSize=this._map.getMapSize();var animatePopOut=new nokia.aduno.medosui.Fx(this._animation);this._currentSelectedItem=aSelectorItem;this._dialogEffect(animatePopOut,"expand",this._animationDuration,null,currentSelectedItemPosition,dialogSize,currentSelectedItemSize).addEventHandler("ended",this._onEndOpenDialog,this)},_onEndOpenDialog:function(aEvent){this._application.openModalDialog(this._currentSelectedItem.getId());this._application.closeModalDialog("animation");this._isSelectorToBeClosed=false;this._currentSelectedItem.addEventHandler("closed",this.closeCurrentItem,this)},_onCloseModalDialog:function(aEvent){this.closeCurrentItem(null,aEvent.data.noAnimation)},closeCurrentItem:function(aEndCloseDialogHandler,noAnimation){if(this._currentSelectedItem){this._currentSelectedItem.removeEventHandler("closed",this.closeCurrentItem,this);if(noAnimation){if(aEndCloseDialogHandler){}else{this._animation.getReplica().addCssClass("nm_Hidden");this.getReplica().addCssClass("nm_Hidden");this._application.closeModalDialog("animation");this._application.closeModalDialog(this._currentSelectedItem.getId());this._lastSelectedItem=this._currentSelectedItem;this._currentSelectedItem=null;this.hide()}}else{if(!this._animation){return}this._animation.removeChild(this._animationImage);this._animationImage=new Container();this._animationImage.getReplica().addCssClass("nmn_SelectorItemImage");this._animation.setChildAt(this._animationImage,"animImage",false,false);var currentSelectedItemPosition=nokia.aduno.dom.Dimensions.getPosition(this._currentSelectedItem.getNode());var currentSelectedItemSize=nokia.aduno.dom.Dimensions.getSize(this._currentSelectedItem.getNode());var dialogSize=this._map.getMapSize();var animatePopIn=new nokia.aduno.medosui.Fx(this._animation);var dialogEffect=this._dialogEffect(animatePopIn,"collapse",this._animationDuration,null,currentSelectedItemPosition,dialogSize,currentSelectedItemSize);if(aEndCloseDialogHandler){dialogEffect.addEventHandler("ended",aEndCloseDialogHandler)}else{dialogEffect.addEventHandler("ended",this._endCloseDialog,this)}this._application.closeModalDialog(this._currentSelectedItem.getId());this._application.openModalDialog("animation")}}},_endCloseDialog:function(){this._animation.getReplica().addCssClass("nm_Hidden");this._application.closeModalDialog("animation");this._application.closeModalDialog(this._currentSelectedItem.getId());this._lastSelectedItem=this._currentSelectedItem;this._currentSelectedItem=null;this.hide()},reopenLastItem:function(){this.show(this._lastSelectedItem)},hide:function(){this._visible=false;this._selectorAnimationContainerRelativeDone=false;this._selectorAnimationSlideDone=false;this._selectorFx=new nokia.aduno.medosui.Fx(this);this._slideEffect(this._selectorFx,"up",this._animationDuration);this._selectorFx.addEventHandler("ended",this._onHideFinished,this);this._selectorItemsFx=new nokia.aduno.medosui.Fx(this._selectorContainer);this.fireEvent(Selector.EVENT_SELECTOR_HIDE_STARTED)},hideWithoutAnimation:function(){this.getReplica().addCssClass("nm_Hidden")},_onHideFinished:function(){this._selectorFx.removeEventHandler("ended",this._onHideFinished,this);this.fireEvent(Selector.EVENT_SELECTOR_HIDE_FINISHED);this.getReplica().addCssClass("nm_Hidden")},show:function(aSelectorItem){this.getReplica().removeCssClass("nm_Hidden");if(aSelectorItem){this._dialogToOpen=aSelectorItem}else{this._dialogToOpen=null}this._visible=true;if(this._selectorItems.length!==this._selectorContainer._children.length){Collection.forEach(this._selectorItems,function(aSelectorItem,aId){if(aSelectorItem){this._selectorContainer.addChild(aSelectorItem)}},this)}this._selectorFx=new nokia.aduno.medosui.Fx(this);this._selectorFx.addEventHandler("ended",this._onShowFinished,this);this._slideEffect(this._selectorFx,"down",this._animationDuration);this._isSelected=true;this.fireEvent(Selector.EVENT_SELECTOR_SHOW_STARTED)},showDialog:function(aSelectorItemId){this.show(this._getSelectorItem(aSelectorItemId))},_onShowFinished:function(){this._selectorFx.removeEventHandler("ended",this._onShowFinished,this);this.fireEvent(Selector.EVENT_SELECTOR_SHOW_FINISHED);if(this._dialogToOpen){this._openDialog(this._dialogToOpen)}},_dialogEffect:function(aEffect,aDirection,aDuration,aIntialPause,currentSelectedItemPosition,dialogSize,currentSelectedItemSize){var styles={left:[10,currentSelectedItemPosition.x],top:[10,currentSelectedItemPosition.y],width:[dialogSize.width-20,currentSelectedItemSize.x],height:[dialogSize.height-20,currentSelectedItemSize.y]};if(aDirection==="expand"){styles.left=[currentSelectedItemPosition.x,10];styles.top=[currentSelectedItemPosition.y,10];styles.width=[currentSelectedItemSize.x,dialogSize.width-20];styles.height=[currentSelectedItemSize.y,dialogSize.height-20]}return this._doEffect(aEffect,styles,aDuration,aIntialPause)},_slideEffect:function(aEffect,aDirection,aDuration,aIntialPause){var styles={top:[0,-268]};if(aDirection==="down"){styles.top=[-268,0]}return this._doEffect(aEffect,styles,aDuration,aIntialPause)},_fadeEffect:function(aEffect,aDirection,aDuration,aIntialPause){var styles={opacity:[0,1]};if(aDirection==="out"){styles.opacity=[1,0]}return this._doEffect(aEffect,styles,aDuration,aIntialPause)},_doEffect:function(aEffect,aStyles,aDuration,aIntialPause){if(aIntialPause&&aIntialPause>0){var pauseStyles={};for(var i=0,len=aStyles.length;i<len;i++){pauseStyles[i]=[aStyles[i][0],aStyles[i][0]]}aEffect.effect({duration:aIntialPause,fps:this._fps,styles:pauseStyles})}aEffect.effect({duration:aDuration,fps:this._fps,styles:aStyles,combineStyles:true});aEffect.start();return aEffect},_getSelectorItem:function(aId){for(var i=0;i<this._selectorItems.length;i++){if(this._selectorItems[i].getId()==aId){return this._selectorItems[i]}}return null},switchDialog:function(aId){var that=this;this.closeCurrentItem(function(){that._animation.getReplica().addCssClass("nm_Hidden");that._application.closeModalDialog("animation");that._application.closeModalDialog(that._currentSelectedItem.getId());that._lastSelectedItem=that._currentSelectedItem;that._currentSelectedItem=null;that._openDialog(that._getSelectorItem(aId))})}});Selector.EVENT_SELECTOR_HIDE_STARTED="selector: hide started";Selector.EVENT_SELECTOR_HIDE_FINISHED="selector: hide finished";Selector.EVENT_SELECTOR_SHOW_STARTED="selector: show started";Selector.EVENT_SELECTOR_SHOW_FINISHED="selector: show finished";Selector.SelectorTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({BackSelector:'<div class="nmn_BackSelector"></div>',Selector:'<div class="nmn_Selector nm_Hidden"><div class="nmn_centerDivSelector"><div id="selectorContainer"></div></div><div id="backSelector"></div></div><div id="animations"></div>',SelectorContainer:'<div class="nmn_centerContainerSelector"></div>',SelectorItem:'<div class="nmn_SelectorItem" id="selectorItem"></div>',selectorItemButton:'<div class="nmn_SelectorItemButton" id="selectorItemButton"><div id="button" class="nmn_SelectorItemButtonText"></div></div>',Animations:'<div class="nmn_Animation" id="anim"><div id="animImage"></div></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var SelectorItem=new Class({Extends:Container,Name:"SelectorItem",_id:null,_imageFile:null,_label:null,initialize:function(aTemplate,aTemplateLibrary,aIndex,aId,aImage,aLabel){this._super(aTemplate,aTemplateLibrary);this._id=aId;this._index=aIndex;this._imageFile=aImage;this._button=new Button("selectorItemButton",aLabel);this._button._addCssClass("nmn_selectorItem"+aIndex);this.setChildAt(this._button,"selectorItem",false,false);this._button.addEventHandler("selected",this._onClick,this)},_onClick:function(aEvent){this.fireEvent(new nokia.aduno.utils.Event("selected",{id:this._id}))},getImageFile:function(fakePath){if(fakePath){return this._imageFile.substring(6)}else{return this._imageFile}},getId:function(){return this._id}});var TouchRouteSummary=new Class({Extends:Container,Name:"TouchRouteSummary",Implements:[Destroyable],initialize:function(aTemplate,aTemplateLibrary,aRoutingModel,aMapModel,aParentSpice){this._super(aTemplate,aTemplateLibrary);this._routing=aRoutingModel;this._parentSpice=aParentSpice;this._map=aMapModel;aRoutingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_STARTED,this._onRouteCalculationStarted,this);aRoutingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculated,this);aRoutingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._onRouteCalculateError,this);aRoutingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_CANCELLED,this._onRouteCalculationCancelled,this);aRoutingModel.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._onCurrentRouteChanged,this);this.getReplica().setText("routeLabel",this._parentSpice.translateString("__I18N_nokia.maps.pfw.spices.touchroutesummary.route__"));this._updateRouteInfo()},_updateRouteInfo:function(){var aRoute=this._routing.getCurrentRoute();var routeLength=0;var routeDuration=0;if(aRoute){routeLength=aRoute.getLength();routeDuration=aRoute.getDuration()}var routeLengthTxt=Units.getReadableDistance(routeLength,this._map.getMeasurementType());var routeDurationTxt=Units.getReadableTime(routeDuration);if(routeLength===0){routeLengthTxt.value=this._parentSpice.translateString("__I18N_nokia.maps.pfw.spices.touchroutesummary.noroutelength__")}if(routeDuration===0){routeDurationTxt.value=this._parentSpice.translateString("__I18N_nokia.maps.pfw.spices.touchroutesummary.norouteduration__")}this.getReplica().setText("routeLabel",this._parentSpice.translateString("__I18N_nokia.maps.pfw.spices.touchroutesummary.route__"));this.getReplica().setText("routeInfoValue",routeLengthTxt.value+" "+this._parentSpice.translateString(routeLengthTxt.unit)+" / "+routeDurationTxt.value+" "+this._parentSpice.translateString(routeDurationTxt.unit))},_onRouteCalculateError:function(aRouteEvent){this.getReplica().removeCssClass("routeCalculationNotifier","nmp_RouteInCalculation");this._updateRouteInfo()},_onRouteCalculated:function(aRouteEvent){this.getReplica().removeCssClass("routeCalculationNotifier","nmp_RouteInCalculation");this._updateRouteInfo()},_onRouteCalculationCancelled:function(aRouteEvent){this.getReplica().removeCssClass("routeCalculationNotifier","nmp_RouteInCalculation");this._updateRouteInfo()},_onRouteCalculationStarted:function(aRouteEvent){var bindObj=this;setTimeout(function(){bindObj.getReplica().setText("routeLabel",bindObj._parentSpice.translateString("__I18N_nokia.maps.pfw.spices.routeinfospice.calcprogress__"));bindObj.getReplica().setText("routeInfoValue","");bindObj.getReplica().addCssClass("routeCalculationNotifier","nmp_RouteInCalculation")},1)},_onWaypointsChanged:function(aEvent){this._updateRouteInfo()},_onCurrentRouteChanged:function(aRouteChangeEvent){var newRoute=aRouteChangeEvent.getData().newRoute;var oldRoute=aRouteChangeEvent.getData().oldRoute;this.getReplica().removeCssClass("routeCalculationNotifier","nmp_RouteInCalculation");this._updateRouteInfo()},accept:function(aVisitor){}});TouchRouteSummary.TouchRouteSummaryTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({TouchRouteSummary:'<div id="top" class="nmp_RouteSummary_Container"><span id="routeLabel" class="nmp_Label"></span> <span id="routeInfoValue" class="nmp_Label"></span><div class="nmp_RouteCalculationInProgressIndicator"><div id="routeCalculationNotifier"/></div></div>'},nokia.aduno.medosui.DefaultTouchTemplateLibrary);var ListScrollable=new Class({Name:"ListScrollable",Extends:Scrollable,_scrollOffset:null,_currentScroll:null,_maxScrollItems:null,setControl:function(aControl){if(typeof aControl.addChild=="function"){this._super(aControl);aControl.addEventHandler("changed",this._onListChanged,this)}else{error("ListScrollable behavior can only be used for List controls.")}},_onListChanged:function(){if(this._control.getReplica()._replicaElement){this._scrollOffset=this._control.getReplica()._replicaElement.offsetHeight/this._control._children.length;this._maxScrollItems=Math.floor(this.getRootElement().offsetHeight/this._scrollOffset);this._currentScroll=1}},scrollList:function(aScrollDown){if(this._scrollOffset===null){this._onListChanged()}if(this._currentScroll===0){this.scrollToPos(0,0);this._currentScroll=1}else{if(this._focusedChildIndex===this._control._children.length-1){this.scrollToPos(0,this._control._children.length*this._scrollOffset);this._currentScroll=this._maxScrollItems}else{if(aScrollDown){if(this._currentScroll<this._maxScrollItems){this._currentScroll++}else{this.scrollToPos(0,this.getRootElement().scrollTop+this._scrollOffset)}}else{if(this._currentScroll>1){this._currentScroll--}else{this.scrollToPos(0,this.getRootElement().scrollTop-this._scrollOffset)}}}}}});var EnableButton=new Class({Name:"EnableButton",Extends:Button,_enabled:true,setEnabled:function(aEnabled){if(!!aEnabled){this.getReplica().removeCssClass("nmp_Disabled")}else{this.getReplica().addCssClass("nmp_Disabled")}this._enabled=aEnabled},isEnabled:function(){return this._enabled},_onClick:function(aEvent){if(this._enabled){this._super(aEvent)}}});nokia.maps.pfw.ui.addMembers({SettingsMenu:SettingsMenu,SettingsMenuOption:SettingsMenuOption,SettingsMenuOptionMulti:SettingsMenuOptionMulti,TransportationModeSettings:TransportationModeSettings,RouteTypeSettings:RouteTypeSettings,BlockersSettings:BlockersSettings,KeyControlledList:KeyControlledList,PrintView:PrintView,ProgressBar:ProgressBar,SncApplicationUi:SncApplicationUi,KeyControlledDialog:KeyControlledDialog,DropDownList:DropDownList,ManeuverListItem:ManeuverListItem,WaypointListItem:WaypointListItem,SearchListItem:SearchListItem,TouchDialog:TouchDialog,TouchApplicationUi:TouchApplicationUi,SpiceTranslationAdapter:SpiceTranslationAdapter,Selector:Selector,SelectorItem:SelectorItem,TouchRouteSummary:TouchRouteSummary,ListScrollable:ListScrollable,EnableButton:EnableButton})};new function(){new nokia.aduno.Ns("nokia.maps.pfw.spices");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 DiscoveryFramework=nokia.maps.dfw.DiscoveryFramework;var layout=nokia.maps.pfw.layout;var Serializable=nokia.maps.pfw.Serializable;var Destroyable=nokia.maps.pfw.Destroyable;var MouseEventHandler=nokia.maps.pfw.MouseEventHandler;var PluginLogger=nokia.maps.pfw.PluginLogger;var PluginControl=nokia.maps.pfw.PluginControl;var Location=nokia.maps.pfw.Location;var MapObject=nokia.maps.pfw.MapObject;var MapMarker=nokia.maps.pfw.MapMarker;var Layer=nokia.maps.pfw.Layer;var MapPolyline=nokia.maps.pfw.MapPolyline;var MapPolygon=nokia.maps.pfw.MapPolygon;var Spice=nokia.maps.pfw.Spice;var Player=nokia.maps.pfw.Player;var PlayerManager=nokia.maps.pfw.PlayerManager;var MapModel=nokia.maps.pfw.MapModel;var ZoomModel=nokia.maps.pfw.ZoomModel;var PersistenceModel=nokia.maps.pfw.PersistenceModel;var ConnectivityModel=nokia.maps.pfw.ConnectivityModel;var PositionModel=nokia.maps.pfw.PositionModel;var RoutingModel=nokia.maps.pfw.RoutingModel;var Route=nokia.maps.pfw.Route;var RouteSettingsModel=nokia.maps.pfw.RouteSettingsModel;var SpiceManager=nokia.maps.pfw.SpiceManager;var MouseEventHandling=nokia.maps.pfw.MouseEventHandling;var GuidanceModel=nokia.maps.pfw.GuidanceModel;var Maneuver=nokia.maps.pfw.Maneuver;var PlacesModel=nokia.maps.pfw.PlacesModel;var SearchModel=nokia.maps.pfw.SearchModel;var SearchStringBuilder=nokia.maps.pfw.SearchStringBuilder;var Waypoint=nokia.maps.pfw.Waypoint;var ReverseGeoCodingModel=nokia.maps.pfw.ReverseGeoCodingModel;var ApplicationModel=nokia.maps.pfw.ApplicationModel;var AppearanceModel=nokia.maps.pfw.AppearanceModel;var PlayerTranslationVisitor=nokia.maps.pfw.PlayerTranslationVisitor;var Units=nokia.maps.pfw.Units;var TrafficMapObject=nokia.maps.pfw.TrafficMapObject;var ReferencePrinter=nokia.maps.pfw.ReferencePrinter;var DeviceModel=nokia.maps.pfw.DeviceModel;var SncApplicationModel=nokia.maps.pfw.SncApplicationModel;var TouchApplicationModel=nokia.maps.pfw.TouchApplicationModel;var TouchApplicationPlayer=nokia.maps.pfw.TouchApplicationPlayer;var SettingsMenu=nokia.maps.pfw.ui.SettingsMenu;var SettingsMenuOption=nokia.maps.pfw.ui.SettingsMenuOption;var SettingsMenuOptionMulti=nokia.maps.pfw.ui.SettingsMenuOptionMulti;var TransportationModeSettings=nokia.maps.pfw.ui.TransportationModeSettings;var RouteTypeSettings=nokia.maps.pfw.ui.RouteTypeSettings;var BlockersSettings=nokia.maps.pfw.ui.BlockersSettings;var KeyControlledList=nokia.maps.pfw.ui.KeyControlledList;var PrintView=nokia.maps.pfw.ui.PrintView;var ProgressBar=nokia.maps.pfw.ui.ProgressBar;var SncApplicationUi=nokia.maps.pfw.ui.SncApplicationUi;var KeyControlledDialog=nokia.maps.pfw.ui.KeyControlledDialog;var DropDownList=nokia.maps.pfw.ui.DropDownList;var ManeuverListItem=nokia.maps.pfw.ui.ManeuverListItem;var WaypointListItem=nokia.maps.pfw.ui.WaypointListItem;var SearchListItem=nokia.maps.pfw.ui.SearchListItem;var TouchDialog=nokia.maps.pfw.ui.TouchDialog;var TouchApplicationUi=nokia.maps.pfw.ui.TouchApplicationUi;var SpiceTranslationAdapter=nokia.maps.pfw.ui.SpiceTranslationAdapter;var Selector=nokia.maps.pfw.ui.Selector;var SelectorItem=nokia.maps.pfw.ui.SelectorItem;var TouchRouteSummary=nokia.maps.pfw.ui.TouchRouteSummary;var ListScrollable=nokia.maps.pfw.ui.ListScrollable;var EnableButton=nokia.maps.pfw.ui.EnableButton;eval(nokia.aduno.utils.getImportCode());eval(nokia.aduno.dom.getImportCode());eval(nokia.aduno.medosui.getImportCode());eval(nokia.aduno.i18n.getImportCode());var ConsoleSpice=new Class({Name:"ConsoleSpice",Extends:Spice,_minimized:true,_expanded:false,_log:null,_showButton:null,_logCapacity:25,_numUnread:0,_externalId:null,initialize:function(aSpiceManager,aExternalPlaceholderId){this._super(aSpiceManager);this._externalId=aExternalPlaceholderId;nokia.aduno.utils.logger.addLogger(this);if(nokia.maps.pfw.layout.snc){this._spiceManager.setKeyHandler(KeyEventManager.KEY_9,0,nokia.aduno.utils.bind(this,this._keyHandler))}},_createUi:function(){return nokia.maps.pfw.layout.snc?this._createUiForS60():this._createUiForWeb()},_createUiForS60:function(){var container=new Container("S60Console",ConsoleSpice.ConsoleSpiceTemplateLibrary);var log=new List("Log");container.setChildAt(log,"log");container.hide();this._log=log;return container},_createUiForWeb:function(){var self=this;var container=nokia.aduno.utils.platform.maemo?new Container("ConsoleMaemo",ConsoleSpice.ConsoleSpiceTemplateLibrary):new Container("Console",ConsoleSpice.ConsoleSpiceTemplateLibrary);var log=new List("Log");var filter=null;var showButton=null;var clearButton=null;var closeButton=null;var expandButton=null;if(nokia.aduno.utils.platform.maemo){filter=new TextInput("TextInputMaemo");showButton=new Button("ConsoleButtonMaemo","Console");clearButton=new Button("ClearButtonMaemo","Clear");closeButton=new Button("CloseButtonMaemo","Close");expandButton=new Button("ExpandButtonMaemo","Up")}else{filter=new TextInput();showButton=new Button("ConsoleButton","Console");clearButton=new Button(null,"Clear");closeButton=new Button(null,"Close")}container.setChildAt(filter,"filter");container.setChildAt(showButton,"showButton");container.setChildAt(clearButton,"clearButton");container.setChildAt(closeButton,"closeButton");container.setChildAt(log,"log");if(nokia.aduno.utils.platform.maemo){container.setChildAt(expandButton,"expandButton")}closeButton.addEventHandler("selected",function(){self._minimized=true;self._numUnread=0;container.getReplica().addCssClass("nmp_MinimizedConsoleSpice");showButton.setText("Console");showButton.show()});clearButton.addEventHandler("selected",function(){log.removeAllChildren()});showButton.addEventHandler("selected",function(){self._minimized=false;container.getReplica().removeCssClass("nmp_MinimizedConsoleSpice");showButton.hide()});if(nokia.aduno.utils.platform.maemo){expandButton.addEventHandler("selected",function(){if(self._expanded){self._expanded=false;log.getReplica().removeCssClass("nmp_LogHighMaemo");expandButton.setText("Up")}else{self._expanded=true;log.getReplica().addCssClass("nmp_LogHighMaemo");expandButton.setText("Down")}})}filter.addEventHandler("changed",function(){var match=filter.getValue().toLowerCase();for(var i=0,c=log.getChildCount();i<c;i++){var entry=log.getChildAt(i);var text=entry.getChildAt("message").getText().toLowerCase();if(text.indexOf(match)>=0){entry.show()}else{entry.hide()}}});this._log=log;this._showButton=showButton;return container},warn:function(aMessage){this._writeToLog("WarningLogEntry",aMessage)},info:function(aMessage){this._writeToLog("InfoLogEntry",aMessage)},error:function(aMessage){this._writeToLog("ErrorLogEntry",aMessage)},debug:function(aMessage){this._writeToLog("DebugLogEntry",aMessage)},_writeToLog:function(aType,aMessage){var timestamp=new Date();var entry=new Container(aType);timestamp=(/\d\d$/.exec("0"+timestamp.getHours()))+":"+(/\d\d$/.exec("0"+timestamp.getMinutes()))+":"+(/\d\d$/.exec("0"+timestamp.getSeconds()));if(nokia.aduno.utils.platform.maemo){entry.setChildAt(new Label("TimestampMaemo",timestamp),"timestamp");entry.setChildAt(new Label("MessageMaemo",aMessage),"message")}else{entry.setChildAt(new Label("Timestamp",timestamp),"timestamp");entry.setChildAt(new Label("Message",aMessage),"message")}this._log.addChildAt(0,entry);while(this._log.removeChildAt(this._logCapacity)){}if(!nokia.maps.pfw.layout.snc&&this._minimized){this._numUnread=Math.min(this._logCapacity,this._numUnread+1);this._showButton.setText("Console ("+this._numUnread+")")}},_onShowConsole:function(){this._scrollY=0;this._log.getRootElement().scrollTop=0;this._spiceControl.show();if(nokia.maps.pfw.layout.snc){this._upHandler=this._spiceManager.removeKeyHandler(KeyEventManager.KEY_UP,0);this._downHandler=this._spiceManager.removeKeyHandler(KeyEventManager.KEY_DOWN,0);if(!this._consoleScrollHandler){this._consoleScrollHandler=nokia.aduno.utils.bind(this,this._scrollKeyHandler)}this._spiceManager.setKeyHandler(KeyEventManager.KEY_UP,0,nokia.aduno.utils.bind(this,this._consoleScrollHandler));this._spiceManager.setKeyHandler(KeyEventManager.KEY_DOWN,0,nokia.aduno.utils.bind(this,this._consoleScrollHandler))}},_onHideConsole:function(){this._spiceControl.hide();if(nokia.maps.pfw.layout.snc){this._spiceManager.removeKeyHandler(KeyEventManager.KEY_UP,0);this._spiceManager.removeKeyHandler(KeyEventManager.KEY_DOWN,0);if(this._upHandler){this._spiceManager.setKeyHandler(KeyEventManager.KEY_UP,0,this._downHandler);this._spiceManager.setKeyHandler(KeyEventManager.KEY_DOWN,0,this._downHandler)}}},_scrollKeyHandler:function(aKeyEvent){var step=15,key=aKeyEvent.getKey();if(key==KeyEventManager.KEY_UP){this._scrollY-=step}else{if(key==KeyEventManager.KEY_DOWN){this._scrollY+=step}}this._log.getRootElement().scrollTop=this._scrollY;this._scrollY=this._log.getRootElement().scrollTop},_keyHandler:function(aKeyEvent){if(aKeyEvent.keyDown){if(this._spiceControl.isVisible()){this._onHideConsole()}else{this._onShowConsole()}}},onAttach:function(){if(this._externalId){var parent=document.getElementById(this._externalId);var child=this._spiceControl.getRootElement();if(parent&&child){parent.appendChild(child)}}}});ConsoleSpice.ConsoleSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({Console:'<div class="nmp_ConsoleSpice nmp_MinimizedConsoleSpice"><div id="theConsole" class="nmp_Console"><div class="nmp_ConsoleToolbar"><input id="filter" /><div style="float: right"><a id="clearButton"></a><a id="closeButton"></a></div><div style="clear: both"></div></div><div id="log"></div></div><a id="showButton"></a></div>',ConsoleMaemo:'<div class="nmp_ConsoleSpice nmp_MinimizedConsoleSpice"><div id="theConsole" class="nmp_Console"><div class="nmp_ConsoleToolbarMaemo"><div id="filter"></div><div class="nmp_ConsoleButtonsBarMaemo"><div id="expandButton"></div><div id="clearButton"></div><div id="closeButton"></div></div><div style="clear: both"></div></div><div id="log"></div></div><div id="showButton"></div></div>',ConsoleButton:'<div class="nmm_Butt nmp_ConsoleButton"><a id="button"></a></div>',ConsoleButtonMaemo:'<div class="nmp_ConsoleButtonMaemo"><div id="button"></div></div>',ClearButtonMaemo:'<div class="nmp_ClearButtonMaemo"><div id="button"></div></div>',CloseButtonMaemo:'<div class="nmp_CloseButtonMaemo"><div id="button"></div></div>',ExpandButtonMaemo:'<div class="nmp_ExpandButtonMaemo"><div id="button"></div></div>',Button:'<div class="nmm_Butt"><a id="button"></a></div>',Timestamp:'<span id="label" class="nmp_ConsoleTimestamp"></span>',Message:'<span id="label"></span>',TimestampMaemo:'<span id="label" class="nmp_ConsoleTimestampMaemo"></span>',MessageMaemo:'<span id="label" class="nmp_ConsoleTimestampMaemo"></span>',TextInput:'<div style="float: left"><input id="input" type="text" /></div>',TextInputMaemo:'<div style="float: left"><input class="nmp_InputFilterMaemo" id="input" type="text" /></div>',Log:'<div class="nmp_Log"></div>',InfoLogEntry:'<div class="nmp_InfoLogEntry"><span id="timestamp"></span><span id="message"></span></div>',DebugLogEntry:'<div class="nmp_DebugLogEntry"><span id="timestamp"></span><span id="message"></span></div>',WarningLogEntry:'<div class="nmp_WarningLogEntry"><span id="timestamp"></span><span id="message"></span></div>',ErrorLogEntry:'<div class="nmp_ErrorLogEntry"><span id="timestamp"></span><span id="message"></span></div>',S60Console:'<div class="nmp_S60ConsoleSpice"><div class="nmp_S60ConsoleOverlay"></div><div id="log"></div></div>'});var KeyMapPanSpice=new Class({Name:"KeyMapPanSpice",Extends:Spice,interval:nokia.aduno.utils.browser.s60?120:66,baseSpeed:nokia.aduno.utils.browser.s60?18:15,maximumSpeedUp:nokia.aduno.utils.browser.s60?70:60,maximumSpeedTime:nokia.aduno.utils.browser.s60?2000:3500,singleClickSpeed:nokia.aduno.utils.browser.s60?26:null,initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._keyrepeater={left:false,right:false,up:false,down:false,repeater:null,elapsedTime:0};this._mapModel=aMapModel;var keyBind=bind(this,this._handleKeys);aSpiceManager.setKeyHandler(KeyEventManager.KEY_RIGHT,0,keyBind);aSpiceManager.setKeyHandler(KeyEventManager.KEY_LEFT,0,keyBind);aSpiceManager.setKeyHandler(KeyEventManager.KEY_UP,0,keyBind);aSpiceManager.setKeyHandler(KeyEventManager.KEY_DOWN,0,keyBind);aSpiceManager.addEventHandler(SpiceManager.EVENT_BLUR,this._onBlur,this)},_handleKeys:function(aKeyEvent){if(aKeyEvent.keyPress||aKeyEvent.keyLongPress){return}var key=aKeyEvent.getKey();if(aKeyEvent.keyUp&&this._keyrepeater.repeater&&this._keyrepeater.elapsedTime<150){this._doKeyRepeating(this.singleClickSpeed)}if(key===KeyEventManager.KEY_RIGHT){this._keyrepeater.right=aKeyEvent.keyDown}else{if(key===KeyEventManager.KEY_LEFT){this._keyrepeater.left=aKeyEvent.keyDown}}if(key===KeyEventManager.KEY_UP){this._keyrepeater.up=aKeyEvent.keyDown}else{if(key===KeyEventManager.KEY_DOWN){this._keyrepeater.down=aKeyEvent.keyDown}}if(this._keyrepeater.left||this._keyrepeater.right||this._keyrepeater.up||this._keyrepeater.down){if(!this._keyrepeater.repeater){this._keyrepeater.repeater=nokia.aduno.utils.setPeriodical(this.interval,this,this._doKeyRepeating);this._lastTime=new Date().getTime()}}else{if(aKeyEvent.keyUp&&this._keyrepeater.repeater){nokia.aduno.utils.cancelPeriodical(this._keyrepeater.repeater);this._keyrepeater.repeater=null;this._keyrepeater.elapsedTime=0}}},_distanceByTime:function(aElapsedTime){var x=Math.min(1,aElapsedTime/this.maximumSpeedTime);return(x*x)*this.maximumSpeedUp+this.baseSpeed},_doKeyRepeating:function(aDist){var offset={x:0,y:0};var dist=aDist;var newTime=0;if(!dist){dist=Math.floor(this._distanceByTime(this._keyrepeater.elapsedTime));newTime=new Date().getTime();var elapsed=(newTime-this._lastTime);this._keyrepeater.elapsedTime+=elapsed;dist*=(elapsed/this.interval)}if(this._keyrepeater.right){offset.x+=dist}if(this._keyrepeater.left){offset.x-=dist}if(this._keyrepeater.up){offset.y-=dist}if(this._keyrepeater.down){offset.y+=dist}this._lastTime=newTime;this._mapModel.jumpByPixel(offset.x,offset.y)},_onBlur:function(){if(this._keyrepeater&&this._keyrepeater.repeater){nokia.aduno.utils.cancelPeriodical(this._keyrepeater.repeater);this._keyrepeater.repeater=null;this._keyrepeater.elapsedTime=0;this._keyrepeater.right=false;this._keyrepeater.left=false;this._keyrepeater.up=false;this._keyrepeater.down=false}}});var MouseSpice=new Class({Name:"MouseSpice",Extends:Spice,_leftClickingBehaviorEnabled:true,initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._mapModel=aMapModel;var dragBind=bind(this,this._onDrag);var leftClickBind=bind(this,this._onClick);this._mouseUpBind=bind(this,this._onMouseUp);this._spiceManager.setDragHandler(dragBind);this._spiceManager.setMouseClickHandler(SpiceManager.MOUSE_BUTTON_LEFT,SpiceManager.MOUSE_CLICK_SINGLE,leftClickBind);this._spiceManager.addEventHandler(SpiceManager.EVENT_DRAGGING_DELEGATED,this._delegatedDragHandler,this);this._alreadyRegistered=false;this._setupJS=!this._mapModel.getPluginControl().isPluginInUse();this._animationTime=this._setupJS?500:1000;this._animationTimeSquare=Math.pow(this._animationTime,2);this._publicMethods=["handleOnClick"]},setLeftClickingBehaviorEnabled:function(aEnabled){this._leftClickingBehaviorEnabled=!!aEnabled},isLeftClickingBehaviorEnabled:function(){return this._leftClickingBehaviorEnabled},_onDrag:function(aDragData){if(!this._alreadyRegistered){this._spiceManager.setMouseUpHandler(this._mouseUpBind);this._alreadyRegistered=true;this._mapModel.setDetailLevel(MapModel.DETAIL_LEVEL_MID);this._mapModel.onDragStart()}else{if(aDragData.button===0){this._mapModel.setDetailLevel(MapModel.DETAIL_LEVEL_HIGH);this._mapModel.onDragDone();this._spiceManager.removeMouseUpHandler(this._mouseUpBind);this._alreadyRegistered=false;this._lastDragTime=0;return}}this._lastDragTime=new Date().getTime();if(this._setupJS){var xValue=aDragData.deltaX;var yValue=aDragData.deltaY;if(Math.abs(aDragData.deltaX)>MouseSpice.MAX_SPEED){xValue=(aDragData.deltaX>0?1:-1)*MouseSpice.MAX_SPEED}if(Math.abs(aDragData.deltaY)>MouseSpice.MAX_SPEED){yValue=(aDragData.deltaY>0?1:-1)*MouseSpice.MAX_SPEED}this._lastDragMovement=[-xValue,-yValue]}else{this._lastDragMovement=[-aDragData.deltaX,-aDragData.deltaY]}this._mapModel.jumpByPixel(-aDragData.deltaX,-aDragData.deltaY)},_delegatedDragHandler:function(aDragEvent){var data=aDragEvent.getData();this._mapModel.jumpByPixel(-data.deltaX,-data.deltaY)},handleOnClick:function(aClickEvent){this._onClick(aClickEvent)},_onClick:function(aClickEvent){if(!this._leftClickingBehaviorEnabled){return}var data=aClickEvent.getData();var mapMarkers=this._mapModel.getMapMarkersAt(data);var canceled=false;var mapMarker=this._mapModel.getClosestPoi(data,mapMarkers);if(mapMarker&&mapMarker.isClickable()){this._mapModel.selectMapObject(mapMarker);mapMarker.fireEvent(new nokia.aduno.utils.Event("selected",mapMarker));canceled=true}else{this._mapModel.selectMapObject(null)}if(!canceled){if(nokia.aduno.utils.platform.maemo&&this._mapModel.getDetailLevel()!==MapModel.DETAIL_LEVEL_HIGH){this._mapModel.setDetailLevel(MapModel.DETAIL_LEVEL_HIGH)}this._mapModel.moveTo({x:data.x,y:data.y,animationMode:"linear"})}},_onMouseUp:function(aButton){if(this._lastDragTime===0){return}if(this._kineticInterval){delete (this.kineticInterval)}this._startTime=new Date().getTime();var timeDiff=this._startTime-this._lastDragTime;if(aButton==1&&timeDiff<100){var binding=bind(this,this.moveKinetic);this._kineticInterval=setInterval(function(){binding()},100)}else{this._mapModel.setDetailLevel(MapModel.DETAIL_LEVEL_HIGH);this._mapModel.onDragDone()}this._spiceManager.removeMouseUpHandler(this._mouseUpBind);this._alreadyRegistered=false;this._lastDragTime=0;return true},moveKinetic:function(){var time=new Date().getTime()-this._startTime;if(time<this._animationTime){var factor=(Math.pow(this._animationTime-time,2)/this._animationTimeSquare);var x=this._lastDragMovement[0]*factor;var y=this._lastDragMovement[1]*factor;if(!this._mapModel.getPluginControl().isPluginInUse()){x=Math.round(x);y=Math.round(y)}this._mapModel.jumpByPixel(x,y)}else{if(this._kineticInterval){clearInterval(this._kineticInterval);delete this._kineticInterval;this._mapModel.setDetailLevel(MapModel.DETAIL_LEVEL_HIGH);this._mapModel.onDragDone()}}}});MouseSpice.MAX_SPEED=50;var MouseHoverSpice=new Class({Name:"MouseHoverSpice",Extends:Spice,Implements:nokia.aduno.utils.EventSource,_mapModel:null,_timeoutId:-1,_timeoutMsec:500,_objectsMouseIsOver:[],_previous:{x:-1,y:-1},_current:{x:-1,y:-1},_layerHandlers:{},_publicMethods:["addEventHandlerForLayer","removeEventHandlerForLayer","setTimeout","getTimeout"],initialize:function(aSpiceManager,aMapModel,aTimeoutInMillis){this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._timeoutMsec=+aTimeoutInMillis>0?+aTimeoutInMillis:500;this._moveHandler=nokia.aduno.dom.bindWithEvent(this,this._handleMouseMove);this._outHandler=nokia.aduno.dom.bindWithEvent(this,this._handleMouseOut);this._callback=nokia.aduno.utils.bind(this,this._timeoutCallback)},onAttach:function(){this._node=new nokia.aduno.dom.XNode(this._mapModel._pluginControl.getRootElement());this._node.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_MOVE,this._moveHandler);this._node.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this._outHandler)},onDetach:function(){this._node.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_MOVE,this._moveHandler);this._node.removeEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this._outHandler);if(this._timeoutId>-1){window.clearTimeout(this._timeoutId);this._timeoutId=-1}},setTimeout:function(aMilliseconds){if(+aMilliseconds>0){this._timeoutMsec=+aMilliseconds;return true}return false},getTimeout:function(){return this._timeoutMsec},addEventHandlerForLayer:function(aLayerName,aCallback){if(typeof aLayerName!="string"||typeof aCallback!="function"){return false}var callbacks=this._layerHandlers[aLayerName];if(!callbacks){callbacks=[];this._layerHandlers[aLayerName]=callbacks}for(var i=0,c=callbacks.length;i<c;i++){if(callbacks[i]==aCallback){return false}}callbacks.push(aCallback);return true},removeEventHandlerForLayer:function(aLayerName,aCallback){var callbacks=this._layerHandlers[aLayerName];if(callbacks){if(typeof aCallback=="function"){for(var i=0,c=callbacks.length;i<c;i++){if(aCallback==callbacks[i]){callbacks.splice(i,1);return true}}}else{delete this._layerHandlers[aLayerName];return true}}return false},_handleMouseMove:function(aMouseEvent){this._current.x=aMouseEvent.get("pageX");this._current.y=aMouseEvent.get("pageY");if(this._timeoutId>-1){window.clearTimeout(this._timeoutId);this._timeoutId=-1}this._timeoutId=window.setTimeout(this._callback,this._timeoutMsec);if(this._objectsMouseIsOver.length>0){var pos=this._mouseToGeo(this._current.x,this._current.y);var markers=[];var markersToRemove=[];if(pos){markers=this._mapModel.getMapMarkersAt(pos)}for(var i=this._objectsMouseIsOver.length-1;i>=0;i--){var isStillHoveringOver=false;for(var j=0,c=markers.length;j<c;j++){if(this._objectsMouseIsOver[i].isSame(markers[j])){isStillHoveringOver=true;break}}if(!isStillHoveringOver){markersToRemove.push(this._objectsMouseIsOver[i]);this._objectsMouseIsOver.splice(i,1)}}if(markersToRemove.length>0){this._fireMouseEvent(MouseHoverSpice.EVENT_MOUSE_OUT_MAP_OBJECT,pos,markersToRemove)}}},_handleMouseOut:function(aMouseEvent){if(this._timeoutId>=0){window.clearTimeout(this._timeoutId);this._timeoutId=-1}},_fireMouseEvent:function(aEventType,aPosition,aMarkers){var buckets={};for(var i=0,c=aMarkers.length;i<c;i++){var layer=null;if(aMarkers[i].getLayer&&type(aMarkers[i].getLayer)==="function"){layer=aMarkers[i].getLayer()}var name=layer?layer.getName():null;if(layer&&this._layerHandlers[name]){var bucket=buckets[name];if(!bucket){buckets[name]=[aMarkers[i]]}else{bucket.push(aMarkers[i])}}}for(var key in buckets){var layer=buckets[key][0].getLayer();if(layer.isVisible()){var e=new nokia.aduno.utils.Event(aEventType,{latitude:aPosition.latitude,longitude:aPosition.longitude,markers:buckets[key]});var handlers=this._layerHandlers[layer.getName()];for(var i=0,c=handlers.length;i<c;i++){handlers[i](e)}}}this.fireEvent(new nokia.aduno.utils.Event(aEventType,{latitude:aPosition.latitude,longitude:aPosition.longitude,markers:aMarkers}))},_mouseToGeo:function(aX,aY){var canvas=nokia.aduno.dom.Dimensions.getCoordinates(this._mapModel._pluginControl.getRootElement());var cursor={x:aX-canvas.left,y:aY-canvas.top};if(cursor.x>=0&&cursor.y>=0&&cursor.x<canvas.width&&cursor.y<canvas.height){var geo=this._mapModel.toGeo(cursor);if(geo){return{latitude:geo.getLatitude(),longitude:geo.getLongitude()}}}return null},_timeoutCallback:function(){if(this._previous.x==this._current.x&&this._previous.y==this._current.y){var pos=this._mouseToGeo(this._current.x,this._current.y);if(pos){var markers=this._mapModel.getMapMarkersAt(pos)||[];var newMarkers=[];for(var i=0,c=markers.length;i<c;i++){var hoveringOverAlready=false;for(var j=0,d=this._objectsMouseIsOver.length;j<d;j++){if(markers[i].isSame(this._objectsMouseIsOver[j])){hoveringOverAlready=true;break}}if(!hoveringOverAlready){newMarkers.push(markers[i]);this._objectsMouseIsOver.push(markers[i])}}this._fireMouseEvent(MouseHoverSpice.EVENT_MOUSE_OVER_MAP_OBJECT,pos,newMarkers)}}this._previous=this._current}});MouseHoverSpice.EVENT_MOUSE_OVER_MAP_OBJECT="mouseOverMapObject";MouseHoverSpice.EVENT_MOUSE_OUT_MAP_OBJECT="mouseOutMapObject";var ZoomSpice=new Class({Name:"ZoomSpice",Extends:Spice,_zoomAnimationTimeout:1000,_lastZoomTimestamp:0,initialize:function(aSpiceManager,aMapModel,aZoomModel){this._zoomModel=aZoomModel;this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._mapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onModelZoomChange,this);this._mapModel.addEventHandler(MapModel.EVENT_MAXZOOM,this._onMaxZoomChange,this);this._spiceManager.setKeyHandler(KeyEventManager.KEY_NUM_PLUS,0,nokia.aduno.utils.bind(this,this.handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_NUM_MINUS,0,nokia.aduno.utils.bind(this,this.handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_NUM_PLUS,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this.handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_NUM_MINUS,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this.handleKey));if(nokia.aduno.utils.browser.msie||nokia.aduno.utils.browser.safari){this._spiceManager.setKeyHandler(KeyEventManager.KEY_PLUS_IE,0,nokia.aduno.utils.bind(this,this.handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_MINUS_IE,0,nokia.aduno.utils.bind(this,this.handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_PLUS_IE,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this.handleKy));this._spiceManager.setKeyHandler(KeyEventManager.KEY_MINUS_IE,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this.handleKey))}if(nokia.aduno.utils.browser.mozilla){this._spiceManager.setKeyHandler(KeyEventManager.KEY_PLUS_MOZ,0,nokia.aduno.utils.bind(this,this.handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_PLUS_MOZ,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this.handleKey))}if(nokia.maps.pfw.layout.snc){this._S60ZoomSlider=null;this._S60ZoomSliderFxObj=null;this._S60ZoomTimer=null;this._S60ZoomTimeout=2000;this._S60ZoomSliderMinHeight=0;this._S60ZoomSliderMaxHeight=0;this._S60ZoomSliderTop=0}else{this._spiceManager.setWheelHandler(nokia.aduno.utils.bind(this,this.handleMouseWheel));this._spiceManager.setMouseClickHandler(SpiceManager.MOUSE_BUTTON_LEFT,SpiceManager.MOUSE_CLICK_DOUBLE,nokia.aduno.utils.bind(this,this.handleMouseDoubleClickLeft));this._spiceManager.setMouseClickHandler(SpiceManager.MOUSE_BUTTON_RIGHT,SpiceManager.MOUSE_CLICK_DOUBLE,nokia.aduno.utils.bind(this,this.handleMouseDoubleClickRight));this._mouseBeenOverTheOverlay=false;this._mouseOverlayTimer=null;this._mouseOverlayTimeout=1000;this._mouseOverlayFxObj=null;this._mouseOverlayFxAct=false}},_createUi:function(){var slider=null;if(!nokia.maps.pfw.layout.snc){slider=new ComboSlider(true,null,ZoomSpice.ZoomSpiceTemplateLibrary,{size:nokia.aduno.utils.browser.snc?{x:0,y:0}:nokia.aduno.utils.browser.touch?{x:0,y:0}:nokia.aduno.utils.browser.msie?{x:0,y:0}:{x:28,y:139},buttonSize:nokia.aduno.utils.browser.snc?{x:0,y:0}:nokia.aduno.utils.browser.touch?{x:0,y:0}:nokia.aduno.utils.browser.msie?{x:0,y:0}:{x:28,y:19}});slider.addEventHandler("changed",this._onUIZoomChange,this);slider.setSteps(this._zoomModel.getStepCount());slider.setValue(this._zoomModel.convertStepToValue(this._mapModel.getZoomScale()),true);this._sliderLabels=new Container("ComboSliderLabels",ZoomSpice.ZoomSpiceTemplateLibrary);this._countryButton=new Button("ComboSliderCountryButton","__I18N_mapPlayer_43_mapControl_zoomControl_bookmark_country__");this._stateButton=new Button("ComboSliderStateButton","__I18N_mapPlayer_44_mapControl_zoomControl_bookmark_state__");this._cityButton=new Button("ComboSliderCityButton","__I18N_mapPlayer_45_mapControl_zoomControl_bookmark_city__");this._streetButton=new Button("ComboSliderStreetButton","__I18N_mapPlayer_46_mapControl_zoomControl_bookmark_street__");this._sliderLabels.setChildAt(this._countryButton,"CountryButton");this._sliderLabels.setChildAt(this._stateButton,"StateButton");this._sliderLabels.setChildAt(this._cityButton,"CityButton");this._sliderLabels.setChildAt(this._streetButton,"StreetButton");this._countryButton.addEventHandler("selected",this._onSliderLabelsClick,this);this._stateButton.addEventHandler("selected",this._onSliderLabelsClick,this);this._cityButton.addEventHandler("selected",this._onSliderLabelsClick,this);this._streetButton.addEventHandler("selected",this._onSliderLabelsClick,this);this._sliderLabels.hide();slider._slider.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onMouseEnteredSlider);slider._slider.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onMouseExitedSlider);this._sliderLabels.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onMouseEnteredOverlay);this._sliderLabels.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onMouseExitedOverlay);this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._sliderLabels);slider.setChildAt(this._sliderLabels,"ComboSliderLabels");this._isJS=!this._mapModel.getPluginControl().isPluginInUse();if(this._isJS){this._sliderLabels.getReplica().addCssClass("ComboSliderLabels","nmp_js");this._levels={CountryButton:13,StateButton:10,CityButton:7,StreetButton:2}}else{this._levels={CountryButton:15,StateButton:12,CityButton:9,StreetButton:4}}}else{slider=new Container("S60Zoom",ZoomSpice.ZoomSpiceTemplateLibrary);this._S60ZoomSlider=new nokia.aduno.medosui.Control(ZoomSpice.ZoomSpiceTemplateLibrary.getTemplate("S60Slider"));this._S60ZoomSliderFxObj=new nokia.aduno.medosui.Fx(this._S60ZoomSlider);slider.setChildAt(this._S60ZoomSlider,"Slider")}return slider},_onSliderLabelsClick:function(aClickEvent){var posId=aClickEvent.source.getPosId();if(this._levels.hasOwnProperty(posId)){this._spiceControl.setValue(this._levels[posId])}this._sliderLabels.hide()},_s60OpenSlider:function(){if(this._S60ZoomTimer){clearTimeout(this._S60ZoomTimer)}this._S60ZoomTimer=null;if(this._S60ZoomSliderFxAct){this._S60ZoomSliderFxObj.stop();delete this._S60ZoomSliderFxObj;this._S60ZoomSliderFxObj=new nokia.aduno.medosui.Fx(this._S60ZoomSlider);this._S60ZoomSliderFxAct=false}var sliderHeight=100-(Math.floor(this._zoomModel.getStep()*100/(this._zoomModel.getStepCount()-1)));var replica=this._S60ZoomSlider.getReplica();replica.setStyle("zoomcontainer","height",this._S60ZoomSliderMaxHeight+"px");replica.setStyle("zoomcontainer","top","0px");replica.setStyle("zoombar","display","block");replica.setStyle("zoomslider","top",sliderHeight+"px");replica.setStyle("zoomslider","display","block");var binder=this;this._S60ZoomTimer=setTimeout(function(){binder._s60CloseSlider()},this._S60ZoomTimeout)},_s60CloseSlider:function(){this._S60ZoomSlider.getReplica().setStyle("zoomslider","display","none");this._S60ZoomSliderFxAct=true;this._S60ZoomSliderFxObj.addEventHandler("ended",function(){this._S60ZoomSliderFxAct=false;this._S60ZoomSlider.getReplica().setStyle("zoombar","display","none")},this);this._S60ZoomSliderFxObj.effect({duration:500,styles:{top:[0,this._S60ZoomSliderTop+"px"],height:[this._S60ZoomSliderMaxHeight+"px",this._S60ZoomSliderMinHeight+"px"]}}).start()},_onModelZoomChange:function(aEvent){if(!nokia.maps.pfw.layout.snc){var step=this._zoomModel.getStep();if(this._zoomModel._limitedZoomScale){if(step>=2&&step<=15){this._spiceControl.setValue(step,true)}}else{this._spiceControl.setValue(step,true)}}else{if(!this._S60ZoomTimer){this._s60OpenSlider()}}},_onUIZoomChange:function(aEvent){var val=aEvent.getData().value;if(this._zoomModel._limitedZoomScale&&(val||val===0)){var self=this;var scale=this._zoomModel.getZoomScale();var step=this._zoomModel.convertValueToStep(scale);if(val<2){if(step!=2){this._zoomModel.setStep(2)}setTimer(50,this,function(){self._spiceControl.setValue(2,true)})}else{if(val>15){if(step>15){this._zoomModel.setStep(15)}setTimer(50,this,function(){self._spiceControl.setValue(15,true)})}else{this._zoomModel.setStep(val)}}}else{if(val||val===0){this._zoomModel.setStep(val);if(nokia.maps.pfw.layout.snc){this._s60OpenSlider()}}}},handleMouseWheel:function(aWheelEvent){var eventCopy=aWheelEvent._eventCopy;var newCenter;if(nokia.aduno.utils.browser.msie){newCenter={x:eventCopy.offsetX,y:eventCopy.offsetY}}else{newCenter={x:eventCopy.layerX,y:eventCopy.layerY}}var _target=aWheelEvent.get("target");if(!this._mapModel.getPluginControl().isPluginInUse()&&_target.nodeName=="IMG"){var _targetParent=_target.parentNode||_target.parent;newCenter.x+=_target.offsetLeft+_targetParent.offsetLeft;newCenter.y+=_target.offsetTop+_targetParent.offsetTop}var curCenter=this._mapModel.getPluginControl().getMapSize();curCenter.x=Math.round(curCenter.width/2);curCenter.y=Math.round(curCenter.height/2);var delta=-parseInt(aWheelEvent.get("wheelDelta"));var curValue=this._zoomModel.getStep()+((delta>0)?1:-1);if(this._zoomModel._limitedZoomScale){if(curValue>=2&&curValue<=15){this._mapModel.setTransformAbsoluteCenter(newCenter.x,newCenter.y);this._mapModel.moveTo({animationMode:"none",scale:this._zoomModel.convertStepToValue(curValue)});this._spiceControl.setValue(curValue,true);this._mapModel.setTransformAbsoluteCenter(curCenter.x,curCenter.y)}}else{if(curValue>=0&&curValue<this._zoomModel.getStepCount()){this._mapModel.setTransformAbsoluteCenter(newCenter.x,newCenter.y);this._mapModel.moveTo({animationMode:"none",scale:this._zoomModel.convertStepToValue(curValue)});if(nokia.maps.pfw.layout.snc){this._s60OpenSlider()}this._spiceControl.setValue(curValue,true);this._mapModel.setTransformAbsoluteCenter(curCenter.x,curCenter.y)}}return true},handleKey:function(aKeyEvent){if(aKeyEvent.keyPress||aKeyEvent.keyDown){var val=this._zoomModel.getStep();var keyCode=aKeyEvent._eventCopy.keyCode;if(nokia.aduno.utils.browser.msie||nokia.aduno.utils.browser.safari){if(keyCode!==KeyEventManager.KEY_MINUS_IE&&keyCode!==KeyEventManager.KEY_PLUS_IE){if(nokia.aduno.utils.browser.safari&&aKeyEvent._eventCopy.charCode===keyCode){return false}if(nokia.aduno.utils.browser.msie){var which=aKeyEvent._eventCopy.hasOwnProperty&&aKeyEvent._eventCopy.hasOwnProperty("which");if(!which||(keyCode!==KeyEventManager.KEY_NUM_MINUS&&keyCode!==KeyEventManager.KEY_NUM_PLUS)){return false}}}}else{if(nokia.aduno.utils.browser.mozilla){if(keyCode!==KeyEventManager.KEY_PLUS_MOZ&&keyCode!==KeyEventManager.KEY_NUM_MINUS&&keyCode!==KeyEventManager.KEY_NUM_PLUS){return false}}}if(this._lastZoomTimestamp+this._zoomAnimationTimeout>new Date().getTime()){return}switch(keyCode){case KeyEventManager.KEY_NUM_PLUS:case KeyEventManager.KEY_PLUS_MOZ:case KeyEventManager.KEY_PLUS_IE:if(this._zoomModel._limitedZoomScale){if(val>2){this._zoomModel.setStep(val-1);this._spiceControl.setValue(val-1,true);this._lastZoomTimestamp=new Date().getTime()}}else{if(val>0){this._zoomModel.setStep(val-1);this._lastZoomTimestamp=new Date().getTime();if(!nokia.maps.pfw.layout.snc){this._spiceControl.setValue(val-1,true)}else{this._s60OpenSlider()}}}aKeyEvent.preventDefault();aKeyEvent.stopPropagation();return true;case KeyEventManager.KEY_NUM_MINUS:case KeyEventManager.KEY_MINUS_IE:if(this._zoomModel._limitedZoomScale){if(val<this._zoomModel.getStepCount()-3){this._zoomModel.setStep(val+1);this._spiceControl.setValue(val+1,true);this._lastZoomTimestamp=new Date().getTime()}}else{if(val<this._zoomModel.getStepCount()-1){this._zoomModel.setStep(val+1);this._lastZoomTimestamp=new Date().getTime();if(!nokia.maps.pfw.layout.snc){this._spiceControl.setValue(val+1,true)}else{this._s60OpenSlider()}}}aKeyEvent.preventDefault();aKeyEvent.stopPropagation();return true;default:break}}return false},handleMouseDoubleClickLeft:function(aClickEvent){var _step=this._zoomModel.getStep();var _data=aClickEvent.getData();var _newStep=_step;if(this._zoomModel._limitedZoomScale){if(_step>2){_newStep=_step-1}}else{if(_step>0){_newStep=_step-1}}this._mapModel.moveTo({animationMode:"linear",scale:this._zoomModel.convertStepToValue(_newStep),x:_data.x,y:_data.y});this._spiceControl.setValue(_newStep,true);aClickEvent.preventDefault()},handleMouseDoubleClickRight:function(aClickEvent){var _step=this._zoomModel.getStep();var _data=aClickEvent.getData();var _newStep=_step;if(this._zoomModel._limitedZoomScale){if(_step<this._zoomModel.getStepCount()-3){_newStep=_step+1}}else{if(_step<this._zoomModel.getStepCount()-1){_newStep=_step+1}}this._mapModel.moveTo({animationMode:"linear",scale:this._zoomModel.convertStepToValue(_newStep),x:_data.x,y:_data.y});this._spiceControl.setValue(_newStep,true);aClickEvent.preventDefault()},onAttach:function(){if(!nokia.maps.pfw.layout.snc){}else{var zoombar=nokia.aduno.dom.Dimensions.getSize(this._S60ZoomSlider.getElement("zoombar"));var zoomminus=nokia.aduno.dom.Dimensions.getSize(this._S60ZoomSlider.getElement("zoomminus"));var zoomplus=nokia.aduno.dom.Dimensions.getSize(this._S60ZoomSlider.getElement("zoomplus"));this._S60ZoomSliderMinHeight=zoomminus.y+zoomplus.y;this._S60ZoomSliderMaxHeight=zoombar.y+zoomminus.y+zoomplus.y;this._S60ZoomSliderTop=Math.floor(zoombar.y/2);this._S60ZoomSlider.getReplica().setStyle("zoombar","display","none")}if(!this._mapModel.getPluginControl().isPluginInUse()){this._spiceControl.setValue(this._zoomModel.getStep())}},_onMaxZoomChange:function(aEvent){if(this._spiceControl.setValue){var step=this._zoomModel.getStep();if(this._zoomModel._limitedZoomScale){step=Math.max(Math.min(step,15),2);this._zoomModel.setStep(step)}this._spiceControl.setValue(step,true)}},_onMouseEnteredSlider:function(aMouseOverEvent){this._mouseBeenOverTheOverlay=false;if(this._mouseOverlayTimer){clearTimeout(this._mouseOverlayTimer)}this._mouseOverlayTimer=null;this._sliderLabels.show()},_onMouseExitedSlider:function(aMouseOutEvent){if(!this._mouseOverlayFxAct){var x=aMouseOutEvent.get("pageX");var y=aMouseOutEvent.get("pageY");var rect=nokia.aduno.dom.Dimensions.getCoordinates(this._sliderLabels.getRootElement());if(x<rect.left||x>=rect.left+rect.width||y<rect.top||y>=rect.top+rect.height){var self=this;this._mouseOverlayTimer=setTimeout(function(){self._sliderLabels.hide()},this._mouseOverlayTimeout)}}},_onMouseEnteredOverlay:function(aMouseOverEvent){this._mouseBeenOverTheOverlay=true;if(this._mouseOverlayTimer){clearTimeout(this._mouseOverlayTimer)}this._mouseOverlayTimer=null},_onMouseExitedOverlay:function(aMouseOutEvent){if(this._mouseBeenOverTheOverlay&&!this._mouseOverlayFxAct){var x=aMouseOutEvent.get("pageX");var y=aMouseOutEvent.get("pageY");var rect=nokia.aduno.dom.Dimensions.getCoordinates(this._sliderLabels.getRootElement());if(x<rect.left||x>=rect.left+rect.width||y<rect.top||y>=rect.top+rect.height){var self=this;this._mouseOverlayTimer=setTimeout(function(){self._sliderLabels.hide()},this._mouseOverlayTimeout)}}}});ZoomSpice.ZoomSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({S60Zoom:'<div class="nmp_S60ZoomSpice"><div id="Slider"></div></div>',S60Slider:'<div id="zoomcontainer" class="nmp_zoom_s60"><div id="zoomminus" class="nmp_zoom_minus"></div><div id="zoombar" class="nmp_zoom_slider"><div id="zoomslider"></div></div><div id="zoomplus" class="nmp_zoom_plus"></div></div>',ComboSlider:'<div id="comboSlider" class="nm_CombSlid"><div id="increaseButton"></div><div id="slider"></div><div id="decreaseButton"></div><div id="ComboSliderLabels"></div></div>',Slider:'<div class="nm_Slid" unselectable="on"><div id="sliderButton"></div></div>',SliderButton:'<div id="sliderButton" unselectable="on"></div>',ComboSliderIncreaseButton:'<div id="increaseButton"><div id="button" class="nm_CombSlidAdd" unselectable="on"></div></div>',ComboSliderDecreaseButton:'<div id="decreaseButton"><div id="button" class="nm_CombSlidSub" unselectable="on"></div></div>',ComboSliderLabels:'<div id="ComboSliderLabels" class="nm_CombSlidLabels"><div id="CountryButton"></div><div id="StateButton"></div><div id="CityButton"></div><div id="StreetButton"></div></div>',ComboSliderCountryButton:'<div class="nm_CombSlidLabelCountry" unselectable="on"><div id="button" unselectable="on"></div></div>',ComboSliderStateButton:'<div class="nm_CombSlidLabelState" unselectable="on"><div id="button" unselectable="on"></div></div>',ComboSliderCityButton:'<div class="nm_CombSlidLabelCity" unselectable="on"><div id="button" unselectable="on"></div></div>',ComboSliderStreetButton:'<div class="nm_CombSlidLabelStreet" unselectable="on"><div id="button" unselectable="on"></div></div>',Draggable:'<div id="draggable"></div>'});var InfoPlacard=new Class({Name:"InfoPlacard",Extends:Spice,_mapModel:null,_zoomModel:null,_flagOnClick:null,_zoomDetailLevel:-1,_infoMarkerId:-1,initialize:function(aSpiceManager,aMapModel,aZoomModel){this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._zoomModel=aZoomModel;this._zoomDetailLevel=aZoomModel.getStep();aMapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onMapZoomLevelChanged,this)},showForMapPosition:function(aPosition,aZoomCallback){if(aPosition){this._prepareForDisplay();this.setZoomCallback(aZoomCallback);var self=this;var marker=MapMarker.parse({latitude:aPosition.latitude,longitude:aPosition.longitude,infoTitle:this._computeInfoTexts(this._zoomModel.getStep(),aPosition,null).title});this._infoMarkerId=marker.getId();this._mapModel.selectMapObject(marker);this._mapModel.reverseGeoCode(aPosition,function(aMapLocations){var location=aMapLocations&&aMapLocations.length?aMapLocations[0]:null;var info=self._computeInfoTexts(self._zoomModel.getStep(),aPosition,location);marker.setInfoTitle(info.title);marker.setInfoDescription(info.description)});return true}return false},showForMapMarker:function(aMapMarker,aZoomCallback){if(aMapMarker){this._prepareForDisplay();this.setZoomCallback(aZoomCallback);this._mapModel.selectMapObject(aMapMarker);return true}return false},_computeTimeZoneOffset:function(aCoordinates){if(!aCoordinates){return""}if(typeof aCoordinates.getLongitude!="function"){aCoordinates=this._mapModel.getPluginControl().createGeoCoordinates(aCoordinates.latitude,aCoordinates.longitude)}var tz=this._mapModel._map.getTimeOffset(aCoordinates);var hours=tz<0?"-"+(/\d\d$/.exec("0"+parseInt(-tz/60))[0]):"+"+(/\d\d$/.exec("0"+parseInt(tz/60))[0]);var isValid=Math.abs(parseInt(hours,10))<=12;return isValid?("GMT "+hours+":"+(/\d\d$/.exec("0"+(Math.abs(tz)%60)))[0]):null},_computeInfoTexts:function(aZoomStep,aCoordinates,aMapLocation){var street=aMapLocation?aMapLocation.ADDR_STREET_NAME:null;var houseNumber=aMapLocation?aMapLocation.ADDR_HOUSE_NUMBER:null;var city=aMapLocation?aMapLocation.ADDR_CITY_NAME:null;var country=aMapLocation?aMapLocation.ADDR_COUNTRY_NAME:null;var place=aMapLocation?aMapLocation.PLACE_NAME:null;var title=null,desc=null;var detailLevel=this._zoomStepToDetailLevel(aZoomStep);if(detailLevel==InfoPlacard.ZOOM_INFO_WORLD){title=country;desc=this._computeTimeZoneOffset(aCoordinates)}else{if(detailLevel==InfoPlacard.ZOOM_INFO_COUNTRY){if(city){title=city;desc=country}else{title=country;desc=this._computeTimeZoneOffset(aCoordinates)}}else{if(detailLevel==InfoPlacard.ZOOM_INFO_CITY){if(street){title=street+(houseNumber?" "+houseNumber:"");desc=(country||"");if(country&&city){desc+=" "+city}else{desc+=(city||"")}if(desc==" "){desc=null}}else{if(city){title=city;desc=country}else{if(place){title=place;desc=country}}}}else{nokia.aduno.utils.error("aZoomStep out of bounds.")}}}if(!title||title.length===0){if(!desc){desc=country}else{if(country){desc=country+" "+desc}}title=this._formatCoordinatesValue({latitude:aCoordinates.latitude||(aCoordinates.getLatitude?aCoordinates.getLatitude():0),longitude:aCoordinates.longitude||(aCoordinates.getLongitude?aCoordinates.getLongitude():0)})}return{title:title,description:desc}},_formatCoordinatesValue:function(aCoordinates){var convert=function(coord,neghemi,poshemi){var hemisphere=poshemi;coord=+coord;if(coord<0){hemisphere=neghemi;coord=-coord}var degrees=parseInt(coord,10);var minutes=(coord-degrees)*60;var seconds=(minutes-parseInt(minutes,10))*60;return degrees+"\u00B0"+(/\d\d$/.exec("0"+parseInt(minutes,10)))+"'"+(/\d\d$/.exec("0"+parseInt(seconds,10)))+'"'+hemisphere};if(!aCoordinates||typeof aCoordinates.latitude!="number"||typeof aCoordinates.longitude!="number"){return null}return convert(aCoordinates.latitude,"S","N")+", "+convert(aCoordinates.longitude,"W","E")},_onMapZoomLevelChanged:function(){if(this._zoomCallback){this._zoomCallback()}if(this._selected&&this.updateMapMarkerLabels){this.updateMapMarkerLabels()}},setZoomCallback:function(aFunction){this._zoomCallback=typeof aFunction=="function"?aFunction:null},zoomCallbackForMapLocationMarker:function(){if(!this._selected||!this._selected.getId||this._selected.getId()!==this._infoMarkerId){return}var zoomStep=this._zoomModel.getStep();var level=this._zoomStepToDetailLevel(zoomStep);if(level!=this._zoomDetailLevel){this._zoomDetailLevel=level;this._mapModel.reverseGeoCode(this._selected.getPosition(),function(aMapLocations){var location=aMapLocations&&aMapLocations.length?aMapLocations[0]:null;var info=this._computeInfoTexts(zoomStep,this._selected.getPosition(),location);this.setTitle(info.title);this.setDescription(info.description)},this)}},getTitle:function(){return this._titleLabel?this._titleLabel.getText():null},getDescription:function(){return this._descLabel?this._descLabel.getText():null},setTitle:function(aText){if(this._titleLabel){if(aText&&aText.length>0){this._titleLabel.setText(aText);this._titleLabel.show()}else{this._titleLabel.hide()}return true}return false},setDescription:function(aText){if(this._descLabel){if(aText&&aText.length>0){this._descLabel.setText(aText);this._descLabel.show()}else{this._descLabel.hide()}return true}return false},_zoomStepToDetailLevel:function(aZoomStep){if(aZoomStep>=14){return InfoPlacard.ZOOM_INFO_WORLD}else{if(aZoomStep>=10&&aZoomStep<=13){return InfoPlacard.ZOOM_INFO_COUNTRY}else{if(aZoomStep>=0&&aZoomStep<=9){return InfoPlacard.ZOOM_INFO_CITY}}}return InfoPlacard.ZOOM_INFO_UNKNOWN},_prepareForDisplay:function(){this._zoomDetailLevel=this._zoomStepToDetailLevel(this._zoomModel.getStep())}});InfoPlacard.ZOOM_INFO_UNKNOWN=0;InfoPlacard.ZOOM_INFO_WORLD=1;InfoPlacard.ZOOM_INFO_COUNTRY=2;InfoPlacard.ZOOM_INFO_CITY=3;var InfoBarSpice=new Class({Name:"InfoBarSpice",Extends:InfoPlacard,_animationDuration:700,initialize:function(aSpiceManager,aMapModel,aZoomModel){this._super(aSpiceManager,aMapModel,aZoomModel);this._mapModel.addEventHandler(MapModel.EVENT_MAPOBJECT_SELECTED,this._onMapObjectSelected,this);this._mapModel.addEventHandler(MapModel.EVENT_MAPOBJECT_UNSELECTED,this._onMapObjectUnselected,this);this._mapModel.addEventHandler(MapModel.EVENT_POSITION_CHANGED,this._onMapMoved,this);this._spiceManager.setKeyHandler(KeyEventManager.KEY_3,0,nokia.aduno.utils.bind(this,this._keyHandler))},_createUi:function(){var bar=new Container("InfoBar",InfoBarSpice.InfoBarTemplateLibrary);this._titleLabel=new Label("TitleLabel","");this._descLabel=new Label("DescriptionLabel","");bar.setChildAt(this._titleLabel,"title");bar.setChildAt(this._descLabel,"description");this._titleLabel.hide();this._descLabel.hide();bar.hide();return bar},_onMapObjectSelected:function(aSelectEvent){this._selected=aSelectEvent.getData();this._prepareForDisplay();if(this._selected){this._selected.addEventHandler(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,this._onMarkerPropertyChanged,this);var title=this._selected.getInfoTitle();var desc=this._selected.getInfoDescription();this.setTitle(title);this.setDescription(desc);if(title&&title.length>0){this._showInfoBar()}return true}else{this._hideInfoBar();return false}},_onMapObjectUnselected:function(){if(this._selected){this._selected=null;this._selected.removeEventHandler(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,this._onMarkerPropertyChanged,this);this._hideInfoBar()}},_onMarkerPropertyChanged:function(aPropertyChangedEvent){var data=aPropertyChangedEvent.getData();switch(data.property){case"infoTitle":this.setTitle(data.value);break;case"infoDescription":this.setDescription(data.value);break}},_showInfoBar:function(){if(this._fx){this._fx.stop()}var size=this._spiceManager.getSize();this._hideAsap=false;this._fx=new nokia.aduno.medosui.Fx(this._spiceControl);this._fx.addEventHandler("ended",function(){this._fx=null;if(this._hideAsap){this._hideInfoBar()}},this);this._fx.effect({duration:this._animationDuration,styles:{top:[size.y/2,20],left:[size.x/2,0],width:[0,size.x]}}).start();this._spiceControl.show()},_hideInfoBar:function(){if(this._fx){this._hideAsap=true;return}var y=nokia.aduno.dom.Dimensions.getOffsets(this._spiceControl.getRootElement()).y;this._fx=new nokia.aduno.medosui.Fx(this._spiceControl);this._fx.addEventHandler("ended",function(){this._fx=null;this._spiceControl.hide()},this);this._fx.effect({duration:this._animationDuration,styles:{top:[y,-100]}}).start()},_onMapMoved:function(aPosition){this._onMapObjectUnselected()},_keyHandler:function(aKeyEvent){if(!aKeyEvent.keyDown){return}if(this._selected){this._onMapObjectUnselected()}else{this.showForMapPosition(this._mapModel.toGeo(),this.zoomCallbackForMapLocationMarker)}}});InfoBarSpice.InfoBarTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({InfoBar:'<div class="nmp_InfoBarSpice"><div id="title"></div><div id="description"></div></div>',TitleLabel:'<h1 id="label"></h1>',DescriptionLabel:'<p id="label"></p>'});var InfoBubbleSpice=new Class({Name:"InfoBubbleSpice",Extends:InfoPlacard,_size:{x:0,y:0},_offset:null,_rightClickBehaviorEnabled:false,_hidedByMinimap:false,_minimapSpice:null,_minimapRectangle:{width:0,height:0,left:0,top:0},_bodyRectangle:{width:0,height:0,left:0,top:0},_tipRectangle:null,_showBubbleOnAnimationEndAt:null,_minWidth:160,_maxWidth:265,_selected:null,_isTraffic:false,_moveToCenter:true,initialize:function(aSpiceManager,aMapModel,aZoomModel){this._super(aSpiceManager,aMapModel,aZoomModel);this._publicMethods=["setTitle","setDescription","showWithHtmlBody","showForMapMarker","showBubbleAtPoint","show","hide","updateBubblePosition"];this._offset=InfoBubbleSpice.BUBBLE_DEFAULT_OFFSET;this._rightClickHandler=bind(this,this._onRightClick);aMapModel.addEventHandler(MapModel.EVENT_MAPOBJECT_SELECTED,this._onMapObjectSelected,this);aMapModel.addEventHandler(MapModel.EVENT_MAPOBJECT_UNSELECTED,this._onMapObjectUnselected,this);aMapModel.addEventHandler(MapModel.EVENT_POSITION_CHANGED,this._onMapMoved,this);aMapModel.addEventHandler(MapModel.EVENT_ORIENTATION,this._onMapMoved,this);aMapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onMapMoved,this);aMapModel.addEventHandler(MapModel.EVENT_ANIMATION_START,this._onAnimationStart,this);aMapModel.addEventHandler(MapModel.EVENT_ANIMATION_DONE,this._onAnimationEnd,this);this.setRightClickBehaviorEnabled(true);this._recalculateBodyRectangle=true;this._hideByPosition=false},showBubbleAtPoint:function(aPoint){this._moveToCenter=false;if(aPoint.className&&aPoint.className==="MapMarker"){this.showForMapMarker(aPoint);return}else{if(aPoint.x!==null&&aPoint.y!==null&&aPoint.x!==undefined&&aPoint.y!==undefined){aPoint=this._mapModel.pixelToGeo(aPoint.x,aPoint.y)}}this.showForMapPosition(aPoint,this.zoomCallbackForMapLocationMarker)},setRightClickBehaviorEnabled:function(aEnabled){if(aEnabled&&!this._rightClickBehaviorEnabled){this._spiceManager.setMouseClickHandler(SpiceManager.MOUSE_BUTTON_RIGHT,SpiceManager.MOUSE_CLICK_SINGLE,this._rightClickHandler);this._rightClickBehaviorEnabled=true}else{if(!aEnabled&&this._rightClickBehaviorEnabled){this._spiceManager.removeMouseClickHandler(SpiceManager.MOUSE_BUTTON_RIGHT,SpiceManager.MOUSE_CLICK_SINGLE);this._rightClickBehaviorEnabled=false}}},isRightClickBehaviorEnabled:function(){return this._rightClickBehaviorEnabled},onAttach:function(){if(nokia.aduno.utils.browser.msie){this._textSelectionCallback=function(){return false};this._spiceControl.getRootElement().attachEvent("onselectstart",this._textSelectionCallback)}},onDetach:function(){if(nokia.aduno.utils.browser.msie){this._spiceControl.getRootElement().detachEvent("onselectstart",this._textSelectionCallback)}},show:function(aPosition,aBubbleWidth,aTitle,aDescription){if(this._selected){this._spiceControl.hide();this._titleLabel.hide();this._descLabel.hide();this._htmlContainer.hide();this.setBubbleWidth(aBubbleWidth||200);this.setTitle(aTitle);this.setDescription(aDescription);this._animateBubbleIntoView(aPosition);this._isTraffic=false}},hide:function(){if(this._hideEffect){return}var self=this;var finalizer=function(){self._hideEffect=null;self._spiceControl.hide();self._titleLabel.hide();self._descLabel.hide();self._htmlContainer=new Label("HtmlLabel","");self._htmlContainer.hide();self._spiceControl.setChildAt(self._htmlContainer,"htmlContainer",true,false);this._isTraffic=false};if(nokia.aduno.utils.browser.msie){finalizer()}else{this._hideEffect=new Fx(this._spiceControl);this._hideEffect.addEventHandler("ended",finalizer,this);this._hideEffect.addEventHandler("stopped",finalizer,this);this._hideEffect.effect({duration:200,styles:{opacity:[1,0]}}).start()}},updateBubblePosition:function(){this._recalculateBodyRectangle=true;this._positionInfoBubble()},showWithHtmlBody:function(aPosition,aBubbleWidth,aHtmlString){this._spiceControl.hide();this._titleLabel.hide();this._descLabel.hide();this.setBubbleWidth(aBubbleWidth);if(!this._htmlContainer._posId){this._htmlContainer=new Label("HtmlLabel","");this._htmlContainer.hide();this._spiceControl.setChildAt(this._htmlContainer,"htmlContainer",true,false)}this._htmlContainer._replica.setInnerHtml("label",""+aHtmlString);this._htmlContainer.show();this._animateBubbleIntoView(aPosition);this._isTraffic=false;if(this._iconImage){this._spiceControl.getReplica().removeCssClass("nmp_InfoBubbleWithIcon");this._spiceControl.removeChild(this._iconImage);this._iconImage=null}var replica=this._spiceControl.getReplica();replica.setStyle(TemplateReplica.ROOT_ID,"opacity","1");this._spiceControl.show();this._bubblePosition=aPosition;this._positionInfoBubble()},updateMapMarkerLabels:function(){if(!this._selected||!this._selected.getId||this._selected.getId()===this._infoMarkerId){return}this._recalculateBodyRectangle=true;var zoomStep=this._zoomModel.getStep();var self=this;this._mapModel.reverseGeoCode(this._selected.getPosition(),function(aMapLocations){if(self._selected){var location=aMapLocations&&aMapLocations.length?aMapLocations[0]:null;var info=self._computeInfoTexts(zoomStep,self._selected.getPosition(),location);var title=self._selected.getType()=="traffic"?self._selected.getTrafficInfoText():self._selected.getInfoTitle();var desc=self._selected.getType()=="traffic"?self._selected.getAffectedStreets():self._selected.getInfoDescription();if(title===undefined||title===""){self._selected.setDefaultInfoTitle(info.title)}if(desc===undefined||desc===""){if(self._selected.getType!="traffic"){self._selected.setDefaultInfoDescription(info.description)}}self._bubblePosition=self._selected.getPosition();self._positionInfoBubble()}},this)},setBubbleWidth:function(aWidth){aWidth=+aWidth;if(isNaN(aWidth)||this._minWidth<this._width||aWidth>this._maxWidth){return false}var replica=this._spiceControl.getReplica();var tipMargin=nokia.aduno.utils.browser.msie&&navigator.userAgent.indexOf("MSIE 6")>=0?((aWidth/2)-20)/2:(aWidth/2)-20;replica.setStyle(TemplateReplica.ROOT_ID,"width",aWidth+"px");replica.setStyle("tip","margin-left",tipMargin+"px");this._recalculateBodyRectangle=true;if(this._spiceControl.isVisible()){this._positionInfoBubble()}return true},setTitle:function(aText){if(this._titleLabel&&aText&&aText.length>0){var text=this._setSoftHyphens(aText);this._titleLabel._replica.setInnerHtml("label",text);this._titleLabel.show();return true}this._titleLabel.hide();this._recalculateBodyRectangle=true;if(this._spiceControl.isVisible()){this._positionInfoBubble()}return false},setDescription:function(aText){if(this._descLabel){if(aText&&aText.length>0){var text=this._setSoftHyphens(aText);this._descLabel._replica.setInnerHtml("label",text);this._descLabel.show()}else{this._descLabel.hide()}return true}return false},_setSoftHyphens:function(aText){if(!aText||aText.length==0){return false}var word,words=aText.split(" ");var text=[];for(var i=0,word=words[0];i<words.length;i++,word=words[i]){if(word.length<=10){text.push(word.replace(/&/g,"&amp;"))}else{var subword=[];for(var j=0;j<word.length;j+=5){subword.push(word.substr(j,5).replace(/&/g,"&amp;"))}text.push(subword.join("&shy;"))}}text=text.join(" ");text=text.replace(/</g,"&lt;");text=text.replace(/>/g,"&gt;");return text},_createUi:function(){var infoBubble=new Container("InfoBubble",InfoBubbleSpice.InfoBubbleTemplateLibrary);var closeButton=new Button("CloseButton","");this._fx=new nokia.aduno.medosui.Fx(infoBubble);this._titleLabel=new Label("TitleLabel","");this._descLabel=new Label("DescriptionLabel","");this._htmlContainer=new Label("HtmlLabel","");this._htmlContainer.hide();infoBubble.hide();infoBubble.setChildAt(closeButton,"closeButton");infoBubble.setChildAt(this._titleLabel,"title");infoBubble.setChildAt(this._descLabel,"description");infoBubble.setChildAt(this._htmlContainer,"htmlContainer");closeButton.addEventHandler("selected",function(){this._mapModel.unselectMapObject();this.hide()},this);var binder=this;infoBubble.accept=function(aVisitor){binder._translations=aVisitor._translator._translationTable};return infoBubble},_onMapMoved:function(aPosition){if(this._animationId){window.clearInterval(this._animationId);this._animationId=null}this._positionInfoBubble()},_onMapObjectSelected:function(aSelectEvent){if(this._hideEffect){this._hideEffect.stop();this._hideEffect=null}var selected=aSelectEvent.getData();var layer=selected.getLayer();if(layer){if(layer.hasOwnInfoBubble()||selected.hasOwnInfoBubble()){return}}var latLonPos=selected.getPosition();var position=this._mapModel.geoToPixel(latLonPos);var title="";var desc="";if(selected.getType()=="traffic"){this._isTraffic=true;title=selected.getTrafficInfoText();desc=selected.getAffectedStreets();var providerImage=new Image("TrafficProviderImage",InfoBubbleSpice.InfoBubbleTemplateLibrary);providerImage.setSource(this._trafficRegionIcon);var trafficInfo=new Label("DescriptionLabel",InfoBubbleSpice.InfoBubbleTemplateLibrary);trafficInfo.getReplica().setInnerHtml("label",this._translations["nokia.maps.pfw.spices.infobubblespice.traffic.affectedstreets"]+"<br/>"+desc);trafficInfo.getReplica().addCssClass("nmp_InfoBubbleTrafficDescription");this._trafficDetails=new Container("TrafficProviderContainer",InfoBubbleSpice.InfoBubbleTemplateLibrary);this._trafficDetails.setChildAt(providerImage,"trafProvImage",true,false);this._trafficDetails.setChildAt(trafficInfo,"trafficDescription",true,false);this._spiceControl.setChildAt(this._trafficDetails,"htmlContainer",true,false);this.setDescription("")}else{this._isTraffic=false;title=selected.getInfoTitle();desc=selected.getInfoDescription();selected.addEventHandler(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,this._onMarkerPropertyChanged,this);if(this._trafficDetails){this._spiceControl.removeChild(this._trafficDetails);this._trafficDetails=null}}var geoCenter=this._mapModel.getMapCenterPosition();var center=this._mapModel.geoToPixel(geoCenter);var animate=false;if(position!==null){animate=(position.x!=center.x||position.y!=center.y)}else{animate=(latLonPos.latitude!=geoCenter.latitude||latLonPos.longitude!=geoCenter.longitude)}this._spiceControl.hide();this._htmlContainer.hide();this._selected=selected;if((selected.getType()=="traffic")||selected.getInfoIcon()){if(!this._iconImage){this._iconImage=new Container("Icon",InfoBubbleSpice.InfoBubbleTemplateLibrary);this._spiceControl.setChildAt(this._iconImage,"icon")}this._spiceControl.getReplica().addCssClass("nmp_InfoBubbleWithIcon");if(selected.getType()=="traffic"){this._iconImage.getRootElement().setAttribute("src",selected.getTrafficIconUrl())}else{this._iconImage.getRootElement().setAttribute("src",selected.getInfoIcon())}}else{if(this._iconImage){this._spiceControl.getReplica().removeCssClass("nmp_InfoBubbleWithIcon");this._spiceControl.removeChild(this._iconImage);this._iconImage=null}}var replica=this._spiceControl.getReplica();replica.removeStyle(TemplateReplica.ROOT_ID,"width");this.setTitle(title);if(!(selected.getType()=="traffic")){this.setDescription(desc)}if(!title||title.length===0||!desc||desc.length===0){this.updateMapMarkerLabels()}this._calculateBodyRectangle();if(this._size.x<this._minWidth){this.setBubbleWidth(this._minWidth)}else{if(this._size.x>this._maxWidth){this.setBubbleWidth(this._maxWidth)}else{this.setBubbleWidth(this._size.x)}}if(animate&&this._moveToCenter){this._setupBubbleAnimation(latLonPos);this._mapModel.moveTo(latLonPos)}else{this._animateBubbleIntoView(latLonPos)}this._moveToCenter=true},_onAnimationStart:function(aEvent){var position=aEvent.getData();var pixel=this._mapModel.toPixel();if(pixel&&position.x===pixel.getX()&&position.y===pixel.getY()){return}if(this._spiceControl.isVisible()){var self=this;if(!this._animationId&&!this._showBubbleOnAnimationEndAt){this._animationId=window.setInterval(function(){self._positionInfoBubble()},33)}}},_onAnimationEnd:function(aEvent){if(this._animationId){window.clearInterval(this._animationId);this._animationId=null}if(this._showBubbleOnAnimationEndAt){var position=this._showBubbleOnAnimationEndAt;this._showBubbleOnAnimationEndAt=null;this._animateBubbleIntoView(position)}},_onMapObjectUnselected:function(){if(!this._hideEffect){if(this._selected){if(this._selected.getType&&this._selected.getType()!="traffic"){this._selected.removeEventHandler(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,this._onMarkerPropertyChanged,this)}this._selected=null;this._infoMarkerId=-1;this._hidedByMinimap=false}this._bubblePosition=null;this.hide()}},_onRightClick:function(aClickEvent){var data=aClickEvent.getData();this.showForMapPosition(this._mapModel.pixelToGeo(data.x,data.y),this.zoomCallbackForMapLocationMarker)},_onMarkerPropertyChanged:function(aPropertyChangedEvent){var data=aPropertyChangedEvent.getData();switch(data.property){case"infoIconUri":if(data.value){if(!this._iconImage){this._iconImage=new Container("Icon",InfoBubbleSpice.InfoBubbleTemplateLibrary);this._spiceControl.setChildAt(this._iconImage,"icon");this._spiceControl.getReplica().addCssClass("nmp_InfoBubbleWithIcon")}this._iconImage.show();this._spiceControl.getReplica().addCssClass("nmp_InfoBubbleWithIcon");this._iconImage.getRootElement().setAttribute("src",data.value)}else{if(this._iconImage){this._iconImage.hide();this._spiceControl.getReplica().removeCssClass("nmp_InfoBubbleWithIcon")}}break;case"infoTitle":this.setTitle(data.value);break;case"infoDescription":this.setDescription(data.value);break;case"position":this._bubblePosition=data.value;break;case"location":this._bubblePosition={longitude:data.value.longitude,latitude:data.value.latitude};break}this._recalculateBodyRectangle=true;if(data.value===undefined||data.value===""||data.property==="position"||data.property==="location"){this.updateMapMarkerLabels()}if(this._spiceControl.isVisible()||this._hidedByMinimap){this._positionInfoBubble()}},_onSizeChanged:function(){this._calculateMinimapRectangle();this._positionInfoBubble()},_onMinimapStateChanged:function(aEvent){var minimapState=aEvent.getData();if(!minimapState.visible||!minimapState.shown){if(this._hidedByMinimap){this._positionInfoBubble();this._spiceControl.show()}}else{if(minimapState.shown){this._calculateMinimapRectangle();if(this._spiceControl.isVisible()){this._checkBubbleOverlappedByMinimap()}}}},_positionInfoBubble:function(){var visible=this._spiceControl.isVisible();if((visible||this._hidedByMinimap||this._hideByPosition)&&this._bubblePosition){var position=null;if(this._bubblePosition.x!==undefined&&this._bubblePosition.x!==null&&this._bubblePosition.y!==undefined&&this._bubblePosition.y!==null){this._bubblePosition=this._mapModel.pixelToGeo(this._bubblePosition.x,this._bubblePosition.y)}position=this._mapModel.geoToPixel(this._bubblePosition);if(position===null||position===undefined){if(visible){this._spiceControl.hide();this._hideByPosition=true}}else{if(!visible){this._spiceControl.show();this._hideByPosition=false}if(this._recalculateBodyRectangle){this._calculateBodyRectangle();this._recalculateBodyRectangle=false}var x=position.x-(this._size.x+this._offset.x)/2;var y=position.y-(this._size.y+this._offset.y);var replica=this._spiceControl.getReplica();replica.setStyle(TemplateReplica.ROOT_ID,"left",x+"px");replica.setStyle(TemplateReplica.ROOT_ID,"top",y+"px")}this._checkBubbleOverlappedByMinimap()}},_setupBubbleAnimation:function(aPosition){this._showBubbleOnAnimationEndAt=aPosition},_animateBubbleIntoView:function(aPosition){if(!this._selected||aPosition===null||aPosition===undefined){return}this._showBubbleOnAnimationEndAt=null;if(this._hideEffect){this._hideEffect.stop();this._hideEffect=null}var replica=this._spiceControl.getReplica();replica.setStyle(TemplateReplica.ROOT_ID,"opacity","0");replica.setStyle(TemplateReplica.ROOT_ID,"left","-9999px");this._spiceControl.show();this._offset=this._selected&&this._selected.getInfoIcon()?{x:InfoBubbleSpice.MARKER_BUBBLE_OFFSET.x,y:InfoBubbleSpice.MARKER_BUBBLE_OFFSET.y}:{x:InfoBubbleSpice.BUBBLE_DEFAULT_OFFSET.x,y:InfoBubbleSpice.BUBBLE_DEFAULT_OFFSET.y};replica.removeCssClass("nmp_InfoBubbleMax");this._size=nokia.aduno.dom.Dimensions.getSize(this._spiceControl.getRootElement());if(this._size.y>390){replica.addCssClass("nmp_InfoBubbleMax");this._size=nokia.aduno.dom.Dimensions.getSize(this._spiceControl.getRootElement())}if(typeof aPosition.latitude=="number"){this._bubblePosition=aPosition}else{if(typeof aPosition.getLatitude=="function"){this._bubblePosition={latitude:aPosition.getLatitude(),longitude:aPosition.getLongitude()}}else{this._bubblePosition=this._mapModel.pixelToGeo(aPosition.x,aPosition.y)}}this._positionInfoBubble();if(!nokia.aduno.utils.browser.msie){this._showEffect=new nokia.aduno.medosui.Fx(this._spiceControl);this._showEffect.addEventHandler("ended",function(){this._showEffect=null;replica.setStyle(TemplateReplica.ROOT_ID,"opacity","1")},this);this._showEffect.effect({duration:200,styles:{opacity:[0,1]},fps:60,transition:"normal"}).start()}},_checkBubbleOverlappedByMinimap:function(){if(!this._minimapSpice){this._initializeMinimap()}if(!this._tipRectangle){this._calculateTipRectangle()}var checkOverlapping=(this._minimapSpice&&this._minimapSpice.isVisible&&this._minimapSpice.isVisible())&&(this._spiceControl.isVisible()||this._hidedByMinimap);if(checkOverlapping){var bodyPosition;var tipPosition;if(this._spiceControl.isVisible()){bodyPosition=nokia.aduno.dom.Dimensions.getPosition(this._spiceControl.getRootElement());tipPosition=nokia.aduno.dom.Dimensions.getPosition(this._spiceControl.getElement("tip"))}else{if(this._hidedByMinimap){this._spiceControl.getReplica().addCssClass("nmp_InfoSpiceHidden");this._spiceControl.show();bodyPosition=nokia.aduno.dom.Dimensions.getPosition(this._spiceControl.getRootElement());tipPosition=nokia.aduno.dom.Dimensions.getPosition(this._spiceControl.getElement("tip"));this._spiceControl.hide();this._spiceControl.getReplica().removeCssClass("nmp_InfoSpiceHidden")}}this._bodyRectangle.left=bodyPosition.x;this._bodyRectangle.top=bodyPosition.y;this._tipRectangle.left=tipPosition.x;this._tipRectangle.top=tipPosition.y;var overlapped=this._rectanglesOverlapped(this._bodyRectangle,this._minimapRectangle)||this._rectanglesOverlapped(this._tipRectangle,this._minimapRectangle);if(overlapped){this._spiceControl.hide();this._hidedByMinimap=true}else{this._spiceControl.show();this._hidedByMinimap=false}}},_rectanglesOverlapped:function(rect1,rect2){if(!rect1||!rect2){return false}return(rect1.left+rect1.width-1>=rect2.left)&&(rect2.left+rect2.width-1>=rect1.left)&&(rect1.top+rect1.height-1>=rect2.top)&&(rect2.top+rect2.height-1>=rect1.top)},_initializeMinimap:function(){this._minimapSpice=this._spiceManager.getSpice("MiniMapSpice");if(this._minimapSpice){this._spiceManager.addEventHandler(SpiceManager.EVENT_SIZE_CHANGED,this._onSizeChanged,this);this._minimapSpice.getUi().addEventHandler(MiniMapSpice.STATE_CHANGED,this._onMinimapStateChanged,this);this._calculateMinimapRectangle()}},_calculateMinimapRectangle:function(){this._minimapRectangle=nokia.aduno.dom.Dimensions.getCoordinates(this._minimapSpice.getUi().getRootElement())},_calculateTipRectangle:function(){this._tipRectangle={width:0,height:0,left:0,top:0};if(this._spiceControl.isVisible()){var size=nokia.aduno.dom.Dimensions.getSize(this._spiceControl.getElement("tip"))}else{this._spiceControl.getReplica().addCssClass("nmp_InfoSpiceHidden");this._spiceControl.show();var size=nokia.aduno.dom.Dimensions.getSize(this._spiceControl.getElement("tip"));this._spiceControl.hide();this._spiceControl.getReplica().removeCssClass("nmp_InfoSpiceHidden")}this._tipRectangle.width=size.x;this._tipRectangle.height=size.y;if(nokia.aduno.utils.browser.msie){this._tipRectangle.width-=10;this._tipRectangle.height-=5}else{this._tipRectangle.width-=10;this._tipRectangle.height-=10}},_calculateBodyRectangle:function(){if(this._spiceControl.isVisible()){this._size=nokia.aduno.dom.Dimensions.getSize(this._spiceControl.getRootElement())}else{this._spiceControl.getReplica().addCssClass("nmp_InfoSpiceHidden");this._spiceControl.show();this._size=nokia.aduno.dom.Dimensions.getSize(this._spiceControl.getRootElement());this._spiceControl.hide();this._spiceControl.getReplica().removeCssClass("nmp_InfoSpiceHidden")}this._bodyRectangle.width=this._size.x;this._bodyRectangle.height=this._size.y;if(nokia.aduno.utils.browser.msie){this._bodyRectangle.width-=5;this._bodyRectangle.height-=60}else{this._bodyRectangle.width-=5;this._bodyRectangle.height-=5}},setTrafficRegionIcon:function(aIcon){this._trafficRegionIcon=aIcon},isTrafficBubble:function(){return this._isTraffic}});InfoBubbleSpice.InfoBubbleTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({InfoBubble:'<div class="nmp_InfoSpice"><div class="nmp_InfoBubbleBodyContainer"><div class="nmp_InfoBubbleContent"><div id="icon"></div><h1 id="title"></h1><span id="description"></span><div id="htmlContainer"></div></div><div id="closeButton"></div></div><div class="nmp_InfoBubbleBottomContainer"><div class="nmp_InfoBubbleCorner"></div></div><div id="tip" class="nmp_InfoBubbleTip"></div></div>',CloseButton:'<span id="button" class="nmp_InfoBubbleCloseButton"></span>',TitleLabel:'<h1 id="label"></h1>',DescriptionLabel:'<span id="label"></span>',Icon:'<img id="iconActual" class="nmp_InfoBubbleIcon" />',Button:'<div class="nmm_Butt"><a id="button"></a></div>',HtmlLabel:'<div id="label"></div>',TrafficProviderContainer:'<div class="nmp_InfoBubbleTrafficContainer"><div class="nmp_InfoBubbleTrafficProvider"><div id="trafProvImage"></div></div><div id="trafficDescription"></div></div>',TrafficProviderImage:'<img id="image"></img>'});InfoBubbleSpice.MARKER_BUBBLE_OFFSET={x:-9,y:3};InfoBubbleSpice.BUBBLE_DEFAULT_OFFSET={x:-5,y:-5};var MapModeSpice=new Class({Name:"MapModeSpice",Extends:Spice,_2dLabel:"__I18N_mapPlayer_38_mapControl_tiltControl_buttonLabel_2d__",_3dLabel:"__I18N_mapPlayer_37_mapControl_tiltControl_buttonLabel_3d__",initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._model=aMapModel},_createUi:function(){var container=new Container("MapMode",MapModeSpice.TemplateLibrary);this._mapModeButton=new Button("MapModeButton",this._model.getMode3d()?this._2dLabel:this._3dLabel);this._mapModeButton.addEventHandler("selected",this._onModeClicked,this);container.setChildAt(this._mapModeButton,"MapModeButton");if(this._model.getPluginControl().isPluginInUse()){this._model.addEventHandler(MapModel.EVENT_TILT,this._onModelTiltChanged,this)}else{this._mapModeButton.getReplica().addCssClass(TemplateReplica.ROOT_ID,"nm_Disabled")}return container},_onModeClicked:function(aEvent){if(!this._model.getPluginControl().isPluginInUse()){this._model.showDownload();return}this._model.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_TILT_START,this._model.getMode3d()));this._model.moveTo({tilt:this._model.getMode3d()?0:this._model.TILT_3D});this._mapModeButton.setText(this._model.getMode3d()?this._3dLabel:this._2dLabel);if(this._spiceManager._localizer){this._spiceManager._localizer.traverse(this._mapModeButton.getRootElement())}},_onModelTiltChanged:function(aEvent){this._mapModeButton.setText(this._model.getMode3d()?this._2dLabel:this._3dLabel);if(this._spiceManager._localizer){this._spiceManager._localizer.traverse(this._mapModeButton.getRootElement())}}});MapModeSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({MapMode:'<div class="nmp_MapModeSpice" unselectable="on"><div id="MapModeButton"></div></div>',MapModeButton:'<div class="nmm_Butt" unselectable="on"><a id="button" unselectable="on"></a></div>'});var MapTypeSpice=new Class({Name:"MapTypeSpice",Extends:Spice,Implements:[Serializable],_mapType:null,_mapTypeButton:null,_mouseBeenOverTheOverlay:false,_mouseOverlayTimer:null,_mouseOverlayTimeout:500,_mouseOverlayFxObj:null,_mouseOverlayFxAct:false,initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._model=aMapModel;this._mapMappings={0:"normal",1:"satellite",2:"terrain"};this._mapNameMappings={normal:0,hybrid:1,terrain:2,satellite:1}},_createUi:function(){this._container=new Container("MapType",MapTypeSpice.TemplateLibrary);this._dialog=new Container("Dialog");this._dialog.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onMouseEnteredOverlay);this._dialog.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onMouseExitedOverlay);this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._dialog);this._dialog.hide();this._mapTypeTopTip=new nokia.aduno.medosui.Container("TopTip",MapTypeSpice.TemplateLibrary);this._dialog.setChildAt(this._mapTypeTopTip,"mapTypeTopTip");var closeButton=new nokia.aduno.medosui.Button("CloseButton","Close");closeButton.addEventHandler("selected",this._onTypeClick,this);this._dialog.setChildAt(closeButton,"closeButton");var normalButton=new Button("NormalButton","__I18N_mapPlayer_17_buttonsArray_mapview_buttonLabel_map__");var satelliteButton=new Button("SatelliteButton","__I18N_mapPlayer_18_buttonsArray_mapview_buttonLabel_satellite__");var terrainButton=new Button("TerrainButton","__I18N_mapPlayer_19_buttonsArray_mapview_buttonLabel_terrain__");this._isJsPlugin=!this._model.getPluginControl().isPluginInUse();this._labelsButton=new CheckButton(null,"__I18N_mapPlayer_68_buttonsArray_mapview_checkbox_labels__");this._labelsButton.addEventHandler("selected",this._onLabelsClicked,this);this._dialog.setChildAt(this._labelsButton,"labelsCheckButton");if(this._isJsPlugin){var satelliteReplica=satelliteButton.getReplica();var terrainReplica=terrainButton.getReplica();var labelsReplica=this._labelsButton.getReplica();if(nokia.aduno.utils.browser.msie){satelliteReplica.setStyle(TemplateReplica.ROOT_ID,"filter","alpha(opacity = 40)");terrainReplica.setStyle(TemplateReplica.ROOT_ID,"filter","alpha(opacity = 40)")}else{satelliteReplica.setStyle(TemplateReplica.ROOT_ID,"opacity","0.4");terrainReplica.setStyle(TemplateReplica.ROOT_ID,"opacity","0.4")}labelsReplica.setAttribute("checkButtonButton","disabled","true")}else{this._container.getReplica().addCssClass(TemplateReplica.ROOT_ID,"nmp_MapTypesForPlugin")}var mapType=new SelectionList("TypeSelector",null,"nm_Selected");this._mapType=mapType;this._mapTypeButton=new Button(null,"__I18N_mapPlayer_17_buttonsArray_mapview_buttonLabel_map__");this._mapTypeButton.addEventHandler("selected",this._onTypeClick,this);mapType.addChild(normalButton);mapType.addChild(satelliteButton);mapType.addChild(terrainButton);if(this._isJsPlugin){mapType.setSelectionIndex(0);this._labelsButton.setState(true)}else{mapType.setSelectionIndex(this._mapNameMappings[this._model.getMapType()]||0)}mapType.addEventHandler("selected",this._onTypeSelected,this);this._dialog.setChildAt(this._mapType,"TypeSelector");this._container.setChildAt(this._dialog,"MapTypeDialog");this._container.setChildAt(this._mapTypeButton,"TypeButton");this._model.addEventHandler(MapModel.EVENT_MAPTYPE,this._onModelMapTypeChanged,this);this._container.handleKey=function(aKeyEvent){return true};return this._container},_onTypeClick:function(aSelectEvent){if(!this._dialog.isVisible()||this._mouseOverlayFxAct){this._showMenuDialog()}else{this._hideMenuDialog()}},_onLabelsClicked:function(aSelectEvent){if(this._isJsPlugin){this._labelsButton.setState(true);return}var state=aSelectEvent.source.getState();var mapType=this._model.getMapType();if(state&&mapType=="satellite"){this._model.setMapType("hybrid")}else{if(!state&&mapType=="hybrid"){this._model.setMapType("satellite")}}},_showMenuDialog:function(){this._mapTypeButton.getReplica().addCssClass("nmm_Selected");this._spiceManager.handleModalSpiceOpened(this);if(this._mouseOverlayFxAct){this._mouseOverlayFxObj.stop();delete this._mouseOverlayFxObj;this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._dialog);this._mouseOverlayFxAct=false}this._dialog.getReplica().setStyle(TemplateReplica.ROOT_ID,"opacity","1");this._dialog.show();this._container.focus();var dialogPos=nokia.aduno.dom.Dimensions.getPosition(this._dialog.getRootElement(),this._spiceControl.getRootElement().parentNode.parentNode);var buttonPos=nokia.aduno.dom.Dimensions.getPosition(this._mapTypeButton.getRootElement(),this._spiceControl.getRootElement().parentNode.parentNode);var buttonSize=nokia.aduno.dom.Dimensions.getSize(this._mapTypeButton.getRootElement());var tipSize=nokia.aduno.dom.Dimensions.getSize(this._mapTypeTopTip.getRootElement());var tipLeft=Math.round(buttonPos.x+(buttonSize.x/2)-(tipSize.x/2)-dialogPos.x);this._mapTypeTopTip.getReplica().setStyle(TemplateReplica.ROOT_ID,"left",tipLeft+"px")},_hideMenuDialog:function(){if(!this._mouseOverlayFxAct){this._mouseOverlayFxAct=true;this._mouseBeenOverTheOverlay=false;this._mapTypeButton.getReplica().removeCssClass("nmm_Selected");if(nokia.aduno.utils.browser.msie){this._mouseOverlayFxAct=false;this._container.blur();this._dialog.hide()}else{this._mouseOverlayFxObj.addEventHandler("ended",function(){this._mouseOverlayFxAct=false;this._container.blur();this._dialog.hide()},this);this._mouseOverlayFxObj.effect({duration:300,styles:{opacity:[1,0]}}).start()}}},_enableOrDisableLabelCheckButton:function(){if(this._mapType.getSelectionIndex()===1){this._labelsButton.enable()}else{this._labelsButton.disable()}},_onTypeSelected:function(aSelectEvent){if(this._ignoreTypeSelectedEvent){this._ignoreTypeSelectedEvent=false;return}var data=aSelectEvent.getData();var type=this._mapMappings[data.selectedIndex]||"normal";if((this._isJsPlugin)&&(data.selectedIndex==1||data.selectedIndex==2)){this._mapType.setSelectionIndex(0);this._model.showDownload();type=this._mapMappings[0]}if(this._dialog.isVisible()){this._hideMenuDialog()}if(type=="satellite"&&this._labelsButton.getState()){type="hybrid"}if((!this._isJsPlugin)&&(this._model.getMapType()!==this._mapMappings[data.selectedIndex])){this._model.setMapType(type);this._mapTypeButton.setText(this._mapType.getChildAt(data.selectedIndex).getText());this._enableOrDisableLabelCheckButton()}},_onModelMapTypeChanged:function(aEvent){var data=aEvent.getData();var type=this._model.getMapType();if(type=="satellite"&&this._labelsButton.getState()){this._labelsButton.setState(false)}else{if(type=="hybrid"&&!this._labelsButton.getState()){this._labelsButton.setState(true)}}if(this._mapType.getSelectionIndex()!==this._mapNameMappings[data]){this._ignoreTypeSelectedEvent=true;this._mapType.setSelectionIndex(this._mapNameMappings[type]);this._mapTypeButton.setText(this._mapType.getChildAt(this._mapType.getSelectionIndex()).getText());this._enableOrDisableLabelCheckButton()}},_onMouseEnteredOverlay:function(aMouseOverEvent){this._mouseBeenOverTheOverlay=true;if(this._mouseOverlayTimer){clearTimeout(this._mouseOverlayTimer)}this._mouseOverlayTimer=null},_onMouseExitedOverlay:function(aMouseOutEvent){if(this._mouseBeenOverTheOverlay&&!this._mouseOverlayFxAct){var x=aMouseOutEvent.get("pageX");var y=aMouseOutEvent.get("pageY");var rect=nokia.aduno.dom.Dimensions.getCoordinates(this._mapType.getRootElement());if(x<rect.left||x>=rect.left+rect.width||y<rect.top||y>=rect.top+rect.height){var self=this;this._mouseOverlayTimer=setTimeout(function(){self._hideMenuDialog()},this._mouseOverlayTimeout)}}},onOtherSpiceReceivedFocus:function(){this._hideMenuDialog()},serialize:function(aPersistence){if(!this._isJsPlugin){aPersistence.addData("Labels",this._labelsButton.getState()+"")}},deserialize:function(aPersistence){if(!this._isJsPlugin){this._labelsButton.setState(false);try{if(aPersistence.getData("Labels")=="true"){this._labelsButton.setState(true)}}catch(err){this._labelsButton.setState(true)}}}});MapTypeSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({MapType:'<div class="nmp_MapTypeSpice" unselectable="on"><div id="TypeButton"></div><div id="MapTypeDialog"></div></div>',Dialog:'<div class="nmp_MapTypeDialog" style="height: 189px" unselectable="on"><div id="mapTypeTopTip"></div><div id="TypeSelector"></div><div style="clear: both" unselectable="on"></div><div class="nmp_MapTypeOptions" unselectable="on"><div class="nmp_MapTypeColsLeft" unselectable="on"></div><div class="nmp_MapTypeColsMid" unselectable="on"><div id="labelsCheckButton"></div></div><div class="nmp_MapTypeColsRight" unselectable="on"></div><div style="clear: both"></div></div><div class="nmp_MapTypePosCloseButton"><div id="closeButton"></div></div></div>',TypeButton:'<span id="button" class="nmp_MapTypeButton" unselectable="on"></span>',CheckButton:'<div id="checkButton" unselectable="on"><input type="checkbox" id="checkButtonButton" unselectable="on"></input><span id="checkButtonText" unselectable="on"></span></div>',TypeSelector:'<div class="nmp_MapTypeSelect" unselectable="on"></div>',NormalButton:'<div class="nmp_MapTypeColsLeft" unselectable="on"><div class="nmp_MapTypeLabel" id="button" unselectable="on"></div><div class="nmp_MapTypeNormalButton" unselectable="on"><span unselectable="on"></span></div></div>',SatelliteButton:'<div class="nmp_MapTypeColsMid" unselectable="on"><div class="nmp_MapTypeLabel" id="button" unselectable="on"></div><div class="nmp_MapTypeSatelliteButton" unselectable="on"><span unselectable="on"></span></div></div>',TerrainButton:'<div class="nmp_MapTypeColsRight" unselectable="on"><div class="nmp_MapTypeLabel" id="button" unselectable="on"></div><div class="nmp_MapTypeTerrainButton" unselectable="on"><span unselectable="on"></span></div></div>',CloseButton:'<span id="button" class="nmp_MapTypeCloseButton" unselectable="on"></span>',Button:'<div class="nmm_Butt" unselectable="on"><a id="button" unselectable="on"></a></div>',TopTip:'<div class="nmp_MapTypeTopTip" unselectable="on"></div>'});var TrafficSpice=new Class({Name:"TrafficSpice",Extends:Spice,_trafficInfoVisible:false,initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._model=aMapModel;this._pfwPath=aSpiceManager.getOption("pfwPath")},_createUi:function(){var container=new Container("Traffic",TrafficSpice.TrafficTemplateLibrary);this._trafficInfoVisible=this._model.getTrafficInfoVisible();this._trafficInfoButton=new Button("TrafficInfoButton","Traffic");this._trafficInfoButton.addEventHandler("selected",this._onTrafficInfoClick,this);if(this._trafficInfoVisible){this._trafficInfoButton.getReplica().addCssClass("nmm_Selected")}else{this._trafficInfoButton.getReplica().removeCssClass("nmm_Selected")}container.setChildAt(this._trafficInfoButton,"TrafficInfoButton");if(!this._model.getPluginControl().isPluginInUse()){container.getReplica().addCssClass(TemplateReplica.ROOT_ID,"nm_Disabled")}else{this._model.addEventHandler(MapModel.EVENT_TRAFFIC_INFO,this._onModelTrafficInfoChanged,this)}this._model.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onModelZoomChange,this);this._model.addEventHandler(MapModel.EVENT_MOVE_DONE,this._onModelMapMoveDone,this);var binder=this;container.accept=function(aVisitor){binder._model.setMapLanguage(binder._spiceManager._language)};return container},_onTrafficInfoClick:function(aEvent){if(!this._model.getPluginControl().isPluginInUse()){this._model.showDownload();return}this._trafficInfoVisible=!this._model.getTrafficInfoVisible();var trafficLegend=this._spiceManager.getSpice("TrafficLegendSpice");if(this._trafficInfoVisible){this._trafficInfoButton.getReplica().addCssClass("nmm_Selected");if(trafficLegend){trafficLegend.show()}}else{this._trafficInfoButton.getReplica().removeCssClass("nmm_Selected");if(trafficLegend){trafficLegend.hide()}}this._model.setTrafficInfoVisible(this._trafficInfoVisible);this._checkBoundaries()},_onModelMapMoveDone:function(aEvent){var mapSize=this._model.getMapSize();var infoSpice=this._spiceManager.getSpice("InfoBubbleSpice");if(infoSpice){if(infoSpice.isTrafficBubble()&&infoSpice._bubblePosition){var bubblePosInPx=this._model.geoToPixel(infoSpice._bubblePosition);if(bubblePosInPx){if((bubblePosInPx.x+(infoSpice._bodyRectangle.width/2))>mapSize.width||(bubblePosInPx.x<(infoSpice._bodyRectangle.width/2))||(bubblePosInPx.y-(infoSpice._bodyRectangle.height)<0)){infoSpice.hide()}}else{infoSpice.hide()}}}},_onModelZoomChange:function(aEvent){var zoomScale=aEvent.source.getZoomScale();if(zoomScale>2000){var infoSpice=this._spiceManager.getSpice("InfoBubbleSpice");if(infoSpice){if(infoSpice._selected&&infoSpice._selected.getType&&infoSpice._selected.getType()==="traffic"){infoSpice.hide()}}}},_onModelTrafficInfoChanged:function(aEvent){var visible=aEvent.getData()=="visible";if(visible!==this._trafficInfoVisible){this._trafficInfoVisible=visible;if(this._trafficInfoVisible){this._trafficInfoButton.getReplica().addCssClass("nmm_Selected")}else{this._trafficInfoButton.getReplica().removeCssClass("nmm_Selected")}}},_checkBoundaries:function(){var centerPosition=this._model.getMapCenterPosition();this._model.reverseGeoCode(centerPosition,this._handleReverseGeoCode,this)},_handleReverseGeoCode:function(aLocations){var inTrafficRegion=false;var region=null;if(aLocations.length>0){var countryCode=aLocations[0].ADDR_COUNTRY_CODE;for(var i=0,len=TrafficSpice.TRAFFIC_REGIONS.length;i<len;i++){region=TrafficSpice.TRAFFIC_REGIONS[i];if(countryCode===region.countryCode){inTrafficRegion=true;break}}}if(inTrafficRegion){if(!this._spiceControl.isVisible()){this._spiceControl.show()}if(this._trafficInfoVisible){this._model._map.setTrafficInfoCenter(this._model._map.getCenter());var icon=this._pfwPath+"images/spices/traffic/"+region.icon;this._spiceManager.getSpice("InfoBubbleSpice").setTrafficRegionIcon(icon)}}else{if(this._spiceControl.isVisible()){this._spiceControl.hide();this._model.setTrafficInfoVisible(false)}}},onAttach:function(){if(this._model.getPluginControl().isPluginInUse()){this._model.addEventHandler(MapModel.EVENT_MOVE_DONE,this._checkBoundaries,this)}}});TrafficSpice.TrafficTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({Traffic:'<div class="nmp_TrafficSpice"><div id="TrafficInfoButton"></div><div id="trafficLegend"></div></div>',TrafficInfoButton:'<div class="nmp_TrafficInfoButton"><span id="button"></span></div>'});TrafficSpice.AUSTRALIA={icon:"roadsense.jpg",countryCode:"AUS"};TrafficSpice.USA={icon:"navteq.jpg",countryCode:"USA"};TrafficSpice.CANADA={icon:"navteq.jpg",countryCode:"CAN"};TrafficSpice.GERMANY={icon:"adac.jpg",countryCode:"DEU"};TrafficSpice.AUSTRIA={icon:"oeamtc.jpg",countryCode:"AUT"};TrafficSpice.FRANCE={icon:"navteq.jpg",countryCode:"FRA"};TrafficSpice.UK={icon:"itis.jpg",countryCode:"GBR"};TrafficSpice.FINLAND={icon:"destia.jpg",countryCode:"FIN"};TrafficSpice.SPAIN={icon:"race.jpg",countryCode:"ESP"};TrafficSpice.SWITZERLAND={icon:"tcs.jpg",countryCode:"CHE"};TrafficSpice.NETHERLANDS={icon:"anwb.jpg",countryCode:"NLD"};TrafficSpice.SINGAPORE={icon:"mib.jpg",countryCode:"SGP"};TrafficSpice.TRAFFIC_REGIONS=[TrafficSpice.AUSTRALIA,TrafficSpice.AUSTRIA,TrafficSpice.CANADA,TrafficSpice.FINLAND,TrafficSpice.GERMANY,TrafficSpice.NETHERLANDS,TrafficSpice.SINGAPORE,TrafficSpice.SPAIN,TrafficSpice.SWITZERLAND,TrafficSpice.UK,TrafficSpice.USA];var BounceSpice=new Class({Name:"BounceSpice",Extends:Spice,_mapModel:null,initialize:function(aSpiceManager,aMapModel){this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._mapModel.addEventHandler(MapModel.EVENT_MAPOBJECT_SELECTED,this._onMapObjectSelected,this);this._mapModel.addEventHandler(MapModel.EVENT_MAPOBJECT_UNSELECTED,this._onMapObjectUnselected,this);this._interval=null;this._frames=30;this._currentFrame=0},_onMapObjectSelected:function(aEvent){this._selected=aEvent.getData();if(this._selected._nativeIcon){this._originalWidth=this._selected._nativeIcon.getIcon().getWidth();this._originalHeight=this._selected._nativeIcon.getIcon().getHeight();var bound=this;var handler=function(){bound._onIteration.call(bound)};this._interval=setInterval(handler,1000/this._frames);this._currentFrame=0}},_onMapObjectUnselected:function(aEvent){if(this._interval){cancelTimer(this._interval);this._interval=null}if(this._selected&&this._selected._nativeIcon){this._selected._nativeIcon.setSize(this._originalWidth,this._originalHeight)}this._selected=null},_bounceFunction:function(aValue){return(1.5-(Math.cos(Math.PI*4*aValue))/2)},_onIteration:function(){this._currentFrame++;if(this._currentFrame>=this._frames){cancelTimer(this._interval);this._interval=null;if(this._selected._nativeIcon){this._selected._nativeIcon.setSize(this._originalWidth,this._originalHeight)}if(this._selected._nativeLayer){this._mapModel._map.addLayer(this._selected.getLayer().getNativeLayer())}return}var val=Math.floor(32*this._bounceFunction(this._currentFrame/this._frames));this._selected._nativeIcon.setSize(val,val);this._mapModel._map.addLayer(this._selected.getLayer().getNativeLayer())}});var OrientationTiltWheel=new nokia.aduno.utils.Class({Extends:nokia.aduno.medosui.Control,Name:"OrientationTiltWheel",_compassSize:63,_diamondSize:65,_buttonSize:33,_northAngle:18,_overTiltDistance:16,_centerDistance:32,_repeaterInterval:100,_rotatorInterval:50,initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._angle=0;this._tiltVisible=true;this._tiltRepeater=null;this._tiltRepeaterRun=false;this._isRotatingNorth=false;this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OVER,this,this._handleMouseOver);this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this,this._handleMouseOut);this._replica.addEventHandler("overUpper",nokia.aduno.dom.XNode.DOM_MOUSE_OVER,this,this._handleMouseOverTilt);this._replica.addEventHandler("overUpper",nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this,this._handleMouseOutTilt);this._replica.addEventHandler("overLower",nokia.aduno.dom.XNode.DOM_MOUSE_OVER,this,this._handleMouseOverTilt);this._replica.addEventHandler("overLower",nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this,this._handleMouseOutTilt);this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._handleMouseDown);var node=new XNode(document).addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,bindWithEvent(this,this._handleMouseUp));this.addBehavior(new Draggable());this.addEventHandler("dragged",this._onDrag,this)},setWheelPosition:function(aAngleStep){if(aAngleStep===this._angle){return}if(this._northRotator){nokia.aduno.utils.cancelPeriodical(this._northRotator);this._northRotator=null;this._isRotatingNorth=false}this._angle=aAngleStep%360;this._updateCss()},setTiltVisible:function(aVisible){if(aVisible){this._tiltVisible=true;this.getReplica().removeCssClass("tilt","nm_Hidden");this.getReplica().removeCssClass("text","nm_Hidden");this.getReplica().removeCssClass(TemplateReplica.ROOT_ID,"nm_Disabled")}else{this._tiltVisible=false;this.getReplica().addCssClass("tilt","nm_Hidden");this.getReplica().addCssClass("text","nm_Hidden");this.getReplica().addCssClass(TemplateReplica.ROOT_ID,"nm_Disabled");this._handleMouseOutTilt()}},_onDrag:function(aDragEvent){if(!this._isEnabled){return}var data=aDragEvent.getData();if(isNaN(data.mouseX)||isNaN(data.mouseY)){return}var calc=this._calculateToCenter(data.mouseX,data.mouseY);if(!this._wasDragged){this._initialDragAngle=calc.angle-this._angle}this._wasDragged=true;this.setWheelPosition(calc.angle-this._initialDragAngle);this.fireEvent(new nokia.aduno.utils.Event("rotated",this._angle))},_handleMouseOver:function(aEvent){this._over=true;this._updateCss()},_handleMouseOut:function(aEvent){this._over=false;this._updateCss()},_handleMouseOverTilt:function(aEvent){this._overTilt=true;if(aEvent.get("target")===this.getElement("overUpper")){this._upperTilt=true}else{this._upperTilt=false}this._updateCss()},_handleMouseOutTilt:function(aEvent){this._overTilt=false;this._downTilt=false;this._upperTilt=false;if(this._tiltRepeater){nokia.aduno.utils.cancelPeriodical(this._tiltRepeater);this._tiltRepeater=null}this._tiltRepeaterRun=false;this._updateCss()},_handleMouseDown:function(aEvent){if(aEvent.get("which")!==1||isNaN(aEvent.get("pageX"))||isNaN(aEvent.get("pageY"))){return}if(!this._isEnabled){this.fireEvent(new nokia.aduno.utils.Event(OrientationTiltWheel.EVENT_CLICKED,null));return}if(this._northRotator&&!this._isRotatingNorth){nokia.aduno.utils.cancelPeriodical(this._northRotator);this._isRotatingNorth=false;this._northRotator=null}var calc=this._calculateToCenter(aEvent.get("pageX"),aEvent.get("pageY"));if(calc.distance<this._overTiltDistance){this._downTilt=true;this._updateCss();this._tiltRepeaterRun=false;this._tiltRepeater=nokia.aduno.utils.setPeriodical(this._repeaterInterval,this,this._doTiltRepeat);aEvent.stopPropagation()}else{if(calc.distance>this._centerDistance){aEvent.stopPropagation()}else{this._downWheel=true;this._wasDragged=false;this._updateCss()}}},_handleMouseUp:function(aEvent){if(aEvent.get("which")!==1||isNaN(aEvent.get("pageX"))||isNaN(aEvent.get("pageY"))){return}var calc=this._calculateToCenter(aEvent.get("pageX"),aEvent.get("pageY"));if(calc.distX>this._centerDistance||calc.distY>this._centerDistance){this._over=false}if(this._tiltRepeater){nokia.aduno.utils.cancelPeriodical(this._tiltRepeater);this._tiltRepeater=null}if(this._over&&this._downWheel){if(!this._wasDragged&&!this._isRotatingNorth){if(calc.north){this._initialRotateAngle=this._angle;this._rotateTime=0;this._northRotator=nokia.aduno.utils.setPeriodical(this._rotatorInterval,this,this._doRotateNorth)}else{this.setWheelPosition(calc.angle);this.fireEvent(new nokia.aduno.utils.Event("rotated",calc.angle))}}}else{if(this._overTilt&&this._downTilt&&!this._tiltRepeaterRun){if(this._upperTilt){this.fireEvent(new nokia.aduno.utils.Event("tilted","up"))}else{this.fireEvent(new nokia.aduno.utils.Event("tilted","down"))}}}this._downWheel=false;this._downTilt=false;this._wasDragged=false;this._updateCss()},_doTiltRepeat:function(){this._tiltRepeaterRun=true;if(this._upperTilt){this.fireEvent(new nokia.aduno.utils.Event("tilted","up"))}else{this.fireEvent(new nokia.aduno.utils.Event("tilted","down"))}},_rotateFunction:function(x){return Math.pow(x,1/2)},_doRotateNorth:function(){if(this._rotateTime>=1){this.setWheelPosition(0);this.fireEvent(new nokia.aduno.utils.Event("rotated",0));this._isRotatingNorth=false;return}else{this._rotateTime=Math.min(1,this._rotateTime+0.075);if(this._initialRotateAngle>180){this._angle=360-((360-this._initialRotateAngle)*(1-this._rotateFunction(this._rotateTime)))}else{this._angle=this._initialRotateAngle*(1-this._rotateFunction(this._rotateTime))}this._angle=Math.floor((this._angle+360)%360);this._isRotatingNorth=(this._angle>0)?true:false;this.fireEvent(new nokia.aduno.utils.Event("rotated",this._angle));this._updateCss()}},_calculateToCenter:function(mouseX,mouseY){var pos=nokia.aduno.dom.Dimensions.getPosition(this.getRootElement());var ret={};ret.distX=mouseX-(pos.x+this._centerDistance);ret.distY=mouseY-(pos.y+this._centerDistance);ret.distance=(Math.sqrt(Math.pow(ret.distX,2)+Math.pow(ret.distY,2)));if(ret.distY>0&&ret.distX>=0){ret.angle=90+(Math.asin(Math.abs(ret.distY)/ret.distance)*180/Math.PI)}else{if(ret.distY<0&&ret.distX<0){ret.angle=270+(Math.asin(Math.abs(ret.distY)/ret.distance)*180/Math.PI)}else{if(ret.distX>=0){ret.angle=(Math.asin(Math.abs(ret.distX)/ret.distance)*180/Math.PI)}else{ret.angle=180+(Math.asin(Math.abs(ret.distX)/ret.distance)*180/Math.PI)}}}ret.angle=Math.floor(ret.angle);var angle=Math.floor(this._angle/10)*10;if(angle<this._northAngle){ret.north=(ret.angle>360-this._northAngle+angle||ret.angle<angle+this._northAngle)}else{if(angle>=360-this._northAngle){ret.north=(ret.angle>angle-this._northAngle||ret.angle<angle-360-this._northAngle)}else{ret.north=(ret.angle>angle-this._northAngle&&ret.angle<angle+this._northAngle)}}return ret},_updateCss:function(){var step=Math.floor(this._angle/10);var xText=step%9;var yText=Math.floor(step/9);var xBack=step%9;var yBack=0;if(this._downWheel){yBack=2}else{if(this._over&&!this._overTilt){yBack=1}}var yTilt=0;if((this._overTilt||this._downTilt)&&!this._downWheel){if(this._upperTilt){yTilt=1}else{yTilt=2}if(this._downTilt){yTilt+=2}}if(this._tiltVisible){this.getReplica().setStyle("back","background-position",(-this._compassSize*xBack)+"px "+(-this._compassSize*yBack)+"px");this.getReplica().setStyle("text","background-position",(-this._diamondSize*xText)+"px "+(-this._diamondSize*yText)+"px");this.getReplica().setStyle("tilt","background-position","0px "+(-this._buttonSize*yTilt)+"px")}}});OrientationTiltWheel.EVENT_CLICKED="clicked";var OrientationTiltSpice=new Class({Name:"OrientationTiltSpice",Extends:Spice,_mapModel:null,_tiltStep:5,_orientationStep:3,initialize:function(aSpiceManager,aMapModel){this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._mapModel.addEventHandler(MapModel.EVENT_TILT,this._onModelTiltChanged,this);this._mapModel.addEventHandler(MapModel.EVENT_ORIENTATION,this._onModelOrientationChanged,this);this._maxTilt=this._mapModel.MAX_TILT;if(this._mapModel.getPluginControl().isPluginInUse()){if(nokia.aduno.utils.browser.s60){this._spiceManager.setKeyHandler(KeyEventManager.KEY_4,0,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_6,0,nokia.aduno.utils.bind(this,this._handleKey))}else{this._spiceManager.setKeyHandler(KeyEventManager.KEY_LEFT,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_RIGHT,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_UP,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_DOWN,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey))}}},_createUi:function(){if(nokia.maps.pfw.layout.snc){return null}else{var control=new OrientationTiltWheel(null,OrientationTiltSpice.OrientationTiltSpiceTemplateLibrary);control.addEventHandler("rotated",this._onUiOrientationChanged,this);control.addEventHandler("tilted",this._onUiTiltSelected,this);if(!this._mapModel.getPluginControl().isPluginInUse()){control.disable();control.setTiltVisible(false);control.addEventHandler(OrientationTiltWheel.EVENT_CLICKED,this._onUiClicked,this)}return control}},_handleKey:function(aKeyEvent){var key=aKeyEvent.getKey();var orientation=this._mapModel.getOrientation();var tilt=this._mapModel.getTilt();if(nokia.aduno.utils.browser.s60){switch(key){case KeyEventManager.KEY_4:this._mapModel.setOrientation(orientation-this._orientationStep);break;case KeyEventManager.KEY_6:this._mapModel.setOrientation(orientation+this._orientationStep);break}}else{if(aKeyEvent.keyPress||aKeyEvent.keyDown){if(key===KeyEventManager.KEY_LEFT){this._mapModel.setOrientation(orientation-this._orientationStep)}if(key===KeyEventManager.KEY_RIGHT){this._mapModel.setOrientation(orientation+this._orientationStep)}if(key===KeyEventManager.KEY_UP){this._mapModel.setTilt(Math.min(this._maxTilt,tilt+this._tiltStep))}if(key===KeyEventManager.KEY_DOWN){this._mapModel.setTilt(Math.max(0,tilt-this._tiltStep))}}}},_onUiOrientationChanged:function(aEvent){this._mapModel.setOrientation(360-aEvent.getData())},_onUiTiltSelected:function(aEvent){var tilt=this._mapModel.getTilt();if(aEvent.getData()==="up"){this._mapModel.setTilt(Math.min(this._maxTilt,tilt+this._tiltStep))}else{this._mapModel.setTilt(Math.max(0,tilt-this._tiltStep))}},_onModelTiltChanged:function(aEvent){},_onModelOrientationChanged:function(aEvent){if(!nokia.maps.pfw.layout.snc){this._spiceControl.setWheelPosition(360-aEvent.getData())}},_onUiClicked:function(aEvent){this._mapModel.showDownload()}});OrientationTiltSpice.OrientationTiltSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({OrientationTiltWheel:'<div class="nmm_orTiWhee" unselectable="on"><div class="nmm_orWheeBack" id="back" unselectable="on"></div><div class="nmm_orWheeText" id="text" unselectable="on"></div><div class="nmm_tiltButt" id="tilt" unselectable="on"><div class="nmm_tiltUpper" id="overUpper" unselectable="on"></div><div class="nmm_tiltLower" id="overLower" unselectable="on"></div></div></div>',Draggable:'<div id="draggable" unselectable="on"></div>'});var PositionSpice=new Class({Name:"PositionSpice",Extends:Spice,_publicMethods:["moveToPosition"],initialize:function(aSpiceManager,aMapModel,aPositionModel,aZoomModel){this._map=aMapModel;this._zoomModel=aZoomModel;this._spiceManager=aSpiceManager;this._zoomEventCounter=0;this._positionEventCounter=0;this._isTracking=false;this._map.setAutoTracking(false);this._position=aPositionModel;this._position.addEventHandler(PositionModel.EVENT_POSITION,this.onPositionChanged,this);this._position.addEventHandler(PositionModel.EVENT_PROVIDER,this.onProviderChanged,this);this._map.addEventHandler(MapModel.EVENT_AUTO_TRACKING_CHANGED,this.onAutoTrackingChanged,this);this._spiceManager.setKeyHandler(50,0,nokia.aduno.utils.bind(this,this.handleKey));this._pfwPath=this._spiceManager.getOption("pfwPath");var position=this._position.getPosition();this._markers={accurate2d:null,accurate3d:null,inaccurate2d:null,inaccurate3d:null};if(nokia.aduno.utils.browser.s60){this._markers.accurate2d=new MapMarker(null,position,this._pfwPath+"images\\spices\\position\\pos_accurate.bmp");this._markers.inaccurate2d=new MapMarker(null,position,this._pfwPath+"images\\spices\\position\\pos_inaccurate.bmp");this._markers.accurate3d=this._markers.accurate2d;this._markers.inaccurate3d=this._markers.inaccurate2d}else{if(nokia.aduno.utils.platform.maemo){this._markers.accurate2d=new MapMarker(null,position,this._pfwPath+"images/spices/maemoposition/pos_accurate.svg");this._markers.inaccurate2d=new MapMarker(null,position,this._pfwPath+"images/spices/maemoposition/pos_inaccurate.svg");this._markers.accurate3d=new MapMarker(null,position,this._pfwPath+"images/spices/maemoposition/pos_accurate_3d.svg");this._markers.inaccurate3d=new MapMarker(null,position,this._pfwPath+"images/spices/maemoposition/pos_inaccurate_3d.svg");this._map.addEventHandler(MapModel.EVENT_TILT,this._onTiltChanged,this)}else{this._markers.accurate2d=new MapMarker(null,position,this._pfwPath+"images/spices/position/pos_accurate.svg");this._markers.inaccurate2d=new MapMarker(null,position,this._pfwPath+"images/spices/position/pos_inaccurate.svg");this._markers.accurate3d=this._markers.accurate2d;this._markers.inaccurate3d=this._markers.inaccurate2d}}this._myControl=null},_createUi:function(){return null},getPosition:function(){if(this._position){return this._position.getPosition()}else{return null}},moveToPosition:function(){var position=this.getPosition();if(position){this._map.moveTo(position)}},onMapMoved:function(aEvent){if(this.isTracking()&&this._positionEventCounter===0){this.setTrackingEnabled(false)}else{this._positionEventCounter--}},onMapZoomChange:function(aEvent){if(this.isTracking()&&this._zoomEventCounter===0){this.setTrackingEnabled(false)}else{this._zoomEventCounter--}},onMapTiltChanged:function(){this.setTrackingEnabled(false)},_onTiltChanged:function(aData){this._setCurrentMarker()},onMapOrientationChanged:function(){this.setTrackingEnabled(false)},setTrackingEnabled:function(aFlag){if(aFlag&&!this.isTracking()){this._isTracking=true;this._positionEventCounter=0;this._zoomEventCounter=0;this._map.addEventHandler(MapModel.EVENT_POSITION_CHANGED,this.onMapMoved,this);this._map.addEventHandler(MapModel.EVENT_TILT,this.onMapTiltChanged,this);this._map.addEventHandler(MapModel.EVENT_ORIENTATION,this.onMapOrientationChanged,this);this._map.setAutoTracking(false)}else{if(!aFlag&&this.isTracking()){this._isTracking=false;this._map.removeEventHandler(MapModel.EVENT_POSITION_CHANGED,this.onMapMoved,this);this._map.removeEventHandler(MapModel.EVENT_TILT,this.onMapTiltChanged,this);this._map.removeEventHandler(MapModel.EVENT_ORIENTATION,this.onMapOrientationChanged,this)}}},onPositionChanged:function(aEvent){var data=aEvent.getData();if(nokia.aduno.utils.platform.maemo){this._spiceManager.getSpice("MaemoInfoBarSpice").updateDistanceInfo()}if(!this._currentMarker){return}this._currentMarker.setPosition(data.position);if(this.isTracking()){this._positionEventCounter++;this._map.setMapCenterPosition(data.position)}},onProviderChanged:function(aEvent){this._setCurrentMarker();if(!this._currentMarker){return}var provider=aEvent.getData();if(this.isTracking()){if(provider!=PositionModel.PROVIDER_NONE){this._map.setMapCenterPosition(this._currentMarker.getPosition());this._zoomModel.setStep(PositionSpice.ZOOMLEVELS[provider])}}},onAutoTrackingChanged:function(aEvent){if(this.isTracking()&&this._map.getAutoTracking()){this.setTrackingEnabled(false)}},isTracking:function(){return this._isTracking},handleKey:function(aKeyEvent){if(aKeyEvent.keyDown){var key=aKeyEvent.getKey();switch(key){case KeyEventManager.KEY_2:this.setTrackingEnabled(!this.isTracking());break;case KeyEventManager.KEY_0:this.moveToPosition();break}}},_setCurrentMarker:function(){if(this.isTracking()){this.setTrackingEnabled(true)}var newMarker=null;var posMethod=this._position.getPositioningTechnologyID();var pos=(posMethod!=PositionModel.PROVIDER_NONE)?this._position.getPosition():this._map.getMapCenterPosition();var zoomStep=null;var oldMarker=this._currentMarker;var markerName="inaccurate";switch(posMethod){case PositionModel.PROVIDER_GPS:case PositionModel.PROVIDER_CELL:zoomStep=PositionSpice.ZOOMLEVELS[posMethod];break;case PositionModel.PROVIDER_WIFI:case PositionModel.PROVIDER_IP:markerName="accurate";zoomStep=PositionSpice.ZOOMLEVELS[posMethod];break;default:if(this._position._isDemo()){zoomStep=PositionSpice.ZOOMLEVELS[posMethod]}else{markerName=null}}if(markerName){markerName+=this._map.getMode3d()?"3d":"2d";this._currentMarker=this._markers[markerName]||null;if(oldMarker!=this._currentMarker){if(oldMarker){oldMarker.hide()}if(this._currentMarker){if(!this._currentMarker.wasAddedToMap()){this._map.addToLayer(this._currentMarker,"positionLayer")}this._currentMarker.show()}}}else{return}if(this.isTracking()){this._positionEventCounter++;this._map.moveTo(pos);if(zoomStep){this._zoomEventCounter++;this._zoomModel.setStep(zoomStep)}}}});PositionSpice.ZOOMLEVELS=[];PositionSpice.ZOOMLEVELS[PositionModel.PROVIDER_NONE]=0;PositionSpice.ZOOMLEVELS[PositionModel.PROVIDER_GPS]=2;PositionSpice.ZOOMLEVELS[PositionModel.PROVIDER_WIFI]=2;PositionSpice.ZOOMLEVELS[PositionModel.PROVIDER_CELL]=4;PositionSpice.ZOOMLEVELS[PositionModel.PROVIDER_IP]=7;var SearchSpice={Name:"SearchSpice",Extends:Spice,initialize:function(aSpiceManager,aMapModel,aSearchModel,aPage){if(!aSearchModel){throw new nokia.aduno.utils.ArgumentError("aSearchModel is required")}if(!aSearchModel.isReady()){throw new ArgumentError("The SearchModel is not ready")}this._super(aSpiceManager);this._model=aMapModel;this._searchModel=aSearchModel;this._page=aPage;this._spiceManager=aSpiceManager;this._dfw=null;this._publicMethods=["show","hide","search"]},_createUi:function(){this._dfwContainer=new Container("DfwContainer",SearchSpice.SearchSpiceTemplateLibrary);this._dfw=new nokia.maps.dfw.ui.DiscoveryFrameworkUI(this._searchModel.getDiscoveryFrameworkCore(),this._page);this._dfw.addEventHandler("ResultSelected",this._onResultSelected,this);this._dfw.addEventHandler("ResultsReceived",this._onResultsReceived,this);this._dfw.addEventHandler("ResultsCleared",this._onResultsCleared,this);this._dfw.addEventHandler("SuggestionSelected",this._onSuggestionSelected,this);this._dfwSearchBox=this._dfw.getSearchBox();this._dfwResultList=this._dfw.getResultList();this._dfwPagingFrame=this._dfw.getPagingFrame();this._dfwErrorPresenter=this._dfw.getErrorPresenter();this._dfwProgressIndicator=this._dfw.getProgressIndicator();this._dfwContainer.setChildAt(this._dfwSearchBox,"dfwSearchBox");this._dfwContainer.setChildAt(this._dfwProgressIndicator,"dfwProgressIndicator");this._resultContainer=new Container("ResultContainer",SearchSpice.SearchSpiceTemplateLibrary);this._resultContainer.hide();this._resultContainer.setChildAt(this._dfwErrorPresenter,"ErrorPresenter",true,true);this._resultContainer.setChildAt(this._dfwResultList,"ResultList",true,true);this._resultContainer.setChildAt(this._dfwPagingFrame,"PagingFrame",true,true);this._dfwContainer.setChildAt(this._resultContainer,"ResultContainer",true,true);return this._dfwContainer},_onResultSelected:function(aEvent){this._resultContainer.hide();this._moveToSearchResult(aEvent.getData(),this._searchResultObjects[aEvent.getData().index])},_onResultMapObjectSelected:function(aEvent){this._moveToSearchResult(aEvent.source.searchResult,aEvent.source);aEvent.preventDefault()},_moveToSearchResult:function(aResult,aMapObject){if(this._selectedSearchResult){}this._selectedSearchResult=aMapObject;this._dfwResultList.getSelected().setSelectionIndex((aResult.index-1)%this._searchModel.getOption("resultsPerPage"));this._model.selectMapObject(aMapObject);this._model.moveTo(aResult)},_onResultsReceived:function(aEvent){var data=aEvent.getData();this._cleanupSearchResults();for(var i=data.length-1;i>=0;i--){var obj=data[i];var mapMarker=MapMarker.parseMapMarker({longitude:obj.longitude,latitude:obj.latitude,infoIcon:obj.iconUrl,infoTitle:obj.row1,infoDescription:obj.row2,handler:this._onResultMapObjectSelected,bind:this});mapMarker.searchResult=obj;mapMarker.setClickable(true);info("before #layers "+this._model.getLayers().length);this._model.addToLayer(mapMarker,this.className+"Layer");info("after #layers "+this._model.getLayers().length);this._searchResultObjects[obj.index]=mapMarker}if(data.length>0){this._resultContainer.show()}},_onResultsCleared:function(aEvent){this._cleanupSearchResults()},_cleanupSearchResults:function(){for(var i in this._searchResultObjects){if(this._searchResultObjects.hasOwnProperty(i)){this._model.removeFromLayer(this._searchResultObjects[i]);delete this._searchResultObjects[i]}}this._searchResultObjects=[];this._selectedSearchResult=null;this._resultContainer.hide()},_onSuggestionSelected:function(event){var suggestionItem=event.getData();if(suggestionItem.suggestionType==="direct"){nokia.aduno.utils.info("Direct suggestion, result item:");nokia.aduno.utils.info(suggestionItem.resultItem)}else{if(suggestionItem.suggestionType==="term"){nokia.aduno.utils.info("Term suggestion, no result item")}}},show:function(){this._dfwContainer.show()},hide:function(){this._dfwContainer.hide()},search:function(term){this._dfwSearchBox.setValue(term);this._dfwSearchBox.fireSearch()}};SearchSpice=new Class(SearchSpice);SearchSpice.SearchSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({SearchResultList:'<ul class="nmm_SearchResults"></ul>',SearchResultElement:'<li class="nmm_SearchResultEntry"><a id="button" href=""></a></li>',DropDown:'<div id="dropDown" class="nmm_Choo"><div id="dropDownButton"></div><div id="dropDownList"></div></div>',DropDownButton:'<div id="checkButton" class="nmm_DDown"><div id="checkButtonButton"><span id="checkButtonText"></span></div></div>',DropDownList:"<ul></ul>",DropDownListElement:'<li><a id="button"></a></li>',Collapsable:"<div></div>",DfwContainer:'<div class="nmps_DfwControls"><div class="nmm_searchBox"><div id="dfwSearchBox"></div><div id="ResultContainer" class="nmm_ResultContainer"></div></div><div id="dfwProgressIndicator"></div></div>',ResultContainer:'<div class="nmm_resultContainer"><div id="ErrorPresenter"></div><div id="ResultList" class="nmm_rlContainer"></div><div id="PagingFrame"></div></div>'},(nokia.maps.dfw)?nokia.maps.dfw.ui.DFWTemplateLibrary:nokia.aduno.medosui.DefaultTemplateLibrary);var ResultWindow=new Class({Extends:nokia.aduno.medosui.Window,Name:"ResultWindow",initialize:function(aTemplate,aTemplateLibrary){this._super(aTemplate,aTemplateLibrary);this._dragBar=new nokia.aduno.medosui.Container("ResultWindowDragbar");this.setChildAt(this._dragBar,"DragBar");this._closeButton=new nokia.aduno.medosui.Button("ResultWindowCloseButton");this._dragBar.setChildAt(this._closeButton,"CloseButton",false,true);this._closeButton.addEventHandler("selected",this.onClose,this);this._dragBar.addBehavior(new Draggable());this._dragBar.addEventHandler("dragged",this.onDrag,this)},show:function(){this.getReplica().removeCssClass("nmm_rwHidden");return this},hide:function(){this.getReplica().addCssClass("nmm_rwHidden");return this},setPosition:function(aPosition){this.getReplica().setStyle("ResultWindow","left",aPosition.x+"px");this.getReplica().setStyle("ResultWindow","top",aPosition.y+"px");return this},onClose:function(aEvent){var event=new nokia.aduno.utils.Event("closed",null,true);this.fireEvent(event);if(!event.isPreventDefault()){this.hide()}},onDrag:function(aDragEvent){var data=aDragEvent.getData();var position;var elem=this.getElement("ResultWindow");if(elem.parentNode&&elem.parentNode.tagName){position=nokia.aduno.dom.Dimensions.getPosition(elem,elem.parentNode)}else{position=nokia.aduno.dom.Dimensions.getPosition(elem)}this.getReplica().setStyle("ResultWindow","left",(position.x+data.deltaX)+"px");this.getReplica().setStyle("ResultWindow","top",(position.y+data.deltaY)+"px")}});var Persistence=new nokia.aduno.utils.Class({Name:"Persistence",Implements:Options,initialize:function(aDocument,aOptions){this.setOptions(aOptions);this._document=aDocument},addData:function(aKey,aValue){if(aKey!==undefined&&aKey!==null){var dataString=escape(aKey)+"=";if(aValue!==undefined&&aValue!==null){dataString+=escape(aValue)}if(this._options.expires){dataString+="; expires="+escape(this._options.expires)}if(this._options.path){dataString+="; path="+escape(this._options.path)}if(this._options.domain){dataString+="; domain="+escape(this._options.domain)}if(this._options.secure){dataString+="; secure"}this._document.cookie=dataString}return this},getData:function(aKey){var ret={};ret[aKey]=null;if(this._document.cookie){var splitted=this._document.cookie.split("; ");if(splitted&&splitted.length>0){var index=Collection.indexOf(splitted,function(aValue){return aValue.indexOf(escape(aKey))>-1});if(index!==Collection.NOT_FOUND){splitted=splitted[index].split("=");if(splitted&&splitted.length>0&&splitted[1]!==undefined&&splitted[1]!==""){ret[aKey]=unescape(splitted[1])}}}}return ret},removeData:function(aKey){var dateObject=new Date();dateObject.setTime(0);document.cookie=escape(aKey)+"=; expires="+dateObject.toGMTString();return this}});var NewSettingsSpice=new Class({Name:"NewSettingsSpice",Extends:Spice,Implements:[Serializable],_mouseBeenOverTheOverlay:false,_mouseOverlayTimer:null,_mouseOverlayTimeout:500,_mouseOverlayFxObj:null,_mouseOverlayFxAct:false,initialize:function(aSpiceManager,aMapModel,aPfwPath){this._super(aSpiceManager);this._mapModel=aMapModel;this._colorMappings={0:"day",1:"night",2:"auto"};this._colorNameMappings={day:0,night:1,auto:2};this._languageMappings={};this._languageNameMappings={};this._pfwPath=aPfwPath;var i=0;for(var key in NewSettingsSpice.SUPPORTED_LANGUAGES){if(NewSettingsSpice.SUPPORTED_LANGUAGES.hasOwnProperty(key)){this._languageMappings[i]=key;this._languageNameMappings[key]=i;i++}}},_createUi:function(){this._settingsContainer=new nokia.aduno.medosui.Container("Settings",NewSettingsSpice.NewSettingsSpiceTemplate);this._menuContainer=new nokia.aduno.medosui.Container("Menu",NewSettingsSpice.NewSettingsSpiceTemplate);this._settingsTopTip=new nokia.aduno.medosui.Container("TopTip",NewSettingsSpice.NewSettingsSpiceTemplate);this._menuContainer.setChildAt(this._settingsTopTip,"settingsTopTip");this._settingsButton=new nokia.aduno.medosui.Button("Button","__I18N_mapPlayer_15_buttonsArray_settings_buttonLabel__");this._settingsButton.addEventHandler("selected",this._showSettingsMenu,this);this._settingsContainer.setChildAt(this._settingsButton,"settingsbutton");var closeButton=new nokia.aduno.medosui.Button("CloseButton","__I18N_mapPlayer_61_commons_close_toolTip__");closeButton.addEventHandler("selected",function(aEvent){this._showSettingsMenu()},this);this._menuContainer.setChildAt(closeButton,"closeButton");this._color=new SelectionList("Selector",null,"nm_Selected");var dayButton=new Button("ColorDayButton");var nightButton=new Button("ColorNightButton");this._color.addChild(dayButton);this._color.addChild(nightButton);this._color.setSelectionIndex(0);this._color.addEventHandler("selected",this._onColorSelected,this);this._menuContainer.setChildAt(this._color,"ColorSelector");this._landmarks=new SelectionList("Selector",null,"nm_Selected");var onButton=new Button("LandmarksOnButton");var offButton=new Button("LandmarksOffButton");this._landmarks.addChild(offButton);this._landmarks.addChild(onButton);this._landmarks.setSelectionIndex(1);this._landmarks.addEventHandler("selected",this._onLandmarksSelected,this);this._menuContainer.setChildAt(this._landmarks,"LandmarksSelector");this._language=new SelectionList("DropDownSelectList",NewSettingsSpice.NewSettingsSpiceTemplate,null);for(var key in NewSettingsSpice.SUPPORTED_LANGUAGES){if(NewSettingsSpice.SUPPORTED_LANGUAGES.hasOwnProperty(key)){var tempLang=new Button("DropDownOption",NewSettingsSpice.SUPPORTED_LANGUAGES[key]);this._language.addChild(tempLang)}}this._mapModel.addEventHandler(MapModel.EVENT_UI_LANGUAGE,this._onModelUiLanguageChanged,this);this._language.getReplica().addEventHandler(TemplateReplica.ROOT_ID,"change",this,this._onLanguageSelected);this._menuContainer.setChildAt(this._language,"LanguageSelector");this._dialog=new nokia.aduno.medosui.Container("Dialog");this._settingsContainer.setChildAt(this._dialog,"settingsDialog");this._dialog.setChildAt(this._menuContainer,"settingsmenu");if(!nokia.aduno.utils.browser.msie){this._dialog.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onMouseEnteredOverlay);this._dialog.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onMouseExitedOverlay)}this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._dialog);this._dialog.hide();this._mapModel.addEventHandler(MapModel.EVENT_COLOR,this._onModelColorChanged,this);this._mapModel.addEventHandler(MapModel.EVENT_LANDMARKS,this._onModelLandmarksChanged,this);this._menuContainer.handleKey=function(aKeyEvent){return true};return this._settingsContainer},_showSettingsMenu:function(aEvent){if(!this._dialog.isVisible()||this._mouseOverlayFxAct){this._showMenuDialog()}else{this._hideMenuDialog()}},_showMenuDialog:function(){var root=this.getUi().getRootElement();if(this._spiceManager&&this._spiceManager._localizer){this._spiceManager._localizer.traverse(root)}this._settingsButton.getReplica().addCssClass("nmm_Selected");this._spiceManager.handleModalSpiceOpened(this);if(this._mouseOverlayFxAct){this._mouseOverlayFxObj.stop();delete this._mouseOverlayFxObj;this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._dialog);this._mouseOverlayFxAct=false}this._dialog.getReplica().setStyle(TemplateReplica.ROOT_ID,"opacity","1");this._dialog.show();this._menuContainer.focus();var dialogPos=nokia.aduno.dom.Dimensions.getPosition(this._dialog.getRootElement(),this._spiceControl.getRootElement().parentNode.parentNode);var buttonPos=nokia.aduno.dom.Dimensions.getPosition(this._settingsButton.getRootElement(),this._spiceControl.getRootElement().parentNode.parentNode);var buttonSize=nokia.aduno.dom.Dimensions.getSize(this._settingsButton.getRootElement());var tipSize=nokia.aduno.dom.Dimensions.getSize(this._settingsTopTip.getRootElement());var tipLeft=Math.round(buttonPos.x+(buttonSize.x/2)-(tipSize.x/2)-dialogPos.x);this._settingsTopTip.getReplica().setStyle(TemplateReplica.ROOT_ID,"left",tipLeft+"px")},_hideMenuDialog:function(){if(!this._mouseOverlayFxAct){this._mouseOverlayFxAct=true;this._mouseBeenOverTheOverlay=false;this._settingsButton.getReplica().removeCssClass("nmm_Selected");if(nokia.aduno.utils.browser.msie){this._mouseOverlayFxAct=false;this._menuContainer.blur();this._dialog.hide()}else{this._mouseOverlayFxObj.addEventHandler("ended",function(){this._mouseOverlayFxAct=false;this._menuContainer.blur();this._dialog.hide()},this);this._mouseOverlayFxObj.effect({duration:300,styles:{opacity:[1,0]}}).start()}}},_onMouseEnteredOverlay:function(aMouseOverEvent){this._mouseBeenOverTheOverlay=true;if(this._mouseOverlayTimer){clearTimeout(this._mouseOverlayTimer)}this._mouseOverlayTimer=null},_onMouseExitedOverlay:function(aMouseOutEvent){if(this._mouseBeenOverTheOverlay&&!this._mouseOverlayFxAct){var x=aMouseOutEvent.get("pageX");var y=aMouseOutEvent.get("pageY");var rect=nokia.aduno.dom.Dimensions.getCoordinates(this._dialog.getRootElement());if(x<rect.left||x>=rect.left+rect.width||y<rect.top||y>=rect.top+rect.height){var self=this;this._mouseOverlayTimer=setTimeout(function(){self._hideMenuDialog()},this._mouseOverlayTimeout)}}},_onColorSelected:function(aEvent){var data=aEvent.getData();var type=this._colorMappings[data.selectedIndex]||"day";if(this._mapModel.getColor()!==this._colorMappings[data.selectedIndex]){this._mapModel.setColor(type)}},_onModelColorChanged:function(aEvent){var data=aEvent.getData();var type=this._mapModel.getColor();if(this._color.getSelectionIndex()!==this._colorNameMappings[data]){this._color.setSelectionIndex(this._colorNameMappings[type]||0)}},_onLandmarksSelected:function(aEvent){var data=aEvent.getData();this._mapModel.setLandmarksVisible(data.selectedIndex===1)},_onModelLandmarksChanged:function(aEvent){var visible=aEvent.getData()=="visible";if(visible){this._landmarks.setSelectionIndex(1)}else{this._landmarks.setSelectionIndex(0)}},_onLanguageSelected:function(aDomEvent){var index=aDomEvent.get("target").selectedIndex;var type=this._languageMappings[index]||"en-GB";if(this._mapModel.getUiLanguage()!==this._languageMappings[index]){this._mapModel.setUiLanguage(type)}},_onModelUiLanguageChanged:function(aEvent){var data=aEvent.getData();var type=this._mapModel.getUiLanguage();if(this._language.getSelectionIndex()!==this._languageNameMappings[data]){this._language.setSelectionIndex(this._languageNameMappings[type]||0)}},serialize:function(aPersistence){try{aPersistence.addData("ColorSettings",this._color.getSelectionIndex());aPersistence.addData("LandmarksSettings",this._landmarks.getSelectionIndex())}catch(err){}},deserialize:function(aPersistence){var colorNum=0;var landmarksNum=0;try{colorNum=aPersistence.getData("ColorSettings");landmarksNum=aPersistence.getData("LandmarksSettings")}catch(err){colorNum=0;landmarksNum=0}this._color.setSelectionIndex(colorNum||0);this._landmarks.setSelectionIndex(landmarksNum||1)},onOtherSpiceReceivedFocus:function(){this._hideMenuDialog()},translateUi:function(aDefaultTranslationVisitor,aLanguage){this._super(aDefaultTranslationVisitor,aLanguage);var mapUiLanguage=this._mapModel.getUiLanguage();var codeCorrect=false;if(mapUiLanguage!==undefined&&mapUiLanguage!==null){var code=mapUiLanguage.split("-");if(code.length==2){mapUiLanguage=code[0].toLowerCase()+"-"+code[1].toUpperCase();codeCorrect=true}}if(!codeCorrect){return}var count=this._language.getChildCount();var langText=NewSettingsSpice.SUPPORTED_LANGUAGES[mapUiLanguage];for(var i=0;i<count;i++){var button=this._language.getChildAt(i);var btText=button.getText();if(button.getText()==langText){button.getReplica().setAttribute(TemplateReplica.ROOT_ID,"selected","selected");break}}}});NewSettingsSpice.NewSettingsSpiceTemplate=new nokia.aduno.dom.TemplateLibrary({Settings:'<div class="nmp_NewSettingsSpice" unselectable="on"><div id="settingsbutton"></div><div id="settingsDialog"></div></div>',Dialog:'<div class="nmp_SettingsDialog" unselectable="on"><div id="settingsmenu"></div></div>',Menu:'<div class="nmp_SettingsMenu" unselectable="on"><div id="settingsTopTip" unselectable="on"></div><div class="nmp_SettingsContainer" unselectable="on"><div class="nmp_SettingsHeadline1" unselectable="on">__I18N_mapPlayer_1_settings_header_txt__</div><div class="nmp_Settings2Cols" unselectable="on"><div id="ColorSelector"></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_2_settings_nightMode_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_3_settings_nightMode_txt_body__</div></div></div><div class="nmp_Settings2Cols" unselectable="on"><div id="LandmarksSelector"></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_4_settings_landmarks_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_5_settings_landmarks_txt_body__</div></div></div><div class="nmp_Settings2Cols" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><div id="LanguageSelector"></div></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_6_settings_mapLanguage_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_7_settings_mapLanguage_txt_body__</div></div></div><div class="nmp_SettingsFull" unselectable="on"><p>\u00BB <a href="__I18N_mapPlayer_9_about_Ovi_link__" unselectable="on" target="blank">__I18N_mapPlayer_8_about_Ovi_txt__</a><br />\u00BB <a href="__I18N_mapPlayer_11_about_mobile_link__" unselectable="on" target="blank">__I18N_mapPlayer_10_about_mobile_txt__</a></p></div><div class="nmp_PosCloseButton" unselectable="on"><div id="closeButton" class="nmp_MenuCloseButton"></div></div></div><div class="nmp_SettingsBottomEdge" unselectable="on"></div></div>',CloseButton:'<span id="button" class="nmp_CloseButton" unselectable="on"></span>',Selector:'<div class="nmp_Settings2ColsLeft" unselectable="on"></div>',ColorDayButton:'<div unselectable="on"><div id="button" class="nmp_ColorDayButton" unselectable="on"></div></div>',ColorNightButton:'<div unselectable="on"><div id="button" class="nmp_ColorNightButton" unselectable="on"></div></div>',LandmarksOnButton:'<div unselectable="on"><div id="button" class="nmp_LandmarksOnButton" unselectable="on"></div></div>',LandmarksOffButton:'<div unselectable="on"><div id="button" class="nmp_LandmarksOffButton" unselectable="on"></div></div>',DropDownSelectList:"<select></select>",DropDownOption:'<option id="button"></option>',Button:'<div class="nmm_Butt"><a id="button" unselectable="on"></a></div>',TopTip:'<div class="nmp_SettingsTopTip" unselectable="on"></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);NewSettingsSpice.SUPPORTED_LANGUAGES={"en-GB":"English (British)","fr-FR":"Française","de-DE":"Deutsch","es-ES":"Español","it-IT":"Italiano"};var RouteInfoSpiceTemplateLibrary=new TemplateLibrary({RouteInfo:'<div class="nmp_RouteInfo"><span id="routeInfoLabel"></span></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var RouteInfoSpice=new Class({Name:"RouteInfoSpice",Extends:Spice,_routing:null,_routeSettings:null,_application:null,_guidance:null,_enabled:true,initialize:function(aSpiceManager,aTranslator,aModels){this._super(aSpiceManager,aTranslator);this._routing=aModels.routing;this._routeSettings=aModels.routeSettings;this._guidance=aModels.guidance;this._application=aModels.application;this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STARTED,this._onGuidanceStarted,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STOPPED,this._onGuidanceStopped,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_DONE,this._onGuidanceStopped,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculationDone,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._onRouteCalculationDone,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_CANCELLED,this._onRouteCalculationCancelled,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_PROGRESS,this._onRouteCalculationProgressed,this);this._routing.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._onCurrentRouteChanged,this);this._routeSettings.addEventHandler(RouteSettingsModel.EVENT_DISTANCE_UNIT,this._onDistanceUnitChanged,this)},setEnabled:function(aEnabled){if(aEnabled){this._show()}else{this._hide()}this._enabled=aEnabled},_createUi:function(){if(!nokia.maps.pfw.layout.touch){this._routeInfo=new Container("RouteInfo",RouteInfoSpiceTemplateLibrary);this._routeInfo.hide();return this._routeInfo}return null},_onRouteCalculationProgressed:function(aRouteEvent){var calcProgress=aRouteEvent.getData().percentage;if(!calcProgress||calcProgress===0){this._setText(this.translateString("__I18N_nokia.maps.pfw.spices.routeinfospice.calcprogress__"),"")}},_onRouteCalculationDone:function(aRouteEvent){var route=aRouteEvent.getData().route;this._setRouteInfoText(route)},_onRouteCalculationError:function(aRouteEvent){this._hide()},_onRouteCalculationCancelled:function(aRouteEvent){this._hide()},_setRouteInfoText:function(aRoute){var distance=Units.getReadableDistance(aRoute.getLength(),this._routeSettings.isUsingImperialUnits());var time=Units.getReadableTime(aRoute.getDuration());this._setText(this.translateString("__I18N_nokia.maps.pfw.spices.routeinfospice.routeinfo__"),distance.value+" "+this.translateString(distance.unit)+" "+time.value+" "+this.translateString(time.unit));if(aRoute.isValid()&&nokia.maps.pfw.layout.touch){this._application.setTitlebarEnabled(true)}},_setGpsInfoText:function(infoText){this._setText(infoText)},_onDistanceUnitChanged:function(aEvent){if(this._enabled&&this._routeInfo.isVisible()){this._setRouteInfoText(this._routing.getCurrentRoute())}},_onCurrentRouteChanged:function(aEvent){if(aEvent.getData().newRoute===null||!aEvent.getData().newRoute.isValid()){this._hide()}},_hide:function(){this._routeInfo.hide()},_show:function(){this._routeInfo.show()},_setText:function(aLabel,aValue){if(nokia.maps.pfw.layout.touch){this._application.setTitle(aLabel,aValue);this._application.setTitlebarButton(this._onCancelPressed,this,"cancel")}else{this._routeInfo.getReplica().setText("routeInfoLabel",aLabel+aValue);if(this._enabled){if(!aLabel){this._hide()}else{this._show()}}}},_onCancelPressed:function(aEvent){if(nokia.maps.pfw.layout.touch){this._routing.cancelRouteCalculation();if(nokia.maps.pfw.layout.touch){this._application.setTitlebarEnabled(false);this._application.showSelector(true,true)}}},_onGuidanceStarted:function(){this._hide()},_onGuidanceStopped:function(){this._show()}});var FlyBySpice=new Class({Name:"FlyBySpice",Extends:Spice,Implements:[EventSource],_DEFAULTS:{position:{latitude:52.5208255648613,longitude:13.409595340490341},tiltStart:20,tiltEnd:70,orientationStart:0,orientationEnd:270,scaleStart:100,scaleEnd:400,duration:7000},_SUPPORTED_SINGLE_VALUES:Array("duration"),_SUPPORTED_RANGE_VALUES:Array("tilt","orientation","scale"),_mapModel:null,initialize:function(aSpiceManager,aMapModel,aSettings){this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._interval=null;this._fps=30;this._frames=0;this._currentFrame=0;this._setValues(aSettings);var keyBind=bind(this,this._onStart);aSpiceManager.setKeyHandler(65,0,keyBind)},_onStart:function(){this._currentFrame=-1;this._onIteration();var bound=this;var handler=function(){bound._onIteration.call(bound)};this._interval=setInterval(handler,1000/this._fps)},_setValues:function(aSettings){this._values={start:{},end:{},current:{}};var context=this;var settingsValid=aSettings?true:false;var fillSingleValues=function(item){var isValid=false;if(settingsValid){var value=aSettings[item];isValid=value?true:((value===0||value==="")?true:false)}context._values.current[item]=isValid?value:context._DEFAULTS[item]};var fillRangeValues=function(item){var keyStart=item+"Start";var keyEnd=item+"End";var isValidStart=false;var isValidEnd=false;if(settingsValid){var valueStart=aSettings[keyStart];var valueEnd=aSettings[keyEnd];isValidStart=valueStart?true:((valueStart===0)?true:false);isValidEnd=valueEnd?true:((valueEnd===0)?true:false)}context._values.start[item]=isValidStart?valueStart:context._DEFAULTS[keyStart];context._values.end[item]=isValidEnd?valueEnd:context._DEFAULTS[keyEnd]};nokia.aduno.utils.Collection.forEach(this._SUPPORTED_SINGLE_VALUES,fillSingleValues,context);nokia.aduno.utils.Collection.forEach(this._SUPPORTED_RANGE_VALUES,fillRangeValues,context);var positionValid=settingsValid?(aSettings.position?true:false):false;var latitudeValid=!positionValid?false:(aSettings.position.latitude?true:((aSettings.position.latitude===0)?true:false));var longitudeValid=!positionValid?false:(aSettings.position.longitude?true:((aSettings.position.longitude===0)?true:false));context._values.current.position={latitude:(latitudeValid?aSettings.position.latitude:context._DEFAULTS.position.latitude),longitude:(longitudeValid?aSettings.position.longitude:context._DEFAULTS.position.longitude)};this._frames=this._values.current.duration*this._fps/1000;if(this._frames<1){this._frames=1}context._values.current.animationMode=""},_onIteration:function(){this._currentFrame++;if(this._currentFrame>this._frames){cancelTimer(this._interval);this.fireEvent(new nokia.aduno.utils.Event(MapModel.EVENT_ANIMATION_DONE));return}var progress=this._currentFrame/this._frames;var context=this;var calcIntermediate=function(item){var start=context._values.start[item];var delta=context._values.end[item]-start;context._values.current[item]=start+(delta*progress)};if(this._currentFrame){}nokia.aduno.utils.Collection.forEach(this._SUPPORTED_RANGE_VALUES,calcIntermediate,context);this._mapModel.moveTo(context._values.current)}});var WebRouteSettingsSpice=new Class({Name:"WebRouteSettingsSpice",Extends:Spice,_transportationMode:Route.TRANSPORTATION_MODE_CAR,_walkMode:Route.ROUTE_TYPE_STREET,_driveRouteType:Route.ROUTE_TYPE_OPTIMIZED,_walkFerryState:true,_driveBlockerStates:[],_cancelTimeout:null,_translations:null,initialize:function(aSpiceManager,aModels){this._super(aSpiceManager);this._routeSettingsModel=aModels.routeSettings;this._routeSettingsModel.addEventHandler(RouteSettingsModel.EVENT_BLOCKERS,this._update,this);this._routeSettingsModel.addEventHandler(RouteSettingsModel.EVENT_ROUTE_TYPE,this._update,this);this._routeSettingsModel.addEventHandler(RouteSettingsModel.EVENT_TRANSPORTATION_MODE,this._update,this);this._routeSettingsModel.addEventHandler(RouteSettingsModel.EVENT_RESET,this._update,this);this._driveBlockerStates[Route.ROUTE_BLOCKER_FERRIES]=this._routeSettingsModel.getAllowFerries();this._driveBlockerStates[Route.ROUTE_BLOCKER_TUNNELS]=this._routeSettingsModel.getAllowTunnels();this._driveBlockerStates[Route.ROUTE_BLOCKER_MOTORWAYS]=this._routeSettingsModel.getAllowHighways();this._driveBlockerStates[Route.ROUTE_BLOCKER_TOLLROADS]=this._routeSettingsModel.getAllowTollroads();this._driveBlockerStates[Route.ROUTE_BLOCKER_UNPAVEDROADS]=this._routeSettingsModel.getAllowUnpavedRoads();this._driveBlockerStates[Route.ROUTE_BLOCKER_MOTORAILTRAINS]=this._routeSettingsModel.getAllowMotorailTrain()},_createUi:function(){var binder=this;var templateLibrary=WebRouteSettingsSpice.WebRouteSettingsSpiceTemplateLibrary;this._panel=new Container("RouteSettingsContainer",templateLibrary);this._transportationOptionsPanel=new Container("TransportationOptionsPanel",templateLibrary);this._driveOptionsPanel=new Container("RouteSettingsDriveOptionsPanel",templateLibrary);this._walkOptionsPanel=new Container("RouteSettingsWalkOptionsPanel",templateLibrary);this._transportationRadioGroup=new RadioGroup("TransportationModeRadioGroup",templateLibrary);this._driveOptionsRadioGroup=new RadioGroup("RouteSettingsDriveModeRadioGroup",templateLibrary);this._walkOptionsRadioGroup=new RadioGroup("RouteSettingsWalkModeRadioGroup",templateLibrary);this._transportationSettingsToggleButton=new Button("TransportationSettingsToggle",templateLibrary);this._transportationSettingsToggleButton.addEventHandler("selected",this._showTransportationSettingsOptionsPanel,this);this._transportationSettingsToggleButton.setText("__I18N_nokia.maps.pfw.ui.transportationmodesettings.captiondrive__");this._routeSettingsToggleButton=new Button("RouteSettingsToggle",templateLibrary);this._routeSettingsToggleButton.addEventHandler("selected",this._showRouteSettingsOptionsPanel,this);this._routeSettingsToggleButton.setText("__I18N_nokia.maps.pfw.ui.transportationmodesettings.captionsettings__");this._addTransportationRouteOptions();this._addDriveRouteSettingsOptions();this._addWalkRouteSettingsOptions();this._addDriveRouteSettingsBlockers();this._addWalkRouteSettingsBlockers();this._transportationOptionsPanel.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onTransportationPanelMouseOver);this._transportationOptionsPanel.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onTransportationPanelMouseOut);this._driveOptionsPanel.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onDrivePanelMouseOver);this._driveOptionsPanel.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onDrivePanelMouseOut);this._walkOptionsPanel.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onWalkPanelMouseOver);this._walkOptionsPanel.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onWalkPanelMouseOut);this._panel.setChildAt(this._transportationSettingsToggleButton,"transportationSettingsToggle");this._panel.setChildAt(this._routeSettingsToggleButton,"routeSettingsToggle");this._panel.setChildAt(this._transportationOptionsPanel,"transportationOptionsContainer");this._panel.setChildAt(this._driveOptionsPanel,"driveOptionsContainer");this._panel.setChildAt(this._walkOptionsPanel,"walkOptionsContainer");this._transportationOptionsPanel.hide();this._driveOptionsPanel.hide();this._walkOptionsPanel.hide();this._panel.accept=function(aVisitor){binder._translations=aVisitor._translator._translationTable;binder._transportationOptionsPanel.getReplica().setText("transportationCaption",binder._translations["nokia.maps.pfw.ui.transportationmodesettings.lbltransportation"]);binder._driveOptionsPanel.getReplica().setText("routeCaption",binder._translations["nokia.maps.pfw.ui.transportationmodesettings.lblroute"]);binder._driveOptionsPanel.getReplica().setText("blockerCaption",binder._translations["nokia.maps.pfw.ui.transportationmodesettings.lblblockers"]);binder._walkOptionsPanel.getReplica().setText("routeCaption",binder._translations["nokia.maps.pfw.ui.transportationmodesettings.lblroute"]);binder._walkOptionsPanel.getReplica().setText("blockerCaption",binder._translations["nokia.maps.pfw.ui.transportationmodesettings.lblblockers"]);aVisitor.visitButton(binder._transportationSettingsToggleButton);aVisitor.visitButton(binder._routeSettingsToggleButton);aVisitor._visitIterable(binder._transportationRadioGroup);aVisitor._visitIterable(binder._driveOptionsPanel);aVisitor._visitIterable(binder._walkOptionsPanel)};return this._panel},onAttach:function(){this._transportationRadioGroup.setSelectionIndex(0)},_onTransportationPanelMouseOver:function(aEvent){if(this._cancelTimeout){clearTimeout(this._cancelTimeout)}this._transportationOptionsPanel.show()},_onTransportationPanelMouseOut:function(eEvent){var binder=this;this._cancelTimeout=setTimeout(function(){binder._transportationOptionsPanel.hide()},500)},_onDrivePanelMouseOver:function(aEvent){if(this._cancelTimeout){clearTimeout(this._cancelTimeout)}this._driveOptionsPanel.show()},_onDrivePanelMouseOut:function(aEvent){var binder=this;this._cancelTimeout=setTimeout(function(){binder._driveOptionsPanel.hide()},500)},_onWalkPanelMouseOver:function(aEvent){if(this._cancelTimeout){clearTimeout(this._cancelTimeout)}this._walkOptionsPanel.show()},_onWalkPanelMouseOut:function(aEvent){var binder=this;this._cancelTimeout=setTimeout(function(){binder._walkOptionsPanel.hide()},500)},_update:function(aEvent){if(this._routeSettingsModel.getTransportationMode()===Route.TRANSPORTATION_MODE_CAR){this._transportationRadioGroup.setSelectionIndex(0)}else{if(this._routeSettingsModel.getTransportationMode()===Route.TRANSPORTATION_MODE_PEDESTRIAN){this._transportationRadioGroup.setSelectionIndex(1)}else{warn("Unsupported transportation mode in "+this.className)}}this._driveBlockerStates[Route.ROUTE_BLOCKER_FERRIES]=this._routeSettingsModel.getAllowFerries();this._driveBlockerStates[Route.ROUTE_BLOCKER_TUNNELS]=this._routeSettingsModel.getAllowTunnels();this._driveBlockerStates[Route.ROUTE_BLOCKER_MOTORWAYS]=this._routeSettingsModel.getAllowHighways();this._driveBlockerStates[Route.ROUTE_BLOCKER_TOLLROADS]=this._routeSettingsModel.getAllowTollroads();this._driveBlockerStates[Route.ROUTE_BLOCKER_UNPAVEDROADS]=this._routeSettingsModel.getAllowUnpavedRoads();this._driveBlockerStates[Route.ROUTE_BLOCKER_MOTORAILTRAINS]=this._routeSettingsModel.getAllowMotorailTrain();this._setupDrivePanelOptions()},_showTransportationSettingsOptionsPanel:function(){this._walkOptionsPanel.hide();this._driveOptionsPanel.hide();if(this._transportationMode===Route.TRANSPORTATION_MODE_CAR){this._transportationRadioGroup.setSelectionIndex(0)}else{this._transportationRadioGroup.setSelectionIndex(1)}this._toggleControlVisibility(this._transportationOptionsPanel)},_showRouteSettingsOptionsPanel:function(){var transportationMode=this._routeSettingsModel.getTransportationMode();this._transportationOptionsPanel.hide();switch(transportationMode){case Route.TRANSPORTATION_MODE_CAR:this._toggleControlVisibility(this._driveOptionsPanel);this._walkOptionsPanel.hide();this._setupDrivePanelOptions();break;case Route.TRANSPORTATION_MODE_PEDESTRIAN:this._toggleControlVisibility(this._walkOptionsPanel);this._driveOptionsPanel.hide();this._setupWalkPanelOptions();break}},_onSelectDriveMode:function(){var buttonName=(this._translations)?this._translations["nokia.maps.pfw.ui.transportationmodesettings.captiondrive"]:"__I18N_nokia.maps.pfw.ui.transportationmodesettings.captiondrive__";this._transportationSettingsToggleButton.setText(buttonName);this._transportationSettingsToggleButton.getReplica().removeCssClass("nmp_RouteSettings_WalkIcon");this._transportationSettingsToggleButton.getReplica().addCssClass("nmp_RouteSettings_DriveIcon");this._transportationMode=Route.TRANSPORTATION_MODE_CAR;this._routeSettingsModel.setTransportationMode(this._transportationMode,this._driveRouteType)},_onSelectWalkMode:function(){var buttonName=(this._translations)?this._translations["nokia.maps.pfw.ui.transportationmodesettings.captionwalk"]:"__I18N_nokia.maps.pfw.ui.transportationmodesettings.captionwalk__";this._transportationSettingsToggleButton.setText(buttonName);this._transportationSettingsToggleButton.getReplica().removeCssClass("nmp_RouteSettings_DriveIcon");this._transportationSettingsToggleButton.getReplica().addCssClass("nmp_RouteSettings_WalkIcon");this._transportationMode=Route.TRANSPORTATION_MODE_PEDESTRIAN;this._routeSettingsModel.setTransportationMode(Route.TRANSPORTATION_MODE_PEDESTRIAN);this._routeSettingsModel.setRouteType(this._walkMode)},_onSelectStraightLineMode:function(){this._walkMode=Route.ROUTE_TYPE_STRAIGHT_LINE;this._routeSettingsModel.setRouteType(this._walkMode)},_onSelectStreetMode:function(){this._walkMode=Route.ROUTE_TYPE_STREET;this._routeSettingsModel.setRouteType(this._walkMode)},_onSelectOptimisedMode:function(){this._driveRouteType=Route.ROUTE_TYPE_OPTIMIZED;this._routeSettingsModel.setRouteType(this._driveRouteType)},_onSelectFastestMode:function(){this._driveRouteType=Route.ROUTE_TYPE_FASTEST;this._routeSettingsModel.setRouteType(this._driveRouteType)},_onSelectShortestMode:function(){this._driveRouteType=Route.ROUTE_TYPE_SHORTEST;this._routeSettingsModel.setRouteType(this._driveRouteType)},_onSelectFerriesBlocker:function(aEvent){var state=aEvent.source.getState();if(this._transportationMode===Route.TRANSPORTATION_MODE_CAR){this._driveBlockerStates[Route.ROUTE_BLOCKER_FERRIES]=state}else{this._walkFerryState=state}this._routeSettingsModel.setAllowFerries(state)},_onSelectTunnelsBlocker:function(aEvent){var state=aEvent.source.getState();this._driveBlockerStates[Route.ROUTE_BLOCKER_TUNNELS]=state;this._routeSettingsModel.setAllowTunnels(state)},_onSelectHighwaysBlocker:function(aEvent){var state=aEvent.source.getState();this._driveBlockerStates[Route.ROUTE_BLOCKER_MOTORWAYS]=state;this._routeSettingsModel.setAllowHighways(state)},_onSelectTollsBlocker:function(aEvent){var state=aEvent.source.getState();this._driveBlockerStates[Route.ROUTE_BLOCKER_TOLLROADS]=state;this._routeSettingsModel.setAllowTollroads(state)},_onSelectMotorailsBlocker:function(aEvent){var state=aEvent.source.getState();this._driveBlockerStates[Route.ROUTE_BLOCKER_MOTORAILTRAINS]=state;this._routeSettingsModel.setAllowMotorailTrain(state)},_onSelectUnpavedBlocker:function(aEvent){var state=aEvent.source.getState();this._driveBlockerStates[Route.ROUTE_BLOCKER_UNPAVEDROADS]=state;this._routeSettingsModel.setAllowUnpavedRoads(state)},_addTransportationRouteOptions:function(){var driveModeButton=new CheckButton("RadioButton","__I18N_nokia.maps.pfw.ui.transportationmodesettings.captiondrive__");var walkModeButton=new CheckButton("RadioButton","__I18N_nokia.maps.pfw.ui.transportationmodesettings.captionwalk__");this._transportationRadioGroup.addChild(driveModeButton);this._transportationRadioGroup.addChild(walkModeButton);driveModeButton.addEventHandler("selected",this._onSelectDriveMode,this);walkModeButton.addEventHandler("selected",this._onSelectWalkMode,this);this._transportationRadioGroup.setSelectionIndex(0);this._transportationOptionsPanel.setChildAt(this._transportationRadioGroup,"transportModeRadioGroup")},_addDriveRouteSettingsOptions:function(){var optimisedRouteButton=new CheckButton("RadioButton","__I18N_nokia.maps.pfw.ui.routetypesettings.optimized__");var fastestRouteButton=new CheckButton("RadioButton","__I18N_nokia.maps.pfw.ui.routetypesettings.fastest__");var shortestRouteButton=new CheckButton("RadioButton","__I18N_nokia.maps.pfw.ui.routetypesettings.shortest__");this._driveOptionsRadioGroup.addChild(optimisedRouteButton);this._driveOptionsRadioGroup.addChild(fastestRouteButton);this._driveOptionsRadioGroup.addChild(shortestRouteButton);optimisedRouteButton.addEventHandler("selected",this._onSelectOptimisedMode,this);fastestRouteButton.addEventHandler("selected",this._onSelectFastestMode,this);shortestRouteButton.addEventHandler("selected",this._onSelectShortestMode,this);this._driveOptionsPanel.setChildAt(this._driveOptionsRadioGroup,"driveOptionsRadioGroup")},_addWalkRouteSettingsOptions:function(){var straightLineRouteButton=new CheckButton("RadioButton","__I18N_nokia.maps.pfw.ui.routetypesettings.straightline__");var streetRouteButton=new CheckButton("RadioButton","__I18N_nokia.maps.pfw.ui.routetypesettings.street__");this._walkOptionsRadioGroup.addChild(straightLineRouteButton);this._walkOptionsRadioGroup.addChild(streetRouteButton);straightLineRouteButton.addEventHandler("selected",this._onSelectStraightLineMode,this);streetRouteButton.addEventHandler("selected",this._onSelectStreetMode,this);this._walkOptionsPanel.setChildAt(this._walkOptionsRadioGroup,"walkOptionsRadioGroup")},_addWalkRouteSettingsBlockers:function(){var walkModeFerriesButton=new CheckButton("CheckBox","__I18N_nokia.maps.pfw.ui.blockersettings.ferries__");walkModeFerriesButton.addEventHandler("selected",this._onSelectFerriesBlocker,this);this._walkOptionsPanel.setChildAt(walkModeFerriesButton,"walkBlockersFerriesCheckBox")},_addDriveRouteSettingsBlockers:function(){var driveModeTunnelsButton=new CheckButton("CheckBox","__I18N_nokia.maps.pfw.ui.blockersettings.tunnels__");var driveModeHighwaysButton=new CheckButton("CheckBox","__I18N_nokia.maps.pfw.ui.blockersettings.motorways__");var driveModeFerriesButton=new CheckButton("CheckBox","__I18N_nokia.maps.pfw.ui.blockersettings.ferries__");var driveModeTollsButton=new CheckButton("CheckBox","__I18N_nokia.maps.pfw.ui.blockersettings.tollroads__");var driveModeMotorailsButton=new CheckButton("CheckBox","__I18N_nokia.maps.pfw.ui.blockersettings.motorails__");var driveModeUnpavedButton=new CheckButton("CheckBox","__I18N_nokia.maps.pfw.ui.blockersettings.dirtroads__");driveModeTunnelsButton.addEventHandler("selected",this._onSelectTunnelsBlocker,this);driveModeHighwaysButton.addEventHandler("selected",this._onSelectHighwaysBlocker,this);driveModeFerriesButton.addEventHandler("selected",this._onSelectFerriesBlocker,this);driveModeTollsButton.addEventHandler("selected",this._onSelectTollsBlocker,this);driveModeMotorailsButton.addEventHandler("selected",this._onSelectMotorailsBlocker,this);driveModeUnpavedButton.addEventHandler("selected",this._onSelectUnpavedBlocker,this);this._driveOptionsPanel.setChildAt(driveModeTunnelsButton,"driveBlockersTunnelsCheckBox");this._driveOptionsPanel.setChildAt(driveModeHighwaysButton,"driveBlockersHighwaysCheckBox");this._driveOptionsPanel.setChildAt(driveModeFerriesButton,"driveBlockersFerriesCheckBox");this._driveOptionsPanel.setChildAt(driveModeTollsButton,"driveBlockersTollsCheckBox");this._driveOptionsPanel.setChildAt(driveModeMotorailsButton,"driveBlockersMotorailsCheckBox");this._driveOptionsPanel.setChildAt(driveModeUnpavedButton,"driveBlockersUnpavedCheckBox")},_toggleControlVisibility:function(control){if(control instanceof Control){if(control.isVisible()){control.hide()}else{control.show()}}else{warn("Unsupported type for this method in _toggleControlVisibility, "+this.className)}},_setupDrivePanelOptions:function(){switch(this._routeSettingsModel.getRouteType()){case Route.ROUTE_TYPE_OPTIMIZED:this._driveOptionsRadioGroup.setSelectionIndex(0);break;case Route.ROUTE_TYPE_FASTEST:this._driveOptionsRadioGroup.setSelectionIndex(1);break;case Route.ROUTE_TYPE_SHORTEST:this._driveOptionsRadioGroup.setSelectionIndex(2);break}this._driveOptionsPanel.getChildAt("driveBlockersTunnelsCheckBox").setState(this._driveBlockerStates[Route.ROUTE_BLOCKER_TUNNELS]);this._driveOptionsPanel.getChildAt("driveBlockersHighwaysCheckBox").setState(this._driveBlockerStates[Route.ROUTE_BLOCKER_MOTORWAYS]);this._driveOptionsPanel.getChildAt("driveBlockersFerriesCheckBox").setState(this._driveBlockerStates[Route.ROUTE_BLOCKER_FERRIES]);this._driveOptionsPanel.getChildAt("driveBlockersTollsCheckBox").setState(this._driveBlockerStates[Route.ROUTE_BLOCKER_TOLLROADS]);this._driveOptionsPanel.getChildAt("driveBlockersMotorailsCheckBox").setState(this._driveBlockerStates[Route.ROUTE_BLOCKER_MOTORAILTRAINS]);this._driveOptionsPanel.getChildAt("driveBlockersUnpavedCheckBox").setState(this._driveBlockerStates[Route.ROUTE_BLOCKER_UNPAVEDROADS])},_setupWalkPanelOptions:function(){if(this._walkMode===Route.ROUTE_TYPE_STRAIGHT_LINE){this._walkOptionsRadioGroup.setSelectionIndex(0)}else{this._walkOptionsRadioGroup.setSelectionIndex(1)}this._walkOptionsPanel.getChildAt("walkBlockersFerriesCheckBox").setState(this._walkFerryState)}});WebRouteSettingsSpice.WebRouteSettingsSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({RouteSettingsContainer:'<div class="nmp_RouteSettingsPanel"><div id="transportationSettingsToggle"></div><div id="routeSettingsToggle"></div><div id="transportationOptionsContainer"></div><div id="driveOptionsContainer"></div><div id="walkOptionsContainer"></div></div>',TransportationOptionsPanel:'<div class="nmp_TransportationOptionsContainer"><fieldset class="nmp_RouteSettings_RouteOption"><h4><span id="transportationCaption"></span></h4><div id="transportModeRadioGroup"></div></fieldset></div>',RouteSettingsDriveOptionsPanel:'<div class="nmp_RouteSettings_RouteSettingsDrivePanel"><fieldset class="nmp_RouteSettings_RouteOption"><h4><span id="routeCaption"></span></h4><div id="driveOptionsRadioGroup"></div></fieldset><fieldset class="nmp_RouteSettings_RouteBlockers"><h4><span id="blockerCaption"></span></h4><div id="driveBlockersTunnelsCheckBox"></div><div id="driveBlockersHighwaysCheckBox"></div><div id="driveBlockersFerriesCheckBox"></div><div id="driveBlockersTollsCheckBox"></div><div id="driveBlockersMotorailsCheckBox"></div><div id="driveBlockersUnpavedCheckBox"></div></fieldset></div>',RouteSettingsWalkOptionsPanel:'<div class="nmp_RouteSettings_RouteSettingsWalkPanel"><fieldset class="nmp_RouteSettings_RouteOption"><h4><span id="routeCaption"></span></h4><div id="walkOptionsRadioGroup"></div></fieldset><fieldset class="nmp_RouteSettings_RouteBlockers"><h4><span id="blockerCaption"></span></h4><div id="walkBlockersFerriesCheckBox"></div></fieldset></div>',TransportationSettingsToggle:'<div class="nmp_RouteSettings_TransportationButton nmp_RouteSettings_DriveIcon"><span class="nmp_RouteSettings_TransportationIcon" /><span id="button"></span></div>',RouteSettingsToggle:'<div class="nmp_RouteSettings_RouteButton"><span id="button"></span></div>',TransportationModeRadioGroup:'<div class="nmp_RouteSettings_TransportationModeRadioGroup"></div>',RouteSettingsDriveModeRadioGroup:'<div class="nmp_RouteSettings_RouteSettingsDriveModeRadioGroup"></div>',RouteSettingsWalkModeRadioGroup:'<div class="nmp_RouteSettings_RouteSettingsWalkModeRadioGroup"></div>',CheckButton:'<div id="checkButton" class="nmp_CheckButton"><input type="checkbox" id="checkButtonButton"></input><span id="checkButtonText"></span></div>',RadioButton:'<div id="radioButton" class="nmp_RadioButton"><input type="radio" id="checkButtonButton"></input><span id="checkButtonText"></span></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var WebWaypointSpice=new Class({Name:"WebWaypointSpice",Extends:Spice,_waypointList:null,_routing:null,_routeSettings:null,_searchModel:null,_maneuversOn:false,_waypointItems:[],_waypointListMap:[],_maneuverItems:[],_maneuverListMap:[],_numSearchItems:0,_searchItems:[],_searchBoxes:[],_resultLists:[],_searchPosition:-1,_deleteIndex:0,_translations:null,_isDestination:false,_currentSelectedIndex:-1,_scrollFx:null,_scrollDuration:500,_firstDfw:0,_secondDfw:1,_resultListIndex:0,_changeTimeout:null,_searchError:false,_pluginControl:null,initialize:function(aSpiceManager,aModels,aPage,aNumDfw){this._super(aSpiceManager);this._routing=aModels.routing;this._routing.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._onCurrentRouteChanged,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculated,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._onRouteError,this);this._routing.addEventHandler(RoutingModel.EVENT_WAYPOINT_CLICKED,this._onWaypointClicked,this);this._routing.addEventHandler(RoutingModel.EVENT_PREVIOUS_MANEUVER,this._onPreviousManeuver,this);this._routing.addEventHandler(RoutingModel.EVENT_NEXT_MANEUVER,this._onNextManeuver,this);this._routing.addEventHandler(RoutingModel.EVENT_CLEAR_CURRENT_ROUTE,this._onClearCurrentRoute,this);this._routing.addEventHandler(RoutingModel.EVENT_PRINT_CURRENT_ROUTE,this._onPrintCurrentRoute,this);this._routing.setCurrentRoute(null);this._routeSettings=aModels.routeSettings;this._routeSettings.addEventHandler(RouteSettingsModel.EVENT_BLOCKERS,this._onRouteSettingsChanged,this);this._routeSettings.addEventHandler(RouteSettingsModel.EVENT_ROUTE_TYPE,this._onRouteSettingsChanged,this);this._routeSettings.addEventHandler(RouteSettingsModel.EVENT_TRANSPORTATION_MODE,this._onRouteSettingsChanged,this);this._model=aModels.map;this._model.addEventHandler(MapModel.EVENT_POSITION_CHANGED,this._onMapMove,this);this._model.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onMapMove,this);this._model.addEventHandler(MapModel.EVENT_ANIMATION_DONE,this._onMapMove,this);this._model.addEventHandler(MapModel.EVENT_MEASUREMENT_TYPE_CHANGED,this._onMeasurementChanged,this);this._pluginControl=this._model.getPluginControl();this._searchModel=aModels.search;this._page=aPage;this._spiceManager.addEventHandler(SpiceManager.EVENT_SIZE_CHANGED,this._onSizeChanged,this);if(aNumDfw){this._secondDfw=aNumDfw-1;this._firstDfw=aNumDfw-2}},serialize:function(aPersistence){try{aPersistence.addData("WebWaypointSpice measurement",this._model.getMeasurementType())}catch(err){debug("Cannot serialize WebWaypointSpice")}},deserialize:function(aPersistence){var isImperial=false;try{retVal=aPersistence.getData("WebWaypointSpice measurement")}catch(err){debug("Cannot deserialize WebWaypointSpice: "+err)}if(retVal==="true"){isImperial=true}this._model.setMeasurementType(isImperial);this._updateRouteInfo(this._routing.getCurrentRoute())},_createUi:function(){var binder=this;var templateLibrary=WebWaypointSpice.WebWaypointSpiceTemplateLibrary;this._panel=new Container("WaypointPanel",templateLibrary);this._panel.getReplica().setText("routeLabelRight","0 km | 0 min");this._waypointList=new SelectionList("WaypointList",templateLibrary);this._waypointList.addEventHandler("selected",this._onWaypointItemSelected,this);this._maneuverButton=new Button("ManeuverToggle");this._maneuverButton.addEventHandler("selected",this._addManeuversToList,this);this._maneuverButton.removeCSSTrigger(Control.CSS_TRIGGER_OVER);this._panel.setChildAt(this._maneuverButton,"maneuverToggle");var waypointScroll=new Scrollable("WaypointScrollable",templateLibrary);this._waypointList.addBehavior(waypointScroll);this._waypointsListContainer=new Container("WaypointContainer",templateLibrary);this._waypointsListContainer.setChildAt(this._waypointList,"waypointList",false,false);this._panel.setChildAt(this._waypointsListContainer,"waypointContainer",false,false);this._searchModel.getDiscoveryFrameworkCore(0)._eventController.addListener(this);this._searchModel.getDiscoveryFrameworkCore(1)._eventController.addListener(this);this._panel.accept=function(aVisitor){binder._translator=aVisitor._translator;binder._maneuverButton.setText(binder._translator.translate("__I18N_nokia.maps.pfw.spices.webwaypointspice.btnshowturns__"));binder._panel.getReplica().setText("routeLabelLeft",binder._translator.translate("__I18N_nokia.maps.pfw.spices.webwaypointspice.totaldistanceandtime__"))};return this._panel},onAttach:function(){var binder=this;var resizeSpice=function(){if(binder._model.getMapSize().height>10){binder._setWaypointsListHeight()}else{setTimeout(function(){resizeSpice()},500)}};resizeSpice();this._updateUi(null)},_onSizeChanged:function(aEvent){this._setWaypointsListHeight()},_setWaypointsListHeight:function(){var size=this._model.getMapSize();var height=size.height-157;if(height<150){height=150}this._waypointsListContainer.getReplica().setStyle("WaypointListContainer","height",height+"px")},_updateUi:function(aRoute,aData){var route=aRoute;if(!route){route=this._createRoute()}this._removeSwitchButtons();if(aData){var routeWaypoints=route.getWaypoints();switch(aData.action){case Route.ROUTE_WAYPOINT_ADDED:if(!this._isDestination){this._searchPosition=-1}if(this._maneuversOn){this._removeManeuversFromList()}var index=this._resetSearchBoxes(routeWaypoints);if(index===-1){index=aData.index}if(routeWaypoints[aData.index]){this._waypointList.addChildAt(index,this._createWaypointItem(routeWaypoints[aData.index],index,routeWaypoints.length))}if(routeWaypoints.length===1){this._model.moveTo(routeWaypoints[0].getPosition())}this._updateWaypointListMap();break;case Route.ROUTE_WAYPOINT_REMOVED:if(this._searchPosition===0){this._isDestination=true}this._waypointList.removeChildAt(this._deleteIndex);if(this._maneuversOn){this._removeManeuversFromList();this._addManeuversToList()}var delCount=this._waypointList.getChildCount();for(var di=aData.index;di<delCount-1;di++){var item=this._waypointList.getChildAt(di);this._updateWaypointDeleteHandler(item,di)}if(routeWaypoints.length===1){this._maneuverButton.getReplica().addCssClass("plusMinus","disabled");this._updateRouteInfo(null)}if(delCount===1){this._resetSearchBoxes(routeWaypoints)}this._updateWaypointListMap();this._deleteIndex=0;break;case Route.ROUTE_WAYPOINT_REPLACED:this._waypointList.removeChildAt(aData.index);this._waypointList.addChildAt(aData.index,routeWaypoints[aData.index]);break;case Route.ROUTE_WAYPOINT_MOVED:var top=null;var bottom=null;if(aData.isSearchMove){top=this._waypointList.getChildAt(aData.index_from);bottom=this._waypointList.getChildAt(aData.index_to);this._resetSearchBoxes(routeWaypoints)}else{if(this._searchPosition!==-1&&this._searchPosition<=aData.index_from){aData.index_from=aData.index_from+1;aData.index_to=aData.index_to+1}top=this._waypointList.getChildAt(aData.index_from);bottom=this._waypointList.getChildAt(aData.index_to);top.getReplica().removeStyle("item","top");bottom.getReplica().removeStyle("item","top");this._waypointList.removeChildAt(aData.index_from);this._waypointList.addChildAt(aData.index_to,top)}this._updateWaypointDeleteHandler(top,aData.index_to);this._updateWaypointDeleteHandler(bottom,aData.index_from);this._updateWaypointListMap();break;case Route.ROUTE_WAYPOINT_CLEARED:this._removeManeuversFromList();this._maneuverButton.getReplica().addCssClass("plusMinus","disabled");this._updateRouteInfo(null);this._waypointList.removeAllChildren();this._waypointList.addChild(this._createSearchItem(0));this._waypointList.addChild(this._createSearchItem(1));this._updateWaypointListMap();break}}else{this._waypointList.removeAllChildren();this._waypointList.addChild(this._createSearchItem(0));this._waypointList.addChild(this._createSearchItem(1))}this._createSwitchButtons();this._resetListItems()},_resetSearchBoxes:function(aWaypoints,aFullReset){var retVal=-1;if(aWaypoints.length>=1){var listCount=this._waypointList.getChildCount();for(var i=listCount-1;i>=0;i--){if(this._waypointList.getChildAt(i).getReplica().getRootElement().className.indexOf("Search")!==-1){this._waypointList.getChildAt(i)._children[0].clearBox();this._waypointList.removeChildAt(i)}}if(this._searchPosition===-1){this._waypointList.addChild(this._createSearchItem(1))}else{if(this._searchPosition===0){if(aWaypoints.length>1&&!aWaypoints[0]){this._waypointList.addChild(this._createSearchItem(0));this._searchPosition=retVal}else{this._waypointList.addChildAt(this._searchPosition,this._createSearchItem(0));retVal=this._searchPosition+1}}else{this._waypointList.addChildAt(this._searchPosition,this._createSearchItem(1));retVal=this._searchPosition+1}}}else{if(this._waypointList.getChildCount()<2){var index=0;if(this._isDestination){index=1}this._waypointList.addChildAt(index,this._createSearchItem(index));this._searchPosition=-1}}this._isDestination=false;return retVal},_addManeuversToList:function(){var maneuvers=null;var waypoints=null;if(this._routing.getCurrentRoute()){maneuvers=this._routing.getCurrentRoute().getManeuvers();waypoints=this._routing.getCurrentRoute().getWaypoints();this._waypointListMap=[]}if(maneuvers&&maneuvers.length>0){this._updateManeuversButton(this._addManeuversToList,this._removeManeuversFromList,"plus","minus");var currentWaypointIndex=0;if(this._currentSelectedIndex!=-1){currentWaypointIndex=this._currentSelectedIndex}this._currentSelectedIndex=-1;var index=0;var maneuverIndex=0;var waypointIndex=1;var waypointNativeIndex=0;var svg=this._routing.getSvgFromServer(this._routing._pfwPath+"images/ui/web/big_dot.svg");for(var i=0,len=maneuvers.length;i<len;i++){index=waypointIndex+i;maneuverIndex++;var maneuver=maneuvers[i];this._maneuverListMap[maneuver.getId()]=index;var maneuverListItem=new ManeuverListItem(maneuver,"ManeuverItem",WebWaypointSpice.WebWaypointSpiceTemplateLibrary,this._model,this._translator);maneuverListItem.setIndex(maneuverIndex+".");maneuverListItem.setShowManeuverOnMouseOver(true);maneuverListItem.addEventHandler(Maneuver.SHOW_MANEUVER_ON_MAP,this._onManeuverShow,this);maneuverListItem.addEventHandler(Maneuver.HIDE_MANEUVER_ON_MAP,this._onManeuverHide,this);maneuverListItem.addEventHandler(ManeuverListItem.EVENT_MANEUVER_SELECTED,this._onSelectManeuverItem,this);this._waypointList.addChildAt(index,maneuverListItem);if(maneuver.getWaypointIndex()===0){this._waypointListMap[waypoints[waypointNativeIndex++].getId()]=0;waypointIndex=1;if(currentWaypointIndex===0){this._currentSelectedIndex=0}}else{if(maneuver.getWaypointIndex()>0&&maneuver.getWaypointIndex()<len){waypointIndex=maneuver.getWaypointIndex()+1;if(waypoints[waypointNativeIndex]){this._waypointListMap[waypoints[waypointNativeIndex].getId()]=index+1;waypointNativeIndex++}if(currentWaypointIndex===maneuver.getWaypointIndex()){this._currentSelectedIndex=index+1}}}var icon=svg.replace("[placeholder]",maneuverIndex);this._maneuverItems[maneuver.getDistanceFromStart()]=icon}this._maneuverButton.setText(this._translator.translate("__I18N_nokia.maps.pfw.spices.webwaypointspice.btnhideturns__"))}},_removeManeuversFromList:function(){this._updateManeuversButton(this._removeManeuversFromList,this._addManeuversToList,"minus","plus");for(var i=this._waypointList.getChildCount()-1;i>=0;i--){var item=this._waypointList.getChildAt(i);if(item.className==="ManeuverListItem"){this._waypointList.removeChildAt(i)}}this._waypointList.getChildAt(0).focus();this._currentSelectedIndex=-1;this._maneuverListMap=[];this._updateWaypointListMap();this._createSwitchButtons();this._maneuverButton.setText(this._translator.translate("__I18N_nokia.maps.pfw.spices.webwaypointspice.btnshowturns__"))},_updateManeuversButton:function(aRemovedHandler,aAddHandler,aRemoveClass,aAddclass){this._maneuverButton.removeEventHandler("selected",aRemovedHandler,this);this._maneuverButton.addEventHandler("selected",aAddHandler,this);this._maneuverButton.getReplica().removeCssClass(aRemoveClass);this._maneuverButton.getReplica().addCssClass(aAddclass);if(!this._maneuversOn){this._removeSwitchButtons();this._maneuversOn=true}else{this._maneuversOn=false}},_onManeuverShow:function(aEvent){var maneuver=aEvent.getData().maneuver;var value=this._maneuverItems[maneuver.getDistanceFromStart()];var layer=this._routing._maneuverLayer;if(typeof value==="string"){var mapicon=this._pluginControl.createMapIcon();var loc=this._pluginControl.createLocation();loc.setGeoCoordinates(this._model.toGeo(maneuver.getPosition()));mapicon.setLocation(loc);mapicon.setVisibility(true);var svgIcon=this._pluginControl.createIconFromSvg(this._maneuverItems[maneuver.getDistanceFromStart()]);mapicon.setIcon(svgIcon);mapicon.setSize(25,25);layer.addMapObject(mapicon);this._maneuverItems[maneuver.getDistanceFromStart()]=mapicon}else{layer.addMapObject(this._maneuverItems[maneuver.getDistanceFromStart()])}},_onManeuverHide:function(aEvent){var maneuver=aEvent.getData().maneuver;if(this._maneuverItems[maneuver.getDistanceFromStart()]){var layer=this._routing._maneuverLayer;layer.removeMapObject(this._maneuverItems[maneuver.getDistanceFromStart()])}},_updateWaypointListMap:function(){this._waypointListMap=[];if(this._routing.getCurrentRoute()){var waypoints=this._routing.getCurrentRoute().getWaypoints();for(var i=0,len=waypoints.length;i<len;i++){this._waypointListMap[waypoints[i].getId()]=i}}},_onMeasurementChanged:function(aEvent){var data=aEvent.getData();this._updateRouteInfo(this._routing.getCurrentRoute());if(this._maneuversOn){this._removeManeuversFromList();this._addManeuversToList()}var dfw=null;dfw=this._searchModel.getDiscoveryFrameworkCore(this._firstDfw);dfw._context.imperialUnits=data.useImperialUnits;dfw._eventController.fireEvent(new nokia.aduno.utils.Event(nokia.maps.dfw.utils.DFWEventConfiguration.Context_UnitChanged));dfw=this._searchModel.getDiscoveryFrameworkCore(this._secondDfw);dfw._context.imperialUnits=data.useImperialUnits;dfw._eventController.fireEvent(new nokia.aduno.utils.Event(nokia.maps.dfw.utils.DFWEventConfiguration.Context_UnitChanged))},_updateRouteInfo:function(aRoute){var routeLength=0;var routeDuration=0;if(aRoute){routeLength=aRoute.getLength();routeDuration=aRoute.getDuration()}var routeLengthTxt=Units.getReadableDistance(routeLength,this._model.getMeasurementType());var routeDurationTxt=Units.getReadableTime(routeDuration);this._setRouteInfo(routeLengthTxt.value+" "+this.translateString(routeLengthTxt.unit),routeDurationTxt.value+" "+this.translateString(routeDurationTxt.unit))},_setRouteInfo:function(aRouteLengthText,aRouteDurationText){this._panel.getReplica().setText("routeLabelRight",aRouteLengthText+" | "+aRouteDurationText)},_onWaypointClicked:function(aEvent){var waypoint=aEvent.getData().waypoint;var binder=this;var selectWaypoint=function(){if(binder._waypointListMap[waypoint.getId()]!==undefined){binder._waypointList.fireEvent(new nokia.aduno.utils.Event("selected",{selectedIndex:binder._waypointListMap[waypoint.getId()]}),false)}};if(!this._maneuversOn&&this._routing.getCurrentRoute().getManeuvers()){this._removeSwitchButtons();this._addManeuversToList();this._maneuversOn=true;setTimeout(selectWaypoint,250)}else{selectWaypoint()}},_createWaypointItem:function(aWaypoint,aIndex,arrWayPointsLength){var waypointItem=new WaypointListItem(aWaypoint,aIndex,"WaypointItem",WebWaypointSpice.WebWaypointSpiceTemplateLibrary,this._spiceManager,true,true);waypointItem.addEventHandler(WaypointListItem.EVENT_WAYPOINT_SELECTED,this._onSelectWaypointItem,this);waypointItem.addEventHandler(WaypointListItem.EVENT_DRAG_END,this._onWaypointItemDragEnd,this);waypointItem.removeCSSTrigger(Control.CSS_TRIGGER_OVER);this._updateWaypointDeleteHandler(waypointItem,aIndex);this._waypointItems[aWaypoint]=waypointItem;return waypointItem},_updateWaypointIndexes:function(){for(var i=0,len=this._waypointList.getChildCount();i<len;i++){var listItem=this._waypointList.getChildAt(i);listItem.setIndex(i)}},_onWaypointItemSelected:function(aEvent){var data=aEvent.getData();if(data.selectedIndex!==this._currentSelectedIndex&&this._currentSelectedIndex!=-1){this._waypointList.getChildAt(this._currentSelectedIndex).getReplica().removeCssClass("nmp_ListItemFocused")}this._currentSelectedIndex=data.selectedIndex;this._waypointList.getChildAt(this._currentSelectedIndex).getReplica().addCssClass("nmp_ListItemFocused");this._scrollToItem(this._waypointList.getChildAt(this._currentSelectedIndex))},_onSelectWaypointItem:function(aEvent){this._model.moveTo(aEvent.getData().waypoint.getPosition())},_onWaypointItemDragEnd:function(aEvent){var oldIndex=aEvent.getData().oldIndex;var newIndex=aEvent.getData().newIndex;if(oldIndex!==newIndex){this._routing.getCurrentRoute().moveWaypoint(oldIndex,newIndex)}else{this._waypointList.getChildAt(oldIndex).getReplica().removeStyle("item","top")}},_onSelectManeuverItem:function(aEvent){this._model.moveTo(aEvent.getData().maneuver.getPosition())},_onClearCurrentRoute:function(aEvent){var currentRoute=this._routing.getCurrentRoute();if(currentRoute!==null){this._clearRoute=true;this._routing.clearRoute(currentRoute);currentRoute.clear();this._routeSettings.reset()}},_onPrintCurrentRoute:function(aEvent){var currentRoute=this._routing.getCurrentRoute();if(currentRoute!==null){currentRoute.getPrintView(this._translator,this._spiceManager,this._model)}},_onMapMove:function(){var position=this._model.getMapCenterPosition();if(this._searchModel.getDiscoveryFrameworkCore(this._firstDfw)._nspQuery&&this._searchModel.getDiscoveryFrameworkCore(this._secondDfw)._nspQuery){this._searchModel.getDiscoveryFrameworkCore(this._firstDfw)._nspQuery.queryParams.otherParams.lat=position.latitude;this._searchModel.getDiscoveryFrameworkCore(this._firstDfw)._nspQuery.queryParams.otherParams.lon=position.longitude;this._searchModel.getDiscoveryFrameworkCore(this._secondDfw)._nspQuery.queryParams.otherParams.lat=position.latitude;this._searchModel.getDiscoveryFrameworkCore(this._secondDfw)._nspQuery.queryParams.otherParams.lon=position.longitude}},_updateWaypointDeleteHandler:function(aListItem,aIndex){var binder=this;try{if(aListItem.getReplica().getRootElement()){if(aListItem.getReplica().getRootElement().className.indexOf("Search")!==-1){return}}}catch(ex){}var deleteButton=aListItem.getChildAt("button");if(deleteButton){aListItem.removeChild(deleteButton)}deleteButton=new Button("WaypointDelete");deleteButton.addEventHandler("selected",function(){binder._deleteWaypoint(aIndex)},this);aListItem.setChildAt(deleteButton,"button")},_scrollToItem:function(aItem){if(!this._scrollFx){this._scrollFx=new Fx(this._waypointList.getBehavior("Scrollable").getRootElement())}if(this._scrollFx.currentFx){this._scrollFx.stop()}this._scrollFx.effect({duration:this._scrollDuration,attributes:{scrollTop:[this._waypointList.getBehavior("Scrollable").getRootElement().scrollTop,aItem.getReplica().getRootElement().offsetTop]}}).start()},_createSwitchButton:function(aIndex){var binder=this;var switchButton=new Button("WaypointSwitch");switchButton.addEventHandler("selected",function(){binder._switchWaypoints(aIndex,aIndex+1)},this);switchButton.removeCSSTrigger(Control.CSS_TRIGGER_OVER);return switchButton},_createSwitchButtons:function(){var count=this._waypointList.getChildCount();for(var i=0;i<count-1;i++){var listItem=this._waypointList.getChildAt(i);listItem.setChildAt(this._createSwitchButton(i),"switch")}},_removeSwitchButtons:function(){var count=this._waypointList.getChildCount();for(var i=0;i<count-1;i++){var listItem=this._waypointList.getChildAt(i);var switcher=listItem.getChildAt("switch");if(switcher){listItem.removeChild(switcher)}}},_switchWaypoints:function(aTop,aBottom){if(this._changeTimeout){clearTimeout(this._changeTimeout);this._changeTimeout=null}var top=this._waypointList.getChildAt(aTop);var bottom=this._waypointList.getChildAt(aBottom);if(top.getReplica().getRootElement().className.indexOf("Search")!==-1){if(aBottom===this._waypointList.getChildCount()-1){this._searchPosition=-1}else{this._searchPosition=aTop+1}this._updateUi(this._routing.getCurrentRoute(),{action:Route.ROUTE_WAYPOINT_MOVED,index_from:aTop,index_to:aBottom,isSearchMove:true})}else{if(bottom.getReplica().getRootElement().className.indexOf("Search")!==-1){this._searchPosition=aBottom-1;this._updateUi(this._routing.getCurrentRoute(),{action:Route.ROUTE_WAYPOINT_MOVED,index_from:aTop,index_to:aBottom,isSearchMove:true})}else{if(this._searchPosition!==-1&&this._searchPosition<aTop){aTop=aTop-1}this._routing.getCurrentRoute().moveWaypoint(aTop,aTop+1)}}},_resetListItems:function(){var i=65;var count=this._waypointList.getChildCount();for(var j=0;j<count;j++){var waypointItem=this._waypointList.getChildAt(j);if(i>90){var remainder=String.fromCharCode(i%91+65);waypointItem.getReplica().setText("icon",String.fromCharCode(i/91+64)+""+remainder)}else{waypointItem.getReplica().setText("icon",String.fromCharCode(i))}if(waypointItem.setIndex){waypointItem.setIndex(j)}if(waypointItem.className==="WaypointListItem"){waypointItem.getReplica().removeStyle("item","top");waypointItem.getReplica().removeCssClass("nmp_ListItemFocused")}i++}},_deleteWaypoint:function(aIndex){var route=this._routing.getCurrentRoute();if(route.getWaypoints().length>0){this._routing.cancelRouteCalculation()}this._routing.clearRoute(route);this._routing.removeWaypointsFromMap();if(this._maneuversOn){this._removeManeuversFromList()}this._deleteIndex=aIndex;if((this._searchPosition!==-1&&this._searchPosition<=aIndex&&this._searchPosition>0)||route.getWaypoints().length===aIndex){aIndex=aIndex-1}route.removeWaypointAt(aIndex)},_onPreviousManeuver:function(aEvent){if(this._currentSelectedIndex>0){this._waypointList.fireEvent(new nokia.aduno.utils.Event("selected",{selectedIndex:this._currentSelectedIndex-1}),false)}},_onNextManeuver:function(aEvent){if(this._currentSelectedIndex<this._waypointList.getChildCount()-1){this._waypointList.fireEvent(new nokia.aduno.utils.Event("selected",{selectedIndex:this._currentSelectedIndex+1}),false)}},_onRouteCalculated:function(aRouteEvent){var eventData=aRouteEvent.getData();this._updateRouteInfo(eventData.route);this._maneuverItems=[];var binder=this;setTimeout(function(){binder._routing.addManeuverSpots(eventData.route)},1);this._maneuverButton.getReplica().removeCssClass("plusMinus","disabled")},_onRouteError:function(aError){var data=aError.getData();if(data.errorCause===RoutingModel.ERROR_CAUSE_CANNOT_DO_PEDESTRIAN){this._removeManeuversFromList();this._updateRouteInfo(null);var route=this._routing.getCurrentRoute();route._maneuvers=null;this._maneuverButton.getReplica().addCssClass("plusMinus","disabled")}},_createRoute:function(){var route=new Route(null,this._pluginControl);route.setColor({red:0,green:173,blue:238,alpha:255});this._routeSettings.applySettings(route);this._routing.setCurrentRoute(route);return route},_addWaypoint:function(aPosition,aAddress,aDestination){var waypoint=new Waypoint(aPosition,null,aAddress);var route=this._routing.getCurrentRoute();if(route===null){route=this._createRoute()}this._isDestination=aDestination;if(aDestination&&route.getWaypoints().length===0){this._searchPosition=0;route.addWaypoint(waypoint);route.addDummyWaypoint(0)}else{if(this._searchPosition===-1){route.addWaypoint(waypoint)}else{route.insertWaypointAt(this._searchPosition,waypoint);this._searchPosition=-1}}},_onWaypointsChanged:function(aEvent){var route=this._routing.getCurrentRoute();if(!route){this._createRoute()}var data=aEvent.getData();this._updateUi(route,data);if(data.action!==Route.ROUTE_WAYPOINT_CLEARED){var binder=this;this._changeTimeout=setTimeout(function(){if(route.isValid()){binder._routeSettings.applySettings(binder._routing.getCurrentRoute());binder._routing.calculateRoute(route)}else{if(route.getWaypoints().length<=1){binder._routing.cancelRouteCalculation()}route._maneuvers=null}},1000)}},_onCurrentRouteChanged:function(aRouteChangeEvent){var newRoute=aRouteChangeEvent.getData().newRoute;var oldRoute=aRouteChangeEvent.getData().oldRoute;if(oldRoute){oldRoute.removeEventHandler(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,this._onWaypointsChanged,this)}if(newRoute){newRoute.addEventHandler(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,this._onWaypointsChanged,this)}else{this._createRoute()}},_onRouteSettingsChanged:function(aEvent){if(this._routing.getCurrentRoute()&&this._routing.getCurrentRoute().getWaypoints().length>1&&!this._routeSettings.hasEqualSettings(this._routing.getCurrentRoute())){this._routeSettings.applySettings(this._routing.getCurrentRoute());this._routing.calculateRoute(this._routing.getCurrentRoute());if(this._maneuversOn){this._removeManeuversFromList()}}},_resultSelected:function(aResultItem,aIndex){this._resultLists[aIndex].getChildAt("root")._clearResults();this._resultLists[aIndex].hide();this._searchBoxes[aIndex].setValue(aResultItem.title);var isDestination=false;if(aIndex===1&&this._routing.getCurrentRoute().getWaypoints().length===0){isDestination=true}this._addWaypoint({latitude:parseFloat(aResultItem.latitude),longitude:parseFloat(aResultItem.longitude)},aResultItem.title,isDestination)},_clearResultList:function(aIndex){this._resultLists[aIndex].hide()},_createSearchItem:function(aIndex){var searchItem=null;if(this._numSearchItems<=aIndex){var dfwCore=null;if(this._numSearchItems===0){dfwCore=this._searchModel.getDiscoveryFrameworkCore(this._firstDfw)}else{if(this._numSearchItems===1){dfwCore=this._searchModel.getDiscoveryFrameworkCore(this._secondDfw)}}searchItem=new SearchListItem(aIndex,null,null,this._spiceManager);if(dfwCore._nspQuery){var position=this._model.getMapCenterPosition();dfwCore._nspQuery.queryParams.otherParams.lat=position.latitude;dfwCore._nspQuery.queryParams.otherParams.lon=position.longitude;var dfwUI=new nokia.maps.dfw.ui.DiscoveryFrameworkUI(dfwCore,this._page);this._searchBoxes[aIndex]=dfwUI.getSearchBox();var resultList=null;var errorPresenter=null;resultList=dfwUI.getResultList();errorPresenter=dfwUI.getErrorPresenter();this._resultLists[aIndex]=new Container("WaypointResultContainer",WebWaypointSpice.WebWaypointSpiceTemplateLibrary);this._resultLists[aIndex].setChildAt(errorPresenter,"errorPresenter");this._resultLists[aIndex].setChildAt(resultList,"root");var binder=this;this._resultLists[aIndex].hide();searchItem.setChildAt(this._searchBoxes[aIndex],"searchBox");searchItem.setChildAt(this._resultLists[aIndex],"suggestionList")}this._searchItems[this._searchItems.length]=searchItem;this._numSearchItems++}else{searchItem=this._searchItems[aIndex]}return searchItem},onResultListResultItemSelected:function(aEvent){var index=0;if(aEvent.source===this._searchModel.getDiscoveryFrameworkCore(this._secondDfw)._eventController){index=1}if(aEvent.getData().resultItem){this._resultSelected(aEvent.getData().resultItem,index)}},onResultServiceNewResultsAvailable:function(aEvent){if(aEvent.source===this._searchModel.getDiscoveryFrameworkCore(this._firstDfw)._eventController){this._resultLists[0].show()}else{this._resultLists[1].show()}},onResultServiceResultsCleared:function(aEvent){if(aEvent.source===this._searchModel.getDiscoveryFrameworkCore(this._firstDfw)._eventController){this._resultLists[0].hide()}else{this._resultLists[1].hide()}},onSearchBoxLostFocus:function(aEvent){var index=0;if(aEvent.source===this._searchModel.getDiscoveryFrameworkCore(this._secondDfw)._eventController){index=1}var binder=this;setTimeout(function(){binder._clearResultList(index)},500)},onResultListError:function(aEvent){this._searchError=true},onResultListNoError:function(aEvent){this._searchError=false},onSearchBoxKeyUpEvent:function(aEvent){var index=0;if(aEvent.source===this._searchModel.getDiscoveryFrameworkCore(this._secondDfw)._eventController){index=1}var resultList=this._resultLists[index].getChildAt("root").getSelected();var keyCode=aEvent.getData().e.keyCode;var selectionIndex=resultList.getSelectionIndex();if(keyCode===38){if(selectionIndex>0){--selectionIndex}else{selectionIndex=resultList.getChildCount()-1}resultList.setSelectionIndex(selectionIndex)}else{if(keyCode===40){if(selectionIndex+1<resultList.getChildCount()){++selectionIndex}else{selectionIndex=0}resultList.setSelectionIndex(selectionIndex)}else{if(keyCode===13){if(!this._searchError){resultList.getSelected().fireEvent("selected");resultList.getSelected()._onSelected()}}}}aEvent.getData().handled=true}});WebWaypointSpice.WebWaypointSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({WaypointPanel:'<div class="nmp_WaypointsPanel"><div id="top" class="nmp_WaypointsPanel_Top"><div id="routeLabelLeft" class="nmp_WaypointsPanel_TopLeft nmp_WebBoldText"></div><div id="routeLabelRight" class="nmp_WaypointsPanel_TopRight"></div><div  class="nmp_WaypointsPanel_Turns"><div id="maneuverToggle"></div></div></div><div id="waypointContainer"></div></div>',WaypointContainer:'<div id="WaypointListContainer" class="nmp_Waypoints_Container"><div id="WaypointScrollable"><div id="waypointList"></div></div></div>',WaypointScrollable:'<div class="nmp_WaypointScrollable"></div>',WaypointList:'<div class="nmp_WaypointList"></div>',WaypointItem:'<div id="item" class="nmp_WaypointsItem_Container"><div class="nmp_WaypointsItem"><div class="nmp_WaypointIcon nmp_WaypointItemIcon"><span id="icon"></span></div><div id="place" class="nmp_Label nmp_WaypointsItem_Place"></div><div id="street" class="nmp_WaypointsItem_Label nmp_WaypointsItem_Street"></div><div id="button" class="nmp_WaypointsItem_Delete"></div></div><div class="nmp_WaypointSwitchContainer"><div id="switch"></div></div></div>',WaypointDelete:'<div class="nmp_WaypointDelete"></div>',WaypointSwitch:'<div class="nmp_WaypointSwitch"></div>',SearchBox:'<div id="searchBox" class="nmp_WaypointSearch_Box"><span id="termBox"></span><span id="searchButton"></span></div>',WaypointResultContainer:'<div class="nmp_WaypointSuggestion"><div id="errorPresenter"></div><div id="root" class="nmp_WaypointSuggestion_Results"></div><div class="nmp_WaypointSuggestion_Footer"><div></div></div></div>',WaypointResults:"<div></div>",ResultList:'<ul id="list" class="nmp_WaypointSuggestion_List"></ul>',ResultListItem:'<li id="item" class="nmp_WaypointSuggestion_ListItem"><span class="nm_Hidden" id="resultNumber"></span><span id="resultLine1Wrapper" class="nmp_ellipsis"><span class="nmd_ResultLine1" id="resultLine1"></span></span><span id="resultLine2Wrapper"><span class="nmd_ResultLine2" id="resultLine2"></span></span><span class="nmd_ResultDistance" id="resultDistance"></span><span class="nmd_ResultIcon" id="resultIcon"></span></li>',ErrorPresenter:'<div id="errorPresenter" class="nmp_ErrorPresenter"></div>',ManeuverToggle:'<div id="plusMinus" class="nmp_WaypointsPanel_PlusMinus plus disabled nmp_WebBoldText"><span id="button"></span></div>',ManeuverItem:'<div class="nmp_ManeuverContainer"><div class="nmp_ManeuverItem"><div id="maneuver" class="nmp_Icon"></div><div class="nmp_ManeuverItem_Label"><span id="index" class="nmp_ManeuverItem_Index"></span><span id="description" class="nmp_ManeuverItem_Description"></span></div><div id="distance" class="nmp_ManeuverItem_Distance"><span id="distanceFromPrevious" class="nmp_ManeuverItem_DistanceFromPrevious"></span><span id="distanceFromStart" class="nmp_ManeuverItem_DistanceFromStart"></span></div></div><div class="nmp_ManeuverItemFooter"></div></div>',PlaceHolder:'<div id="placeholder" style="background-color: red; width: 100%"></div>'},nokia.maps.dfw.ui.DFWTemplateLibrary);var GuidanceMapSpice=new Class({Name:"GuidanceMapSpice",Extends:Spice,_guidanceModel:null,_mapModel:null,_positionModel:null,_gpsIconLayer:null,ICON_GPS_POSITION:"../ext/pfw/images/spices/guidancemapspice/touch/ico_gps_car_2d_red.svg",initialize:function(aSpiceManager,aModels){this._super(aSpiceManager);this._guidanceModel=aModels.guidance;this._mapModel=aModels.map;this._positionModel=aModels.position;this._zoomModel=aModels.zoom;this._applicationModel=aModels.application;this._deviceModel=aModels.device;this._guidanceModel.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STARTED,this._activate,this);this._guidanceModel.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STOPPED,this._deactivate,this);this._guidanceModel.addEventHandler(GuidanceModel.EVENT_GUIDANCE_DONE,this._deactivate,this)},_activate:function(aEvent){var size=this._spiceManager.getSize();this._transformDelta={x:0,y:size.y/4};this._mapModel.setTransformCenter(this._transformDelta.x,this._transformDelta.y);this._zoomModel.setStep(2);this._positionMarkerAccurate=this._createMapMarker(this.ICON_GPS_POSITION);this._positionMarkerAccurate.setPosition(this._mapModel.getMapCenterPosition());this._positionModel.addEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);if(layout.snc){this._applicationModel.pushSettings();this._applicationModel.setButtonLabels("Options","Stop");this._applicationModel.setTitlebarEnabled(false);var keyBind=bind(this,this._handleKeys);this._spiceManager.setKeyHandler(KeyEventManager.KEY_LSK,0,keyBind);this._spiceManager.setKeyHandler(KeyEventManager.KEY_CSK,0,keyBind);this._spiceManager.setKeyHandler(KeyEventManager.KEY_RSK,0,keyBind)}this._deviceModel.setDisableBacklightDimming(true)},_deactivate:function(aEvent){this._deviceModel.setDisableBacklightDimming(false);this._positionModel.removeEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);if(this._positionChangeSimulator){this._positionModel._setPositionProvider();this._positionChangeSimulator.deactivate()}this._mapModel.setTransformCenter(-this._transformDelta.x,-this._transformDelta.y);this._mapModel.setOrientation(0);this._positionMarkerAccurate.hide();if(layout.snc){this._applicationModel.popSettings();this._spiceManager.removeKeyHandler(KeyEventManager.KEY_LSK,0);this._spiceManager.removeKeyHandler(KeyEventManager.KEY_CSK,0);this._spiceManager.removeKeyHandler(KeyEventManager.KEY_RSK,0)}},_createMapMarker:function(aImageUri){var marker=new MapMarker(null,null,aImageUri);marker.show();this._gpsIconLayer=this._mapModel.createLayer({name:"Guidance SVG Layer"});this._gpsIconLayer.addMapObjects(marker);marker.setPosition(this._mapModel.getMapCenterPosition());this._gpsIconLayer.setZIndex(1000);this._gpsIconLayer.show();return marker},_onPositionChanged:function(aEvent){var positionData=aEvent.getData();this._mapModel.setMapCenterPosition(positionData.position);this._mapModel.setOrientation(positionData.direction);this._positionMarkerAccurate.setPosition(positionData.position)},_handleKeys:function(aKeyEvent){if(aKeyEvent.keyDown){var key=aKeyEvent.getKey();switch(key){case KeyEventManager.KEY_LSK:nokia.aduno.utils.info("The guidance options are not yet implented.");break;case KeyEventManager.KEY_RSK:this._guidanceModel.stopNavigation();break}}}});var TopMenuSpice=new Class({Name:"TopMenuSpice",Extends:Spice,initialize:function(){},_createUi:function(){var c=new nokia.aduno.medosui.Control("right",TopMenuSpice.BackgroundTemplate);return c},onAttach:function(){this._spiceControl.getRootElement().parentNode.className="nmp_TopMenuBar"},hide:function(){this._spiceControl.getRootElement().parentNode.className="nmp_TopMenuBar nm_Hidden"},show:function(){this._spiceControl.getRootElement().parentNode.className="nmp_TopMenuBar"}});TopMenuSpice.BackgroundTemplate=new nokia.aduno.dom.TemplateLibrary({right:'<div class="nmp_TopMenuBarRight" unselectable="on"></div>'});var CopyrightSpice=new Class({Name:"CopyrightSpice",Extends:Spice,initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._mapModel=aMapModel;this._currentWhite=null;this._previousText="";this._publicMethods=["updateCopyrightText"];this._spiceManager.addEventHandler(SpiceManager.EVENT_UI_TRANSLATED,this._translateSpice,this)},onAttach:function(){this._mapModel.addEventHandler(MapModel.EVENT_MOVE_DONE,this.updateCopyrightText,this);this._mapModel.addEventHandler(MapModel.EVENT_ANIMATION_DONE,this.updateCopyrightText,this);this._mapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this.updateCopyrightText,this);this._mapModel.addEventHandler(MapModel.EVENT_MAPTYPE,this._onMapChange,this);this._mapModel.addEventHandler(MapModel.EVENT_COLOR,this._onMapChange,this);this.updateCopyrightText();if(nokia.aduno.utils.browser.msie){this._textSelectionCallback=function(){return false};this._spiceControl.getRootElement().attachEvent("onselectstart",this._textSelectionCallback)}},onDetach:function(){if(nokia.aduno.utils.browser.msie){this._spiceControl.getRootElement().detachEvent("onselectstart",this._textSelectionCallback)}},_createUi:function(){var containerId=nokia.aduno.utils.platform.maemo?"CopyrightContainerMaemo":"CopyrightContainer";this._container=new nokia.aduno.medosui.Container(containerId,CopyrightSpice.TemplateLibrary);this._copyright=new nokia.aduno.medosui.Control("Copyright",CopyrightSpice.TemplateLibrary);this._container.setChildAt(this._copyright,"copyright");this._spiceManager.addDraggingDelegationControl(this._container);return this._container},updateCopyrightText:function(){var message=this._mapModel.getCopyright();if(message&&message.length>0){var root=this._copyright.getRootElement();while(root.childNodes.length){root.removeChild(root.firstChild)}root.appendChild(document.createTextNode(message));this._copyright.getReplica().addCssClass("nmp_Copyright");this._copyright.show();if(message!==this._previousText){this._spiceControl.fireEvent(new nokia.aduno.utils.Event(CopyrightSpice.COPYRIGHT_TEXT_CHANGED,{text:message}))}this._previousText=message}else{this._copyright.hide()}this._translateSpice()},_onMapChange:function(aEvent){var color=this._mapModel.getColor();var type=this._mapModel.getMapType();var xnode=new XNode(this._container.getRootElement());if(color=="night"||type=="terrain"||type=="hybrid"||type=="satellite"){xnode.addCssClass("white")}else{xnode.removeCssClass("white")}},_translateSpice:function(){if(this._spiceManager&&this._spiceManager._localizer){this._spiceManager._localizer.traverse(this.getUi().getRootElement())}}});CopyrightSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({CopyrightContainer:'<div class="nmp_CopyrightContainer"><div id="copyright"></div><div class="nmp_TermsOfUse"><a href="__I18N_mapPlayer_67_settings_donwloadPlugin_link_termsAndConditions__" unselectable="on" target="blank">__I18N_mapPlayer_66_settings_donwloadPlugin_txt_termsAndConditions__</a></div></div>',CopyrightContainerMaemo:'<div class="nmp_CopyrightContainer"><div id="copyright"></div></div>',Copyright:"<div></div>"});CopyrightSpice.COPYRIGHT_TEXT_CHANGED="copyrightTextChanged";var WatermarkSpice=new Class({Name:"WatermarkSpice",Extends:Spice,initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._mapModel=aMapModel},_createUi:function(){var watermark=new nokia.aduno.medosui.Container("Watermark",WatermarkSpice.TemplateLibrary);this._mapModel.addEventHandler(MapModel.EVENT_MAPTYPE,this._onMapChange,this);this._mapModel.addEventHandler(MapModel.EVENT_COLOR,this._onMapChange,this);this._spiceManager.addDraggingDelegationControl(watermark);return watermark},_onMapChange:function(){var color=this._mapModel.getColor();var type=this._mapModel.getMapType();var xnode=new XNode(this._spiceControl.getRootElement());if(color=="night"||type=="terrain"||type=="hybrid"||type=="satellite"){xnode.addCssClass("white")}else{xnode.removeCssClass("white")}}});WatermarkSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({Watermark:'<div class="nmp_Watermark" unselectable="on"><div unselectable="on"></div></div>'});var ScaleBarSpice=new Class({Name:"ScaleBarSpice",Extends:Spice,Implements:Serializable,MEASUREMENTS:[{lengthInMeters:1000},{lengthInMeters:1609.344}],RULER_SCALES:[1,2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000,100000,200000,500000,1000000,2000000,5000000,10000000,20000000,50000000],_kmLabel:"__I18N_mapPlayer_26_mapControl_scale_txt_kilometres__\u00A0",_mileLabel:"__I18N_mapPlayer_24_mapControl_scale_txt_miles__\u00A0",defaultRulerWidth:45,initialize:function(aSpiceManager,aMapModel,aZoomModel){this._zoomModel=aZoomModel;this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._currentMeasurement=aMapModel.getMeasurementType()?1:0;this._enlargeButton=null;this._measurentButtonWidth=0;this._rulerBar=null;this._spiceControlReplica=null;this._isEnlarged=false;this._timer=null;this._mapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onZoomChange,this);this._mapModel.addEventHandler(MapModel.EVENT_MAXZOOM,this._onZoomChange,this);this._mapModel.addEventHandler(MapModel.EVENT_MEASUREMENT_TYPE_CHANGED,this._onMeasurementChanged,this);this._spiceManager.addEventHandler(SpiceManager.EVENT_SIZE_CHANGED,this._setRulerTimer,this);this._minimapSpice=this._spiceManager.getSpice("MiniMapSpice");if(this._minimapSpice){this._minimapSpice.getUi().addEventHandler(MiniMapSpice.STATE_CHANGED,this._onMinimapStateChanged,this)}this._copyrightSpice=this._spiceManager.getSpice("CopyrightSpice");if(this._copyrightSpice){this._copyrightSpice.getUi().addEventHandler(CopyrightSpice.COPYRIGHT_TEXT_CHANGED,this._setRulerTimer,this)}},serialize:function(aPersistence){},deserialize:function(aPersistence){},_createUi:function(){if(nokia.maps.pfw.layout.snc){return null}var scaleBar=new Container("ScaleBarContainer",ScaleBarSpice.ScaleBarSpiceTemplateLibrary);this._enlargeButton=new Button("ScaleBarEnlargeButton");this._enlargeButton.addEventHandler("selected",this._handleEnlargeMouseClick,this);this._rulerBar=new List("ScaleBarRuler");this._rulerBar.addChild(new Label("ScaleBarText"));this._measurementButton=new Button("ScaleBarMeasurementButton");this._measurementButton.addEventHandler("selected",this._handleMeasurementMouseClick,this);scaleBar.setChildAt(this._enlargeButton,"enlargeButton");scaleBar.setChildAt(this._rulerBar,"rulerBar");scaleBar.setChildAt(this._measurementButton,"measurementButton");return scaleBar},_onZoomChange:function(aEvent){this._setRulerTimer()},_handleEnlargeMouseClick:function(aClickEvent){if(!this._isEnlarged){this._spiceControlReplica.addCssClass("enlargeButton","nmp_ScaleBarEnlargedButton");this._spiceControlReplica.addCssClass(TemplateReplica.ROOT_ID,"nmp_ScaleBarEnlarged")}else{this._spiceControlReplica.removeCssClass("enlargeButton","nmp_ScaleBarEnlargedButton");this._spiceControlReplica.removeCssClass(TemplateReplica.ROOT_ID,"nmp_ScaleBarEnlarged")}this._isEnlarged=!this._isEnlarged;this._setRulerTimer()},_handleMeasurementMouseClick:function(aClickEvent){this._mapModel.setMeasurementType(this._currentMeasurement===0)},_setMeasurementUi:function(){if(this._currentMeasurement===1){this._spiceControlReplica.addCssClass("measurementButton","nmp_ScaleBarImperialButton");this._measurementButton.setText(this._mileLabel)}else{this._spiceControlReplica.removeCssClass("measurementButton","nmp_ScaleBarImperialButton");this._measurementButton.setText(this._kmLabel)}if(this._spiceManager._localizer){this._spiceManager._localizer.traverse(this._measurementButton.getRootElement())}this._setRulerTimer()},_onMeasurementChanged:function(aEvent){var data=aEvent.getData();var measurement=data.useImperialUnits?1:0;if(this._currentMeasurement!==measurement){this._currentMeasurement=measurement;this._setMeasurementUi()}},onAttach:function(){this._spiceControlReplica=this._spiceControl.getReplica();if(this._minimapSpice){if(!this._minimapSpice.getUi().isVisible()){this._spiceControlReplica.addCssClass("nmp_MinimapSpiceHidden")}else{if(!this._minimapSpice.isVisible()){this._spiceControlReplica.addCssClass("nmp_MinimapSpiceClosed")}}}else{this._spiceControlReplica.addCssClass("nmp_MinimapSpiceClosed")}if(this._currentMeasurement===0){this._spiceControlReplica.removeCssClass("measurementButton","nmp_ScaleBarImperialButton");this._measurementButton.setText(this._kmLabel)}else{this._spiceControlReplica.addCssClass("measurementButton","nmp_ScaleBarImperialButton");this._measurementButton.setText(this._mileLabel)}this._spiceControl.setCSSTrigger(Control.CSS_TRIGGER_OVER);var self=this;window.setTimeout(function(){if(self._spiceManager._localizer){self._spiceManager._localizer.traverse(self._measurementButton.getRootElement())}self._setRulerTimer()},0)},_setRulerTimer:function(){if(this._timer){cancelTimer(this._timer)}this._timer=nokia.aduno.utils.setTimer(10,this,this._setRuler)},_setRuler:function(){var windowWidth=this._spiceManager.getSize().x;if(windowWidth<400){this._spiceControl.hide();return}else{this._spiceControl.show()}var model=this._mapModel;var distance=model.getZoomScale()*this.defaultRulerWidth/100;var defaultLength=this.MEASUREMENTS[0].lengthInMeters;distance*=defaultLength;distance/=this.MEASUREMENTS[this._currentMeasurement].lengthInMeters;distance=Math.round(distance);var scalesLength=this.RULER_SCALES.length-1;var normDistance=distance;for(var i=0;i<scalesLength;i++){normDistance=this.RULER_SCALES[i];if(normDistance>=distance){break}}var newWidth=Math.round(this.defaultRulerWidth*normDistance/distance);normDistance/=defaultLength;if(this._rulerBar.getChildAt(0)){this._rulerBar.getChildAt(0).setText(""+normDistance)}while(this._rulerBar.getChildCount()>1){this._rulerBar.removeChildAt(1)}if(this._isEnlarged){if(!this._measurentButtonWidth){this._measurentButtonWidth=Dimensions.getSize(this._spiceControlReplica.getElement("measurementButton")).x;this._enlargeButtonWidth=Dimensions.getSize(this._spiceControlReplica.getElement("enlargeButton")).x}var viewPortWidth=windowWidth;var spice=this._spiceManager.getSpice("MiniMapSpice");if(spice&&spice.getUi().isVisible()){viewPortWidth-=nokia.aduno.dom.Dimensions.getSize(spice.getUi().getRootElement()).x;viewPortWidth-=5}spice=this._spiceManager.getSpice("CopyrightSpice");if(spice){var csUi=spice.getUi().getRootElement();var scUiLength=0;for(var ii=0;ii<csUi.childNodes.length;ii++){var csUiChild=csUi.childNodes[ii];if(csUiChild){var csUiChildLength=nokia.aduno.dom.Dimensions.getSize(csUiChild).x;if(csUiChildLength>scUiLength){scUiLength=csUiChildLength}}}viewPortWidth-=scUiLength}viewPortWidth-=170;if(viewPortWidth>=newWidth){var rulerCount=Math.floor(viewPortWidth/newWidth);var labelText=normDistance;for(var j=0;j<rulerCount;j++){labelText+=normDistance;labelText*=1000;labelText=Math.round(labelText)/1000;this._rulerBar.addChild(new Label("ScaleBarText",labelText+"\u00A0"))}}}var childCount=this._rulerBar.getChildCount();if((childCount*newWidth)>viewPortWidth){childCount-=1;this._rulerBar.removeChildAt(childCount)}for(var k=0;k<childCount;k++){this._rulerBar.getChildAt(k).getReplica().setStyle(TemplateReplica.ROOT_ID,"width",newWidth+"px")}this._rulerBar.getReplica().setStyle(TemplateReplica.ROOT_ID,"width",(childCount*newWidth)+"px");this._spiceControl.getReplica().setStyle(TemplateReplica.ROOT_ID,"width",((childCount*newWidth)+76)+"px")},_onMinimapStateChanged:function(aEvent){var replica=this._spiceControl.getReplica();var minimapState=aEvent.getData();replica.removeCssClass("nmp_MinimapSpiceHidden");replica.removeCssClass("nmp_MinimapSpiceClosed");if(!minimapState.visible){replica.addCssClass("nmp_MinimapSpiceHidden")}else{if(!minimapState.shown){replica.addCssClass("nmp_MinimapSpiceClosed")}}this._setRulerTimer()}});ScaleBarSpice.ScaleBarSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({ScaleBarContainer:'<div class="nmp_ScaleBarContainer" unselectable="on"><div class="nmp_ScaleBarAlphaWrapper" unselectable="on"><div id="enlargeButton"></div><div id="rulerBar"></div><div id="measurementButton"></div></div></div>',ScaleBarEnlargeButton:'<div class="nmp_ScaleBarButton" unselectable="on"><div id="button" class="nmp_ScaleBarEnlargeButton" unselectable="on"></div></div>',ScaleBarRuler:'<div class="nmp_ScaleBarRuler" unselectable="on"></div>',ScaleBarText:'<div class="nmp_ScaleBarRulerSection" unselectable="on"><div id="label" unselectable="on"></div></div>',ScaleBarMeasurementButton:'<div class="nmp_ScaleBarButton" unselectable="on"><div id="button" class="nmp_ScaleBarMeasurementButton" unselectable="on"></div></div>'});var MiniMapSpice=new Class({Name:"MiniMapSpice",Extends:Spice,initialize:function(aSpiceManager,aMapModel,aAppearanceModel,aZoomModel,aMinimalSizes){this._super(aSpiceManager);this._mapModel=aMapModel;this._zoomModel=aZoomModel;this._minimalSizes=aMinimalSizes;this._zoomHigh=this._zoomModel.getStep()>=MiniMapSpice.MAX_ZOOM;this._appear=aAppearanceModel;this._mapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onZoom,this);this._mapModel.addEventHandler(MapModel.EVENT_TILT,this._onModelTiltChanged,this);this._mapModel.addEventHandler(MapModel.EVENT_TILT_START,this._onModelTiltStart,this);this._mapModel.addEventHandler(MapModel.EVENT_ANIMATION_DONE,this._onAnimationDone,this);this._isIn3D=this._mapModel.getMode3d();this._publicMethods=["isVisible"];this._timer=null;this._miniMap={width:0,height:0,top:0,left:0};this._shown=false;this._cursor=null;this._cursorDim={height:0,width:0,left:0,top:0};this._spiceManager.addEventHandler(SpiceManager.EVENT_SIZE_CHANGED,this._onResizeTimer,this)},isVisible:function(){return this._shown},_createUi:function(){this._container=new Container(null,MiniMapSpice.TemplateLib);this._cursor=new Control("Cursor",MiniMapSpice.TemplateLib);this._draggable=new Draggable();this._cursor.addBehavior(this._draggable);this._button=new Button(MiniMapSpice.TemplateLib.getTemplate("Button"));this._button.addEventHandler("selected",this._onClick,this);this._button.getReplica().addCssClass("nmp_MiniMapButton");this._button.setCSSTrigger(Control.CSS_TRIGGER_OVER);this._button.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._cursor.addEventHandler("dragged",this._onDrag,this);this._cursor.addEventHandler("draggingEnded",this._onDragEnd,this);this._container.setChildAt(this._button,"button");this._container.setChildAt(this._cursor,"cursor");this._cursor.hide();if(!this._mapModel.getPluginControl().isPluginInUse()){this._container.getReplica().addCssClass(TemplateReplica.ROOT_ID,"nm_Disabled")}return this._container},onAttach:function(){this._isIn3D=this._mapModel.getMode3d();this._zoomHigh=this._zoomModel.getStep()>=MiniMapSpice.MAX_ZOOM;this._isIn3D?this._hideControl():this._showControl()},_onClick:function(){if(!this._mapModel.getPluginControl().isPluginInUse()){this._mapModel.showDownload();return}if(this._shown){this._hideMiniMap();this._fireStateEvent()}else{this._showMiniMap();this._fireStateEvent()}},_onResizeTimer:function(){if(this._timer){cancelTimer(this._timer)}this._timer=nokia.aduno.utils.setTimer(1,this,this._onResize)},_onResize:function(){if(!this._shown){return}if(this._minimalSizes){if(this._appear.getWidth()<=this._minimalSizes.x||this._appear.getHeight()<=this._minimalSizes.y){this._isHiddenBySize=true;this._appear.hideMiniMap();return}else{if(this._isHiddenBySize===true){this._isHiddenBySize=false;this._appear.showMiniMap()}}}var cursorReplica=this._cursor.getReplica();this._miniMap.height=Math.round(this._appear.getHeight()/4);this._miniMap.width=Math.round(this._appear.getWidth()/4);var _cursorDimDelta=2;var _xStartPositionDelta=3;var _yStartPositionDelta=2;var _shadedAreaHeightCoefficient=40/100;var _shadedAreaWidthCoefficient=40/100;var _zoomStep=this._zoomModel.getStep();switch(_zoomStep){case 10:_shadedAreaWidthCoefficient=41/100;break;case 11:_shadedAreaWidthCoefficient=42/100;break;case 12:_shadedAreaWidthCoefficient=43/100;break;case 13:_shadedAreaWidthCoefficient=44/100;break;default:_shadedAreaWidthCoefficient=40/100}this._cursorDim.height=Math.floor(this._miniMap.height*_shadedAreaHeightCoefficient)-_cursorDimDelta;this._cursorDim.width=Math.floor(this._miniMap.width*_shadedAreaWidthCoefficient)-_cursorDimDelta;switch(this._appear.getPosition()){case this._appear.POSITION_BOTTOMRIGHT:this._miniMap.top=this._appear.getHeight()-this._miniMap.height;this._miniMap.left=this._appear.getWidth()-this._miniMap.width;break;case this._appear.POSITION_BOTTOMLEFT:this._miniMap.top=this._appear.getHeight()-this._miniMap.height;this._miniMap.left=0;break;case this._appear.POSITION_TOPRIGHT:this._miniMap.top=0;this._miniMap.left=this._appear.getWidth()-this._miniMap.width;break;case this._appear.POSITION_TOPLEFT:this._miniMap.top=0;this._miniMap.left=0;break;default:debug(this.className+"._onResize: unknown position")}this._startPosition={left:Math.ceil((this._miniMap.width-this._cursorDim.width)/2)+_xStartPositionDelta,top:Math.ceil((this._miniMap.height-this._cursorDim.height)/2)+_yStartPositionDelta};this._cursorDim.left=this._startPosition.left;this._cursorDim.top=this._startPosition.top;this._container.getReplica().setStyle(TemplateReplica.ROOT_ID,"height",this._miniMap.height+"px");this._container.getReplica().setStyle(TemplateReplica.ROOT_ID,"width",this._miniMap.width+"px");cursorReplica.setStyle(TemplateReplica.ROOT_ID,"height",this._cursorDim.height+"px");cursorReplica.setStyle(TemplateReplica.ROOT_ID,"width",this._cursorDim.width+"px");cursorReplica.setStyle(TemplateReplica.ROOT_ID,"left",this._cursorDim.left+"px");cursorReplica.setStyle(TemplateReplica.ROOT_ID,"top",this._cursorDim.top+"px")},_onDragEnd:function(){var mapWidth=this._appear.getWidth();var mapHeight=this._appear.getHeight();var minGeo=this._mapModel.toGeo({x:0,y:0});var maxGeo=this._mapModel.toGeo({x:mapWidth,y:mapHeight});var diffLat=0;var diffLong=0;if(maxGeo!==null){diffLat=Math.abs(maxGeo.getLatitude()-minGeo.getLatitude());diffLong=Math.abs(maxGeo.getLongitude()-minGeo.getLongitude())}else{console.debug("maxGeo is null")}var x=((this._cursorDim.left-this._startPosition.left)/this._cursorDim.width)*diffLong;var y=((this._cursorDim.top-this._startPosition.top)/this._cursorDim.height)*diffLat;var center=this._mapModel.getMapCenterPosition();this._delta=null;this._mapModel.moveTo({latitude:center.latitude-y,longitude:center.longitude+x,animationMode:"linear"});if(nokia.aduno.utils.browser.msie){var cursorReplica=this._cursor.getReplica();cursorReplica.setStyle(TemplateReplica.ROOT_ID,"left",this._startPosition.left+"px");cursorReplica.setStyle(TemplateReplica.ROOT_ID,"top",this._startPosition.top+"px");this._cursorDim.left=this._startPosition.left;this._cursorDim.top=this._startPosition.top}else{if(this._fx){this._fx.stop()}this._fx=new Fx(this._cursor);var end=function(){this._fx=null;this._cursorDim.left=this._startPosition.left;this._cursorDim.top=this._startPosition.top};this._fx.addEventHandler("ended",end,this);this._fx.addEventHandler("stopped",end,this);this._fx.effect({duration:1000,styles:{left:[this._cursorDim.left,this._startPosition.left],top:[this._cursorDim.top,this._startPosition.top]}}).start()}},_onDrag:function(aEvent){if(this._fx){this._fx.stop()}var data=aEvent.getData();if(!this._delta){this._delta={offX:data.mouseX-this._miniMap.left-this._cursorDim.left,offY:data.mouseY-this._miniMap.top-this._cursorDim.top}}var cursorReplica=this._cursor.getReplica();var newX=data.mouseX-this._miniMap.left-this._delta.offX;var newY=data.mouseY-this._miniMap.top-this._delta.offY;if(newX>=0&&newX<=(this._miniMap.width-this._cursorDim.width)){cursorReplica.setStyle(TemplateReplica.ROOT_ID,"left",newX+"px");this._cursorDim.left=newX}if(newY>=0&&newY<=(this._miniMap.height-this._cursorDim.height)){cursorReplica.setStyle(TemplateReplica.ROOT_ID,"top",newY+"px");this._cursorDim.top=newY}},_onZoom:function(aEvent){this._zoomHigh=this._zoomModel.getStep()>=MiniMapSpice.MAX_ZOOM;if(this._isIn3D){return}if(this._zoomHigh){if(this._spiceControl.isVisible()){this._hideControl()}}else{if(!this._spiceControl.isVisible()){this._showControl()}}},_onModelTiltStart:function(aEvent){var currentMode3D=aEvent.getData();if(!currentMode3D){this._hideControl()}},_onModelTiltChanged:function(aEvent){this._isIn3D=this._mapModel.getMode3d();if(this._isIn3D){if(this._spiceControl.isVisible()){this._hideControl()}}else{this._zoomHigh=this._zoomModel.getStep()>=MiniMapSpice.MAX_ZOOM;this._showControl()}},_onAnimationDone:function(){this._onModelTiltChanged()},_showMiniMap:function(){this._appear.showMiniMap();if(!this._zoomHigh){this._cursor.show()}this._shown=true;this._onResize();this._container.getReplica().addCssClass("open");this._button.getReplica().addCssClass("open")},_hideMiniMap:function(){this._appear.hideMiniMap();if(!this._zoomHigh){this._cursor.hide()}this._container.getReplica().setStyle(TemplateReplica.ROOT_ID,"height","");this._container.getReplica().setStyle(TemplateReplica.ROOT_ID,"width","");this._container.getReplica().removeCssClass("open");this._button.getReplica().removeCssClass("open");this._shown=false},_hideControl:function(){this._wasShownBeforeHiding=this._shown;if(this._shown){this._hideMiniMap()}this._spiceControl.hide();this._fireStateEvent()},_showControl:function(){if(!this._zoomHigh){this._spiceControl.show();if(this._wasShownBeforeHiding){this._showMiniMap()}this._fireStateEvent()}},_fireStateEvent:function(){this._spiceControl.fireEvent(new nokia.aduno.utils.Event(MiniMapSpice.STATE_CHANGED,{visible:this._spiceControl.isVisible(),shown:this.isVisible()}))}});MiniMapSpice.TemplateLib=new nokia.aduno.dom.TemplateLibrary({Container:'<div class="nmp_MiniMap" unselectable="on"><div id="cursor"></div><div id="button" class="nmp_MiniMapButton" unselectable="on"></div></div>',Cursor:'<div class="nmp_Cursor" unselectable="on"></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);MiniMapSpice.MAX_ZOOM=14;MiniMapSpice.STATE_CHANGED="minimapStateChanged";var ShowRouteOnMapSpice=new Class({Name:"ShowRouteOnMapSpice",Extends:Spice,WAYPOINT_ICONS_SNC:{start:"images\\snc\\route_icon_start.bmp",end:"images\\snc\\route_icon_destination.bmp",stopover:"images\\snc\\route_icon_waypoint.bmp"},WAYPOINT_ICONS_TOUCH_PATH:"images/spices/waypoint/touch/waypoint_empty.svg",WAYPOINT_ICONS_WEB_PATH:"images/ui/web/startpoint.svg",_currentRoute:null,_pfwPath:"",_waypointSvg:"",_waypointIcons:[],initialize:function(aSpiceManager,aModels,aPfwPath){this._super(aSpiceManager);this._routingModel=aModels.routing;this._application=aModels.application;this._mapModel=aModels.map;this._pfwPath=aPfwPath;this._routingModel.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._onCurrentRouteChanged,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculated,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._onRouteCalculationError,this);var svgPath=this._pfwPath;if(nokia.aduno.utils.platform.maemo||nokia.maps.pfw.layout.touch){svgPath+=this.WAYPOINT_ICONS_TOUCH_PATH}else{svgPath+=this.WAYPOINT_ICONS_WEB_PATH}this._waypointSvg=this._routingModel.getSvgFromServer(svgPath);for(var i=0;i<8;i++){var letter=this._getIconLetter(i);this._waypointIcons[i]=this._waypointSvg.replace("[placeholder]",letter)}},_onRouteCalculated:function(aRouteEvent){var route=aRouteEvent.getData().route;var size=this._mapModel.getMapSize();if(this._application){this._routingModel.zoomToRoute(route,this._application.getVisibleAreaRestriction(size.width,size.height))}else{this._routingModel.zoomToRoute(route)}this._routingModel.showRoutePath(route)},_onRouteCalculationError:function(aRouteEvent){},_onCurrentRouteChanged:function(aRouteChangeEvent){var route=aRouteChangeEvent.getData().newRoute;if(route!=this._currentRoute&&this._currentRoute!==null){this._currentRoute.removeEventHandler(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,this._onWaypointsChanged,this);if(nokia.maps.pfw.layout.touch||nokia.maps.pfw.layout.snc){this._routingModel.removeWaypointsFromMap(this._currentRoute)}else{this._routingModel.removeWaypointsFromMap(this._currentRoute);this._routingModel.removeManeuverSpots(this._currentRoute)}this._routingModel.hideRoutePath(this._currentRoute)}if(route!==null){route.addEventHandler(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,this._onWaypointsChanged,this)}if(route!=this._currentRoute&&route&&route.hasDefinedWaypoints()){if(nokia.maps.pfw.layout.snc){this._routingModel.showRouteWaypoints(route,this._getRouteWaypointIcons(route))}else{this._routingModel.showWaypointsOnMap(route,this._getRouteWaypointIcons(route))}}this._currentRoute=route},_onWaypointsChanged:function(aEvent){if(nokia.maps.pfw.layout.snc){this._routingModel.showRouteWaypoints(this._currentRoute,this._getRouteWaypointIcons(this._currentRoute))}else{this._routingModel.showWaypointsOnMap(this._currentRoute,this._getRouteWaypointIcons(this._currentRoute))}},_getRouteWaypointIcons:function(aRoute){var waypointCount=aRoute.getWaypointCount();var numberOfNewIcons=waypointCount-this._waypointIcons.length;if(numberOfNewIcons>0){var firstNewWaypoint=waypointCount-numberOfNewIcons;for(var i=firstNewWaypoint;i<waypointCount;i++){var letter=this._getIconLetter(i);this._waypointIcons[i]=this._waypointSvg.replace("[placeholder]",letter)}}var routeWaypointIcons=this._waypointIcons.slice(0,waypointCount);return routeWaypointIcons},_getIconLetter:function(aIndex){var letter="";var i=65+aIndex;if(i>90){var remainder=String.fromCharCode(i%91+65);letter=String.fromCharCode(i/91+64)+""+remainder}else{letter=String.fromCharCode(i)}return letter}});var TitleBarSpice=new Class({Name:"TitleBarSpice",Extends:Spice,initialize:function(aSpiceManager,aMapModel,aZoomModel,aOptions){this._super(aSpiceManager);this._mapModel=aMapModel;this._zoomModel=aZoomModel;this._options=aOptions||{};this._onUpdateHandler=bind(this,function(aMapLocation){var center=this._mapModel.toGeo();var zoom=this._zoomModel.getStep();var text=this._computeTitleText(aMapLocation,center,zoom);this.onUpdateTitle(text);this._working=false});aMapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onMapMoved,this);aMapModel.addEventHandler(MapModel.EVENT_DRAG_DONE,this._onMapMoved,this);aMapModel.addEventHandler(MapModel.EVENT_MOVE_DONE,this._onMapMoved,this)},_createUi:function(){var container=new Container("TitleBar",TitleBarSpice.TitleBarSpiceTemplateLibrary);this._titleLabel=new Label();container.setChildAt(this._titleLabel,"titleLabel");return container},_onMapMoved:function(){if(!this._working){this._working=true;this._center=this._mapModel.toGeo();this._titleLabel.setText("\u00A0");this._mapModel.reverseGeoCode(this._center,this._onUpdateHandler)}},onUpdateTitle:function(aText){this._titleLabel.setText(aText)},onAttach:function(){if(this._options.id){var parent=document.getElementById(this._options.id);var child=this._spiceControl.getRootElement();if(parent&&child){parent.appendChild(child)}}var repl=this.getUi().getReplica();if(this._options.backgroundImage){repl.setStyle(TemplateReplica.ROOT_ID,"background-image","url("+this._options.backgroundImage+")")}if(this._options.backgroundColor){repl.setStyle(TemplateReplica.ROOT_ID,"background-color",this._options.backgroundColor)}if(this._options.borderColor){repl.setStyle(TemplateReplica.ROOT_ID,"border-bottom-color",this._options.borderColor)}if(this._options.textColor){repl.setStyle(TemplateReplica.ROOT_ID,"color",this._options.textColor)}this._onMapMoved()},_computeTitleText:function(aMapLocation,aCoordinates,aZoomStep){var street=aMapLocation?aMapLocation.ADDR_STREET_NAME:null;var houseNumber=aMapLocation?aMapLocation.ADDR_HOUSE_NUMBER:null;var city=aMapLocation?aMapLocation.ADDR_CITY_NAME:null;var country=aMapLocation?aMapLocation.ADDR_COUNTRY_NAME:null;var place=aMapLocation?aMapLocation.PLACE_NAME:null;var fragments=[];if(aMapLocation){if(aZoomStep>=14){country&&fragments.push(country)}else{if(aZoomStep>=10&&aZoomStep<=13){city&&fragments.push(city);country&&fragments.push(country)}else{if(aZoomStep>=0&&aZoomStep<=9){street&&fragments.push(street+(houseNumber?" "+houseNumber:""));city&&fragments.push(city);country&&fragments.push(country)}}}}return fragments.length>0?fragments.join(", "):"\u00A0"}});TitleBarSpice.TitleBarSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({TitleBar:'<div class="nmp_TitleBarSpice"><div id="titleLabel"></div></div>',Label:'<span id="label"></span>'});var InstallPluginSpice=new Class({Name:"InstallPluginSpice",Extends:Spice,_mouseBeenOverTheOverlay:false,_mouseOverlayTimer:null,_mouseOverlayTimeout:500,_mouseOverlayFxObj:null,_mouseOverlayFxAct:false,_browserIsSupported:true,initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._mapModel=aMapModel;this._mapModel.addEventHandler(MapModel.EVENT_SHOW_DOWNLOAD,this._onShowDownload,this);this._languageMappings={};this._languageNameMappings={};var i=0;for(var key in NewSettingsSpice.SUPPORTED_LANGUAGES){if(NewSettingsSpice.SUPPORTED_LANGUAGES.hasOwnProperty(key)){this._languageMappings[i]=key;this._languageNameMappings[key]=i;i++}}this._installPluginHandler=null;this._publicMethods=["setInstallPluginHandler"];this._checkIfBrowserIsSupported();this.pluginVersion=player.getPluginVersion();var downloadPluginPath="http://static.s2g.gate5.de/ovi_maps/";this.downloadUrl=null;if(nokia.aduno.utils.platform.windows){if(nokia.aduno.utils.browser.msie){this.downloadUrl=downloadPluginPath+"OviMaps_"+Player.DOWNLOAD_PLUGIN_VERSION+".cab";if(document.cookie.indexOf("installPluginInProgress")>-1){document.cookie="installPluginInProgress=1; expires="+((new Date((new Date()).getTime()+(-10000))).toGMTString())+";";this._addInstallObjectToDom()}}}else{if(nokia.aduno.utils.platform.mac){if(nokia.aduno.utils.browser.safari){this.downloadUrl=downloadPluginPath+"OviMaps_"+Player.DOWNLOAD_PLUGIN_VERSION+".dmg"}}}if(nokia.aduno.utils.browser.mozilla){this.downloadUrl=downloadPluginPath+"OviMaps_"+Player.DOWNLOAD_PLUGIN_VERSION+".xpi"}},_checkIfBrowserIsSupported:function(){this._browserIsSupported=true;if(navigator.userAgent.indexOf("Win64")>-1){this._browserIsSupported=false}if((navigator.userAgent.indexOf("Firefox")>-1)&&(navigator.userAgent.indexOf("Macintosh")>-1)){this._browserIsSupported=false}},_createUi:function(){this._installContainer=new nokia.aduno.medosui.Container("Settings",InstallPluginSpice.InstallPluginSpiceTemplate);if(this._browserIsSupported){this._menuContainer=new nokia.aduno.medosui.Container("MenuSupported",InstallPluginSpice.InstallPluginSpiceTemplate)}else{this._menuContainer=new nokia.aduno.medosui.Container("MenuUnsupported",InstallPluginSpice.InstallPluginSpiceTemplate)}this._settingsTopTip=new nokia.aduno.medosui.Container("TopTip",NewSettingsSpice.NewSettingsSpiceTemplate);this._menuContainer.setChildAt(this._settingsTopTip,"settingsTopTip");this._settingsButton=new nokia.aduno.medosui.Button("Button","__I18N_mapPlayer_15_buttonsArray_settings_buttonLabel__");this._settingsButton.addEventHandler("selected",this._showInstallMenu,this);this._installContainer.setChildAt(this._settingsButton,"settingsButton");var closeButton=new nokia.aduno.medosui.Button("CloseButton","Close");closeButton.addEventHandler("selected",function(aEvent){this._showInstallMenu()},this);this._menuContainer.setChildAt(closeButton,"closeButton");this._language=new SelectionList("DropDownSelectList",NewSettingsSpice.NewSettingsSpiceTemplate,null);for(var key in InstallPluginSpice.SUPPORTED_LANGUAGES){if(InstallPluginSpice.SUPPORTED_LANGUAGES.hasOwnProperty(key)){var tempLang=new Button("DropDownOption",InstallPluginSpice.SUPPORTED_LANGUAGES[key]);this._language.addChild(tempLang)}}this._mapModel.addEventHandler(MapModel.EVENT_UI_LANGUAGE,this._onModelUiLanguageChanged,this);this._language.getReplica().addEventHandler(TemplateReplica.ROOT_ID,"change",this,this._onLanguageSelected);this._menuContainer.setChildAt(this._language,"LanguageSelector");if(this._browserIsSupported){this._acceptButton=new nokia.aduno.medosui.CheckButton("AcceptButton","__I18N_mapPlayer_66_settings_donwloadPlugin_txt_termsAndConditions__",false,false);this._acceptButton.addEventHandler("selected",this._onAcceptSelected,this);this._menuContainer.setChildAt(this._acceptButton,"ConfirmCheckbox");this._installButton=new nokia.aduno.medosui.Button("ButtonLarge","__I18N_mapPlayer_12_settings_downloadPlugin_buttonLabel__");this._installButton.addEventHandler("selected",this._onInstallSelected,this);this._installButton.getReplica().addCssClass("nm_Disabled");this._menuContainer.setChildAt(this._installButton,"InstallButton")}else{}this._dialog=new nokia.aduno.medosui.Container("Dialog",InstallPluginSpice.InstallPluginSpiceTemplate);this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._dialog);if(!nokia.aduno.utils.browser.msie){this._dialog.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onMouseEnteredOverlay);this._dialog.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onMouseExitedOverlay)}this._installContainer.setChildAt(this._dialog,"settingsDialog");this._dialog.setChildAt(this._menuContainer,"settingsmenu");this._dialog.hide();return this._installContainer},_showInstallMenu:function(aEvent){if(!this._dialog.isVisible()){this._spiceManager.handleModalSpiceOpened(this);this._settingsButton.getReplica().addCssClass("nmm_Selected");var size=this._mapModel.getMapSize();var root=this.getUi().getRootElement();if(this._spiceManager&&this._spiceManager._localizer){this._spiceManager._localizer.traverse(root)}if(this._mouseOverlayFxAct){this._mouseOverlayFxObj.stop();delete this._mouseOverlayFxObj;this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._dialog);this._mouseOverlayFxAct=false}this._dialog.getReplica().setStyle(TemplateReplica.ROOT_ID,"opacity","1");this._dialog.show();var dialogPos=nokia.aduno.dom.Dimensions.getPosition(this._dialog.getRootElement(),this._spiceControl.getRootElement().parentNode.parentNode);var buttonPos=nokia.aduno.dom.Dimensions.getPosition(this._settingsButton.getRootElement(),this._spiceControl.getRootElement().parentNode.parentNode);var buttonSize=nokia.aduno.dom.Dimensions.getSize(this._settingsButton.getRootElement());var tipSize=nokia.aduno.dom.Dimensions.getSize(this._settingsTopTip.getRootElement());var tipLeft=Math.round(buttonPos.x+(buttonSize.x/2)-(tipSize.x/2)-dialogPos.x);this._settingsTopTip.getReplica().setStyle(TemplateReplica.ROOT_ID,"left",tipLeft+"px")}else{this._settingsButton.getReplica().removeCssClass("nmm_Selected");this._dialog.hide()}},_onShowDownload:function(aEvent){if(!this._dialog.isVisible()){this._showInstallMenu()}},_onLanguageSelected:function(aDomEvent){var index=aDomEvent.get("target").selectedIndex;var type=this._languageMappings[index]||"en-GB";if(this._mapModel.getUiLanguage()!==this._languageMappings[index]){this._mapModel.setUiLanguage(type)}},_onModelUiLanguageChanged:function(aEvent){var data=aEvent.getData();var type=this._mapModel.getUiLanguage();if(this._language.getSelectionIndex()!==this._languageNameMappings[data]){this._language.setSelectionIndex(this._languageNameMappings[type]||0)}},_onAcceptSelected:function(aEvent){if(this._acceptButton.getState()){this._installButton.getReplica().removeCssClass("nm_Disabled")}else{this._installButton.getReplica().addCssClass("nm_Disabled")}},_onInstallSelected:function(aEvent){if(!this._acceptButton.getState()){return}else{if(nokia.aduno.utils.browser.msie){if(document.cookie.indexOf("installPluginInProgress")==-1){document.cookie="installPluginInProgress=1"}this._addInstallObjectToDom()}else{location.href=this.downloadUrl}if(this._installPluginHandler){this._installPluginHandler()}}},setInstallPluginHandler:function(aHandler){this._installPluginHandler=aHandler},_onMouseEnteredOverlay:function(aMouseOverEvent){this._mouseBeenOverTheOverlay=true;if(this._mouseOverlayTimer){clearTimeout(this._mouseOverlayTimer)}this._mouseOverlayTimer=null},_onMouseExitedOverlay:function(aMouseOutEvent){if(this._mouseBeenOverTheOverlay&&!this._mouseOverlayFxAct){var x=aMouseOutEvent.get("pageX");var y=aMouseOutEvent.get("pageY");var rect=nokia.aduno.dom.Dimensions.getCoordinates(this._dialog.getRootElement());if(x<rect.left||x>=rect.left+rect.width||y<rect.top||y>=rect.top+rect.height){var self=this;this._mouseOverlayTimer=setTimeout(function(){self._hideMenuDialog()},this._mouseOverlayTimeout)}}},_hideMenuDialog:function(){if(!this._mouseOverlayFxAct){this._mouseOverlayFxAct=true;this._mouseBeenOverTheOverlay=false;this._settingsButton.getReplica().removeCssClass("nmm_Selected");if(nokia.aduno.utils.browser.msie){this._mouseOverlayFxAct=false;this._menuContainer.blur();this._dialog.hide()}else{this._mouseOverlayFxObj.addEventHandler("ended",function(){this._mouseOverlayFxAct=false;this._menuContainer.blur();this._dialog.hide()},this);this._mouseOverlayFxObj.effect({duration:300,styles:{opacity:[1,0]}}).start()}}},_addInstallObjectToDom:function(){if(!document.getElementById("pluginObject")){var installObject='<object id="pluginObject" style="width: 1px; height: 1px;" onreadystatechange="nokia.maps.pfw.spices.InstallPluginSpice.pluginInstallCallback();" CLASSID="clsid:4FEE6316-7B6F-4A6C-BD4E-4157C59A9E9D" CODEBASE='+this.downloadUrl+"#Version=-1,-1,-1,-1 ></object>";var myDiv=document.createElement("div");document.getElementsByTagName("body")[0].appendChild(myDiv);myDiv.innerHTML=installObject}},onOtherSpiceReceivedFocus:function(){this._dialog.hide()},translateUi:function(aDefaultTranslationVisitor,aLanguage){this._super(aDefaultTranslationVisitor,aLanguage);var mapUiLanguage=this._mapModel.getUiLanguage();var codeCorrect=false;if(mapUiLanguage!==undefined&&mapUiLanguage!==null){var code=mapUiLanguage.split("-");if(code.length==2){mapUiLanguage=code[0].toLowerCase()+"-"+code[1].toUpperCase();codeCorrect=true}}if(!codeCorrect){return}var count=this._language.getChildCount();var langText=NewSettingsSpice.SUPPORTED_LANGUAGES[mapUiLanguage];for(var i=0;i<count;i++){var button=this._language.getChildAt(i);var btText=button.getText();if(button.getText()==langText){button.getReplica().setAttribute(TemplateReplica.ROOT_ID,"selected","selected");break}}}});InstallPluginSpice.pluginInstallCallback=function(){var newPluginVersion=player.getPluginVersion();if(newPluginVersion&&InstallPluginSpice.pluginVersion!=newPluginVersion){if(document.cookie.indexOf("installPluginInProgress")>-1){document.cookie="installPluginInProgress=1; expires="+((new Date((new Date()).getTime()+(-10000))).toGMTString())+";"}window.location.reload(true)}};InstallPluginSpice.InstallPluginSpiceTemplate=new nokia.aduno.dom.TemplateLibrary({Settings:'<div class="nmp_InstallPluginSpice" unselectable="on"><div id="settingsOverlay"></div><div id="settingsButton"></div><div id="settingsDialog"></div></div>',Dialog:'<div class="nmp_SettingsDialog" unselectable="on"><div id="settingsmenu"></div></div>',MenuSupported:'<div class="nmp_SettingsMenu" unselectable="on"><div id="settingsTopTip" unselectable="on"></div><div class="nmp_SettingsContainer" unselectable="on"><div class="nmp_SettingsHeadline1" unselectable="on">__I18N_mapPlayer_1_settings_header_txt__</div><div class="nmp_Settings2Cols" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><div class="nmp_ColorDayTeaser" unselectable="on"></div><div class="nmp_ColorNightTeaser" unselectable="on"></div></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_2_settings_nightMode_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_3_settings_nightMode_txt_body__</div></div></div><div class="nmp_Settings2Cols" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><div class="nmp_LandmarksOffTeaser" unselectable="on"></div><div class="nmp_LandmarksOnTeaser" unselectable="on"></div></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_4_settings_landmarks_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_5_settings_landmarks_txt_body__</div></div></div><div class="nmp_Settings2Cols" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><div id="LanguageSelector"></div></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_6_settings_mapLanguage_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_7_settings_mapLanguage_txt_body__</div></div></div><div class="nmp_SettingsFull" unselectable="on"><p class="nmp_InstallTeaser" unselectable="on">__I18N_mapPlayer_64_settings_donwloadPlugin_txt_teaser__</p><div id="checkButton" class="nmp_SettingsConfirm" unselectable="on">__I18N_mapPlayer_65_settings_donwloadPlugin_txt_termsAndConditions__ <a id="checkButtonText" href="__I18N_mapPlayer_67_settings_donwloadPlugin_link_termsAndConditions__" unselectable="on" target="blank">__I18N_mapPlayer_66_settings_donwloadPlugin_txt_termsAndConditions__</a><div id="ConfirmCheckbox"></div></div></div><div class="nmp_Settings2Cols nmp_Settings2ColsNoColor" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><p unselectable="on">\u00BB <a href="__I18N_mapPlayer_9_about_Ovi_link__" unselectable="on" target="blank">__I18N_mapPlayer_8_about_Ovi_txt__</a><br />\u00BB <a href="__I18N_mapPlayer_11_about_mobile_link__" unselectable="on" target="blank">__I18N_mapPlayer_10_about_mobile_txt__</a></p></div><div class="nmp_Settings2ColsRight" unselectable="on"><div id="InstallButton"></div></div></div><div class="nmp_PosCloseButton" unselectable="on"><div id="closeButton" class="nmp_MenuCloseButton"></div></div></div><div class="nmp_SettingsBottomEdge" unselectable="on"></div></div>',MenuUnsupported:'<div class="nmp_SettingsMenu" unselectable="on"><div id="settingsTopTip" unselectable="on"></div><div class="nmp_SettingsContainer" unselectable="on"><div class="nmp_SettingsHeadline1" unselectable="on">__I18N_mapPlayer_1_settings_header_txt__</div><div class="nmp_Settings2Cols" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><div class="nmp_ColorDayTeaser" unselectable="on"></div><div class="nmp_ColorNightTeaser" unselectable="on"></div></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_2_settings_nightMode_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_3_settings_nightMode_txt_body__</div></div></div><div class="nmp_Settings2Cols" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><div class="nmp_LandmarksOffTeaser" unselectable="on"></div><div class="nmp_LandmarksOnTeaser" unselectable="on"></div></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_4_settings_landmarks_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_5_settings_landmarks_txt_body__</div></div></div><div class="nmp_Settings2Cols" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><div id="LanguageSelector"></div></div><div class="nmp_Settings2ColsRight" unselectable="on"><div class="nmp_SettingsHeadline2" unselectable="on">__I18N_mapPlayer_6_settings_mapLanguage_txt_title__</div><div class="nmp_SettingsText" unselectable="on">__I18N_mapPlayer_7_settings_mapLanguage_txt_body__</div></div></div><div class="nmp_SettingsFull" unselectable="on"><div id="checkButton" class="nmp_SettingsConfirm" unselectable="on"><p class="nmp_notSupportedExplanation" unselectable="on">__I18N_mapPlayer_73_settings_donwloadPlugin_txt_notAvailable__ <br/><a id="checkButtonText" href="__I18N_mapPlayer_75_settings_donwloadPlugin_link_checkCompatibility__" unselectable="on" target="blank">__I18N_mapPlayer_74_settings_donwloadPlugin_txt_checkCompatibility__</a></p></div></div><div class="nmp_Settings2Cols nmp_Settings2ColsNoColor" unselectable="on"><div class="nmp_Settings2ColsLeft" unselectable="on"><p unselectable="on">\u00BB <a href="__I18N_mapPlayer_9_about_Ovi_link__" unselectable="on" target="blank">__I18N_mapPlayer_8_about_Ovi_txt__</a><br />\u00BB <a href="__I18N_mapPlayer_11_about_mobile_link__" unselectable="on" target="blank">__I18N_mapPlayer_10_about_mobile_txt__</a></p></div><div class="nmp_Settings2ColsRight" unselectable="on"><div id="InstallButton"></div></div></div><div class="nmp_PosCloseButton" unselectable="on"><div id="closeButton" class="nmp_MenuCloseButton"></div></div></div><div class="nmp_SettingsBottomEdge" unselectable="on"></div></div>',CloseButton:'<span id="button" class="nmp_CloseButton" unselectable="on"></span>',Button:'<div class="nmm_Butt" unselectable="on"><a id="button" unselectable="on"></a></div>',ButtonLarge:'<div class="nmm_ButtLarge" unselectable="on"><div class="nmp_Dummy" id="button" unselectable="on"></div><span id="pluginInstallObject" class="nm_Hidden" unselectable="on"></span></div>',DropDownSelectList:"<select></select>",DropDownOption:'<option id="button"></option>',AcceptButton:'<input type="checkbox" id="checkButtonButton" class="nmp_SettingsAcceptButton"></input>'});InstallPluginSpice.SUPPORTED_LANGUAGES={"en-GB":"English (British)","fr-FR":"Française","de-DE":"Deutsch","es-ES":"Español","it-IT":"Italiano"};var CenterCursorSpice=new Class({Name:"CenterCursorSpice",Extends:Spice,_mapModel:null,_container:null,_2DMode:"nmp_CenterCursorSpice2D",_3DMode:"nmp_CenterCursorSpice3D",_iconSize:{x:50,y:50},initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._mapModel=aMapModel;aMapModel.addEventHandler(MapModel.EVENT_TILT,this._onModelTiltChanged,this);this._spiceManager.addEventHandler(SpiceManager.EVENT_SIZE_CHANGED,this._onSizeChanged,this)},_createUi:function(){var container=new Container("CenterCursor",CenterCursorSpice.TemplateLibrary);container.getReplica().addCssClass(this._mapModel.getMode3d()?this._3DMode:this._2DMode);container.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_CLICK,this,this._onClickHandle);this._container=container;this._spiceManager.addDraggingDelegationControl(this._container);return container},_onModelTiltChanged:function(aEvent){if(this._mapModel.getMode3d()){this._container.getReplica().removeCssClass(this._2DMode);this._container.getReplica().addCssClass(this._3DMode)}else{this._container.getReplica().removeCssClass(this._3DMode);this._container.getReplica().addCssClass(this._2DMode)}this._setCursorPosition()},_onSizeChanged:function(aEvent){this._setCursorPosition()},_setCursorPosition:function(){var mapCenterGeo=this._mapModel.getMapCenterPosition();var mapCenterPx=this._mapModel.geoToPixel(mapCenterGeo);this._spiceControl.getReplica().setStyle(TemplateReplica.ROOT_ID,"left",(mapCenterPx.x-this._iconSize.x/2)+"px");this._spiceControl.getReplica().setStyle(TemplateReplica.ROOT_ID,"top",(mapCenterPx.y-this._iconSize.y/2)+"px")},onAttach:function(){var mapCenterPx=this._mapModel.geoToPixel(this._mapModel.getMapCenterPosition());if(mapCenterPx.x<this._iconSize.x/2||mapCenterPx.y<this._iconSize.y/2){var self=this;window.setTimeout(nokia.aduno.utils.bind(self,self.onAttach),300);return}this._setCursorPosition()},_onClickHandle:function(aEvent){var spice=this._spiceManager.getSpice("MouseSpice");if(spice){var data={};data.x=aEvent.get("pageX");data.y=aEvent.get("pageY");spice.handleOnClick(new nokia.aduno.utils.Event("selected",data))}}});CenterCursorSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({CenterCursor:"<div></div>"});var LayerListSpice=new Class({Name:"LayerListSpice",Extends:Spice,_mouseBeenOverTheOverlay:false,_mouseOverlayTimer:null,_mouseOverlayTimeout:500,_mouseOverlayFxObj:null,_mouseOverlayFxAct:false,_layers:[],initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._mapModel=aMapModel},_createUi:function(){this._settingsContainer=new nokia.aduno.medosui.Container("Settings",LayerListSpice.LayerListSpiceTemplate);this._menuContainer=new nokia.aduno.medosui.Container("Menu",LayerListSpice.LayerListSpiceTemplate);this._layerlistTopTip=new nokia.aduno.medosui.Container("TopTip",LayerListSpice.LayerListSpiceTemplate);this._menuContainer.setChildAt(this._layerlistTopTip,"layerListTopTip");this._settingsButton=new nokia.aduno.medosui.Button("LayerListButton","");this._settingsButton.addEventHandler("selected",this._showSettingsMenu,this);this._settingsContainer.setChildAt(this._settingsButton,"settingsbutton");var closeButton=new nokia.aduno.medosui.Button("CloseButton","__I18N_mapPlayer_61_commons_close_toolTip__");closeButton.addEventHandler("selected",function(aEvent){this._showSettingsMenu()},this);this._menuContainer.setChildAt(closeButton,"closeButton");this._dialog=new nokia.aduno.medosui.Container("Dialog");this._settingsContainer.setChildAt(this._dialog,"settingsDialog");this._dialog.setChildAt(this._menuContainer,"settingsmenu");this._dialog.getReplica().addEventHandler(XNode.DOM_MOUSE_OVER,this,this._onMouseEnteredOverlay);this._dialog.getReplica().addEventHandler(XNode.DOM_MOUSE_OUT,this,this._onMouseExitedOverlay);this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._dialog);this._dialog.hide();this._headlineLabel=new nokia.aduno.medosui.Label("Headline","Points of Interest");this._menuContainer.setChildAt(this._headlineLabel,"headline");var poiSettingsContainer=new nokia.aduno.medosui.Container("PoiSettings",LayerListSpice.LayerListSpiceTemplate);this._menuContainer.setChildAt(poiSettingsContainer,"poisettings");poiSettingsContainer._addCssClass("nmp_LayerSettings");this._list=new nokia.aduno.medosui.List("List",LayerListSpice.LayerListSpiceTemplate);this._list._addCssClass("nmp_LayerList");this._buildList();poiSettingsContainer.setChildAt(this._list,"poilist");this._mapModel.addEventHandler(MapModel.EVENT_LAYERS_CHANGED,this._onLayerChanged,this);this._menuContainer.handleKey=function(aKeyEvent){return true};this.setListTitle(LayerListSpice.DEFAULT_TITLE);return this._settingsContainer},_showSettingsMenu:function(aEvent){if(!this._dialog.isVisible()||this._mouseOverlayFxAct){this._showMenuDialog()}else{this._hideMenuDialog()}},_showMenuDialog:function(){this._settingsButton.getReplica().addCssClass("nmm_Selected");this._spiceManager.handleModalSpiceOpened(this);if(this._mouseOverlayFxAct){this._mouseOverlayFxObj.stop();delete this._mouseOverlayFxObj;this._mouseOverlayFxObj=new nokia.aduno.medosui.Fx(this._dialog);this._mouseOverlayFxAct=false}this._dialog.getReplica().setStyle(TemplateReplica.ROOT_ID,"opacity","1");this._dialog.show();this._menuContainer.focus();var dialogPos=nokia.aduno.dom.Dimensions.getPosition(this._dialog.getRootElement(),this._spiceControl.getRootElement().parentNode.parentNode);var buttonPos=nokia.aduno.dom.Dimensions.getPosition(this._settingsButton.getRootElement(),this._spiceControl.getRootElement().parentNode.parentNode);var buttonSize=nokia.aduno.dom.Dimensions.getSize(this._settingsButton.getRootElement());var tipSize=nokia.aduno.dom.Dimensions.getSize(this._layerlistTopTip.getRootElement());var tipLeft=Math.round(buttonPos.x+(buttonSize.x/2)-(tipSize.x/2)-dialogPos.x);this._layerlistTopTip.getReplica().setStyle(TemplateReplica.ROOT_ID,"left",tipLeft+"px")},_hideMenuDialog:function(){if(!this._mouseOverlayFxAct){this._mouseOverlayFxAct=true;this._mouseBeenOverTheOverlay=false;this._settingsButton.getReplica().removeCssClass("nmm_Selected");if(nokia.aduno.utils.browser.msie){this._mouseOverlayFxAct=false;this._menuContainer.blur();this._dialog.hide()}else{this._mouseOverlayFxObj.addEventHandler("ended",function(){this._mouseOverlayFxAct=false;this._menuContainer.blur();this._dialog.hide()},this);this._mouseOverlayFxObj.effect({duration:300,styles:{opacity:[1,0]}}).start()}}},_onMouseEnteredOverlay:function(aMouseOverEvent){this._mouseBeenOverTheOverlay=true;if(this._mouseOverlayTimer){window.clearTimeout(this._mouseOverlayTimer);this._mouseOverlayTimer=null}},_onMouseExitedOverlay:function(aMouseOutEvent){if(this._mouseBeenOverTheOverlay&&!this._mouseOverlayFxAct){var x=aMouseOutEvent.get("pageX");var y=aMouseOutEvent.get("pageY");var rect=nokia.aduno.dom.Dimensions.getCoordinates(this._dialog.getRootElement());if(x<rect.left||x>=rect.left+rect.width||y<rect.top||y>=rect.top+rect.height){var self=this;this._mouseOverlayTimer=setTimeout(function(){self._hideMenuDialog()},this._mouseOverlayTimeout)}}},_onLayerChanged:function(aEvent){var data=aEvent.getData();var layer=data.layer;if(layer.isLayerEntryEnabled()){this._addListEntry(layer)}else{this._removeListEntry(layer)}this._buildList()},_onLayerClicked:function(aEvent){var visible=aEvent.source.getState();var title=aEvent.source.getValue();var layer=null;for(var i=0,c=this._layers.length;i<c;i++){if(this._layers[i].getName()===title){layer=this._layers[i];break}}if(layer){if(visible){layer.show()}else{layer.hide()}this._checkShownAllButton()}aEvent.source.setState(layer&&visible)},_onShowAllButtonClicked:function(aEvent){var visible=aEvent.source.getState();for(var i=0,l=this._layers.length;i<l;i++){if(this._layers[i]){if(visible){this._layers[i].show()}else{this._layers[i].hide()}}}for(var j=0,c=this._list.getChildCount();j<c;j++){var child=this._list.getChildAt(j);if(!child.getReplica().getAttribute("checkButtonButton","disabled")){child.setState(visible)}}},_addElementToList:function(aName,aLabel,aState,aHandler,aIconPath){var control=new nokia.aduno.medosui.CheckButton(null,aLabel,aName,aState);if(aIconPath){control.getReplica().setInnerHtml("image",'<img src="'+aIconPath+'" />')}if(typeof aHandler=="function"){control.addEventHandler("selected",aHandler,this)}this._list.addChild(control);if(nokia.aduno.utils.browser.msie){control.setState(aState)}return control},_buildList:function(){if(!this._list){return}this._layers.sort(function(a,b){return a.getEntryName()>=b.getEntryName()});var allLayersVisible=true;var numActiveLayers=0;var firstColorIndex=1;this._list.removeAllChildren();if(!this._showAllButton){this._showAllButton=this._addElementToList("Show All","Show All",false,this._onShowAllButtonClicked);this._showAllButton._addCssClass("nmp_LayerEntryAll")}if(this._showAllButton.isVisible()){this._list.addChild(this._showAllButton);firstColorIndex=0}var layer=null;for(var i=0,c=this._layers.length;i<c;i++){layer=this._layers[i];var title=layer.getEntryName();var visible=layer.isVisible();var iconUri=layer.getIcon();var category=layer.getCategory();if(!iconUri){var image=MapMarker.PoiImages[category]||null;iconUri=image?"../../pfw/images/spices/poiCategories/"+image+".png":null}allLayersVisible&=visible;numActiveLayers++;var entry=this._addElementToList(layer.getName(),title,visible,this._onLayerClicked,iconUri);if(!layer){entry.disable()}entry._addCssClass((i+firstColorIndex)%2?"nmp_LayerEntryLite":"nmp_LayerEntryDark")}if(numActiveLayers===0){this._showAllButton.disable()}else{this._showAllButton.enable()}this._showAllButton.setState(numActiveLayers>0&&allLayersVisible)},_checkShownAllButton:function(){var allLayersVisible=true;for(var i=0,c=this._layers.length;i<c;i++){allLayersVisible&=this._layers[i].isVisible();if(!allLayersVisible){break}}if(this._showAllButton){this._showAllButton.setState(allLayersVisible)}},onOtherSpiceReceivedFocus:function(){this._hideMenuDialog()},setListTitle:function(aText){if(this._headlineLabel){this._headlineLabel.setText(aText);return true}return false},getListTitle:function(aText){return this._headlineLabel?this._headlineLabel.getText():null},setShowAllVisible:function(aVisible){if(aVisible){this._showAllButton.show()}else{this._showAllButton.hide()}this._buildList()},getShowAllVisible:function(){return this._showAllButton?this._showAllButton.isVisible():false},setShowAllTitle:function(aText){if(this._showAllButton){this._showAllButton.setText(aText);return true}return false},getShowAllTitle:function(){return this._showAllButton?this._showAllButton.getText():null},_addListEntry:function(aLayer){for(var i=0,c=this._layers.length;i<c;i++){if(this._layers[i].getName()===aLayer.getName()){return false}}this._layers.push(aLayer);return true},_removeListEntry:function(aLayer){var name=aLayer.getName();for(var i=0,c=this._layers.length;i<c;i++){if(this._layers[i].getName()==name){this._layers.splice(i,1);return true}}return false}});LayerListSpice.DEFAULT_TITLE="Custom Layers";LayerListSpice.LayerListSpiceTemplate=new nokia.aduno.dom.TemplateLibrary({Settings:'<div class="nmp_LayerListSpice" unselectable="on"><div id="settingsbutton"></div><div id="settingsDialog"></div></div>',Dialog:'<div class="nmp_LayerListDialog" unselectable="on"><div id="settingsmenu"></div></div>',Menu:'<div class="nmp_LayerListMenu" unselectable="on"><div id="layerListTopTip"></div><div class="nmp_LayerListContainer" unselectable="on"><div id="headline" class="nmp_LayerListHeadline">Layers</div><div class="nmp_PosCloseButton" unselectable="on"><div id="closeButton" class="nmp_MenuCloseButton"></div></div><div id="poisettings"></div></div><div class="nmp_LayerListBottomEdge" unselectable="on"></div></div>',Headline:'<div id="label" class="nmp_LayerListHeadline" unselectable="on">Points of Interest</div>',CloseButton:'<span id="button" class="nmp_CloseButton" unselectable="on"></span>',SettingsLabel:'<div class="nmp_LayerListLabel" unselectable="on"><span id="label" unselectable="on"></span></div>',RadioLine:'<div unselectable="on"><div id="label" unselectable="on"></div><div id="radiogroup" unselectable="on"></div></div>',Line:'<div class="nmp_Line" unselectable="on"></div>',PoiSettings:'<div unselectable="on"><div id="poilist" unselectable="on"></div></div>',PoiSettingsLine:"<div></div>",PoiMenuEntry:'<div id="zoomcontainer" class="nmp_zoom" unselectable="on"></div>',Checkbox:"<div></div>",CheckButton:'<div id="checkButton" unselectable="on"><input type="checkbox" id="checkButtonButton" class="nmp_LayerListCheckbox" unselectable="on"></input><span id="image" unselectable="on"></span><span id="checkButtonText" unselectable="on"></span></div>',Button:'<div class="nmm_Butt" unselectable="on"><a id="button" unselectable="on"></a></div>',LayerListButton:'<div class="nmp_LayerListButton" unselectable="on"><span id="button" unselectable="on"></span></div>',TopTip:'<div class="nmp_LayerListTopTip" unselectable="on"></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var WhereSearchSpice=new Class({Name:"WhereSearchSpice",Extends:Spice,initialize:function(aSpiceManager,aMapModel,aSearchModel,aPage){if(!aSearchModel){throw new nokia.aduno.utils.ArgumentError("aSearchModel is required")}if(!aSearchModel.isReady()){throw new ArgumentError("The SearchModel is not ready")}this._super(aSpiceManager);this._model=aMapModel;this._searchModel=aSearchModel;this._page=aPage;this._spiceManager=aSpiceManager;this._dfw=null},_createUi:function(){var dfwContainer=new Container("DfwContainer",WhereSearchSpice.WhereSearchSpiceTemplateLibrary);this._dfw=new nokia.maps.dfw.ui.DiscoveryFrameworkUI(this._searchModel.getDiscoveryFrameworkCore(),this._page);this._dfw.addEventHandler("ResultSelected",this._onResultSelected,this);this._dfw.addEventHandler("ResultsReceived",this._onResultsReceived,this);this._dfw.addEventHandler("ResultsCleared",this._onResultsCleared,this);this._dfw.addEventHandler("SuggestionSelected",this._onSuggestionSelected,this);this._dfwSearchBox=this._dfw.getSearchBox();this._dfwResultList=this._dfw.getResultList();this._dfwSuggestionList=this._dfw.getSuggestionList();this._dfwPagingFrame=this._dfw.getPagingFrame();this._dfwErrorPresenter=this._dfw.getErrorPresenter();this._dfwProgressIndicator=this._dfw.getProgressIndicator();dfwContainer.setChildAt(this._dfwSearchBox,"dfwSearchBox");dfwContainer.setChildAt(this._dfwSuggestionList,"dfwSuggestionList");dfwContainer.setChildAt(this._dfwProgressIndicator,"dfwProgressIndicator");this._resultWindow=new ResultWindow();this._resultWindow.hide();this._resultWindow.setChildAt(this._dfwErrorPresenter,"ErrorPresenter",true,true);this._resultWindow.setChildAt(this._dfwResultList,"ResultList",true,true);this._resultWindow.setChildAt(this._dfwPagingFrame,"PagingFrame",true,true);this._resultWindow.addEventHandler("closed",this._cleanupSearchResults,this);dfwContainer.setChildAt(this._resultWindow,"resultWindow");return dfwContainer},_onResultSelected:function(aEvent){this._moveToSearchResult(aEvent.getData(),this._searchResultObjects[aEvent.getData().index])},_onResultMapObjectSelected:function(aEvent){this._moveToSearchResult(aEvent.source.searchResult,aEvent.source);aEvent.preventDefault()},_moveToSearchResult:function(aResult,aMapObject){if(this._selectedSearchResult){}this._selectedSearchResult=aMapObject;this._dfwResultList.getSelected().setSelectionIndex((aResult.index-1)%this._searchModel.getOption("resultsPerPage"));this._model.selectMapObject(aMapObject);this._model.moveTo(aResult)},_onResultsReceived:function(aEvent){var data=aEvent.getData();this._cleanupSearchResults();for(var i=data.length-1;i>=0;i--){var obj=data[i];var mapMarker=MapMarker.parse({longitude:obj.longitude,latitude:obj.latitude,infoIcon:obj.iconUrl,infoTitle:obj.row1,infoDescription:obj.row2,handler:this._onResultMapObjectSelected,bind:this});mapMarker.searchResult=obj;mapMarker.setClickable(true);this._model.addToLayer(mapMarker,this.className+"Layer");this._searchResultObjects[obj.index]=mapMarker}if(data.length>0){this._moveToSearchResult(data[0],this._searchResultObjects[data[0].index]);this._resultWindow.setTitle("Search results");this._dfwResultList.getSelected().setSelectionIndex(0)}else{this._resultWindow.setTitle("An Error occurred")}if(data.length!==1){this._resultWindow.show()}},_onResultsCleared:function(aEvent){this._cleanupSearchResults()},_cleanupSearchResults:function(){for(var i in this._searchResultObjects){if(this._searchResultObjects.hasOwnProperty(i)){this._model.removeFromLayer(this._searchResultObjects[i]);delete this._searchResultObjects[i]}}this._searchResultObjects=[];this._selectedSearchResult=null;this._resultWindow.hide()},_onSuggestionSelected:function(event){var suggestionItem=event.getData();if(suggestionItem.suggestionType==="direct"){nokia.aduno.utils.info("Direct suggestion, result item:");nokia.aduno.utils.info(suggestionItem.resultItem)}else{if(suggestionItem.suggestionType==="term"){nokia.aduno.utils.info("Term suggestion, no result item")}}}});WhereSearchSpice.WhereSearchSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({SearchResultList:'<ul class="nmm_SearchResults"></ul>',SearchResultElement:'<li class="nmm_SearchResultEntry"><a id="button" href=""></a></li>',ResultWindow:'<div class="nmm_searchWindow" id="ResultWindow"><div id="DragBar"></div><div class="nmm_rwContent"><div class="nmm_rwTitle"><h1 id="title"></h1></div><div id="ErrorPresenter"></div><div id="ResultList" class="nmm_rlContainer"></div><div id="PagingFrame"></div></div><div class="nmm_rwFooter"></div></div>',ResultWindowDragbar:'<div class="nmm_rwDragHandle" id="CloseButton"></div>',ResultWindowCloseButton:'<a class="nmm_rwCloseButton" href="" id="button"></a>',DropDown:'<div id="dropDown" class="nmm_Choo"><div id="dropDownButton"></div><div id="dropDownList"></div></div>',DropDownButton:'<div id="checkButton" class="nmm_DDown"><div id="checkButtonButton"><span id="checkButtonText"></span></div></div>',DropDownList:"<ul></ul>",DropDownListElement:'<li><a id="button"></a></li>',Collapsable:"<div></div>",DfwContainer:'<div class="nmps_DfwControls"><div class="nmm_searchBox"><div id="dfwSearchBox"></div><div id="dfwSuggestionList"></div></div><div id="dfwProgressIndicator"></div><div id="resultWindow"></div></div>'},(nokia.maps.dfw)?nokia.maps.dfw.ui.DFWTemplateLibrary:nokia.aduno.medosui.DefaultTemplateLibrary);var TrafficLegendSpice=new Class({Name:"TrafficLegendSpice",Extends:Spice,_trafficInfoVisible:false,initialize:function(aSpiceManager,aMapModel){this._super(aSpiceManager);this._model=aMapModel;this._model.addEventHandler(MapModel.EVENT_MAPTYPE,this._onMapTypeChange,this);this._model.addEventHandler(MapModel.EVENT_TRAFFIC_INFO,this._onModelTrafficInfoChanged,this)},_createUi:function(){var container=new Container("Legend",TrafficLegendSpice.TLSLibrary);var binder=this;container.accept=function(aVisitor){binder._translations=aVisitor._translator._translationTable;container.getReplica().setInnerHtml("labelHeavy",binder._translations["nokia.maps.pfw.spices.trafficspice.legend.heavy"]);container.getReplica().setInnerHtml("labelLight",binder._translations["nokia.maps.pfw.spices.trafficspice.legend.light"])};container.hide();return container},show:function(){this._spiceControl.show()},hide:function(){this._spiceControl.hide()},_onMapTypeChange:function(aEvent){var mapType=aEvent.getData();if(mapType==="satellite"){this._spiceControl.getReplica().addCssClass("trafficLegendContainer","nmp_TrafficSpice_SatelliteView")}else{this._spiceControl.getReplica().removeCssClass("trafficLegendContainer","nmp_TrafficSpice_SatelliteView")}},_onModelTrafficInfoChanged:function(aEvent){var visible=aEvent.getData()=="visible";if(visible){this.show()}else{this.hide()}}});TrafficLegendSpice.TLSLibrary=new nokia.aduno.dom.TemplateLibrary({Legend:'<div id="trafficLegendContainer" class="nmp_TrafficSpice_Legend"><div id="labelHeavy" class="nmp_TrafficSpice_Heavy"></div><div id="labelLight" class="nmp_TrafficSpice_Light"></div></div>'});var TouchWaypointSpice=new Class({Name:"TouchWaypointSpice",Extends:Spice,_startButton:null,_waypointsList:null,_reverseGeoCoding:null,_routing:null,_position:null,_application:null,_search:null,_maneuversOn:false,_waypointItems:[],_currentEditingWaypointIndex:null,initialize:function(aSpiceManager,aTranslator,aModels,aPage,aPfwPath){this._super(aSpiceManager,aTranslator);this._routing=aModels.routing;this._map=aModels.map;this._reverseGeoCoding=aModels.reverseGeoCoding;this._application=aModels.application;this._position=aModels.position;this._search=aModels.search;this._page=aPage;this._pfwPath=aPfwPath;this._reverseGeoCoding.addEventHandler(ReverseGeoCodingModel.EVENT_REVERSE_GEOCODE_DONE,this._onReverseGeoCodeDone,this);this._routing.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._onCurrentRouteChanged,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculated,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_CANCELLED,this._onRouteCalculationCancelled,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._onRouteCalculationCancelled,this);this._position.addEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);this._map.addEventHandler(MapModel.EVENT_POSITION,this._onMapMove,this);this._map.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onMapMove,this);this._map.addEventHandler(MapModel.EVENT_ANIMATION_DONE,this._onMapMove,this)},_createUi:function(){var templateLibrary=TouchWaypointSpice.TouchWaypointSpiceTemplateLibrary;this._waypointsDialog=this._createWaypointsDialog();this._waypointsDialog.addEventHandler(TouchDialog.EVENT_CLOSE,this._onDialogClose,this);this._waypointsDialog.addEventHandler(TouchDialog.EVENT_CANCEL,this._onDialogCancel,this);this._searchContainer=this._createSearchContainer();this._destinationContainer=this._createDestinationContainer();this._waypointsContainer=new Container("WaypointContainer",templateLibrary);var content=new Container("ContentContainer",templateLibrary);content.setChildAt(this._searchContainer,"search");content.setChildAt(this._destinationContainer,"destination");content.setChildAt(this._waypointsContainer,"waypoints");this._waypointsDialog.setChildAt(content,"content");this._waypointsList=new List(null,templateLibrary);this._waypointsList._addCssClass("nmp_WaypointList");var waypointScroll=new ListScrollable("WaypointScrollable",templateLibrary);this._waypointsList.addBehavior(waypointScroll);this._waypointsContainer.setChildAt(this._waypointsList,"waypointList");this._startButton=new Container("WaypointListButtonItem",templateLibrary);var startButton=new Button(null,"__I18N_nokia.maps.pfw.spices.waypointspice.setstartpoint__");this._startButton.setChildAt(startButton,"button",false,true);this._startButton.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._buttonBar=new Container("WaypointListButtonBar",templateLibrary);this._buttonBar.getReplica().addCssClass("nmp_WaypointButton_LastItem");this._addAnotherDestinationButton=new Button("ResizableButton","__I18N_nokia.maps.pfw.spices.touchwaypointspice.addanotherdestination__");this._addAnotherDestinationButton.addEventHandler("selected",this._onAddStopover,this);this._addAnotherDestinationButton.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._buttonBar.setChildAt(this._addAnotherDestinationButton,"leftButton",false,true);this._addDestinationButton=new Button("ResizableButton","__I18N_nokia.maps.pfw.spices.waypointspice.adddestination__");this._addDestinationButton.addEventHandler("selected",this._onAddDestination,this);this._addDestinationButton.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._buttonBar.setChildAt(this._addDestinationButton,"leftButton2",false,true);this._deleteRouteButton=new Button("ResizableButton","__I18N_nokia.maps.pfw.spices.waypointspice.deleteroute__");this._deleteRouteButton.addEventHandler("selected",this._onClearRouteClicked,this);this._deleteRouteButton.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._deleteRouteButton.getReplica().addCssClass("nmp_WaypointButton_RightButton");this._buttonBar.setChildAt(this._deleteRouteButton,"rightButton",false,true);return new SpiceTranslationAdapter([this._waypointsDialog,this._buttonBar])},_createWaypointsDialog:function(){var waypointsDialog=new TouchDialog("TouchDialog",TouchDialog.TouchDialogTemplateLibrary,"__I18N_nokia.maps.pfw.spices.touchwaypointspice.setyourwaypoints__");var routeSummaryBar=new TouchRouteSummary("TouchRouteSummary",TouchRouteSummary.TouchRouteSummaryTemplateLibrary,this._routing,this._map,this);routeSummaryBar.addEventHandler(TouchRouteSummary.EVENT_CLEAR_ROUTE_CLICKED,this._onClearRouteClicked,this);waypointsDialog.setChildAt(routeSummaryBar,"summaryBarContainer");this._application.registerModalDialog("waypoints",this._pfwPath+"images/ui/touch/preview_waypoints.png",this.translateString("__I18N_nokia.maps.pfw.spices.touchwaypointspice.waypoints__"),waypointsDialog,true);return waypointsDialog},_onDialogClose:function(aEvent){this._application.closeModalDialog("waypoints")},_onDialogCancel:function(aEvent){var search=false;var destination=false;search=this._searchContainer.isVisible();destination=this._destinationContainer.isVisible();if(this._searchContainer.isVisible()){this.switchView("destination")}else{if(this._destinationContainer.isVisible()){this.switchView("waypoints")}else{this.switchView("waypoints");this._waypointsDialog.close()}}},_createDestinationContainer:function(){var templateLibrary=TouchWaypointSpice.TouchWaypointSpiceTemplateLibrary;var content=new Container("DestinationContainer",templateLibrary);content.hide();var setFromSearchButton=new Button("ResizableButtonMinSize","__I18N_nokia.maps.pfw.spices.touchwaypointspice.setfromsearch__");this._setFromGpsPositionButton=new EnableButton("ResizableButtonMinSize","__I18N_nokia.maps.pfw.spices.touchwaypointspice.gpsposition__");var setFromMapButton=new Button("ResizableButtonMinSize","__I18N_nokia.maps.pfw.spices.touchwaypointspice.setfrommap__");setFromSearchButton.addEventHandler("selected",this._onSetFromSearchButton,this);this._setFromGpsPositionButton.addEventHandler("selected",this._onSetFromGpsPositionButton,this);setFromMapButton.addEventHandler("selected",this._onSetFromMapButton,this);content.setChildAt(setFromSearchButton,"setFromSearchButton",false,true);content.setChildAt(this._setFromGpsPositionButton,"setFromGpsPositionButton",false,true);content.setChildAt(setFromMapButton,"setFromMapButton",false,true);return content},_createSearchContainer:function(){var content=new Container("SearchDialogContent",TouchWaypointSpice.TouchWaypointSpiceTemplateLibrary);content.hide();this._resultContainer=new Container("ResultContainer",TouchWaypointSpice.TouchWaypointSpiceTemplateLibrary);content.setChildAt(this._resultContainer,"resultContainer",false,false);var searchLabel=new Label(null,"__I18N_nokia.maps.pfw.spices.touchwaypointspice.search__");content.setChildAt(searchLabel,"searchLabel",false,true);this._initDfw(content);return content},_initDfw:function(aSearchContainer){if(this._dfw){return true}var dfw=null;var dfwSearchBox=null;var dfwResultList=null;var dfwErrorPresenter=null;var dfwProgressIndicator=null;try{dfw=new nokia.maps.dfw.ui.DiscoveryFrameworkUI(this._search.getDiscoveryFrameworkCore(),this._page);dfw.setImperialUnits(this._map.getMeasurementType());dfw.addEventHandler("ResultSelected",this._onResultSelected,this);dfw.addEventHandler("ResultButtonSelected",this._onResultButtonSelected,this);dfwErrorPresenter=dfw.getErrorPresenter();dfwSearchBox=dfw.getSearchBox();dfwResultList=dfw.getResultList();dfwProgressIndicator=dfw.getProgressIndicator();dfwResultList.hide();info("Successfully initialized DFW in TouchWaypointSpice")}catch(e){error("Error initializing DFW in TouchWaypointSpice: "+e);return false}this._dfw=dfw;this._dfwSearchBox=dfwSearchBox;this._resultContainer.setChildAt(dfwResultList,"resultList",false,false);this._resultContainer.setChildAt(dfwErrorPresenter,"errorPresenter",false,false);aSearchContainer.setChildAt(dfwSearchBox,"dfwSearchBox",true,true);aSearchContainer.setChildAt(dfwProgressIndicator,"dfwProgressIndicator",false,false);return true},_onSelectPositionCancel:function(){},_onWaypointListClose:function(aEvent){this._hide()},_updateUi:function(aRoute){if(this._waypointsList.getChildCount()>0){this._waypointsList.removeAllChildren()}this._waypointItems=[];var routeWaypoints=[];var hasDefinedWaypoints=false;if(aRoute){routeWaypoints=aRoute.getWaypoints();routeManeuvers=aRoute.getManeuvers();hasDefinedWaypoints=aRoute.hasDefinedWaypoints()}if(!hasDefinedWaypoints&&routeWaypoints.length===1&&routeWaypoints[0]){this._waypointsList.addChild(this._createWaypointItem(routeWaypoints[0],0));this._addAnotherDestinationButton.hide();this._addDestinationButton.show()}else{if(hasDefinedWaypoints&&routeWaypoints.length===1&&routeWaypoints[0]){this._waypointsList.addChild(this._createWaypointItem(routeWaypoints[0],0));this._addAnotherDestinationButton.hide();this._addDestinationButton.show()}else{for(var i=0,len=routeWaypoints.length;i<len;i++){this._waypointsList.addChild(this._createWaypointItem(routeWaypoints[i],i))}this._addAnotherDestinationButton.show();this._addDestinationButton.hide()}}this._waypointsList.addChild(this._buttonBar)},_removeManeuversFromList:function(){for(var i=this._waypointsList.getChildCount()-1;i>=0;i--){var item=this._waypointsList.getChildAt(i);if(item.className==="ManeuverListItem"){this._waypointsList.removeChildAt(i)}}this._waypointsList.getChildAt(0).focus()},_createWaypointItem:function(aWaypoint,aIndex){var waypointItem=new WaypointListItem(aWaypoint,aIndex,"WaypointItem",null,this);waypointItem.addEventHandler(WaypointListItem.EVENT_WAYPOINT_SELECTED,this._onSelectWaypointItem,this);aWaypoint.itemIndex=aIndex;this._waypointItems[aWaypoint.itemIndex]=waypointItem;var reverseGeocode=true;if(aWaypoint.getPosition()&&aWaypoint.getPlace()&&aWaypoint.getDescription()){reverseGeocode=false}else{if(aWaypoint.getPosition()&&aWaypoint.isReverseGeocoded()){reverseGeocode=false}else{if(!aWaypoint.getPosition()){reverseGeocode=false}}}if(reverseGeocode){this._reverseGeoCoding.findLocation(aWaypoint)}return waypointItem},_onSetFromSearchButton:function(){this.switchView("search")},_onSearchDialogClosed:function(aEvent){this.switchView("destination")},_onSetFromGpsPositionButton:function(){var route=this._routing.getCurrentRoute();var gpsWaypoint=new Waypoint();var gpsPosition=null;if(this._isGpsAvailable()){gpsPosition=this._position.getPosition();gpsWaypoint.setGpsPosition(gpsPosition)}else{gpsWaypoint.setGpsPosition(null)}if(this._currentEditingWaypointIndex<route.getWaypointCount()){route.replaceWaypointAt(this._currentEditingWaypointIndex,gpsWaypoint)}else{route.addWaypoint(gpsWaypoint)}if(!route.isValid()){this.switchView("waypoints")}else{var bindObj=this;setTimeout(function(){bindObj._waypointsDialog.close(true);bindObj._routing.calculateRoute(route)},0)}},_onSetFromMapButton:function(){var bindObj=this;setTimeout(function(){bindObj._application.selectPosition(bindObj._currentEditingWaypointTitle,bindObj._onWaypointSelected,bindObj._onSelectPositionCancel,bindObj,{waypointIndex:bindObj._currentEditingWaypointIndex})},0)},_onAddStopover:function(){var currentRoute=this._routing.getCurrentRoute();if(currentRoute&&currentRoute.getWaypoints().length<RoutingModel.MAX_WAYPOINTS){var title=this.translateString("__I18N_nokia.maps.pfw.spices.touchwaypointspice.addanotherdestination__");this._currentEditingWaypointIndex=this._routing.getCurrentRoute().getWaypointCount();this.switchView("destination",title)}else{this._application.showMessageBox("Cannot add stopover","You cannot add another destination. Maximum amount of waypoints has been reached",null,this,["ok"],null)}},_onDeleteWaypointItem:function(aEvent){var yes=this._translator.translate("__I18N_nokia.maps.routingmaplet.yes__");var no=this._translator.translate("__I18N_nokia.maps.routingmaplet.no__");var handlerFunc=this._deleteWaypoint;var text="Do you really want to delete this waypoint?";options=[yes,no];this._application.showMessageBox("",text,handlerFunc,this,options,null)},_deleteWaypoint:function(aEvent){if(aEvent.data.selectedIndex===0){var index=this._currentEditingWaypointIndex;var currentRoute=this._routing.getCurrentRoute();if(currentRoute.getWaypointCount()>1){currentRoute.removeWaypointAt(index)}else{this._routing.setCurrentRoute(null);currentRoute=this._routing.getCurrentRoute()}this._updateUi(currentRoute);if(currentRoute.isValid()){this._routing.calculateRoute(currentRoute)}}},_onSelectWaypointItem:function(aEvent){var waypoint=aEvent.getData().waypoint;var place=null;var description=null;var menuItems=[];menuItems[0]={id:"edit",label:"Edit",icon:null};if(waypoint.getPosition()===null){place=this.translateString("__I18N_nokia.maps.pfw.ui.waypointlistitem.lookuptext__");description=""}else{menuItems[1]={id:"delete",label:"Delete",icon:null};menuItems[2]={id:"map",label:"Show on Map",icon:null};place=waypoint.getPlace();description=waypoint.getDescription();if(!description){description=Units.getReadableLatLonPosition(waypoint.getPosition())}}this._application.configureContextMenu(place,description,null,menuItems,this._onMenuItemSelected,this);this._application.showContextMenu();this._currentEditingWaypointIndex=aEvent.getData().index;this._currentEditingWaypoint=waypoint},_onMenuItemSelected:function(aSelectedItemId){switch(aSelectedItemId){case"edit":this._showDestinationDialog();break;case"delete":this._onDeleteWaypointItem();break;case"map":this._waypointsDialog.close(true);this._map.setMapCenterPosition(this._currentEditingWaypoint.getPosition());break;default:info("TouchWaypointSpice something is wrong with the configuration of the menu...");break}},_showDestinationDialog:function(){var isDestinationWaypoint=false;if(this._currentEditingWaypointIndex>0&&this._routing.getCurrentRoute().getWaypointCount()===(this._currentEditingWaypointIndex+1)){isDestinationWaypoint=true}var titleKey="";if(this._currentEditingWaypointIndex===0){titleKey="__I18N_nokia.maps.pfw.spices.waypointspice.setstartposition__"}else{if(isDestinationWaypoint){titleKey="__I18N_nokia.maps.pfw.spices.waypointspice.setadestination__"}else{titleKey="__I18N_nokia.maps.pfw.spices.waypointspice.setstopover__"}}var title=this.translateString(titleKey);this.switchView("destination",title)},_canUseGpsWaypoint:function(aIndex){var canUseGps=true;var route=this._routing.getCurrentRoute();if(!this._isGpsAvailable()||(route.getWaypoint(aIndex-1)&&route.getWaypoint(aIndex-1).isGpsPosition())||(route.getWaypoint(aIndex+1)&&route.getWaypoint(aIndex+1).isGpsPosition())){canUseGps=false}return canUseGps},_isGpsAvailable:function(){var available=false;if(this._position.isLivePositioningData()&&this._position.getPositioningAccuracy()>0&&this._position.getPositioningAccuracy()<PositionModel.MIN_ACCURACY){available=true}return available},switchView:function(aViewName,aDialogTitle){switch(aViewName){case"waypoints":this._waypointsDialog.setCancelButton(false);this._destinationContainer.hide();this._searchContainer.hide();this._waypointsContainer.show();this._waypointsDialog.setTitle(this.translateString("__I18N_nokia.maps.pfw.spices.touchwaypointspice.setyourwaypoints__"));break;case"destination":this._setFromGpsPositionButton.setEnabled(this._canUseGpsWaypoint(this._currentEditingWaypointIndex));this._waypointsDialog.setCancelButton(true);this._destinationContainer.show();this._searchContainer.hide();this._waypointsContainer.hide();break;case"search":var currentRoute=this._routing.getCurrentRoute();var waypoints=currentRoute.getWaypoints();var position=this._map.getMapCenterPosition();if(currentRoute.getWaypointCount()>1){position=waypoints[currentRoute.getWaypointCount()-1].getPosition()}this._waypointsDialog.setCancelButton(true);this._destinationContainer.hide();this._searchContainer.show();this._waypointsContainer.hide();if(this._initDfw(this._searchContainer)){var dfwCore=this._search.getDiscoveryFrameworkCore(0);if(dfwCore&&dfwCore._nspQuery){dfwCore._nspQuery.queryParams.otherParams.lat=position.latitude;dfwCore._nspQuery.queryParams.otherParams.lon=position.longitude}this._dfwSearchBox.clearBox();this._dfwSearchBox.termBox.focus();this._dfw.setImperialUnits(this._map.getMeasurementType())}break}if(aDialogTitle){this._waypointsDialog.setTitle(aDialogTitle);this._currentEditingWaypointTitle=aDialogTitle}},_onWaypointSelected:function(aEvent){this._currentEditingWaypointIndex=null;var index=aEvent.getData().data.waypointIndex;var position=aEvent.getData().position;var title=aEvent.getData().title;var description=aEvent.getData().description;this._addWaypoint(index,position,title,description);if(!this._routing.getCurrentRoute().isValid()){this._application.showSelector(true,true)}},_onAddDestination:function(){var title=this.translateString("__I18N_nokia.maps.pfw.spices.waypointspice.setadestination__");this._currentEditingWaypointIndex=this._routing.getCurrentRoute().getWaypointCount();this.switchView("destination",title)},_onWaypointsChanged:function(aEvent){var route=this._routing.getCurrentRoute();this._updateUi(route)},_onCurrentRouteChanged:function(aRouteChangeEvent){var newRoute=aRouteChangeEvent.getData().newRoute;var oldRoute=aRouteChangeEvent.getData().oldRoute;if(oldRoute){oldRoute.removeEventHandler(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,this._onWaypointsChanged,this)}if(newRoute){newRoute.addEventHandler(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,this._onWaypointsChanged,this)}this._updateUi(newRoute)},_onClearRouteClicked:function(aEvent){var yes=this._translator.translate("__I18N_nokia.maps.routingmaplet.yes__");var no=this._translator.translate("__I18N_nokia.maps.routingmaplet.no__");var handlerFunc=this._clearRoute;var text="Do you really want to delete this route?";options=[yes,no];this._application.showMessageBox("",text,handlerFunc,this,options,null)},_clearRoute:function(aEvent){if(aEvent.data.selectedIndex===0){this._routing.setCurrentRoute(null)}},_onReverseGeoCodeDone:function(aEvent){var waypoint=aEvent.getData();if(waypoint){var waypointItem=this._waypointItems[waypoint.itemIndex];if(waypointItem){waypointItem.updateItem()}}},_onRouteCalculated:function(aRouteEvent){var eventData=aRouteEvent.getData();this.switchView("waypoints")},_onRouteCalculationCancelled:function(aRouteEvent){this.switchView("waypoints")},_onPositionChanged:function(aEvent){if(this._routing.getCurrentRoute()){var waypoint=this._routing.getCurrentRoute().getWaypoint(0);if(waypoint&&waypoint.isGpsPosition()&&!waypoint.getPosition()){var position=aEvent.getData().position;if(position&&this._isGpsAvailable()){waypoint.setGpsPosition(position);this._routing.getCurrentRoute().replaceWaypointAt(0,waypoint);if(this._routing.getCurrentRoute().isValid()){this._routing.calculateRoute(this._routing.getCurrentRoute())}}else{waypoint.setGpsPosition(null)}}}},_onMapMove:function(aEvent){},_onResultSelected:function(aEvent){var mapResultItem=aEvent.data;var position={latitude:mapResultItem.geoLatitude,longitude:mapResultItem.geoLongitude};this._application.selectPosition(this._currentEditingWaypointTitle,this._onWaypointSelected,this._onSelectPositionCancel,this,{waypointIndex:this._currentEditingWaypointIndex},position)},_onResultButtonSelected:function(aEvent){var mapResultItem=aEvent.getData().resultItem;var position={latitude:mapResultItem.geoLatitude,longitude:mapResultItem.geoLongitude};this._dfwSearchBox.clearBox();this._addWaypoint(this._currentEditingWaypointIndex,position,mapResultItem.row1,mapResultItem.row2);this._map.setMapCenterPosition(position);this._currentEditingWaypointIndex=null},_addWaypoint:function(aIndex,aPosition,aTitle,aDescription){var route=this._routing.getCurrentRoute();var waypoint=new Waypoint(aPosition,null);if(aTitle){waypoint.setPlace(aTitle)}if(aDescription){waypoint.setDescription(aDescription)}if(!route.getWaypoint(aIndex)){route.insertWaypointAt(aIndex,waypoint)}else{route.replaceWaypointAt(aIndex,waypoint)}if(!route.isValid()){this.switchView("waypoints")}else{this._waypointsDialog.close(true);this._routing.calculateRoute(route)}},_show:function(){this._updateUi(this._routing.getCurrentRoute());this.switchView("waypoints");this.getUi().show()},_hide:function(){this.getUi().hide()},getCurrentView:function(){var view="waypoints";if(this._destinationContainer.isVisible()){view="destination"}else{if(this._searchContainer.isVisible()){view="search"}}return view}});TouchWaypointSpice.TouchWaypointSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({ContentContainer:'<div class="nmp_WaypointsContentsContainer"><div id="waypoints"></div><div id="destination"></div><div id="search"></div></div>',DestinationContainer:'<div class="nmp_Destination_Container"><div id="setFromSearchButton" class="nmp_Destination_Container_Item_Touch"></div><div id="setFromGpsPositionButton" class="nmp_Destination_Container_Item_Touch"></div><div id="setFromMapButton" class="nmp_Destination_Container_Item_Touch"></div></div>',WaypointContainer:'<div class="nmp_Waypoints_Container"><div id="waypointList"></div></div>',WaypointScrollable:'<div class="nmp_WaypointScrollable"></div>',WaypointList:'<div class="nmp_WaypointList"></div>',WaypointListButtonItem:'<div class="nmp_WaypointsItem"><div class="nmp_Centered" id="button"></div></div>',WaypointListButtonBar:'<div class="nmp_WaypointsItem"><div class="nmp_Centered"><div id="leftButton"></div><div id="leftButton2"></div><div id="rightButton"></div></div></div>',WaypointItem:'<div class="nmp_WaypointsItem"><p id="icon" class="nmp_Icon"></p><div id="place" class="nmp_Label nmp_WaypointsItem_Place"></div><div id="street" class="nmp_Label nmp_WaypointsItem_Street"></div><div id="spinner"></div></div>',ManeuverItem:'<div class="nmp_WaypointsItem"><p id="icon" class="nmp_Icon"></p><div id="place" class="nmp_Label nmp_WaypointsItem_Place"></div><div id="street" class="nmp_Label nmp_WaypointsItem_Street"></div><div id="spinner"></div></div>',SearchDialogContent:'<div class="nmp_SearchDialogContent"><div class="nmp_SearchBoxContainer"><div id="searchLabel" class="nmp_SearchLabel"></div><div id="dfwSearchBox" class="nmp_SearchBox"></div></div><div id="dfwProgressIndicator"></div><div id="resultContainer"></div></div>',ResultContainer:'<div class="nmp_ResultLisContainer"><div id="errorPresenter"></div><div id="resultList"></div><div id="pagingFrame"></div></div>',ResultList:'<ul id="list" class="nmp_ResultLis"></ul>',ResultListItem:'<li id="item" class="nmp_ResultLisElm"><span class="nmp_ResultNumber" id="resultNumber"></span><span class="nmp_ResultLine1" id="resultLine1"></span><span class="nmp_ResultLine2" id="resultLine2"></span><span class="nmp_ResultDistance" id="resultDistance"></span><span class="nmp_resulticon" id="resulticon"></span><div class="nmp_AddWaypointButton" id="button0"></div></li>',ErrorPresenter:'<div id="errorPresenter" class="nmp_ErrorPresenter"></div>',progressIndicator:'<div id="indicator" class="nmp_ProgressIndicator"></div>',SearchBox:'<div id="searchBox" class="nmp_searchBox"><span id="termBox"></span><span id="searchButton"></span></div>',termBox:'<input id="input" type="text"></input>',clearButton:'<button id="button" class="nmp_clearBtn"></button>',searchButton:'<button id="button" class="nmp_searchBtn"></button>',ResizableButton:'<a class="nmp_ResizableButton" href="javascript:void(0)"><div class="nmp_Left"></div><div class="nmp_Center"><span id="button"></span></div><div class="nmp_Right"></div></a>',ResizableButtonMinSize:'<a class="nmp_ResizableButton" href="javascript:void(0)"><div class="nmp_Left"></div><div class="nmp_Center nmp_MinSize"><span id="button"></span></div><div class="nmp_Right"></div></a>'},nokia.maps.dfw.ui.DFWTemplateLibrary);var TouchDirectionTemplateLibrary=new TemplateLibrary({MainContainer:'<div class="nmp_Main_Container"></div>',WaypointContainer:'<div class="nmp_Waypoints_Container"><div id="waypointList"></div></div>',WaypointScrollable:'<div class="nmp_WaypointScrollable"></div>',WaypointList:'<div class="nmp_WaypointList"></div>',WaypointListButtonItem:'<div class="nmp_WaypointsItem"><div class="nmp_Centered" id="button"></div></div>',WaypointItem:'<div class="nmp_WaypointsItem"><p id="icon" class="nmp_Icon"></p><div id="place" class="nmp_Label nmp_WaypointsItem_Place"></div><div id="street" class="nmp_Label nmp_WaypointsItem_Street"></div><div id="spinner"></div></div>',ManeuverItem:'<div class="nmp_WaypointsItem"><p id="icon" class="nmp_Icon"></p><div id="place" class="nmp_Label nmp_WaypointsItem_Place"></div><div id="street" class="nmp_Label nmp_WaypointsItem_Street"></div><div id="spinner"></div></div>',RouteNotDefinedContainer:'<div class="nmp_NoRouteContainer"><div id="label" class="nmp_NoRouteDefined"></div><div id="button" class="nmp_Centered"></div></div>'},DefaultTouchTemplateLibrary);var TouchDirectionSpice=new Class({Name:"TouchDirectionSpice",Extends:Spice,_startButton:null,_endButton:null,_waypointsList:null,_reverseGeoCoding:null,_routing:null,_position:null,_map:null,_application:null,_maneuversOn:false,_waypointItems:[],initialize:function(aSpiceManager,aTranslator,aModels,aPfwPath){this._super(aSpiceManager,aTranslator);this._routing=aModels.routing;this._map=aModels.map;this._reverseGeoCoding=aModels.reverseGeoCoding;this._application=aModels.application;this._reverseGeoCoding.addEventHandler(ReverseGeoCodingModel.EVENT_REVERSE_GEOCODE_DONE,this._onReverseGeoCodeDone,this);this._routing.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._onCurrentRouteChanged,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculated,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_STARTED,this._onRouteCalculationStarted,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._onRouteCalculationError,this);this._pfwPath=aPfwPath},_createUi:function(){this._directionsDialog=new TouchDialog("TouchDialog",TouchDialog.TouchDialogTemplateLibrary,"__I18N_nokia.maps.pfw.spices.touchdirectionspice.directions__");this._routeSummaryBar=new TouchRouteSummary("TouchRouteSummary",TouchRouteSummary.TouchRouteSummaryTemplateLibrary,this._routing,this._map,this);this._directionsDialog.setChildAt(this._routeSummaryBar,"summaryBarContainer");var mainList=new List("MainContainer",TouchDirectionTemplateLibrary);this._waypointsList=new List(null,TouchDirectionTemplateLibrary);this._waypointsList._addCssClass("nmp_WaypointList");var waypointScroll=new ListScrollable("WaypointScrollable",TouchDirectionTemplateLibrary);this._waypointsList.addBehavior(waypointScroll);this._waypointsListContainer=new Container("WaypointContainer",TouchDirectionTemplateLibrary);this._waypointsListContainer.setChildAt(this._waypointsList,"waypointList");mainList.addChild(this._waypointsListContainer);this._noRouteContainer=new Container("RouteNotDefinedContainer",TouchDirectionTemplateLibrary);this._noRouteContainer.getReplica().setText("label",this.translateString("__I18N_nokia.maps.pfw.spices.touchdirectionspice.noroutedefinedyet__"));this._defineWaypoints=new Button("Button","__I18N_nokia.maps.pfw.spices.touchdirectionspice.defineyourwaypoints__");this._defineWaypoints.addEventHandler("selected",this._onDefineWaypointsButtonPressed,this);this._noRouteContainer.setChildAt(this._defineWaypoints,"button",false,true);mainList.addChild(this._noRouteContainer);this._directionsDialog.setChildAt(mainList,"content");this._application.registerModalDialog("directions",this._pfwPath+"images/ui/touch/preview_directions.png",this.translateString("__I18N_nokia.maps.pfw.spices.touchwaypointspice.directions__"),this._directionsDialog,true);return new SpiceTranslationAdapter([this._directionsDialog])},_onDefineWaypointsButtonPressed:function(){this._application.changeWaypointsDialogView("waypoints");this._application.switchSelectorDialog("waypoints")},_onRouteCalculationStarted:function(aEvent){this._updateUi(this._routing.getCurrentRoute())},_onWaypointListClose:function(aEvent){this._hide()},_updateUi:function(aRoute){this._waypointsList.removeAllChildren();this._waypointItems=[];var routeWaypoints=[];if(aRoute){routeWaypoints=aRoute.getWaypoints();routeManeuvers=aRoute.getManeuvers()}if(!aRoute||!aRoute.isValid()||!aRoute.isCalculated()){this._routeSummaryBar.hide();this._waypointsListContainer.hide();this._noRouteContainer.show()}else{this._routeSummaryBar.show();this._waypointsListContainer.show();this._noRouteContainer.hide();Collection.forEach(routeWaypoints,function(aWaypoint,aId){this._waypointsList.addChild(this._createWaypointItem(aWaypoint,aId))},this);this._addManeuversToList()}},_addManeuversToList:function(){var maneuvers=null;if(this._routing.getCurrentRoute()){maneuvers=this._routing.getCurrentRoute().getManeuvers()}if(maneuvers){this._removeManeuversFromList();for(var i=0;i<maneuvers.length-1;i++){if(maneuvers[i].getWaypointIndex()===null){var indexInWaypointList=i;var maneuver=maneuvers[i];var maneuverListItem=new ManeuverListItem(maneuvers[i],null,null,this._map,this._translator);this._waypointsList.addChildAt(indexInWaypointList,maneuverListItem)}}}},_removeManeuversFromList:function(){for(var i=this._waypointsList.getChildCount()-1;i>=0;i--){var item=this._waypointsList.getChildAt(i);if(item.className==="ManeuverListItem"){this._waypointsList.removeChildAt(i)}}var child=this._waypointsList.getChildAt(0);if(child){child.focus()}},_createWaypointItem:function(aWaypoint,aIndex){var waypointItem=new WaypointListItem(aWaypoint,aIndex,"WaypointItem",null,this,false);aWaypoint.itemIndex=aIndex;this._waypointItems[aWaypoint.itemIndex]=waypointItem;if(aWaypoint.getPosition()&&!aWaypoint.isReverseGeocoded()){this._reverseGeoCoding.findLocation(aWaypoint)}return waypointItem},_onWaypointsChanged:function(aEvent){var route=this._routing.getCurrentRoute();this._updateUi(route)},_onCurrentRouteChanged:function(aRouteChangeEvent){var newRoute=aRouteChangeEvent.getData().newRoute;this._updateUi(newRoute)},_onReverseGeoCodeDone:function(aEvent){var waypoint=aEvent.getData();if(waypoint){var waypointItem=this._waypointItems[waypoint.itemIndex];if(waypointItem){waypointItem.updateItem()}}},_onRouteCalculated:function(aRouteEvent){this._updateUi(this._routing.getCurrentRoute())},_onRouteCalculationError:function(aEvent){this._updateUi(null)},_show:function(){this._updateUi(this._routing.getCurrentRoute());this.getUi().show()},_hide:function(){this.getUi().hide()}});var TouchSearchSpice=new Class({Name:"TouchSearchSpice",Extends:Spice,initialize:function(aSpiceManager,aMapModel,aSearchModel,aPage){if(!aSearchModel){throw new nokia.aduno.utils.ArgumentError("aSearchModel is required")}if(!aSearchModel.isReady()){throw new ArgumentError("The SearchModel is not ready")}this._super(aSpiceManager);this._model=aMapModel;this._searchModel=aSearchModel;this._page=aPage;this._spiceManager=aSpiceManager;this._dfw=null;this._publicMethods=["show","hide","search"]},_createUi:function(){this._dfwContainer=new Container("DfwContainer",TouchSearchSpice.TouchSearchSpiceTemplateLibrary);this._dfw=new nokia.maps.dfw.ui.DiscoveryFrameworkUI(this._searchModel.getDiscoveryFrameworkCore(),this._page);this._dfw.addEventHandler("ResultSelected",this._onResultSelected,this);this._dfw.addEventHandler("ResultsReceived",this._onResultsReceived,this);this._dfw.addEventHandler("ResultsCleared",this._onResultsCleared,this);this._dfw.addEventHandler("SuggestionSelected",this._onSuggestionSelected,this);this._dfwSearchBox=this._dfw.getSearchBox();this._dfwResultList=this._dfw.getResultList();this._dfwPagingFrame=this._dfw.getPagingFrame();this._dfwErrorPresenter=this._dfw.getErrorPresenter();this._dfwProgressIndicator=this._dfw.getProgressIndicator();this._dfwContainer.setChildAt(this._dfwSearchBox,"dfwSearchBox");this._dfwContainer.setChildAt(this._dfwProgressIndicator,"dfwProgressIndicator");this._resultContainer=new Container("ResultContainer",SearchSpice.SearchSpiceTemplateLibrary);this._resultContainer.hide();this._resultContainer.setChildAt(this._dfwErrorPresenter,"ErrorPresenter",true,true);this._resultContainer.setChildAt(this._dfwResultList,"ResultList",true,true);this._resultContainer.setChildAt(this._dfwPagingFrame,"PagingFrame",true,true);this._dfwContainer.setChildAt(this._resultContainer,"ResultContainer",true,true);return this._dfwContainer},_onResultSelected:function(aEvent){},_onResultMapObjectSelected:function(aEvent){},_moveToSearchResult:function(aResult,aMapObject){},_onResultsReceived:function(aEvent){},_onResultsCleared:function(aEvent){},_cleanupSearchResults:function(){},_onSuggestionSelected:function(event){},show:function(){},hide:function(){},search:function(term){this._dfwSearchBox.setValue(term);this._dfwSearchBox.fireSearch()}});TouchSearchSpice=new Class(TouchSearchSpice);TouchSearchSpice.TouchSearchSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({SearchBox:'<div id="searchBox" class="nmp_WaypointSearch_Box"><span id="termBox"></span><span id="searchButton"></span></div>',SearchResultList:'<ul class="nmm_SearchResults"></ul>',SearchResultElement:'<li class="nmm_SearchResultEntry"><a id="button" href=""></a></li>',ResultContainer:'<div class="nmm_resultContainer"><div id="ErrorPresenter"></div><div id="ResultList" class="nmm_rlContainer"></div><div id="PagingFrame"></div></div>'},nokia.maps.dfw.ui.DFWTemplateLibrary);var TouchRouteSettingsTemplateLibrary=new TemplateLibrary({CheckButton:'<a id="checkButton" class="nmp_CheckButton" href="javascript:void(0);"><span id="checkButtonText"></span></a>',RouteSettingsContainer:'<div class="nmp_RouteSettingsContainer"><div id="routeSettingsList"></div></div>',RouteSettingsScrollable:'<div class="nmp_RouteSettingsScrollable"></div>',RouteSettingsRadioGroup:'<div class="nmp_RouteSettingsRadioGroup"/>',TransportationModeContainer:'<div class="nmp_TransportationModeContainer"><div id="label" class="nmp_Label"></div><div id="radioGroup"></div></div>',BlockersMargin:'<div class="nmp_BlockersMargin"></div>',BlockersContainer:'<div class="nmp_BlockersContainer"></div>',BlockerButton:'<div class="nmp_BlockerButton"><div id="checkButtonIcon"></div><p id="checkButtonText"/></div>'},DefaultTouchTemplateLibrary);var TouchRouteSettingsSpice=new Class({Name:"TouchRouteSettingsSpice",Extends:Spice,MODE_DRIVE:0,MODE_WALK:1,MODE_BICYCLE:2,TYPE_FASTEST:0,TYPE_SHORTEST:1,TYPE_OPTIMIZED:2,TYPE_STREET:3,TYPE_STRAIGHT_LINE:4,_modelUpdatesDisabled:false,initialize:function(aSpiceManager,aTranslator,aModels,aPfwPath){this._super(aSpiceManager,aTranslator);this._routeSettingsModel=aModels.routeSettings;this._routingModel=aModels.routing;this._guidance=aModels.guidance;this._application=aModels.application;this._mapModel=aModels.map;this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._update,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._update,this);this._routingModel.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._update,this);this._routeSettingsModel.addEventHandler(RouteSettingsModel.EVENT_BLOCKERS,this._update,this);this._routeSettingsModel.addEventHandler(RouteSettingsModel.EVENT_ROUTE_TYPE,this._update,this);this._routeSettingsModel.addEventHandler(RouteSettingsModel.EVENT_TRANSPORTATION_MODE,this._update,this);this._pfwPath=aPfwPath},_createUi:function(){this._routeSettingsDialog=new TouchDialog("RouteSettingsDialog",TouchDialog.TouchDialogTemplateLibrary,this.translateString("__I18N_nokia.maps.pfw.spices.touchwaypointspice.routesettings__"));this._routeSummaryBar=new TouchRouteSummary("TouchRouteSummary",TouchRouteSummary.TouchRouteSummaryTemplateLibrary,this._routingModel,this._mapModel,this);this._routeSettingsDialog.setChildAt(this._routeSummaryBar,"summaryBarContainer");var routeSettingsContainer=new Container("RouteSettingsContainer",TouchRouteSettingsTemplateLibrary);var routeSettingsList=new List();routeSettingsList._addCssClass("nmp_RouteSettingsList");var scrollable=new ListScrollable("RouteSettingsScrollable");routeSettingsList.addBehavior(scrollable);routeSettingsContainer.setChildAt(routeSettingsList,"routeSettingsList");this._transportationRadioGroup=new RadioGroup("RouteSettingsRadioGroup");var driveButton=new CheckButton("CheckButton","__I18N_nokia.maps.pfw.ui.transportationmodesettings.captiondrive__");var walkButton=new CheckButton("CheckButton","__I18N_nokia.maps.pfw.ui.transportationmodesettings.captionwalk__");var bikeButton=new CheckButton("CheckButton","__I18N_nokia.maps.pfw.ui.transportationmodesettings.captionbicycle__");this._transportationRadioGroup.addChild(driveButton);this._transportationRadioGroup.addChild(walkButton);driveButton.addEventHandler("selected",this._onSelectTransportationMode,this);walkButton.addEventHandler("selected",this._onSelectTransportationMode,this);bikeButton.addEventHandler("selected",this._onSelectTransportationMode,this);var transportationModeContainer=new Container("TransportationModeContainer");transportationModeContainer.getReplica().setText("label",this.translateString("__I18N_nokia.maps.pfw.ui.transportationmodesettings.lbltransportation__"));transportationModeContainer.setChildAt(this._transportationRadioGroup,"radioGroup");this._routeTypeGroup=new RadioGroup("RouteSettingsRadioGroup");this._fastestButton=new CheckButton("CheckButton","__I18N_nokia.maps.pfw.ui.routetypesettings.fastest__");this._shortestButton=new CheckButton("CheckButton","__I18N_nokia.maps.pfw.ui.routetypesettings.shortest__");this._optimizedButton=new CheckButton("CheckButton","__I18N_nokia.maps.pfw.ui.routetypesettings.optimized__");this._streetButton=new CheckButton("CheckButton","__I18N_nokia.maps.pfw.ui.routetypesettings.street__");this._straightButton=new CheckButton("CheckButton","__I18N_nokia.maps.pfw.ui.routetypesettings.straightline__");this._routeTypeGroup.addChild(this._fastestButton);this._routeTypeGroup.addChild(this._shortestButton);this._routeTypeGroup.addChild(this._optimizedButton);this._routeTypeGroup.addChild(this._streetButton);this._routeTypeGroup.addChild(this._straightButton);this._fastestButton.addEventHandler("selected",this._onSelectRouteType,this);this._shortestButton.addEventHandler("selected",this._onSelectRouteType,this);this._optimizedButton.addEventHandler("selected",this._onSelectRouteType,this);this._streetButton.addEventHandler("selected",this._onSelectRouteType,this);this._straightButton.addEventHandler("selected",this._onSelectRouteType,this);var routeTypeContainer=new Container("TransportationModeContainer");routeTypeContainer.getReplica().setText("label",this.translateString("__I18N_nokia.maps.pfw.ui.routetypesettings.lblmain__"));routeTypeContainer.setChildAt(this._routeTypeGroup,"radioGroup");this._blockerButtonHighways=new CheckButton("BlockerButton","__I18N_nokia.maps.pfw.ui.blockersettings.motorways__");this._blockerButtonHighways.getReplica().addCssClass("checkButtonIcon","nmp_BlockerHighways");this._blockerButtonFerries=new CheckButton("BlockerButton","__I18N_nokia.maps.pfw.ui.blockersettings.ferries__");this._blockerButtonFerries.getReplica().addCssClass("checkButtonIcon","nmp_BlockerFerries");this._blockerButtonTunnels=new CheckButton("BlockerButton","__I18N_nokia.maps.pfw.ui.blockersettings.tunnels__");this._blockerButtonTunnels.getReplica().addCssClass("checkButtonIcon","nmp_BlockerTunnels");this._blockerButtonTollroads=new CheckButton("BlockerButton","__I18N_nokia.maps.pfw.ui.blockersettings.tollroads__");this._blockerButtonTollroads.getReplica().addCssClass("checkButtonIcon","nmp_BlockerTollroads");this._blockerButtonUnpavedRoads=new CheckButton("BlockerButton","__I18N_nokia.maps.pfw.ui.blockersettings.dirtroads__");this._blockerButtonUnpavedRoads.getReplica().addCssClass("checkButtonIcon","nmp_BlockerUnpavedRoads");this._blockerButtonMotorailTrain=new CheckButton("BlockerButton","__I18N_nokia.maps.pfw.ui.blockersettings.motorails__");this._blockerButtonMotorailTrain.getReplica().addCssClass("checkButtonIcon","nmp_BlockerMotorailTrains");this._blockerButtonHighways.addEventHandler("selected",this._onSelectBlockerSetting,this);this._blockerButtonFerries.addEventHandler("selected",this._onSelectBlockerSetting,this);this._blockerButtonTunnels.addEventHandler("selected",this._onSelectBlockerSetting,this);this._blockerButtonTollroads.addEventHandler("selected",this._onSelectBlockerSetting,this);this._blockerButtonUnpavedRoads.addEventHandler("selected",this._onSelectBlockerSetting,this);this._blockerButtonMotorailTrain.addEventHandler("selected",this._onSelectBlockerSetting,this);var routeBlockersList=new List("BlockersContainer");routeBlockersList.addChild(new Label(null,"__I18N_nokia.maps.pfw.spices.routesettingsspice.allowedroutetype__"));routeBlockersList.addChild(this._blockerButtonHighways);routeBlockersList.addChild(this._blockerButtonFerries);routeBlockersList.addChild(this._blockerButtonTunnels);routeBlockersList.addChild(this._blockerButtonTollroads);routeBlockersList.addChild(this._blockerButtonUnpavedRoads);routeBlockersList.addChild(this._blockerButtonMotorailTrain);routeSettingsList.addChild(transportationModeContainer);routeSettingsList.addChild(routeTypeContainer);routeSettingsList.addChild(routeBlockersList);this._routeSettingsDialog.setChildAt(routeSettingsContainer,"content",false,false);this._application.registerModalDialog("route settings",this._pfwPath+"images/ui/touch/preview_routesettings.png",this.translateString("__I18N_nokia.maps.pfw.spices.touchwaypointspice.routesettings__"),this._routeSettingsDialog,true);this._update();return new SpiceTranslationAdapter([this._routeSettingsDialog])},_onClearRouteClicked:function(aEvent){this._routingModel.setCurrentRoute(null)},_update:function(aEvent){this._modelUpdatesDisabled=true;var mode=this._routeSettingsModel.getTransportationMode();if(mode==Route.TRANSPORTATION_MODE_CAR){this._transportationRadioGroup.setSelectionIndex(this.MODE_DRIVE);this._fastestButton.show();this._shortestButton.show();this._optimizedButton.show();this._streetButton.hide();this._straightButton.hide()}else{if(mode==Route.TRANSPORTATION_MODE_PEDESTRIAN){this._transportationRadioGroup.setSelectionIndex(this.MODE_WALK);this._fastestButton.hide();this._shortestButton.hide();this._optimizedButton.hide();this._streetButton.show();this._straightButton.show()}else{if(mode==Route.TRANSPORTATION_MODE_BICYCLE){this._transportationRadioGroup.setSelectionIndex(this.MODE_BICYCLE);this._fastestButton.hide();this._shortestButton.hide();this._optimizedButton.hide();this._streetButton.show();this._straightButton.show()}else{warn("Unsupported transportation mode '"+this._routeSettingsModel.getTransportationMode()+"' in "+this.className)}}}switch(this._routeSettingsModel.getRouteType()){case Route.ROUTE_TYPE_FASTEST:this._routeTypeGroup.setSelectionIndex(this.TYPE_FASTEST);break;case Route.ROUTE_TYPE_SHORTEST:this._routeTypeGroup.setSelectionIndex(this.TYPE_SHORTEST);break;case Route.ROUTE_TYPE_OPTIMIZED:this._routeTypeGroup.setSelectionIndex(this.TYPE_OPTIMIZED);break;case Route.ROUTE_TYPE_STREET:this._routeTypeGroup.setSelectionIndex(this.TYPE_STREET);break;case Route.ROUTE_TYPE_STRAIGHT_LINE:this._routeTypeGroup.setSelectionIndex(this.TYPE_STRAIGHT_LINE);break;default:warn("Unsupported route type '"+this._routeSettingsModel.getRouteType()+"' in "+this.className);break}this._updateButton(this._blockerButtonHighways,this._routeSettingsModel.canSetAllowHighways(),this._routeSettingsModel.getAllowHighways());this._updateButton(this._blockerButtonFerries,this._routeSettingsModel.canSetAllowFerries(),this._routeSettingsModel.getAllowFerries());this._updateButton(this._blockerButtonTunnels,this._routeSettingsModel.canSetAllowTunnels(),this._routeSettingsModel.getAllowTunnels());this._updateButton(this._blockerButtonTollroads,this._routeSettingsModel.canSetAllowTollroads(),this._routeSettingsModel.getAllowTollroads());this._updateButton(this._blockerButtonUnpavedRoads,this._routeSettingsModel.canSetAllowUnpavedRoads(),this._routeSettingsModel.getAllowUnpavedRoads());this._updateButton(this._blockerButtonMotorailTrain,this._routeSettingsModel.canSetAllowMotorailTrain(),this._routeSettingsModel.getAllowMotorailTrain());this._modelUpdatesDisabled=false},_updateButton:function(aButton,aEnabled,aSelected){if(aEnabled){aButton.show()}else{aButton.hide()}aButton.setState(aSelected)},_onSelectTransportationMode:function(){if(this._modelUpdatesDisabled){return}switch(this._transportationRadioGroup.getSelectionIndex()){case this.MODE_DRIVE:this._routeSettingsModel.setTransportationMode(Route.TRANSPORTATION_MODE_CAR);break;case this.MODE_WALK:this._routeSettingsModel.setTransportationMode(Route.TRANSPORTATION_MODE_PEDESTRIAN);break;case this.MODE_BIKE:this._routeSettingsModel.setTransportationMode(Route.TRANSPORTATION_MODE_BICYCLE);break}},_onSelectBlockerSetting:function(aEvent){if(this._modelUpdatesDisabled){return}if(this._routeSettingsModel.getAllowHighways()!==this._blockerButtonHighways._state){this._routeSettingsModel.setAllowHighways(this._blockerButtonHighways._state)}if(this._routeSettingsModel.getAllowFerries()!==this._blockerButtonFerries._state){this._routeSettingsModel.setAllowFerries(this._blockerButtonFerries._state)}if(this._routeSettingsModel.getAllowTunnels()!==this._blockerButtonTunnels._state){this._routeSettingsModel.setAllowTunnels(this._blockerButtonTunnels._state)}if(this._routeSettingsModel.getAllowTollroads()!==this._blockerButtonTollroads._state){this._routeSettingsModel.setAllowTollroads(this._blockerButtonTollroads._state)}if(this._routeSettingsModel.getAllowUnpavedRoads()!==this._blockerButtonUnpavedRoads._state){this._routeSettingsModel.setAllowUnpavedRoads(this._blockerButtonUnpavedRoads._state)}if(this._routeSettingsModel.getAllowMotorailTrain()!==this._blockerButtonMotorailTrain._state){this._routeSettingsModel.setAllowMotorailTrain(this._blockerButtonMotorailTrain._state)}},_onSelectRouteType:function(aEvent){if(this._modelUpdatesDisabled){return}switch(this._routeTypeGroup.getSelectionIndex()){case this.TYPE_FASTEST:this._routeSettingsModel.setRouteType(Route.ROUTE_TYPE_FASTEST);break;case this.TYPE_OPTIMIZED:this._routeSettingsModel.setRouteType(Route.ROUTE_TYPE_OPTIMIZED);break;case this.TYPE_SHORTEST:this._routeSettingsModel.setRouteType(Route.ROUTE_TYPE_SHORTEST);break;case this.TYPE_STREET:this._routeSettingsModel.setRouteType(Route.ROUTE_TYPE_STREET);break;case this.TYPE_STRAIGHT_LINE:this._routeSettingsModel.setRouteType(Route.ROUTE_TYPE_STRAIGHT_LINE);break}}});var TouchRouteInfoSpiceTemplateLibrary=new TemplateLibrary({RouteInfo:'<div class="nmp_RouteInfo_Container"><div id="titleBarBackgroundContainer"></div><div id="routeInfoContainer"></div></div>',TitleBarBackground:'<div class="nmp_RouteInfo_TopBar nmp_RouteInfo_Bar_Background"></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var TouchRouteInfoSpice=new Class({Name:"TouchRouteInfoSpice",Extends:Spice,_routing:null,_enabled:true,_map:null,_application:null,initialize:function(aSpiceManager,aTranslator,aModels){this._super(aSpiceManager,aTranslator);this._routing=aModels.routing;this._map=aModels.map;this._application=aModels.application;this._guidance=aModels.guidance;this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STARTED,this._onGuidanceStarted,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STOPPED,this._onGuidanceStopped,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_DONE,this._onGuidanceStopped,this)},_createUi:function(){this._routeInfo=new Container("RouteInfo",TouchRouteInfoSpiceTemplateLibrary);this._routeSummary=new TouchRouteSummary("TouchRouteSummary",TouchRouteSummary.TouchRouteSummaryTemplateLibrary,this._routing,this._map,this);this._routeInfo.setChildAt(this._routeSummary,"routeInfoContainer",false,true);var titleBarBackground=new Container("TitleBarBackground",TouchRouteInfoSpiceTemplateLibrary);this._routeInfo.setChildAt(titleBarBackground,"titleBarBackgroundContainer",false,true);this._application.addVisibleAreaRestrictionControl(this._routeInfo,{top:true});return this._routeInfo},_onGuidanceStarted:function(){this._routeInfo.hide()},_onGuidanceStopped:function(){this._routeInfo.show()}});var TouchStartGuidanceSpiceLibrary=new TemplateLibrary({TouchStartGuidanceSpiceButton:'<div><div class="nmp_StartGuidanceButtons"><div id="guidancebutton" /><div id="simulationbutton" /></div><div id="stopbutton" /></div>',StopGuidanceButton:'<div class="nmp_StopGuidanceButton" />',ResizableButton:'<a class="nmp_ResizableButton nam_Centered" href="javascript:void(0)"><div class="nmp_Left"></div><div class="nmp_Center"><span id="button"></span></div><div class="nmp_Right"></div></a>'},DefaultTouchTemplateLibrary);var TouchStartGuidanceSpice=new Class({Name:"TouchStartGuidanceSpice",Extends:Spice,initialize:function(aSpiceManager,aTranslator,aModels,aEnableSimulation){this._super(aSpiceManager,aTranslator);this._guidance=aModels.guidance;this._routingModel=aModels.routing;this._simulationEnabled=aEnableSimulation},_createUi:function(){var container=new Container("TouchStartGuidanceSpiceButton",TouchStartGuidanceSpiceLibrary);if(this._guidance.isGuidanceSupported()){this._startGuidanceButton=new Button("ResizableButton","Drive now");this._startGuidanceButton.addEventHandler("selected",this._onStartGuidanceClicked,this);container.setChildAt(this._startGuidanceButton,"guidancebutton")}if(this._simulationEnabled){this._startSimulationButton=new Button("ResizableButton","Simulate");this._startSimulationButton.addEventHandler("selected",this._onStartSimulationClicked,this);container.setChildAt(this._startSimulationButton,"simulationbutton")}this._stopGuidanceButton=new Button("StopGuidanceButton");this._stopGuidanceButton.addEventHandler("selected",this._onStopGuidanceClicked,this);container.setChildAt(this._stopGuidanceButton,"stopbutton");this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STARTED,this._update,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STOPPED,this._update,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_DONE,this._update,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._update,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._update,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_CANCELLED,this._update,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_PROGRESS,this._update,this);this._routingModel.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._update,this);this._update();return container},_onStartGuidanceClicked:function(){this._startGuidance(false)},_onStartSimulationClicked:function(){this._startGuidance(true)},_startGuidance:function(aSimulate){var route=this._routingModel.getCurrentRoute();var skins=this._guidance.getAvailableVoiceSkins();if(skins&&skins.length>0){this._guidance.setActiveVoiceSkin(skins[0])}this._guidance.startNavigation(route,aSimulate)},_onStopGuidanceClicked:function(){this._guidance.stopNavigation()},_update:function(){var visibleStart=null,visibleStop=null;if(this._guidance.isNavigationRunning()){visibleStart=false;visibleStop=true}else{var route=this._routingModel.getCurrentRoute();if(route&&route.isValid()){visibleStart=true;visibleStop=false}else{visibleStart=false;visibleStop=false}}info("Start: "+visibleStart+" Stop: "+visibleStop);if(visibleStart===true){if(this._startGuidanceButton){this._startGuidanceButton.show()}if(this._simulationEnabled){this._startSimulationButton.show()}}else{if(visibleStart===false){if(this._startGuidanceButton){this._startGuidanceButton.hide()}if(this._simulationEnabled){this._startSimulationButton.hide()}}else{warn("Unknown routing state")}}if(visibleStop===true){this._stopGuidanceButton.show()}else{if(visibleStop===false){this._stopGuidanceButton.hide()}else{warn("Unknown routing state")}}}});var MaemoZoomSpice=new Class({Name:"MaemoZoomSpice",Extends:Spice,_repeaterInterval:1000,_zoomAnimationTimeout:1000,_lastZoomTimestamp:0,initialize:function(aSpiceManager,aMapModel,aZoomModel){this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._zoomModel=aZoomModel;this._zoomRepeater=null;this._spiceManager.setKeyHandler(KeyEventManager.KEY_NUM_PLUS,0,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_NUM_PLUS,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_PLUS_MOZ,0,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_PLUS_MOZ,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_NUM_MINUS,0,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_NUM_MINUS,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._zoomModel.setRange(this._mapModel.getMinZoomScale()||40,this._mapModel.getMaxZoomScale()||1953509)},_createUi:function(){var container=new Container("MaemoZoomSpiceContainer",MaemoZoomSpice.TemplateLibrary);this._zoomInButton=new Button(MaemoZoomSpice.TemplateLibrary.getTemplate("ZoomIn"));this._zoomInButton.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._zoomInStart);this._zoomInButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);container.setChildAt(this._zoomInButton,"zoomIn");this._zoomOutButton=new Button(MaemoZoomSpice.TemplateLibrary.getTemplate("ZoomOut"));this._zoomOutButton.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._zoomOutStart);this._zoomOutButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);container.setChildAt(this._zoomOutButton,"zoomOut");var node=new XNode(document).addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,bindWithEvent(this,this._stopZoom));this._levelsButton=new Button(MaemoZoomSpice.TemplateLibrary.getTemplate("ZoomLevels"));this._levelsButton.addEventHandler("selected",this._switchZoomLevelsContainer,this);this._levelsButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);container.setChildAt(this._levelsButton,"zoomLevels");this._zoomLevelsContainer=new Container("ZoomLevelsContainer",MaemoZoomSpice.TemplateLibrary);this._zoomLevelsContainer.hide();container.setChildAt(this._zoomLevelsContainer,"zoomLevelsContainer");this._countryButton=new Button("CountryButton","__I18N_mapPlayer_43_mapControl_zoomControl_bookmark_country__");this._countryButton.addEventHandler("selected",this._zoomToLevel,this);this._countryButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._zoomLevelsContainer.setChildAt(this._countryButton,"country");this._stateButton=new Button("StateButton","__I18N_mapPlayer_44_mapControl_zoomControl_bookmark_state__");this._stateButton.addEventHandler("selected",this._zoomToLevel,this);this._stateButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._zoomLevelsContainer.setChildAt(this._stateButton,"state");this._cityButton=new Button("CityButton","__I18N_mapPlayer_45_mapControl_zoomControl_bookmark_city__");this._cityButton.addEventHandler("selected",this._zoomToLevel,this);this._cityButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._zoomLevelsContainer.setChildAt(this._cityButton,"city");this._streetButton=new Button("StreetButton","__I18N_mapPlayer_46_mapControl_zoomControl_bookmark_street__");this._streetButton.addEventHandler("selected",this._zoomToLevel,this);this._streetButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._zoomLevelsContainer.setChildAt(this._streetButton,"street");return container},_switchZoomLevelsContainer:function(){if(this._zoomLevelsContainer.isVisible()){this.close()}else{this._showZoomLevelsContainer()}},_showZoomLevelsContainer:function(){var _orientation=this._spiceManager.getSpice("OrientationTiltSpice");if(_orientation){_orientation.close()}var _settings=this._spiceManager.getSpice("MaemoSettingsSpice");if(_settings){_settings.close()}this._zoomLevelsContainer.show()},close:function(){if(this._zoomLevelsContainer.isVisible()){this._zoomLevelsContainer.hide()}},_zoomToLevel:function(aClickEvent){var posId=aClickEvent.source.getPosId();switch(posId){case"country":this._zoomModel.setStep(13);break;case"state":this._zoomModel.setStep(8);break;case"city":this._zoomModel.setStep(5);break;case"street":this._zoomModel.setStep(2);break;default:break}this.close()},_zoomInStart:function(){this.close();this._zoomIn();this._zoomRepeater=nokia.aduno.utils.setPeriodical(this._repeaterInterval,this,this._zoomIn)},_zoomIn:function(){val=this._zoomModel.getStep();if(val>0){this._zoomModel.setStep(val-1)}this.close()},_zoomOutStart:function(){this.close();this._zoomOut();this._zoomRepeater=nokia.aduno.utils.setPeriodical(this._repeaterInterval,this,this._zoomOut)},_zoomOut:function(){val=this._zoomModel.getStep();if(val<(this._zoomModel.getStepCount()-1)){this._zoomModel.setStep(val+1)}this.close()},_stopZoom:function(){if(this._zoomRepeater){nokia.aduno.utils.cancelPeriodical(this._zoomRepeater);this._zoomRepeater=null}},_handleKey:function(aKeyEvent){if(aKeyEvent.keyPress||aKeyEvent.keyDown){if(this._lastZoomTimestamp+this._zoomAnimationTimeout>new Date().getTime()){return}var key=aKeyEvent.getKey();switch(key){case KeyEventManager.KEY_NUM_PLUS:case KeyEventManager.KEY_PLUS_MOZ:this._lastZoomTimestamp=new Date().getTime();this._zoomIn();aKeyEvent.preventDefault();aKeyEvent.stopPropagation();return true;case KeyEventManager.KEY_NUM_MINUS:this._lastZoomTimestamp=new Date().getTime();this._zoomOut();aKeyEvent.preventDefault();aKeyEvent.stopPropagation();return true;default:break}}return false}});MaemoZoomSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({MaemoZoomSpiceContainer:'<div class="nmp_maemoZoom"><div class="nmp_maemoZoomLT"></div><div class="nmp_maemoZoomLB"></div><div class="nmp_maemoZoomRT"></div><div class="nmp_maemoZoomRB"></div><div class="nmp_maemoZoomButtons"><div class="nmp_maemoZoomSeparator1"></div><div class="nmp_maemoZoomSeparator2"></div><div id="zoomLevels"></div><div id="zoomIn"></div><div id="zoomOut"></div></div><div id="zoomLevelsContainer"></div></div>',ZoomLevels:'<div id="button" class="nmp_maemoZoomLevels"></div>',ZoomIn:'<div id="button" class="nmp_maemoZoomIn"></div>',ZoomOut:'<div id="button" class="nmp_maemoZoomOut"></div>',ZoomLevelsContainer:'<div id="zoomLevelsContainer" class="nmp_maemoZoomLevelsContainer"><div id="country"></div><div id="state"></div><div id="city"></div><div id="street"></div></div>',CountryButton:'<div class="nmp_maemoZoomButton"><div id="button" unselectable="on"></div></div>',StateButton:'<div class="nmp_maemoZoomButton"><div id="button" unselectable="on"></div></div>',CityButton:'<div class="nmp_maemoZoomButton"><div id="button" unselectable="on"></div></div>',StreetButton:'<div class="nmp_maemoZoomButton"><div id="button" unselectable="on"></div></div>'});var MaemoOrientation=new nokia.aduno.utils.Class({Extends:nokia.aduno.medosui.Control,Name:"MaemoOrientation",_compassSize:300,_northAngle:30,_centerDistance:150,_overTiltDistance:58,_rotatorInterval:50,_anglesSin:[],_anglesCos:[],_knobRadius:83/2,_clickXY:{},_clickDelta:20,initialize:function(aTemplate,aTemplateLibrary,aClickDelta){this._super(aTemplate,aTemplateLibrary);this._angle=0;this._isRotating=false;this._clickDelta=aClickDelta;this._replica.addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._handleMouseDown);var node=new XNode(document).addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,bindWithEvent(this,this._handleMouseUp));this.addBehavior(new Draggable());this.addEventHandler("dragged",this._onDrag,this);for(var i=0;i<360;i++){this._anglesSin.push(Math.sin(Math.PI/180*i));this._anglesCos.push(Math.cos(Math.PI/180*i))}},setWheelPosition:function(aAngleStep){if(aAngleStep===this._angle){return}if(this._rotator){nokia.aduno.utils.cancelPeriodical(this._rotator);this._rotator=null;this._isRotating=false}this._angle=aAngleStep%360;this._updateCss()},setTilt:function(anAngle){if(anAngle===0){this.getReplica().addCssClass("tilt","nmp_maemoOrTiTilt3D")}else{this.getReplica().removeCssClass("tilt","nmp_maemoOrTiTilt3D")}},_onDrag:function(aDragEvent){var data=aDragEvent.getData();if(isNaN(data.mouseX)||isNaN(data.mouseY)){return}if(Math.abs(this._clickXY.x-data.mouseX)<this._clickDelta&&Math.abs(this._clickXY.y-data.mouseY)<this._clickDelta){return}var calc=this._calculateToCenter(data.mouseX,data.mouseY);if(!this._wasDragged){this._initialDragAngle=calc.angle-this._angle}this._wasDragged=true;this.setWheelPosition(calc.angle-this._initialDragAngle);this.fireEvent(new nokia.aduno.utils.Event("rotated",{angle:this._angle,dragged:true}))},_handleMouseDown:function(aEvent){if(aEvent.get("which")!==1||isNaN(aEvent.get("pageX"))||isNaN(aEvent.get("pageY"))){return}if(this._rotator&&this._isRotating){nokia.aduno.utils.cancelPeriodical(this._rotator);this._isRotating=false;this._rotator=null}var calc=this._calculateToCenter(aEvent.get("pageX"),aEvent.get("pageY"));if(calc.distance<this._overTiltDistance){this.getReplica().addCssClass("tilt","nmp_maemoOrTiTiltDown");aEvent.stopPropagation();this.fireEvent(new nokia.aduno.utils.Event("tilted"))}else{if(calc.distance>this._centerDistance){aEvent.stopPropagation()}else{this._clickXY={x:aEvent.get("pageX"),y:aEvent.get("pageY")};if(calc.north){this.getReplica().addCssClass("north","nm_MouseDown")}this._downWheel=true;this._wasDragged=false;this._updateCss()}}},_handleMouseUp:function(aEvent){if(aEvent.get("which")!==1||isNaN(aEvent.get("pageX"))||isNaN(aEvent.get("pageY"))){return}var calc=this._calculateToCenter(aEvent.get("pageX"),aEvent.get("pageY"));if(this._downWheel){if(!this._wasDragged&&!this._isRotating){if(calc.north){this._targetRotateAngle=0}else{this._targetRotateAngle=calc.angle}this._initialRotateAngle=this._angle;this._rotateTime=0;if(this._initialRotateAngle!=this._targetRotateAngle){this._rotator=nokia.aduno.utils.setPeriodical(this._rotatorInterval,this,this._doRotate)}}if(this._wasDragged){this.fireEvent(new nokia.aduno.utils.Event("rotated",{angle:this._angle,dragged:false}))}}this.getReplica().removeCssClass("tilt","nmp_maemoOrTiTiltDown");this.getReplica().removeCssClass("north","nm_MouseDown");this._downWheel=false;this._wasDragged=false;this._updateCss()},_rotateFunction:function(x){return Math.pow(x,1/2)},_doRotate:function(){if(this._rotateTime>=1){this.setWheelPosition(this._targetRotateAngle);this.fireEvent(new nokia.aduno.utils.Event("rotated",{angle:this._targetRotateAngle,dragged:false}));nokia.aduno.utils.cancelPeriodical(this._rotator);this._isRotating=false;return}else{this._rotateTime=Math.min(1,this._rotateTime+0.075);var _delta=this._targetRotateAngle-this._initialRotateAngle;if(_delta<-180){_delta+=360}if(_delta>180){_delta-=360}var _rotationStep=_delta*(1-this._rotateFunction(this._rotateTime));this._angle=this._targetRotateAngle-_rotationStep;this._angle=Math.floor((this._angle+360)%360);if(this._angle==0){this._angle=360}this._isRotating=(this._angle==this._targetRotateAngle)?false:true;this.fireEvent(new nokia.aduno.utils.Event("rotated",{angle:this._angle,dragged:this._isRotating}));this._updateCss()}},_calculateToCenter:function(mouseX,mouseY){var pos=nokia.aduno.dom.Dimensions.getPosition(this.getRootElement());var ret={};ret.distX=mouseX-(pos.x+this._centerDistance);ret.distY=mouseY-(pos.y+this._centerDistance);ret.distance=(Math.sqrt(Math.pow(ret.distX,2)+Math.pow(ret.distY,2)));if(ret.distY>0&&ret.distX>=0){ret.angle=90+(Math.asin(Math.abs(ret.distY)/ret.distance)*180/Math.PI)}else{if(ret.distY<0&&ret.distX<0){ret.angle=270+(Math.asin(Math.abs(ret.distY)/ret.distance)*180/Math.PI)}else{if(ret.distX>=0){ret.angle=(Math.asin(Math.abs(ret.distX)/ret.distance)*180/Math.PI)}else{ret.angle=180+(Math.asin(Math.abs(ret.distX)/ret.distance)*180/Math.PI)}}}ret.angle=Math.floor(ret.angle);var _angle=Math.floor(this._angle/10)*10;if(_angle<this._northAngle){ret.north=(ret.angle>360-this._northAngle+_angle||ret.angle<_angle+this._northAngle)}else{if(_angle>=360-this._northAngle){ret.north=(ret.angle>_angle-this._northAngle||ret.angle<_angle-360-this._northAngle)}else{ret.north=(ret.angle>_angle-this._northAngle&&ret.angle<_angle+this._northAngle)}}return ret},_updateCss:function(){var _r=this._compassSize/2-this._knobRadius+8;var _rWSE=_r+12;var _angle=Math.floor(this._angle);var _center=-this._knobRadius+this._centerDistance+8;var _x=_r*this._anglesSin[_angle];var _y=_r*-this._anglesCos[_angle];var _xWSE=_rWSE*this._anglesSin[_angle];var _yWSE=_rWSE*-this._anglesCos[_angle];this.getReplica().setStyle("north","left",(_x+_center)+"px");this.getReplica().setStyle("north","top",(_y+_center)+"px");this.getReplica().setStyle("west","left",(_yWSE+_center)+"px");this.getReplica().setStyle("west","top",(-_xWSE+_center)+"px");this.getReplica().setStyle("south","left",(-_xWSE+_center)+"px");this.getReplica().setStyle("south","top",(-_yWSE+_center)+"px");this.getReplica().setStyle("east","left",(-_yWSE+_center)+"px");this.getReplica().setStyle("east","top",(_xWSE+_center)+"px")}});var MaemoOrientationSpice=new Class({Name:"MaemoOrientationSpice",Extends:Spice,_mapModel:null,_orientationStep:15,_compassSize:77,_down:false,_angle:0,initialize:function(aSpiceManager,aMapModel,aClickDelta){this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._clickDelta=+aClickDelta;this._mapModel.addEventHandler(MapModel.EVENT_TILT,this._onModelTiltChanged,this);this._mapModel.addEventHandler(MapModel.EVENT_ORIENTATION,this._onModelOrientationChanged,this);this._maxTilt=this._mapModel.MAX_TILT;this._spiceManager.setKeyHandler(KeyEventManager.KEY_LEFT,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_RIGHT,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_UP,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey));this._spiceManager.setKeyHandler(KeyEventManager.KEY_DOWN,nokia.aduno.dom.Event.MODIFIER_CTRL,nokia.aduno.utils.bind(this,this._handleKey))},_createUi:function(){var container=new Container("MaemoOrientationSpice",MaemoOrientationSpice.TemplateLibrary);this._compassButton=new Button(MaemoOrientationSpice.TemplateLibrary.getTemplate("CompassButton"));this._compassButton.addEventHandler("selected",this._onOpenOrientation,this);container.setChildAt(this._compassButton,"compass");this._compassButton.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._handleMouseDown);this._compassButton.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this,this._handleMouseUp);this._compassButton.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this,this._handleMouseUp);this._orientation=new Container("Orientation",MaemoOrientationSpice.TemplateLibrary);this._closeOrientationButton=new Button(MaemoOrientationSpice.TemplateLibrary.getTemplate("CloseButton"));this._closeOrientationButton.addEventHandler("selected",this.close,this);this._orientation.setChildAt(this._closeOrientationButton,"closeButton");this._orientationControl=new MaemoOrientation("OrientationControl",MaemoOrientationSpice.TemplateLibrary,this._clickDelta);this._orientationControl.addEventHandler("rotated",this._onUiOrientationChanged,this);this._orientationControl.addEventHandler("tilted",this._onUiTiltSelected,this);this._orientation.setChildAt(this._orientationControl,"orientationControl");this._onUiTiltSelected(this._mapModel.getTilt());this._orientation.hide();container.setChildAt(this._orientation,"orientation");return container},close:function(){this._orientation.hide();this._compassButton.show();this._spiceManager.getSpice("MaemoSettingsSpice").getUi().show()},_onOpenOrientation:function(){var _settings=this._spiceManager.getSpice("MaemoSettingsSpice");if(_settings){_settings.getUi().hide()}var _zoom=this._spiceManager.getSpice("ZoomSpice");if(_zoom){_zoom.close()}this._compassButton.hide();if(this._spiceManager._localizer){this._spiceManager._localizer.traverse(this.getUi().getRootElement())}this._orientation.show()},_handleKey:function(aKeyEvent){var key=aKeyEvent.getKey();var orientation=this._mapModel.getOrientation();var tilt=this._mapModel.getTilt();if(aKeyEvent.keyPress||aKeyEvent.keyDown){if(key===KeyEventManager.KEY_LEFT){this._mapModel.setOrientation(orientation-this._orientationStep)}if(key===KeyEventManager.KEY_RIGHT){this._mapModel.setOrientation(orientation+this._orientationStep)}if(key===KeyEventManager.KEY_UP){this._mapModel.setTilt(this._mapModel.TILT_3D)}if(key===KeyEventManager.KEY_DOWN){this._mapModel.setTilt(0)}}},_onUiOrientationChanged:function(aEvent){if(aEvent.getData().dragged){this._mapModel.setDetailLevel(MapModel.DETAIL_LEVEL_LOW)}else{this._mapModel.setDetailLevel(MapModel.DETAIL_LEVEL_HIGH)}this._mapModel.setOrientation(360-aEvent.getData().angle)},_onUiTiltSelected:function(aEvent){if(this._mapModel.getTilt()===0){this._mapModel.setTilt(this._mapModel.TILT_3D)}else{this._mapModel.setTilt(0)}},_onModelTiltChanged:function(aEvent){this._orientationControl.setTilt(aEvent.getData())},_onModelOrientationChanged:function(aEvent){this._angle=360-aEvent.getData();this._orientationControl.setWheelPosition(this._angle);this._updateCss()},_handleMouseDown:function(){this._down=true;this._updateCss()},_handleMouseUp:function(){this._down=false;this._updateCss()},_updateCss:function(){var _step=((this._angle+360)%360)/30;var _row=0;var _column=Math.floor(_step%12);var _w=this._compassSize;var _h=this._compassSize;if(this._down){_row=1}var _replica=this._compassButton.getReplica();_replica.setStyle("button","background-position",(-_w*_column)+"px "+(-_h*_row)+"px")}});MaemoOrientationSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({MaemoOrientationSpice:'<div><div id="compass"></div><div id="orientation"></div></div>',CompassButton:'<div class="nmp_maemoOrTiButton" ><div class="nmp_maemoOrTiButtonBL"></div><div class="nmp_maemoOrTiButtonBR"></div><div class="nmp_maemoOrTiButtonNorth" id="button"></div></div>',Orientation:'<div class="nmp_maemoOrTiDialog"><div class="nmp_maemoOrTiLT"></div><div class="nmp_maemoOrTiLB"></div><div class="nmp_maemoOrTiRT"></div><div class="nmp_maemoOrTiRB"></div><div id="orientationControl"></div><div id="closeButton"></div></div>',CloseButton:'<div class="nmp_maemoOrTiClose"><div id="button"></div></div>',OrientationControl:'<div class="nmp_maemoOrTiControl"><div class="nmp_maemoOrTiCompass" id="compass"></div><div class="nmp_maemoOrTiNorth" id="north">__I18N_mapPlayer_47_mapControl_rotationControl_north__</div><div class="nmp_maemoOrTiWest" id="west"></div><div class="nmp_maemoOrTiSouth" id="south"></div><div class="nmp_maemoOrTiEast" id="east"></div><div class="nmp_maemoOrTiTilt" id="tilt"></div></div>',Draggable:'<div id="draggable"></div>'});var MaemoSettingsSpice=new Class({Name:"MaemoSettingsSpice",Extends:Spice,Implements:[Serializable],_mapType:null,_ON:"__I18N_mapPlayer_62_commons_status_buttonLabel_on__",_OFF:"__I18N_mapPlayer_63_commons_status_buttonLabel_off__",_ON_CLASS_NAME:"nmp_maemoSettingsOn",initialize:function(aSpiceManager,aMapModel,aPfwPath){this._super(aSpiceManager);this._mapModel=aMapModel;this._mapMappings={0:"normal",1:"hybrid",2:"terrain"};this._mapNameMappings={normal:0,hybrid:1,terrain:2,satellite:1};this._colorMappings={0:"day",1:"night",2:"auto"};this._colorNameMappings={day:0,night:1,auto:2};this._pfwPath=aPfwPath;this._currentColorDay=true;this._currentLandmarksVisible=true},_createUi:function(){this._settingsContainer=new Container("Settings",MaemoSettingsSpice.TemplateLibrary);this._menuContainer=new Container("Menu",MaemoSettingsSpice.TemplateLibrary);this._settingsButton=new Button("Button");this._settingsButton.addEventHandler("selected",this._showSettingsMenu,this);this._settingsContainer.setChildAt(this._settingsButton,"settingsButton");this._mapType=new SelectionList("TypeSelector",null,"nmp_maemoSettingsOn");this._normalButton=new Button("NormalButton","__I18N_mapPlayer_17_buttonsArray_mapview_buttonLabel_map__");this._satelliteButton=new Button("SatelliteButton","__I18N_mapPlayer_18_buttonsArray_mapview_buttonLabel_satellite__");this._terrainButton=new Button("TerrainButton","__I18N_mapPlayer_19_buttonsArray_mapview_buttonLabel_terrain__");this._mapType.addChild(this._normalButton);this._mapType.addChild(this._satelliteButton);this._mapType.addChild(this._terrainButton);this._mapType.setSelectionIndex(this._mapNameMappings[this._mapModel.getMapType()]||0);this._mapType.addEventHandler("selected",this._onTypeSelected,this);this._menuContainer.setChildAt(this._mapType,"TypeSelector");this._dayButton=new Button("ColorDayButton",this._currentColorDay?this._OFF:this._ON);var color=this._mapModel.getColor();if(color===this._colorMappings[1]||color===this._colorMappings[2]){this._currentColorDay=false}if(this._currentColorDay){this._dayButton.getReplica().removeCssClass(this._ON_CLASS_NAME)}else{this._dayButton.getReplica().addCssClass(this._ON_CLASS_NAME)}this._dayButton.addEventHandler("selected",this._onColorSelected,this);this._menuContainer.setChildAt(this._dayButton,"ColorDayButton");this._currentLandmarksVisible=this._mapModel.getLandmarksVisible();this._landmarksButton=new Button("LandmarksButton",this._currentLandmarksVisible?this._ON:this._OFF);if(this._currentLandmarksVisible){this._landmarksButton.getReplica().addCssClass(this._ON_CLASS_NAME)}else{this._landmarksButton.getReplica().removeCssClass(this._ON_CLASS_NAME)}this._landmarksButton.addEventHandler("selected",this._onLandmarksSelected,this);this._menuContainer.setChildAt(this._landmarksButton,"LandmarksButton");this._normalButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._satelliteButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._terrainButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._dayButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._landmarksButton.setCSSTrigger(Control.CSS_TRIGGER_DOWN);this._dialog=new Container("Dialog");this._settingsContainer.setChildAt(this._dialog,"settingsDialog");this._dialog.setChildAt(this._menuContainer,"settingsmenu");this._closeButton=new Button("CloseButton");this._closeButton.addEventHandler("selected",this.close,this);this._dialog.setChildAt(this._closeButton,"closeButton");this._dialog.hide();this._mapModel.addEventHandler(MapModel.EVENT_MAPTYPE,this._onModelMapTypeChanged,this);this._mapModel.addEventHandler(MapModel.EVENT_COLOR,this._onModelColorChanged,this);this._mapModel.addEventHandler(MapModel.EVENT_LANDMARKS,this._onModelLandmarksChanged,this);this._menuContainer.handleKey=function(aKeyEvent){return true};return this._settingsContainer},_showSettingsMenu:function(aEvent){if(!this._dialog.isVisible()){this._showMenuDialog()}else{this.close()}},_showMenuDialog:function(){this._spiceManager.handleModalSpiceOpened(this);var _orientation=this._spiceManager.getSpice("OrientationTiltSpice");if(_orientation){_orientation.getUi().hide()}var _zoom=this._spiceManager.getSpice("ZoomSpice");if(_zoom){_zoom.close()}this._settingsButton.hide();this._dialog.show();this._menuContainer.focus()},close:function(){this._dialog.hide();this._settingsButton.show();this._spiceManager.getSpice("OrientationTiltSpice").getUi().show()},_onTypeSelected:function(aSelectEvent){if(this._ignoreTypeSelectedEvent){this._ignoreTypeSelectedEvent=false;return}var data=aSelectEvent.getData();var type=this._mapMappings[data.selectedIndex]||"normal";if(this._mapModel.getMapType()!==this._mapMappings[data.selectedIndex]){this._mapModel.setMapType(type)}},_onModelMapTypeChanged:function(aEvent){var data=aEvent.getData();var type=this._mapModel.getMapType();if(this._mapType.getSelectionIndex()!==this._mapNameMappings[data]){this._ignoreTypeSelectedEvent=true;this._mapType.setSelectionIndex(this._mapNameMappings[type])}},_onColorSelected:function(aEvent){var _color=this._mapModel.getColor();if((_color===this._colorMappings[1]||_color===this._colorMappings[2])&&!this._currentColorDay){this._mapModel.setColor(this._colorMappings[0])}else{if(this._currentColorDay&&_color===this._colorMappings[0]){this._mapModel.setColor(this._colorMappings[1])}}},_onModelColorChanged:function(aEvent){var _color=aEvent.getData();if((_color===this._colorMappings[1]||_color===this._colorMappings[2])&&this._currentColorDay){this._dayButton.setText(this._ON);this._dayButton.getReplica().addCssClass(this._ON_CLASS_NAME);this._currentColorDay=false}else{if(_color===this._colorMappings[0]&&!this._currentColorDay){this._dayButton.setText(this._OFF);this._dayButton.getReplica().removeCssClass(this._ON_CLASS_NAME);this._currentColorDay=true}}if(this._spiceManager._localizer){this._spiceManager._localizer.traverse(this._dayButton.getRootElement())}},_onLandmarksSelected:function(aEvent){this._mapModel.setLandmarksVisible(this._mapModel.getLandmarksVisible()?false:true)},_onModelLandmarksChanged:function(aEvent){var _landmarkOn=aEvent.getData()=="visible";if(_landmarkOn){this._landmarksButton.setText(this._ON);this._landmarksButton.getReplica().addCssClass(this._ON_CLASS_NAME);this._currentLandmarksVisible=true}else{this._landmarksButton.setText(this._OFF);this._landmarksButton.getReplica().removeCssClass(this._ON_CLASS_NAME);this._currentLandmarksVisible=false}if(this._spiceManager._localizer){this._spiceManager._localizer.traverse(this._landmarksButton.getRootElement())}},serialize:function(aPersistence){try{aPersistence.addData("ColorSettings",this._colorNameMappings[this._mapModel.getColor()]);aPersistence.addData("LandmarksSettings",this._currentLandmarksVisible?"1":"0")}catch(err){}},deserialize:function(aPersistence){var colorNum="0";var landmarksOn="0";try{colorNum=aPersistence.getData("ColorSettings")||"0";landmarksOn=aPersistence.getData("LandmarksSettings")||"0"}catch(err){colorNum="0";landmarksOn="0"}var color=this._mapModel.getColor();if(color!==this._colorNameMappings[colorNum]){this._mapModel.setColor(this._colorMappings[colorNum])}var currentLandmarksVisible=this._mapModel.getLandmarksVisible()?"1":"0";if(currentLandmarksVisible!==landmarksOn){this._mapModel.setLandmarksVisible((landmarksOn==="0")?false:true)}}});MaemoSettingsSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({Settings:'<div><div id="settingsButton"></div><div id="settingsDialog"></div></div>',Button:'<div class="nmp_maemoSettingsIcon"><div class="nmp_maemoSettingsIconBL"></div><div class="nmp_maemoSettingsIconBR"></div><div id="button" class="nmp_maemoSettingsIconIcon"></div></div>',Dialog:'<div class="nmp_maemoSettingsDialog"><div class="nmp_maemoSettingsLT"></div><div class="nmp_maemoSettingsRT"></div><div class="nmp_maemoSettingsLB"></div><div class="nmp_maemoSettingsRB"></div><div id="settingsmenu"></div><div id="closeButton"></div></div>',Menu:'<div class="nmp_maemoSettingsMenu"><div id="TypeSelector"></div><div id="ColorDayButton"></div><div id="LandmarksButton"></div><div class="nmp_maemoSettingsClear"></div></div>',TypeSelector:'<div class="nmp_maemoSettingsTypeSelector"></div>',NormalButton:'<div class="nmp_maemoSettingsButton nmp_maemoSettingsMap"><div id="button"></div></div>',SatelliteButton:'<div class="nmp_maemoSettingsButton nmp_maemoSettingsSatellite"><div id="button"></div></div>',TerrainButton:'<div class="nmp_maemoSettingsButton nmp_maemoSettingsTerrain"><div id="button"></div></div>',ColorDayButton:'<div class="nmp_maemoSettingsButton nmp_maemoSettingsDay"><div class="icon"></div><div class="text" id="button"></div></div>',LandmarksButton:'<div class="nmp_maemoSettingsButton nmp_maemoSettingsLandmarks"><div class="icon"></div><div class="text" id="button"></div></div>',CloseButton:'<div class="nmp_maemoSettingsClose"><div id="button"></div></div>'});var MaemoInfoBarSpice=new Class({Name:"MaemoInfoBarSpice",Extends:InfoPlacard,Implements:[EventSource],_metresLabel:"__I18N_mapPlayer_25_mapControl_scale_txt_metres__",_kilometresLabel:"__I18N_mapPlayer_26_mapControl_scale_txt_kilometres__",_xDelta:5,_yDelta:5,_eventCount:0,_isAddWaypointMode:false,initialize:function(aSpiceManager,aMapModel,aZoomModel,aPositionModel){this._super(aSpiceManager,aMapModel,aZoomModel);this._position=aPositionModel;this._publicMethods=["setMainInfo","setAdditionalInfo","setDistanceInfo","updateDistanceInfo","getMainInfo","getAdditionalInfo","getSelectedMapObject"];this._mapModel=aMapModel;aMapModel.addEventHandler(MapModel.EVENT_ANIMATION_DONE,this._onMapMoved,this);aMapModel.addEventHandler(MapModel.EVENT_DRAG_START,this._onDragStart,this);aMapModel.addEventHandler(MapModel.EVENT_DRAG_DONE,this._onDragDone,this);aMapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._onMapMoved,this);aMapModel.addEventHandler(MapModel.EVENT_MAPOBJECT_SELECTED,this._onMapObjectSelected,this);aMapModel.addEventHandler(MapModel.EVENT_MEASUREMENT_TYPE_CHANGED,this.updateDistanceInfo,this);aMapModel.addEventHandler(MapModel.EVENT_MOVE_DONE,this._onMapMoved,this);aMapModel.addEventHandler(MapModel.EVENT_LAYERS_CHANGED,this._onLayerChanged,this);this._selected=null;this._iconImage=null},setMainInfo:function(aText){this.setTitle(aText)},getMainInfo:function(){return this.getTitle()},setAdditionalInfo:function(aText){this.setDescription(aText)},getAdditionalInfo:function(){return this.getDescription()},setDistanceInfo:function(aText){},updateDistanceInfo:function(){},_createUi:function(){var infoBarContainer=new Container("InfoBarContainer",MaemoInfoBarSpice.TemplateLibrary);this._infoBar=new Button(MaemoInfoBarSpice.TemplateLibrary.getTemplate("InfoBar"));this._infoBar.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._onMouseDownInfoBar);this._infoBar.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_UP,this,this._onMouseUpInfoBar);this._infoBar.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_OUT,this,this._onMouseOutInfoBar);this._infoBar.addEventHandler("selected",this._infoBarClicked,this);this._connectMenuIcon=new Button(MaemoInfoBarSpice.TemplateLibrary.getTemplate("ConnectMenuIcon"));this._connectMenuIcon.getReplica().addEventHandler(nokia.aduno.dom.XNode.DOM_MOUSE_DOWN,this,this._onMouseDownIcon);this._connectMenuIcon.addEventHandler("selected",this._connectMenuIconClicked,this);this._titleLabel=new Label(MaemoInfoBarSpice.TemplateLibrary.getTemplate("MainInfoLabelMaemo"),"");this._descLabel=new Label(MaemoInfoBarSpice.TemplateLibrary.getTemplate("AdditionalInfoLabelMaemo"),"");this._fadder=new Container("Fadder",MaemoInfoBarSpice.TemplateLibrary);infoBarContainer.setChildAt(this._titleLabel,"mainInfo");infoBarContainer.setChildAt(this._descLabel,"additionalInfo");infoBarContainer.setChildAt(this._infoBar,"infoBar");infoBarContainer.setChildAt(this._fadder,"fadder");infoBarContainer.setChildAt(this._connectMenuIcon,"connectMenuIcon");infoBarContainer.show();this._infoBarContainer=infoBarContainer;var self=this;window.setTimeout(nokia.aduno.utils.bind(self,self._onMapMoved),1000);return infoBarContainer},_onMouseDownInfoBar:function(aEvent){this._infoBarContainer.getReplica().addCssClass("nm_MouseDown")},_onMouseUpInfoBar:function(aEvent){if(!this._isAddWaypointMode){this._infoBarContainer.getReplica().removeCssClass("nm_MouseDown")}},_onMouseOutInfoBar:function(aEvent){this._infoBarContainer.getReplica().removeCssClass("nm_MouseDown")},_infoBarClicked:function(){if(!this._isAddWaypointMode){this.fireEvent(new nokia.aduno.utils.Event(MaemoInfoBarSpice.INFOBAR_CLICKED,null))}},_onMouseDownIcon:function(aEvent){aEvent.stopPropagation()},_connectMenuIconClicked:function(){var selectedPosition=this._mapModel.getMapCenterPosition();var title="";var description="";if(this._titleLabel.isVisible()){title=this.getMainInfo()}if(this._descLabel.isVisible()){description=this.getAdditionalInfo()}this.fireEvent(new nokia.aduno.utils.Event(MaemoInfoBarSpice.MENUICON_CLICKED,{position:selectedPosition,title:title,description:description}))},_onMapObjectSelected:function(aSelectEvent){this._selected=aSelectEvent.getData();if(this._selected){this._selected.addEventHandler(MapObject.EVENT_OBJECT_PROPERTY_CHANGED,this._onMarkerPropertyChanged,this);this._mapModel.moveTo(this._selected.getPosition())}},getSelectedMapObject:function(){return this._selected},_onMarkerPropertyChanged:function(aPropertyChangedEvent){var data=aPropertyChangedEvent.getData();var marker=aPropertyChangedEvent.source;if(marker.isVisible()&&this._isPositionInCenter(marker.getPosition())){switch(data.property){case"infoDescription":this.setAdditionalInfo(data.value);break;case"position":if(!this._isPositionInCenter(data.value)){this._working=false;this._mapModel.moveTo(this._mapModel.toGeo())}break;case"location":var position={longitude:data.value.longitude,latitude:data.value.latitude};if(!this._isPositionInCenter(position)){this._working=false;this._mapModel.moveTo(this._mapModel.toGeo())}break}}},_onDragStart:function(){this._mapModel.removeEventHandler(MapModel.EVENT_MOVE_DONE,this._onMapMoved,this)},_onDragDone:function(){this._onMapMoved();this._mapModel.addEventHandler(MapModel.EVENT_MOVE_DONE,this._onMapMoved,this)},_onMapMoved:function(){if(!this._working){this._working=true;this._mapModel.reverseGeoCode(this._mapModel.toGeo(),bind(this,this._onMoveHandler))}},_onLayerChanged:function(aEvent){if(this._selected){if(this._selected.getLayer()===aEvent.data.layer){this._onMapMoved()}}else{this._onMapMoved()}},_onMoveHandler:function(aMapLocation){var location=this._computeAddressText(aMapLocation);var _center=this._mapModel.getMapCenterPosition();var mapObjects=this._mapModel.getMapMarkersAt(_center);if(mapObjects.length>0){this._selected=this._mapModel.getClosestPoi(_center,mapObjects);var _mapCenter=this._mapModel.toPixel(_center);var _poiCenter=this._mapModel.toPixel(this._selected.getLocationStructure());if(_mapCenter.getX()!=_poiCenter.getX()||_mapCenter.getY()!=_poiCenter.getY()){this._mapModel.setMapCenterPosition(this._selected.getLocationStructure())}this.fireEvent(new nokia.aduno.utils.Event(MaemoInfoBarSpice.MAPOBJECT_SELECTED,this._selected))}else{if(this._selected){this.fireEvent(new nokia.aduno.utils.Event(MaemoInfoBarSpice.MAPOBJECT_UNSELECTED,this._selected))}this._selected=null}if(this._selected){var title=this._selected.getInfoTitle();var description=this._selected.getInfoDescription();if(description){this.setAdditionalInfo(description)}else{this.setAdditionalInfo(location.completeAddress)}if(title){this.setMainInfo(title)}else{this.setMainInfo(location.mainPart)}}else{if(!location.mainPart&&!location.additionalPart){this.setMainInfo(Units.getReadableLatLonPosition(_center));this.setAdditionalInfo("")}else{this.setMainInfo(location.mainPart);this.setAdditionalInfo(location.additionalPart)}}this._working=false},_computeAddressText:function(aMapLocation){var zoomStep=this._zoomModel.getStep();var result={mainPart:"",additionalPart:"",completeAddress:""};var street=aMapLocation?aMapLocation.ADDR_STREET_NAME:null;var houseNumber=aMapLocation?aMapLocation.ADDR_HOUSE_NUMBER:null;var city=aMapLocation?aMapLocation.ADDR_CITY_NAME:null;var country=aMapLocation?aMapLocation.ADDR_COUNTRY_NAME:null;var place=aMapLocation?aMapLocation.PLACE_NAME:null;var fragments=[];if(aMapLocation){if(zoomStep>=14){if(country){fragments.push(country);result.mainPart=country}}else{if(zoomStep>=10&&zoomStep<=13){if(city){fragments.push(city);result.mainPart=city}if(country){fragments.push(country);if(result.mainPart===""){result.mainPart=country}else{result.additionalPart=country}}}else{if(zoomStep>=0&&zoomStep<=9){if(street){var streetAndNum=street+(houseNumber?" "+houseNumber:"");fragments.push(streetAndNum);result.mainPart=streetAndNum}if(city){fragments.push(city);if(result.mainPart===""){result.mainPart=city}else{result.additionalPart=city}}if(country){fragments.push(country);if(result.mainPart===""){result.mainPart=country}else{result.additionalPart=city?(city+", "+country):country}}}}}}result.completeAddress=(fragments.length>0)?fragments.join(", "):this._formatCoordinatesValue(this._mapModel.toGeo());return result},_computeDistanceText:function(){var distance=this._calculateDistance();return distance?distance:""},_calculateDistance:function(){var currentPosition=null;if(this._position.isLivePositioningData()){currentPosition=this._position.getPosition()}if(currentPosition&&currentPosition.latitude&&currentPosition.longitude){var currentGeo=this._mapModel.toGeo(currentPosition);var distance=currentGeo.distance(this._mapModel.toGeo());distance=Units.toString(Units.getReadableDistance(distance,this._mapModel.getMeasurementType()));return distance}},_isPositionInCenter:function(aGeoPosition){var positionPx=this._mapModel.geoToPixel(aGeoPosition);var mapCenterPx=this._mapModel.geoToPixel(this._mapModel.getMapCenterPosition());return(positionPx.x>=(mapCenterPx.x-this._xDelta)||positionPx.x<=(mapCenterPx.x+this._xDelta))&&(positionPx.y>=(mapCenterPx.y-this._yDelta)||positionPx.y<=(mapCenterPx.y+this._yDelta))},hide:function(){this._spiceControl.hide()},show:function(){this._spiceControl.show()},setDefaultStyle:function(){if(this._isAddWaypointMode){}else{this._connectMenuIcon.getReplica().removeCssClass("nmp_maemoIBAddWaypointIcon");this._connectMenuIcon.getReplica().removeCssClass("nmp_maemoIBDeleteWaypointIcon");this._connectMenuIcon.getReplica().removeCssClass("nmp_maemoIBConnectMenuIcon");this._infoBar.getReplica().addCssClass("nmp_maemoIB");this.getUi().getReplica().removeCssClass("nmp_SelectWaypointOffset")}},setDetailsStyle:function(){if(this._isAddWaypointMode){}else{this._connectMenuIcon.getReplica().removeCssClass("nmp_maemoIBAddWaypointIcon");this._connectMenuIcon.getReplica().removeCssClass("nmp_maemoIBRemoveWaypointIcon");this._connectMenuIcon.getReplica().addCssClass("nmp_maemoIBConnectMenuIcon");this._infoBar.getReplica().addCssClass("nmp_maemoIB");this.getUi().getReplica().removeCssClass("nmp_SelectWaypointOffset")}},setAddWaypointMode:function(aEnable,aOffset){if(aEnable){this._isAddWaypointMode=true;this._connectMenuIcon.getReplica().removeCssClass("nmp_maemoIBConnectMenuIcon");this._connectMenuIcon.getReplica().removeCssClass("nmp_maemoIBRemoveWaypointIcon");this._connectMenuIcon.getReplica().addCssClass("nmp_maemoIBAddWaypointIcon");this._infoBar.getReplica().removeCssClass("nmp_maemoIB");if(aOffset){this.getUi().getReplica().addCssClass("nmp_SelectWaypointOffset")}else{this.getUi().getReplica().removeCssClass("nmp_SelectWaypointOffset")}}else{this._isAddWaypointMode=false;this.setDefaultStyle()}},isAddWaypointMode:function(){return this._isAddWaypointMode},isVisible:function(){if(this._spiceControl){return this._spiceControl.isVisible()}return false}});MaemoInfoBarSpice.INFOBAR_CLICKED="infobarClicked";MaemoInfoBarSpice.MENUICON_CLICKED="menuClicked";MaemoInfoBarSpice.MAPOBJECT_SELECTED="selectedMapObject";MaemoInfoBarSpice.MAPOBJECT_UNSELECTED="unselectedMapObject";MaemoInfoBarSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({InfoBarContainer:'<div class="nmp_maemoIBContainer"><div class="nmp_maemoIBLT"></div><div class="nmp_maemoIBRT"></div><div class="nmp_maemoIBLB"></div><div class="nmp_maemoIBRB"></div><div class="nmp_maemoIBAddressContainer"><div id="mainInfo"></div><div id="additionalInfo"></div></div><div id="fadder"></div><div id="infoBar"></div><div class="nmp_maemoIBConnectMenu"><div id="connectMenuIcon"></div></div></div>',InfoBar:'<div class="nmp_maemoIB" id="button"></div>',MainInfoLabelMaemo:'<div class="nmp_maemoIBTitle" id="label"></div>',AdditionalInfoLabelMaemo:'<div class="nmp_maemoIBDescription" id="label"></div>',ConnectMenuIcon:'<div class="nmp_maemoIBConnectMenuIcon" id="button"></div>',Fadder:'<div class="nmp_maemoIBFadder"></div>'});var MaemoPositionSpice=new Class({Name:"MaemoPositionSpice",Extends:Spice,_publicMethods:["moveToPosition"],_iconSize:70,initialize:function(aSpiceManager,aMapModel,aPositionModel,aZoomModel){this._spiceManager=aSpiceManager;this._mapModel=aMapModel;this._positionModel=aPositionModel;this._zoomModel=aZoomModel;this._position=null;this._mapModel.addEventHandler(MapModel.EVENT_ANIMATION_DONE,this._drawPositionButton,this);this._mapModel.addEventHandler(MapModel.EVENT_POSITION_CHANGED,this._drawPositionButton,this);this._mapModel.addEventHandler(MapModel.EVENT_ZOOMSCALE,this._drawPositionButton,this);this._mapModel.addEventHandler(MapModel.EVENT_TILT,this._drawPositionButton,this);this._mapModel.addEventHandler(MapModel.EVENT_ORIENTATION,this._drawPositionButton,this);this._positionModel.addEventHandler(PositionModel.EVENT_POSITION,this._drawPositionButton,this);this._positionModel.addEventHandler(PositionModel.EVENT_PROVIDER,this._drawPositionButton,this)},_createUi:function(){this._positionContainer=new Container("Position",MaemoPositionSpice.TemplateLibrary);this._positionButton=new Button("Button");this._positionButton.addEventHandler("selected",this.moveToPosition,this);this._positionContainer.setChildAt(this._positionButton,"positionButton");this._positionContainer.hide();return this._positionContainer},onAttach:function(){var canvas=nokia.aduno.dom.Dimensions.getCoordinates(this._mapModel._pluginControl.getRootElement());this._screenWidth=canvas.width;this._screenHeight=canvas.height;this._drawPositionButton()},moveToPosition:function(){this._updatePosition();if(this._position){this._mapModel.moveTo(this._position)}},_updatePosition:function(){if(this._positionModel&&this._positionModel.isLivePositioningData()){this._position=this._positionModel.getPosition()}else{this._position=null}},_drawPositionButton:function(){this._updatePosition();var centerPosition=this._mapModel.toGeo();var gpsPosition=this._mapModel.toGeo(this._position);if(!this._shouldBeVisible(centerPosition,gpsPosition)){if(this._positionContainer.isVisible()){this._hide()}return}var angle=this._calculateAngle(centerPosition,gpsPosition);var step=Math.ceil(((345+angle)%360)/30);if(step>11){step=0}var row=Math.floor(step/6);var column=Math.floor(step%6);this._positionButton.getReplica().setStyle("button","background-position",(-this._iconSize*column)+"px "+(-this._iconSize*row)+"px");if(!this._positionContainer.isVisible()){this._show()}},_calculateAngle:function(aCenterPosition,aGpsPosition){var centerLong=aCenterPosition.getLongitude()+180;var gpsLong=aGpsPosition.getLongitude()+180;var centerLat=aCenterPosition.getLatitude()+90;var gpsLat=aGpsPosition.getLatitude()+90;gpsLong-=centerLong;gpsLat-=centerLat;var angle=Math.ceil(Math.atan(gpsLat/gpsLong)*180/Math.PI);if(angle>=0){if(gpsLong>0){angle=90-angle}else{angle=270-angle}}else{if(gpsLat>0){angle=270+Math.abs(angle)}else{angle=90+Math.abs(angle)}}angle=(360-this._mapModel.getOrientation()+angle)%360;return angle},_show:function(){if(this._showEffect){return}var self=this;this._showEffect=new nokia.aduno.medosui.Fx(this._positionButton);var replica=this._positionButton.getReplica();replica.setStyle(TemplateReplica.ROOT_ID,"opacity","0");this._spiceControl.show();this._showEffect.addEventHandler("ended",function(){self._showEffect=null;replica.setStyle(TemplateReplica.ROOT_ID,"opacity","1")},self);this._showEffect.effect({duration:500,styles:{opacity:[0,1]},fps:60,transition:"normal"}).start()},_hide:function(){if(this._hideEffect){return}var self=this;this._hideEffect=new nokia.aduno.medosui.Fx(this._positionButton);var replica=this._positionButton.getReplica();this._hideEffect.addEventHandler("ended",function(){self._hideEffect=null;replica.setStyle(TemplateReplica.ROOT_ID,"opacity","0");self._spiceControl.hide()},self);this._hideEffect.effect({duration:500,styles:{opacity:[1,0]},fps:60,transition:"normal"}).start()},_shouldBeVisible:function(aCenterPosition,aGpsPosition){if(!this._position||aGpsPosition.equals(aCenterPosition)){return false}var gpsPixels=this._mapModel.geoToPixel(this._position);if(gpsPixels){if(gpsPixels.x<=0||gpsPixels.x>=this._screenWidth||gpsPixels.y<=0||gpsPixels.y>=this._screenHeight){return true}else{if(!this._spicesDimensionsInitialized){this._getSpicesDimensions()}if(this._spicesDimensionsInitialized){if(this._isPointInRectangle(gpsPixels,this._settingSpiceDim)||this._isPointInRectangle(gpsPixels,this._orientationSpiceDim)||this._isPointInRectangle(gpsPixels,this._zoomSpiceDim)||this._isPointInRectangle(gpsPixels,this._infobarSpiceDim)){return true}}return false}}return true},_getSpicesDimensions:function(){var spice=null;var control=null;var dim=null;spice=this._spiceManager.getSpice("MaemoSettingsSpice");if(!spice){return}control=spice.getUi().getChildAt("settingsButton").getReplica().getElement("button");if(!control){return}dim=nokia.aduno.dom.Dimensions.getCoordinates(control);if(dim.left===0&&dim.top===0&&dim.width===0&&dim.height===0){return}else{this._settingSpiceDim=dim}spice=this._spiceManager.getSpice("OrientationTiltSpice");if(!spice){return}control=spice.getUi().getChildAt("compass").getReplica().getElement("button");if(!control){return}dim=nokia.aduno.dom.Dimensions.getCoordinates(control);if(dim.left===0&&dim.top===0&&dim.width===0&&dim.height===0){return}else{this._orientationSpiceDim=dim}spice=this._spiceManager.getSpice("ZoomSpice");if(!spice){return}control=spice.getUi().getReplica().getRootElement();if(!control){return}dim=nokia.aduno.dom.Dimensions.getCoordinates(control);if(dim.left===0&&dim.top===0&&dim.width===0&&dim.height===0){return}else{this._zoomSpiceDim=dim}spice=this._spiceManager.getSpice("MaemoInfoBarSpice");if(!spice){return}control=spice.getUi().getReplica().getRootElement();if(!control){return}dim=nokia.aduno.dom.Dimensions.getCoordinates(control);if(dim.left===0&&dim.top===0&&dim.width===0&&dim.height===0){return}else{this._infobarSpiceDim=dim}this._spicesDimensionsInitialized=true},_isPointInRectangle:function(aPoint,aRectangle){return aPoint.x>=aRectangle.left&&aPoint.x<(aRectangle.left+aRectangle.width)&&aPoint.y>=aRectangle.top&&aPoint.y<(aRectangle.top+aRectangle.height)},addCustomStyle:function(aCustomStyle){this._positionButton.getReplica().addCssClass(aCustomStyle)},removeCustomStyle:function(aCustomStyle){this._positionButton.getReplica().removeCssClass(aCustomStyle)}});MaemoPositionSpice.TemplateLibrary=new nokia.aduno.dom.TemplateLibrary({Position:'<div id="positionButton"></div>',Button:'<div class="nmp_maemoPositionButton"><div class="nmp_maemoPositionIconBL"></div><div class="nmp_maemoPositionIconBR"></div><div id="button" class="nmp_maemoPositionButtonIcon"></div></div>'});var NextManeuverSpice=new Class({Name:"NextManeuverSpice",Extends:Spice,ICON_SIZE:1,NEXT_MVR_COUNTDWN_THRESHOLD:10,_guidance:null,_position:null,_map:null,_container:null,_maneuverArrivalBar:null,initialize:function(aSpiceManager,aTranslator,aModels){this._super(aSpiceManager,aTranslator);this._guidance=aModels.guidance;this._position=aModels.position;this._map=aModels.map;this._guidance.addEventHandler(GuidanceModel.EVENT_ON_NEXT_MANEUVER_CHANGED,this._onManeuver,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STARTED,this._onGuidanceStarted,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STOPPED,this._onGuidanceStopped,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_DONE,this._onGuidanceStopped,this)},_createUi:function(){var library=null;if(layout.touch){library=NextManeuverSpice.TouchNextManeuverSpiceTemplateLibrary;this.ICON_SIZE=70}else{library=NextManeuverSpice.SncNextManeuverSpiceTemplateLibrary;this.ICON_SIZE=48}this._container=new Container("NextManeuverContainer",library);this._container.hide();this._maneuverArrivalBar=new ProgressBar("ProgressBar",null,true);this._container.setChildAt(this._maneuverArrivalBar,"progressBar",true,false);return this._container},_onPositionChanged:function(aEvent){var data=aEvent.getData();this._updateGuidanceInfo();this._updateArrivalToManeuverBar()},_onGuidanceStarted:function(aEvent){this._updateGuidanceInfo();this._container.show();this._position.addEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this)},_onGuidanceStopped:function(aEvent){this._position.removeEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);this._container.hide()},_onManeuver:function(aEvent){var nextManeuver=this._guidance.getNextManeuver();if(nextManeuver!==null){var streetName=nextManeuver.getNextStreetName();if(!streetName){streetName=nextManeuver.getStreetName()}this._container.getReplica().setText("streetNameLabel",streetName);var index=nextManeuver.getIconIndex();this._container.getReplica().setStyle("icon","background-position","-"+index*this.ICON_SIZE+"px 0")}else{this._container.getReplica().setText("streetNameLabel","No next maneuver")}},_updateGuidanceInfo:function(){var distance=this._guidance.getNextManeuverDistance();var distanceObj=Units.getReadableDistance(distance,this._map.getMeasurementType());var distanceValue=distanceObj.value;var distanceUnit=distanceObj.unit;if(distance<0||!distanceObj||distanceValue===undefined||distanceUnit===undefined){distanceValue="";distanceUnit=""}this._container.getReplica().setText("distanceLabelValue",distanceValue);this._container.getReplica().setText("distanceLabelUnit",this.translateString(distanceUnit))},_updateNextManeuverIcon:function(aManeuver){},_updateArrivalToManeuverBar:function(){var currentSpeed=this._position.getMovementSpeed();var distance=this._guidance.getNextManeuverDistance();var timeToNextManeuver=Math.round(distance/currentSpeed);var nextManeuver=this._guidance.getNextManeuver();if(nextManeuver!==null&&timeToNextManeuver<this.NEXT_MVR_COUNTDWN_THRESHOLD){this._maneuverArrivalBar.setMaximum(this.NEXT_MVR_COUNTDWN_THRESHOLD);this._maneuverArrivalBar.setValue(this.NEXT_MVR_COUNTDWN_THRESHOLD-timeToNextManeuver)}else{this._maneuverArrivalBar.setValue(0)}}});NextManeuverSpice.SncNextManeuverSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({NextManeuverContainer:'<div id="nextManeuverContainer" class="nmp_NextManeuverContainerCenter"><div class="nmp_NextManeuverContainer"><div id="progressBar"></div><div id="icon" class="nmp_NextManeuverIcon"></div><div id="labelContainer" class="nmp_NextManeuverLabelContainer"><div id="streetNameLabel" class="nmp_NextManeuverStreetName"></div><div id="distanceLabel" class="nmp_NextManeuverDistance"><span id="distanceLabelValue" class="nmp_NextManeuverValue"></span><span id="distanceLabelUnit" class="nmp_NextManeuverUnit"></span></div></div></div></div>',ProgressBar:'<div class="nmp_NextManeuverProgressBar"><div id="progress" class="nmp_NextManeuverProgressBar_progress"></div></div>'});NextManeuverSpice.TouchNextManeuverSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({NextManeuverContainer:'<div id="nextManeuverContainer" class="nmp_NextManeuverContainerCenterAligner"><div class="nmp_NextManeuverContainer"><div class="nmp_NextManeuverContainerLeft"/><div class="nmp_NextManeuverContainerCenter"><div id="progressBar"></div><div id="icon" class="nmp_NextManeuverIcon"></div><div id="labelContainer" class="nmp_NextManeuverLabelContainer"><div id="streetNameLabel" class="nmp_NextManeuverStreetName"></div><div id="distanceLabel" class="nmp_NextManeuverDistance"><span id="distanceLabelValue" class="nmp_NextManeuverValue"/><span id="distanceLabelUnit" class="nmp_NextManeuverUnit"/></div></div></div><div class="nmp_NextManeuverContainerRight"/></div></div>',ProgressBar:'<div class="nmp_NextManeuverProgressBar"><div id="progress" class="nmp_NextManeuverProgressBar_progress"></div></div>'});var GuidanceProgressSpice=new Class({Name:"GuidanceProgressSpice",Extends:Spice,_guidance:null,_position:null,_map:null,_container:null,initialize:function(aSpiceManager,aTranslator,aModels){this._super(aSpiceManager,aTranslator);this._guidance=aModels.guidance;this._position=aModels.position;this._map=aModels.map;this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STARTED,this._onGuidanceStarted,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STOPPED,this._onGuidanceStopped,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_DONE,this._onGuidanceStopped,this)},_createUi:function(){var library=layout.snc?GuidanceProgressSpice.GuidanceProgressSpiceTemplateLibrary:GuidanceProgressSpice.TouchGuidanceProgressSpiceTemplateLibrary;this._container=new Container("GuidanceProgressContainer",library);if(layout.snc){this._routeProgress=new ProgressBar();this._container.setChildAt(this._routeProgress,"progressBar",false,true)}this._container.hide();return this._container},_onPositionChanged:function(aEvent){var data=aEvent.getData();this._updateGuidanceProgress()},_onGuidanceStarted:function(aEvent){this._position.addEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);this._currentRoute=aEvent.getData().route;if(layout.snc){this._routeProgress.setValue(0);this._routeProgress.setMaximum(this._currentRoute.getLength())}this._updateGuidanceProgress();this._container.show()},_onGuidanceStopped:function(aEvent){this._position.removeEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);this._container.hide();this._currentRoute=null},_updateGuidanceProgress:function(){var imperialUnits=this._map.getMeasurementType();var currentSpeed=Units.getReadableSpeed(this._position.getMovementSpeed(),imperialUnits,true);var currentSpeedUnit=currentSpeed.unit;var currentSpeedValue=currentSpeed.value;if(!currentSpeed||currentSpeedUnit===undefined||currentSpeedValue===undefined){currentSpeedUnit="";currentSpeedValue=""}var currentDestinationDistance=Units.getReadableDistance(this._guidance.getDistanceToDestination(),imperialUnits);var currentDestinationDistanceValue=currentDestinationDistance.value;var currentDestinationDistanceUnit=currentDestinationDistance.unit;if(!currentDestinationDistance||currentDestinationDistanceValue===undefined||currentDestinationDistanceUnit===undefined){currentDestinationDistanceValue="";currentDestinationDistanceUnit=""}var elapsedDist=this._guidance.getElapsedDistance();if(elapsedDist&&layout.snc){this._routeProgress.setValue(elapsedDist)}var tta=Units.getReadableTime(this._guidance.getTimeToArrival());var ttaValue=tta.value;var ttaUnit=tta.unit;if(!tta||ttaValue===undefined||ttaUnit===undefined){ttaValue="";ttaUnit=""}this._container.getReplica().setText("labelSpeedValue",currentSpeedValue);this._container.getReplica().setText("labelSpeedUnit",this.translateString(currentSpeedUnit));this._container.getReplica().setText("labelDistanceValue",currentDestinationDistanceValue);this._container.getReplica().setText("labelDistanceUnit",this.translateString(currentDestinationDistanceUnit));this._container.getReplica().setText("labelTimeValue",ttaValue);this._container.getReplica().setText("labelTimeUnit",this.translateString(ttaUnit))}});GuidanceProgressSpice.GuidanceProgressSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({GuidanceProgressContainer:'<div id="nmp_GuidanceProgressContainerCenter" class="nmp_GuidanceProgressContainerCenter"><div  class="nmp_GuidanceProgressContainer"><div id="progressBar" class="nmp_GuidanceProgressProgressBar"></div><div class="nmp_GuidanceProgressSpeed"><span id="labelSpeedValue" class="nmp_GuidanceProgressValue"></span><span id="labelSpeedUnit" class="nmp_GuidanceProgressUnit"></span></div><div id="labelDistance" class="nmp_GuidanceProgressDistance"><span id="labelDistanceValue" class="nmp_GuidanceProgressValue"></span><span id="labelDistanceUnit" class="nmp_GuidanceProgressUnit"></span></div><div id="labelTime" class="nmp_GuidanceProgressEta"><span id="labelTimeValue" class="nmp_GuidanceProgressValue"></span><span id="labelTimeUnit" class="nmp_GuidanceProgressUnit"></span></div></div></div>',ProgressBar:'<div class="nmp_GuidanceProgressBar "><div id="progress" class="nmp_Progress" style="width: 60%;"><div class="nmp_Thumb"></div></div></div>'});GuidanceProgressSpice.TouchGuidanceProgressSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({GuidanceProgressContainer:'<div class="nmp_GuidanceProgress"><div id="nmp_GuidanceProgressContainerCenter" class="nmp_GuidanceProgressContainerCenter"><div  class="nmp_GuidanceProgressContainer"><div class="nmp_GuidanceProgressSpeed"><span id="labelSpeedValue" class="nmp_GuidanceProgressValue"></span><span id="labelSpeedUnit" class="nmp_GuidanceProgressUnit"></span></div><div class="nmp_GuidanceProgressSeparation"></div><div id="labelDistance" class="nmp_GuidanceProgressDistance"><span id="labelDistanceValue" class="nmp_GuidanceProgressValue"></span><span id="labelDistanceUnit" class="nmp_GuidanceProgressUnit"></span></div><div class="nmp_GuidanceProgressSeparation"></div><div id="labelTime" class="nmp_GuidanceProgressEta"><span id="labelTimeValue" class="nmp_GuidanceProgressValue"></span><span id="labelTimeUnit" class="nmp_GuidanceProgressUnit"></span></div></div></div></div>'});var TouchTestRouteSpiceLibrary=new TemplateLibrary({Container:'<div class="nmp_TestRouteButton"><div id="button" /></div>',ResizableButton:'<a class="nmp_ResizableButton" href="javascript:void(0)"><div class="nmp_Left"></div><div class="nmp_Center"><span id="button"></span></div><div class="nmp_Right"></div></a>'},DefaultTouchTemplateLibrary);var TouchTestRouteSpice=new Class({Name:"TouchTestRouteSpice",Extends:Spice,initialize:function(aSpiceManager,aModels){this._super(aSpiceManager);this._routing=aModels.routing},_createUi:function(){var container=new Container(null,TouchTestRouteSpiceLibrary);var testRouteButton=new Button("ResizableButton","Route");testRouteButton.addEventHandler("selected",this._createTestRoute,this);container.setChildAt(testRouteButton,"button");return container},_createTestRoute:function(){var route=new Route([new Waypoint({longitude:13.3843,latitude:52.5309}),new Waypoint({longitude:13.353,latitude:52.5161}),new Waypoint({longitude:13.3212,latitude:52.5149}),new Waypoint({longitude:13.2866,latitude:52.5103}),new Waypoint({longitude:13.3859,latitude:52.4749}),new Waypoint({longitude:13.3843,latitude:52.5309})]);this._routing.calculateRoute(route);this._routing.setCurrentRoute(route)}});var SncRouteSettingsSpice=new Class({Name:"SncRouteSettingsSpice",Extends:Spice,initialize:function(aSpiceManager,aModels){this._super(aSpiceManager);this._routeSettingsModel=aModels.routeSettings;this._routingModel=aModels.routing;this._guidance=aModels.guidance;this._application=aModels.application;this._mapModel=aModels.map;this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculationDone,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_ERROR,this._onRouteCalculationError,this);this._routingModel.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_PROGRESS,this._onRouteCalculationProgress,this);this._routingModel.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._onCurrentRouteChanged,this);this.getUi().hide();aSpiceManager.setKeyHandler(KeyEventManager.KEY_1,0,bind(this,this._handleKey))},_createUi:function(){this._menu=null;this._menu=new SettingsMenu("RouteSettingsMenu",SncRouteSettingsSpice.SncRouteSettingsSpiceTemplateLibrary,this._application);this._menu.hide();this._menu.addEventHandler("closed",this._hide,this);var transportSettings=new TransportationModeSettings(this._routeSettingsModel,this._routingModel);this._menu.addOptionMenu(transportSettings);var routeTypeSettings=new RouteTypeSettings(this._routeSettingsModel,this._routingModel);this._menu.addOptionMenu(routeTypeSettings);var blockerSettings=new BlockersSettings(this._routeSettingsModel);this._menu.addOptionMenu(blockerSettings);this._menu.setSelectedOption(0);return this._menu},_handleKey:function(aKeyEvent){if(aKeyEvent.keyDown&&aKeyEvent.getKey()==KeyEventManager.KEY_1){if(this._menu.isVisible()){this._hide()}else{this._show();this._adaptZoomToRoute()}}},_show:function(){this._menu.show();this._menu.setSelectedOption(0);this._application.pushSettings();if(this._routingModel.getCurrentRoute()){this._application.setButtonLabels("rsp.btnnavigate","rsp.btndone")}else{this._application.setButtonLabels("","rsp.btndone")}},_hide:function(aEvent){this._application.popSettings();this._menu.hide();this._adaptZoomToRoute();if(this._routingModel.getCurrentRoute()&&aEvent&&aEvent.getData().cancel===false){var simulate=!browser.s60;this._guidance.startNavigation(this._routingModel.getCurrentRoute(),simulate)}},_adaptZoomToRoute:function(){var currentRoute=this._routingModel.getCurrentRoute();if(currentRoute&&currentRoute.getLength()>0){var mapSize=this._mapModel.getMapSize();var mapHeight=mapSize.height;var mapWidth=mapSize.width;this._routingModel.zoomToRoute(currentRoute,this._application.getVisibleAreaRestriction(mapWidth,mapHeight))}},_onRouteCalculationDone:function(aEvent){if(!this._menu.isVisible()){this._show();this._adaptZoomToRoute()}},_onRouteCalculationError:function(aEvent){var eventData=aEvent.getData();if(eventData.errorCause==RoutingModel.ERROR_CAUSE_ROUTE_USES_DISABLED_ROADS){var disallowedString="";if(eventData.violatedOptions.allowDirtroads){disallowedString+="rsp.dirtroads"}if(eventData.violatedOptions.allowFerries){disallowedString+="rsp.ferries"}if(eventData.violatedOptions.allowHighways){disallowedString+="rsp.highways"}if(eventData.violatedOptions.allowTollroads){disallowedString+="rsp.tollroads"}if(eventData.violatedOptions.allowTunnels){disallowedString+="rsp.tunnels"}if(eventData.violatedOptions.transportationMode){disallowedString+="rsp.transmode"}if(eventData.violatedOptions.routeType){disallowedString+="rsp.routetype"}this._application.showMessageBox("rsp.noroute1","rsp.noroute2"+disallowedString+". "+disallowedString+"rsp.noroute3",this._onViolationsMsgBoxClose,this,["rsp.confirm",""],{errorCause:eventData.errorCause,violatedOptions:eventData.violatedOptions})}else{if(eventData.errorCause==RoutingModel.ERROR_CAUSE_CANNOT_DO_PEDESTRIAN){this._application.showMessageBox("rsp.nopedmode1","rsp.nopedmode2",this._onPedestrianRoutingErrorMsgBoxClose,this,["rsp.close",""])}else{this._application.showMessageBox("rsp.noroute21","rsp.noroute22",this._onRoutingErrorMsgBoxClose,this,["rsp.close",""])}}},_onRouteCalculationProgress:function(){if(!this.getUi().isVisible()){this._show()}},_onCurrentRouteChanged:function(aEvent){if(aEvent.getData().newRoute===null){this._hide()}},_onViolationsMsgBoxClose:function(aEvent){var errorCause=aEvent.getData().data.errorCause;var violatedOptions=aEvent.getData().data.violatedOptions;if(errorCause===RoutingModel.ERROR_CAUSE_ROUTE_USES_DISABLED_ROADS){if(violatedOptions.allowDirtroads){this._routeSettingsModel.setAllowUnpavedRoads(true)}if(violatedOptions.allowFerries){this._routeSettingsModel.setAllowFerries(true)}if(violatedOptions.allowHighways){this._routeSettingsModel.setAllowHighways(true)}if(violatedOptions.allowTollroads){this._routeSettingsModel.setAllowTollroads(true)}if(violatedOptions.allowTunnels){this._routeSettingsModel.setAllowTunnels(true)}}},_onPedestrianRoutingErrorMsgBoxClose:function(aEvent){this._routeSettingsModel.setTransportationMode(Route.TRANSPORTATION_MODE_CAR)},_onRoutingErrorMsgBoxClose:function(aEvent){this._routingModel.clearRoute(this._routingModel.getCurrentRoute())}});SncRouteSettingsSpice.SncRouteSettingsSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({RouteSettingsMenu:'<div class="nmp_RouteSettingsMenu"><div id="tabHeaders" class="nmp_RouteOptionsTabContainer"></div><div id="popupLists" class="nmp_RouteOptionsPopupLists"></div><div id="options" class="nmp_RouteSettingsMenuOptionContainer"></div></div>',RouteSettingsMenuOption:'<div class="nmp_RouteSettingsMenuOption"><div id="label" class="nmp_RouteOptionsLabel"></div><div id="items" class="nmp_RouteOptionValueList"></div></div>',RouteSettingsMenuOptionMulti:'<div class="nmp_RouteSettingsMenuOptionMulti"><div id="items" class="nmp_RouteOptionValueListMulti"></div></div>',SettingsMenuOptionsPopupListItemMultiCheck:'<div class="nmp_RouteOptionsPopupListItemMultiCheckButton"><div class="nmp_SettingsIcon" id="checkButtonButton"></div><div class="nmp_PopupListItemLabel" id="checkButtonText"></div></div>',SettingsMenuOptionsPopupList:'<div class="nmp_RouteOptionsPopupList"></div>',SettingsMenuOptionsPopupListItem:'<div class="nmp_RouteOptionsPopupListItem"><div id="popupListItemIcon" class="nmp_SettingsIcon"></div><div id="popupListItemLabel" class="nmp_PopupListItemLabel"></div></div>',SettingsMenuOptionsTab:'<div class="nmp_RouteOptionsTab"></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var SncWaypointSpice=new Class({Name:"SncWaypointSpice",Extends:Spice,_startButton:null,_endButton:null,_navigateButton:null,_stopoverButton:null,_waypointsList:null,_reverseGeoCoding:null,_routing:null,_position:null,_map:null,_application:null,_maneuversOn:false,_waypointItems:[],initialize:function(aSpiceManager,aModels){this._super(aSpiceManager);this._routing=aModels.routing;this._map=aModels.map;this._reverseGeoCoding=aModels.reverseGeoCoding;this._application=aModels.application;this._reverseGeoCoding.addEventHandler(ReverseGeoCodingModel.EVENT_REVERSE_GEOCODE_DONE,this._onReverseGeoCodeDone,this);this._routing.addEventHandler(RoutingModel.EVENT_CURRENT_ROUTE_CHANGED,this._onCurrentRouteChanged,this);this._routing.addEventHandler(RoutingModel.EVENT_ROUTE_CALCULATION_DONE,this._onRouteCalculated,this);this.getUi().hide()},_createUi:function(){this._waypointsDialog=this._createWaypointsDialog();this._waypointsDialog.getReplica().setText("routeLabelLeft","wps.routelabeleft");this._waypointsDialog.getReplica().setText("routeLabelRight","-- km / -- min");this._waypointsList=new KeyControlledList();this._waypointsList._addCssClass("nmp_WaypointList");this._waypointsList.addEventHandler(KeyControlledList.EVENT_CLOSE,this._onWaypointListClose,this);var waypointScroll=new Scrollable("WaypointScrollable");this._waypointsList.addBehavior(waypointScroll);this._startButton=new Container("WaypointListButtonItem");var startButton=new Button(null,"wps.setstartpoint");this._startButton.setChildAt(startButton,"button",false,true);this._startButton.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._endButton=new Container("WaypointListButtonItem");var endButton=new Button(null,"wps.adddestination");endButton.addEventHandler("selected",this._onAddDestination,this);endButton.getReplica().addCssClass("nmn_WaypointButton_LastItem");this._endButton.setChildAt(endButton,"button",false,true);this._endButton.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._stopoverButton=new Container("WaypointListButtonItem");var stopoverButton=new Button(null,"wps.addstopover");stopoverButton.addEventHandler("selected",this._onAddStopover,this);this._stopoverButton.getReplica().addCssClass("nmp_WaypointButton_LastItem");this._stopoverButton.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._stopoverButton.setChildAt(stopoverButton,"button",false,true);var waypointsListContainer=new Container("WaypointContainer");waypointsListContainer.setChildAt(this._waypointsList,"waypointList");this._waypointsDialog.setChildAt(waypointsListContainer,"waypointContainer");return this._waypointsDialog},_createWaypointsDialog:function(){this._waypointsDialog=new Container("WaypointDialog",SncWaypointSpice.SncWaypointSpiceTemplateLibrary);this._navigateButton=new MenuListItem("navigateNow","","swps.navigatenow",bind(this,this._onNavigateNow),"WaypointButton");this._navigateButton.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);return this._waypointsDialog},_setRouteInfo:function(aRouteLengthText,aRouteDurationText){this._waypointsDialog.getReplica().setText("routeLabelRight",aRouteLengthText+" / "+aRouteDurationText)},_onWaypointListClose:function(aEvent){this._hide()},_updateNavigateButton:function(aRoute){if(aRoute&&aRoute.isValid()){this._waypointsList.addChild(this._navigateButton)}},_onCurrentRouteChanged:function(aRouteChangeEvent){var newRoute=aRouteChangeEvent.getData().newRoute;var oldRoute=aRouteChangeEvent.getData().oldRoute;if(oldRoute){oldRoute.removeEventHandler(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,this._onWaypointsChanged,this)}if(newRoute){newRoute.addEventHandler(Route.EVENT_ROUTE_WAYPOINTS_CHANGED,this._onWaypointsChanged,this)}this._updateUi(newRoute)},_onWaypointsChanged:function(aEvent){var route=this._routing.getCurrentRoute();this._updateUi(route)},_handleKeys:function(aKeyEvent){if(aKeyEvent._originalEvent.type==="keypress"){var key=aKeyEvent.getKey();if(key===KeyEventManager.KEY_LSK){if(!this._maneuversOn){this._addManeuversToList();this._maneuversOn=true}else{this._removeManeuversFromList();this._maneuversOn=false}}}},_updateUi:function(aRoute){this._updateRouteInfo(aRoute);this._updateNavigateButton(aRoute);this._waypointsList.removeAllChildren();this._waypointItems=[];var routeWaypoints=[];if(aRoute){routeWaypoints=aRoute.getWaypoints()}if(routeWaypoints.length===0){this._waypointsList.addChild(this._startButton);this._waypointsList.addChild(this._endButton)}else{if(routeWaypoints.length===1&&routeWaypoints[0]&&routeWaypoints[0].getPosition()){this._waypointsList.addChild(this._createWaypointItem(routeWaypoints[0],0));this._waypointsList.addChild(this._endButton)}else{if(routeWaypoints.length===2&&!routeWaypoints[0]){this._waypointsList.addChild(this._createWaypointItem(new Waypoint(),0));this._waypointsList.addChild(this._createWaypointItem(routeWaypoints[1],1))}else{if(routeWaypoints.length>1){Collection.forEach(routeWaypoints,function(aWaypoint,aId){this._waypointsList.addChild(this._createWaypointItem(aWaypoint,aId))},this);this._waypointsList.addChild(this._stopoverButton)}}}}},_addManeuversToList:function(){var maneuvers=null;if(this._routing.getCurrentRoute()){maneuvers=this._routing.getCurrentRoute().getManeuvers()}if(maneuvers){for(var i=0;i<maneuvers.length-1;i++){if(maneuvers[i].getWaypointIndex()===null){var maneuverListItem=new ManeuverListItem(maneuvers[i],null,null,this._map);maneuverListItem.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);var indexInWaypointList=1+i;this._waypointsList.addChildAt(indexInWaypointList,maneuverListItem)}}}},_updateRouteInfo:function(aRoute){var routeLength=0;var routeDuration=0;if(aRoute){routeLength=aRoute.getLength();routeDuration=aRoute.getDuration()}var routeLengthTxt=Units.getReadableDistance(routeLength,this._map.getMeasurementType());var routeDurationTxt=Units.getReadableTime(routeDuration);if(routeLength===0){routeLengthTxt.value="--,--"}if(routeDuration===0){routeDurationTxt.value="--:--"}this._setRouteInfo(routeLengthTxt.value+" "+this.translateString(routeLengthTxt.unit),routeDurationTxt.value+" "+this.translateString(routeDurationTxt.unit))},_removeManeuversFromList:function(){for(var i=this._waypointsList.getChildCount()-1;i>=0;i--){var item=this._waypointsList.getChildAt(i);if(item.className==="ManeuverListItem"){this._waypointsList.removeChildAt(i)}}this._waypointsList.getChildAt(0).focus()},_createWaypointItem:function(aWaypoint,aIndex){var waypointItem=new WaypointListItem(aWaypoint,aIndex,"WaypointItem",null,this._spiceManager);waypointItem.addEventHandler(WaypointListItem.EVENT_WAYPOINT_SELECTED,this._onSelectWaypointItem,this);aWaypoint.itemIndex=aIndex;this._waypointItems[aWaypoint.itemIndex]=waypointItem;if(aWaypoint.getPosition()&&!aWaypoint.isReverseGeocoded()){this._reverseGeoCoding.findLocation(aWaypoint)}return waypointItem},_onNavigateNow:function(){},_onAddDestination:function(){},_onAddStopover:function(){},_onSelectWaypointItem:function(aEvent){var waypoint=aEvent.getData().waypoint;var index=aEvent.getData().index;var isDestinationWaypoint=false;if(index>0&&this._routing.getCurrentRoute().getWaypoints().length===(index+1)){isDestinationWaypoint=true}},_show:function(){this._updateUi(this._routing.getCurrentRoute());this._application.pushSettings();this._application.setButtonLabels("swps.directions","swps.map");this._application.setTitle("swps.routeplanner");var keyBind=bind(this,this._handleKeys);this._spiceManager.setKeyHandler(KeyEventManager.KEY_LSK,0,keyBind);this.getUi().show();this._focusWaypointsList()},_hide:function(){this._super();this._spiceManager.removeKeyHandler(KeyEventManager.KEY_LSK,0);this._application.popSettings();this.getUi().hide()},_focusWaypointsList:function(){if(this._waypointsList.getChildCount()>0){this._waypointsList.focusChild(0);this._waypointsList.focus()}},_onReverseGeoCodeDone:function(aEvent){var waypoint=aEvent.getData();if(waypoint){var waypointItem=this._waypointItems[waypoint.itemIndex];if(waypointItem){waypointItem.updateItem()}}},_onRouteCalculated:function(aRouteEvent){var eventData=aRouteEvent.getData();this._updateRouteInfo(eventData.route)}});SncWaypointSpice.SncWaypointSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({WaypointDialog:'<div class="nmp_WaypointsDialog"><div id="top" class="nmp_WaypointsDialog_Top"><div id="routeLabel" class="nmp_WaypointsDialog_TopLeft"></div><div id="routeLabelRight" class="nmp_WaypointsDialog_TopRight"></div></div><div id="waypointContainer"></div></div>',WaypointContainer:'<div class="nmp_Waypoints_Container"><div id="WaypointScrollable"><div id="waypointList"></div></div></div>',WaypointScrollable:'<div class="nmp_WaypointScrollable"></div>',WaypointList:'<div class="nmp_WaypointList"></div>',WaypointButton:'<div class="nmp_WaypointButton"></div>',WaypointListButtonItem:'<div class="nmp_WaypointsItem"><div class="nmp_Centered" id="button"></div></div>',WaypointItem:'<div class="nmp_WaypointsItem"><div id="icon" class="nmp_Icon"></div><div id="place" class="nmp_WaypointsItem_Label nmp_WaypointsItem_Place"></div><div id="street" class="nmp_WaypointsItem_Label nmp_WaypointsItem_Street"></div><div id="spinner"></div></div>'},nokia.aduno.medosui.DefaultSnCTemplateLibrary);var S60OptionsSpice=new Class({Name:"S60OptionsSpice",Extends:Spice,indexOf3dButton:0,initialize:function(aSpiceManager,aMapModel,aPfwPath){this._super(aSpiceManager);this._model=aMapModel;this._isVisible=false;this._categories={};this._layers={};this._pfwPath=aPfwPath;this._mapMappings={0:"normal",1:"satellite",2:"terrain"};this._mapNameMappings={normal:0,satellite:1,terrain:2};this._colorMappings={0:"day",1:"night",2:"auto"};this._colorNameMappings={day:0,night:1,auto:2};this.indexOf2dButton=1-this.indexOf3dButton},_createUi:function(){var binder=this;this.container=new Container("S60OptionsContainer",S60OptionsSpice.S60OptionsSpiceTemplateLibrary);this.menuList=new List("S60OptionsMenuSelector",null);var menuButtonMapView=new Button("S60OptionsMenuButton","Map Views");var menuButtonPoiList=new Button("S60OptionsMenuButton","Points of interest");this.menuList.addChild(menuButtonMapView);this.menuList.addChild(menuButtonPoiList);this.menuList.addEventHandler("selected",this._onMenuSelected,this);this.menuList.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this.mapViewContainer=new Container("S60OptionsMapViewContainer",S60OptionsSpice.S60OptionsSpiceTemplateLibrary);this.poiListContainer=new Container("S60OptionsPoiListContainer",S60OptionsSpice.S60OptionsSpiceTemplateLibrary);var mapTypeList=new SelectionList("S60MapTypeSelector",null,"nm_Selected");var normalButton=new Button("S60MapTypeNormalButton","Map");var satelliteButton=new Button("S60MapTypeSatelliteButton","Satellite");var terrainButton=new Button("S60MapTypeTerrainButton","Terrain");mapTypeList.addChild(normalButton);mapTypeList.addChild(satelliteButton);mapTypeList.addChild(terrainButton);mapTypeList.addEventHandler("selected",this._onTypeSelected,this);mapTypeList.setSelectionIndex(this._mapNameMappings[this._model.getMapType()]||0);mapTypeList.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);var mapTiltList=new SelectionList("S60MapTiltSelector",null,"nm_Selected");var tiltButton2d=new Button("S60OptionsButton","2D");var tiltButton3d=new Button("S60OptionsButton","3D");mapTiltList.addChild(tiltButton3d);mapTiltList.addChild(tiltButton2d);mapTiltList.addEventHandler("selected",this._onTiltSelected,this);mapTiltList.setSelectionIndex(this._model.getMode3d()?this.indexOf3dButton:this.indexOf2dButton);mapTiltList.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);var mapColorList=new SelectionList("S60MapColorSelector",null,"nm_Selected");var colorButtonDay=new Button("S60OptionsButton","Day mode");var colorButtonNight=new Button("S60OptionsButton","Night mode");mapColorList.addChild(colorButtonDay);mapColorList.addChild(colorButtonNight);mapColorList.addEventHandler("selected",this._onColorSelected,this);mapColorList.setSelectionIndex(this._colorNameMappings[this._model.getColor()]||0);mapColorList.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this.mapViewContainer.setChildAt(mapTypeList,"S60MapTypeSelector");this.mapViewContainer.setChildAt(mapTiltList,"S60MapTiltSelector");this.mapViewContainer.setChildAt(mapColorList,"S60MapColorSelector");this._poiScroll=new nokia.aduno.medosui.Scrollable("S60PoiListScrollable",S60OptionsSpice.S60OptionsSpiceTemplateLibrary);this._poiList=new nokia.aduno.medosui.SelectionList(null,S60OptionsSpice.S60OptionsSpiceTemplateLibrary,"nm_Focused");this._poiList._addCssClass("nmp_S60PoiList");this._poiList.addBehavior(this._poiScroll);this._poiList.setCSSTrigger(Control.CSS_TRIGGER_FOCUS);this._buildPoiList(this._poiList);this.poiListContainer.setChildAt(this._poiList,"S60PoiListSelector");this.mapViewContainer.hide();this.poiListContainer.hide();this.container.setChildAt(this.menuList,"S60OptionsMenuSelector");this.container.setChildAt(this.mapViewContainer,"S60OptionsMapViewContainer");this.container.setChildAt(this.poiListContainer,"S60OptionsPoiListContainer");this.container.hide();this._model.addEventHandler(MapModel.EVENT_CATEGORIES_CHANGED,this._onCategoryChanged,this);this._model.addEventHandler(MapModel.EVENT_LAYERS_CHANGED,this._onLayerChanged,this);this._model.addEventHandler(MapModel.EVENT_MAPTYPE,this._onModelMapTypeChanged,this);this._model.addEventHandler(MapModel.EVENT_TILT,this._onModelTiltChanged,this);this._model.addEventHandler(MapModel.EVENT_COLOR,this._onModelColorChanged,this);this._spiceManager.setKeyHandler(KeyEventManager.KEY_1,0,nokia.aduno.utils.bind(this,this._handleMenuOpenKey));var menuListHandleKey=function(aKeyEvent){var key=aKeyEvent.getKey();if(!aKeyEvent.keyDown){return true}if(key===KeyEventManager.KEY_9){return false}if(key===KeyEventManager.KEY_1){return false}var currentList,index;if(key===KeyEventManager.KEY_DOWN||key===KeyEventManager.KEY_UP){var offset=(key===KeyEventManager.KEY_UP)?-1:1;var currentButton=this.getFocusedChild();index=this.indexOf(currentButton);var length=this.getChildCount();index=(index+offset+length)%length;this.getChildAt(index).focus()}else{if(key===KeyEventManager.KEY_CSK||key===KeyEventManager.KEY_LSK||key===KeyEventManager.KEY_ENTER||key===KeyEventManager.KEY_5){if(this._focusedChild){var index=this.indexOf(this._focusedChild);var nextIndex=index+offset;if((nextIndex>=0)&&(nextIndex<this.getChildCount())){this.getChildAt(nextIndex).focus()}}else{if(this.getChildCount()>0){this.getChildAt(0).focus()}}this.fireEvent(new nokia.aduno.utils.Event("selected",this.indexOf(this._focusedChild)))}else{if(key===KeyEventManager.KEY_RSK){if(!binder._isVisible){binder._spiceControl.show()}else{binder._spiceControl.hide()}binder._isVisible=!binder._isVisible}}}return true};var menuListBinder=this.menuList;menuListBinder.handleKey=function(aKeyEvent){return menuListHandleKey.apply(menuListBinder,[aKeyEvent])};mapViewContainerhandleKey=function(aKeyEvent){debug("aKeyEvent mapView: "+aKeyEvent);var key=aKeyEvent.getKey();if(!aKeyEvent.keyDown){return true}if(key===KeyEventManager.KEY_9){return false}if(key===KeyEventManager.KEY_1){return false}var currentList,index;if(key===KeyEventManager.KEY_DOWN||key===KeyEventManager.KEY_UP){var typeList=this.getChildAt("S60MapTypeSelector");var tiltList=this.getChildAt("S60MapTiltSelector");var colorList=this.getChildAt("S60MapColorSelector");var newFocusedList=null;if(key==KeyEventManager.KEY_UP){if(tiltList.isFocused()){newFocusedList=typeList}else{if(colorList.isFocused()){newFocusedList=tiltList}else{return true}}}if(key==KeyEventManager.KEY_DOWN){if(typeList.isFocused()){newFocusedList=tiltList}else{if(tiltList.isFocused()){newFocusedList=colorList}else{return true}}}var fc=newFocusedList.getFocusedChild();if(fc){fc.focus()}else{newFocusedList.getSelected().focus()}}else{if(key===KeyEventManager.KEY_LEFT||key===KeyEventManager.KEY_RIGHT){var offset=(key===KeyEventManager.KEY_LEFT)?-1:1;currentList=this.getFocusedChild();var currentButton=currentList.getFocusedChild();index=currentList.indexOf(currentButton);var length=currentList.getChildCount();index=(index+offset+length)%length;currentList.getChildAt(index).focus()}else{if(key===KeyEventManager.KEY_CSK||key===KeyEventManager.KEY_LSK||key===KeyEventManager.KEY_ENTER||key===KeyEventManager.KEY_5){currentList=this.getFocusedChild();index=currentList.indexOf(currentList.getFocusedChild());currentList.setSelectionIndex(index)}else{if(key===KeyEventManager.KEY_RSK){binder._setOptionsMenu()}}}}return true};var mapViewContainerBinder=this.mapViewContainer;mapViewContainerBinder.handleKey=function(aKeyEvent){return mapViewContainerhandleKey.apply(mapViewContainerBinder,[aKeyEvent])};var poiListhandleKey=function(aKeyEvent){debug("aKeyEvent poiList: "+aKeyEvent);var key=aKeyEvent.getKey();if(!aKeyEvent.keyDown){return true}if(key===KeyEventManager.KEY_9){return false}if(key===KeyEventManager.KEY_1){return false}if(key===KeyEventManager.KEY_DOWN||key===KeyEventManager.KEY_UP){var offset=(key===KeyEventManager.KEY_UP)?-1:1;if(this._focusedChild){var index=this.indexOf(this._focusedChild);var nextIndex=index+offset;if((nextIndex>=0)&&(nextIndex<this.getChildCount())){this.getChildAt(nextIndex).focus();var elem=this.getChildAt(nextIndex).getRootElement()}}else{if(this.getChildCount()>0){this.getChildAt(0).focus();var elem=this.getChildAt(0).getRootElement()}}if(elem){var clipHeight=this.getRootElement().parentNode.clientHeight;var clipPos=this.getRootElement().parentNode.scrollTop;var elemHeight=nokia.aduno.dom.Dimensions.getSize(elem).y;var elemPos=nokia.aduno.dom.Dimensions.getPosition(elem,this.getRootElement()).y;if(key===KeyEventManager.KEY_DOWN){if((elemHeight+elemPos-clipPos)>clipHeight){binder._poiScroll.scrollToPos(0,(elemPos-elemHeight))}}else{if(key===KeyEventManager.KEY_UP){if((elemHeight+elemPos-clipPos)<elemHeight){binder._poiScroll.scrollToPos(0,(elemPos-clipHeight+elemHeight+elemHeight))}}}}}else{if(key===KeyEventManager.KEY_CSK||key===KeyEventManager.KEY_LSK||key===KeyEventManager.KEY_ENTER||key===KeyEventManager.KEY_5){var elem=this.getFocusedChild();if(elem){elem.select()}}else{if(key===KeyEventManager.KEY_RSK){binder._setOptionsMenu()}}}return true};var poiListBinder=this._poiList;poiListBinder.handleKey=function(aKeyEvent){return poiListhandleKey.apply(poiListBinder,[aKeyEvent])};return this.container},handleKey:function(aKey){var returnValue=this._super(aKey);if(!returnValue){var key=aKeyEvent.getKey();if(aKeyEvent.keyDown||(key!==0&&!key)||aKeyEvent.keyPress){return true}if(key===KeyEventManager.KEY_RSK){this._setOptionsMenu();return true}}return returnValue},onAttach:function(){},_onMenuSelected:function(aEvent){if(!this._isVisible){return}this.container._removeCssClass("full");var newIndex=aEvent.getData();if(newIndex==0){this._setOptionsMenu("mapview")}else{if(newIndex==1){this._setOptionsMenu("poilist")}}var childCount=this.menuList.getChildCount();for(var x=0;x<childCount;x++){if(x!=newIndex){this.menuList.getChildAt(x).hide();this.menuList.getChildAt(x)._removeCssClass("nm_Active")}else{this.menuList.getChildAt(x)._addCssClass("nm_Active")}}},_onTypeSelected:function(aSelectEvent){if(!this._isVisible){return}var newIndex=aSelectEvent.getData().selectedIndex;if(this._mapNameMappings[this._model.getMapType()]!==newIndex){this._model.setMapType(this._mapMappings[newIndex])}},_onTiltSelected:function(aSelectEvent){if(!this._isVisible){return}var is3d=aSelectEvent.getData().selectedIndex===this.indexOf3dButton;if(this._model.getMode3d()!==is3d){this._model.setMode3d(is3d)}},_onColorSelected:function(aSelectEvent){if(!this._isVisible){return}var color=this._colorMappings[aSelectEvent.getData().selectedIndex];if(this._model.getColor()!==color){this._model.setColor(color)}},_onCategoryClicked:function(aEvent){var source=aEvent.source;if(source.getValue&&source.getState){var val=source.getValue();var state=source.getState();if(val!==undefined&&val!==null&&source!==undefined&&source!==null){if(state){this._model.showCategory(val)}else{this._model.hideCategory(val)}this._checkShownAllButton()}}},_onLayerClicked:function(aEvent){var source=aEvent.source;if(!source){return}var layerName=source.getValue();var state=source.getState();if(layerName&&state!==undefined&&state!==null){if(state){this._model.showLayer(layerName)}else{this._model.hideLayer(layerName)}this._checkShownAllButton()}},_checkShownAllButton:function(){var showAll=true;for(var x in this._categories){if(!this._categories[x].getState()){showAll=false;break}}if(showAll){for(var y in this._layers){if(!this._layers[y].getState()){showAll=false;break}}}this._showAll.setState(showAll)},_isListChildFocused:function(aList){var length=aList.getChildCount();for(var i=0;i<length;i++){if(aList.getChildAt(i).isFocused()){return true}}return false},_setOptionsMenu:function(aMenu){switch(aMenu){case"mapview":this.container._removeCssClass("full");this.menuList.blur();this.poiListContainer.hide();this.poiListContainer.blur();this.mapViewContainer.show();this.mapViewContainer.focus();this.mapViewContainer.getChildAt("S60MapTypeSelector").getSelected().focus();break;case"poilist":this.container._addCssClass("full");this.menuList.blur();this.mapViewContainer.hide();this.mapViewContainer.blur();this.poiListContainer.show();this.poiListContainer.focus();this.poiListContainer.getChildAt("S60PoiListSelector").getChildAt(0).focus();break;default:this.container._removeCssClass("full");this.mapViewContainer.hide();this.mapViewContainer.blur();this.poiListContainer.hide();this.poiListContainer.blur();var childCount=this.menuList.getChildCount();for(var x=0;x<childCount;x++){this.menuList.getChildAt(x).show();this.menuList.getChildAt(x).blur();this.menuList.getChildAt(x)._removeCssClass("nm_Active")}this.menuList.focus();this.menuList.getChildAt(0).focus();break}},_handleMenuOpenKey:function(aKeyEvent){if(aKeyEvent.keyDown||aKeyEvent.keyPress||aKeyEvent.keyLongPress){return this._isVisible}this._setOptionsMenu();if(!this._isVisible){this._spiceControl.show()}else{this._spiceControl.hide()}this._isVisible=!this._isVisible},_onModelMapTypeChanged:function(aEvent){var index=this._mapNameMappings[aEvent.getData()];var typeList=this.mapViewContainer.getChildAt("S60MapTypeSelector");if(index!==typeList.getSelectionIndex()){typeList.setSelectionIndex(index)}},_onModelTiltChanged:function(aEvent){var is3d=aEvent.getData()!==0;var tiltList=this.mapViewContainer.getChildAt("S60MapTiltSelector");if(is3d!==(tiltList.getSelectionIndex()===this.indexOf3dButton)){tiltList.setSelectionIndex(is3d?this.indexOf3dButton:this.indexOf2dButton)}},_onModelColorChanged:function(aEvent){var colorList=this.mapViewContainer.getChildAt("S60MapColorSelector");if(colorList.getSelectionIndex()!==this._colorNameMappings[aEvent.getData()]){colorList.setSelectionIndex(this._colorNameMappings[aEvent.getData()])}},_onCategoryChanged:function(aEvent){var data=aEvent.getData();if(data&&data.type&&data.category&&this._categories){if(data.type=="shown"){if(this._categories[data.category]){this._categories[data.category].setState(true);this._checkShownAllButton()}}else{if(data.type=="hidden"){if(this._categories[data.category]){this._categories[data.category].setState(false);this._checkShownAllButton()}}else{if(data.type=="entryEnabled"){this._buildPoiList(this._poiList.removeAllChildren())}else{if(data.type=="entryDisabled"){this._buildPoiList(this._poiList.removeAllChildren())}}}}}},_onLayerChanged:function(aEvent){var data=aEvent.getData();if(!data){return}var layerName=data.layer;if(data.type&&layerName&&this._layers){if(data.type=="shown"){if(this._layers[layerName]){this._layers[layerName].setState(true);this._checkShownAllButton()}}else{if(data.type=="hidden"){if(this._layers[layerName]){this._layers[layerName].setState(false);this._checkShownAllButton()}}else{if(data.type=="entryEnabled"){this._buildPoiList(this._poiList.removeAllChildren())}else{if(data.type=="entryDisabled"){this._buildPoiList(this._poiList.removeAllChildren())}}}}}},_buildPoiList:function(aList){var allArr=[];this._categories={};this._layers={};var catArr=this._model.getEnabledCategoryEntries();if(catArr){if(catArr.ALL){delete catArr.ALL}allArr[0]=catArr}var layArr=this._model.getEnabledLayerEntries();if(layArr){allArr[1]=layArr}this._showAll=this._addElementToList("Show All",false,aList,this._onShowAllSelected,true);this._showAll._addCssClass("nmp_S60PoiListEntry");var showAll=true;for(var current in allArr){for(var entry in allArr[current]){if(showAll&&!allArr[current][entry]){showAll=false}var entry=this._addElementToList(entry,allArr[current][entry],aList,current==0?this._onCategoryClicked:this._onLayerClicked,current==0);entry._addCssClass("nmp_S60PoiListEntry")}}this._showAll.setState(showAll)},_addElementToList:function(aLabel,aState,aList,aHandler,aIsCategory){label=aLabel.replace(/_/g," ").toLowerCase();label=" "+aLabel.substr(0,1).toUpperCase()+label.substr(1);var c=null;if(aIsCategory){c=new nokia.aduno.medosui.CheckButton(null,label,aLabel,aState);if(MapMarker.PoiImages[aLabel]){var image='<img src="'+this._pfwPath+"images/spices/poiCategories/icons/"+MapMarker.PoiImages[aLabel]+'.png" />'}else{if(aLabel!="Show All"){var image='<img src="'+this._pfwPath+'images/spices/poiCategories/icons/TOURIST_ATTRACTION.png" />'}}c.selected=function(){this._addCssClass("nmp_S60ListElementSelected")};c.deselected=function(){this._removeCssClass("nmp_S60ListElementSelected")};c.getReplica().setInnerHtml("image",image);if(aLabel!="Show All"){this._categories[aLabel]=c}}else{c=new nokia.aduno.medosui.CheckButton(null,label,aLabel,aState);this._layers[aLabel]=c}c.addEventHandler("selected",aHandler,this);aList.addChild(c);return c},_onShowAllSelected:function(aEvent){var src=aEvent.source;if(src&&src.getState){var state=src.getState();Collection.forEach(this._categories,function(elem,i){if(i.toLowerCase()!="show all"){if(state){this._model.showCategory(elem.getValue())}else{this._model.hideCategory(elem.getValue())}}},this);Collection.forEach(this._layers,function(elem,i){if(state){this._model.showLayer(elem.getValue())}else{this._model.hideLayer(elem.getValue())}},this)}}});S60OptionsSpice.S60OptionsSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({S60OptionsContainer:'<div class="nmp_S60OptionsContainer"><div id="S60OptionsMenuSelector"></div><div id="S60OptionsMapViewContainer"></div><div id="S60OptionsPoiListContainer"></div></div>',S60OptionsMenuSelector:'<div class="nmp_S60OptionsMenuSelector"></div>',S60OptionsMenuButton:'<div class="nmp_S60OptionsMenuButton"><span id="button"></span></div>',S60OptionsMapViewContainer:'<div class="nmp_S60OptionsMapViewContainer"><div id="S60MapTypeSelector"></div><div id="S60MapTiltSelector"></div><div id="S60MapColorSelector"></div></div>',S60OptionsPoiListContainer:'<div class="nmp_S60OptionsPoiListContainer"><div id="S60PoiListScrollable"><div id="S60PoiListSelector"></div></div></div>',S60PoiListScrollable:'<div class="nmp_S60PoiListScrollable"></div>',S60PoiListSelector:'<div class="nmp_S60PoiListSelector"></div>',S60MapTypeSelector:'<div class="nmp_S60MapTypeSelector"></div>',S60MapTiltSelector:'<div class="nmp_S60MapTiltSelector"></div>',S60MapColorSelector:'<div class="nmp_S60MapColorSelector"></div>',S60MapTypeNormalButton:'<div class="nmp_S60MapTypeNormalButton"><span id="button"></span></div>',S60MapTypeSatelliteButton:'<div class="nmp_S60MapTypeSatelliteButton"><span id="button"></span></div>',S60MapTypeTerrainButton:'<div class="nmp_S60MapTypeTerrainButton"><span id="button"></span></div>',S60OptionsButton:'<div class="nmp_S60OptionsButton"><span id="button"></span></div>',Button:'<div class="nmm_Butt"><a id="button"></a></div>',CheckButton:'<div id="checkButton"><div id="checkButtonButton" class="checkbutton"></div><span id="image"></span><span id="checkButtonText"></span></div>'},nokia.aduno.medosui.DefaultTemplateLibrary);var NextManeuverSpice=new Class({Name:"NextManeuverSpice",Extends:Spice,ICON_SIZE:1,NEXT_MVR_COUNTDWN_THRESHOLD:10,_guidance:null,_position:null,_map:null,_container:null,_maneuverArrivalBar:null,initialize:function(aSpiceManager,aTranslator,aModels){this._super(aSpiceManager,aTranslator);this._guidance=aModels.guidance;this._position=aModels.position;this._map=aModels.map;this._guidance.addEventHandler(GuidanceModel.EVENT_ON_NEXT_MANEUVER_CHANGED,this._onManeuver,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STARTED,this._onGuidanceStarted,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STOPPED,this._onGuidanceStopped,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_DONE,this._onGuidanceStopped,this)},_createUi:function(){var library=null;if(layout.touch){library=NextManeuverSpice.TouchNextManeuverSpiceTemplateLibrary;this.ICON_SIZE=70}else{library=NextManeuverSpice.SncNextManeuverSpiceTemplateLibrary;this.ICON_SIZE=48}this._container=new Container("NextManeuverContainer",library);this._container.hide();this._maneuverArrivalBar=new ProgressBar("ProgressBar",null,true);this._container.setChildAt(this._maneuverArrivalBar,"progressBar",true,false);return this._container},_onPositionChanged:function(aEvent){var data=aEvent.getData();this._updateGuidanceInfo();this._updateArrivalToManeuverBar()},_onGuidanceStarted:function(aEvent){this._updateGuidanceInfo();this._container.show();this._position.addEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this)},_onGuidanceStopped:function(aEvent){this._position.removeEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);this._container.hide()},_onManeuver:function(aEvent){var nextManeuver=this._guidance.getNextManeuver();if(nextManeuver!==null){var streetName=nextManeuver.getNextStreetName();if(!streetName){streetName=nextManeuver.getStreetName()}this._container.getReplica().setText("streetNameLabel",streetName);var index=nextManeuver.getIconIndex();this._container.getReplica().setStyle("icon","background-position","-"+index*this.ICON_SIZE+"px 0")}else{this._container.getReplica().setText("streetNameLabel","No next maneuver")}},_updateGuidanceInfo:function(){var distance=this._guidance.getNextManeuverDistance();var distanceObj=Units.getReadableDistance(distance,this._map.getMeasurementType());var distanceValue=distanceObj.value;var distanceUnit=distanceObj.unit;if(distance<0||!distanceObj||distanceValue===undefined||distanceUnit===undefined){distanceValue="";distanceUnit=""}this._container.getReplica().setText("distanceLabelValue",distanceValue);this._container.getReplica().setText("distanceLabelUnit",this.translateString(distanceUnit))},_updateNextManeuverIcon:function(aManeuver){},_updateArrivalToManeuverBar:function(){var currentSpeed=this._position.getMovementSpeed();var distance=this._guidance.getNextManeuverDistance();var timeToNextManeuver=Math.round(distance/currentSpeed);var nextManeuver=this._guidance.getNextManeuver();if(nextManeuver!==null&&timeToNextManeuver<this.NEXT_MVR_COUNTDWN_THRESHOLD){this._maneuverArrivalBar.setMaximum(this.NEXT_MVR_COUNTDWN_THRESHOLD);this._maneuverArrivalBar.setValue(this.NEXT_MVR_COUNTDWN_THRESHOLD-timeToNextManeuver)}else{this._maneuverArrivalBar.setValue(0)}}});NextManeuverSpice.SncNextManeuverSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({NextManeuverContainer:'<div id="nextManeuverContainer" class="nmp_NextManeuverContainerCenter"><div class="nmp_NextManeuverContainer"><div id="progressBar"></div><div id="icon" class="nmp_NextManeuverIcon"></div><div id="labelContainer" class="nmp_NextManeuverLabelContainer"><div id="streetNameLabel" class="nmp_NextManeuverStreetName"></div><div id="distanceLabel" class="nmp_NextManeuverDistance"><span id="distanceLabelValue" class="nmp_NextManeuverValue"></span><span id="distanceLabelUnit" class="nmp_NextManeuverUnit"></span></div></div></div></div>',ProgressBar:'<div class="nmp_NextManeuverProgressBar"><div id="progress" class="nmp_NextManeuverProgressBar_progress"></div></div>'});NextManeuverSpice.TouchNextManeuverSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({NextManeuverContainer:'<div id="nextManeuverContainer" class="nmp_NextManeuverContainerCenterAligner"><div class="nmp_NextManeuverContainer"><div class="nmp_NextManeuverContainerLeft"/><div class="nmp_NextManeuverContainerCenter"><div id="progressBar"></div><div id="icon" class="nmp_NextManeuverIcon"></div><div id="labelContainer" class="nmp_NextManeuverLabelContainer"><div id="streetNameLabel" class="nmp_NextManeuverStreetName"></div><div id="distanceLabel" class="nmp_NextManeuverDistance"><span id="distanceLabelValue" class="nmp_NextManeuverValue"/><span id="distanceLabelUnit" class="nmp_NextManeuverUnit"/></div></div></div><div class="nmp_NextManeuverContainerRight"/></div></div>',ProgressBar:'<div class="nmp_NextManeuverProgressBar"><div id="progress" class="nmp_NextManeuverProgressBar_progress"></div></div>'});var GuidanceProgressSpice=new Class({Name:"GuidanceProgressSpice",Extends:Spice,_guidance:null,_position:null,_map:null,_container:null,initialize:function(aSpiceManager,aTranslator,aModels){this._super(aSpiceManager,aTranslator);this._guidance=aModels.guidance;this._position=aModels.position;this._map=aModels.map;this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STARTED,this._onGuidanceStarted,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_STOPPED,this._onGuidanceStopped,this);this._guidance.addEventHandler(GuidanceModel.EVENT_GUIDANCE_DONE,this._onGuidanceStopped,this)},_createUi:function(){var library=layout.snc?GuidanceProgressSpice.GuidanceProgressSpiceTemplateLibrary:GuidanceProgressSpice.TouchGuidanceProgressSpiceTemplateLibrary;this._container=new Container("GuidanceProgressContainer",library);if(layout.snc){this._routeProgress=new ProgressBar();this._container.setChildAt(this._routeProgress,"progressBar",false,true)}this._container.hide();return this._container},_onPositionChanged:function(aEvent){var data=aEvent.getData();this._updateGuidanceProgress()},_onGuidanceStarted:function(aEvent){this._position.addEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);this._currentRoute=aEvent.getData().route;if(layout.snc){this._routeProgress.setValue(0);this._routeProgress.setMaximum(this._currentRoute.getLength())}this._updateGuidanceProgress();this._container.show()},_onGuidanceStopped:function(aEvent){this._position.removeEventHandler(PositionModel.EVENT_POSITION,this._onPositionChanged,this);this._container.hide();this._currentRoute=null},_updateGuidanceProgress:function(){var imperialUnits=this._map.getMeasurementType();var currentSpeed=Units.getReadableSpeed(this._position.getMovementSpeed(),imperialUnits,true);var currentSpeedUnit=currentSpeed.unit;var currentSpeedValue=currentSpeed.value;if(!currentSpeed||currentSpeedUnit===undefined||currentSpeedValue===undefined){currentSpeedUnit="";currentSpeedValue=""}var currentDestinationDistance=Units.getReadableDistance(this._guidance.getDistanceToDestination(),imperialUnits);var currentDestinationDistanceValue=currentDestinationDistance.value;var currentDestinationDistanceUnit=currentDestinationDistance.unit;if(!currentDestinationDistance||currentDestinationDistanceValue===undefined||currentDestinationDistanceUnit===undefined){currentDestinationDistanceValue="";currentDestinationDistanceUnit=""}var elapsedDist=this._guidance.getElapsedDistance();if(elapsedDist&&layout.snc){this._routeProgress.setValue(elapsedDist)}var tta=Units.getReadableTime(this._guidance.getTimeToArrival());var ttaValue=tta.value;var ttaUnit=tta.unit;if(!tta||ttaValue===undefined||ttaUnit===undefined){ttaValue="";ttaUnit=""}this._container.getReplica().setText("labelSpeedValue",currentSpeedValue);this._container.getReplica().setText("labelSpeedUnit",this.translateString(currentSpeedUnit));this._container.getReplica().setText("labelDistanceValue",currentDestinationDistanceValue);this._container.getReplica().setText("labelDistanceUnit",this.translateString(currentDestinationDistanceUnit));this._container.getReplica().setText("labelTimeValue",ttaValue);this._container.getReplica().setText("labelTimeUnit",this.translateString(ttaUnit))}});GuidanceProgressSpice.GuidanceProgressSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({GuidanceProgressContainer:'<div id="nmp_GuidanceProgressContainerCenter" class="nmp_GuidanceProgressContainerCenter"><div  class="nmp_GuidanceProgressContainer"><div id="progressBar" class="nmp_GuidanceProgressProgressBar"></div><div class="nmp_GuidanceProgressSpeed"><span id="labelSpeedValue" class="nmp_GuidanceProgressValue"></span><span id="labelSpeedUnit" class="nmp_GuidanceProgressUnit"></span></div><div id="labelDistance" class="nmp_GuidanceProgressDistance"><span id="labelDistanceValue" class="nmp_GuidanceProgressValue"></span><span id="labelDistanceUnit" class="nmp_GuidanceProgressUnit"></span></div><div id="labelTime" class="nmp_GuidanceProgressEta"><span id="labelTimeValue" class="nmp_GuidanceProgressValue"></span><span id="labelTimeUnit" class="nmp_GuidanceProgressUnit"></span></div></div></div>',ProgressBar:'<div class="nmp_GuidanceProgressBar "><div id="progress" class="nmp_Progress" style="width: 60%;"><div class="nmp_Thumb"></div></div></div>'});GuidanceProgressSpice.TouchGuidanceProgressSpiceTemplateLibrary=new nokia.aduno.dom.TemplateLibrary({GuidanceProgressContainer:'<div class="nmp_GuidanceProgress"><div id="nmp_GuidanceProgressContainerCenter" class="nmp_GuidanceProgressContainerCenter"><div  class="nmp_GuidanceProgressContainer"><div class="nmp_GuidanceProgressSpeed"><span id="labelSpeedValue" class="nmp_GuidanceProgressValue"></span><span id="labelSpeedUnit" class="nmp_GuidanceProgressUnit"></span></div><div class="nmp_GuidanceProgressSeparation"></div><div id="labelDistance" class="nmp_GuidanceProgressDistance"><span id="labelDistanceValue" class="nmp_GuidanceProgressValue"></span><span id="labelDistanceUnit" class="nmp_GuidanceProgressUnit"></span></div><div class="nmp_GuidanceProgressSeparation"></div><div id="labelTime" class="nmp_GuidanceProgressEta"><span id="labelTimeValue" class="nmp_GuidanceProgressValue"></span><span id="labelTimeUnit" class="nmp_GuidanceProgressUnit"></span></div></div></div></div>'});nokia.maps.pfw.spices.addMembers({ConsoleSpice:ConsoleSpice,KeyMapPanSpice:KeyMapPanSpice,MouseSpice:MouseSpice,MouseHoverSpice:MouseHoverSpice,ZoomSpice:ZoomSpice,InfoPlacard:InfoPlacard,InfoBarSpice:InfoBarSpice,InfoBubbleSpice:InfoBubbleSpice,MapModeSpice:MapModeSpice,MapTypeSpice:MapTypeSpice,TrafficSpice:TrafficSpice,BounceSpice:BounceSpice,OrientationTiltWheel:OrientationTiltWheel,OrientationTiltSpice:OrientationTiltSpice,PositionSpice:PositionSpice,SearchSpice:SearchSpice,ResultWindow:ResultWindow,Persistence:Persistence,NewSettingsSpice:NewSettingsSpice,RouteInfoSpice:RouteInfoSpice,FlyBySpice:FlyBySpice,WebRouteSettingsSpice:WebRouteSettingsSpice,WebWaypointSpice:WebWaypointSpice,GuidanceMapSpice:GuidanceMapSpice,TopMenuSpice:TopMenuSpice,CopyrightSpice:CopyrightSpice,WatermarkSpice:WatermarkSpice,ScaleBarSpice:ScaleBarSpice,MiniMapSpice:MiniMapSpice,ShowRouteOnMapSpice:ShowRouteOnMapSpice,TitleBarSpice:TitleBarSpice,InstallPluginSpice:InstallPluginSpice,CenterCursorSpice:CenterCursorSpice,LayerListSpice:LayerListSpice,WhereSearchSpice:WhereSearchSpice,TrafficLegendSpice:TrafficLegendSpice,TouchWaypointSpice:TouchWaypointSpice,TouchDirectionSpice:TouchDirectionSpice,TouchSearchSpice:TouchSearchSpice,TouchRouteSettingsSpice:TouchRouteSettingsSpice,TouchRouteInfoSpice:TouchRouteInfoSpice,TouchStartGuidanceSpice:TouchStartGuidanceSpice,MaemoZoomSpice:MaemoZoomSpice,MaemoOrientation:MaemoOrientation,MaemoOrientationSpice:MaemoOrientationSpice,MaemoSettingsSpice:MaemoSettingsSpice,MaemoInfoBarSpice:MaemoInfoBarSpice,MaemoPositionSpice:MaemoPositionSpice,NextManeuverSpice:NextManeuverSpice,GuidanceProgressSpice:GuidanceProgressSpice,TouchTestRouteSpice:TouchTestRouteSpice,SncRouteSettingsSpice:SncRouteSettingsSpice,SncWaypointSpice:SncWaypointSpice,S60OptionsSpice:S60OptionsSpice,NextManeuverSpice:NextManeuverSpice,GuidanceProgressSpice:GuidanceProgressSpice})};new function(){new nokia.aduno.Ns("nokia.maps.plugin");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 math=Math,PI=math.PI,PI_OVER_4=PI/4,PI_OVER_2=PI/2,PI_OVER_180=PI/180,_180_OVER_PI=180/PI,LN2=math.LN2,LN10=math.LN10,sin=math.sin,cos=math.cos,tan=math.tan,atan=math.atan,asin=math.asin,exp=math.exp,log=math.log,min=math.min,max=math.max,sqrt=math.sqrt,pow=math.pow,abs=math.abs,round=math.round,floor=math.floor,ceil=math.ceil,slice=Array.prototype.slice,encodeURIComp=encodeURIComponent,indexOf=function(list,item){for(var len=list.length-1,i=0;i<len;i++){if(list[i]===item){break}}return i===list.length?-1:i},lastIndexOf=function(list,item){for(var i=list.length-1;i>=0;i--){if(list[i]===item){break}}return i},isNumberOutOfRange=function(value,minValue,maxValue){return typeof value!=="number"||isNaN(value)||value<minValue||value>maxValue},adjustNumberToRange=function(value,minValue,maxValue){var len=arguments.length;value=Number(value);return min(max(value,len>1?minValue:value),len>2?maxValue:value)},addElement=function(parentNode,nodeName,className){var element=parentNode.ownerDocument.createElement(nodeName);if(className){element.className=className}parentNode.appendChild(element);return element},setAttribute=function(element,name,value){element.setAttribute(name,value)},createElementNS=function(document,namespace,name,behavior){return document.createElementNS?document.createElementNS(namespace,name):document.createElement("<"+name+' xmlns="'+namespace+'"'+(behavior?' style="behavior:'+behavior+'"':"")+"/>")},removeNode=function(node){return node.parentNode?node.parentNode.removeChild(node):node},appendChild=function(parent,node){return parent.appendChild(node)},normalizeNumber=function(value,max){return(value%max+max)%max},addCssRule=function(styleSheet,selector,style){var cssRules;if(styleSheet.addRule){cssRules=styleSheet.rules;styleSheet.addRule(selector,style)}else{cssRules=styleSheet.cssRules;styleSheet.insertRule(selector+"{"+style+"}",cssRules.length)}return cssRules[cssRules.length-1]},stringPadding=function(value,chr,length,right){value=""+value;var result=[],i=value.length;for(;i<length;i++){result.push(chr)}result[right?"unshift":"push"](value);return result.join("")},doNothing=new self.Function(),dateFromISO8601=function(aString){aString=""+aString;var regexp=/(\d\d\d\d)(\-)?(\d\d)(\-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?(Z|([\+\-])(\d\d)(:)?(\d\d))?/,date=new Date(),d=aString.match(new RegExp(regexp));if(d){date.setUTCDate(1);date.setUTCFullYear(parseInt(d[1],10));date.setUTCMonth(parseInt(d[3],10)-1);date.setUTCDate(parseInt(d[5],10));date.setUTCHours(parseInt(d[7],10));date.setUTCMinutes(parseInt(d[9],10));date.setUTCSeconds(parseInt(d[11],10));date.setUTCMilliseconds(d[12]?parseFloat(d[12])*1000:0);if(d[13]&&d[13]!=="Z"){var offset=0;offset=(d[15]*60)+parseInt(d[17],10);offset*=((d[14]==="-")?-1:1);date.setTime(date.getTime()-offset*60*1000)}}else{date.setTime(Date.parse(aString))}return date},durationFromISO8601=function(aString){aString=""+aString;var regexp=/P(\d\d\d\d)(\-)?(\d\d)(\-)?(\d\d)(T)?(\d\d)(:)?(\d\d)(:)?(\d\d)(\.\d+)?/,methods=["FullYear","Month","Date","Hours","Minutes","Seconds","Milliseconds"],offsets=[1,3,5,7,9,11,12],date=new Date(),time=date.getTime(),d=aString.match(new RegExp(regexp));if(!d){regexp=/P(\d+Y)?(\d+M)?(\d+D)?(T)?(\d+H)?(\d+M)?(\d+)?(\.\d+)?(S)?/;offsets=[1,2,3,5,6,7,8];d=aString.match(new RegExp(regexp))}for(var i=0;d&&i<methods.length;i++){var value=d[offsets[i]];value=value?(i===6?parseFloat(value)*1000:parseInt(value,10)):0;date["set"+methods[i]](date["get"+methods[i]]()+value)}return date.getTime()-time},NSResolver=function(namespaces){return function(prefix){return namespaces&&namespaces[prefix]||null}},evalXPath=self.XPathResult?function(context,expression,namespaces){var iterator=(context.ownerDocument||context).evaluate(expression,context,new NSResolver(namespaces),XPathResult.ORDERED_NODE_ITERATOR_TYPE,null),result=[],node;while((node=iterator.iterateNext())){result.push(node)}return result||[]}:function(context,expression,namespaces){var doc=context.ownerDocument||context,oldLanguage=doc.getProperty("SelectionLanguage"),oldNamespaces=doc.getProperty("SelectionNamespaces"),result,key,table="";for(key in namespaces){if(namespaces.hasOwnProperty(key)){table+="xmlns:"+key+'="'+namespaces[key]+'" '}}doc.setProperty("SelectionLanguage","XPath");doc.setProperty("SelectionNamespaces",table);result=context.selectNodes(expression);doc.setProperty("SelectionLanguage",oldLanguage);doc.setProperty("SelectionNamespaces",oldNamespaces);return result};var ISupports=new Class({_markedAsISupports:true,_ILLEGAL_ARGUMENT:"IllegalArgument",_ILLEGAL_STATE:"IllegalState",_INTERNAL_ERROR:"InternalError",_throwException:function(methodName,description){throw (this.className||"UnknownClassName")+"::"+methodName+"() - "+description},_prepareCallback:function(callback,callerName,context){var type=typeof callback;if(type==="function"||type==="object"&&!callback){context=context||this;return !callback?null:function(timeout){timeout=timeout||0;if(timeout<0){callback(context)}else{clearTimeout(arguments.callee.timeout);arguments.callee.timeout=setTimeout(function(){callback(context)},timeout)}}}else{this._throwException(callerName,this._ILLEGAL_ARGUMENT)}}});var Point=new Class({Name:"Point",initialize:function(x,y){this._x=x;this._y=y},_equals:function(other){return this._x==other._x&&this._y==other._y},_add:function(offset){return new this.constructor(this._x+offset._x,this._y+offset._y)},_sub:function(offset){return new this.constructor(this._x-offset._x,this._y-offset._y)},_multiply:function(multiplier){return new this.constructor(this._x*multiplier,this._y*multiplier)},_delta:function(other){return new this.constructor(abs(this._x-other._x),abs(this._y-other._y))},_getMidpointTo:function(other){return new this.constructor((this._x+other._x)/2,(this._y+other._y)/2)},_distance:function(other){return sqrt(pow(abs(this._x-other._x),2)+pow(abs(this._y-other._y),2))},_modulo:function(divisor){return new this.constructor(this._x%divisor,this._y%divisor)},toString:function(){return this._x+" "+this._y},_copy:function(){return new this.constructor(this._x,this._y)},_min:function(other){return new this.constructor(min(this._x,other._x),min(this._y,other._y))},_max:function(other){return new this.constructor(max(this._x,other._x),max(this._y,other._y))},_trimm:function(min,max,minY,maxY){if(arguments.length<3){minY=min;maxY=max}this._x=max(min(this._x,max),min);this._y=max(min(this._y,maxY),minY)}});var GeoRectangle=new Class({Name:"GeoRectangle",initialize:function(points){this._northWest=points[0]._copy();this._southEast=points[0]._copy();for(var i=points.length-1;i;i--){this._addPoint(points[i])}},_addPoint:function(point){this._northWest=new IGeoCoordinates(max(this._northWest._latitude,point._latitude),min(this._northWest._longitude,point._longitude));this._southEast=new IGeoCoordinates(min(this._southEast._latitude,point._latitude),max(this._southEast._longitude,point._longitude))},_getMidpoint:function(){return this._southEast._getMidpointTo(this._northWest)},_addMidpoint:function(point){var deltaNW=this._northWest._delta(point),deltaSE=this._southEast._delta(point),maxLatDelta=max(deltaNW._y,deltaSE._y),maxLngDelta=max(deltaNW._x,deltaSE._x);this._addPoint(this._adjustedGeo(point._latitude-maxLatDelta,point._longitude-maxLngDelta));this._addPoint(this._adjustedGeo(point._latitude+maxLatDelta,point._longitude+maxLngDelta))},_adjustedGeo:function(latitude,longitude){return new IGeoCoordinates(adjustNumberToRange(latitude,-90,90),adjustNumberToRange(longitude,-180,180))}});var Rectangle=new Class({Name:"Rectangle",initialize:function(points){this._upperLeft=(this._lowerRight=points[0]._copy())._copy();if(points.length>1){this._addPoints(points.slice(1))}},_addPoint:function(point){this._upperLeft._x=min(this._upperLeft._x,point._x);this._upperLeft._y=min(this._upperLeft._y,point._y);this._lowerRight._x=max(this._lowerRight._x,point._x);this._lowerRight._y=max(this._lowerRight._y,point._y)},_addPoints:function(points){var i=points.length-1;for(;i>=0;i--){this._addPoint(points[i])}},_addMidpoint:function(point){var deltaNW=this._upperLeft._delta(point),deltaSE=this._lowerRight._delta(point),maxXDelta=max(deltaNW._x,deltaSE._x),maxYDelta=max(deltaNW._y,deltaSE._y);this._addPoint(point._x-maxXDelta,point._y-maxYDelta);this._addPoint(point._x+maxXDelta,point._y+maxYDelta)},_getMidpoint:function(){return this._lowerRight._getMidpointTo(this._upperLeft)},_intersection:function(other){if(other){var upperLeft=this._upperLeft._max(other._upperLeft||other),lowerRight=this._lowerRight._min(other._lowerRight||other)}return other&&upperLeft._x<=lowerRight._x&&upperLeft._y<=lowerRight._y?new Rectangle([upperLeft,lowerRight]):null},_intersects:function(other){if(other){var upperLeft=this._upperLeft._max(other._upperLeft||other),lowerRight=this._lowerRight._min(other._lowerRight||other)}return other&&upperLeft._x<=lowerRight._x&&upperLeft._y<=lowerRight._y},_join:function(other){return other?new Rectangle([this._upperLeft._min(other._upperLeft||other),this._lowerRight._max(other._lowerRight||other)]):this._copy()},toString:function(){return"{ "+this._upperLeft+", "+this._lowerRight+" }"},_equals:function(other){return other&&this._upperLeft._x===other._upperLeft._x&&this._upperLeft._y===other._upperLeft._y&&this._lowerRight._x===other._lowerRight._x&&this._lowerRight._y===other._lowerRight._y},_contains:function(other){return other&&(other._upperLeft?this._upperLeft._x<=other._upperLeft._x&&this._upperLeft._y<=other._upperLeft._y&&this._lowerRight._x>=other._lowerRight._x&&this._lowerRight._y>=other._lowerRight._y:this._upperLeft._x<=other._x&&this._upperLeft._y<=other._y&&this._lowerRight._x>=other._x&&this._lowerRight._y>=other._y)},_copy:function(){var copy=new Rectangle([this._upperLeft]);copy._lowerRight=this._lowerRight._copy();return copy}});var Matrix=function(aBase){if(aBase){this.base=aBase}else{this.base=[[1,0,0,0],[0,1,0,0],[0,0,1,0]]}};Matrix.prototype={constructor:Matrix,Name:"Matrix",set:function(aBase){this.base=aBase},concat:function(aMatrix){var m1=this.base,mc=[[],[],[]],m20=aMatrix[0],m21=aMatrix[1],m22=aMatrix[2],mci,m1i,m1i0,m1i1,m1i2;for(var i=2;i>=0;i--){mci=mc[i];m1i=m1[i];m1i0=m1i[0];m1i1=m1i[1];m1i2=m1i[2];mci[0]=m1i0*m20[0]+m1i1*m21[0]+m1i2*m22[0];mci[1]=m1i0*m20[1]+m1i1*m21[1]+m1i2*m22[1];mci[2]=m1i0*m20[2]+m1i1*m21[2]+m1i2*m22[2];mci[3]=m1i0*m20[3]+m1i1*m21[3]+m1i2*m22[3]+m1i[3]}this.base=mc},scale:function(sX,sY,sZ){this.concat([[sX,0,0,0],[0,sY,0,0],[0,0,sZ,0]])},getScale:function(){var b0=this.base[0],b1=this.base[1],b2=this.base[2];return new Vector3D(Math.sqrt(b0[0]*b0[0]+b0[1]*b0[1]+b0[2]*b0[2]),Math.sqrt(b1[0]*b1[0]+b1[1]*b1[1]+b1[2]*b1[2]),Math.sqrt(b2[0]*b2[0]+b2[1]*b2[1]+b2[2]*b2[2]))},translate:function(dx,dy,dz){var m=[[1,0,0,dx],[0,1,0,dy],[0,0,1,dz]];this.concat(m)},getTranslate:function(){return new Vector3D(this.base[0][3],this.base[1][3],this.base[2][3])},rotateX:function(rX){var s=Math.sin(rX),c=Math.cos(rX);this.concat([[1,0,0,0],[0,c,s,0],[0,-s,c,0]])},rotateY:function(ry){var s=Math.sin(ry),c=Math.cos(ry);this.concat([[c,0,-s,0],[0,1,0,0],[s,0,c,0]])},rotateZ:function(rz){var s=Math.sin(rz),c=Math.cos(rz);this.concat([[c,s,0,0],[-s,c,0,0],[0,0,1,0]])},skewX:function(s){var t=Math.tan(s);this.concat([[1,t,0,0],[0,1,0,0],[0,0,1,0]])},skewY:function(s){var t=Math.tan(s);this.concat([[1,0,0,0],[t,1,0,0],[0,0,1,0]])},clone:function(){var newMatrix=new Matrix(),b0=this.base[0],b1=this.base[1],b2=this.base[2];newMatrix.set([[b0[0],b0[1],b0[2],b0[3]],[b1[0],b1[1],b1[2],b1[3]],[b2[0],b2[1],b2[2],b2[3]]]);return newMatrix}};var Vector3D=function(x,y,z){this.x=x?x:0;this.y=y?y:0;this.z=z?z:0};Vector3D.prototype={constructor:Vector3D,Name:"Vector3D",set:function(x,y,z){this.x=x;this.y=y;this.z=z},add:function(aVector){return new Vector3D(this.x+aVector.x,this.y+aVector.y,this.z+aVector.z)},subtract:function(aVector){return new Vector3D(this.x-aVector.x,this.y-aVector.y,this.z-aVector.z)},multiply:function(aVector){return new Vector3D(this.x*aVector.x,this.y*aVector.y,this.z*aVector.z)},divide:function(aVector){return new Vector3D(this.x/aVector.x,this.y/aVector.y,this.z/aVector.z)},dot:function(aVector){var product=this.multiply(aVector);return(product.x+product.y+product.z)},magnitude:function(){return Math.sqrt(this.dot(this))},normal:function(aVector){return new Vector3D((this.y*aVector.z)-(this.z*aVector.y),-((this.x*aVector.z)-(this.z*aVector.x)),(this.x*aVector.y)-(this.y*aVector.x))},normalize:function(){var mag=this.magnitude();return new Vector3D(this.x/mag,this.y/mag,this.z/mag)},transform:function(matrix){var m=matrix.base,m0=m[0],m1=m[1],m2=m[2];return new Vector3D(m0[0]*this.x+m0[1]*this.y+m0[2]*this.z+m0[3],m1[0]*this.x+m1[1]*this.y+m1[2]*this.z+m1[3],m2[0]*this.x+m2[1]*this.y+m2[2]*this.z+m2[3])}};var SvgRenderer=new Class({Name:"SvgRenderer",initialize:function(aDocument){this._document=aDocument},COORD_FACTOR:1000,_PATH_TABLE:{m:{argc:2,vml:"m",move:3,norm:0},c:{argc:6,vml:"c",move:3,norm:1},s:{argc:4,vml:"c",move:3,norm:2},q:{argc:4,vml:"c",move:3,norm:3},t:{argc:2,vml:"c",move:3,norm:4},l:{argc:2,vml:"l",move:3,norm:0},h:{argc:1,vml:"l",move:1,norm:0},v:{argc:1,vml:"l",move:2,norm:0},z:{argc:0,vml:"x",move:0,norm:0}},render:function(aFormat,aSvg){if(!aSvg){return null}var gda=SvgRenderer.getDimensionalAttribute,documentElement=aSvg.documentElement;if(!documentElement||documentElement.namespaceURI!=="http://www.w3.org/2000/svg"||documentElement.tagName!=="svg"){return null}this._unstyle(documentElement);var result={_domElement:null,_width:gda(documentElement,"width"),_height:gda(documentElement,"height")};documentElement.setAttribute("preserveAspectRatio","none");if(!documentElement.getAttribute("viewBox")){documentElement.setAttribute("viewBox",["0 0 ",result._width," ",result._height].join(""))}switch(aFormat){case SvgRenderer.FORMAT_VML:var target=this._document.createElement("div");target.style.overflow="hidden";this._renderToVml(documentElement,new Matrix(),target);result._domElement=target;break;case SvgRenderer.FORMAT_SVG:result._domElement=this._filterSvg(documentElement);break;default:return null}return result},_filterSvg:function(aSvg){if(!aSvg||aSvg.namespaceURI!=="http://www.w3.org/2000/svg"||aSvg.nodeName==="script"){return null}var element=this._createSvgElement(aSvg.nodeName);for(var i=0;i<aSvg.attributes.length;i++){var attribute=aSvg.attributes[i];if(attribute.specified===true&&!attribute.name.match(/on[.]*/g)&&attribute.name!=="xmlns"){var att=attribute.namespaceURI?document.createAttributeNS(attribute.namespaceURI,attribute.name):document.createAttribute(attribute.name);att.nodeValue=attribute.value;element.setAttributeNode(att)}}for(var subElement=aSvg.firstChild;subElement;subElement=subElement.nextSibling){if(subElement.nodeType===1){var newSub=this._filterSvg(subElement);if(newSub){element.appendChild(newSub)}}else{if(subElement.nodeType===3){element.appendChild(document.createTextNode(subElement.nodeValue))}}}return element},_svgBlueprints:{},_createSvgElement:function(aName){if(!this._svgBlueprints[aName]){this._svgBlueprints[aName]=this._document.createElementNS("http://www.w3.org/2000/svg",aName)}return this._svgBlueprints[aName].cloneNode(true)},_vmlBlueprints:null,_createVmlElement:function(aName){if(!this._vmlBlueprints){this._vmlBlueprints={};var sname="vmlrules.css",sheets=this._document.styleSheets,sheet;for(var i=0;i<sheets.length;i++){if([i].href===sname){sheet=sheets[i]}}if(!sheet){sheet=document.createStyleSheet("vmlrules.css")}sheet.addRule(".VmlElement","behavior:url(#default#VML);width:1px;height:1px;display:block;position:absolute;")}if(!this._vmlBlueprints[aName]){this._vmlBlueprints[aName]=this._document.createElement("<"+aName+' xmlns="urn:schemas-microsoft-com:vml" class="VmlElement"/>')}return this._vmlBlueprints[aName].cloneNode(true)},_renderToVml:function(aElement,aMatrix,aTarget){this._unstyle(aElement);var transform=aElement.getAttribute("transform");if(transform){this._translateTransform(aMatrix,transform)}var name="_renderToVml"+aElement.nodeName.toUpperCase();var fun=this[name];if(nokia.aduno.utils.type(fun)!="function"){return}fun.call(this,aElement,aMatrix,aTarget)},_unstyle:function(aElement){var style=aElement.getAttribute("style");if(style){var match,re=/([^:\s*]+)\s*:\s*([^;]+?)\s*(;|$)/g;while((match=re.exec(style))){aElement.setAttribute(match[1],match[2])}aElement.removeAttribute("style")}},_renderToVmlChildren:function(aElement,aMatrix,aTarget){for(var subElement=aElement.firstChild;subElement;subElement=subElement.nextSibling){if(subElement.nodeType===1){this._renderToVml(subElement,aMatrix.clone(),aTarget)}}},_renderToVmlSVG:function(aElement,aMatrix,aTarget){var gda=SvgRenderer.getDimensionalAttribute,canvas=this._createVmlElement("group"),rw=gda(aElement,"width"),rh=gda(aElement,"height"),vbe=aElement.getAttribute("viewBox"),vb=vbe?vbe.split(" "):[0,0,rw,rh],sx=rw/vb[2],sy=rh/vb[3],ox=-vb[0]*sx,oy=-vb[1]*sy;aTarget.style.width=(rw+1)+"px";aTarget.style.height=(rh+1)+"px";aTarget.appendChild(canvas);canvas.coordorigin="0 0";canvas.coordsize="1000 1000";canvas.style.left="0px";canvas.style.top="0px";canvas.style.width="1000px";canvas.style.height="1000px";aMatrix.concat([[sx,0,0,ox],[0,sy,0,oy],[0,0,1,0]]);this._renderToVmlChildren(aElement,aMatrix,canvas)},_renderToVmlG:function(aElement,aMatrix,aTarget){this._renderToVmlChildren(aElement,aMatrix,aTarget)},_renderToVmlPATH:function(aElement,aMatrix,aTarget){this._renderShape(aElement,aMatrix,this._pathToArray(aElement.getAttribute("d")),aTarget)},_renderToVmlRECT:function(aElement,aMatrix,aTarget){var gda=SvgRenderer.getDimensionalAttribute,x=gda(aElement,"x"),y=gda(aElement,"y"),w=gda(aElement,"width"),h=gda(aElement,"height"),rx=gda(aElement,"rx"),ry=gda(aElement,"ry");if(rx>0&&ry>0){var k=0.5522847498,kx=k*rx,ky=k*ry,r=x+w,b=y+h;this._renderShape(aElement,aMatrix,["M",x+rx,y,"L",r-rx,y,"C",r-rx+kx,y,r,y+ry-ky,r,y+ry,"L",r,b-ry,"C",r,b-ry+ky,r-rx+kx,b,r-rx,b,"L",x+rx,b,"C",x+kx,b,x,b-ry+ky,x,b-ry,"L",x,y+ry,"C",x,y+ry-ky,x+kx,y,x+rx,y,"z"],aTarget)}else{this._renderShape(aElement,aMatrix,["M",x,y,"h",w,"v",h,"h",-1*w,"z"],aTarget)}},_renderToVmlCIRCLE:function(aElement,aMatrix,aTarget){var gda=SvgRenderer.getDimensionalAttribute;this._renderEllipse(aElement,aMatrix,gda(aElement,"cx"),gda(aElement,"cy"),gda(aElement,"r"),gda(aElement,"r"),aTarget)},_renderToVmlELLIPSE:function(aElement,aMatrix,aTarget){var gda=SvgRenderer.getDimensionalAttribute;this._renderEllipse(aElement,aMatrix,gda(aElement,"cx"),gda(aElement,"cy"),gda(aElement,"rx"),gda(aElement,"ry"),aTarget)},_renderEllipse:function(aElement,aMatrix,aX,aY,aRx,aRy,aTarget){var k=0.5522847498,kx=k*aRx,ky=k*aRy,l=aX-aRx,r=aX+aRx,circle=["M",aX,aY+aRy,"C",aX+kx,aY+aRy,r,aY+ky,r,aY,"C",r,aY-ky,aX+kx,aY-aRy,aX,aY-aRy,"C",aX-kx,aY-aRy,l,aY-ky,l,aY,"C",l,aY+ky,aX-kx,aY+aRy,aX,aY+aRy,"z"];this._renderShape(aElement,aMatrix,circle,aTarget)},_renderToVmlPOLYLINE:function(aElement,aMatrix,aTarget){var command=this._lopToCommand(aElement.getAttribute("points"));this._renderShape(aElement,aMatrix,command,aTarget)},_renderToVmlPOLYGON:function(aElement,aMatrix,aTarget){var command=this._lopToCommand(aElement.getAttribute("points"));command[command.length]="z";this._renderShape(aElement,aMatrix,command,aTarget)},_lopToCommand:function(aList){var src=this._numbersToArray(aList),command=["M",src[0],src[1],"L"];for(var i=2;i<src.length;i++){command[i+2]=src[i]}return command},_numbersToArray:function(aNumbers){var numbers=aNumbers.replace(/[\,]/g," ").replace(/\s+/g," ").replace(/([0-9])(\-|\+)([0-9])/g,"$1 $2$3").replace(/^\s+/g,"").replace(/\s+$/g,"").split(" ");for(var i=0;i<numbers.length;i++){numbers[i]=numbers[i]*1}return numbers},_renderToVmlLINE:function(aElement,aMatrix,aTarget){var gda=SvgRenderer.getDimensionalAttribute;this._renderShape(aElement,aMatrix,["M",gda(aElement,"x1"),gda(aElement,"y1"),"L",gda(aElement,"x2"),gda(aElement,"y2")],aTarget)},_renderToVmlTEXT:function(aElement,aMatrix,aTarget){var ga=SvgRenderer.getAttribute,gda=SvgRenderer.getDimensionalAttribute,fontStyle=ga(aElement,"font-style","normal"),fontVariant=ga(aElement,"font-variant","normal"),fontWeight=ga(aElement,"font-weight","normal"),fontSize=gda(aElement,"font-size",9)*aMatrix.getScale().y,fontFamily=ga(aElement,"font-family","Arial"),textAnchor=ga(aElement,"text-anchor","start"),x=gda(aElement,"x"),y=gda(aElement,"y"),p1=new Vector3D(x-1,y-fontSize*0.25,1),p2=new Vector3D(x+1,y-fontSize*0.25,1),shape=this._createVmlElement("line"),p=this._createVmlElement("path"),t=this._createVmlElement("textpath");p1=p1.transform(aMatrix);p2=p2.transform(aMatrix);shape.coordsize=this.COORD_FACTOR+" "+this.COORD_FACTOR;shape.setAttribute("from",Math.round(p1.x)+" "+Math.round(p1.y));shape.setAttribute("to",Math.round(p2.x)+" "+Math.round(p2.y));aTarget.appendChild(shape);shape.appendChild(p);p.textPathOk=true;shape.appendChild(t);t.on=true;t.style.font=[fontStyle,fontVariant,fontWeight,fontSize+"px",fontFamily].join(" ");t.style["v-text-align"]=textAnchor==="start"?"left":(textAnchor==="end"?"right":"center");t.string=aElement.text;this._renderShapeAttributes(aElement,aMatrix,shape)},_renderToVmlIMAGE:function(aElement,aMatrix,aTarget){},_getFactor:function(aString){var match,re=/([0-9\+\-\.e]*)(\%)/g;if((match=re.exec(aString))){return parseFloat(match[1])/(match[2]?100:1)}return parseFloat(aString)},_renderToVmlLINEARGRADIENT:function(aElement,aMatrix,aTarget){var gda=SvgRenderer.getDimensionalAttribute,fill=this._createVmlElement("fill"),p1=new Vector3D(gda(aElement,"x1"),gda(aElement,"y1")).transform(aMatrix),p2=new Vector3D(gda(aElement,"x2"),gda(aElement,"y2")).transform(aMatrix),pd=p2.subtract(p1).normalize(),a=((Math.acos(pd.y)/Math.PI)*180)%360,s,colors;fill.setAttribute("type","gradient");aTarget.appendChild(fill);for(var stop=aElement.lastChild;stop;stop=stop.previousSibling){if(stop.nodeType===1&&stop.nodeName==="stop"){this._unstyle(stop);s=(1-this._getFactor(stop.getAttribute("offset")))+" "+stop.getAttribute("stop-color");colors=colors?colors+","+s:s}}fill.setAttribute("colors",colors);fill.setAttribute("angle",a)},_renderToVmlRADIALGRADIENT:function(aElement,aMatrix,aTarget){var gda=SvgRenderer.getDimensionalAttribute,fill=this._createVmlElement("fill"),s,colors;fill.setAttribute("type","gradientradial");aTarget.appendChild(fill);for(var stop=aElement.lastChild;stop;stop=stop.previousSibling){if(stop.nodeType===1&&stop.nodeName==="stop"){this._unstyle(stop);s=(1-this._getFactor(stop.getAttribute("offset")))+" "+stop.getAttribute("stop-color");colors=colors?colors+","+s:s}}fill.setAttribute("focusposition","50%,50%");fill.setAttribute("colors",colors)},_renderToVmlUSE:function(aElement,aMatrix,aTarget){var l=aElement.firstChild,i=aElement.attributes.length-1,a,att;for(;i>=0;i--){a=aElement.attributes[i];if(a.baseName==="href"&&a.namespaceURI==="http://www.w3.org/1999/xlink"){i=-1;att=a}}var id=att?att.nodeValue.replace(/\#/g,""):null,refEle=id?aElement.ownerDocument.selectSingleNode('//*[@id="'+id+'"]'):null;if(refEle){this._renderToVml(refEle,aMatrix,aTarget)}},_renderShape:function(aElement,aMatrix,aPath,aTarget){var shape=this._createVmlElement("shape");aTarget.appendChild(shape);shape.coordsize=this.COORD_FACTOR+" "+this.COORD_FACTOR;var path=this._translatePath(aMatrix,aPath);shape.setAttribute("path",path);this._renderShapeAttributes(aElement,aMatrix,shape)},_renderShapeAttributes:function(aElement,aMatrix,aTarget){var ga=SvgRenderer.getAttribute,gda=SvgRenderer.getDimensionalAttribute,opacity=ga(aElement,"opacity","1"),stroke=ga(aElement,"stroke","none"),fill=ga(aElement,"fill","none"),strokeOpacity=ga(aElement,"stroke-opacity",opacity),fillOpacity=ga(aElement,"fill-opacity",opacity),lineCap=ga(aElement,"stroke-linecap","butt").replace("butt","flat"),lineJoin=ga(aElement,"stroke-linejoin","round"),lineMiterlimit=ga(aElement,"stroke-miterlimit",4);if(stroke!="none"){var strokeElement=this._createVmlElement("stroke"),scale=aMatrix.getScale(),factor=Math.sqrt(scale.x*scale.x+scale.y*scale.y);aTarget.appendChild(strokeElement);strokeElement.setAttribute("color",stroke);strokeElement.setAttribute("opacity",strokeOpacity);strokeElement.setAttribute("endcap",lineCap);strokeElement.setAttribute("joinstyle",lineJoin);strokeElement.setAttribute("miterlimit",lineMiterlimit);strokeElement.setAttribute("weight",(gda(aElement,"stroke-width"))*0.66*factor+"px")}else{aTarget.setAttribute("stroked","f")}if(fill!="none"){var re=/url\(\#([^\)]*)\)/g,match=re.exec(fill);if(match){var refEle=aElement.ownerDocument.selectSingleNode('//*[@id="'+match[1]+'"]');if(refEle){this._renderToVml(refEle,aMatrix,aTarget)}}else{var fillElement=this._createVmlElement("fill");fillElement.on=true;aTarget.appendChild(fillElement);fillElement.setAttribute("color",fill);fillElement.setAttribute("opacity",fillOpacity)}}else{aTarget.setAttribute("filled","f")}},_translateTransform:function(aMatrix,aTransform){var match,re=/([a-zA-Z]*)\s*\(([^\)]*)\)/g;while((match=re.exec(aTransform))){var params=this._numbersToArray(match[2]);switch(match[1].toLowerCase()){case"matrix":aMatrix.concat([[params[0],params[2],0,params[4]],[params[1],params[3],0,params[5]],[0,0,1,0]]);break;case"translate":aMatrix.translate(params[0],params.length>1?params[1]:0,0);break;case"scale":aMatrix.scale(params[0],params.length>1?params[1]:params[0],1);break;case"rotate":if(params.length>1){aMatrix.translate(params[1],params[2],0)}aMatrix.rotateZ((params[0]/180)*Math.PI);if(params.length>1){aMatrix.translate(-params[1],-params[2],0)}break;case"skewx":aMatrix.skewX(params[0]);break;case"skewy":aMatrix.skewY(params[0]);break;default:break}}},_pathToArray:function(aPath){return aPath.replace(/[\,]/g," ").replace(/\s+/g," ").replace(/([0-9])\-/g,"$1 -").replace(/([0-9])\+/g,"$1 ").replace(/([a-zA-Z])([a-zA-Z])/g,"$1 $2").replace(/([a-zA-Z])([0-9]|\.|\-|\+)/g,"$1 $2").replace(/([0-9])([a-zA-Z])/g,"$1 $2").replace(/(\s*)(e|E)(\s*)/g,"$1$2$3").replace(/^\s+/g,"").replace(/\s+$/g,"").split(" ")},_translatePath:function(aMatrix,aPath){var pt=this._PATH_TABLE,commands=[],currentX=0,currentY=0,normX=0,normY=0,tokenPosition=0,i,j,cc;for(i=0;i<aPath.length;i++){if(!isNaN(aPath[i])){aPath[i]=aPath[i]*1}}while(tokenPosition<aPath.length){var svgCommand=aPath[tokenPosition],cmd=pt[svgCommand.toLowerCase()],absolute=svgCommand.toUpperCase()===svgCommand;if(cmd){var args=[];while(++tokenPosition<aPath.length&&!isNaN(aPath[tokenPosition])){args[args.length]=aPath[tokenPosition]*1}if(cmd.argc>0){for(i=0;i<args.length/cmd.argc;i++){var command=[];for(j=0;j<cmd.argc;j++){var value=args[i*cmd.argc+j];if(!absolute){if(cmd.move===1||(cmd.move===3&&(j%2)===0)){value+=currentX}else{if(cmd.move===2||(cmd.move===3&&(j%2)>0)){value+=currentY}}}command[j]=value;args[i*cmd.argc+j]=value}var stretch=2/3;if(cmd.norm===2){command=[normX,normY,command[0],command[1],command[2],command[3]]}else{if(cmd.norm===3){command=[currentX+(command[0]-currentX)*stretch,currentY+(command[1]-currentY)*stretch,command[2]+(command[0]-command[2])*stretch,command[3]+(command[1]-command[3])*stretch,command[2],command[3]]}else{if(cmd.norm===4){command=[currentX+(normX-currentX)*stretch,currentY+(normY-currentY)*stretch,command[0]+(normX-command[0])*stretch,command[1]+(normY-command[1])*stretch,command[0],command[1]]}}}if(cmd.move===1){command=[command[0],currentY]}else{if(cmd.move===2){command=[currentX,command[0]]}}for(cc=0;cc<command.length;cc+=2){var v=new Vector3D(command[cc+0],command[cc+1],1);v=v.transform(aMatrix);command[cc+0]=v.x;command[cc+1]=v.y}for(cc=0;cc<command.length;cc++){command[cc]=Math.round(command[cc]*this.COORD_FACTOR)}commands[commands.length]=cmd.vml+command.join(",");var ni=(i+1)*cmd.argc,p1=args[ni-2],p2=args[ni-1];if(cmd.move===1){currentX=p2}else{if(cmd.move===2){currentY=p2}else{if(cmd.move===3){currentX=p1;currentY=p2}}}if(cmd.norm===0){normX=currentX;normY=currentY}else{normX=2*currentX-args[ni-4];normY=2*currentY-args[ni-3]}}}else{commands[commands.length]=cmd.vml}}else{tokenPosition=aPath.length}}return commands.join(" ")}});SvgRenderer.FORMAT_SVG=0;SvgRenderer.FORMAT_VML=1;SvgRenderer.getAttribute=function(aElement,aAttribute,aDefault){var current=aElement;while(current&&current.nodeType===1){if(current.getAttribute(aAttribute)){return current.getAttribute(aAttribute)}current=current.parentNode}return aDefault};SvgRenderer.getDimensionalAttribute=function(aElement,aAttribute){var raw=aElement.getAttribute(aAttribute);return raw?SvgRenderer.getDimensionalValue(raw):0};SvgRenderer.getDimensionalValue=function(aRaw){var match,re=/([0-9\+\-\.e]*)\s*([a-zA-Z]+)/g;if((match=re.exec(aRaw))){var num=parseFloat(match[1]);switch(match[2].toLowerCase()){case"pt":return num*1.25;case"pc":return num*15;case"mm":return num*3.543307;case"cm":return num*35.43307;case"in":return num*90;default:return num}}return parseFloat(aRaw)};var IArray=new Class({Name:"IArray",Extends:ISupports,initialize:function(aArray){this._array=aArray?aArray.slice(0):[]},push:function(aElement){if(!aElement||!aElement._markedAsISupports){this._throwException("push",this._ILLEGAL_ARGUMENT)}this._array.push(aElement)},at:function(aIndex){if(isNumberOutOfRange(aIndex,0,this._array.length-1)){this._throwException("at",this._ILLEGAL_ARGUMENT)}return this._array[aIndex]},getLength:function(){return this._array.length},_copy:function(){return new IArray(this._array)}});var IGeoCoordinates=new Class({Name:"IGeoCoordinates",Extends:ISupports,initialize:function(latitude,longitude,altitude){this.setLatitude(latitude);this.setLongitude(longitude);if(arguments.length>2){this.setAltitude(altitude)}},UNKNOWN_ALTITUDE:1<<30,setLongitude:function(aLongitude){if(isNumberOutOfRange(aLongitude,-Infinity,Infinity)){this._throwException("setLongitude",this._ILLEGAL_ARGUMENT)}this._longitude=aLongitude===180?180:((((aLongitude+180)%360)+360)%360)-180},getLongitude:function(){return this._longitude},setLatitude:function(aLatitude){if(isNumberOutOfRange(aLatitude,-90,90)){this._throwException("setLatitude",this._ILLEGAL_ARGUMENT)}this._latitude=aLatitude},getLatitude:function(){return this._latitude},_altitude:1<<30,setAltitude:function(aAltitude){if(aAltitude!==this.UNKNOWN_ALTITUDE&&isNumberOutOfRange(aAltitude,-10000,10000)){this._throwException("setAltitude",this._ILLEGAL_ARGUMENT)}this._altitude=aAltitude},getAltitude:function(){return this._altitude},distance:function(other){var latRadians=this._latitude*PI_OVER_180,otherLatRadians=other._latitude*PI_OVER_180;return 6371000*2*asin(min(1,sqrt(pow(sin(latRadians-otherLatRadians)/2,2)+cos(latRadians)*cos(otherLatRadians)*pow(sin((this._longitude*PI_OVER_180)-(other._longitude*PI_OVER_180))/2,2))))},equals:function(other){return this._latitude==other._latitude&&this._longitude==other._longitude},heading:function(other){var eps=1e-9,headingRad=0,dLat=other._latitude-this._latitude,dLng=(other._longitude-this._longitude)*cos(this._latitude*PI_OVER_180);if(abs(dLng)<eps){if(dLat<0){headingRad=PI}}else{headingRad=-atan(dLat/dLng)+PI_OVER_2}if(dLng<0){headingRad+=PI}return headingRad*_180_OVER_PI},_copy:function(){return new IGeoCoordinates(this._latitude,this._longitude,this._altitude)},_getMidpointTo:function(other){return new IGeoCoordinates((this._latitude+other._latitude)/2,(this._longitude+other._longitude)/2)},_delta:function(other){return new Point(abs(this._longitude-other._longitude),abs(this._latitude-other._latitude))},toString:function(){return"{ "+this._latitude+","+this._longitude+" }"},_toMercator:function(){return new Point(this._longitude/360+0.5,min(1,max(0,0.5-(log(tan(PI_OVER_4+PI_OVER_2*this._latitude/180))/PI)/2)))}});IGeoCoordinates._fromMercator=function(mercatorPoint){return new IGeoCoordinates(_180_OVER_PI*(2*atan(exp(PI*(1-2*mercatorPoint._y)))-PI_OVER_2),mercatorPoint._x*360-180)};var IPixelCoordinates=new Class({Name:"IPixelCoordinates",Extends:ISupports,Implements:Point,initialize:function(x,y){this._x=x;this._y=y},setX:function(x){if(isNaN(x)){this._throwException("setX",this._ILLEGAL_ARGUMENT)}this._x=round(x)},getX:function(){return this._x},setY:function(y){if(isNaN(y)){this._throwException("setY",this._ILLEGAL_ARGUMENT)}this._y=round(y)},getY:function(){return this._y}});IPixelCoordinates.prototype.equals=Point.prototype._equals;var persistencePrefix=function(namespace){return"_OM_"+namespace};var IPersistence=new Class({Name:"IPersistence",Extends:ISupports,initialize:function(plugin){if(plugin._persistence){return plugin._persistence}this._plugin=plugin;this._cache={};return this},_getNamespace:function(namespace,method){namespace=persistencePrefix(namespace);if(!this._cache.hasOwnProperty(namespace)){this._throwException(method,this._ILLEGAL_STATE)}return this._cache[namespace]},prepare:function(namespace,callback){namespace=persistencePrefix(namespace);this._cache[namespace]=this._cache[namespace]||{};if(callback){callback(this)}},set:function(namespace,key,value){namespace=this._getNamespace(namespace,"set");namespace[persistencePrefix(key)]=""+value},get:function(namespace,key){namespace=this._getNamespace(namespace,"get");key=persistencePrefix(key);return namespace.hasOwnProperty(key)?namespace[key]:null},remove:function(namespace,key){namespace=this._getNamespace(namespace,"remove");delete namespace[persistencePrefix(key)]},removeAll:function(namespace,keyPrefix){var ns=this._getNamespace(namespace,"removeAll");if(!keyPrefix){delete this._cache[persistencePrefix(namespace)]}else{keyPrefix=persistencePrefix(keyPrefix);for(var key in ns){if(ns.hasOwnProperty(key)&&!key.indexOf(keyPrefix)){delete ns[key]}}}}});var IColor=new Class({Name:"IColor",Extends:ISupports,initialize:function(r,g,b,a){this._red=r;this._green=g;this._blue=b;this._alpha=a},getRed:function(){return this._red},getGreen:function(){return this._green},getBlue:function(){return this._blue},getAlpha:function(){return this._alpha},_copy:function(){return new IColor(this._red,this._green,this._blue,this._alpha)},_getHexRgb:function(){return"#"+stringPadding(this._red.toString(16),"0",2)+stringPadding(this._green.toString(16),"0",2)+stringPadding(this._blue.toString(16),"0",2)}});var ILocation=new Class({Name:"ILocation",Extends:ISupports,initialize:function(){this._fields={}},_geoCoordinates:null,_mercatorCoordinates:null,setGeoCoordinates:function(geoCoordinates){if(geoCoordinates===null){this._geoCoordinates=this._mercatorCoordinates=geoCoordinates}else{if(!(geoCoordinates instanceof IGeoCoordinates)){this._throwException("setGeoCoordinates",this._ILLEGAL_ARGUMENT)}this._geoCoordinates=geoCoordinates._copy();this._mercatorCoordinates=geoCoordinates._toMercator()}},getGeoCoordinates:function(){return this._geoCoordinates?this._geoCoordinates._copy():null},_fieldNames:{},_checkFieldKey:function(key,methodName){if(!this._fieldNames.hasOwnProperty(key)){this._throwException(methodName,this._ILLEGAL_ARGUMENT)}},setField:function(key,value){this._checkFieldKey(key,"setField");this._fields[key]=""+value},getField:function(key){this._checkFieldKey(key,"getField");return this._fields.hasOwnProperty(key)?this._fields[key]||"":""},hasField:function(key){this._checkFieldKey(key,"hasField");return this._fields.hasOwnProperty(key)&&this._fields[key]},_copyMapper:function(value,key){return value},_copy:function(){var copy=new ILocation();copy._fields=Collection.map(this._fields,this._copyMapper);copy.setGeoCoordinates(this._geoCoordinates);return copy}});nokia.aduno.utils.Collection.forEach(("ADDR_COUNTRY_CODE ADDR_PROVINCE_NAME ADDR_COUNTY_NAME ADDR_COUNTRY_NAME ADDR_CITY_NAME ADDR_DISTRICT_NAME ADDR_POSTAL_CODE ADDR_STREET_NAME ADDR_HOUSE_NUMBER ADDR_NEIGHBORHOOD_NAME ADDR_BUILDING_NAME ADDR_BUILDING_FLOOR ADDR_BUILDING_ROOM ADDR_BUILDING_ZONE PLACE_NAME PLACE_CATEGORY PLACE_DESCRIPTION PLACE_PHONE_NUMBER PLACE_URL PLACE_PREMIUM_URL_ID PLACE_PREMIUM_NODE_ID TZ_OFFSET_MINUTES OTHER_DATA").split(" "),function(aValue,aKey){this._fieldNames[aKey]=aValue;this[aValue]=aKey;ILocation[aValue]=aKey},ILocation.prototype);var IIcon=new Class({Name:"IIcon",Extends:ISupports,initialize:function(iPlugin){this._plugin=iPlugin},isValid:function(){return !!this._domElement},_isSvg:!1,getWidth:function(){return this._domElement?this._size._x:this._throwException("getWidth",this._ILLEGAL_STATE)},getHeight:function(){return this._domElement?this._size._y:this._throwException("getHeight",this._ILLEGAL_STATE)},_renderFormat:browser.msie?SvgRenderer.FORMAT_VML:SvgRenderer.FORMAT_SVG,_parseSvg:function(markup){var doc;try{doc=this._plugin._domParser.parse(markup)}catch(e){return false}var result=this._plugin._svgRenderer.render(this._renderFormat,doc);if(result&&result._domElement){this._isSvg=!0;this._onDone(result._domElement,result._width,result._height);return true}else{return false}},_load:function(url){this._url=url;var request=new nokia.aduno.XHttpRequest(),that=this;request.onreadystatechange=function(){if(request.readyState==4){that._onReadyStateLoaded(request);request.onreadystatechange=doNothing;that=(request=null)}};try{request.open("GET",this._url);request.send(null)}catch(e){this._loadAsImage()}},_loadAsImage:function(){var image=new Image(),that=this;this._unprocessed=true;image.onload=function(){that._imageOnLoad(image)};image.onerror=function(){that._imageOnError(image)};image.src=this._url;if(image.complete){if(image.naturalWidth>0&&image.naturalHeight>0){if(this._unprocessed){this._imageOnLoad(image)}}else{if(this._unprocessed){this._imageOnError(image)}}}},_onDone:function(element,width,height){if(element){if(browser.msie){element.className="IMapObject"}else{element.setAttribute("class","IMapObject")}this._domElement=element;this._size=new Point(width,height)}if(this._onDoneCallback){this._onDoneCallback()}},_cleanupImage:function(image){image.onload=(image.onerror=null)},_imageOnLoad:function(image){this._unprocessed=false;this._onDone(image,image.width,image.height);this._cleanupImage(image)},_imageOnError:function(image){this._unprocessed=false;this._onDone();this._cleanupImage(image)},_onReadyStateLoaded:function(request){if(request.status%200){this._loadAsImage()}else{var text;try{text=request.responseText}catch(e){}if(!text||!this._parseSvg(text)){this._loadAsImage()}}}});IIcon._setSize=function(domElement,size){if(domElement.nodeName.toLowerCase()==="div"){var w=parseFloat(domElement.style.width),h=parseFloat(domElement.style.height),fc=domElement.firstChild,cs=(""+fc.getAttribute("coordsize")).split(/[,\s]+/),replace=function(ele){if(ele.nodeName.toLowerCase()==="textpath"){ele.style.fontSize=((parseFloat(ele.style.fontSize)/w)*size._x)+"px"}var cur=ele.firstChild;while(cur){replace(cur);cur=cur.nextSibling}};cs=Math.round((cs[0]/size._x)*w)+" "+Math.round((cs[1]/size._y)*h);fc.setAttribute("coordsize",cs);replace(fc)}domElement.style.width=size._x+"px";domElement.style.height=size._y+"px"};var IPositionProvider=new Class({Name:"IPositionProvider",Extends:ISupports,initialize:function(iPlugin){this._plugin=iPlugin},METHOD_NONE:0,METHOD_GPS:1,METHOD_CELL:2,METHOD_WIFI:3,METHOD_IP:4,_enabled:!1,setEnabled:function(enabled){this._enabled=!!enabled},getEnabled:function(){return this._enabled},getPositionMethod:function(){return this.METHOD_NONE},hasValidPosition:function(){return !1},getPosition:function(){return null},getAccuracy:function(){return -1},getAltitudeAccuracy:function(){return -1},getDirection:function(){return -1},getSpeed:function(){return -1},setOnPositionChange:function(callback){this._onPositionChangeCallback=this._prepareCallback(callback,"setOnPositionChange")},setOnStatusChange:function(callback){this._onStatusChangeCallback=this._prepareCallback(callback,"setOnStatusChange")}});var IMapObject=new Class({Name:"IMapObject",Extends:ISupports,initialize:function(iMap,type){this._iMap=iMap;this._type=type},MAPICON:0,TRAFFICEVENT:1,POLYLINE:2,POLYGON:3,COMPOSITE:4,ROUTE:5,LAYER:6,SAFETYSPOT:7,_IS_MAP_OBJECT:true,getType:function(){return this._type},_isVisible:true,setVisibility:function(visibility){if(this._isVisible!=visibility){this._isVisible=!!visibility;if(this._domElement){this._domElement.style.display=visibility?"":"none"}}},getVisibility:function(){return this._isVisible},_zIndex:0,setZIndex:function(zIndex){if(isNaN(zIndex)||zIndex<0||zIndex>65536||round(zIndex)!=zIndex){this._throwException("setZIndex",this._ILLEGAL_ARGUMENT)}if(this._zIndex!=zIndex){this._zIndex=zIndex;if(this._domElement){this._domElement.style.zIndex=zIndex}}},getZIndex:function(){return this._zIndex},_geoBoundingBox:null,_setGeoBoundingBox:function(geoBoundingBox){var needsUpdate,isExpansion;if(this._geoBoundingBox){if(geoBoundingBox){if(!this._geoBoundingBox._equals(geoBoundingBox)){this._geoBoundingBox=geoBoundingBox._copy();needsUpdate=1;isExpansion=geoBoundingBox._contains(this._geoBoundingBox)}}else{delete this._geoBoundingBox;needsUpdate=1}}else{if(geoBoundingBox){this._geoBoundingBox=geoBoundingBox._copy();needsUpdate=isExpansion=1}}if(needsUpdate&&this._parentMapObject){if(isExpansion){this._parentMapObject._recalcGeoBoundingBox(this._geoBoundingBox)}else{this._parentMapObject._recalcGeoBoundingBox()}}},_coversScreenCoordinate:function(point){return this._isVisible&&this._screenBoundingBox?this._screenBoundingBox._contains(point):!1},_recalcGeoBoundingBox:doNothing,_updateScreenPosition:doNothing,_isAncestorOrSelf:function(other){while(other&&this!==other){other=other._parentMapObject}return !!other}});var IMapIcon=new Class({Name:"IMapIcon",Extends:IMapObject,initialize:function(iMap){this._super(iMap,this.MAPICON)},_icon:null,setIcon:function(icon){if(icon===null){icon=this._iMap._plugin._genericIcon}else{if(!(icon instanceof IIcon)||!icon._domElement){this._throwException("setIcon",this._ILLEGAL_ARGUMENT)}}this._icon=icon;var domElement=icon._domElement.cloneNode(true),parentNode=this._domElement?this._domElement.parentNode:0;if(this._parentMapObject){this._parentMapObject._domElement.appendChild(domElement);if(this._domElement&&this._domElement.parentNode){this._domElement.parentNode.removeChild(this._domElement)}}this._domElement=domElement;domElement.style.display=this._isVisible?"":"none";this._setSize(icon,-1,-1)},getIcon:function(){return this._icon},_location:null,setLocation:function(location){this._location=!(location instanceof ILocation)?this._throwException("setLocation",this._ILLEGAL_ARGUMENT):location._copy();if(location._mercatorCoordinates){this._setGeoBoundingBox(new Rectangle([location._mercatorCoordinates]));this._updateScreenPosition()}},getLocation:function(){return this._location?this._location._copy():this._location},_bitmapNodeName:(new Image()).nodeName,setSize:function(width,height){var icon=this._icon;width*=1;height*=1;if(isNaN(width)||isNaN(height)||width*height<=0){this._throwException("setSize",this._ILLEGAL_ARGUMENT)}if(!icon||!icon._domElement||icon._domElement.nodeName===this._bitmapNodeName){this._throwException("setSize",this._ILLEGAL_STATE)}this._setSize(icon,width,height)},_setSize:function(icon,width,height){if(width<0){width=icon.getWidth();height=icon.getHeight()}if(!this._size||this._size._x!==width||this._size._y!==height){IIcon._setSize(this._domElement,this._size=new Point(width,height));(this._parentMapObject||this)._updateScreenPosition()}},_anchorPoint:new Point(0,0),setAnchorPoint:function(anchorPoint){if(anchorPoint instanceof IPixelCoordinates){this._anchorPoint=new Point(anchorPoint._x,anchorPoint._y);this._updateScreenPosition()}else{this._throwException("setAnchorPoint",this._ILLEGAL_ARGUMENT)}},getAnchorPoint:function(){return new IPixelCoordinates(this._anchorPoint._x,this._anchorPoint._y)},_updateScreenPosition:function(geoArea){if(this._isVisible&&this._parentMapObject&&this._geoBoundingBox&&this._domElement){var position=this._iMap._tileMap._mercatorToScreen(this._geoBoundingBox._upperLeft)._sub(this._anchorPoint);this._domElement.style.left=position._x+"px";this._domElement.style.top=position._y+"px";this._screenBoundingBox=new Rectangle([position,position._add(this._size)])}}});var IMapComposite=new Class({Name:"IMapComposite",Extends:IMapObject,initialize:function(iMap){this._super(iMap,this.COMPOSITE);this._mapObjects=[];this._domElement=iMap._createElement("div","IMapObject")},addMapObject:function(mapObject){if(!mapObject||!mapObject._IS_MAP_OBJECT||mapObject._isAncestorOrSelf(this)){this._throwException("addMapObject",this._ILLEGAL_ARGUMENT)}var parentObject=mapObject._parentMapObject;if(parentObject!==this){if(parentObject){parentObject.removeMapObject(mapObject)}this._mapObjects.push(mapObject);mapObject._parentMapObject=this;if(mapObject._geoBoundingBox){this._geoBoundingBox=mapObject._geoBoundingBox._join(this._geoBoundingBox)}if(mapObject._domElement){this._domElement.appendChild(mapObject._domElement);mapObject._updateScreenPosition();if(mapObject._screenBoundingBox){this._screenBoundingBox=mapObject._screenBoundingBox._join(this._screenBoundingBox)}}}},removeMapObject:function(mapObject){var idx=lastIndexOf(this._mapObjects,mapObject);if(idx>=0){this._mapObjects.splice(idx,1);delete mapObject._parentMapObject;if(mapObject._domElement){try{this._domElement.removeChild(mapObject._domElement)}catch(e){}}if(mapObject._geoBoundingBox){this._recalcGeoBoundingBox()}this._updateScreenPosition()}return idx>=0},removeAllMapObjects:function(){var length=this._mapObjects.length,i=length-1,mapObject;for(;i>=0;i--){mapObject=this._mapObjects[i];if(mapObject._domElement){try{this._domElement.removeChild(mapObject._domElement)}catch(e){}}delete mapObject._parentMapObject}this._mapObjects=[];this._recalcGeoBoundingBox();this._updateScreenPosition();return !!length},getMapObjects:function(){return new IArray(this._mapObjects)},_recalcGeoBoundingBox:function(increase){if(this._geoBoundingBox&&increase){this._geoBoundingBox=this._geoBoundingBox._join(increase)}else{var i=this._mapObjects.length-1,geoBoundingBox;delete this._geoBoundingBox;for(;i>=0;i--){if((geoBoundingBox=this._mapObjects[i]._geoBoundingBox)){this._geoBoundingBox=geoBoundingBox._join(this._geoBoundingBox)}}}},_updateScreenPosition:function(geoArea){var i=this._mapObjects.length-1,mapObject;delete this._screenBoundingBox;for(;i>=0;i--){(mapObject=this._mapObjects[i])._updateScreenPosition();if(mapObject._screenBoundingBox){this._screenBoundingBox=this._screenBoundingBox?this._screenBoundingBox._join(mapObject._screenBoundingBox):mapObject._screenBoundingBox._copy()}}},_coversScreenCoordinate:function(point){var isCovering,i;if(this._isVisible&&this._screenBoundingBox&&this._screenBoundingBox._contains(point)){for(i=this._mapObjects.length-1;!isCovering&&i>=0;i--){isCovering=this._mapObjects[i]._coversScreenCoordinate(point)}}return !!isCovering}});var IMapLayer=new Class({Name:"IMapLayer",Extends:IMapComposite,initialize:function(iMap){this._super(iMap);this._type=this.LAYER;this._domElement.className="IMapObject"},_IS_MAP_OBJECT:false,setVisibility:null,getVisibility:null});var IMapPolyline=new Class({Name:"IMapPolyline",Extends:IMapObject,initialize:function(iMap,type){this._super(iMap,arguments.length>1?type:this.POLYLINE);this._points=[];this._domElement=this.constructor._prototypeElement.cloneNode(true)},_points:[],_mercatorPoints:[],setPoints:function(points){points=points._array;var _points=[],_mercatorPoints=[],point,i=0,length=points.length;for(;i<length;i++){point=points[i];if(!(point instanceof IGeoCoordinates)||length<2){this._throwException("setPoints",this._ILLEGAL_ARGUMENT)}_points.push(point);_mercatorPoints.push(point._toMercator())}this._points=_points;this._mercatorPoints=_mercatorPoints;this._geoBoundingBox=new Rectangle(_mercatorPoints);this._updateScreenPosition()},getPoints:function(){var points=this._points.slice(),i=0,length=points.length;for(;i<length;i++){points[i]=points[i]._copy()}return new IArray(points)},_lineWidth:1,setLineWidth:function(width){if(isNumberOutOfRange(width,0,Number.POSITIVE_INFINITY)){this._throwException("setLineWidth",this._ILLEGAL_ARGUMENT)}this._lineWidth=width;this._updateLineWidth();this._updateScreenPosition()},getLineWidth:function(){return this._lineWidth},_lineColor:new IColor(0,0,255,255),setLineColor:function(color){if(!(color instanceof IColor)){this._throwException("setLineColor",this._ILLEGAL_ARGUMENT)}this._lineColor=color._copy();this._updateLineColor()},getLineColor:function(){return this._lineColor._copy()},_pathSuffix:"",_setVectorPath:browser.msie?function(path){this._domElement.path=path}:function(path){this._domElement.style.width=this._iMap._tileMap._mapSize._lowerRight._x+"px";this._domElement.style.height=this._iMap._tileMap._mapSize._lowerRight._y+"px";this._domElement.firstChild.setAttribute("d",path)},_updateScreenPosition:function(geoArea){var i=1,points=this._mercatorPoints,length=points.length,tileMap=this._iMap._tileMap,path=["M",tileMap._mercatorToScreen(points[0]),"L"],lineWidthExpansion=this._lineWidth/2;for(;i<length;i++){path.push(tileMap._mercatorToScreen(points[i]))}if(this._pathSuffix){path.push(this._pathSuffix)}this._setVectorPath(path.join(" "));this._screenBoundingBox=new Rectangle(this._mercatorPoints);this._screenBoundingBox._upperLeft=this._iMap._tileMap._mercatorToScreen(this._screenBoundingBox._upperLeft)._sub(new Point(lineWidthExpansion,lineWidthExpansion));this._screenBoundingBox._lowerRight=this._iMap._tileMap._mercatorToScreen(this._screenBoundingBox._lowerRight)._add(new Point(lineWidthExpansion,lineWidthExpansion))},_updateLineWidth:browser.msie?function(){this._domElement.firstChild.weight=this._lineWidth+"px";this._domElement.stroked=this._lineWidth?"t":"f"}:function(width){setAttribute(this._domElement.firstChild,"stroke-width",this._lineWidth)},_updateLineColor:browser.msie?function(){var stroke=this._domElement.firstChild;stroke.color=this._lineColor._getHexRgb();stroke.opacity=this._lineColor._alpha/255}:function(){var path=this._domElement.firstChild;setAttribute(path,"stroke",this._lineColor._getHexRgb());setAttribute(path,"stroke-opacity",this._lineColor._alpha/255)},_coversScreenCoordinate:function(point){var isCovering,i,len=this._mercatorPoints.length,p1;if(this._isVisible&&len>1&&this._screenBoundingBox&&this._screenBoundingBox._contains(point)){p1=this._iMap._tileMap._mercatorToScreen(this._mercatorPoints[0]);for(i=1;!isCovering&&i<len;i++){var p2=this._iMap._tileMap._mercatorToScreen(this._mercatorPoints[i]),xD=p2._x-p1._x,yD=p2._y-p1._y;if((xD!==0)||(yD!==0)){var u=((point._x-p1._x)*xD+(point._y-p1._y)*yD)/(xD*xD+yD*yD),cp=u<0?p1:(u>1?p2:new Point(p1._x+u*xD,p1._y+u*yD));isCovering=cp._distance(point)<this._lineWidth/2}p1=p2}}return !!isCovering}});IMapPolyline._prepare=function(iMap){var doc=iMap._document,namespace,proto,cssClassName="TileMapPoly",vmlBehavior="behavior:url(#default#VML);";if(browser.msie){doc.namespaces.add("vml","urn:schemas-microsoft-com:vml");addCssRule(iMap._styleSheet,"vml\\:shape",vmlBehavior+"position:absolute; width:1px; height:1px;");addCssRule(iMap._styleSheet,"vml\\:stroke",vmlBehavior);addCssRule(iMap._styleSheet,"vml\\:fill",vmlBehavior);var stroke=doc.createElement("<vml:stroke/>");proto=doc.createElement("<vml:shape/>");proto.coordSize="1 1";proto.filled=!1;stroke.joinstyle="round";stroke.endcap="round";stroke.color="#0000FF";stroke.opacity=1;stroke.weight="1px";proto.appendChild(stroke);proto.className=cssClassName;addCssRule(iMap._styleSheet,"."+cssClassName,"position:absolute;width:1px;height:1px;")}else{namespace="http://www.w3.org/2000/svg";var path=createElementNS(doc,namespace,"path");proto=createElementNS(doc,namespace,"svg");setAttribute(proto,"version","1.1");setAttribute(proto,"baseProfile","tiny");setAttribute(proto,"overflow","visible");proto.style.overflow="visible";setAttribute(path,"stroke","#0000ff");setAttribute(path,"stroke-width","1");setAttribute(path,"stroke-opacity","1");setAttribute(path,"stroke-linejoin","round");setAttribute(path,"stroke-linecap","round");setAttribute(path,"fill","none");proto.appendChild(path);proto.setAttribute("class",cssClassName);addCssRule(iMap._styleSheet,"."+cssClassName,"position:absolute;")}(this)._prototypeElement=proto};var IMapPolygon=new Class({Name:"IMapPolygon",Extends:IMapPolyline,initialize:function(aIMap){this._super(aIMap,this.POLYGON)},_fillColor:new IColor(0,0,255,255),setFillColor:function(color){if(!(color instanceof IColor)){this._throwException("setFillColor",this._ILLEGAL_ARGUMENT)}this._fillColor=color._copy();this._updateFillColor()},getFillColor:function(){return this._fillColor._copy()},_pathSuffix:browser.msie?"XE":"z",_updateFillColor:browser.msie?function(){var fill=this._domElement.childNodes[1];fill.color=this._fillColor._getHexRgb();fill.opacity=this._fillColor._alpha/255}:function(){var path=this._domElement.firstChild;setAttribute(path,"fill",this._fillColor._getHexRgb());setAttribute(path,"fill-opacity",this._fillColor._alpha/255)},_coversScreenCoordinate:function(point){var i,len=this._mercatorPoints.length,p1,count=0;if(this._isVisible&&len>1&&this._screenBoundingBox&&this._screenBoundingBox._contains(point)){p1=this._iMap._tileMap._mercatorToScreen(this._mercatorPoints[0]);for(i=0;i<len;i++){var p2=this._iMap._tileMap._mercatorToScreen(this._mercatorPoints[(i+1)%len]);if(p1._y<=point._y&&p2._y>=point._y||p1._y>=point._y&&p2._y<=point._y){var xD=p2._x-p1._x,yD=p2._y-p1._y,hx=p1._x+xD*(point._y-p1._y)/yD;count+=(point._x>hx?1:0)}p1=p2}}return(count%2)>0}});IMapPolygon._prepare=function(){var proto=((this)._prototypeElement=IMapPolyline._prototypeElement.cloneNode(true)),doc=proto.ownerDocument;if(browser.msie){proto.filled=!0;var fill=doc.createElement("<vml:fill/>");fill.color="#0000FF";fill.opacity=1;proto.appendChild(fill)}else{var path=proto.firstChild;setAttribute(path,"fill","#0000FF");setAttribute(path,"fill-opacity",1)}};var TileMapOptions=doNothing;var checkTileMapOptions=function(options){options.padding=max(options.padding||0,0);options.format=options.format||"png";return options&&options.limpidImage};var IMap=new Class({Name:"IMap",Extends:ISupports,initialize:function(aPlugin,containerElement,options){this._document=containerElement.ownerDocument;this._styleSheet=this._addCssStyleSheet();this._domElement=addElement(containerElement,"div","IMap");this._domElement.style.cssText="position:relative;width:100%;height:100%;overflow:hidden;z-index:0";this._panElement=addElement(this._domElement,"div","IMapPan");this._panElement.style.position="relative";this._setPanElementPosition(1);this._tileMap=new TileMap(this,this._panElement,options);this._tileMap._adjustSize();addCssRule(this._styleSheet,".IMapObject","background-color:transparent;position:absolute;z-index:0;");this._plugin=aPlugin;this._zoomLevels=new IArray(this._tileMap._zoomLevels);this._minZoomScale=this._tileMap._zoomLevels[this._tileMap._MAX_ZOOM_LEVEL];this._maxZoomScale=this._tileMap._zoomLevels[0];this._colorScheme=this.COLORS_DAY;this._mapType=this.TYPE_NORMAL;IMapPolyline._prepare(this);IMapPolygon._prepare();this._detailLevel=this.DETAIL_LEVEL_LESS;this._trafficInfoCenter=this._tileMap._geoCenter._copy();this._mapLayersElement=addElement(this._panElement,"div","IMapLayers");this._mapLayersElement.style.position="relative";this._mapLayers=[];this._routesMapLayer=new IMapLayer(this);this.addLayer(this._routesMapLayer)},_HIT_TEST_PADDING:new Point(100,100),ANIMATION_NONE:0,ANIMATION_LINEAR:1,ANIMATION_BOW:2,TYPE_NORMAL:1,TYPE_SATELLITE:2,TYPE_HYBRID:3,TYPE_TERRAIN:4,_TYPE_NAMES:",normal,satellite,hybrid,terrain".split(","),COLORS_DAY:1,COLORS_NIGHT:2,COLORS_AUTOMATIC:3,_COLOR_SCHEME_NAMES:",day,night,automatic".split(","),PRESERVE_SCALE:0,PRESERVE_ORIENTATION:32768,PRESERVE_PERSPECTIVE:1000,PERSPECTIVE_3D_DEFAULT:45,PED_CROSSWALK:0,PED_STAIRS:1,PED_ESCALATOR:2,PED_ELEVATOR:3,PED_TUNNEL:4,PED_BRIDGE:5,PED_ALL:6,TRAFFIC_ERROR:0,TRAFFIC_PENDING:1,TRAFFIC_COMPLETED:2,DETAIL_LEVEL_FULL:0,DETAIL_LEVEL_LESS:1,DETAIL_LEVEL_LEAST:2,_POINT_ZERO:new Point(0,0),setMapType:function(type){if(type!==this.TYPE_NORMAL&&type!==this.TYPE_SATELLITE&&type!==this.TYPE_HYBRID&&type!==this.TYPE_TERRAIN){this._throwException("setMapType",this._ILLEGAL_ARGUMENT)}this._mapType=type;this._update(0)},getMapType:function(){return this._mapType},_perspective:0,setPerspective:function(angle){},getPerspective:function(){return this._perspective},setZoomScale:function(zoomScale){if(isNumberOutOfRange(zoomScale,this._minZoomScale,this._maxZoomScale)){this._throwException("setZoomScale",this._ILLEGAL_ARGUMENT)}if(this._tileMap._setZoomScale(zoomScale,1)&&this._onScaleChangeCallback){this._onScaleChangeCallback()}},getZoomScale:function(){return this._tileMap._zoomScale},getMaxZoomScale:function(){return this._maxZoomScale},getMinZoomScale:function(){return this._minZoomScale},getZoomLevels:function(){return this._zoomLevels._copy()},setColorScheme:function(scheme){if(scheme!==this.COLORS_DAY&&scheme!==this.COLORS_NIGHT&&scheme!==this.COLORS_AUTOMATIC){this._throwException("setColorScheme",this._ILLEGAL_ARGUMENT)}this._colorScheme=scheme;this._update(0)},getColorScheme:function(){return this._colorScheme},_orientation:0,setOrientation:function(angle){},getOrientation:function(){return this._orientation},setCenter:function(center){this._tileMap._setCenter(center,true)},getCenter:function(){return this._tileMap._geoCenter._copy()},setTransformCenter:function(center){this._tileMap._setMapCenterOffset(new Point(center._x,center._y))},getTransformCenter:function(center){return new IPixelCoordinates(this._tileMap._mapCenterOffset._x,this._tileMap._mapCenterOffset._y)},getCopyright:function(){return"2008 Navteq, 2008 Nav2"},set3DLandmarksVisibility:function(visibility){if(visibility){this._3DLandmarksVisibility=!0}else{delete this._3DLandmarksVisibility}},get3DLandmarksVisibility:function(){return !!this._3DLandmarksVisibility},getDetailLevel:function(){return this._detailLevel},setDetailLevel:function(level){if(level!==this.DETAIL_LEVEL_FULL&&level!==this.DETAIL_LEVEL_LESS&&level!==this.DETAIL_LEVEL_LEAST){this._throwException("setDetailLevel",this._ILLEGAL_ARGUMENT)}this._detailLevel=level},_safetySpotsVisibility:!1,setSafetySpotsVisibility:function(visibility){this._safetySpotsVisibility=!!visibility},getSafetySpotsVisibility:function(){return this._safetySpotsVisibility},_trafficInfoVisibility:!1,setTrafficInfoVisibility:function(visibility){this._trafficInfoVisibility=!!visibility},getTrafficInfoVisibility:function(){return this._trafficInfoVisibility},_trafficInfoRadius:10,getTrafficInfoRadius:function(){return this._trafficInfoRadius},setTrafficInfoRadius:function(radius){if(isNumberOutOfRange(radius,1,1000)){this._throwException("setTrafficInfoRadius",this._ILLEGAL_ARGUMENT)}},getTrafficInfoCenter:function(){return this._trafficInfoCenter._copy()},setTrafficInfoCenter:function(center){this._trafficInfoCenter=center._copy()},setOnMoveDone:function(callback){this._onMoveDoneCallback=this._prepareCallback(callback,"setOnMoveDone")},setOnScaleChange:function(callback){this._onScaleChangeCallback=this._prepareCallback(callback,"setOnScaleChange")},setOnOrientationChange:function(callback){this._onOrientationChangeCallback=this._prepareCallback(callback,"setOnOrientationChange")},setOnPerspectiveChange:function(callback){this._onPerspectiveChangeCallback=this._prepareCallback(callback,"setOnPerspectiveChange")},setOnAnimationDone:function(callback){this._onAnimationDoneCallback=this._prepareCallback(callback,"setOnAnimationDone")},_poiCategoryNames:"AIRLINEACCESS AMUSEMENTPARK CARDEALER CASINO CINEMA COMPANY CONCERTHALL CONGRESS COURTHOUSE CULTURALCENTRE EXHIBITIONCENTRE GOLFCOURSE GOVERNMENTOFFICE HOLIDAYPARK MUSEUM OPERA PARKINGGARAGE PETROLSTATION PLACEOFWORSHIP POSTOFFICE RENTACARFACILITY RESTAREA RESTAURANT SHOP SHOPPINGCENTRE STADIUM THEATRE TOURISTATTRACTION TOURISTINFORMATIONCENTRE UNIVERSITY ZOO LIBRARY CAMPING BARDISCO EMBASSY FERRYTERMINAL FRONTIERCROSSING HOSPITAL HOTEL PARKINGAREA POLICE RAILWAYSTATION UNDERGROUNDSTATION AIRPORT MOUNTAINPASS MOUNTAINPEAK CARREPAIR CASHDISPENSER PARKRECREATION PHARMACY BEACH 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098 099 100 101 102 103 104 105 EDUCATION 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 RAILWAYSTATION_ACCESS BARS_CAFES PARKING SPORT_OUTDOOR METRO_ACCESS AUT_METRO_ACCESS AUT_METRO_STOP BEL_METRO_ACCESS BEL_METRO_STOP CZE_METRO_ACCESS CZE_METRO_STOP DEN_METRO_ACCESS DEN_METRO_STOP FIN_METRO_ACCESS FIN_METRO_STOP FRA_METRO_ACCESS FRA_METRO_STOP FRA_RER_ACCESS FRA_RER_STOP DEU_METRO_ACCESS DEU_METRO_STOP DEU_SBAHN_ACCESS DEU_SBAHN_STOP ITA_METRO_ACCESS ITA_METRO_STOP NOR_METRO_ACCESS NOR_METRO_STOP PRT_METRO_ACCESS PRT_METRO_STOP ESP_BARCA_METRO_ACCESS ESP_BARCA_METRO_STOP ESP_CERCA_METRO_ACCESS ESP_CERCA_METRO_STOP ESP_MADRID_METRO_ACCESS ESP_MADRID_METRO_STOP SWE_METRO_ACCESS SWE_METRO_STOP GBR_GLASGOW_METRO_ACCESS GBR_GLASGOW_METRO_STOP GBR_LONDON_METRO_ACCESS GBR_LONDON_METRO_STOP ALL INVALID".split(" "),_poiCategories:{},getPoiCategories:function(){return new IArray(this._poiCategoryNames)},_getPoiCategoryByName:function(methodName,categoryName){if(!this._poiCategories.hasOwnProperty(categoryName)){this._throwException(methodName,this._ILLEGAL_ARGUMENT)}return this._poiCategories[categoryName]},showPoiCategory:function(name,visibility){this._getPoiCategoryByName("showPoiCategory",name)._isVisible=!!visibility},isPoiCategoryVisible:function(name){return this._getPoiCategoryByName("isPoiCategoryVisible",name)._isVisible},getPoiIcon:function(name){return this._getPoiCategoryByName("getPoiIcon",name)._icon||this._plugin._genericIcon},showPedestrianFeature:function(feature,visibility){if(isNumberOutOfRange(feature,this.PED_CROSSWALK,this.PED_ALL)){this._throwException("showPedestrianFeature",this._ILLEGAL_ARGUMENT)}},moveTo:function(center,animation,zoomScale,orientation,perspective){if(center!==null){this.setCenter(center)}if(zoomScale!==this.PRESERVE_SCALE){this.setZoomScale(zoomScale)}if(this._onAnimationDoneCallback&&animation!==this.ANIMATION_NONE){this._onAnimationDoneCallback()}},showPoints:function(points,center,animation,orientation,perspective){var geoRectangle=new GeoRectangle(points._array);if(center!==null){geoRectangle._addMidpoint(center)}this.moveTo(geoRectangle._getMidpoint(),animation,this._tileMap._getZoomScaleForGeoArea(geoRectangle),orientation,perspective)},jumpByPixel:function(xOffset,yOffset){var offset=new Point(-xOffset,-yOffset),layer=this._tileMap._tileLayer;this._setPanElementPosition(0,offset);this._center=layer._mapPixelToMercator(layer._mercatorToMapPixel(this._center)._sub(offset));this._tileMap._geoCenter=IGeoCoordinates._fromMercator(this._center);this._update(150);if(this._onMoveDoneCallback){this._onMoveDoneCallback(300)}},jumpToPixel:function(center){this.jumpByPixel(center._x-this._tileMap._mapCenterOffset._x,center._y-this._tileMap._mapCenterOffset._y)},convertToGeo:function(coordinate){return this._tileMap._mapSize._contains(coordinate)?this._tileMap._screenToGeo(coordinate):null},convertToScreen:function(aGeoCoordinates){var coordinate=this._tileMap._geoToScreen(aGeoCoordinates);return this._tileMap._mapSize._contains(coordinate)?new IPixelCoordinates(coordinate._x,coordinate._y):null},addRoute:function(route){if(!(route instanceof IRoute)){this._throwException("addRoute",this._ILLEGAL_ARGUMENT)}this._routesMapLayer.addMapObject(route)},removeRoute:function(route){return this._routesMapLayer.removeMapObject(route)},addLayer:function(layer){if(!(layer instanceof IMapLayer)){this._throwException("addLayer",this._ILLEGAL_ARGUMENT)}if(lastIndexOf(this._mapLayers,layer)<0){this._mapLayers.push(layer);this._mapLayersElement.appendChild(layer._domElement)}},removeLayer:function(layer){var index=lastIndexOf(this._mapLayers,layer);if(index>=0){this._mapLayers.splice(index,1);this._mapLayersElement.removeChild(layer._domElement)}return index>=0},getMapObjects:function(point){if(!(point instanceof IPixelCoordinates)){this._throwException("getMapObjects",this._ILLEGAL_ARGUMENT)}if(this._tileMap._mapSize._contains(point)){var mapObject,mapObjects,i,boundingBox=new Rectangle([point._sub(this._HIT_TEST_PADDING),point._add(this._HIT_TEST_PADDING)])._intersection(this._tileMap._mapSize);boundingBox._upperLeft=this._tileMap._screenToMercator(boundingBox._upperLeft);boundingBox._lowerRight=this._tileMap._screenToMercator(boundingBox._lowerRight);mapObjects=this._getMapObjectsForGeoArea(boundingBox,boundingBox._intersects);for(i=mapObjects.length-1;i>=0;i--){if(!mapObjects[i]._coversScreenCoordinate(point)){mapObjects.splice(i,1)}}if(mapObjects.length>1){mapObjects.sort(function(a,b){return point._distance(a._screenBoundingBox._getMidpoint())-point._distance(b._screenBoundingBox._getMidpoint())})}}return new IArray(mapObjects||[])},getMapObjectsIn:function(coord1,coord2){if(!(coord1 instanceof IPixelCoordinates)||!(coord2 instanceof IPixelCoordinates)){this._throwException("getMapObjectsIn",this._ILLEGAL_ARGUMENT)}var boundingBox=new Rectangle([coord1,coord2])._intersection(this._tileMap._mapSize);boundingBox._upperLeft=this._tileMap._screenToMercator(boundingBox._upperLeft);boundingBox._lowerRight=this._tileMap._screenToMercator(boundingBox._lowerRight);var mapObjectsIn=this._getMapObjectsForGeoArea(boundingBox,boundingBox._contains);if(mapObjectsIn.length>1){var midpoint=boundingBox._getMidpoint();mapObjectsIn.sort(function(a,b){return midpoint._distance(a._geoBoundingBox._getMidpoint())-midpoint._distance(b._geoBoundingBox._getMidpoint())})}return new IArray(mapObjectsIn)},_getMapObjectsForGeoArea:function(geoArea,filter){var filtered=[],i,mapObjects,j,mapObject;if(geoArea){for(i=this._mapLayers.length-1;i>=0;i--){mapObjects=this._mapLayers[i]._mapObjects;for(j=mapObjects.length-1;j>=0;j--){mapObject=mapObjects[j];if(mapObject._isVisible&&filter.call(geoArea,mapObject._geoBoundingBox)){filtered.push(mapObject)}}}}return filtered},getTimeOffset:function(point){return round(point._longitude/15)*60},_autoTracking:true,setAutoTracking:function(enabled){this._autoTracking=!!enabled},getAutoTracking:function(){return this._autoTracking},_positionCursor:null,setPositionCursor:function(icon){this._positionCursor=icon},getPositionCursor:function(icon){return this._positionCursor},_createElement:function(elementName,className){var element=this._document.createElement(elementName);if(className){element.className=className}return element},_setPanElementPosition:function(isAbsolute,position){if(isAbsolute){this._panElementPosition=(position||this._POINT_ZERO)._copy()}else{if(position){this._panElementPosition=this._panElementPosition._add(position)}}this._panElement.style.left=this._panElementPosition._x+"px";this._panElement.style.top=this._panElementPosition._y+"px"},_addCssStyleSheet:function(){var doc=this._document,styles=doc.styleSheets,styleSheet=doc.createElement("style");styleSheet.setAttribute("type","text/css");doc.getElementsByTagName("head")[0].appendChild(styleSheet);styleSheet=styles[styles.length-1];return styleSheet},_delayedUpdateTimeout:-1,_delayedUpdate:function(timeout,center,mapCenterOffset,zoomLevel){clearTimeout(this._delayedUpdateTimeout);if(timeout>=0){var that=this;this._delayedUpdateTimeout=setTimeout(function(){that._delayedUpdate(-1,center,mapCenterOffset,zoomLevel)},timeout||0)}else{this._setPanElementPosition(1);this._center=center;this._tileMap._mapCenterOffset=mapCenterOffset;this._tileMap.zoomLevel=zoomLevel;for(var level=this._tileMap._MAX_ZOOM_LEVEL;level>=0;level--){this._tileMap._tileLayers[level]._update()}for(var i=this._mapLayers.length-1;i>=0;i--){this._mapLayers[i]._updateScreenPosition()}}},_update:function(timeout){this._delayedUpdate(arguments.length?timeout:50,this._center._copy(),this._tileMap._mapCenterOffset._copy(),this._tileMap._zoomLevel)}});nokia.aduno.utils.Collection.forEach(IMap.prototype._poiCategoryNames,function(aValue,aKey){this._poiCategories[aValue]={_isVisible:!1,_icon:null}},IMap.prototype);var IAppearance=new Class({Extends:ISupports,initialize:function(map){this._map=map;this._overviewMapPosition=this.POS_SE},POS_SE:0,POS_SW:1,POS_NW:2,POS_NE:3,_overviewMapVisibility:false,setOverviewMapVisibility:function(visibility){if(this._overviewMapVisibility!=visibility){this._overviewMapVisibility=!!visibility;if(visibility){}}},getOverviewMapVisibility:function(){return this._overviewMapVisibility},setOverviewMapPosition:function(position){if(position<this.POS_SE||position>this.POS_NE){this._throwException("setOverviewMapPosition",this._ILLEGAL_ARGUMENT)}if(this._overviewMapPosition!=position){this._overviewMapPosition=position;if(this._overviewMapVisibility){}}},getOverviewMapPosition:function(){return this._overviewMapPosition},_getDimension:function(){var callee=arguments.callee;if(!callee._dimension){callee._dimension=nokia.aduno.dom.Dimensions.getCoordinates(this._map._domElement);setTimeout(function(){callee._dimension=0},0)}return callee._dimension},getLeft:function(){return this._getDimension().left},getTop:function(){return this._getDimension().top},getWidth:function(){return this._getDimension().width},getHeight:function(){return this._getDimension().height}});var IPlugin=new Class({Name:"IPlugin",Extends:ISupports,initialize:function(containerElement,options){if(!containerElement||!checkTileMapOptions(options,containerElement.ownerDocument)){this._throwException("initialize",this._ILLEGAL_ARGUMENT)}this._containerElement=containerElement;this._tileMapOptions=options;return this},LOG_INFO:0,LOG_WARNING:1,LOG_ERROR:2,LOG_DEBUG:3,MAP_INTERNATIONAL_VARIANT:0,MAP_CHINESE_VARIANT:1,MAP_PAKISTANI_VARIANT:2,adjustMapSize:function(){this._tileMap._adjustSize()},setup:function(mapVariant){this._errorDescription="setup failed";this._svgRenderer=new SvgRenderer(this._containerElement.ownerDocument);this._genericIcon=this.createIconFromSvg('<svg xmlns="http://www.w3.org/2000/svg" width="22px" height="32px"><path transform="translate(11,11) scale(10)" fill="blue" opacity=".65" stroke-width=".15" stroke="black" d="M 0 2 C 0 1 1 0.5523 1 0 C 1 -0.5523 0.5523 -1 0 -1 C -0.5523 -1 -1 -0.5523 -1 0 C -1 0.5523 0 1 0 2 z"/></svg>');this._map=new IMap(this,this._containerElement,this._tileMapOptions);this._appearance=new IAppearance(this._map);this._persistence=new IPersistence(this);this._positionProvider=new IPositionProvider(this);this._errorDescription=""},_domParser:new nokia.aduno.dom.Parser(),_errorDescription:"not setted up",getErrorDescription:function(){return this._errorDescription},shutdown:function(){},getVersionPlugin:function(){return"2.2.32.2."+(/\d+/.exec("$Revision: 7940 $")[0])},getVersionAPI:function(){return"2.0.2"},getDeviceType:function(){return"proxy"},getUUID:function(){return null},_onlineMode:true,setOnlineMode:function(allowed){this._onlineMode=!!allowed},getOnlineMode:function(){return this._onlineMode},_logLevelMapping:{0:"info",1:"warn",2:"error",3:"debug"},log:function(level,message){try{nokia.aduno.utils[this._logLevelMapping[level]](message)}catch(e){}},_language:"DEF",setLanguage:function(language){language=(""+language).toUpperCase();if(language!=="DEF"&&!(new RegExp("\\b"+language+"\\b").test("ABW,AFG,AGO,AIA,ALA,ALB,AND,ANT,ARE,ARG,ARM,ASM,ATA,ATF,ATG,AUS,AUT,AZE,BDI,BEL,BEN,BFA,BGD,BGR,BHR,BHS,BIH,BLM,BLR,BLZ,BMU,BOL,BRA,BRB,BRN,BTN,BVT,BWA,CAF,CAN,CCK,CHE,CHL,CHN,CIV,CMR,COD,COG,COK,COL,COM,CPV,CRI,CUB,CXR,CYM,CYP,CZE,DEU,DJI,DMA,DNK,DOM,DZA,ECU,EGY,ERI,ESH,ESP,EST,ETH,FIN,FJI,FLK,FRA,FRO,FSM,GAB,GBR,GEO,GGY,GHA,GIB,GIN,GLP,GMB,GNB,GNQ,GRC,GRD,GRL,GTM,GUF,GUM,GUY,HKG,HMD,HND,HRV,HTI,HUN,IDN,IMN,IND,IOT,IRL,IRN,IRQ,ISL,ISR,ITA,JAM,JEY,JOR,JPN,KAZ,KEN,KGZ,KHM,KIR,KNA,KOR,KWT,LAO,LBN,LBR,LBY,LCA,LIE,LKA,LSO,LTU,LUX,LVA,MAC,MAF,MAR,MCO,MDA,MDG,MDV,MEX,MHL,MKD,MLI,MLT,MMR,MNE,MNG,MNP,MOZ,MRT,MSR,MTQ,MUS,MWI,MYS,MYT,NAM,NCL,NER,NFK,NGA,NIC,NIU,NLD,NOR,NPL,NRU,NZL,OMN,PAK,PAN,PCN,PER,PHL,PLW,PNG,POL,PRI,PRK,PRT,PRY,PSE,PYF,QAT,REU,ROU,RUS,RWA,SAU,SDN,SEN,SGP,SGS,SHN,SJM,SLB,SLE,SLV,SMR,SOM,SPM,SRB,STP,SUR,SVK,SVN,SWE,SWZ,SYC,SYR,TCA,TCD,TGO,THA,TJK,TKL,TKM,TLS,TON,TTO,TUN,TUR,TUV,TWN,TZA,UGA,UKR,UMI,URY,USA,UZB,VAT,VCT,VEN,VGB,VIR,VNM,VUT,WLF,WSM,YEM,ZAF,ZMB,ZWE"))){this._invalidArgumentError("IMap::setLanguage","language",language,"Invalid language code.")}this._language=language},getLanguage:function(){return this._language},getAppearance:function(){return this._appearance},getMap:function(){return this._map},getPersistence:function(){return this._persistence},getGuidance:function(){return null},getPositionProvider:function(){return this._positionProvider},getConnectivity:function(){return null},getDeviceManager:function(){return null},createArray:function(){return new IArray()},createColor:function(r,g,b,a){var value,i=0;for(;i<4;i++){value=arguments[i];if(isNumberOutOfRange(value,0,255)||round(value!=value)){this._throwException("createColor",this._ILLEGAL_ARGUMENT)}}return new IColor(r,g,b,a)},createGeoCoordinates:function(latitude,longitude){return new IGeoCoordinates(latitude,longitude)},createPixelCoordinates:function(x,y){return new IPixelCoordinates(x,y)},createFinder:function(){return new IFinder(this)},createHttpRequest:function(){return new IHttpRequest(this)},createIconFromUrl:function(url,callback){var icon=new IIcon(this);icon._onDoneCallback=this._prepareCallback(callback,"createIconFromUrl",icon);icon._load(url)},createIconFromSvg:function(markup){var icon=new IIcon(this);icon._parseSvg(markup);return icon},createLayer:function(){return new IMapLayer(this._map)},createMapComposite:function(){return new IMapComposite(this._map)},createLocation:function(){return new ILocation()},createMapIcon:function(){return new IMapIcon(this._map)},createMapPolyline:function(points,lineColor,lineWidth){var polyline=new IMapPolyline(this._map);polyline.setPoints(points);if(lineColor!==null){polyline.setLineColor(lineColor)}if(lineWidth!==null){polyline.setLineWidth(lineWidth)}return polyline},createMapPolygon:function(points,lineColor,lineWidth,fillColor){var polygon=new IMapPolygon(this._map);polygon.setPoints(points);if(lineColor!==null){polygon.setLineColor(lineColor)}if(lineWidth!==null){polygon.setLineWidth(lineWidth)}if(fillColor!==null){polygon.setFillColor(fillColor)}return polygon},createRoutePlan:function(stopovers){var plan=new IRoutePlan(this);plan.addStopovers(stopovers);return plan},createRouter:function(){return new IRouter(this)},createRouteOptions:function(){return new IRouteOptions(this)}});var TileLayer=new Class({Name:"TileLayer",initialize:function(tileMap,level){this._tileMap=tileMap;this._level=level;this._totalPixelsPerAxis=(this._totalTilesPerAxis=pow(2,level))*tileMap._TILE_SIZE;this._domElement=addElement(tileMap._domElement,"div","TileLayer")},_BASE_URL:"http://maptile.svc.nokia.com.edgesuite.net/maptiler/maptile/newest/",_stoppLoading:function(){var tiles=this._domElement.childNodes,i=tiles.length-1,tile;for(;i>=0;i--){tile=tiles[i];if(tile._loader){removeNode(tile);this._cleanupTile(tile)}}this._outStandingTilesCount=0},_onTileLoadHandler:function(){var tile=this._tile,layer=tile._layer;tile.className="";tile.src=this.src;this._tileCache._addTile(this._tileId,tile,this._timeStamp);layer._cleanupTile(tile);if(!layer._outStandingTilesCount){layer._tileMap._onTielLayerLoad(layer._level)}},_onTileErrorHandler:function(){var tile=this._tile;tile.className="TileError";tile._layer._cleanupTile(tile)},_cleanupTile:function(tile){var loader=tile._loader;loader._tile=tile._loader=tile._layer=loader._tileCache=loader.onload=loader.onerror=null;if(--this._outStandingTilesCount<0){this._outStandingTilesCount=0}},_tileDisanceSorter:function(first,second){return first._centerDistance>second._centerDistance?-1:first._centerDistance==second._centerDistance?0:1},_update:function(){var layerNode=this._domElement,layerStyle=layerNode.style,levelDelta=this._tileMap._zoomLevel-this._level;if(levelDelta){this._stoppLoading()}if(isNumberOutOfRange(levelDelta,-1,4)){layerStyle.display="none"}else{layerStyle.display="block";layerStyle.zIndex=-abs(2*levelDelta-(levelDelta>0));var center=this._mercatorToMapPixel(this._tileMap._iMap._center),scaling=pow(2,levelDelta),px="px",tileSize=this._tileMap._TILE_SIZE,scaledTileSize=scaling*tileSize,centerOffset=this._tileMap._mapCenterOffset,layerOffset,padding=this._tileMap._padding,origin,tilePoint,row=0,col,tile,firstTileImage,tileStyle,layerSize,tmp,timestamp=new Date()-0,tiles=[];layerOffset=centerOffset._modulo(tileSize)._sub(center._modulo(tileSize))._modulo(tileSize);layerOffset=layerOffset._sub(new Point(layerOffset._x>0?tileSize:0,layerOffset._y>0?tileSize:0));if((tmp=padding+layerOffset._x)>0){layerOffset._x-=ceil(tmp/tileSize)*tileSize}if((tmp=padding+layerOffset._y)>0){layerOffset._y-=ceil(tmp/tileSize)*tileSize}layerSize=new Point(this._tileMap._mapSize._lowerRight._x-layerOffset._x+padding,this._tileMap._mapSize._lowerRight._y-layerOffset._y+padding);origin=center._sub(centerOffset)._add(layerOffset);origin._x=normalizeNumber(origin._x,this._totalPixelsPerAxis);layerOffset._x=centerOffset._x-scaling*abs(centerOffset._x-layerOffset._x);layerOffset._y=centerOffset._y-scaling*abs(centerOffset._y-layerOffset._y);layerStyle.left=layerOffset._x+px;layerStyle.top=layerOffset._y+px;tilePoint=this._pixelToTile(origin);while(row*tileSize<=layerSize._y){col=0;while(col*tileSize<=layerSize._x){tile=this._getTile(tilePoint._x+col,tilePoint._y+row,timestamp,levelDelta);if(tile){if(tile._loader){tile._centerDistance=abs(center._x-(origin._x+col*tileSize+tileSize/2))+abs(center._y-(origin._y+row*tileSize+tileSize/2));tiles.push(tile)}tileStyle=(this._domElement.appendChild(tile)).style;tileStyle.top=row*scaledTileSize+px;tileStyle.left=col*scaledTileSize+px;tileStyle.width=(tileStyle.height=scaledTileSize+px);if(!firstTileImage){firstTileImage=tile}}col++}row++}this._removeAllTilesBefore(firstTileImage);this._outStandingTilesCount=tiles.length;tiles.sort(this._tileDisanceSorter);for(tmp=tiles.length-1;tmp>=0;tmp--){tiles[tmp]._loader.src=tiles[tmp]._loader._source}}},_getTile:function(x,y,timeStamp,onlyCached){var totalTilesPerAxis=this._totalTilesPerAxis;if(y>=0&&y<totalTilesPerAxis){x=x<0?totalTilesPerAxis-(x%totalTilesPerAxis):x%totalTilesPerAxis;var tileId=[this._tileMap._iMap._mapType,this._tileMap._iMap._colorScheme,this._level,x,y].join("-"),tile=this._tileMap._tileCache._getTile(tileId,timeStamp);if(!tile){if(!onlyCached){tile=this._tileMap._tilePlaceHolder.cloneNode(!1);tile._layer=this;var loader=(tile._loader=new Image()),iMap=this._tileMap._iMap;loader._tileId=tileId;loader._tileCache=this._tileMap._tileCache;loader._tile=tile;loader.onload=this._onTileLoadHandler;loader.onerror=this._onTileErrorHandler;loader._source=[this._BASE_URL,iMap._TYPE_NAMES[iMap._mapType===iMap.TYPE_HYBRID?iMap.TYPE_SATELLITE:iMap._mapType],".",iMap._COLOR_SCHEME_NAMES[iMap.COLORS_DAY],"/",this._level,"/",x,"/",y,"/",this._tileMap._TILE_SIZE,"/",this._tileMap._options.format,"?token=",this._tileMap._options.token,(this._tileMap._options.host?"&referer="+this._tileMap._options.host:"")].join("")}}else{if(tile.parentNode){tile=tile.cloneNode(!1)}}}return tile},_removeAllTilesBefore:function(tile,stopLoading){var firstTile,loader;while((firstTile=this._domElement.firstChild)&&firstTile!==tile){loader=firstTile._loader;if(stopLoading&&loader){firstTile._loader.onload=firstTile._loader.onerror=null;firstTile._loader.src="";this.cleanupTile(firstTile)}this._domElement.removeChild(firstTile)}},_mapPixelToMercator:function(pixel){var point=new Point((pixel._x/this._totalPixelsPerAxis)%1,(pixel._y/this._totalPixelsPerAxis)%1);return point},_mercatorToMapPixel:function(mercator){return new Point(round(mercator._x*this._totalPixelsPerAxis),round(mercator._y*this._totalPixelsPerAxis))},_pixelToTile:function(pixelPoint){return new Point(floor(abs(pixelPoint._x%this._totalPixelsPerAxis)/this._tileMap._TILE_SIZE),floor(pixelPoint._y/this._tileMap._TILE_SIZE))}});var TileCache=new Class({Name:"TileCache",initialize:function(maxTiles){this._maxTiles=maxTiles;this._tiles={};this._counter=0;var that=this;this._sortTimeStampDescending=function(id1,id2){return that._tiles[id2]._timeStamp-that._tiles[id1]._timeStamp}},_cleanupTimeout:-1,_cleanup:function(instantly){var tmp=this._counter;if(this._counter>this._maxTiles){var that=this;if(instantly){var tileIDs=[],tileId,i;for(tileId in this._tiles){if(this._tiles.hasOwnProperty(tileId)){tileIDs.push(tileId)}}tileIDs.sort(this._sortTimeStampDescending);for(i=tileIDs.length-1;i>=0&&this._counter>this._maxTiles;i--){delete this._tiles[tileIDs[i]];this._counter-=1}}else{clearTimeout(this._cleanupTimeout);this._cleanupTimeout=setTimeout(function(){that._cleanup(1)},50000)}}},_getTile:function(tileId,timeStamp){var tile=this._tiles[tileId];if(tile){tile._timeStamp=timeStamp||(new Date()-0)}return tile},_addTile:function(tileId,tile,timeStamp){if(!this._tiles[tileId]){this._counter+=1;this._tiles[tileId]=tile;tile._timeStamp=timeStamp||(new Date()-0)}}});var TileMap=new Class({Name:"TileMap",initialize:function(iMap,containerElement,options){this._iMap=iMap;this._options=options;this._tilePlaceHolder=new Image();this._tilePlaceHolder.unselectable="on";this._tilePlaceHolder.style.MozUserSelect="none";this._tilePlaceHolder.src=options.limpidImage;this._tilePlaceHolder.className="TileLoading";this._padding=options.padding;this._tileCache=new TileCache(500);this._tileLayers=[];this._zoomLevels=[];this._domElement=addElement(containerElement,"div","TileMap");this._domElement.style.position="relative";addCssRule(iMap._styleSheet,".TileLayer","background-color:transparent;position:absolute;");addCssRule(iMap._styleSheet,".TileLayer img","background-color:transparent;position:absolute;");for(var level=this._MAX_ZOOM_LEVEL;level>=0;level--){this._tileLayers[level]=new TileLayer(this,level);this._zoomLevels[level]=round(4000000000/this._tileLayers[level]._totalPixelsPerAxis)}this._iMap._center=(this._geoCenter=new IGeoCoordinates(PI,PI))._toMercator();this._setZoomLevel(round(this._zoomLevels.length/2));this._mapSize=new Rectangle([new Point(-1,-1),new Point(-1,-1)])},_TILE_SIZE:256,_MAX_ZOOM_LEVEL:17,_setZoomLevel:function(zoomLevel){var hasChanged=!1;if(!isNaN(zoomLevel)){zoomLevel=max(0,min(this._MAX_ZOOM_LEVEL,zoomLevel));hasChanged=this._zoomLevel!=zoomLevel;if(hasChanged){this._zoomLevel=zoomLevel;this._tileLayer=this._tileLayers[zoomLevel];this._zoomScale=this._zoomLevels[zoomLevel]}}return hasChanged},_zoomScaleToLevel:function(scale){return -round(log((scale*this._TILE_SIZE)/4000000000)/LN2)},_setZoomScale:function(zoomScale,immediately){if(this._setZoomLevel(this._zoomScaleToLevel(zoomScale))){this._iMap._update(immediately?-1:0);return true}},_onTielLayerLoad:function(level){if(level===this._zoomLevel){for(var i=this._tileLayers.length-1;i>=0;i--){if(i!==level){this._tileLayers[i]._domElement.style.display="none"}}}},_adjustSize:function(){var mapSize=new Rectangle([new Point(0,0),new Point(this._iMap._domElement.offsetWidth,this._iMap._domElement.offsetHeight)]);if(!this._mapSize._equals(mapSize)){this._mapSize=mapSize;this._mapCenterOffset=new Point(round(mapSize._lowerRight._x/2),round(mapSize._lowerRight._y/2));this._iMap._update()}},_setCenter:function(geoCenter,isUpdating){var changed;if(!this._geoCenter.equals(geoCenter)){this._geoCenter=geoCenter._copy();var center=geoCenter._toMercator();if(!this._iMap._center._equals(center)){this._iMap._center=center;changed=1;if(isUpdating){this._iMap._update()}}}if(this._iMap._onMoveDoneCallback){this._iMap._onMoveDoneCallback(300)}return !!changed},_setMapCenterOffset:function(offset){if(!this._mapCenterOffset._equals(offset)){this._iMap._center=this._screenToMercator(offset);this._geoCenter=IGeoCoordinates._fromMercator(this._iMap._center);this._mapCenterOffset=offset._copy()}},_moveTo:function(center,zoomScale){if(this._setZoomLevel(this._zoomScaleToLevel(zoomScale))||this._setCenter(center)){this._iMap._update()}},_getZoomScaleForGeoArea:function(area){var northWest=area._northWest._toMercator(),southEast=area._southEast._toMercator(),deltaX=abs(northWest._x-southEast._x),deltaY=abs(northWest._y-southEast._y),level=this._MAX_ZOOM_LEVEL,layer;for(;level;level--){layer=this._tileLayers[level];if(deltaX*layer._totalPixelsPerAxis+20<this._mapSize._lowerRight._x&&deltaY*layer._totalPixelsPerAxis+20<this._mapSize._lowerRight._y){break}}return this._zoomLevels[level]},_screenToGeo:function(offset){return IGeoCoordinates._fromMercator(this._screenToMercator(offset))},_screenToMercator:function(offset){var layer=this._tileLayer;return layer._mapPixelToMercator(layer._mercatorToMapPixel(this._iMap._center)._add(offset._sub(this._mapCenterOffset)))},_geoToScreen:function(point){return this._mercatorToScreen(point._toMercator())},_mercatorToScreen:function(point){return this._tileLayer._mercatorToMapPixel(point._sub(this._iMap._center))._add(this._mapCenterOffset)}});var IHttpRequest=new Class({Name:"IHttpRequest",Extends:ISupports,initialize:function(){this._request=new nokia.aduno.XHttpRequest();var that=this;this._request.onreadystatechange=function(){that._onReadyStateChange();if(that._request.readyState==4){that._request.onreadystatechange=doNothing;that=(that._request=null)}};this._onReadyStateChange()},UNSENT:0,OPENED:1,HEADERS_RECEIVED:2,LOADING:3,DONE:4,responseText:"",onreadystatechange:null,setRequestHeader:function(name,value){this._request.setRequestHeader(name,value)},send:function(data){this._request.send(arguments.length?data:null)},getResponseHeader:function(header){return this._request.getResponseHeader(header)},getAllResponseHeaders:function(){return this._request.getAllResponseHeaders()},open:function(method,url,async,user,password){if(method!=="GET"&&method!=="POST"){this._throwException("open",this._ILLEGAL_ARGUMENT)}var resolvedUrl=""+url;if(!this._schemeRegExp.test(resolvedUrl)){var loc=document.location;if(resolvedUrl.indexOf("/")){resolvedUrl=document.baseURI.replace(this._pathRegExp,"")+resolvedUrl}else{resolvedUrl=loc.protocol+"//"+loc.hostname+(loc.port?":"+loc.port:"")+resolvedUrl}}this._request.open(method,resolvedUrl,!!async,user||null,password||null)},abort:function(){this._request.abort()},_onReadyStateChange:function(){if(!browser.msie||this._request.readystate!==2){this.status=this._request.status;this.readyState=this._request.readyState;this.responseText=this._request.responseText;if(this.onreadystatechange){this.onreadystatechange(this)}}},_schemeRegExp:/^[a-zA-Z0-9\-\.\+]+\:/,_pathRegExp:/[^\/]*$/});var IFinder=new Class({Name:"IFinder",Extends:ISupports,initialize:function(iPlugin){this._iPlugin=iPlugin;this._status=this.STATUS_NOTRUN},_TIMEOUT:30000,_GEO_CODE_MAP:{max_results:"total",language:"lg",onebox_text:"q",geopos:"geopos",country:"country",state:"state",city:"city",street:"street",house_number:"number"},STATUS_OK:0,STATUS_ERROR:1,STATUS_BUSY:2,STATUS_NOTRUN:3,STATUS_CANCELED:4,SEARCH_TYPE_OFFLINE:0,SEARCH_TYPE_ONLINE:1,_BASE_URL:"http://dev-a7.bln.gate5.de/geocoder/",_GEO_CODING_PATH:"gc/1.0?",_REVERSE_GEO_CODING_PATH:"rgc/1.0?",getStatus:function(){return this._status},setOnGeoCodeDone:function(callback){this._onGeoCodeDoneCallback=this._prepareCallback(callback,"setOnGeoCodeDone")},_results:new IArray(),getResults:function(){return this._results._copy()},geoCode:function(type,query){try{var methodName="geoCode",params=this._parseGeoCodeQuery(query)}catch(e){this._throwException(methodName,this._ILLEGAL_ARGUMENT)}if(params.q){var rgcFinder=new IFinder(this._iPlugin),that=this;rgcFinder._onGeoCodeDoneCallback=function(){try{var loc=rgcFinder.getResults().at(0);loc=loc.getField(loc.ADDR_COUNTRY_CODE)}catch(e){}if(loc){params.q+=" "+loc;delete params.lat;delete params["long"];that._sendRequest(methodName,type,this._GEO_CODING_PATH,params)}else{that._onGeoCodeDone(that.STATUS_OK)}};rgcFinder.reverseGeoCode(type,new IGeoCoordinates(params.lat,params["long"]))}else{this._sendRequest(methodName,type,this._GEO_CODING_PATH,params)}},reverseGeoCode:function(type,position){var methodName="reverseGeoCode",params;if(!(position instanceof IGeoCoordinates)){this._throwException(methodName,this._ILLEGAL_ARGUMENT)}params={lat:position._latitude,"long":position._longitude};this._sendRequest(methodName,type,this._REVERSE_GEO_CODING_PATH,params)},cancel:function(){if(this._status===this.STATUS_BUSY){IFinder._cancelRequest(this._requestId)}},_sendRequest:function(callerName,type,path,params){if(this._status===this.STATUS_BUSY){this._throwException(callerName,this._ILLEGAL_STATE)}if(type!==this.SEARCH_TYPE_ONLINE&&type!==this.SEARCH_TYPE_OFFLINE){this._throwException(callerName,this._ILLEGAL_ARGUMENT)}this._status=this.STATUS_BUSY;delete this._results;if(type===this.SEARCH_TYPE_OFFLINE){this._error("[JS-Plugin] IFinder::"+callerName+" won't work offline")}else{var that=this,url=[this._BASE_URL,path,this._createUrlQuery(params)].join(""),receiver=function(response){that._receive(response);callerName=type=path=params=that=url=receiver=null};this._requestId=IFinder._sendRequest(url,receiver,this._TIMEOUT)}},_receive:function(response){var errorMessage;if(response===IFinder._CANCELED){this._onGeoCodeDone(this.STATUS_CANCELED)}else{if(response===IFinder._NO_RESPONSE){errorMessage="no response"}else{try{this._parseResponse(response);this._onGeoCodeDone(this.STATUS_OK)}catch(e){errorMessage=e}}}if(errorMessage){this._error("IFinder response processing: "+errorMessage)}},_error:function(warnMessage){if(warnMessage){logger.warn("IFinder "+warnMessage)}this._onGeoCodeDone(this.STATUS_ERROR)},_onGeoCodeDone:function(status){this._status=status;if(this._onGeoCodeDoneCallback){this._onGeoCodeDoneCallback()}},_locationAddrXPathFieldKeyMap:{"s:countryCode":ILocation.ADDR_COUNTRY_CODE,"s:state":ILocation.ADDR_PROVINCE_NAME,"s:county":ILocation.ADDR_COUNTY_NAME,"s:country":ILocation.ADDR_COUNTRY_NAME,"s:city":ILocation.ADDR_CITY_NAME,"s:district":ILocation.ADDR_DISTRICT_NAME,"s:postCode":ILocation.ADDR_POSTAL_CODE,"s:thoroughfare/s:name":ILocation.ADDR_STREET_NAME,"s:thoroughfare/s:number":ILocation.ADDR_HOUSE_NUMBER},_nsTable:{s:"nokia:search:gc:1.0"},_parseResponse:function(markup){var node=this._iPlugin._domParser.parse(markup),nsR=this._nsTable,xpResults=evalXPath(node,"/s:response/s:place",nsR),results=[],location,i=xpResults.length-1,xpath,temp,temp2;for(;i>=0;i--){node=xpResults[i];results[i]=(location=new ILocation());if((temp=evalXPath(node,"s:location/s:position",nsR)[0])){location.setGeoCoordinates(new IGeoCoordinates(Number(evalXPath(temp,"s:latitude/text()",nsR)[0].nodeValue),Number(evalXPath(temp,"s:longitude/text()",nsR)[0].nodeValue)))}if((temp=evalXPath(node,"s:address",nsR)[0])){for(xpath in this._locationAddrXPathFieldKeyMap){if(this._locationAddrXPathFieldKeyMap.hasOwnProperty(xpath)&&(temp2=evalXPath(temp,xpath+"/text()",nsR)[0])){location.setField(this._locationAddrXPathFieldKeyMap[xpath],temp2.nodeValue)}}}}this._results=new IArray(results)},_parseGeoCodeQuery:function(markup){var children=this._iPlugin._domParser.parse(["<q>",markup,"</q>"].join("")).documentElement.childNodes,i=children.length-1,query={},child,value;for(;i>=0;i--){child=children[i];if(child.nodeType===1&&this._GEO_CODE_MAP.hasOwnProperty(child.nodeName)&&child.firstChild&&child.firstChild.nodeType===3){if((value=(""+child.firstChild.nodeValue).replace(/^\s+|\s+$/g,""))){query[this._GEO_CODE_MAP[child.nodeName]]=value}}}if(query.q){if(!/^(\d+(\.\d+)?);(\d+(\.\d+)?)$/.test(query.geopos)){throw""}query.lat=RegExp.$1*1;query["long"]=RegExp.$3*1}delete query.geopos;return query},_createUrlQuery:function(parameters){var key,items=[],options=this._iPlugin._map._tileMap._options;if(!parameters.lg){parameters.lg=encodeURIComp(this._iPlugin._language)}if(options.hasOwnProperty("token")&&options.token){parameters.token=encodeURIComp(options.token)}if(options.hasOwnProperty("host")&&options.host){parameters.referer=encodeURIComp(options.host)}for(key in parameters){if(parameters.hasOwnProperty(key)){items.push([key,"=",encodeURIComp(parameters[key])].join(""))}}return items.join("&")}});IFinder._callbacks={};IFinder._nextCallbackId=0;IFinder._NO_RESPONSE={};IFinder._CANCELED={};IFinder._sendRequest=function(url,receiver,timeout){var id=(this._nextCallbackId++).toString(32),head=document.getElementsByTagName("head")[0],script=document.createElement("script"),that=this,callback=(this._callbacks[id]=function(response,ok){if(callback._timeoutId){receiver(ok?response:that._NO_RESPONSE);clearTimeout(callback._timeoutId);head.removeChild(script);delete callback._timeoutId;delete that._callbacks[id];url=receiver=timeout=id=head=script=that=null}});callback._timeoutId=setTimeout(callback,timeout);script.onerror=callback;script.type="text/javascript";script.src=[url,(url.match(/\?/)?"&":"?"),"callback_func=nokia.maps.plugin.IFinder.receive&","callback_id=",id].join("");script.charset="UTF-8";head.insertBefore(script,head.firstChild);return id};IFinder._cancelRequest=function(id){this.receive(id,this._CANCELED)};IFinder.receive=function(id,response){if(this._callbacks.hasOwnProperty(id)){this._callbacks[id](response,!0)}};var IRouter=new Class({Name:"IRouter",Extends:ISupports,initialize:function(aPlugin){this._plugin=aPlugin;this._violated=new IRouteOptionsViolated(aPlugin);this._mode=this.MODE_DEFAULT;this._status=this.STATUS_NOTRUN;this._progress=0;this._cause=this.CAUSE_NO_ERROR;this._request=new nokia.aduno.XHttpRequest();this._prepareRequest()},MODE_DEFAULT:0,MODE_FORCEONLINE:1,STATUS_OK:0,STATUS_ERROR:1,STATUS_BUSY:2,STATUS_NOTRUN:3,STATUS_CANCELED:4,CAUSE_NO_ERROR:0,CAUSE_CANNOT_DO_PEDESTRIAN:1,CAUSE_GRAPH_DISCONNECTED:2,CAUSE_GRAPH_DISCONNECTED_CHECK_OPTIONS:3,CAUSE_NO_START_POINT:4,CAUSE_NO_END_POINT:5,CAUSE_NO_END_POINT_CHECK_OPTIONS:6,CAUSE_ROUTE_USES_DISABLED_ROADS:7,_BASE_URL:"http://localhost:8080/jsp/newjsp.jsp?",setOnProgress:function(aCallback){this._onProgressCallback=this._prepareCallback(aCallback,"setOnProgress")},setOnRoutingDone:function(aCallback){this._onRoutingDoneCallback=this._prepareCallback(aCallback,"setOnRoutingDone")},setMode:function(aMode){this._mode=aMode},calculate:function(aPlan){if(this._status===this.STATUS_BUSY){this._throwException("calculate",this._ILLEGAL_STATE)}else{this._plan=aPlan;this._route=new IRoute(this._plan,new this._plugin._domParser.parse(['<?xml version="1.0" encoding="UTF-8"?>','<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="nokia:search:routing:1.0"',' xsi:schemaLocation="nokia:search:routing:1.0 routing.xsd"',' resultCode="0" resultDescription="succeeded" language="eng" offset="0" count="1">',' <route timeOfDepature="2009-06-09T10:30:00+02:00" timeOfArrival="2009-06-09T10:31:00+02:00" distance="280">','  <maneuver description="Make a UTurn" action="UTURN" turn="RETURN" duration="PT0M" distance="0">',"   <maneuverPoints>52.52995,13.38614</maneuverPoints>","  </maneuver>",'  <maneuver description="Turn left into EichendorffstraÃŸe" action="JUNCTION" turn="QUITE_LEFT" duration="PT1M" distance="140">',"   <wayPoints>52.52995,13.38615 52.53005,13.38634 52.53017,13.38664 52.53026,13.38694 ","   52.53037,13.38711 52.53040,13.38724</wayPoints>","   <maneuverPoints>52.53039,13.38728 52.53040,13.38733 52.53041,13.38737 52.53045,13.38738 52.53048,13.38738</maneuverPoints>","  </maneuver>",'  <maneuver description="You reach your target EichendorffstraÃŸe 5" action="END" turn="NO_TURN" duration="PT2M" distance="280">',"   <wayPoints>52.53051,13.38736 52.53058,13.38733 52.53077,13.38720 52.53095,13.38710</wayPoints>","   <maneuverPoints>52.53106,13.38704</maneuverPoints>","  </maneuver>"," </route>","</routes>"].join("")));this._status=this.STATUS_OK;if(this._onRoutingDoneCallback){this._onRoutingDoneCallback()}return}},_onReadyStateChange:function(){if(this._request.readyState===4){var warning;if(this._request.status!==200){warning="HTTP status "+this._request.status}else{try{this._route=new IRoute(this._plan,this._request.responseXML);this._status=this.STATUS_OK}catch(e){this._status=this.STATUS_ERROR;warning="answer not interpretable as route - "+e}}if(warning){logger.warn("IRouter - "+warning)}if(this._onRoutingDoneCallback){this._onRoutingDoneCallback()}}},_prepareRequest:function(){this._request.onreadystatechange=doNothing;this._request.abort();var that=this;this._request.onreadystatechange=function(){that._onReadyStateChange()}},cancel:function(){this._status=this.STATUS_CANCELED},getProgress:function(){return this._progress},getStatus:function(){return this._status},getCalculatedRoute:function(){return this._route},getErrorCause:function(){return this._cause},getOptionsViolated:function(){return this._violated._copy()}});var IRoute=new Class({Name:"IRoute",Extends:IMapObject,initialize:function(aRoutePlan,aDocument){this._super(aRoutePlan._plugin._map,this.ROUTE);this._routePlan=aRoutePlan;this._plugin=aRoutePlan._plugin;this._color=new IColor(0,0,255,255);this._points=[];var root=aDocument.documentElement,route=root.firstChild,pointsExpr=/(\-?\d*\.?\d*),(\-?\d*\.?\d*)/g;while(route&&route.nodeName!=="route"){route=route.nextSibling}if(!route){throw"no route found in answer"}this._length=route.getAttribute("distance")*1;this._duration=(dateFromISO8601(route.getAttribute("timeOfArrival")).getTime()-dateFromISO8601(route.getAttribute("timeOfDepature")).getTime())/1000;this._maneuvers=[];for(var mi=0;mi<route.childNodes.length;mi++){var me=route.childNodes[mi];if(me.nodeName==="maneuver"){var maneuver=new IManeuver(this._plugin);this._maneuvers.push(maneuver);maneuver._command=me.getAttribute("description");maneuver._command=me.getAttribute("description");for(var mpi=0;mpi<me.childNodes.length;mpi++){var pe=me.childNodes[mpi],match,re=new RegExp(pointsExpr);if(pe.nodeName==="wayPoints"){var txt="",tn=pe.firstChild;for(;tn;tn=tn.nextSibling){txt+=tn.nodeValue}while((match=re.exec(txt))){this._points.push(new IGeoCoordinates(match[1]*1,match[2]*1))}}else{if(pe.nodeName==="maneuverPoints"){}}}}}this._polyline=this._plugin.createMapPolyline(new IArray(this._points),this._color._copy(),4);this._domElement=this._polyline._domElement;this._geoBoundingBox=this._polyline._geoBoundingBox;var boundingRect=new GeoRectangle(this._polyline._points);this._boundingBox=[boundingRect._northWest._copy(),boundingRect._southEast._copy()]},_updateScreenPosition:function(geoArea){this._polyline._updateScreenPosition(geoArea);this._screenBoundingBox=this._polyline._screenBoundingBox},_coversScreenCoordinates:function(point){return this._polyline._coversScreenCoordinates(point)},setColor:function(aColor){if(!(aColor instanceof IColor)){this._throwException("setColor",this._ILLEGAL_ARGUMENT)}this._polyline.setLineColor(aColor)},getColor:function(){return this._polyline.getLineColor()},getBoundingBox:function(){return new IArray(this._boundingBox.map(function(i){return i._copy()}))},getRoutePlan:function(){return this._routePlan._copy()},getLength:function(){return this._length},getDuration:function(){return this._duration},getManeuvers:function(){return new IArray(this._maneuvers.map(function(i){return i._copy()}))}});var IRoutePlan=new Class({Name:"IRoutePlan",Extends:ISupports,initialize:function(aPlugin){this._plugin=aPlugin;this._stopovers=[]},addStopover:function(aStopover){if(!(aStopover instanceof IGeoCoordinates)){this._throwException("addStopover",this._ILLEGAL_ARGUMENT)}this._stopovers.push({stopover:aStopover._copy(),options:new IRouteOptions(this._plugin)})},addStopovers:function(aStopovers){aStopovers=aStopovers._array;var stopovers=[],stopover,length=aStopovers.length;for(var i=0;i<length;i++){stopover=aStopovers[i];if(!(stopover instanceof IGeoCoordinates)||length<2){this._throwException("addStopovers",this._ILLEGAL_ARGUMENT)}stopovers.push({stopover:stopover._copy(),options:new IRouteOptions(this._plugin)})}this._stopovers=stopovers},insertStopover:function(aStopover,aIndex){if(!(aStopover instanceof IGeoCoordinates)||aIndex<0||aIndex>this._stopovers.length){this._throwException("insertStopover",this._ILLEGAL_ARGUMENT)}this._stopovers.splice(aIndex,0,{stopover:aStopover._copy(),options:new IRouteOptions(this._plugin)})},getStopoverAt:function(aIndex){if(aIndex<0||aIndex>=this._stopovers.length){this._throwException("getStopoverAt",this._ILLEGAL_ARGUMENT)}return this._stopovers[aIndex].stopover._copy()},removeStopover:function(aIndex){if(aIndex<0||aIndex>=this._stopovers.length){this._throwException("removeStopover",this._ILLEGAL_ARGUMENT)}this._stopovers.splice(aIndex,1)},removeAllStopovers:function(){this._stopovers=[]},setRouteOptionsAt:function(aOptions,aIndex){if(!(aOptions instanceof IRouteOptions)||aIndex<0||aIndex>=this._stopovers.length){this._throwException("setRouteOptionsAt",this._ILLEGAL_ARGUMENT)}this._stopovers[aIndex].options=aOptions._copy()},getRouteOptionsAt:function(aIndex){if(aIndex<0||aIndex>=this._stopovers.length){this._throwException("getRouteOptionsAt",this._ILLEGAL_ARGUMENT)}return this._stopovers[aIndex].options._copy()},getStopoverCount:function(){return this._stopovers.length},setAllRouteOptions:function(aOptions){if(!(aOptions instanceof IRouteOptions)){this._throwException("setAllRouteOptions",this._ILLEGAL_ARGUMENT)}for(var i=0;i<this._stopovers.length;i++){this._stopovers[i].options=aOptions._copy()}},_createQuery:function(){var p=this._plugin,o=this._stopovers[0].options,start=this._stopovers[0].stopover,dest=this._stopovers[this._stopovers.length-1].stopover,so=[],query=["token="+p._tileMapOptions.token,"referer="+p._tileMapOptions.host,"offset=0","total=1","slong="+start._longitude,"slat="+start._latitude,"dlong="+dest._longitude,"dlat="+dest._latitude,"lg="+p._language];for(var i=1;i<this._stopovers.length-1;i++){var soi=this._stopovers[i].stopover;so.push(soi._latitude+","+soi._longitude)}if(so.length>0){query.push("stopovers="+encodeURIComp(so.join(" ")))}return query.join("&")+"&"+o._createQuery()},_copy:function(){var copy=new IRoutePlan(this._plugin);copy._stopovers=this._stopovers.map(function(i){return{stopover:i.stopover._copy(),options:i.options._copy()}});return copy}});var IRouteOptions=new Class({Name:"IRouteOptions",Extends:ISupports,initialize:function(aPlugin){this._plugin=aPlugin;this._routeType=this.TYPE_FASTEST;this._routeMode=this.MODE_CAR;this._allowHighways=true;this._allowTollRoads=true;this._allowFerries=true;this._allowTunnels=true;this._allowDirtRoads=true;this._allowRailFerries=true},TYPE_FASTEST:0,TYPE_SHORTEST:1,TYPE_ECONOMIC:2,_TYPES:["fastest","shortest","economic"],MODE_CAR:0,MODE_SHORTEST:1,MODE_PEDESTRIAN:2,MODE_BICYCLE:3,_MODES:["car","shortest","pedestrian","bicycle"],PRESET_CAR_FAST:0,PRESET_CAR_SLOW:1,PRESET_BIKE:2,PRESET_VAN:3,PRESET_MOTORBIKE:4,PRESET_PEDESTRIAN:5,PRESET_SCOOTER:6,setRouteType:function(aType){this._routeType=aType},getRouteType:function(){return this._routeType},setRouteMode:function(aMode){this._routeMode=aMode},getRouteMode:function(){return this._routeMode},setAllowHighways:function(aAllow){this._allowHighways=aAllow},getAllowHighways:function(){return this._allowHighways},setAllowTollRoads:function(aAllow){this._allowTollRoads=aAllow},getAllowTollRoads:function(){return this._allowTollRoads},setAllowFerries:function(aAllow){this._allowFerries=aAllow},getAllowFerries:function(){return this._allowFerries},setAllowTunnels:function(aAllow){this._allowTunnels=aAllow},getAllowTunnels:function(){return this._allowTunnels},setAllowDirtRoads:function(aAllow){this._allowDirtRoads=aAllow},getAllowDirtRoads:function(){return this._allowDirtRoads},setAllowRailFerries:function(aAllow){this._allowRailFerries=aAllow},getAllowRailFerries:function(){return this._allowRailFerries},setPresetMode:function(aPresetMode){this._routeMode=this.MODE_CAR;this._routeType=this.TYPE_FASTEST;this._allowHighways=this._allowTollroads=this._allowFerries=this._allowTunnels=this._allowDirtroads=this._allowRailFerries=true;switch(aPresetMode){case this.PRESET_VAN:case this.PRESET_MOTORBIKE:case this.PRESET_CAR_FAST:break;case this.PRESET_SCOOTER:case this.PRESET_CAR_SLOW:this._routeType=this.TYPE_SHORTEST;break;case this.PRESET_BIKE:this._routeMode=this.MODE_BICYCLE;this._routeType=this.TYPE_SHORTEST;this._allowHighways=this._allowTollroads=this._allowFerries=false;break;case this.PRESET_PEDESTRIAN:this._routeMode=this.MODE_PEDESTRIAN;this._routeType=this.TYPE_SHORTEST;this._allowHighways=this._allowTollroads=this._allowFerries=this._allowTunnels=this._allowRailFerries=false;break;default:this._throwException("setPresetMode",this._ILLEGAL_ARGUMENT);break}},_createQuery:function(){var p=this._plugin,query=[],da=[];if(this._routeType!==this.TYPE_FASTEST){query.push(this._TYPES[this._routeType])}if(this._routeMode!==this.MODE_CAR){query.push(this._MODES[this._routeMode])}if(!this._allowHighways){da.push("highways")}if(!this._allowTollRoads){da.push("tollroads")}if(!this._allowFerries){da.push("ferries")}if(!this._allowTunnels){da.push("tunnels")}if(!this._allowDirtRoads){da.push("dirtroads")}if(!this._allowRailFerries){da.push("railferries")}if(da.length>0){query.push("disallow="+da.join(","))}return query.join("&")},_copy:function(){var copy=new IRouteOptions(this._plugin);copy._routeType=this._routeType;copy._routeMode=this._routeMode;copy._allowHighways=this._allowHighways;copy._allowTollRoads=this._allowTollRoads;copy._allowFerries=this._allowFerries;copy._allowTunnels=this._allowTunnels;copy._allowDirtRoads=this._allowDirtRoads;copy._allowRailFerries=this._allowRailFerries;return copy}});var IRouteOptionsViolated=new Class({Name:"IRouteOptionsViolated",Extends:ISupports,initialize:function(aPlugin){this._plugin=aPlugin;this._isRouteType=false;this._isRouteMode=false;this._isAllowHighways=false;this._isAllowTollRoads=false;this._isAllowDirtRoads=false;this._isAllowFerries=false;this._isAllowRailFerries=false;this._isAllowTunnels=false},isRouteType:function(){return this._isRouteType},isRouteMode:function(){return this._isRouteMode},isAllowHighways:function(){return this._isAllowHighways},isAllowTollRoads:function(){return this._isAllowTollRoads},isAllowDirtRoads:function(){return this._isAllowDirtRoads},isAllowFerries:function(){return this._isAllowFerries},isAllowRailFerries:function(){return this._isAllowRailFerries},isAllowTunnels:function(){return this._isAllowTunnels},_copy:function(){var copy=new IRouteOptionsViolated(this._plugin);copy._isRouteType=this._isRouteType;copy._isRouteMode=this._isRouteMode;copy._isAllowHighways=this._isAllowHighways;copy._isAllowTollRoads=this._isAllowTollRoads;copy._isAllowDirtRoads=this._isAllowDirtRoads;copy._isAllowFerries=this._isAllowFerries;copy._isAllowRailFerries=this._isAllowRailFerries;copy._isAllowTunnels=this._isAllowTunnels;return copy}});var IManeuver=new Class({Name:"IManeuver",Extends:ISupports,initialize:function(aPlugin){this._plugin=aPlugin;this._action=this.ACTION_UNDEFINED;this._turn=this.TURN_UNDEFINED;this._distanceFromStart=0;this._distanceFromPreviousManeuver=0;this._streetName="";this._routeName="";this._nextStreetName="";this._signPost="";this._trafficDirection=this.TRAFFIC_DIR_RIGHT;this._icon=this.ICON_UNDEFINED;this._command="";this._geoCoordinates=null;this._angle=0;this._mapOrientation=0},ACTION_UNDEFINED:0,ACTION_NO_ACTION:1,ACTION_END:2,ACTION_STOPOVER:3,ACTION_JUNCTION:4,ACTION_ROUNDABOUT:5,ACTION_UTURN:6,ACTION_ENTER_HIGHWAY:7,ACTION_ENTER_HIGHWAY_FROM_RIGHT:8,ACTION_ENTER_HIGHWAY_FROM_LEFT:9,ACTION_PASS_JUNCTION:10,ACTION_LEAVE_HIGHWAY:11,ACTION_CHANGE_HIGHWAY:12,ACTION_CONTINUE_HIGHWAY:13,ACTION_FERRY:14,TURN_UNDEFINED:0,TURN_NO_TURN:1,TURN_KEEP_MIDDLE:2,TURN_KEEP_RIGHT:3,TURN_LIGHT_RIGHT:4,TURN_QUITE_RIGHT:5,TURN_HEAVY_RIGHT:6,TURN_KEEP_LEFT:7,TURN_LIGHT_LEFT:8,TURN_QUITE_LEFT:9,TURN_HEAVY_LEFT:10,TURN_RETURN:11,TURN_ROUNDABOUT_1:12,TURN_ROUNDABOUT_2:13,TURN_ROUNDABOUT_3:14,TURN_ROUNDABOUT_4:15,TURN_ROUNDABOUT_5:16,TURN_ROUNDABOUT_6:17,TURN_ROUNDABOUT_7:18,TURN_ROUNDABOUT_8:19,TURN_ROUNDABOUT_9:20,TURN_ROUNDABOUT_10:21,TURN_ROUNDABOUT_11:22,TURN_ROUNDABOUT_12:23,ICON_UNDEFINED:0,ICON_GO_STRAIGHT:1,ICON_UTURN_RIGHT:2,ICON_UTURN_LEFT:3,ICON_KEEP_RIGHT:4,ICON_LIGHT_RIGHT:5,ICON_QUITE_RIGHT:6,ICON_HEAVY_RIGHT:7,ICON_KEEP_LEFT:8,ICON_LIGHT_LEFT:9,ICON_QUITE_LEFT:10,ICON_HEAVY_LEFT:11,ICON_ENTER_MOTORWAY_RIGHT_LANE:12,ICON_ENTER_MOTORWAY_LEFT_LANE:13,ICON_LEAVE_MOTORWAY_RIGHT_LANE:14,ICON_LEAVE_MOTORWAY_LEFT_LANE:15,ICON_MOTORWAY_KEEP_RIGHT:16,ICON_MOTORWAY_KEEP_LEFT:17,ICON_ROUNDABOUT_1:18,ICON_ROUNDABOUT_2:19,ICON_ROUNDABOUT_3:20,ICON_ROUNDABOUT_4:21,ICON_ROUNDABOUT_5:22,ICON_ROUNDABOUT_6:23,ICON_ROUNDABOUT_7:24,ICON_ROUNDABOUT_8:25,ICON_ROUNDABOUT_9:26,ICON_ROUNDABOUT_10:27,ICON_ROUNDABOUT_11:28,ICON_ROUNDABOUT_12:29,ICON_ROUNDABOUT_1_LH:30,ICON_ROUNDABOUT_2_LH:31,ICON_ROUNDABOUT_3_LH:32,ICON_ROUNDABOUT_4_LH:33,ICON_ROUNDABOUT_5_LH:34,ICON_ROUNDABOUT_6_LH:35,ICON_ROUNDABOUT_7_LH:36,ICON_ROUNDABOUT_8_LH:37,ICON_ROUNDABOUT_9_LH:38,ICON_ROUNDABOUT_10_LH:39,ICON_ROUNDABOUT_11_LH:40,ICON_ROUNDABOUT_12_LH:41,ICON_END:42,ICON_FERRY:43,TRAFFIC_DIR_LEFT:1,TRAFFIC_DIR_RIGHT:0,getAction:function(){return this._action},getTurn:function(){return this._turn},getDistanceFromStart:function(){return this._distanceFromStart},getDistanceFromPreviousManeuver:function(){return this._distanceFromPreviousManeuver},getStreetName:function(){return this._streetName},getRouteName:function(){return this._routeName},getNextStreetName:function(){return this._nextStreetName},getSignPost:function(){return this._signPost},getTrafficDirection:function(){return this._trafficDirection},getIcon:function(){return this._icon},getCommand:function(){return this._command},getGeoCoordinates:function(){return this._geoCoordinates?this._geoCoordinates._copy():null},getAngle:function(){return this._angle},getMapOrientation:function(){return this._mapOrientation},_copy:function(){var copy=new IManeuver(this._plugin);copy._action=this._action;copy._turn=this._turn;copy._distanceFromStart=this._distanceFromStart;copy._distanceFromPreviousManeuver=this._distanceFromPreviousManeuver;copy._streetName=this._streetName;copy._routeName=this._routeName;copy._nextStreetName=this._nextStreetName;copy._signPost=this._signPost;copy._trafficDirection=this._trafficDirection;copy._icon=this._icon;copy._command=this._command;copy._geoCoordinates=this._geoCoordinates;copy._angle=this._angle;copy._mapOrientation=this._mapOrientation;return copy}});nokia.maps.plugin.addMembers({ISupports:ISupports,Point:Point,GeoRectangle:GeoRectangle,Rectangle:Rectangle,Matrix:Matrix,Vector3D:Vector3D,SvgRenderer:SvgRenderer,IArray:IArray,IGeoCoordinates:IGeoCoordinates,IPixelCoordinates:IPixelCoordinates,IPersistence:IPersistence,IColor:IColor,ILocation:ILocation,IIcon:IIcon,IPositionProvider:IPositionProvider,IMapObject:IMapObject,IMapIcon:IMapIcon,IMapComposite:IMapComposite,IMapLayer:IMapLayer,IMapPolyline:IMapPolyline,IMapPolygon:IMapPolygon,TileMapOptions:TileMapOptions,IMap:IMap,IAppearance:IAppearance,IPlugin:IPlugin,TileLayer:TileLayer,TileCache:TileCache,TileMap:TileMap,IHttpRequest:IHttpRequest,IFinder:IFinder,IRouter:IRouter,IRoute:IRoute,IRoutePlan:IRoutePlan,IRouteOptions:IRouteOptions,IRouteOptionsViolated:IRouteOptionsViolated,IManeuver:IManeuver})};new function(){new nokia.aduno.Ns("nokia.maps.mapplayer");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=nokia.maps.pfw.layout;var Serializable=nokia.maps.pfw.Serializable;var Destroyable=nokia.maps.pfw.Destroyable;var MouseEventHandler=nokia.maps.pfw.MouseEventHandler;var PluginLogger=nokia.maps.pfw.PluginLogger;var PluginControl=nokia.maps.pfw.PluginControl;var Location=nokia.maps.pfw.Location;var MapObject=nokia.maps.pfw.MapObject;var MapMarker=nokia.maps.pfw.MapMarker;var Layer=nokia.maps.pfw.Layer;var MapPolyline=nokia.maps.pfw.MapPolyline;var MapPolygon=nokia.maps.pfw.MapPolygon;var Spice=nokia.maps.pfw.Spice;var Player=nokia.maps.pfw.Player;var PlayerManager=nokia.maps.pfw.PlayerManager;var MapModel=nokia.maps.pfw.MapModel;var ZoomModel=nokia.maps.pfw.ZoomModel;var PersistenceModel=nokia.maps.pfw.PersistenceModel;var ConnectivityModel=nokia.maps.pfw.ConnectivityModel;var PositionModel=nokia.maps.pfw.PositionModel;var RoutingModel=nokia.maps.pfw.RoutingModel;var Route=nokia.maps.pfw.Route;var RouteSettingsModel=nokia.maps.pfw.RouteSettingsModel;var SpiceManager=nokia.maps.pfw.SpiceManager;var MouseEventHandling=nokia.maps.pfw.MouseEventHandling;var GuidanceModel=nokia.maps.pfw.GuidanceModel;var Maneuver=nokia.maps.pfw.Maneuver;var PlacesModel=nokia.maps.pfw.PlacesModel;var SearchModel=nokia.maps.pfw.SearchModel;var SearchStringBuilder=nokia.maps.pfw.SearchStringBuilder;var Waypoint=nokia.maps.pfw.Waypoint;var ReverseGeoCodingModel=nokia.maps.pfw.ReverseGeoCodingModel;var ApplicationModel=nokia.maps.pfw.ApplicationModel;var AppearanceModel=nokia.maps.pfw.AppearanceModel;var PlayerTranslationVisitor=nokia.maps.pfw.PlayerTranslationVisitor;var Units=nokia.maps.pfw.Units;var TrafficMapObject=nokia.maps.pfw.TrafficMapObject;var ReferencePrinter=nokia.maps.pfw.ReferencePrinter;var DeviceModel=nokia.maps.pfw.DeviceModel;var SncApplicationModel=nokia.maps.pfw.SncApplicationModel;var TouchApplicationModel=nokia.maps.pfw.TouchApplicationModel;var TouchApplicationPlayer=nokia.maps.pfw.TouchApplicationPlayer;var ConsoleSpice=nokia.maps.pfw.spices.ConsoleSpice;var KeyMapPanSpice=nokia.maps.pfw.spices.KeyMapPanSpice;var MouseSpice=nokia.maps.pfw.spices.MouseSpice;var MouseHoverSpice=nokia.maps.pfw.spices.MouseHoverSpice;var ZoomSpice=nokia.maps.pfw.spices.ZoomSpice;var InfoPlacard=nokia.maps.pfw.spices.InfoPlacard;var InfoBarSpice=nokia.maps.pfw.spices.InfoBarSpice;var InfoBubbleSpice=nokia.maps.pfw.spices.InfoBubbleSpice;var MapModeSpice=nokia.maps.pfw.spices.MapModeSpice;var MapTypeSpice=nokia.maps.pfw.spices.MapTypeSpice;var TrafficSpice=nokia.maps.pfw.spices.TrafficSpice;var BounceSpice=nokia.maps.pfw.spices.BounceSpice;var OrientationTiltWheel=nokia.maps.pfw.spices.OrientationTiltWheel;var OrientationTiltSpice=nokia.maps.pfw.spices.OrientationTiltSpice;var PositionSpice=nokia.maps.pfw.spices.PositionSpice;var SearchSpice=nokia.maps.pfw.spices.SearchSpice;var ResultWindow=nokia.maps.pfw.spices.ResultWindow;var Persistence=nokia.maps.pfw.spices.Persistence;var NewSettingsSpice=nokia.maps.pfw.spices.NewSettingsSpice;var RouteInfoSpice=nokia.maps.pfw.spices.RouteInfoSpice;var FlyBySpice=nokia.maps.pfw.spices.FlyBySpice;var WebRouteSettingsSpice=nokia.maps.pfw.spices.WebRouteSettingsSpice;var WebWaypointSpice=nokia.maps.pfw.spices.WebWaypointSpice;var GuidanceMapSpice=nokia.maps.pfw.spices.GuidanceMapSpice;var TopMenuSpice=nokia.maps.pfw.spices.TopMenuSpice;var CopyrightSpice=nokia.maps.pfw.spices.CopyrightSpice;var WatermarkSpice=nokia.maps.pfw.spices.WatermarkSpice;var ScaleBarSpice=nokia.maps.pfw.spices.ScaleBarSpice;var MiniMapSpice=nokia.maps.pfw.spices.MiniMapSpice;var ShowRouteOnMapSpice=nokia.maps.pfw.spices.ShowRouteOnMapSpice;var TitleBarSpice=nokia.maps.pfw.spices.TitleBarSpice;var InstallPluginSpice=nokia.maps.pfw.spices.InstallPluginSpice;var CenterCursorSpice=nokia.maps.pfw.spices.CenterCursorSpice;var LayerListSpice=nokia.maps.pfw.spices.LayerListSpice;var WhereSearchSpice=nokia.maps.pfw.spices.WhereSearchSpice;var TrafficLegendSpice=nokia.maps.pfw.spices.TrafficLegendSpice;var TouchWaypointSpice=nokia.maps.pfw.spices.TouchWaypointSpice;var TouchDirectionSpice=nokia.maps.pfw.spices.TouchDirectionSpice;var TouchSearchSpice=nokia.maps.pfw.spices.TouchSearchSpice;var TouchRouteSettingsSpice=nokia.maps.pfw.spices.TouchRouteSettingsSpice;var TouchRouteInfoSpice=nokia.maps.pfw.spices.TouchRouteInfoSpice;var TouchStartGuidanceSpice=nokia.maps.pfw.spices.TouchStartGuidanceSpice;var MaemoZoomSpice=nokia.maps.pfw.spices.MaemoZoomSpice;var MaemoOrientation=nokia.maps.pfw.spices.MaemoOrientation;var MaemoOrientationSpice=nokia.maps.pfw.spices.MaemoOrientationSpice;var MaemoSettingsSpice=nokia.maps.pfw.spices.MaemoSettingsSpice;var MaemoInfoBarSpice=nokia.maps.pfw.spices.MaemoInfoBarSpice;var MaemoPositionSpice=nokia.maps.pfw.spices.MaemoPositionSpice;var NextManeuverSpice=nokia.maps.pfw.spices.NextManeuverSpice;var GuidanceProgressSpice=nokia.maps.pfw.spices.GuidanceProgressSpice;var TouchTestRouteSpice=nokia.maps.pfw.spices.TouchTestRouteSpice;var SncRouteSettingsSpice=nokia.maps.pfw.spices.SncRouteSettingsSpice;var SncWaypointSpice=nokia.maps.pfw.spices.SncWaypointSpice;var S60OptionsSpice=nokia.maps.pfw.spices.S60OptionsSpice;var NextManeuverSpice=nokia.maps.pfw.spices.NextManeuverSpice;var GuidanceProgressSpice=nokia.maps.pfw.spices.GuidanceProgressSpice;var ISupports=nokia.maps.plugin.ISupports;var Point=nokia.maps.plugin.Point;var GeoRectangle=nokia.maps.plugin.GeoRectangle;var Rectangle=nokia.maps.plugin.Rectangle;var Matrix=nokia.maps.plugin.Matrix;var Vector3D=nokia.maps.plugin.Vector3D;var SvgRenderer=nokia.maps.plugin.SvgRenderer;var IArray=nokia.maps.plugin.IArray;var IGeoCoordinates=nokia.maps.plugin.IGeoCoordinates;var IPixelCoordinates=nokia.maps.plugin.IPixelCoordinates;var IPersistence=nokia.maps.plugin.IPersistence;var IColor=nokia.maps.plugin.IColor;var ILocation=nokia.maps.plugin.ILocation;var IIcon=nokia.maps.plugin.IIcon;var IPositionProvider=nokia.maps.plugin.IPositionProvider;var IMapObject=nokia.maps.plugin.IMapObject;var IMapIcon=nokia.maps.plugin.IMapIcon;var IMapComposite=nokia.maps.plugin.IMapComposite;var IMapLayer=nokia.maps.plugin.IMapLayer;var IMapPolyline=nokia.maps.plugin.IMapPolyline;var IMapPolygon=nokia.maps.plugin.IMapPolygon;var TileMapOptions=nokia.maps.plugin.TileMapOptions;var IMap=nokia.maps.plugin.IMap;var IAppearance=nokia.maps.plugin.IAppearance;var IPlugin=nokia.maps.plugin.IPlugin;var TileLayer=nokia.maps.plugin.TileLayer;var TileCache=nokia.maps.plugin.TileCache;var TileMap=nokia.maps.plugin.TileMap;var IHttpRequest=nokia.maps.plugin.IHttpRequest;var IFinder=nokia.maps.plugin.IFinder;var IRouter=nokia.maps.plugin.IRouter;var IRoute=nokia.maps.plugin.IRoute;var IRoutePlan=nokia.maps.plugin.IRoutePlan;var IRouteOptions=nokia.maps.plugin.IRouteOptions;var IRouteOptionsViolated=nokia.maps.plugin.IRouteOptionsViolated;var IManeuver=nokia.maps.plugin.IManeuver;var MapPlayer=new nokia.aduno.utils.Class({Name:"MapPlayer",Extends:Player,map:null,options:{cssFiles:["import_mapplayer.css"],uiLanguage:null,jsPlugin:Player.JS_PLUGIN_SUPPORTED,sliderSteps:18,resultsPerPage:5,spices:{},path:{dfwPath:"dfw/",internationalizationPath:"i18n",mapplayerPath:"mapplayer/"},minimalSpiceSize:{x:250,y:250},titleBar:{id:null,backgroundImage:null,backgroundColor:"#FFF",borderColor:"#28363F",textColor:"#28363F"},touchDevice:{snapDistance:35,clickDelta:20},debug:{console:false,consoleId:null},defaultState:{latitude:50.0548,longitude:14.414,orientation:0,tilt:0,scale:976563,mapMode:"day",landmarks:true,mapType:"normal"}},_unhideableSpices:{ConsoleSpice:true,CopyrightSpice:true,WatermarkSpice:true,InfoBubbleSpice:true},_topMenuSpices:{MapTypeSpice:true,MapModeSpice:true,NewSettingsSpice:true,TrafficSpice:true},MapPlayerTemplateLibrary:new nokia.aduno.dom.TemplateLibrary({PluginPage:'<div class="nmm_mapPlayer"><div class="nmm_maxSize" id="plugin"></div><div class="nmm_Controls" id="mapPlayerControls"></div><div id="spices" style="display: none" class="nmm_Spices"><div id="CenterCursorSpice"></div><div id="MaemoInfoBarSpice"></div><div id="MaemoPositionSpice"></div><div id="CopyrightSpice"></div><div id="ZoomSpice"></div><div id="PositionSpice"></div><div id="InfoBubbleSpice"></div><div id="InfoBarSpice"></div><div id="OrientationTiltSpice"></div><div id="SearchSpice"></div><div id="S60OptionsSpice"></div><div id="MaemoSettingsSpice"></div><div id="MiniMapSpice"></div><div id="WatermarkSpice"></div><div id="TitleBarSpice"></div><div id="ScaleBarSpice"></div><div id="TopMenuSpice"><div id="MapTypeSpice"></div><div id="MapModeSpice"></div><div id="TrafficSpice"></div><div id="NewSettingsSpice"></div><div id="InstallPluginSpice"></div></div><div id="ConsoleSpice"></div><div id="TrafficLegendSpice"></div></div><div class="nmn_ScreenPage"><div id="WebRouteSettingsSpice"></div><div id="WebWaypointSpice"></div></div></div>',PluginControl:'<div id="pluginControl" class="nmm_plugControl"></div>'},nokia.aduno.medosui.DefaultTemplateLibrary),initialize:function(aNode,aOptions,aInitialObjects,aLayer){if(this.options.path){for(var o in this.options.path){this._options[o]=this.options.path[o]}}if(aOptions&&aOptions.path){var pathOption=(typeof aOptions.path==="object"?aOptions.path:{});for(var o in pathOption){this._options[o]=pathOption[o]}}for(var f in aOptions){if(aOptions.hasOwnProperty(f)){var currentOpt=aOptions[f];if(typeof currentOpt==="object"){var obj={};for(var i in currentOpt){if(currentOpt.hasOwnProperty(i)){obj[i]=currentOpt[i]}}this._options[f]=obj}else{this._options[f]=currentOpt}}}if(!nokia.aduno.utils.platform.maemo){var plV=this.getPluginVersion();if(plV!==null&&plV!==undefined){var pluginArray=plV.split(".");var requiredArray=Player.REQUIRED_PLUGIN_VERSION.split(".");if(pluginArray.length==4){for(var j=0;j<4;j++){if(pluginArray[j]!==requiredArray[j]){if(pluginArray[j]<requiredArray[j]){this._options.jsPlugin=Player.JS_PLUGIN_FORCED}break}}}}}if(nokia.maps.pfw.layout.snc){this._options.minimalSpiceSize={x:125,y:125}}this._optionalSpices={};for(var i in this.getOption("spices")){this._optionalSpices[this.getOption("spices")[i]]=true}this._initialObjects=aInitialObjects;this._initialLayer=aLayer;this._super(aNode,this.MapPlayerTemplateLibrary,this._options)},postInitialize:function(){this._mouseEventHandling=new MouseEventHandling(this._spiceManager);if(nokia.aduno.utils.browser.msie){this.getOption("cssFiles").push("ie_mapplayer.css")}else{if(nokia.aduno.utils.platform.maemo){while(this.getOption("cssFiles").length){this.getOption("cssFiles").pop()}this.getOption("cssFiles").push("mapplayer.css");this.getOption("cssFiles").push("../../pfw/stylesheets/import_maemo.css")}}this._loadCssFiles();this._spiceManager.addEventHandler(SpiceManager.EVENT_UI_TRANSLATED,this._onUiTranslated,this)},postPreStart:function(){var plV=this.getPluginVersion();if(this.isPluginForbiddenOnPage()||!this.isPluginAvailable()){this._createJsUi()}else{if(!plV){window.alert("Please Download the Plugin");return}else{this._createPluginUi()}}var state=this.hasOption("defaultState")?this.getOption("defaultState"):false;if(state){if(!state.latitude){state.latitude=0}if(!state.longitude){state.longitude=0}if(!state.orientation){state.orientation=0}if(!state.tilt){state.tilt=0}if(!state.scale){state.scale=this.map.getMaxZoomScale()}if(state.landmarks===undefined){state.landmarks=true}if(!state.mapMode){state.mapMode="day"}if(!state.mapType){state.mapType="normal"}state.animationMode="none";this.map.moveTo(state);if(this.isPluginInUse()){this.map.setMapType(state.mapType);this.map.setColor(state.mapMode);this.map.setLandmarksVisible(state.landmarks)}}},postAttach:function(){var plugin=this._page.getChildAt("plugin");plugin.setOnline();this.map.setExternalConnectionsReady()},_createPluginUi:function(){var self=this;var plugin=this._page.getChildAt("plugin");var touchDeviceOptions=this.getOption("touchDevice");if(nokia.maps.pfw.layout.touch||nokia.aduno.utils.platform.maemo){this.map=new MapModel(plugin,nokia.aduno.utils.browser.s60,touchDeviceOptions.snapDistance)}else{this.map=new MapModel(plugin,nokia.aduno.utils.browser.s60,0)}this.zoom=new ZoomModel(plugin,this.map,this.getOption("sliderSteps"));this.position=new PositionModel(plugin);this._mouseEventHandling.attachEventHandlers(plugin);this._mouseEventHandling.prependHandler(this.map);this.persistence=new PersistenceModel(plugin);this.persistence.addSerializable(this.map);this.map.setOrientation(0);this.map.setTilt(0);this.map.setMode3d(false);this.map.setMapType("normal");this.map.addEventHandler(MapModel.EVENT_UI_LANGUAGE,function(aLanguageEvent){this._spiceManager.translateSpices(aLanguageEvent.getData())},this);this.zoom.setStep(nokia.aduno.utils.browser.s60?3:this.getOption("sliderSteps"));this.map.registerPluginHandlers(!this.isPluginAvailable());if(this._initialObjects){this.map.addToLayer(this._initialObjects,this._initialLayer)}if(!this._createdSpices){var pfwPath=this.getOption("pfwPath");var debugOptions=this.getOption("debug");if(debugOptions&&debugOptions.console){this.addSpice(new ConsoleSpice(this._spiceManager,debugOptions.consoleId))}this.addSpice(new WatermarkSpice(this._spiceManager,this.map,pfwPath));this.addSpice(new KeyMapPanSpice(this._spiceManager,this.map));if(nokia.aduno.utils.platform.maemo){this.addSpice(new MaemoZoomSpice(this._spiceManager,this.map,this.zoom),"ZoomSpice");this.addSpice(new MaemoOrientationSpice(this._spiceManager,this.map,touchDeviceOptions.clickDelta),"OrientationTiltSpice");this.addSpice(new MaemoPositionSpice(this._spiceManager,this.map,this.position,this.zoom))}else{this.addSpice(new ZoomSpice(this._spiceManager,this.map,this.zoom));this.addSpice(new OrientationTiltSpice(this._spiceManager,this.map))}this.addSpice(new PositionSpice(this._spiceManager,this.map,this.position,this.zoom));if(!nokia.maps.pfw.layout.snc){this.addSpice(new CopyrightSpice(this._spiceManager,this.map));this.addSpice(new MouseSpice(this._spiceManager,this.map));this.addSpice(new MouseHoverSpice(this._spiceManager,this.map));this.addSpice(new BounceSpice(this._spiceManager,this.map));if(!nokia.maps.pfw.layout.touch&&!nokia.aduno.utils.platform.maemo){this.addSpice(new TopMenuSpice());this.addSpice(new InfoBubbleSpice(this._spiceManager,this.map,this.zoom));this.addSpice(new TrafficSpice(this._spiceManager,this.map));this.addSpice(new MapModeSpice(this._spiceManager,this.map));this.addSpice(new MapTypeSpice(this._spiceManager,this.map));this.addSpice(new NewSettingsSpice(this._spiceManager,this.map,pfwPath));this.addSpice(new MiniMapSpice(this._spiceManager,this.map,new AppearanceModel(this.map._pluginControl.getAppearance()),this.zoom,this.getOption("minimalSpiceSize")));this.addSpice(new ScaleBarSpice(this._spiceManager,this.map,this.zoom));var tb=this.getOption("titleBar");if(tb&&tb.id){this.addSpice(new TitleBarSpice(this._spiceManager,this.map,this.zoom,tb))}}else{this.hideGUI("TopMenuSpice");this.addSpice(new MaemoInfoBarSpice(this._spiceManager,this.map,this.zoom,this.position));this.addSpice(new MaemoSettingsSpice(this._spiceManager,this.map,pfwPath));this.addSpice(new CenterCursorSpice(this._spiceManager,this.map))}}else{this.addSpice(new S60OptionsSpice(this._spiceManager,this.map,pfwPath));this.addSpice(new InfoBarSpice(this._spiceManager,this.map,this.zoom))}this._createdSpices=true;this.onResized()}if(!nokia.aduno.utils.browser.s60&&!this.hasOption("defaultState")){this.persistence.deserialize()}if(!nokia.maps.pfw.layout.snc){setTimeout(function(){self.callSpice.apply(self,["CopyrightSpice","updateCopyrightText",[]])},0)}window.setTimeout(function(){self.loadLink.apply(self)},0);if(!(typeof nokiaMapLoader!=="undefined"&&nokiaMapLoader!==null&&this._spiceManager.translateExternal(nokiaMapLoader.options.uiLanguage))){var lang=this.getOption("uiLanguage")||null;if(!(lang!==null&&this.map.setUiLanguage(this.getOption("uiLanguage").replace("#","")))){this.map.setUiLanguage("en-GB")}}this.map.setMapLanguage("ENG")},_createJsUi:function(){if(this._createdSpices){return}var pfwPath=this.getOption("pfwPath");var debugOptions=this.getOption("debug");var plugin=this._page.getChildAt("plugin");this.map=new MapModel(plugin,nokia.aduno.utils.browser.s60,0);this.map.registerPluginHandlers(this.getOption("jsPlugin")===Player.JS_PLUGIN_SUPPORTED);this.zoom=new ZoomModel(plugin,this.map,this.getOption("sliderSteps"));this.map.addEventHandler(MapModel.EVENT_UI_LANGUAGE,function(aLanguageEvent){this._spiceManager.translateSpices(aLanguageEvent.getData())},this);this._mouseEventHandling.attachEventHandlers(plugin);this._mouseEventHandling.prependHandler(this.map);this.addSpice(new MiniMapSpice(this._spiceManager,this.map,new AppearanceModel(this.map._pluginControl.getAppearance()),this.zoom));this.addSpice(new ScaleBarSpice(this._spiceManager,this.map,this.zoom));this.addSpice(new WatermarkSpice(this._spiceManager,this.map,pfwPath));this.addSpice(new CopyrightSpice(this._spiceManager,this.map));this.addSpice(new KeyMapPanSpice(this._spiceManager,this.map));this.addSpice(new MouseSpice(this._spiceManager,this.map));this.addSpice(new ZoomSpice(this._spiceManager,this.map,this.zoom));this.zoom.setStep(nokia.aduno.utils.browser.s60?3:this.getOption("sliderSteps"));this.addSpice(new TopMenuSpice());this.addSpice(new TrafficSpice(this._spiceManager,this.map));this.addSpice(new MapModeSpice(this._spiceManager,this.map));this.addSpice(new MapTypeSpice(this._spiceManager,this.map));this.addSpice(new InstallPluginSpice(this._spiceManager,this.map,self));this.addSpice(new OrientationTiltSpice(this._spiceManager,this.map));this.addSpice(new InfoBubbleSpice(this._spiceManager,this.map,this.zoom));var tb=this.getOption("titleBar");if(tb&&tb.id){this.addSpice(new TitleBarSpice(this._spiceManager,this.map,this.zoom,tb))}if(debugOptions&&debugOptions.console){this.addSpice(new ConsoleSpice(this._spiceManager,debugOptions.consoleId))}this._createdSpices=true;this.onResized();if(!(typeof nokiaMapLoader!=="undefined"&&nokiaMapLoader!==null&&this._spiceManager.translateExternal(nokiaMapLoader.options.uiLanguage))){var lang=this.getOption("uiLanguage")||null;if(!(lang!==null&&this.map.setUiLanguage(this.getOption("uiLanguage").replace("#","")))){this.map.setUiLanguage("en-GB")}}this.map.setMapLanguage("ENG");this.addEventHandler(Player.EVENT_SIZE_CHANGED,function(aSize){if(this.map._map&&this.map._map._tileMap&&this.map._map._tileMap._adjustSize){this.map._map._tileMap._adjustSize()}},this);var self=this;if(nokia.aduno.utils.browser.safari){this._safariTilemapsFixupIntervalId=window.setInterval(function(){if(self.map._map._tileMap._mapSize._y!=0){window.clearInterval(this._safariTilemapsFixupIntervalId);return}self.map._map._tileMap._adjustSize()},100)}},_onUiTranslated:function(aTranslationEvent){this._page.getReplica().removeStyle("spices","display");if(!this._isFullyInitialized){this.fireEvent(new nokia.aduno.utils.Event(Player.EVENT_INITIALIZATION_DONE,{pluginUsed:this.isPluginInUse()}));this._isFullyInitialized=true}},setGUILanguage:function(aLanguageCode){return this.map.setUiLanguage(aLanguageCode)},getGUILanguage:function(){return this.map.getUiLanguage()},addSpice:function(aSpice,aSlotName){this._super(aSpice,aSlotName);if(this.persistence){this.persistence.addSerializable(aSpice)}var name=aSpice.className;if(this.getOption("spices").length>0){if(!this._unhideableSpices[name]&&!this._optionalSpices[name]){this.hideGUI(aSpice)}}},postDetach:function(){if(!this.isAttached){return}if(this.map){this.map.unregisterPluginHandlers()}this._mouseEventHandling.removeEventHandlers()},_windowUnloaded:function(aEvent){this._super(aEvent);if(this.persistence!==null&&this.persistence!==undefined){this.persistence.serialize()}if(this.map&&this.map.getPluginControl()){this.map.getPluginControl().shutdown()}this.destroyObject()},_loadCssFiles:function(){if(typeof nokiaMapLoader!=="undefined"&&nokiaMapLoader!==null){return}this._super();var cssFiles=this.getOption("cssFiles");var baseCssPath=this.getOption("mapplayerPath")+"stylesheets/";var cssLoader;for(var i=0;i<cssFiles.length;i++){cssLoader=new nokia.aduno.Loader({uri:baseCssPath+""+cssFiles[i],type:"css",window:self})}},showInfo:function(aMapObject){if(this._spiceManager&&aMapObject){var infoSpice=this._spiceManager.getSpice("InfoBubbleSpice");if(infoSpice){infoSpice._onMapObjectSelected.apply(infoSpice,[{getData:function(){return aMapObject}}])}}},setDefaultMouseLeftClickBehaviorEnabled:function(aEnabled){var spice=this._spiceManager.getSpice("MouseSpice");if(spice){spice.setLeftClickingBehaviorEnabled(aEnabled)}},isDefaultMouseLeftClickBehaviorEnabled:function(){var spice=this._spiceManager.getSpice("MouseSpice");return spice&&spice.isLeftClickingBehaviorEnabled()},setDefaultMouseRightClickBehaviorEnabled:function(aEnabled){var spice=this._spiceManager.getSpice("InfoBubbleSpice");if(spice){spice.setRightClickBehaviorEnabled(aEnabled)}},isDefaultMouseRightClickBehaviorEnabled:function(){var spice=this._spiceManager.getSpice("InfoBubbleSpice");return spice&&spice.isRightClickBehaviorEnabled()},createLink:function(){var values=this.map.getCurrentMapProperties();var url="?lat="+values.latitude+"&lon="+values.longitude;url+="&zoom="+values.scale+"&orient="+values.orientation+"&tilt="+values.tilt;return location.protocol+location.host+"/"+location.pathname+url},loadLink:function(){var paramString=location.search;if(!paramString||paramString.length<2){return}paramString=paramString.substring(1);var obj={};var pairs=paramString.split("&");for(var y=pairs.length-1;y>=0;y--){var vk=pairs[y].split("=");if(vk.length==2){obj[vk[0]]=vk[1]}}var moveToObject={};var position={};for(var x in obj){if(x=="lat"){position.latitude=parseFloat(obj[x]||0)}else{if(x=="lon"){position.longitude=parseFloat(obj[x]||0)}else{if(x=="orient"){moveToObject.orientation=(parseInt(obj[x]||0))}else{if(x=="tilt"){moveToObject.tilt=(parseInt(obj[x]||0))}else{if(x=="zoom"){moveToObject.scale=parseInt(obj[x]||40)}}}}}}if(position.latitude!==null&&position.longitude!==null&&position.latitude!==undefined&&position.longitude!==undefined){moveToObject.position=position}this.map.moveTo(moveToObject)},showPluginDownloadPrompt:function(){this.map.showDownload()},getUUID:function(){return this.map.getUUID()},showInfoBubble:function(aPoint){this.callSpice("InfoBubbleSpice","showBubbleAtPoint",aPoint)}});MapPlayer.GUI_ALL="all";MapPlayer.GUI_LAYER_LIST="LayerListSpice";MapPlayer.GUI_MAP_MODE="MapModeSpice";MapPlayer.GUI_MAP_TYPE="MapTypeSpice";MapPlayer.GUI_MINI_MAP="MiniMapSpice";MapPlayer.GUI_NEW_SETTING="NewSettingSpice";MapPlayer.GUI_ORIENTATION_TILT_WHEEL="OrientationTiltSpice";MapPlayer.GUI_SCALE_BAR="ScaleBarSpice";MapPlayer.GUI_TOP_MENU="TopMenuSpice";MapPlayer.GUI_TRAFFIC_CONTROL="TrafficSpice";MapPlayer.GUI_ZOOM_CONTROL="ZoomSpice";nokia.maps.mapplayer.addMembers({MapPlayer:MapPlayer})};
