/* (c) 2009 allesklar.com */
ak.namespace('ak.maps2009');ak.maps2009.config={xmlServerUrl:'http://'+window.location.host+'/xml/',imgServerUrl:'http://stadtplan.meinestadt.de/img/',product:'map',env:'prod'};ak.namespace("ak.maps2009");ak.maps2009.ServiceManager=Class.create({initialize:function()
{var services={};var components={};var self=this;this.registerService=function(name,service){services[name]=service;self['get'+name+'Service']=function(){return service;};};this.registerComponent=function(name,component){components[name]=component;self['get'+name+'Component']=function(){return component;};};this.getService=function(name){return services[name]||null;};this.getComponent=function(name){return components[name]||null;};},configure:function(config){config=config||{};var manager=this;if(config.services)
{config.services.each(function(service){manager.registerService(service.name,service.service);});}
if(config.components)
{config.components.each(function(component){manager.registerComponent(component.name,component.component);});}}});ak.maps2009.ServiceManager.getInstance=function(config)
{if(!ak.maps2009.ServiceManager.instance)
{ak.maps2009.ServiceManager.instance=new ak.maps2009.ServiceManager();}
if(config)
{ak.maps2009.ServiceManager.instance.configure(config);}
return ak.maps2009.ServiceManager.instance;};ak.namespace("ak.maps2009");ak.maps2009.ServiceFinder={getService:function(serviceName)
{var serviceManager=ak.maps2009.ServiceManager.getInstance();return serviceManager?serviceManager.getService(serviceName):null;},getServiceManager:function(){return ak.maps2009.ServiceManager.getInstance();},getComponent:function(componentName)
{var serviceManager=ak.maps2009.ServiceManager.getInstance();return serviceManager?serviceManager.getComponent(componentName):null;},injectServices:function(serviceNames)
{var self=this;serviceNames.each(function(serviceName){var functionName="get"+serviceName+"Service";self[functionName]=function(){return self.getService(serviceName);};});},injectComponents:function(componentNames)
{var self=this;componentNames.each(function(componentName){var functionName="get"+componentName+"Component";self[functionName]=function(){return self.getComponent(componentName);};});}};ak.namespace("ak.maps2009.internalServices.logging");ak.maps2009.internalServices.logging.LoggingService=Class.create({ERROR_LEVEL:0,INFO_LEVEL:1,DEBUG_LEVEL:2,levelMap:{"error":0,"info":1,"debug":2},initialize:function(options)
{options=options||{};this.bufferSize=options.bufferSize||200;this.buffer=new ak.utils.RingBuffer(this.bufferSize);this.setLevel(options.level||this.ERROR_LEVEL);this.stackTraceFunc=Prototype.emptyFunction;this.levels={};var levels=options.levels;if(levels){for(var loggerID in levels){this.setLevel(levels[loggerID],loggerID);}}
if(options.externalConsole){this.console=null;try{var target=options.console||'consoleWindow'
this.externalWindow=window.open('console.html',target,'dependent=yes,width=800,height=400,left=10,top=10,resizable=yes,scrollbars=yes');}catch(e){alert('Creating Console Window failed: '+e.message);}}else{this.console=$(options.console)||$("console");}},externalConsoleLoaded:function(){var consoleDocument=this.externalWindow.document;this.console=consoleDocument.getElementsByTagName("body")[0];this.flushMessages();},externalConsoleClosed:function(){this.console=null;},setLevel:function(level,loggerID)
{if(Object.isString(level))
{level=this.levelMap[level]||this.ERROR_LEVEL;}
if(level>=this.ERROR_LEVEL&&level<=this.DEBUG_LEVEL)
{if(loggerID)
{this.levels[loggerID]=level;}
else
{this.defaultLevel=level;}}},getLevel:function(loggerID)
{var level;if(loggerID)
{level=this.levels[loggerID];}
if(Object.isUndefined(level))
{level=this.defaultLevel;}
return level;},debug:function(loggerID,message)
{var entry={level:this.DEBUG_LEVEL,loggerID:loggerID,levelName:"debug",time:new Date(),message:message};this._log(entry);},info:function(loggerID,message)
{var entry={level:this.INFO_LEVEL,loggerID:loggerID,levelName:"info",time:new Date(),message:message};this._log(entry);},error:function(loggerID,message)
{var entry={level:this.ERROR_LEVEL,loggerID:loggerID,levelName:"error",time:new Date(),message:message};this._log(entry);},trace:function(loggerID,message)
{var stackTrace=this.stackTraceFunc();this.debug(loggerID,message+", stack trace:");var print=this._print.bind(this);var level=this.DEBUG_LEVEL;stackTrace.each(function(line,index){if(index>0)print(line,level)});},flushMessages:function()
{var log=this._log.bind(this);this.buffer.toArray().each(log);},getAllMessages:function()
{return this.buffer.toArray();},getStackTraceFunction:function()
{var mode;try{(0)()}catch(e)
{mode=e.stack?'Firefox':window.opera?'Opera':'Other';}
switch(mode)
{case'Firefox':return function()
{try{(0)()}catch(e)
{return e.stack.replace(/^.*?\n/,'').replace(/(?:\n@:0)?\s+$/m,'').replace(/^\(/gm,'{anonymous}(').split("\n");}};case'Opera':return function()
{try{(0)()}catch(e)
{var lines=e.message.split("\n"),ANON='{anonymous}',lineRE=/Line\s+(\d+).*?in\s+(http\S+)(?:.*?in\s+function\s+(\S+))?/i,i,j,len;for(i=4,j=0,len=lines.length;i<len;i+=2)
{if(lineRE.test(lines[i]))
{lines[j++]=(RegExp.$3?RegExp.$3+'()@'+RegExp.$2+RegExp.$1:ANON+RegExp.$2+':'+RegExp.$1)+' -- '+lines[i+1].replace(/^\s+/,'');}}
lines.splice(j,lines.length-j);return lines;}};default:return function()
{var curr=arguments.callee.caller,FUNC='function',ANON="{anonymous}",fnRE=/function\s*([\w\-$]+)?\s*\(/i,stack=[],j=0,fn,args,i;while(curr)
{fn=fnRE.test(curr.toString())?RegExp.$1||ANON:ANON;args=stack.slice.call(curr.arguments);i=args.length;while(i--)
{switch(typeof args[i])
{case'string':args[i]='"'+args[i].replace(/"/g,'\\"')+'"';break;case'function':args[i]=FUNC;break;}}
stack[j++]=fn+'('+args.join()+')';curr=curr.caller;}
return stack;};}},_log:function(entry)
{var loggerID=entry.loggerID;var level=this.getLevel(loggerID);if(level>=entry.level)
{this.buffer.append(entry);pad=function(number,length,paddingChar){var string=number.toString();while(string.length<length){string=paddingChar+string;}
return string;};var time=entry.time;time=pad(time.getHours(),2,'0')+":"+
pad(time.getMinutes(),2,'0')+":"+
pad(time.getSeconds(),2,'0')+"."+
pad(time.getMilliseconds(),3,'0');var message=entry.levelName+" - "+loggerID+" - "+time+" - "+entry.message;this._print(message,entry.level);}},_print:function(message,level)
{if(this.console){this.console.innerHTML+="<code>"+message+"</code><br \>";}
try
{if(console)
{if(level==this.DEBUG_LEVEL&&console.debug)
{console.debug(message);}
else if(level==this.INFO_LEVEL&&console.info)
{console.info(message);}
else if(level==this.ERROR_LEVEL&&console.error)
{console.error(message);}}}catch(e){}}});ak.namespace("ak.maps2009.internalServices.logging");ak.maps2009.internalServices.logging.MockLoggingService=Class.create({ERROR_LEVEL:0,INFO_LEVEL:1,DEBUG_LEVEL:2,initialize:function()
{},setLevel:function()
{},debug:function()
{},info:function()
{},error:function()
{},trace:function()
{},flushMessages:function()
{},getAllMessages:function()
{return[];}});ak.namespace("ak.maps2009");ak.maps2009.Logger=Object.extend(Object.clone(ak.maps2009.ServiceFinder),{setLoggerId:function(loggerId)
{this.loggerId=loggerId;},getLoggerId:function(){return this.loggerId;},debug:function(message)
{var loggerId=this.loggerId||'unknown';this.getService('Logging').debug(loggerId,message);},info:function(message)
{var loggerId=this.loggerId||'unknown';this.getService('Logging').info(loggerId,message);},error:function(message)
{var loggerId=this.loggerId||'unknown';this.getService('Logging').error(loggerId,message);},trace:function(message)
{var loggerId=this.loggerId||'unknown';this.getService('Logging').trace(loggerId,message);},isDebugEnabled:function()
{var logger=this.getService('Logging');return logger.getLevel()==logger.DEBUG_LEVEL;},checkForMandatoryParameters:function(config,mandatory){for(var i=0;i<mandatory.length;i++){if(!config[mandatory[i]]){this.error("Missing mandatory config parameter '"+mandatory[i]+"'.");return false;}}
return true;}});ak.namespace("ak.maps2009.internalServices.ajax");Ajax.Request.prototype.success=function()
{var status=this.getStatus();return status&&(status>=200&&status<300);};ak.maps2009.internalServices.ajax.ActivityResponder=Class.create(ak.maps2009.Logger,{initialize:function(activityVisualizerId)
{this.activityVisualizerId=activityVisualizerId;this.activities={};this.setLoggerId('ActivityResponder');},onCreate:function(request)
{this.debug('onCreate');var options=request.options;var activity=(options&&options.activity)?options.activity:this.activityVisualizerId;if(!this.activities[activity]){this.activities[activity]=1;}else{this.activities[activity]++;}
$(activity).style.display="block";},onComplete:function(request)
{this.debug('onComplete');var options=request.options;var activity=(options&&options.activity)?options.activity:this.activityVisualizerId;this.activities[activity]--;if(this.activities[activity]<=0){$(activity).hide();}}});ak.maps2009.internalServices.ajax.TimeoutResponder=Class.create(ak.maps2009.Logger,{initialize:function(timeout,onTimeout)
{this.timeout=timeout;this.onTimeout=onTimeout;this.setLoggerId('TimeoutResponder');},onCreate:function(request)
{this.debug('onCreate');var options=request.options;var timeout=(options&&options.timeout)?options.timeout:this.timeout;var onTimeout=(options&&options.onTimeout)?options.onTimeout:this.onTimeout;var callInProgress=this._callInProgress;request['timer']=window.setTimeout(function(){var abortType=typeof request.transport.abort;if(abortType=="function"||abortType=="object"||abortType=="unknown")
{if(callInProgress(request.transport))
{this.debug('Timeout of '+timeout+' ms exceeded, aborting request ...');try
{request.transport.abort();if(onTimeout)
{onTimeout(request);}}
catch(e)
{this.error(e);}}}}.bind(this),timeout);},onComplete:function(request)
{this.debug('onComplete');window.clearTimeout(request['timer']);},_callInProgress:function(xhr){switch(xhr.readyState){case 1:case 2:case 3:return true;default:return false;}}});ak.maps2009.internalServices.ajax.QueueResponder=Class.create(ak.maps2009.Logger,{initialize:function(maxConcurrentRequests,maxConcurrentLowRequests,onOutdated)
{this.setLoggerId('QueueResponder');this.maxConcurrentRequests=maxConcurrentRequests;this.maxConcurrentLowRequests=(maxConcurrentLowRequests&&maxConcurrentLowRequests<maxConcurrentRequests)?maxConcurrentLowRequests:this.maxConcurrentRequests-1;this.queuedRequests={high:new ak.utils.Queue(),low:new ak.utils.Queue()};this.activeLowRequestCount=0;this.namedActiveRequests={};this.onOutdated=onOutdated||Prototype.emptyFunction;},maximumReached:function(priority)
{priority=priority||'high';if(priority=='high')
{return Ajax.activeRequestCount>=this.maxConcurrentRequests;}
return this.activeLowRequestCount>=this.maxConcurrentLowRequests;},enqueue:function(request)
{if(request.options)
{this.abortPreviousRequests(request.options.caller);this.deletePreviousRequests(request.options.caller);if(request.options.priority=='low')
{this.queuedRequests.low.enqueue(request);return;}}
this.queuedRequests.high.enqueue(request);},deletePreviousRequests:function(caller){if(!caller)return;this.queuedRequests.high.removeAll(function(request){return(request.options&&request.options.caller==caller);});},abortPreviousRequests:function(caller){if(!caller)return;var request=this.namedActiveRequests[caller];if(request)
{var options=request.options||{};var onOutdated=options.onOutdated||this.onOutdated;options.onFailure=Prototype.emptyFunction;try
{request.transport.abort();onOutdated(request);}
catch(e){this.error(e);}}},getQueuedRequests:function(priority){if(priority){return this.queuedRequests[priority]?this.queuedRequests[priority].toArray():[];}
return this.queuedRequests.high.toArray().concat(this.queuedRequests.low.toArray());},onComplete:function(request)
{this.debug('onComplete, active requests: '+Ajax.activeRequestCount);if(request.options)
{if(request.options.caller)
{this.namedActiveRequests[request.options.caller]=undefined;}
if(request.options.priority=='low')
{this.activeLowRequestCount--;}}
if(Ajax.activeRequestCount<this.maxConcurrentRequests)
{var newRequest=(this.queuedRequests.high.isEmpty()&&this.activeLowRequestCount<this.maxConcurrentLowRequests)?this.queuedRequests.low.dequeue():this.queuedRequests.high.dequeue();if(newRequest)
{if(newRequest.type=="request")
{return new Ajax.Request(newRequest.url,newRequest.options);}
else
{return new Ajax.Updater(newRequest.container,newRequest.url,newRequest.options);}}}},onCreate:function(request)
{this.debug('onCreate, active requests: '+Ajax.activeRequestCount);if(request.options)
{if(request.options.priority=='low')
{this.activeLowRequestCount++;}
if(request.options.caller)
{this.abortPreviousRequests(request.options.caller);this.namedActiveRequests[request.options.caller]=request;}}}});ak.maps2009.internalServices.ajax.AjaxService=Class.create(ak.maps2009.Logger,{initialize:function(options)
{ak.maps2009.internalServices.ajax.AjaxService.responders.each(function(responder){Ajax.Responders.unregister(responder);});this.setLoggerId("AjaxService");options=options||{};if(options.timeout)
{this.timeoutResponder=new ak.maps2009.internalServices.ajax.TimeoutResponder(options.timeout,options.onTimeout);}
else
{this.timeoutResponder=options.timeoutResponder;}
if(this.timeoutResponder)
{Ajax.Responders.register(this.timeoutResponder);ak.maps2009.internalServices.ajax.AjaxService.responders.push(this.timeoutResponder);}
if(options.activityVisualizerId)
{this.activityResponder=new ak.maps2009.internalServices.ajax.ActivityResponder(options.activityVisualizerId);}
else
{this.activityResponder=options.activityResponder;}
if(this.activityResponder)
{Ajax.Responders.register(this.activityResponder);ak.maps2009.internalServices.ajax.AjaxService.responders.push(this.activityResponder);}
if(options.maxConcurrentRequests)
{this.queueResponder=new ak.maps2009.internalServices.ajax.QueueResponder(options.maxConcurrentRequests,options.maxConcurrentLowRequests,options.onOutdated);}
else
{this.queueResponder=options.queueResponder;}
if(this.queueResponder)
{Ajax.Responders.register(this.queueResponder);ak.maps2009.internalServices.ajax.AjaxService.responders.push(this.queueResponder);}
if(options.errorCallback)
{Ajax.Responders.register({onFailure:options.errorCallback});}},queuedRequests:function(priority)
{return(this.queueResponder)?this.queueResponder.getQueuedRequests(priority):[];},request:function(url,options)
{options=options||{};if(this.queueResponder&&this.queueResponder.maximumReached(options.priority))
{this.queueResponder.enqueue({type:"request",url:url,options:options});}
else
{return new Ajax.Request(url,options);}},update:function(container,url,options)
{options=options||{};if(this.queueResponder&&this.queueResponder.maximumReached(options.priority))
{this.queueResponder.enqueue({type:"update",container:container,url:url,options:options});return null;}
else
{return new Ajax.Updater(container,url,options);}}});ak.maps2009.internalServices.ajax.AjaxService.responders=[];ak.namespace("ak.maps2009.externalServices.rerender");ak.maps2009.externalServices.rerender.RerenderService=Class.create(ak.maps2009.Logger,{initialize:function(options){options=options||{};this.setLoggerId('RerenderService');this.baseParams=options.baseParams||{};this.contentElements={};},setBaseParameters:function(params){this.baseParams=params;},registerContentElement:function(ceId,container,parameters){parameters=parameters||{};if(!$(container))return this.error("Container '"+container+"' does not exist in DOM!");if(!parameters.ceId)return this.error("Missing property ceId in parameters!");this.contentElements[ceId]={params:parameters,container:container};},rerenderContentElement:function(ceId,options){options=options||{};this.debug('rerenderContentElement('+ceId+', '+Object.toJSON(options)+')');var ce=this.contentElements[ceId];if(!ce)return this.error("Unknown content element '"+ceId+"'!");var inputChanged=false;for(var name in options){if(typeof ce.params[name]!='undefined'&&options[name]!=ce.params[name]){ce.params[name]=options[name];inputChanged=true;}}
if(!inputChanged)return this.debug('no need to rerender '+ceId);var params=Object.clone(this.baseParams);for(var name in ce.params){var value=ce.params[name];if(typeof value!='undefined'&&value!=null&&value!=''){params[name]=ce.params[name];}}
if(params.startAt==1)delete params.startAt;var url=document.location.href.replace(/\?.*$/,'');this.getService('Ajax').update({success:ce.container},url,{caller:ceId,activity:this.getLoadingIndicator(ce.container),evalScripts:true,method:'get',parameters:params,onCreate:function(){$(ce.container).update(new Element('div').update(new Element('div').update('Inhalt wird geladen ...').addClassName('redlinehead')).insert('Bitte warten!'));},onFailure:function(){$(ce.container).update(new Element('div').update(new Element('div').update('Fehler').addClassName('redlinehead')).insert('Update fehlgeschlagen!'));}});},getLoadingIndicator:function(container){var htmlId=container+'-loading';var indicator=$(htmlId);if(!indicator){var ce=$(container);var dim=ce.getDimensions();var offset=ce.positionedOffset();var indicator=new Element('div',{id:htmlId}).setStyle({backgroundColor:'#ffffff',display:'none',position:'absolute',left:offset.left+'px',top:offset.top+'px',width:dim.width+'px',height:'64px'}).update(new Element('div'));indicator.insert(new Element('div').setStyle({backgroundImage:'url(http://img.meinestadt.de/pix/eventapp/bu_indicator.gif)',backgroundRepeat:'no-repeat',backgroundPosition:'center center',height:'30px',padding:'0px'}));ce.parentNode.appendChild(indicator);}
return htmlId;}});ak.namespace("ak.maps2009.internalServices.forwarding");ak.maps2009.internalServices.forwarding.ForwardingService=Class.create(ak.maps2009.Logger,{initialize:function(options){options=options||{};this.setLoggerId("ForwardingService");this.baseUrl=options.baseUrl||window.location.href.replace(/\?.*$/,'');this.state=options.state||this.getStateFromUrl();this.defaultParams=options.defaultParams||{};this.cssUpdateClass=options.cssUpdateClass||'';},getStateFromUrl:function(){var search=window.location.search;search=search.replace(/\+/g,' ');return search?search.toQueryParams():{};},updateState:function(options,state){var stateChanged=false;state=state||this.state;if(typeof options!='object'){return this.error('First parameter of updateState must be type of object!');}
this.debug('updateState: '+Object.toJSON(options));for(var name in options){var value=options[name];if(value===state[name])continue;var type=typeof(value);if(type==='undefined'||this.defaultParams[name]==value){delete state[name];stateChanged=true;continue;}
if(type==='string'||type==='number'||type==='undefined'){state[name]=value;stateChanged=true;}else{this.error("Invalid state information: value of '"+name+"' is neither string nor number!");}}
if(stateChanged&&this.cssUpdateClass){$$('a.'+this.cssUpdateClass).each(this.updateLink.bind(this));}else this.debug('stateChanged: '+stateChanged+' class: '+this.cssUpdateClass);},getState:function(){return this.state;},getStateAsQueryString:function(state){state=state||this.state;return Object.toQueryString(state)||'';},getForwardUrl:function(state){var forwardUrl=this.baseUrl;var queryString=this.getStateAsQueryString(state);if(queryString)forwardUrl+='?'+queryString;this.debug('getForwardUrl '+forwardUrl);return forwardUrl;},getUpdatedUrl:function(options){var state=Object.clone(this.state);this.updateState(options,state);return this.getForwardUrl(state);},updateLink:function(link){this.debug('updateLink');var pos=link.href.search(/\?/);var baseUrl=(pos===-1)?link.href:link.href.substring(0,pos);link.href=baseUrl+'?'+this.getStateAsQueryString();}});ak.namespace("ak.maps2009.internalServices.mediator");ak.maps2009.internalServices.mediator.BaseMediatorService=Class.create(ak.maps2009.Logger,{initialize:function(options){options=options||{};this.setLoggerId('BaseMediatorService');this.townSearch=new ak.maps2009.utils.search.TownSearch();this.stopWatch=new ak.utils.StopWatch();},mapZoomed:function(zoomLevel){},mapPanned:function(centerX,centerY){this.getService('Mediator').triggerTownSearch(centerY,centerX);},viewRectChanged:function(viewRect){this.debug('viewRectChanged');},searchRectEquals:function(rect1,rect2){return(rect1&&rect1&&rect1.centerX==rect2.centerX&&rect1.centerY==rect2.centerY&&rect1.radiusX==rect2.radiusX&&rect1.radiusY==rect2.radiusY);},mapStyleChanged:function(style){this.debug('mapStyleChanged');this.triggerLinkTracking({mapStyle:style});this.reloadPITracking({eventName:'mapStyle',omniture:false,xiti:false})},shapeHovered:function(shapeId){return true;},shapeLeft:function(shapeId){return true;},shapeLeftClicked:function(shapeId){this.debug('shapeLeftClicked '+shapeId);var poi=this.getPoiByShapeId(shapeId);if(poi){this.triggerLinkTracking({result:poi.getTrackingName(),detail:'Karte-Klick'});if(poi.getClassName()==='ClusterPoi'&&poi.hasItems()===false){this.getComponent('Map').zoomIn({x:poi.getData().longitude,y:poi.getData().latitude});}else{this.getComponent('Map').showInfoBox(poi);}
return true;}else{this.debug('Shape '+shapeId+" has been clicked but isn't a POI!");return false;}},getPoiByShapeId:function(shapeId){return this.townSearch.getPoiByShapeId(shapeId);},poiCloseLinkClicked:function(poi){this.getComponent('Map').hideInfoBox(poi);if(poi.isClustered()){this.getComponent('Map').showInfoBox(poi.getClusterPoi());}},triggerTownSearch:function(latitude,longitude){this.debug('triggerTownSearch');this.townSearch.update({latitude:latitude,longitude:longitude},{onSuccess:function(results){var currentTown=this.getCurrentTown();this.getComponent('TownSign').showSign(currentTown.getData());this.getComponent('Map').showPoiList(results);}.bind(this)});},getCurrentTown:function(){return this.townSearch.getPoiByIndex(0);},logProfilingData:function(){if(this.isDebugEnabled()){this.debug("profiling for SearchService:");var laps=this.stopWatch.getAllLaps();laps.each(function(lap){this.debug(lap.name+" needed "+lap.duration+" ms");},this);}},reloadPITracking:function(e){if(e.eventName){var trackingService=this.getService('Tracking');if(trackingService){trackingService.reloadPITracking(e);}}
else{this.error('no tracking-event defined');}},triggerLinkTracking:function(event){var trackingService=this.getService('Tracking');if(trackingService){trackingService.triggerLinkTracking(event);}},birdseyeEntered:function(){this.debug('birdseyeEntered');var infoTextShown=this.getService('Cookie').getCookie('birdseyeInfoText');if(infoTextShown!='shown'&&this.getService('Cookie').checkCookie()){this.debug('Browser akzeptiert cookies');this.getService('Cookie').setCookie('birdseyeInfoText','shown');this.getComponent('Map').showBirdseyeInfoText();}
this.setSearchType('address');},birdseyeLeft:function(){this.debug('birdseyeLeft');},setRouteSearchInput:function(searchInput){this.setSearchType('route');this.getComponent('RouteSearch').setSearchInput(searchInput);}});ak.namespace("ak.maps2009.internalServices.mediator");ak.maps2009.internalServices.mediator.MytownMediatorService=Class.create(ak.maps2009.Logger,{initialize:function(options){options=options||{};this.setLoggerId('MytownMediatorService');this.search=null;this.mapCeId='map';this.listeners={};this.waitForContentElements(options.contentElementsToWaitFor);},poiCloseLinkClicked:function(poi){poi.infoBox.style.visibility='hidden';},setContentElementId:function(ceId){this.mapCeId=ceId;},setSearch:function(search){this.search=search;},getLastSearchInput:function(){return(this.search)?this.search.getLastSearchInput():null;},getVisibleSearchResults:function(){return this.search.getVisibleSearchResults();},getSearchResults:function(){return this.search.getResults();},triggerSearch:function(options){this.debug('triggerSearch');if(!this.search)return this.debug('not initialized');options=options||{};var triggered=this.search.update(options,{onSuccess:this.handleSearchResults.bind(this),onFailure:this.handleSearchFailure.bind(this)});if(triggered){this.debug('clear layer : '+this.search.poiLayer);this.getComponent('Map').clearLayer(this.search.poiLayer);}},handleSearchResults:function(results){this.debug('handleSearchResults'+Object.toJSON(results));this.getComponent('Map').showPoiList(results);},getCurrentTown:function(){return null;},handleSearchFailure:function(){this.debug('Search failed!');},mapZoomed:function(zoomLevel){this.debug('mapZoomed: '+zoomLevel);this.handleEvent(this.mapCeId,'mapZoomed',{zoom:zoomLevel});},mapPanned:function(centerX,centerY){this.debug('mapPanned: '+centerX+' '+centerY);},viewRectChanged:function(viewRect){this.viewRectChanged=function(viewRect){this.debug('viewRectChanged');this.handleEvent(this.mapCeId,'viewRectChanged',{lat:viewRect.centerY,lng:viewRect.centerX,radiusX:viewRect.radiusX,radiusY:viewRect.radiusY,startAt:1,kazdistance:''});this.triggerSearch({searchRect:viewRect,distance:''});}.bind(this);},mapStyleChanged:function(style){},shapeHovered:function(shapeId){return true;},shapeLeft:function(shapeId){return true;},shapeLeftClicked:function(shapeId){var poi=this.getPoiByShapeId(shapeId)
if(poi){this.triggerLinkTracking({result:poi.getTrackingName(),detail:'Karte-Klick'});this.getComponent('Map').showInfoBox(poi);return true;}else{this.debug('Shape '+shapeId+" has been clicked but isn't a POI!");return false;}},getPoiByShapeId:function(shapeId){this.debug('getPoiByShapeId '+shapeId);return(this.search)?this.search.getPoiByShapeId(shapeId):null;},waitForContentElements:function(contentElements){this.contentElementsToWaitFor=(Object.isArray(contentElements))?contentElements:[];this.debug('contentElementsToWaitFor '+Object.toJSON(this.contentElementsToWaitFor));if(this.contentElementsToWaitFor.length==0){this.enableContentElements();document.observe('dom:loaded',this.enableContentElements.bind(this));}},allListenersRegistered:function(contentElement){this.debug('allListenersRegistered '+contentElement);this.contentElementsToWaitFor=this.contentElementsToWaitFor.without(contentElement);this.debug('contentElementsToWaitFor '+Object.toJSON(this.contentElementsToWaitFor));if(this.contentElementsToWaitFor.length==0){this.enableContentElements();}},enableContentElements:function(){this.debug('enableContentElements');$$('.mt-disable').each(function(e){e.parentNode.removeChild(e);delete e;});},addListener:function(element,event,handler){this.debug('addListener() element: '+element+' event: '+event);if(typeof(handler)!='function'){return this.error('Argument handler is no function - addListener failed!');}
if(!this.listeners[element]){this.listeners[element]={};}
if(!this.listeners[element][event]){this.listeners[element][event]=[];}
this.listeners[element][event].push(handler);},handleEvent:function(element,event,options){this.debug('handleEvent '+element+' '+event);this.debug(Object.toJSON(options));options=options||{};this.getService('Forwarding').updateState(options);var state=this.getService('Forwarding').getState();try{var handlers=this.listeners[element][event];}catch(e){return this.debug("No handlers defined for event '"+event+"' of element '"+element+"'");}
try{handlers.each(function(h){h(state);});}catch(e){this.debug(e.message);}},hitListItemHovered:function(index){var poi=this.search.getPoiByIndex(index);if(!poi){this.info('Hit list item '+index+" has been hovered but doesn't exist!");return;}
this.getComponent('HitList').highlightPoi(poi);this.getComponent('Map').heightenPoi(poi);},hitListItemLeft:function(index){var poi=this.search.getPoiByIndex(index);if(!poi)return;this.getComponent('HitList').undoHighlightPoi(poi);this.getComponent('Map').rescalePoi(poi);},hitListItemLeftClicked:function(index){this.triggerLinkTracking({result:'hit',detail:'Liste-Klick'});var poi=this.search.getPoiByIndex(index);if(!poi){return this.error('Hit list item '+index+" has been hovered but doesn't exist!");}
this.getComponent('Map').showInfoBox(poi);},hitListPageClicked:function(index){this.triggerLinkTracking({result:'hit',detail:'Blaettern-Klick'});var indices=this.getComponent('HitList').showPage(index,this.search.getResults());this.getComponent("Map").showPoiList(this.search.getResults(),this.search.poiLayer,indices);},reloadPITracking:function(e){if(e.eventName){var trackingService=this.getService('Tracking');if(trackingService){trackingService.reloadPITracking(e);}}
else{this.error('no tracking-event defined');}},triggerLinkTracking:function(event){var trackingService=this.getService('Tracking');if(trackingService){trackingService.triggerLinkTracking(event);}},setRouteSearchInput:function(searchInput){var center=this.getComponent('Map').getCenterAndZoom();var state=Object.clone(searchInput);state.stateType='main';state.searchType='route';state.lat=center.y;state.lng=center.x;state.zoom=center.zoom;var href='http://stadtplan.meinestadt.de/index.php?'+Object.toQueryString(state);(window.open(href,'_blank','')).focus();}});ak.namespace("ak.maps2009.utils.stateCodec");ak.maps2009.utils.stateCodec.StateCodecFactory={createStateCodec:function(state){state=state||{};if(Object.isUndefined(state.stateType))
{return null;}
var mapping={'main':ak.maps2009.utils.stateCodec.MainStateCodec,'company':ak.maps2009.utils.stateCodec.CompanyStateCodec,'address':ak.maps2009.utils.stateCodec.AddressStateCodec,'route':ak.maps2009.utils.stateCodec.RouteStateCodec,'print':ak.maps2009.utils.stateCodec.PrintStateCodec,'hits':ak.maps2009.utils.stateCodec.HitsStateCodec}
var stateCodecClass=mapping[state.stateType];if(Object.isUndefined(stateCodecClass)){return this.error("could not create state codec for unknown state type '"+state.stateType+"'");}
return new stateCodecClass();},debug:function(message){var serviceManager=ak.maps2009.ServiceManager.getInstance();var log=serviceManager.getLoggingService();log.debug("StateCodecFactory",message);},error:function(message){var serviceManager=ak.maps2009.ServiceManager.getInstance();var log=serviceManager.getLoggingService();log.error("StateCodecFactory",message);}};ak.namespace("ak.maps2009.applications");ak.maps2009.applications.BaseApp=Class.create(ak.maps2009.Logger,{initialize:function()
{this.setLoggerId("BaseApp");this.serviceManager=ak.maps2009.ServiceManager.getInstance();var loggingService=new ak.maps2009.internalServices.logging.LoggingService({level:"debug"});this.serviceManager.configure({services:[{name:"Logging",service:loggingService}]});this.stateCodec=ak.maps2009.utils.stateCodec.StateCodecFactory.createStateCodec(this.getStateFromUrl());},getStateFromUrl:function(){var search=window.location.search;search=search.replace(/\+/g,' ');return search?search.toQueryParams():null;},getStateCodec:function(stateType)
{if(!stateType||(this.stateCodec&&this.stateCodec.getStateType()==stateType))
{return this.stateCodec;}
return ak.maps2009.utils.stateCodec.StateCodecFactory.createStateCodec({stateType:stateType});}});ak.namespace("ak.maps2009.applications.mytown");ak.maps2009.applications.mytown.MytownApp=Class.create(ak.maps2009.applications.BaseApp,{initialize:function($super,options){options=options||{};$super();this.setLoggerId('MytownApp');var ajaxOptions=Object.extend({maxConcurrentRequests:10,activityVisualizerId:'ajax-visualizer',timeout:10000},options.ajax);var loggingOptions=Object.extend({level:"info",externalConsole:(ak.maps2009.config.env=='dev'),levels:{MytownMediatorService:'debug'}},options.logging);var rerenderOptions=options.rerender;var mediatorOptions=options.mediator;var forwardingOptions=Object.extend({defaultParams:{startAt:1},cssUpdateClass:'ak-update'},options.forwarding);this.serviceManager.configure({services:[{name:"Ajax",service:new ak.maps2009.internalServices.ajax.AjaxService(ajaxOptions)},{name:"Logging",service:new ak.maps2009.internalServices.logging.LoggingService(loggingOptions)},{name:"Rerender",service:new ak.maps2009.externalServices.rerender.RerenderService(rerenderOptions)},{name:"Mediator",service:new ak.maps2009.internalServices.mediator.MytownMediatorService(mediatorOptions)},{name:'Forwarding',service:new ak.maps2009.internalServices.forwarding.ForwardingService(forwardingOptions)}]});},getZoomLevelByVisibleKm:function(visKm){var maxVisKm=26250;if(visKm>=maxVisKm)return 1;var zoomLevel=Math.floor(Math.log(maxVisKm/visKm)/Math.log(2))+1;return Math.min(zoomLevel,19);},getZoomLevelByLatitudeDifference:function(radiusY){radiusY=Math.round(radiusY*100000);if(radiusY>=7200000)return 1;var zoomLevel=Math.round(Math.log(11637160.0/radiusY)/Math.log(2))+1;return Math.min(zoomLevel,19);},getZoomLevel:function(state){if(state.distance)return this.getZoomLevelByVisibleKm(state.distance*2);if(state.radiusX&&state.radiusY)return this.getZoomLevelByLatitudeDifference(state.radiusY);return state.zoom||11;},initMap:function(state){this.debug('initMap');if(!(ak.maps2009.components&&ak.maps2009.components.map)){return this.error("Map module has not been loaded yet - initMap failed!");}
var serviceManager=ak.maps2009.ServiceManager.getInstance();var ivwOptions=Object.extend({imgContainer:"mt-ivw",imgSrcPath:"http://mstadt.ivwbox.de/cgi-bin/ivw/CP",eventMapping:{'onendpan':'SP-PLANV-A','onendzoom':'SP-PLANV-A'}},state.ivw);var trackingService=new ak.maps2009.internalServices.tracking.TrackingService({ivw:ivwOptions});serviceManager.registerService('Tracking',trackingService);var mediator=serviceManager.getService('Mediator');if(state.ceId)mediator.setContentElementId(state.ceId);if(!state.lat||!state.lng){return this.error("No center given - initMap failed!");}
var mapComponent=new ak.maps2009.components.map.VirtualEarthComponent({mapContainer:'map',infoBoxContainer:'infoBox',loadingIndicator:'loading-indicator'});serviceManager.registerComponent('Map',mapComponent);var center={latitude:state.lat,longitude:state.lng};var zoomLevel=this.getZoomLevel(state);mapComponent.loadMap({center:center,zoom:zoomLevel,showControls:true,showScalebar:true,style:VEMapStyle.Road,disableMapStyleChange:true});switch(state.searchType){case'company':var searchService=new ak.maps2009.externalServices.companySearch.CompanySearchService();serviceManager.registerService('CompanySearch',searchService);var search=new ak.maps2009.utils.search.CompanySearch();break;case'kaz':var searchService=new ak.maps2009.externalServices.jsonSearch.JsonSearchService({searcherUrl:'get_classified_ads.php'});serviceManager.registerService('KazSearch',searchService);var search=new ak.maps2009.utils.search.KazSearch();break;case'kaufda':var searchService=new ak.maps2009.externalServices.jsonSearch.JsonSearchService({searcherUrl:'services/service.php'});serviceManager.registerService('KaufdaSearch',searchService);var search=new ak.maps2009.utils.search.KaufdaSearch();break;default:this.error("Invalid searchType '"+state.searchType+"'!");return;}
mediator.setSearch(search);state.searchRect=state.distance?{centerX:center.longitude,centerY:center.latitude,radiusX:state.distance/(Math.cos(center.latitude)*111.32),radiusY:state.distance/111.32}:mapComponent.getCurrentViewRect();mediator.triggerSearch(state);},updateSearch:function(options){if(options.address){var map=this.getComponent('Map');var mediator=this.getService('Mediator');map.findAddress({address:options.address,setBestMapView:false,onSuccess:function(address){map.setCenter(address.longitude,address.latitude);options.searchRect=map.getCurrentViewRect();mediator.triggerSearch(options);},onFailure:function(){mediator.handleEvent(mediator.mapCeId,'addressNotFound',{});mediator.triggerSearch(options);}});}
this.getService('Mediator').triggerSearch(options);},updateViewport:function(state){var map=this.getComponent('Map');if(!map)return this.debug('MapComponent has not been initialized yet!');map.setCenterAndZoom(state.lng,state.lat,state.zoom);},reload:function(options,target){target=target||'_self';var url=this.getService('Forwarding').getUpdatedUrl(options);window.open(url,target,'');}});
