/*

  OpenLayers.js -- OpenLayers Map Viewer Library

  Copyright 2005-2007 MetaCarta, Inc., released under the BSD license.
  Please see http://svn.openlayers.org/trunk/openlayers/release-license.txt
  for the full text of the license.

  Includes compressed code under the following licenses:

  (For uncompressed versions of the code used please see the
  OpenLayers SVN repository: <http://openlayers.org/>)

*/

/* Contains portions of Prototype.js:
 *
 * Prototype JavaScript framework, version 1.4.0
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
 *
/*--------------------------------------------------------------------------*/

/**  
*  
*  Contains portions of Rico <http://openrico.org/>
* 
*  Copyright 2005 Sabre Airline Solutions  
*  
*  Licensed under the Apache License, Version 2.0 (the "License"); you
*  may not use this file except in compliance with the License. You
*  may obtain a copy of the License at
*  
*         http://www.apache.org/licenses/LICENSE-2.0  
*  
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
*  implied. See the License for the specific language governing
*  permissions and limitations under the License. 
*
**/

var Prototype={Version:'1.5.1.1',Browser:{IE:!!(window.attachEvent&&!window.opera),Opera:!!window.opera,WebKit:navigator.userAgent.indexOf('AppleWebKit/')>-1,Gecko:navigator.userAgent.indexOf('Gecko')>-1&&navigator.userAgent.indexOf('KHTML')==-1},BrowserFeatures:{XPath:!!document.evaluate,ElementExtensions:!!window.HTMLElement,SpecificElementExtensions:(document.createElement('div').__proto__!==document.createElement('form').__proto__)},ScriptFragment:'<script[^>]*>([\\S\\s]*?)<\/script>',JSONFilter:/^\/\*-secure-([\s\S]*)\*\/\s*$/,emptyFunction:function(){},K:function(x){return x}}
var Class={create:function(){return function(){this.initialize.apply(this,arguments);}}}
var Abstract=new Object();Object.extend=function(destination,source){for(var property in source){destination[property]=source[property];}
return destination;}
Object.extend(Object,{inspect:function(object){try{if(object===undefined)return'undefined';if(object===null)return'null';return object.inspect?object.inspect():object.toString();}catch(e){if(e instanceof RangeError)return'...';throw e;}},toJSON:function(object){var type=typeof object;switch(type){case'undefined':case'function':case'unknown':return;case'boolean':return object.toString();}
if(object===null)return'null';if(object.toJSON)return object.toJSON();if(object.ownerDocument===document)return;var results=[];for(var property in object){var value=Object.toJSON(object[property]);if(value!==undefined)
results.push(property.toJSON()+': '+value);}
return'{'+results.join(', ')+'}';},keys:function(object){var keys=[];for(var property in object)
keys.push(property);return keys;},values:function(object){var values=[];for(var property in object)
values.push(object[property]);return values;},clone:function(object){return Object.extend({},object);}});Function.prototype.bind=function(){var __method=this,args=$A(arguments),object=args.shift();return function(){return __method.apply(object,args.concat($A(arguments)));}}
Function.prototype.bindAsEventListener=function(object){var __method=this,args=$A(arguments),object=args.shift();return function(event){return __method.apply(object,[event||window.event].concat(args));}}
Object.extend(Number.prototype,{toColorPart:function(){return this.toPaddedString(2,16);},succ:function(){return this+1;},times:function(iterator){$R(0,this,true).each(iterator);return this;},toPaddedString:function(length,radix){var string=this.toString(radix||10);return'0'.times(length-string.length)+string;},toJSON:function(){return isFinite(this)?this.toString():'null';}});Date.prototype.toJSON=function(){return'"'+this.getFullYear()+'-'+
(this.getMonth()+1).toPaddedString(2)+'-'+
this.getDate().toPaddedString(2)+'T'+
this.getHours().toPaddedString(2)+':'+
this.getMinutes().toPaddedString(2)+':'+
this.getSeconds().toPaddedString(2)+'"';};var Try={these:function(){var returnValue;for(var i=0,length=arguments.length;i<length;i++){var lambda=arguments[i];try{returnValue=lambda();break;}catch(e){}}
return returnValue;}}
var PeriodicalExecuter=Class.create();PeriodicalExecuter.prototype={initialize:function(callback,frequency){this.callback=callback;this.frequency=frequency;this.currentlyExecuting=false;this.registerCallback();},registerCallback:function(){this.timer=setInterval(this.onTimerEvent.bind(this),this.frequency*1000);},stop:function(){if(!this.timer)return;clearInterval(this.timer);this.timer=null;},onTimerEvent:function(){if(!this.currentlyExecuting){try{this.currentlyExecuting=true;this.callback(this);}finally{this.currentlyExecuting=false;}}}}
Object.extend(String,{interpret:function(value){return value==null?'':String(value);},specialChar:{'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','\\':'\\\\'}});Object.extend(String.prototype,{gsub:function(pattern,replacement){var result='',source=this,match;replacement=arguments.callee.prepareReplacement(replacement);while(source.length>0){if(match=source.match(pattern)){result+=source.slice(0,match.index);result+=String.interpret(replacement(match));source=source.slice(match.index+match[0].length);}else{result+=source,source='';}}
return result;},sub:function(pattern,replacement,count){replacement=this.gsub.prepareReplacement(replacement);count=count===undefined?1:count;return this.gsub(pattern,function(match){if(--count<0)return match[0];return replacement(match);});},scan:function(pattern,iterator){this.gsub(pattern,iterator);return this;},truncate:function(length,truncation){length=length||30;truncation=truncation===undefined?'...':truncation;return this.length>length?this.slice(0,length-truncation.length)+truncation:this;},strip:function(){return this.replace(/^\s+/,'').replace(/\s+$/,'');},stripTags:function(){return this.replace(/<\/?[^>]+>/gi,'');},stripScripts:function(){return this.replace(new RegExp(Prototype.ScriptFragment,'img'),'');},extractScripts:function(){var matchAll=new RegExp(Prototype.ScriptFragment,'img');var matchOne=new RegExp(Prototype.ScriptFragment,'im');return(this.match(matchAll)||[]).map(function(scriptTag){return(scriptTag.match(matchOne)||['',''])[1];});},evalScripts:function(){return this.extractScripts().map(function(script){return eval(script)});},escapeHTML:function(){var self=arguments.callee;self.text.data=this;return self.div.innerHTML;},unescapeHTML:function(){var div=document.createElement('div');div.innerHTML=this.stripTags();return div.childNodes[0]?(div.childNodes.length>1?$A(div.childNodes).inject('',function(memo,node){return memo+node.nodeValue}):div.childNodes[0].nodeValue):'';},toQueryParams:function(separator){var match=this.strip().match(/([^?#]*)(#.*)?$/);if(!match)return{};return match[1].split(separator||'&').inject({},function(hash,pair){if((pair=pair.split('='))[0]){var key=decodeURIComponent(pair.shift());var value=pair.length>1?pair.join('='):pair[0];if(value!=undefined)value=decodeURIComponent(value);if(key in hash){if(hash[key].constructor!=Array)hash[key]=[hash[key]];hash[key].push(value);}
else hash[key]=value;}
return hash;});},toArray:function(){return this.split('');},succ:function(){return this.slice(0,this.length-1)+
String.fromCharCode(this.charCodeAt(this.length-1)+1);},times:function(count){var result='';for(var i=0;i<count;i++)result+=this;return result;},camelize:function(){var parts=this.split('-'),len=parts.length;if(len==1)return parts[0];var camelized=this.charAt(0)=='-'?parts[0].charAt(0).toUpperCase()+parts[0].substring(1):parts[0];for(var i=1;i<len;i++)
camelized+=parts[i].charAt(0).toUpperCase()+parts[i].substring(1);return camelized;},capitalize:function(){return this.charAt(0).toUpperCase()+this.substring(1).toLowerCase();},underscore:function(){return this.gsub(/::/,'/').gsub(/([A-Z]+)([A-Z][a-z])/,'#{1}_#{2}').gsub(/([a-z\d])([A-Z])/,'#{1}_#{2}').gsub(/-/,'_').toLowerCase();},dasherize:function(){return this.gsub(/_/,'-');},inspect:function(useDoubleQuotes){var escapedString=this.gsub(/[\x00-\x1f\\]/,function(match){var character=String.specialChar[match[0]];return character?character:'\\u00'+match[0].charCodeAt().toPaddedString(2,16);});if(useDoubleQuotes)return'"'+escapedString.replace(/"/g,'\\"')+'"';return"'"+escapedString.replace(/'/g,'\\\'')+"'";},toJSON:function(){return this.inspect(true);},unfilterJSON:function(filter){return this.sub(filter||Prototype.JSONFilter,'#{1}');},isJSON:function(){var str=this.replace(/\\./g,'@').replace(/"[^"\\\n\r]*"/g,'');return(/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);},evalJSON:function(sanitize){var json=this.unfilterJSON();try{if(!sanitize||json.isJSON())return eval('('+json+')');}catch(e){}
throw new SyntaxError('Badly formed JSON string: '+this.inspect());},include:function(pattern){return this.indexOf(pattern)>-1;},startsWith:function(pattern){return this.indexOf(pattern)===0;},endsWith:function(pattern){var d=this.length-pattern.length;return d>=0&&this.lastIndexOf(pattern)===d;},empty:function(){return this=='';},blank:function(){return/^\s*$/.test(this);}});if(Prototype.Browser.WebKit||Prototype.Browser.IE)Object.extend(String.prototype,{escapeHTML:function(){return this.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');},unescapeHTML:function(){return this.replace(/&amp;/g,'&').replace(/&lt;/g,'<').replace(/&gt;/g,'>');}});String.prototype.gsub.prepareReplacement=function(replacement){if(typeof replacement=='function')return replacement;var template=new Template(replacement);return function(match){return template.evaluate(match)};}
String.prototype.parseQuery=String.prototype.toQueryParams;Object.extend(String.prototype.escapeHTML,{div:document.createElement('div'),text:document.createTextNode('')});with(String.prototype.escapeHTML)div.appendChild(text);var Template=Class.create();Template.Pattern=/(^|.|\r|\n)(#\{(.*?)\})/;Template.prototype={initialize:function(template,pattern){this.template=template.toString();this.pattern=pattern||Template.Pattern;},evaluate:function(object){return this.template.gsub(this.pattern,function(match){var before=match[1];if(before=='\\')return match[2];return before+String.interpret(object[match[3]]);});}}
var $break={},$continue=new Error('"throw $continue" is deprecated, use "return" instead');var Enumerable={each:function(iterator){var index=0;try{this._each(function(value){iterator(value,index++);});}catch(e){if(e!=$break)throw e;}
return this;},eachSlice:function(number,iterator){var index=-number,slices=[],array=this.toArray();while((index+=number)<array.length)
slices.push(array.slice(index,index+number));return slices.map(iterator);},all:function(iterator){var result=true;this.each(function(value,index){result=result&&!!(iterator||Prototype.K)(value,index);if(!result)throw $break;});return result;},any:function(iterator){var result=false;this.each(function(value,index){if(result=!!(iterator||Prototype.K)(value,index))
throw $break;});return result;},collect:function(iterator){var results=[];this.each(function(value,index){results.push((iterator||Prototype.K)(value,index));});return results;},detect:function(iterator){var result;this.each(function(value,index){if(iterator(value,index)){result=value;throw $break;}});return result;},findAll:function(iterator){var results=[];this.each(function(value,index){if(iterator(value,index))
results.push(value);});return results;},grep:function(pattern,iterator){var results=[];this.each(function(value,index){var stringValue=value.toString();if(stringValue.match(pattern))
results.push((iterator||Prototype.K)(value,index));})
return results;},include:function(object){var found=false;this.each(function(value){if(value==object){found=true;throw $break;}});return found;},inGroupsOf:function(number,fillWith){fillWith=fillWith===undefined?null:fillWith;return this.eachSlice(number,function(slice){while(slice.length<number)slice.push(fillWith);return slice;});},inject:function(memo,iterator){this.each(function(value,index){memo=iterator(memo,value,index);});return memo;},invoke:function(method){var args=$A(arguments).slice(1);return this.map(function(value){return value[method].apply(value,args);});},max:function(iterator){var result;this.each(function(value,index){value=(iterator||Prototype.K)(value,index);if(result==undefined||value>=result)
result=value;});return result;},min:function(iterator){var result;this.each(function(value,index){value=(iterator||Prototype.K)(value,index);if(result==undefined||value<result)
result=value;});return result;},partition:function(iterator){var trues=[],falses=[];this.each(function(value,index){((iterator||Prototype.K)(value,index)?trues:falses).push(value);});return[trues,falses];},pluck:function(property){var results=[];this.each(function(value,index){results.push(value[property]);});return results;},reject:function(iterator){var results=[];this.each(function(value,index){if(!iterator(value,index))
results.push(value);});return results;},sortBy:function(iterator){return this.map(function(value,index){return{value:value,criteria:iterator(value,index)};}).sort(function(left,right){var a=left.criteria,b=right.criteria;return a<b?-1:a>b?1:0;}).pluck('value');},toArray:function(){return this.map();},zip:function(){var iterator=Prototype.K,args=$A(arguments);if(typeof args.last()=='function')
iterator=args.pop();var collections=[this].concat(args).map($A);return this.map(function(value,index){return iterator(collections.pluck(index));});},size:function(){return this.toArray().length;},inspect:function(){return'#<Enumerable:'+this.toArray().inspect()+'>';}}
Object.extend(Enumerable,{map:Enumerable.collect,find:Enumerable.detect,select:Enumerable.findAll,member:Enumerable.include,entries:Enumerable.toArray});var $A=Array.from=function(iterable){if(!iterable)return[];if(iterable.toArray){return iterable.toArray();}else{var results=[];for(var i=0,length=iterable.length;i<length;i++)
results.push(iterable[i]);return results;}}
if(Prototype.Browser.WebKit){$A=Array.from=function(iterable){if(!iterable)return[];if(!(typeof iterable=='function'&&iterable=='[object NodeList]')&&iterable.toArray){return iterable.toArray();}else{var results=[];for(var i=0,length=iterable.length;i<length;i++)
results.push(iterable[i]);return results;}}}
Object.extend(Array.prototype,Enumerable);if(!Array.prototype._reverse)
Array.prototype._reverse=Array.prototype.reverse;Object.extend(Array.prototype,{_each:function(iterator){for(var i=0,length=this.length;i<length;i++)
iterator(this[i]);},clear:function(){this.length=0;return this;},first:function(){return this[0];},last:function(){return this[this.length-1];},compact:function(){return this.select(function(value){return value!=null;});},flatten:function(){return this.inject([],function(array,value){return array.concat(value&&value.constructor==Array?value.flatten():[value]);});},without:function(){var values=$A(arguments);return this.select(function(value){return!values.include(value);});},indexOf:function(object){for(var i=0,length=this.length;i<length;i++)
if(this[i]==object)return i;return-1;},reverse:function(inline){return(inline!==false?this:this.toArray())._reverse();},reduce:function(){return this.length>1?this:this[0];},uniq:function(sorted){return this.inject([],function(array,value,index){if(0==index||(sorted?array.last()!=value:!array.include(value)))
array.push(value);return array;});},clone:function(){return[].concat(this);},size:function(){return this.length;},inspect:function(){return'['+this.map(Object.inspect).join(', ')+']';},toJSON:function(){var results=[];this.each(function(object){var value=Object.toJSON(object);if(value!==undefined)results.push(value);});return'['+results.join(', ')+']';}});Array.prototype.toArray=Array.prototype.clone;function $w(string){string=string.strip();return string?string.split(/\s+/):[];}
if(Prototype.Browser.Opera){Array.prototype.concat=function(){var array=[];for(var i=0,length=this.length;i<length;i++)array.push(this[i]);for(var i=0,length=arguments.length;i<length;i++){if(arguments[i].constructor==Array){for(var j=0,arrayLength=arguments[i].length;j<arrayLength;j++)
array.push(arguments[i][j]);}else{array.push(arguments[i]);}}
return array;}}
var Hash=function(object){if(object instanceof Hash)this.merge(object);else Object.extend(this,object||{});};Object.extend(Hash,{toQueryString:function(obj){var parts=[];parts.add=arguments.callee.addPair;this.prototype._each.call(obj,function(pair){if(!pair.key)return;var value=pair.value;if(value&&typeof value=='object'){if(value.constructor==Array)value.each(function(value){parts.add(pair.key,value);});return;}
parts.add(pair.key,value);});return parts.join('&');},toJSON:function(object){var results=[];this.prototype._each.call(object,function(pair){var value=Object.toJSON(pair.value);if(value!==undefined)results.push(pair.key.toJSON()+': '+value);});return'{'+results.join(', ')+'}';}});Hash.toQueryString.addPair=function(key,value,prefix){key=encodeURIComponent(key);if(value===undefined)this.push(key);else this.push(key+'='+(value==null?'':encodeURIComponent(value)));}
Object.extend(Hash.prototype,Enumerable);Object.extend(Hash.prototype,{_each:function(iterator){for(var key in this){var value=this[key];if(value&&value==Hash.prototype[key])continue;var pair=[key,value];pair.key=key;pair.value=value;iterator(pair);}},keys:function(){return this.pluck('key');},values:function(){return this.pluck('value');},merge:function(hash){return $H(hash).inject(this,function(mergedHash,pair){mergedHash[pair.key]=pair.value;return mergedHash;});},remove:function(){var result;for(var i=0,length=arguments.length;i<length;i++){var value=this[arguments[i]];if(value!==undefined){if(result===undefined)result=value;else{if(result.constructor!=Array)result=[result];result.push(value)}}
delete this[arguments[i]];}
return result;},toQueryString:function(){return Hash.toQueryString(this);},inspect:function(){return'#<Hash:{'+this.map(function(pair){return pair.map(Object.inspect).join(': ');}).join(', ')+'}>';},toJSON:function(){return Hash.toJSON(this);}});function $H(object){if(object instanceof Hash)return object;return new Hash(object);};if(function(){var i=0,Test=function(value){this.key=value};Test.prototype.key='foo';for(var property in new Test('bar'))i++;return i>1;}())Hash.prototype._each=function(iterator){var cache=[];for(var key in this){var value=this[key];if((value&&value==Hash.prototype[key])||cache.include(key))continue;cache.push(key);var pair=[key,value];pair.key=key;pair.value=value;iterator(pair);}};ObjectRange=Class.create();Object.extend(ObjectRange.prototype,Enumerable);Object.extend(ObjectRange.prototype,{initialize:function(start,end,exclusive){this.start=start;this.end=end;this.exclusive=exclusive;},_each:function(iterator){var value=this.start;while(this.include(value)){iterator(value);value=value.succ();}},include:function(value){if(value<this.start)
return false;if(this.exclusive)
return value<this.end;return value<=this.end;}});var $R=function(start,end,exclusive){return new ObjectRange(start,end,exclusive);}
var Ajax={getTransport:function(){return Try.these(function(){return new XMLHttpRequest()},function(){return new ActiveXObject('Msxml2.XMLHTTP')},function(){return new ActiveXObject('Microsoft.XMLHTTP')})||false;},activeRequestCount:0}
Ajax.Responders={responders:[],_each:function(iterator){this.responders._each(iterator);},register:function(responder){if(!this.include(responder))
this.responders.push(responder);},unregister:function(responder){this.responders=this.responders.without(responder);},dispatch:function(callback,request,transport,json){this.each(function(responder){if(typeof responder[callback]=='function'){try{responder[callback].apply(responder,[request,transport,json]);}catch(e){}}});}};Object.extend(Ajax.Responders,Enumerable);Ajax.Responders.register({onCreate:function(){Ajax.activeRequestCount++;},onComplete:function(){Ajax.activeRequestCount--;}});Ajax.Base=function(){};Ajax.Base.prototype={setOptions:function(options){this.options={method:'post',asynchronous:true,contentType:'application/x-www-form-urlencoded',encoding:'UTF-8',parameters:''}
Object.extend(this.options,options||{});this.options.method=this.options.method.toLowerCase();if(typeof this.options.parameters=='string')
this.options.parameters=this.options.parameters.toQueryParams();}}
Ajax.Request=Class.create();Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];Ajax.Request.prototype=Object.extend(new Ajax.Base(),{_complete:false,initialize:function(url,options){this.transport=Ajax.getTransport();this.setOptions(options);this.request(url);},request:function(url){this.url=url;this.method=this.options.method;var params=Object.clone(this.options.parameters);if(!['get','post'].include(this.method)){params['_method']=this.method;this.method='post';}
this.parameters=params;if(params=Hash.toQueryString(params)){if(this.method=='get')
this.url+=(this.url.include('?')?'&':'?')+params;else if(/Konqueror|Safari|KHTML/.test(navigator.userAgent))
params+='&_=';}
try{if(this.options.onCreate)this.options.onCreate(this.transport);Ajax.Responders.dispatch('onCreate',this,this.transport);this.transport.open(this.method.toUpperCase(),this.url,this.options.asynchronous);if(this.options.asynchronous)
setTimeout(function(){this.respondToReadyState(1)}.bind(this),10);this.transport.onreadystatechange=this.onStateChange.bind(this);this.setRequestHeaders();this.body=this.method=='post'?(this.options.postBody||params):null;this.transport.send(this.body);if(!this.options.asynchronous&&this.transport.overrideMimeType)
this.onStateChange();}
catch(e){this.dispatchException(e);}},onStateChange:function(){var readyState=this.transport.readyState;if(readyState>1&&!((readyState==4)&&this._complete))
this.respondToReadyState(this.transport.readyState);},setRequestHeaders:function(){var headers={'X-Requested-With':'XMLHttpRequest','X-Prototype-Version':Prototype.Version,'Accept':'text/javascript, text/html, application/xml, text/xml, */*'};if(this.method=='post'){headers['Content-type']=this.options.contentType+
(this.options.encoding?'; charset='+this.options.encoding:'');if(this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005)
headers['Connection']='close';}
if(typeof this.options.requestHeaders=='object'){var extras=this.options.requestHeaders;if(typeof extras.push=='function')
for(var i=0,length=extras.length;i<length;i+=2)
headers[extras[i]]=extras[i+1];else
$H(extras).each(function(pair){headers[pair.key]=pair.value});}
for(var name in headers)
this.transport.setRequestHeader(name,headers[name]);},success:function(){return!this.transport.status||(this.transport.status>=200&&this.transport.status<300);},respondToReadyState:function(readyState){var state=Ajax.Request.Events[readyState];var transport=this.transport,json=this.evalJSON();if(state=='Complete'){try{this._complete=true;(this.options['on'+this.transport.status]||this.options['on'+(this.success()?'Success':'Failure')]||Prototype.emptyFunction)(transport,json);}catch(e){this.dispatchException(e);}
var contentType=this.getHeader('Content-type');if(contentType&&contentType.strip().match(/^(text|application)\/(x-)?(java|ecma)script(;.*)?$/i))
this.evalResponse();}
try{(this.options['on'+state]||Prototype.emptyFunction)(transport,json);Ajax.Responders.dispatch('on'+state,this,transport,json);}catch(e){this.dispatchException(e);}
if(state=='Complete'){this.transport.onreadystatechange=Prototype.emptyFunction;}},getHeader:function(name){try{return this.transport.getResponseHeader(name);}catch(e){return null}},evalJSON:function(){try{var json=this.getHeader('X-JSON');return json?json.evalJSON():null;}catch(e){return null}},evalResponse:function(){try{return eval((this.transport.responseText||'').unfilterJSON());}catch(e){this.dispatchException(e);}},dispatchException:function(exception){(this.options.onException||Prototype.emptyFunction)(this,exception);Ajax.Responders.dispatch('onException',this,exception);}});Ajax.Updater=Class.create();Object.extend(Object.extend(Ajax.Updater.prototype,Ajax.Request.prototype),{initialize:function(container,url,options){this.container={success:(container.success||container),failure:(container.failure||(container.success?null:container))}
this.transport=Ajax.getTransport();this.setOptions(options);var onComplete=this.options.onComplete||Prototype.emptyFunction;this.options.onComplete=(function(transport,param){this.updateContent();onComplete(transport,param);}).bind(this);this.request(url);},updateContent:function(){var receiver=this.container[this.success()?'success':'failure'];var response=this.transport.responseText;if(!this.options.evalScripts)response=response.stripScripts();if(receiver=$(receiver)){if(this.options.insertion)
new this.options.insertion(receiver,response);else
receiver.update(response);}
if(this.success()){if(this.onComplete)
setTimeout(this.onComplete.bind(this),10);}}});Ajax.PeriodicalUpdater=Class.create();Ajax.PeriodicalUpdater.prototype=Object.extend(new Ajax.Base(),{initialize:function(container,url,options){this.setOptions(options);this.onComplete=this.options.onComplete;this.frequency=(this.options.frequency||2);this.decay=(this.options.decay||1);this.updater={};this.container=container;this.url=url;this.start();},start:function(){this.options.onComplete=this.updateComplete.bind(this);this.onTimerEvent();},stop:function(){this.updater.options.onComplete=undefined;clearTimeout(this.timer);(this.onComplete||Prototype.emptyFunction).apply(this,arguments);},updateComplete:function(request){if(this.options.decay){this.decay=(request.responseText==this.lastText?this.decay*this.options.decay:1);this.lastText=request.responseText;}
this.timer=setTimeout(this.onTimerEvent.bind(this),this.decay*this.frequency*1000);},onTimerEvent:function(){this.updater=new Ajax.Updater(this.container,this.url,this.options);}});function $(element){if(arguments.length>1){for(var i=0,elements=[],length=arguments.length;i<length;i++)
elements.push($(arguments[i]));return elements;}
if(typeof element=='string')
element=document.getElementById(element);return Element.extend(element);}
if(Prototype.BrowserFeatures.XPath){document._getElementsByXPath=function(expression,parentElement){var results=[];var query=document.evaluate(expression,$(parentElement)||document,null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);for(var i=0,length=query.snapshotLength;i<length;i++)
results.push(query.snapshotItem(i));return results;};document.getElementsByClassName=function(className,parentElement){var q=".//*[contains(concat(' ', @class, ' '), ' "+className+" ')]";return document._getElementsByXPath(q,parentElement);}}else document.getElementsByClassName=function(className,parentElement){var children=($(parentElement)||document.body).getElementsByTagName('*');var elements=[],child,pattern=new RegExp("(^|\\s)"+className+"(\\s|$)");for(var i=0,length=children.length;i<length;i++){child=children[i];var elementClassName=child.className;if(elementClassName.length==0)continue;if(elementClassName==className||elementClassName.match(pattern))
elements.push(Element.extend(child));}
return elements;};if(!window.Element)var Element={};Element.extend=function(element){var F=Prototype.BrowserFeatures;if(!element||!element.tagName||element.nodeType==3||element._extended||F.SpecificElementExtensions||element==window)
return element;var methods={},tagName=element.tagName,cache=Element.extend.cache,T=Element.Methods.ByTag;if(!F.ElementExtensions){Object.extend(methods,Element.Methods),Object.extend(methods,Element.Methods.Simulated);}
if(T[tagName])Object.extend(methods,T[tagName]);for(var property in methods){var value=methods[property];if(typeof value=='function'&&!(property in element))
element[property]=cache.findOrStore(value);}
element._extended=Prototype.emptyFunction;return element;};Element.extend.cache={findOrStore:function(value){return this[value]=this[value]||function(){return value.apply(null,[this].concat($A(arguments)));}}};Element.Methods={visible:function(element){return $(element).style.display!='none';},toggle:function(element){element=$(element);Element[Element.visible(element)?'hide':'show'](element);return element;},hide:function(element){$(element).style.display='none';return element;},show:function(element){$(element).style.display='';return element;},remove:function(element){element=$(element);element.parentNode.removeChild(element);return element;},update:function(element,html){html=typeof html=='undefined'?'':html.toString();$(element).innerHTML=html.stripScripts();setTimeout(function(){html.evalScripts()},10);return element;},replace:function(element,html){element=$(element);html=typeof html=='undefined'?'':html.toString();if(element.outerHTML){element.outerHTML=html.stripScripts();}else{var range=element.ownerDocument.createRange();range.selectNodeContents(element);element.parentNode.replaceChild(range.createContextualFragment(html.stripScripts()),element);}
setTimeout(function(){html.evalScripts()},10);return element;},inspect:function(element){element=$(element);var result='<'+element.tagName.toLowerCase();$H({'id':'id','className':'class'}).each(function(pair){var property=pair.first(),attribute=pair.last();var value=(element[property]||'').toString();if(value)result+=' '+attribute+'='+value.inspect(true);});return result+'>';},recursivelyCollect:function(element,property){element=$(element);var elements=[];while(element=element[property])
if(element.nodeType==1)
elements.push(Element.extend(element));return elements;},ancestors:function(element){return $(element).recursivelyCollect('parentNode');},descendants:function(element){return $A($(element).getElementsByTagName('*')).each(Element.extend);},firstDescendant:function(element){element=$(element).firstChild;while(element&&element.nodeType!=1)element=element.nextSibling;return $(element);},immediateDescendants:function(element){if(!(element=$(element).firstChild))return[];while(element&&element.nodeType!=1)element=element.nextSibling;if(element)return[element].concat($(element).nextSiblings());return[];},previousSiblings:function(element){return $(element).recursivelyCollect('previousSibling');},nextSiblings:function(element){return $(element).recursivelyCollect('nextSibling');},siblings:function(element){element=$(element);return element.previousSiblings().reverse().concat(element.nextSiblings());},match:function(element,selector){if(typeof selector=='string')
selector=new Selector(selector);return selector.match($(element));},up:function(element,expression,index){element=$(element);if(arguments.length==1)return $(element.parentNode);var ancestors=element.ancestors();return expression?Selector.findElement(ancestors,expression,index):ancestors[index||0];},down:function(element,expression,index){element=$(element);if(arguments.length==1)return element.firstDescendant();var descendants=element.descendants();return expression?Selector.findElement(descendants,expression,index):descendants[index||0];},previous:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.previousElementSibling(element));var previousSiblings=element.previousSiblings();return expression?Selector.findElement(previousSiblings,expression,index):previousSiblings[index||0];},next:function(element,expression,index){element=$(element);if(arguments.length==1)return $(Selector.handlers.nextElementSibling(element));var nextSiblings=element.nextSiblings();return expression?Selector.findElement(nextSiblings,expression,index):nextSiblings[index||0];},getElementsBySelector:function(){var args=$A(arguments),element=$(args.shift());return Selector.findChildElements(element,args);},getElementsByClassName:function(element,className){return document.getElementsByClassName(className,element);},readAttribute:function(element,name){element=$(element);if(Prototype.Browser.IE){if(!element.attributes)return null;var t=Element._attributeTranslations;if(t.values[name])return t.values[name](element,name);if(t.names[name])name=t.names[name];var attribute=element.attributes[name];return attribute?attribute.nodeValue:null;}
return element.getAttribute(name);},getHeight:function(element){return $(element).getDimensions().height;},getWidth:function(element){return $(element).getDimensions().width;},classNames:function(element){return new Element.ClassNames(element);},hasClassName:function(element,className){if(!(element=$(element)))return;var elementClassName=element.className;if(elementClassName.length==0)return false;if(elementClassName==className||elementClassName.match(new RegExp("(^|\\s)"+className+"(\\s|$)")))
return true;return false;},addClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element).add(className);return element;},removeClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element).remove(className);return element;},toggleClassName:function(element,className){if(!(element=$(element)))return;Element.classNames(element)[element.hasClassName(className)?'remove':'add'](className);return element;},observe:function(){Event.observe.apply(Event,arguments);return $A(arguments).first();},stopObserving:function(){Event.stopObserving.apply(Event,arguments);return $A(arguments).first();},cleanWhitespace:function(element){element=$(element);var node=element.firstChild;while(node){var nextNode=node.nextSibling;if(node.nodeType==3&&!/\S/.test(node.nodeValue))
element.removeChild(node);node=nextNode;}
return element;},empty:function(element){return $(element).innerHTML.blank();},descendantOf:function(element,ancestor){element=$(element),ancestor=$(ancestor);while(element=element.parentNode)
if(element==ancestor)return true;return false;},scrollTo:function(element){element=$(element);var pos=Position.cumulativeOffset(element);window.scrollTo(pos[0],pos[1]);return element;},getStyle:function(element,style){element=$(element);style=style=='float'?'cssFloat':style.camelize();var value=element.style[style];if(!value){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null;}
if(style=='opacity')return value?parseFloat(value):1.0;return value=='auto'?null:value;},getOpacity:function(element){return $(element).getStyle('opacity');},setStyle:function(element,styles,camelized){element=$(element);var elementStyle=element.style;for(var property in styles)
if(property=='opacity')element.setOpacity(styles[property])
else
elementStyle[(property=='float'||property=='cssFloat')?(elementStyle.styleFloat===undefined?'cssFloat':'styleFloat'):(camelized?property:property.camelize())]=styles[property];return element;},setOpacity:function(element,value){element=$(element);element.style.opacity=(value==1||value==='')?'':(value<0.00001)?0:value;return element;},getDimensions:function(element){element=$(element);var display=$(element).getStyle('display');if(display!='none'&&display!=null)
return{width:element.offsetWidth,height:element.offsetHeight};var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility='hidden';els.position='absolute';els.display='block';var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};},makePositioned:function(element){element=$(element);var pos=Element.getStyle(element,'position');if(pos=='static'||!pos){element._madePositioned=true;element.style.position='relative';if(window.opera){element.style.top=0;element.style.left=0;}}
return element;},undoPositioned:function(element){element=$(element);if(element._madePositioned){element._madePositioned=undefined;element.style.position=element.style.top=element.style.left=element.style.bottom=element.style.right='';}
return element;},makeClipping:function(element){element=$(element);if(element._overflow)return element;element._overflow=element.style.overflow||'auto';if((Element.getStyle(element,'overflow')||'visible')!='hidden')
element.style.overflow='hidden';return element;},undoClipping:function(element){element=$(element);if(!element._overflow)return element;element.style.overflow=element._overflow=='auto'?'':element._overflow;element._overflow=null;return element;}};Object.extend(Element.Methods,{childOf:Element.Methods.descendantOf,childElements:Element.Methods.immediateDescendants});if(Prototype.Browser.Opera){Element.Methods._getStyle=Element.Methods.getStyle;Element.Methods.getStyle=function(element,style){switch(style){case'left':case'top':case'right':case'bottom':if(Element._getStyle(element,'position')=='static')return null;default:return Element._getStyle(element,style);}};}
else if(Prototype.Browser.IE){Element.Methods.getStyle=function(element,style){element=$(element);style=(style=='float'||style=='cssFloat')?'styleFloat':style.camelize();var value=element.style[style];if(!value&&element.currentStyle)value=element.currentStyle[style];if(style=='opacity'){if(value=(element.getStyle('filter')||'').match(/alpha\(opacity=(.*)\)/))
if(value[1])return parseFloat(value[1])/100;return 1.0;}
if(value=='auto'){if((style=='width'||style=='height')&&(element.getStyle('display')!='none'))
return element['offset'+style.capitalize()]+'px';return null;}
return value;};Element.Methods.setOpacity=function(element,value){element=$(element);var filter=element.getStyle('filter'),style=element.style;if(value==1||value===''){style.filter=filter.replace(/alpha\([^\)]*\)/gi,'');return element;}else if(value<0.00001)value=0;style.filter=filter.replace(/alpha\([^\)]*\)/gi,'')+'alpha(opacity='+(value*100)+')';return element;};Element.Methods.update=function(element,html){element=$(element);html=typeof html=='undefined'?'':html.toString();var tagName=element.tagName.toUpperCase();if(['THEAD','TBODY','TR','TD'].include(tagName)){var div=document.createElement('div');switch(tagName){case'THEAD':case'TBODY':div.innerHTML='<table><tbody>'+html.stripScripts()+'</tbody></table>';depth=2;break;case'TR':div.innerHTML='<table><tbody><tr>'+html.stripScripts()+'</tr></tbody></table>';depth=3;break;case'TD':div.innerHTML='<table><tbody><tr><td>'+html.stripScripts()+'</td></tr></tbody></table>';depth=4;}
$A(element.childNodes).each(function(node){element.removeChild(node)});depth.times(function(){div=div.firstChild});$A(div.childNodes).each(function(node){element.appendChild(node)});}else{element.innerHTML=html.stripScripts();}
setTimeout(function(){html.evalScripts()},10);return element;}}
else if(Prototype.Browser.Gecko){Element.Methods.setOpacity=function(element,value){element=$(element);element.style.opacity=(value==1)?0.999999:(value==='')?'':(value<0.00001)?0:value;return element;};}
Element._attributeTranslations={names:{colspan:"colSpan",rowspan:"rowSpan",valign:"vAlign",datetime:"dateTime",accesskey:"accessKey",tabindex:"tabIndex",enctype:"encType",maxlength:"maxLength",readonly:"readOnly",longdesc:"longDesc"},values:{_getAttr:function(element,attribute){return element.getAttribute(attribute,2);},_flag:function(element,attribute){return $(element).hasAttribute(attribute)?attribute:null;},style:function(element){return element.style.cssText.toLowerCase();},title:function(element){var node=element.getAttributeNode('title');return node.specified?node.nodeValue:null;}}};(function(){Object.extend(this,{href:this._getAttr,src:this._getAttr,type:this._getAttr,disabled:this._flag,checked:this._flag,readonly:this._flag,multiple:this._flag});}).call(Element._attributeTranslations.values);Element.Methods.Simulated={hasAttribute:function(element,attribute){var t=Element._attributeTranslations,node;attribute=t.names[attribute]||attribute;node=$(element).getAttributeNode(attribute);return node&&node.specified;}};Element.Methods.ByTag={};Object.extend(Element,Element.Methods);if(!Prototype.BrowserFeatures.ElementExtensions&&document.createElement('div').__proto__){window.HTMLElement={};window.HTMLElement.prototype=document.createElement('div').__proto__;Prototype.BrowserFeatures.ElementExtensions=true;}
Element.hasAttribute=function(element,attribute){if(element.hasAttribute)return element.hasAttribute(attribute);return Element.Methods.Simulated.hasAttribute(element,attribute);};Element.addMethods=function(methods){var F=Prototype.BrowserFeatures,T=Element.Methods.ByTag;if(!methods){Object.extend(Form,Form.Methods);Object.extend(Form.Element,Form.Element.Methods);Object.extend(Element.Methods.ByTag,{"FORM":Object.clone(Form.Methods),"INPUT":Object.clone(Form.Element.Methods),"SELECT":Object.clone(Form.Element.Methods),"TEXTAREA":Object.clone(Form.Element.Methods)});}
if(arguments.length==2){var tagName=methods;methods=arguments[1];}
if(!tagName)Object.extend(Element.Methods,methods||{});else{if(tagName.constructor==Array)tagName.each(extend);else extend(tagName);}
function extend(tagName){tagName=tagName.toUpperCase();if(!Element.Methods.ByTag[tagName])
Element.Methods.ByTag[tagName]={};Object.extend(Element.Methods.ByTag[tagName],methods);}
function copy(methods,destination,onlyIfAbsent){onlyIfAbsent=onlyIfAbsent||false;var cache=Element.extend.cache;for(var property in methods){var value=methods[property];if(!onlyIfAbsent||!(property in destination))
destination[property]=cache.findOrStore(value);}}
function findDOMClass(tagName){var klass;var trans={"OPTGROUP":"OptGroup","TEXTAREA":"TextArea","P":"Paragraph","FIELDSET":"FieldSet","UL":"UList","OL":"OList","DL":"DList","DIR":"Directory","H1":"Heading","H2":"Heading","H3":"Heading","H4":"Heading","H5":"Heading","H6":"Heading","Q":"Quote","INS":"Mod","DEL":"Mod","A":"Anchor","IMG":"Image","CAPTION":"TableCaption","COL":"TableCol","COLGROUP":"TableCol","THEAD":"TableSection","TFOOT":"TableSection","TBODY":"TableSection","TR":"TableRow","TH":"TableCell","TD":"TableCell","FRAMESET":"FrameSet","IFRAME":"IFrame"};if(trans[tagName])klass='HTML'+trans[tagName]+'Element';if(window[klass])return window[klass];klass='HTML'+tagName+'Element';if(window[klass])return window[klass];klass='HTML'+tagName.capitalize()+'Element';if(window[klass])return window[klass];window[klass]={};window[klass].prototype=document.createElement(tagName).__proto__;return window[klass];}
if(F.ElementExtensions){copy(Element.Methods,HTMLElement.prototype);copy(Element.Methods.Simulated,HTMLElement.prototype,true);}
if(F.SpecificElementExtensions){for(var tag in Element.Methods.ByTag){var klass=findDOMClass(tag);if(typeof klass=="undefined")continue;copy(T[tag],klass.prototype);}}
Object.extend(Element,Element.Methods);delete Element.ByTag;};var Toggle={display:Element.toggle};Abstract.Insertion=function(adjacency){this.adjacency=adjacency;}
Abstract.Insertion.prototype={initialize:function(element,content){this.element=$(element);this.content=content.stripScripts();if(this.adjacency&&this.element.insertAdjacentHTML){try{this.element.insertAdjacentHTML(this.adjacency,this.content);}catch(e){var tagName=this.element.tagName.toUpperCase();if(['TBODY','TR'].include(tagName)){this.insertContent(this.contentFromAnonymousTable());}else{throw e;}}}else{this.range=this.element.ownerDocument.createRange();if(this.initializeRange)this.initializeRange();this.insertContent([this.range.createContextualFragment(this.content)]);}
setTimeout(function(){content.evalScripts()},10);},contentFromAnonymousTable:function(){var div=document.createElement('div');div.innerHTML='<table><tbody>'+this.content+'</tbody></table>';return $A(div.childNodes[0].childNodes[0].childNodes);}}
var Insertion=new Object();Insertion.Before=Class.create();Insertion.Before.prototype=Object.extend(new Abstract.Insertion('beforeBegin'),{initializeRange:function(){this.range.setStartBefore(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.parentNode.insertBefore(fragment,this.element);}).bind(this));}});Insertion.Top=Class.create();Insertion.Top.prototype=Object.extend(new Abstract.Insertion('afterBegin'),{initializeRange:function(){this.range.selectNodeContents(this.element);this.range.collapse(true);},insertContent:function(fragments){fragments.reverse(false).each((function(fragment){this.element.insertBefore(fragment,this.element.firstChild);}).bind(this));}});Insertion.Bottom=Class.create();Insertion.Bottom.prototype=Object.extend(new Abstract.Insertion('beforeEnd'),{initializeRange:function(){this.range.selectNodeContents(this.element);this.range.collapse(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.appendChild(fragment);}).bind(this));}});Insertion.After=Class.create();Insertion.After.prototype=Object.extend(new Abstract.Insertion('afterEnd'),{initializeRange:function(){this.range.setStartAfter(this.element);},insertContent:function(fragments){fragments.each((function(fragment){this.element.parentNode.insertBefore(fragment,this.element.nextSibling);}).bind(this));}});Element.ClassNames=Class.create();Element.ClassNames.prototype={initialize:function(element){this.element=$(element);},_each:function(iterator){this.element.className.split(/\s+/).select(function(name){return name.length>0;})._each(iterator);},set:function(className){this.element.className=className;},add:function(classNameToAdd){if(this.include(classNameToAdd))return;this.set($A(this).concat(classNameToAdd).join(' '));},remove:function(classNameToRemove){if(!this.include(classNameToRemove))return;this.set($A(this).without(classNameToRemove).join(' '));},toString:function(){return $A(this).join(' ');}};Object.extend(Element.ClassNames.prototype,Enumerable);var Selector=Class.create();Selector.prototype={initialize:function(expression){this.expression=expression.strip();this.compileMatcher();},compileMatcher:function(){if(Prototype.BrowserFeatures.XPath&&!(/\[[\w-]*?:/).test(this.expression))
return this.compileXPathMatcher();var e=this.expression,ps=Selector.patterns,h=Selector.handlers,c=Selector.criteria,le,p,m;if(Selector._cache[e]){this.matcher=Selector._cache[e];return;}
this.matcher=["this.matcher = function(root) {","var r = root, h = Selector.handlers, c = false, n;"];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){p=ps[i];if(m=e.match(p)){this.matcher.push(typeof c[i]=='function'?c[i](m):new Template(c[i]).evaluate(m));e=e.replace(m[0],'');break;}}}
this.matcher.push("return h.unique(n);\n}");eval(this.matcher.join('\n'));Selector._cache[this.expression]=this.matcher;},compileXPathMatcher:function(){var e=this.expression,ps=Selector.patterns,x=Selector.xpath,le,m;if(Selector._cache[e]){this.xpath=Selector._cache[e];return;}
this.matcher=['.//*'];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in ps){if(m=e.match(ps[i])){this.matcher.push(typeof x[i]=='function'?x[i](m):new Template(x[i]).evaluate(m));e=e.replace(m[0],'');break;}}}
this.xpath=this.matcher.join('');Selector._cache[this.expression]=this.xpath;},findElements:function(root){root=root||document;if(this.xpath)return document._getElementsByXPath(this.xpath,root);return this.matcher(root);},match:function(element){return this.findElements(document).include(element);},toString:function(){return this.expression;},inspect:function(){return"#<Selector:"+this.expression.inspect()+">";}};Object.extend(Selector,{_cache:{},xpath:{descendant:"//*",child:"/*",adjacent:"/following-sibling::*[1]",laterSibling:'/following-sibling::*',tagName:function(m){if(m[1]=='*')return'';return"[local-name()='"+m[1].toLowerCase()+"' or local-name()='"+m[1].toUpperCase()+"']";},className:"[contains(concat(' ', @class, ' '), ' #{1} ')]",id:"[@id='#{1}']",attrPresence:"[@#{1}]",attr:function(m){m[3]=m[5]||m[6];return new Template(Selector.xpath.operators[m[2]]).evaluate(m);},pseudo:function(m){var h=Selector.xpath.pseudos[m[1]];if(!h)return'';if(typeof h==='function')return h(m);return new Template(Selector.xpath.pseudos[m[1]]).evaluate(m);},operators:{'=':"[@#{1}='#{3}']",'!=':"[@#{1}!='#{3}']",'^=':"[starts-with(@#{1}, '#{3}')]",'$=':"[substring(@#{1}, (string-length(@#{1}) - string-length('#{3}') + 1))='#{3}']",'*=':"[contains(@#{1}, '#{3}')]",'~=':"[contains(concat(' ', @#{1}, ' '), ' #{3} ')]",'|=':"[contains(concat('-', @#{1}, '-'), '-#{3}-')]"},pseudos:{'first-child':'[not(preceding-sibling::*)]','last-child':'[not(following-sibling::*)]','only-child':'[not(preceding-sibling::* or following-sibling::*)]','empty':"[count(*) = 0 and (count(text()) = 0 or translate(text(), ' \t\r\n', '') = '')]",'checked':"[@checked]",'disabled':"[@disabled]",'enabled':"[not(@disabled)]",'not':function(m){var e=m[6],p=Selector.patterns,x=Selector.xpath,le,m,v;var exclusion=[];while(e&&le!=e&&(/\S/).test(e)){le=e;for(var i in p){if(m=e.match(p[i])){v=typeof x[i]=='function'?x[i](m):new Template(x[i]).evaluate(m);exclusion.push("("+v.substring(1,v.length-1)+")");e=e.replace(m[0],'');break;}}}
return"[not("+exclusion.join(" and ")+")]";},'nth-child':function(m){return Selector.xpath.pseudos.nth("(count(./preceding-sibling::*) + 1) ",m);},'nth-last-child':function(m){return Selector.xpath.pseudos.nth("(count(./following-sibling::*) + 1) ",m);},'nth-of-type':function(m){return Selector.xpath.pseudos.nth("position() ",m);},'nth-last-of-type':function(m){return Selector.xpath.pseudos.nth("(last() + 1 - position()) ",m);},'first-of-type':function(m){m[6]="1";return Selector.xpath.pseudos['nth-of-type'](m);},'last-of-type':function(m){m[6]="1";return Selector.xpath.pseudos['nth-last-of-type'](m);},'only-of-type':function(m){var p=Selector.xpath.pseudos;return p['first-of-type'](m)+p['last-of-type'](m);},nth:function(fragment,m){var mm,formula=m[6],predicate;if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';if(mm=formula.match(/^(\d+)$/))
return'['+fragment+"= "+mm[1]+']';if(mm=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(mm[1]=="-")mm[1]=-1;var a=mm[1]?Number(mm[1]):1;var b=mm[2]?Number(mm[2]):0;predicate="[((#{fragment} - #{b}) mod #{a} = 0) and "+"((#{fragment} - #{b}) div #{a} >= 0)]";return new Template(predicate).evaluate({fragment:fragment,a:a,b:b});}}}},criteria:{tagName:'n = h.tagName(n, r, "#{1}", c);   c = false;',className:'n = h.className(n, r, "#{1}", c); c = false;',id:'n = h.id(n, r, "#{1}", c);        c = false;',attrPresence:'n = h.attrPresence(n, r, "#{1}"); c = false;',attr:function(m){m[3]=(m[5]||m[6]);return new Template('n = h.attr(n, r, "#{1}", "#{3}", "#{2}"); c = false;').evaluate(m);},pseudo:function(m){if(m[6])m[6]=m[6].replace(/"/g,'\\"');return new Template('n = h.pseudo(n, "#{1}", "#{6}", r, c); c = false;').evaluate(m);},descendant:'c = "descendant";',child:'c = "child";',adjacent:'c = "adjacent";',laterSibling:'c = "laterSibling";'},patterns:{laterSibling:/^\s*~\s*/,child:/^\s*>\s*/,adjacent:/^\s*\+\s*/,descendant:/^\s/,tagName:/^\s*(\*|[\w\-]+)(\b|$)?/,id:/^#([\w\-\*]+)(\b|$)/,className:/^\.([\w\-\*]+)(\b|$)/,pseudo:/^:((first|last|nth|nth-last|only)(-child|-of-type)|empty|checked|(en|dis)abled|not)(\((.*?)\))?(\b|$|\s|(?=:))/,attrPresence:/^\[([\w]+)\]/,attr:/\[((?:[\w-]*:)?[\w-]+)\s*(?:([!^$*~|]?=)\s*((['"])([^\]]*?)\4|([^'"][^\]]*?)))?\]/},handlers:{concat:function(a,b){for(var i=0,node;node=b[i];i++)
a.push(node);return a;},mark:function(nodes){for(var i=0,node;node=nodes[i];i++)
node._counted=true;return nodes;},unmark:function(nodes){for(var i=0,node;node=nodes[i];i++)
node._counted=undefined;return nodes;},index:function(parentNode,reverse,ofType){parentNode._counted=true;if(reverse){for(var nodes=parentNode.childNodes,i=nodes.length-1,j=1;i>=0;i--){node=nodes[i];if(node.nodeType==1&&(!ofType||node._counted))node.nodeIndex=j++;}}else{for(var i=0,j=1,nodes=parentNode.childNodes;node=nodes[i];i++)
if(node.nodeType==1&&(!ofType||node._counted))node.nodeIndex=j++;}},unique:function(nodes){if(nodes.length==0)return nodes;var results=[],n;for(var i=0,l=nodes.length;i<l;i++)
if(!(n=nodes[i])._counted){n._counted=true;results.push(Element.extend(n));}
return Selector.handlers.unmark(results);},descendant:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
h.concat(results,node.getElementsByTagName('*'));return results;},child:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++){for(var j=0,children=[],child;child=node.childNodes[j];j++)
if(child.nodeType==1&&child.tagName!='!')results.push(child);}
return results;},adjacent:function(nodes){for(var i=0,results=[],node;node=nodes[i];i++){var next=this.nextElementSibling(node);if(next)results.push(next);}
return results;},laterSibling:function(nodes){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
h.concat(results,Element.nextSiblings(node));return results;},nextElementSibling:function(node){while(node=node.nextSibling)
if(node.nodeType==1)return node;return null;},previousElementSibling:function(node){while(node=node.previousSibling)
if(node.nodeType==1)return node;return null;},tagName:function(nodes,root,tagName,combinator){tagName=tagName.toUpperCase();var results=[],h=Selector.handlers;if(nodes){if(combinator){if(combinator=="descendant"){for(var i=0,node;node=nodes[i];i++)
h.concat(results,node.getElementsByTagName(tagName));return results;}else nodes=this[combinator](nodes);if(tagName=="*")return nodes;}
for(var i=0,node;node=nodes[i];i++)
if(node.tagName.toUpperCase()==tagName)results.push(node);return results;}else return root.getElementsByTagName(tagName);},id:function(nodes,root,id,combinator){var targetNode=$(id),h=Selector.handlers;if(!nodes&&root==document)return targetNode?[targetNode]:[];if(nodes){if(combinator){if(combinator=='child'){for(var i=0,node;node=nodes[i];i++)
if(targetNode.parentNode==node)return[targetNode];}else if(combinator=='descendant'){for(var i=0,node;node=nodes[i];i++)
if(Element.descendantOf(targetNode,node))return[targetNode];}else if(combinator=='adjacent'){for(var i=0,node;node=nodes[i];i++)
if(Selector.handlers.previousElementSibling(targetNode)==node)
return[targetNode];}else nodes=h[combinator](nodes);}
for(var i=0,node;node=nodes[i];i++)
if(node==targetNode)return[targetNode];return[];}
return(targetNode&&Element.descendantOf(targetNode,root))?[targetNode]:[];},className:function(nodes,root,className,combinator){if(nodes&&combinator)nodes=this[combinator](nodes);return Selector.handlers.byClassName(nodes,root,className);},byClassName:function(nodes,root,className){if(!nodes)nodes=Selector.handlers.descendant([root]);var needle=' '+className+' ';for(var i=0,results=[],node,nodeClassName;node=nodes[i];i++){nodeClassName=node.className;if(nodeClassName.length==0)continue;if(nodeClassName==className||(' '+nodeClassName+' ').include(needle))
results.push(node);}
return results;},attrPresence:function(nodes,root,attr){var results=[];for(var i=0,node;node=nodes[i];i++)
if(Element.hasAttribute(node,attr))results.push(node);return results;},attr:function(nodes,root,attr,value,operator){if(!nodes)nodes=root.getElementsByTagName("*");var handler=Selector.operators[operator],results=[];for(var i=0,node;node=nodes[i];i++){var nodeValue=Element.readAttribute(node,attr);if(nodeValue===null)continue;if(handler(nodeValue,value))results.push(node);}
return results;},pseudo:function(nodes,name,value,root,combinator){if(nodes&&combinator)nodes=this[combinator](nodes);if(!nodes)nodes=root.getElementsByTagName("*");return Selector.pseudos[name](nodes,value,root);}},pseudos:{'first-child':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(Selector.handlers.previousElementSibling(node))continue;results.push(node);}
return results;},'last-child':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(Selector.handlers.nextElementSibling(node))continue;results.push(node);}
return results;},'only-child':function(nodes,value,root){var h=Selector.handlers;for(var i=0,results=[],node;node=nodes[i];i++)
if(!h.previousElementSibling(node)&&!h.nextElementSibling(node))
results.push(node);return results;},'nth-child':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root);},'nth-last-child':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,true);},'nth-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,false,true);},'nth-last-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,formula,root,true,true);},'first-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,"1",root,false,true);},'last-of-type':function(nodes,formula,root){return Selector.pseudos.nth(nodes,"1",root,true,true);},'only-of-type':function(nodes,formula,root){var p=Selector.pseudos;return p['last-of-type'](p['first-of-type'](nodes,formula,root),formula,root);},getIndices:function(a,b,total){if(a==0)return b>0?[b]:[];return $R(1,total).inject([],function(memo,i){if(0==(i-b)%a&&(i-b)/a>=0)memo.push(i);return memo;});},nth:function(nodes,formula,root,reverse,ofType){if(nodes.length==0)return[];if(formula=='even')formula='2n+0';if(formula=='odd')formula='2n+1';var h=Selector.handlers,results=[],indexed=[],m;h.mark(nodes);for(var i=0,node;node=nodes[i];i++){if(!node.parentNode._counted){h.index(node.parentNode,reverse,ofType);indexed.push(node.parentNode);}}
if(formula.match(/^\d+$/)){formula=Number(formula);for(var i=0,node;node=nodes[i];i++)
if(node.nodeIndex==formula)results.push(node);}else if(m=formula.match(/^(-?\d*)?n(([+-])(\d+))?/)){if(m[1]=="-")m[1]=-1;var a=m[1]?Number(m[1]):1;var b=m[2]?Number(m[2]):0;var indices=Selector.pseudos.getIndices(a,b,nodes.length);for(var i=0,node,l=indices.length;node=nodes[i];i++){for(var j=0;j<l;j++)
if(node.nodeIndex==indices[j])results.push(node);}}
h.unmark(nodes);h.unmark(indexed);return results;},'empty':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++){if(node.tagName=='!'||(node.firstChild&&!node.innerHTML.match(/^\s*$/)))continue;results.push(node);}
return results;},'not':function(nodes,selector,root){var h=Selector.handlers,selectorType,m;var exclusions=new Selector(selector).findElements(root);h.mark(exclusions);for(var i=0,results=[],node;node=nodes[i];i++)
if(!node._counted)results.push(node);h.unmark(exclusions);return results;},'enabled':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(!node.disabled)results.push(node);return results;},'disabled':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(node.disabled)results.push(node);return results;},'checked':function(nodes,value,root){for(var i=0,results=[],node;node=nodes[i];i++)
if(node.checked)results.push(node);return results;}},operators:{'=':function(nv,v){return nv==v;},'!=':function(nv,v){return nv!=v;},'^=':function(nv,v){return nv.startsWith(v);},'$=':function(nv,v){return nv.endsWith(v);},'*=':function(nv,v){return nv.include(v);},'~=':function(nv,v){return(' '+nv+' ').include(' '+v+' ');},'|=':function(nv,v){return('-'+nv.toUpperCase()+'-').include('-'+v.toUpperCase()+'-');}},matchElements:function(elements,expression){var matches=new Selector(expression).findElements(),h=Selector.handlers;h.mark(matches);for(var i=0,results=[],element;element=elements[i];i++)
if(element._counted)results.push(element);h.unmark(matches);return results;},findElement:function(elements,expression,index){if(typeof expression=='number'){index=expression;expression=false;}
return Selector.matchElements(elements,expression||'*')[index||0];},findChildElements:function(element,expressions){var exprs=expressions.join(','),expressions=[];exprs.scan(/(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)/,function(m){expressions.push(m[1].strip());});var results=[],h=Selector.handlers;for(var i=0,l=expressions.length,selector;i<l;i++){selector=new Selector(expressions[i].strip());h.concat(results,selector.findElements(element));}
return(l>1)?h.unique(results):results;}});function $$(){return Selector.findChildElements(document,$A(arguments));}
var Form={reset:function(form){$(form).reset();return form;},serializeElements:function(elements,getHash){var data=elements.inject({},function(result,element){if(!element.disabled&&element.name){var key=element.name,value=$(element).getValue();if(value!=null){if(key in result){if(result[key].constructor!=Array)result[key]=[result[key]];result[key].push(value);}
else result[key]=value;}}
return result;});return getHash?data:Hash.toQueryString(data);}};Form.Methods={serialize:function(form,getHash){return Form.serializeElements(Form.getElements(form),getHash);},getElements:function(form){return $A($(form).getElementsByTagName('*')).inject([],function(elements,child){if(Form.Element.Serializers[child.tagName.toLowerCase()])
elements.push(Element.extend(child));return elements;});},getInputs:function(form,typeName,name){form=$(form);var inputs=form.getElementsByTagName('input');if(!typeName&&!name)return $A(inputs).map(Element.extend);for(var i=0,matchingInputs=[],length=inputs.length;i<length;i++){var input=inputs[i];if((typeName&&input.type!=typeName)||(name&&input.name!=name))
continue;matchingInputs.push(Element.extend(input));}
return matchingInputs;},disable:function(form){form=$(form);Form.getElements(form).invoke('disable');return form;},enable:function(form){form=$(form);Form.getElements(form).invoke('enable');return form;},findFirstElement:function(form){return $(form).getElements().find(function(element){return element.type!='hidden'&&!element.disabled&&['input','select','textarea'].include(element.tagName.toLowerCase());});},focusFirstElement:function(form){form=$(form);form.findFirstElement().activate();return form;},request:function(form,options){form=$(form),options=Object.clone(options||{});var params=options.parameters;options.parameters=form.serialize(true);if(params){if(typeof params=='string')params=params.toQueryParams();Object.extend(options.parameters,params);}
if(form.hasAttribute('method')&&!options.method)
options.method=form.method;return new Ajax.Request(form.readAttribute('action'),options);}}
Form.Element={focus:function(element){$(element).focus();return element;},select:function(element){$(element).select();return element;}}
Form.Element.Methods={serialize:function(element){element=$(element);if(!element.disabled&&element.name){var value=element.getValue();if(value!=undefined){var pair={};pair[element.name]=value;return Hash.toQueryString(pair);}}
return'';},getValue:function(element){element=$(element);var method=element.tagName.toLowerCase();return Form.Element.Serializers[method](element);},clear:function(element){$(element).value='';return element;},present:function(element){return $(element).value!='';},activate:function(element){element=$(element);try{element.focus();if(element.select&&(element.tagName.toLowerCase()!='input'||!['button','reset','submit'].include(element.type)))
element.select();}catch(e){}
return element;},disable:function(element){element=$(element);element.blur();element.disabled=true;return element;},enable:function(element){element=$(element);element.disabled=false;return element;}}
var Field=Form.Element;var $F=Form.Element.Methods.getValue;Form.Element.Serializers={input:function(element){switch(element.type.toLowerCase()){case'checkbox':case'radio':return Form.Element.Serializers.inputSelector(element);default:return Form.Element.Serializers.textarea(element);}},inputSelector:function(element){return element.checked?element.value:null;},textarea:function(element){return element.value;},select:function(element){return this[element.type=='select-one'?'selectOne':'selectMany'](element);},selectOne:function(element){var index=element.selectedIndex;return index>=0?this.optionValue(element.options[index]):null;},selectMany:function(element){var values,length=element.length;if(!length)return null;for(var i=0,values=[];i<length;i++){var opt=element.options[i];if(opt.selected)values.push(this.optionValue(opt));}
return values;},optionValue:function(opt){return Element.extend(opt).hasAttribute('value')?opt.value:opt.text;}}
Abstract.TimedObserver=function(){}
Abstract.TimedObserver.prototype={initialize:function(element,frequency,callback){this.frequency=frequency;this.element=$(element);this.callback=callback;this.lastValue=this.getValue();this.registerCallback();},registerCallback:function(){setInterval(this.onTimerEvent.bind(this),this.frequency*1000);},onTimerEvent:function(){var value=this.getValue();var changed=('string'==typeof this.lastValue&&'string'==typeof value?this.lastValue!=value:String(this.lastValue)!=String(value));if(changed){this.callback(this.element,value);this.lastValue=value;}}}
Form.Element.Observer=Class.create();Form.Element.Observer.prototype=Object.extend(new Abstract.TimedObserver(),{getValue:function(){return Form.Element.getValue(this.element);}});Form.Observer=Class.create();Form.Observer.prototype=Object.extend(new Abstract.TimedObserver(),{getValue:function(){return Form.serialize(this.element);}});Abstract.EventObserver=function(){}
Abstract.EventObserver.prototype={initialize:function(element,callback){this.element=$(element);this.callback=callback;this.lastValue=this.getValue();if(this.element.tagName.toLowerCase()=='form')
this.registerFormCallbacks();else
this.registerCallback(this.element);},onElementEvent:function(){var value=this.getValue();if(this.lastValue!=value){this.callback(this.element,value);this.lastValue=value;}},registerFormCallbacks:function(){Form.getElements(this.element).each(this.registerCallback.bind(this));},registerCallback:function(element){if(element.type){switch(element.type.toLowerCase()){case'checkbox':case'radio':Event.observe(element,'click',this.onElementEvent.bind(this));break;default:Event.observe(element,'change',this.onElementEvent.bind(this));break;}}}}
Form.Element.EventObserver=Class.create();Form.Element.EventObserver.prototype=Object.extend(new Abstract.EventObserver(),{getValue:function(){return Form.Element.getValue(this.element);}});Form.EventObserver=Class.create();Form.EventObserver.prototype=Object.extend(new Abstract.EventObserver(),{getValue:function(){return Form.serialize(this.element);}});if(!window.Event){var Event=new Object();}
Object.extend(Event,{KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,element:function(event){return $(event.target||event.srcElement);},isLeftClick:function(event){return(((event.which)&&(event.which==1))||((event.button)&&(event.button==1)));},pointerX:function(event){return event.pageX||(event.clientX+
(document.documentElement.scrollLeft||document.body.scrollLeft));},pointerY:function(event){return event.pageY||(event.clientY+
(document.documentElement.scrollTop||document.body.scrollTop));},stop:function(event){if(event.preventDefault){event.preventDefault();event.stopPropagation();}else{event.returnValue=false;event.cancelBubble=true;}},findElement:function(event,tagName){var element=Event.element(event);while(element.parentNode&&(!element.tagName||(element.tagName.toUpperCase()!=tagName.toUpperCase())))
element=element.parentNode;return element;},observers:false,_observeAndCache:function(element,name,observer,useCapture){if(!this.observers)this.observers=[];if(element.addEventListener){this.observers.push([element,name,observer,useCapture]);element.addEventListener(name,observer,useCapture);}else if(element.attachEvent){this.observers.push([element,name,observer,useCapture]);element.attachEvent('on'+name,observer);}},unloadCache:function(){if(!Event.observers)return;for(var i=0,length=Event.observers.length;i<length;i++){Event.stopObserving.apply(this,Event.observers[i]);Event.observers[i][0]=null;}
Event.observers=false;},observe:function(element,name,observer,useCapture){element=$(element);useCapture=useCapture||false;if(name=='keypress'&&(Prototype.Browser.WebKit||element.attachEvent))
name='keydown';Event._observeAndCache(element,name,observer,useCapture);},stopObserving:function(element,name,observer,useCapture){element=$(element);useCapture=useCapture||false;if(name=='keypress'&&(Prototype.Browser.WebKit||element.attachEvent))
name='keydown';if(element.removeEventListener){element.removeEventListener(name,observer,useCapture);}else if(element.detachEvent){try{element.detachEvent('on'+name,observer);}catch(e){}}}});if(Prototype.Browser.IE)
Event.observe(window,'unload',Event.unloadCache,false);var Position={includeScrollOffsets:false,prepare:function(){this.deltaX=window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0;this.deltaY=window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0;},realOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.scrollTop||0;valueL+=element.scrollLeft||0;element=element.parentNode;}while(element);return[valueL,valueT];},cumulativeOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;}while(element);return[valueL,valueT];},positionedOffset:function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;element=element.offsetParent;if(element){if(element.tagName=='BODY')break;var p=Element.getStyle(element,'position');if(p=='relative'||p=='absolute')break;}}while(element);return[valueL,valueT];},offsetParent:function(element){if(element.offsetParent)return element.offsetParent;if(element==document.body)return element;while((element=element.parentNode)&&element!=document.body)
if(Element.getStyle(element,'position')!='static')
return element;return document.body;},within:function(element,x,y){if(this.includeScrollOffsets)
return this.withinIncludingScrolloffsets(element,x,y);this.xcomp=x;this.ycomp=y;this.offset=this.cumulativeOffset(element);return(y>=this.offset[1]&&y<this.offset[1]+element.offsetHeight&&x>=this.offset[0]&&x<this.offset[0]+element.offsetWidth);},withinIncludingScrolloffsets:function(element,x,y){var offsetcache=this.realOffset(element);this.xcomp=x+offsetcache[0]-this.deltaX;this.ycomp=y+offsetcache[1]-this.deltaY;this.offset=this.cumulativeOffset(element);return(this.ycomp>=this.offset[1]&&this.ycomp<this.offset[1]+element.offsetHeight&&this.xcomp>=this.offset[0]&&this.xcomp<this.offset[0]+element.offsetWidth);},overlap:function(mode,element){if(!mode)return 0;if(mode=='vertical')
return((this.offset[1]+element.offsetHeight)-this.ycomp)/element.offsetHeight;if(mode=='horizontal')
return((this.offset[0]+element.offsetWidth)-this.xcomp)/element.offsetWidth;},page:function(forElement){var valueT=0,valueL=0;var element=forElement;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body)
if(Element.getStyle(element,'position')=='absolute')break;}while(element=element.offsetParent);element=forElement;do{if(!window.opera||element.tagName=='BODY'){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;}}while(element=element.parentNode);return[valueL,valueT];},clone:function(source,target){var options=Object.extend({setLeft:true,setTop:true,setWidth:true,setHeight:true,offsetTop:0,offsetLeft:0},arguments[2]||{})
source=$(source);var p=Position.page(source);target=$(target);var delta=[0,0];var parent=null;if(Element.getStyle(target,'position')=='absolute'){parent=Position.offsetParent(target);delta=Position.page(parent);}
if(parent==document.body){delta[0]-=document.body.offsetLeft;delta[1]-=document.body.offsetTop;}
if(options.setLeft)target.style.left=(p[0]-delta[0]+options.offsetLeft)+'px';if(options.setTop)target.style.top=(p[1]-delta[1]+options.offsetTop)+'px';if(options.setWidth)target.style.width=source.offsetWidth+'px';if(options.setHeight)target.style.height=source.offsetHeight+'px';},absolutize:function(element){element=$(element);if(element.style.position=='absolute')return;Position.prepare();var offsets=Position.positionedOffset(element);var top=offsets[1];var left=offsets[0];var width=element.clientWidth;var height=element.clientHeight;element._originalLeft=left-parseFloat(element.style.left||0);element._originalTop=top-parseFloat(element.style.top||0);element._originalWidth=element.style.width;element._originalHeight=element.style.height;element.style.position='absolute';element.style.top=top+'px';element.style.left=left+'px';element.style.width=width+'px';element.style.height=height+'px';},relativize:function(element){element=$(element);if(element.style.position=='relative')return;Position.prepare();element.style.position='relative';var top=parseFloat(element.style.top||0)-(element._originalTop||0);var left=parseFloat(element.style.left||0)-(element._originalLeft||0);element.style.top=top+'px';element.style.left=left+'px';element.style.height=element._originalHeight;element.style.width=element._originalWidth;}}
if(Prototype.Browser.WebKit){Position.cumulativeOffset=function(element){var valueT=0,valueL=0;do{valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;if(element.offsetParent==document.body)
if(Element.getStyle(element,'position')=='absolute')break;element=element.offsetParent;}while(element);return[valueL,valueT];}}
Element.addMethods();String.prototype.parseColor=function(){var color='#';if(this.slice(0,4)=='rgb('){var cols=this.slice(4,this.length-1).split(',');var i=0;do{color+=parseInt(cols[i]).toColorPart()}while(++i<3);}else{if(this.slice(0,1)=='#'){if(this.length==4)for(var i=1;i<4;i++)color+=(this.charAt(i)+this.charAt(i)).toLowerCase();if(this.length==7)color=this.toLowerCase();}}
return(color.length==7?color:(arguments[0]||this));}
Element.collectTextNodes=function(element){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:(node.hasChildNodes()?Element.collectTextNodes(node):''));}).flatten().join('');}
Element.collectTextNodesIgnoreClass=function(element,className){return $A($(element).childNodes).collect(function(node){return(node.nodeType==3?node.nodeValue:((node.hasChildNodes()&&!Element.hasClassName(node,className))?Element.collectTextNodesIgnoreClass(node,className):''));}).flatten().join('');}
Element.setContentZoom=function(element,percent){element=$(element);element.setStyle({fontSize:(percent/100)+'em'});if(Prototype.Browser.WebKit)window.scrollBy(0,0);return element;}
Element.getInlineOpacity=function(element){return $(element).style.opacity||'';}
Element.forceRerendering=function(element){try{element=$(element);var n=document.createTextNode(' ');element.appendChild(n);element.removeChild(n);}catch(e){}};Array.prototype.call=function(){var args=arguments;this.each(function(f){f.apply(this,args)});}
var Effect={_elementDoesNotExistError:{name:'ElementDoesNotExistError',message:'The specified DOM element does not exist, but is required for this effect to operate'},tagifyText:function(element){if(typeof Builder=='undefined')
throw("Effect.tagifyText requires including script.aculo.us' builder.js library");var tagifyStyle='position:relative';if(Prototype.Browser.IE)tagifyStyle+=';zoom:1';element=$(element);$A(element.childNodes).each(function(child){if(child.nodeType==3){child.nodeValue.toArray().each(function(character){element.insertBefore(Builder.node('span',{style:tagifyStyle},character==' '?String.fromCharCode(160):character),child);});Element.remove(child);}});},multiple:function(element,effect){var elements;if(((typeof element=='object')||(typeof element=='function'))&&(element.length))
elements=element;else
elements=$(element).childNodes;var options=Object.extend({speed:0.1,delay:0.0},arguments[2]||{});var masterDelay=options.delay;$A(elements).each(function(element,index){new effect(element,Object.extend(options,{delay:index*options.speed+masterDelay}));});},PAIRS:{'slide':['SlideDown','SlideUp'],'blind':['BlindDown','BlindUp'],'appear':['Appear','Fade']},toggle:function(element,effect){element=$(element);effect=(effect||'appear').toLowerCase();var options=Object.extend({queue:{position:'end',scope:(element.id||'global'),limit:1}},arguments[2]||{});Effect[element.visible()?Effect.PAIRS[effect][1]:Effect.PAIRS[effect][0]](element,options);}};var Effect2=Effect;Effect.Transitions={linear:Prototype.K,sinoidal:function(pos){return(-Math.cos(pos*Math.PI)/2)+0.5;},reverse:function(pos){return 1-pos;},flicker:function(pos){var pos=((-Math.cos(pos*Math.PI)/4)+0.75)+Math.random()/4;return(pos>1?1:pos);},wobble:function(pos){return(-Math.cos(pos*Math.PI*(9*pos))/2)+0.5;},pulse:function(pos,pulses){pulses=pulses||5;return(Math.round((pos%(1/pulses))*pulses)==0?((pos*pulses*2)-Math.floor(pos*pulses*2)):1-((pos*pulses*2)-Math.floor(pos*pulses*2)));},none:function(pos){return 0;},full:function(pos){return 1;}};Effect.ScopedQueue=Class.create();Object.extend(Object.extend(Effect.ScopedQueue.prototype,Enumerable),{initialize:function(){this.effects=[];this.interval=null;},_each:function(iterator){this.effects._each(iterator);},add:function(effect){var timestamp=new Date().getTime();var position=(typeof effect.options.queue=='string')?effect.options.queue:effect.options.queue.position;switch(position){case'front':this.effects.findAll(function(e){return e.state=='idle'}).each(function(e){e.startOn+=effect.finishOn;e.finishOn+=effect.finishOn;});break;case'with-last':timestamp=this.effects.pluck('startOn').max()||timestamp;break;case'end':timestamp=this.effects.pluck('finishOn').max()||timestamp;break;}
effect.startOn+=timestamp;effect.finishOn+=timestamp;if(!effect.options.queue.limit||(this.effects.length<effect.options.queue.limit))
this.effects.push(effect);if(!this.interval)
this.interval=setInterval(this.loop.bind(this),15);},remove:function(effect){this.effects=this.effects.reject(function(e){return e==effect});if(this.effects.length==0){clearInterval(this.interval);this.interval=null;}},loop:function(){var timePos=new Date().getTime();for(var i=0,len=this.effects.length;i<len;i++)
this.effects[i]&&this.effects[i].loop(timePos);}});Effect.Queues={instances:$H(),get:function(queueName){if(typeof queueName!='string')return queueName;if(!this.instances[queueName])
this.instances[queueName]=new Effect.ScopedQueue();return this.instances[queueName];}}
Effect.Queue=Effect.Queues.get('global');Effect.DefaultOptions={transition:Effect.Transitions.sinoidal,duration:1.0,fps:100,sync:false,from:0.0,to:1.0,delay:0.0,queue:'parallel'}
Effect.Base=function(){};Effect.Base.prototype={position:null,start:function(options){function codeForEvent(options,eventName){return((options[eventName+'Internal']?'this.options.'+eventName+'Internal(this);':'')+
(options[eventName]?'this.options.'+eventName+'(this);':''));}
if(options.transition===false)options.transition=Effect.Transitions.linear;this.options=Object.extend(Object.extend({},Effect.DefaultOptions),options||{});this.currentFrame=0;this.state='idle';this.startOn=this.options.delay*1000;this.finishOn=this.startOn+(this.options.duration*1000);this.fromToDelta=this.options.to-this.options.from;this.totalTime=this.finishOn-this.startOn;this.totalFrames=this.options.fps*this.options.duration;eval('this.render = function(pos){ '+'if(this.state=="idle"){this.state="running";'+
codeForEvent(options,'beforeSetup')+
(this.setup?'this.setup();':'')+
codeForEvent(options,'afterSetup')+'};if(this.state=="running"){'+'pos=this.options.transition(pos)*'+this.fromToDelta+'+'+this.options.from+';'+'this.position=pos;'+
codeForEvent(options,'beforeUpdate')+
(this.update?'this.update(pos);':'')+
codeForEvent(options,'afterUpdate')+'}}');this.event('beforeStart');if(!this.options.sync)
Effect.Queues.get(typeof this.options.queue=='string'?'global':this.options.queue.scope).add(this);},loop:function(timePos){if(timePos>=this.startOn){if(timePos>=this.finishOn){this.render(1.0);this.cancel();this.event('beforeFinish');if(this.finish)this.finish();this.event('afterFinish');return;}
var pos=(timePos-this.startOn)/this.totalTime,frame=Math.round(pos*this.totalFrames);if(frame>this.currentFrame){this.render(pos);this.currentFrame=frame;}}},cancel:function(){if(!this.options.sync)
Effect.Queues.get(typeof this.options.queue=='string'?'global':this.options.queue.scope).remove(this);this.state='finished';},event:function(eventName){if(this.options[eventName+'Internal'])this.options[eventName+'Internal'](this);if(this.options[eventName])this.options[eventName](this);},inspect:function(){var data=$H();for(property in this)
if(typeof this[property]!='function')data[property]=this[property];return'#<Effect:'+data.inspect()+',options:'+$H(this.options).inspect()+'>';}}
Effect.Parallel=Class.create();Object.extend(Object.extend(Effect.Parallel.prototype,Effect.Base.prototype),{initialize:function(effects){this.effects=effects||[];this.start(arguments[1]);},update:function(position){this.effects.invoke('render',position);},finish:function(position){this.effects.each(function(effect){effect.render(1.0);effect.cancel();effect.event('beforeFinish');if(effect.finish)effect.finish(position);effect.event('afterFinish');});}});Effect.Event=Class.create();Object.extend(Object.extend(Effect.Event.prototype,Effect.Base.prototype),{initialize:function(){var options=Object.extend({duration:0},arguments[0]||{});this.start(options);},update:Prototype.emptyFunction});Effect.Opacity=Class.create();Object.extend(Object.extend(Effect.Opacity.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});var options=Object.extend({from:this.element.getOpacity()||0.0,to:1.0},arguments[1]||{});this.start(options);},update:function(position){this.element.setOpacity(position);}});Effect.Move=Class.create();Object.extend(Object.extend(Effect.Move.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({x:0,y:0,mode:'relative'},arguments[1]||{});this.start(options);},setup:function(){this.element.makePositioned();this.originalLeft=parseFloat(this.element.getStyle('left')||'0');this.originalTop=parseFloat(this.element.getStyle('top')||'0');if(this.options.mode=='absolute'){this.options.x=this.options.x-this.originalLeft;this.options.y=this.options.y-this.originalTop;}},update:function(position){this.element.setStyle({left:Math.round(this.options.x*position+this.originalLeft)+'px',top:Math.round(this.options.y*position+this.originalTop)+'px'});}});Effect.MoveBy=function(element,toTop,toLeft){return new Effect.Move(element,Object.extend({x:toLeft,y:toTop},arguments[3]||{}));};Effect.Scale=Class.create();Object.extend(Object.extend(Effect.Scale.prototype,Effect.Base.prototype),{initialize:function(element,percent){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({scaleX:true,scaleY:true,scaleContent:true,scaleFromCenter:false,scaleMode:'box',scaleFrom:100.0,scaleTo:percent},arguments[2]||{});this.start(options);},setup:function(){this.restoreAfterFinish=this.options.restoreAfterFinish||false;this.elementPositioning=this.element.getStyle('position');this.originalStyle={};['top','left','width','height','fontSize'].each(function(k){this.originalStyle[k]=this.element.style[k];}.bind(this));this.originalTop=this.element.offsetTop;this.originalLeft=this.element.offsetLeft;var fontSize=this.element.getStyle('font-size')||'100%';['em','px','%','pt'].each(function(fontSizeType){if(fontSize.indexOf(fontSizeType)>0){this.fontSize=parseFloat(fontSize);this.fontSizeType=fontSizeType;}}.bind(this));this.factor=(this.options.scaleTo-this.options.scaleFrom)/100;this.dims=null;if(this.options.scaleMode=='box')
this.dims=[this.element.offsetHeight,this.element.offsetWidth];if(/^content/.test(this.options.scaleMode))
this.dims=[this.element.scrollHeight,this.element.scrollWidth];if(!this.dims)
this.dims=[this.options.scaleMode.originalHeight,this.options.scaleMode.originalWidth];},update:function(position){var currentScale=(this.options.scaleFrom/100.0)+(this.factor*position);if(this.options.scaleContent&&this.fontSize)
this.element.setStyle({fontSize:this.fontSize*currentScale+this.fontSizeType});this.setDimensions(this.dims[0]*currentScale,this.dims[1]*currentScale);},finish:function(position){if(this.restoreAfterFinish)this.element.setStyle(this.originalStyle);},setDimensions:function(height,width){var d={};if(this.options.scaleX)d.width=Math.round(width)+'px';if(this.options.scaleY)d.height=Math.round(height)+'px';if(this.options.scaleFromCenter){var topd=(height-this.dims[0])/2;var leftd=(width-this.dims[1])/2;if(this.elementPositioning=='absolute'){if(this.options.scaleY)d.top=this.originalTop-topd+'px';if(this.options.scaleX)d.left=this.originalLeft-leftd+'px';}else{if(this.options.scaleY)d.top=-topd+'px';if(this.options.scaleX)d.left=-leftd+'px';}}
this.element.setStyle(d);}});Effect.Highlight=Class.create();Object.extend(Object.extend(Effect.Highlight.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({startcolor:'#ffff99'},arguments[1]||{});this.start(options);},setup:function(){if(this.element.getStyle('display')=='none'){this.cancel();return;}
this.oldStyle={};if(!this.options.keepBackgroundImage){this.oldStyle.backgroundImage=this.element.getStyle('background-image');this.element.setStyle({backgroundImage:'none'});}
if(!this.options.endcolor)
this.options.endcolor=this.element.getStyle('background-color').parseColor('#ffffff');if(!this.options.restorecolor)
this.options.restorecolor=this.element.getStyle('background-color');this._base=$R(0,2).map(function(i){return parseInt(this.options.startcolor.slice(i*2+1,i*2+3),16)}.bind(this));this._delta=$R(0,2).map(function(i){return parseInt(this.options.endcolor.slice(i*2+1,i*2+3),16)-this._base[i]}.bind(this));},update:function(position){this.element.setStyle({backgroundColor:$R(0,2).inject('#',function(m,v,i){return m+(Math.round(this._base[i]+(this._delta[i]*position)).toColorPart());}.bind(this))});},finish:function(){this.element.setStyle(Object.extend(this.oldStyle,{backgroundColor:this.options.restorecolor}));}});Effect.ScrollTo=Class.create();Object.extend(Object.extend(Effect.ScrollTo.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);this.start(arguments[1]||{});},setup:function(){Position.prepare();var offsets=Position.cumulativeOffset(this.element);if(this.options.offset)offsets[1]+=this.options.offset;var max=window.innerHeight?window.height-window.innerHeight:document.body.scrollHeight-
(document.documentElement.clientHeight?document.documentElement.clientHeight:document.body.clientHeight);this.scrollStart=Position.deltaY;this.delta=(offsets[1]>max?max:offsets[1])-this.scrollStart;},update:function(position){Position.prepare();window.scrollTo(Position.deltaX,this.scrollStart+(position*this.delta));}});Effect.Fade=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();var options=Object.extend({from:element.getOpacity()||1.0,to:0.0,afterFinishInternal:function(effect){if(effect.options.to!=0)return;effect.element.hide().setStyle({opacity:oldOpacity});}},arguments[1]||{});return new Effect.Opacity(element,options);}
Effect.Appear=function(element){element=$(element);var options=Object.extend({from:(element.getStyle('display')=='none'?0.0:element.getOpacity()||0.0),to:1.0,afterFinishInternal:function(effect){effect.element.forceRerendering();},beforeSetup:function(effect){effect.element.setOpacity(effect.options.from).show();}},arguments[1]||{});return new Effect.Opacity(element,options);}
Effect.Puff=function(element){element=$(element);var oldStyle={opacity:element.getInlineOpacity(),position:element.getStyle('position'),top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};return new Effect.Parallel([new Effect.Scale(element,200,{sync:true,scaleFromCenter:true,scaleContent:true,restoreAfterFinish:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:1.0,beforeSetupInternal:function(effect){Position.absolutize(effect.effects[0].element)},afterFinishInternal:function(effect){effect.effects[0].element.hide().setStyle(oldStyle);}},arguments[1]||{}));}
Effect.BlindUp=function(element){element=$(element);element.makeClipping();return new Effect.Scale(element,0,Object.extend({scaleContent:false,scaleX:false,restoreAfterFinish:true,afterFinishInternal:function(effect){effect.element.hide().undoClipping();}},arguments[1]||{}));}
Effect.BlindDown=function(element){element=$(element);var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:0,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makeClipping().setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.element.undoClipping();}},arguments[1]||{}));}
Effect.SwitchOff=function(element){element=$(element);var oldOpacity=element.getInlineOpacity();return new Effect.Appear(element,Object.extend({duration:0.4,from:0,transition:Effect.Transitions.flicker,afterFinishInternal:function(effect){new Effect.Scale(effect.element,1,{duration:0.3,scaleFromCenter:true,scaleX:false,scaleContent:false,restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned().setStyle({opacity:oldOpacity});}})}},arguments[1]||{}));}
Effect.DropOut=function(element){element=$(element);var oldStyle={top:element.getStyle('top'),left:element.getStyle('left'),opacity:element.getInlineOpacity()};return new Effect.Parallel([new Effect.Move(element,{x:0,y:100,sync:true}),new Effect.Opacity(element,{sync:true,to:0.0})],Object.extend({duration:0.5,beforeSetup:function(effect){effect.effects[0].element.makePositioned();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoPositioned().setStyle(oldStyle);}},arguments[1]||{}));}
Effect.Shake=function(element){element=$(element);var oldStyle={top:element.getStyle('top'),left:element.getStyle('left')};return new Effect.Move(element,{x:20,y:0,duration:0.05,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-40,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:40,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-40,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:40,y:0,duration:0.1,afterFinishInternal:function(effect){new Effect.Move(effect.element,{x:-20,y:0,duration:0.05,afterFinishInternal:function(effect){effect.element.undoPositioned().setStyle(oldStyle);}})}})}})}})}})}});}
Effect.SlideDown=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');var elementDimensions=element.getDimensions();return new Effect.Scale(element,100,Object.extend({scaleContent:false,scaleX:false,scaleFrom:window.opera?0:1,scaleMode:{originalHeight:elementDimensions.height,originalWidth:elementDimensions.width},restoreAfterFinish:true,afterSetup:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().setStyle({height:'0px'}).show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.undoClipping().undoPositioned();effect.element.down().undoPositioned().setStyle({bottom:oldInnerBottom});}},arguments[1]||{}));}
Effect.SlideUp=function(element){element=$(element).cleanWhitespace();var oldInnerBottom=element.down().getStyle('bottom');return new Effect.Scale(element,window.opera?0:1,Object.extend({scaleContent:false,scaleX:false,scaleMode:'box',scaleFrom:100,restoreAfterFinish:true,beforeStartInternal:function(effect){effect.element.makePositioned();effect.element.down().makePositioned();if(window.opera)effect.element.setStyle({top:''});effect.element.makeClipping().show();},afterUpdateInternal:function(effect){effect.element.down().setStyle({bottom:(effect.dims[0]-effect.element.clientHeight)+'px'});},afterFinishInternal:function(effect){effect.element.hide().undoClipping().undoPositioned().setStyle({bottom:oldInnerBottom});effect.element.down().undoPositioned();}},arguments[1]||{}));}
Effect.Squish=function(element){return new Effect.Scale(element,window.opera?1:0,{restoreAfterFinish:true,beforeSetup:function(effect){effect.element.makeClipping();},afterFinishInternal:function(effect){effect.element.hide().undoClipping();}});}
Effect.Grow=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.full},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var initialMoveX,initialMoveY;var moveX,moveY;switch(options.direction){case'top-left':initialMoveX=initialMoveY=moveX=moveY=0;break;case'top-right':initialMoveX=dims.width;initialMoveY=moveY=0;moveX=-dims.width;break;case'bottom-left':initialMoveX=moveX=0;initialMoveY=dims.height;moveY=-dims.height;break;case'bottom-right':initialMoveX=dims.width;initialMoveY=dims.height;moveX=-dims.width;moveY=-dims.height;break;case'center':initialMoveX=dims.width/2;initialMoveY=dims.height/2;moveX=-dims.width/2;moveY=-dims.height/2;break;}
return new Effect.Move(element,{x:initialMoveX,y:initialMoveY,duration:0.01,beforeSetup:function(effect){effect.element.hide().makeClipping().makePositioned();},afterFinishInternal:function(effect){new Effect.Parallel([new Effect.Opacity(effect.element,{sync:true,to:1.0,from:0.0,transition:options.opacityTransition}),new Effect.Move(effect.element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition}),new Effect.Scale(effect.element,100,{scaleMode:{originalHeight:dims.height,originalWidth:dims.width},sync:true,scaleFrom:window.opera?1:0,transition:options.scaleTransition,restoreAfterFinish:true})],Object.extend({beforeSetup:function(effect){effect.effects[0].element.setStyle({height:'0px'}).show();},afterFinishInternal:function(effect){effect.effects[0].element.undoClipping().undoPositioned().setStyle(oldStyle);}},options))}});}
Effect.Shrink=function(element){element=$(element);var options=Object.extend({direction:'center',moveTransition:Effect.Transitions.sinoidal,scaleTransition:Effect.Transitions.sinoidal,opacityTransition:Effect.Transitions.none},arguments[1]||{});var oldStyle={top:element.style.top,left:element.style.left,height:element.style.height,width:element.style.width,opacity:element.getInlineOpacity()};var dims=element.getDimensions();var moveX,moveY;switch(options.direction){case'top-left':moveX=moveY=0;break;case'top-right':moveX=dims.width;moveY=0;break;case'bottom-left':moveX=0;moveY=dims.height;break;case'bottom-right':moveX=dims.width;moveY=dims.height;break;case'center':moveX=dims.width/2;moveY=dims.height/2;break;}
return new Effect.Parallel([new Effect.Opacity(element,{sync:true,to:0.0,from:1.0,transition:options.opacityTransition}),new Effect.Scale(element,window.opera?1:0,{sync:true,transition:options.scaleTransition,restoreAfterFinish:true}),new Effect.Move(element,{x:moveX,y:moveY,sync:true,transition:options.moveTransition})],Object.extend({beforeStartInternal:function(effect){effect.effects[0].element.makePositioned().makeClipping();},afterFinishInternal:function(effect){effect.effects[0].element.hide().undoClipping().undoPositioned().setStyle(oldStyle);}},options));}
Effect.Pulsate=function(element){element=$(element);var options=arguments[1]||{};var oldOpacity=element.getInlineOpacity();var transition=options.transition||Effect.Transitions.sinoidal;var reverser=function(pos){return transition(1-Effect.Transitions.pulse(pos,options.pulses))};reverser.bind(transition);return new Effect.Opacity(element,Object.extend(Object.extend({duration:2.0,from:0,afterFinishInternal:function(effect){effect.element.setStyle({opacity:oldOpacity});}},options),{transition:reverser}));}
Effect.Fold=function(element){element=$(element);var oldStyle={top:element.style.top,left:element.style.left,width:element.style.width,height:element.style.height};element.makeClipping();return new Effect.Scale(element,5,Object.extend({scaleContent:false,scaleX:false,afterFinishInternal:function(effect){new Effect.Scale(element,1,{scaleContent:false,scaleY:false,afterFinishInternal:function(effect){effect.element.hide().undoClipping().setStyle(oldStyle);}});}},arguments[1]||{}));};Effect.Morph=Class.create();Object.extend(Object.extend(Effect.Morph.prototype,Effect.Base.prototype),{initialize:function(element){this.element=$(element);if(!this.element)throw(Effect._elementDoesNotExistError);var options=Object.extend({style:{}},arguments[1]||{});if(typeof options.style=='string'){if(options.style.indexOf(':')==-1){var cssText='',selector='.'+options.style;$A(document.styleSheets).reverse().each(function(styleSheet){if(styleSheet.cssRules)cssRules=styleSheet.cssRules;else if(styleSheet.rules)cssRules=styleSheet.rules;$A(cssRules).reverse().each(function(rule){if(selector==rule.selectorText){cssText=rule.style.cssText;throw $break;}});if(cssText)throw $break;});this.style=cssText.parseStyle();options.afterFinishInternal=function(effect){effect.element.addClassName(effect.options.style);effect.transforms.each(function(transform){if(transform.style!='opacity')
effect.element.style[transform.style]='';});}}else this.style=options.style.parseStyle();}else this.style=$H(options.style)
this.start(options);},setup:function(){function parseColor(color){if(!color||['rgba(0, 0, 0, 0)','transparent'].include(color))color='#ffffff';color=color.parseColor();return $R(0,2).map(function(i){return parseInt(color.slice(i*2+1,i*2+3),16)});}
this.transforms=this.style.map(function(pair){var property=pair[0],value=pair[1],unit=null;if(value.parseColor('#zzzzzz')!='#zzzzzz'){value=value.parseColor();unit='color';}else if(property=='opacity'){value=parseFloat(value);if(Prototype.Browser.IE&&(!this.element.currentStyle.hasLayout))
this.element.setStyle({zoom:1});}else if(Element.CSS_LENGTH.test(value)){var components=value.match(/^([\+\-]?[0-9\.]+)(.*)$/);value=parseFloat(components[1]);unit=(components.length==3)?components[2]:null;}
var originalValue=this.element.getStyle(property);return{style:property.camelize(),originalValue:unit=='color'?parseColor(originalValue):parseFloat(originalValue||0),targetValue:unit=='color'?parseColor(value):value,unit:unit};}.bind(this)).reject(function(transform){return((transform.originalValue==transform.targetValue)||(transform.unit!='color'&&(isNaN(transform.originalValue)||isNaN(transform.targetValue))))});},update:function(position){var style={},transform,i=this.transforms.length;while(i--)
style[(transform=this.transforms[i]).style]=transform.unit=='color'?'#'+
(Math.round(transform.originalValue[0]+
(transform.targetValue[0]-transform.originalValue[0])*position)).toColorPart()+
(Math.round(transform.originalValue[1]+
(transform.targetValue[1]-transform.originalValue[1])*position)).toColorPart()+
(Math.round(transform.originalValue[2]+
(transform.targetValue[2]-transform.originalValue[2])*position)).toColorPart():transform.originalValue+Math.round(((transform.targetValue-transform.originalValue)*position)*1000)/1000+transform.unit;this.element.setStyle(style,true);}});Effect.Transform=Class.create();Object.extend(Effect.Transform.prototype,{initialize:function(tracks){this.tracks=[];this.options=arguments[1]||{};this.addTracks(tracks);},addTracks:function(tracks){tracks.each(function(track){var data=$H(track).values().first();this.tracks.push($H({ids:$H(track).keys().first(),effect:Effect.Morph,options:{style:data}}));}.bind(this));return this;},play:function(){return new Effect.Parallel(this.tracks.map(function(track){var elements=[$(track.ids)||$$(track.ids)].flatten();return elements.map(function(e){return new track.effect(e,Object.extend({sync:true},track.options))});}).flatten(),this.options);}});Element.CSS_PROPERTIES=$w('backgroundColor backgroundPosition borderBottomColor borderBottomStyle '+'borderBottomWidth borderLeftColor borderLeftStyle borderLeftWidth '+'borderRightColor borderRightStyle borderRightWidth borderSpacing '+'borderTopColor borderTopStyle borderTopWidth bottom clip color '+'fontSize fontWeight height left letterSpacing lineHeight '+'marginBottom marginLeft marginRight marginTop markerOffset maxHeight '+'maxWidth minHeight minWidth opacity outlineColor outlineOffset '+'outlineWidth paddingBottom paddingLeft paddingRight paddingTop '+'right textIndent top width wordSpacing zIndex');Element.CSS_LENGTH=/^(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0$/;String.prototype.parseStyle=function(){var element=document.createElement('div');element.innerHTML='<div style="'+this+'"></div>';var style=element.childNodes[0].style,styleRules=$H();Element.CSS_PROPERTIES.each(function(property){if(style[property])styleRules[property]=style[property];});if(Prototype.Browser.IE&&this.indexOf('opacity')>-1){styleRules.opacity=this.match(/opacity:\s*((?:0|1)?(?:\.\d*)?)/)[1];}
return styleRules;};Element.morph=function(element,style){new Effect.Morph(element,Object.extend({style:style},arguments[2]||{}));return element;};['getInlineOpacity','forceRerendering','setContentZoom','collectTextNodes','collectTextNodesIgnoreClass','morph'].each(function(f){Element.Methods[f]=Element[f];});Element.Methods.visualEffect=function(element,effect,options){s=effect.dasherize().camelize();effect_class=s.charAt(0).toUpperCase()+s.substring(1);new Effect[effect_class](element,options);return $(element);};Element.addMethods();if(typeof Effect=='undefined')
throw("controls.js requires including script.aculo.us' effects.js library");var Autocompleter={}
Autocompleter.Base=function(){};Autocompleter.Base.prototype={baseInitialize:function(element,update,options){element=$(element)
this.element=element;this.update=$(update);this.hasFocus=false;this.changed=false;this.active=false;this.index=0;this.entryCount=0;if(this.setOptions)
this.setOptions(options);else
this.options=options||{};this.options.paramName=this.options.paramName||this.element.name;this.options.tokens=this.options.tokens||[];this.options.frequency=this.options.frequency||0.4;this.options.minChars=this.options.minChars||1;this.options.onShow=this.options.onShow||function(element,update){if(!update.style.position||update.style.position=='absolute'){update.style.position='absolute';Position.clone(element,update,{setHeight:false,offsetTop:element.offsetHeight});}
Effect.Appear(update,{duration:0.15});};this.options.onHide=this.options.onHide||function(element,update){new Effect.Fade(update,{duration:0.15})};if(typeof(this.options.tokens)=='string')
this.options.tokens=new Array(this.options.tokens);this.observer=null;this.element.setAttribute('autocomplete','off');Element.hide(this.update);Event.observe(this.element,'blur',this.onBlur.bindAsEventListener(this));Event.observe(this.element,'keypress',this.onKeyPress.bindAsEventListener(this));Event.observe(window,'beforeunload',function(){element.setAttribute('autocomplete','on');});},show:function(){if(Element.getStyle(this.update,'display')=='none')this.options.onShow(this.element,this.update);if(!this.iefix&&(Prototype.Browser.IE)&&(Element.getStyle(this.update,'position')=='absolute')){new Insertion.After(this.update,'<iframe id="'+this.update.id+'_iefix" '+'style="display:none;position:absolute;filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0);" '+'src="javascript:false;" frameborder="0" scrolling="no"></iframe>');this.iefix=$(this.update.id+'_iefix');}
if(this.iefix)setTimeout(this.fixIEOverlapping.bind(this),50);},fixIEOverlapping:function(){Position.clone(this.update,this.iefix,{setTop:(!this.update.style.height)});this.iefix.style.zIndex=1;this.update.style.zIndex=2;Element.show(this.iefix);},hide:function(){this.stopIndicator();if(Element.getStyle(this.update,'display')!='none')this.options.onHide(this.element,this.update);if(this.iefix)Element.hide(this.iefix);},startIndicator:function(){if(this.options.indicator)Element.show(this.options.indicator);},stopIndicator:function(){if(this.options.indicator)Element.hide(this.options.indicator);},onKeyPress:function(event){if(this.active)
switch(event.keyCode){case Event.KEY_TAB:case Event.KEY_RETURN:this.selectEntry();Event.stop(event);case Event.KEY_ESC:this.hide();this.active=false;Event.stop(event);return;case Event.KEY_LEFT:case Event.KEY_RIGHT:return;case Event.KEY_UP:this.markPrevious();this.render();if(Prototype.Browser.WebKit)Event.stop(event);return;case Event.KEY_DOWN:this.markNext();this.render();if(Prototype.Browser.WebKit)Event.stop(event);return;}
else
if(event.keyCode==Event.KEY_TAB||event.keyCode==Event.KEY_RETURN||(Prototype.Browser.WebKit>0&&event.keyCode==0))return;this.changed=true;this.hasFocus=true;if(this.observer)clearTimeout(this.observer);this.observer=setTimeout(this.onObserverEvent.bind(this),this.options.frequency*1000);},activate:function(){this.changed=false;this.hasFocus=true;this.getUpdatedChoices();},onHover:function(event){var element=Event.findElement(event,'LI');if(this.index!=element.autocompleteIndex)
{this.index=element.autocompleteIndex;this.render();}
Event.stop(event);},onClick:function(event){var element=Event.findElement(event,'LI');this.index=element.autocompleteIndex;this.selectEntry();this.hide();},onBlur:function(event){setTimeout(this.hide.bind(this),250);this.hasFocus=false;this.active=false;},render:function(){if(this.entryCount>0){for(var i=0;i<this.entryCount;i++)
this.index==i?Element.addClassName(this.getEntry(i),"selected"):Element.removeClassName(this.getEntry(i),"selected");if(this.hasFocus){this.show();this.active=true;}}else{this.active=false;this.hide();}},markPrevious:function(){if(this.index>0)this.index--
else this.index=this.entryCount-1;this.getEntry(this.index).scrollIntoView(true);},markNext:function(){if(this.index<this.entryCount-1)this.index++
else this.index=0;this.getEntry(this.index).scrollIntoView(false);},getEntry:function(index){return this.update.firstChild.childNodes[index];},getCurrentEntry:function(){return this.getEntry(this.index);},selectEntry:function(){this.active=false;this.updateElement(this.getCurrentEntry());},updateElement:function(selectedElement){if(this.options.updateElement){this.options.updateElement(selectedElement);return;}
var value='';if(this.options.select){var nodes=document.getElementsByClassName(this.options.select,selectedElement)||[];if(nodes.length>0)value=Element.collectTextNodes(nodes[0],this.options.select);}else
value=Element.collectTextNodesIgnoreClass(selectedElement,'informal');var lastTokenPos=this.findLastToken();if(lastTokenPos!=-1){var newValue=this.element.value.substr(0,lastTokenPos+1);var whitespace=this.element.value.substr(lastTokenPos+1).match(/^\s+/);if(whitespace)
newValue+=whitespace[0];this.element.value=newValue+value;}else{this.element.value=value;}
this.element.focus();if(this.options.afterUpdateElement)
this.options.afterUpdateElement(this.element,selectedElement);},updateChoices:function(choices){if(!this.changed&&this.hasFocus){this.update.innerHTML=choices;Element.cleanWhitespace(this.update);Element.cleanWhitespace(this.update.down());if(this.update.firstChild&&this.update.down().childNodes){this.entryCount=this.update.down().childNodes.length;for(var i=0;i<this.entryCount;i++){var entry=this.getEntry(i);entry.autocompleteIndex=i;this.addObservers(entry);}}else{this.entryCount=0;}
this.stopIndicator();this.index=0;if(this.entryCount==1&&this.options.autoSelect){this.selectEntry();this.hide();}else{this.render();}}},addObservers:function(element){Event.observe(element,"mouseover",this.onHover.bindAsEventListener(this));Event.observe(element,"click",this.onClick.bindAsEventListener(this));},onObserverEvent:function(){this.changed=false;if(this.getToken().length>=this.options.minChars){this.getUpdatedChoices();}else{this.active=false;this.hide();}},getToken:function(){var tokenPos=this.findLastToken();if(tokenPos!=-1)
var ret=this.element.value.substr(tokenPos+1).replace(/^\s+/,'').replace(/\s+$/,'');else
var ret=this.element.value;return/\n/.test(ret)?'':ret;},findLastToken:function(){var lastTokenPos=-1;for(var i=0;i<this.options.tokens.length;i++){var thisTokenPos=this.element.value.lastIndexOf(this.options.tokens[i]);if(thisTokenPos>lastTokenPos)
lastTokenPos=thisTokenPos;}
return lastTokenPos;}}
Ajax.Autocompleter=Class.create();Object.extend(Object.extend(Ajax.Autocompleter.prototype,Autocompleter.Base.prototype),{initialize:function(element,update,url,options){this.baseInitialize(element,update,options);this.options.asynchronous=true;this.options.onComplete=this.onComplete.bind(this);this.options.defaultParams=this.options.parameters||null;this.url=url;},getUpdatedChoices:function(){this.startIndicator();var entry=encodeURIComponent(this.options.paramName)+'='+
encodeURIComponent(this.getToken());this.options.parameters=this.options.callback?this.options.callback(this.element,entry):entry;if(this.options.defaultParams)
this.options.parameters+='&'+this.options.defaultParams;new Ajax.Request(this.url,this.options);},onComplete:function(request){this.updateChoices(request.responseText);}});Autocompleter.Local=Class.create();Autocompleter.Local.prototype=Object.extend(new Autocompleter.Base(),{initialize:function(element,update,array,options){this.baseInitialize(element,update,options);this.options.array=array;},getUpdatedChoices:function(){this.updateChoices(this.options.selector(this));},setOptions:function(options){this.options=Object.extend({choices:10,partialSearch:true,partialChars:2,ignoreCase:true,fullSearch:false,selector:function(instance){var ret=[];var partial=[];var entry=instance.getToken();var count=0;for(var i=0;i<instance.options.array.length&&ret.length<instance.options.choices;i++){var elem=instance.options.array[i];var foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase()):elem.indexOf(entry);while(foundPos!=-1){if(foundPos==0&&elem.length!=entry.length){ret.push("<li><strong>"+elem.substr(0,entry.length)+"</strong>"+
elem.substr(entry.length)+"</li>");break;}else if(entry.length>=instance.options.partialChars&&instance.options.partialSearch&&foundPos!=-1){if(instance.options.fullSearch||/\s/.test(elem.substr(foundPos-1,1))){partial.push("<li>"+elem.substr(0,foundPos)+"<strong>"+
elem.substr(foundPos,entry.length)+"</strong>"+elem.substr(foundPos+entry.length)+"</li>");break;}}
foundPos=instance.options.ignoreCase?elem.toLowerCase().indexOf(entry.toLowerCase(),foundPos+1):elem.indexOf(entry,foundPos+1);}}
if(partial.length)
ret=ret.concat(partial.slice(0,instance.options.choices-ret.length))
return"<ul>"+ret.join('')+"</ul>";}},options||{});}});Field.scrollFreeActivate=function(field){setTimeout(function(){Field.activate(field);},1);}
Ajax.InPlaceEditor=Class.create();Ajax.InPlaceEditor.defaultHighlightColor="#FFFF99";Ajax.InPlaceEditor.prototype={initialize:function(element,url,options){this.url=url;this.element=$(element);this.options=Object.extend({paramName:"value",okButton:true,okLink:false,okText:"ok",cancelButton:false,cancelLink:true,cancelText:"cancel",textBeforeControls:'',textBetweenControls:'',textAfterControls:'',savingText:"Saving...",clickToEditText:"Click to edit",okText:"ok",rows:1,onComplete:function(transport,element){new Effect.Highlight(element,{startcolor:this.options.highlightcolor});},onFailure:function(transport){alert("Error communicating with the server: "+transport.responseText.stripTags());},callback:function(form){return Form.serialize(form);},handleLineBreaks:true,loadingText:'Loading...',savingClassName:'inplaceeditor-saving',loadingClassName:'inplaceeditor-loading',formClassName:'inplaceeditor-form',highlightcolor:Ajax.InPlaceEditor.defaultHighlightColor,highlightendcolor:"#FFFFFF",externalControl:null,submitOnBlur:false,ajaxOptions:{},evalScripts:false},options||{});if(!this.options.formId&&this.element.id){this.options.formId=this.element.id+"-inplaceeditor";if($(this.options.formId)){this.options.formId=null;}}
if(this.options.externalControl){this.options.externalControl=$(this.options.externalControl);}
this.originalBackground=Element.getStyle(this.element,'background-color');if(!this.originalBackground){this.originalBackground="transparent";}
this.element.title=this.options.clickToEditText;this.onclickListener=this.enterEditMode.bindAsEventListener(this);this.mouseoverListener=this.enterHover.bindAsEventListener(this);this.mouseoutListener=this.leaveHover.bindAsEventListener(this);Event.observe(this.element,'click',this.onclickListener);Event.observe(this.element,'mouseover',this.mouseoverListener);Event.observe(this.element,'mouseout',this.mouseoutListener);if(this.options.externalControl){Event.observe(this.options.externalControl,'click',this.onclickListener);Event.observe(this.options.externalControl,'mouseover',this.mouseoverListener);Event.observe(this.options.externalControl,'mouseout',this.mouseoutListener);}},enterEditMode:function(evt){if(this.saving)return;if(this.editing)return;this.editing=true;this.onEnterEditMode();if(this.options.externalControl){Element.hide(this.options.externalControl);}
Element.hide(this.element);this.createForm();this.element.parentNode.insertBefore(this.form,this.element);if(!this.options.loadTextURL)Field.scrollFreeActivate(this.editField);if(evt){Event.stop(evt);}
return false;},createForm:function(){this.form=document.createElement("form");this.form.id=this.options.formId;Element.addClassName(this.form,this.options.formClassName)
this.form.onsubmit=this.onSubmit.bind(this);this.createEditField();if(this.options.textarea){var br=document.createElement("br");this.form.appendChild(br);}
if(this.options.textBeforeControls)
this.form.appendChild(document.createTextNode(this.options.textBeforeControls));if(this.options.okButton){var okButton=document.createElement("input");okButton.type="submit";okButton.value=this.options.okText;okButton.className='editor_ok_button';this.form.appendChild(okButton);}
if(this.options.okLink){var okLink=document.createElement("a");okLink.href="#";okLink.appendChild(document.createTextNode(this.options.okText));okLink.onclick=this.onSubmit.bind(this);okLink.className='editor_ok_link';this.form.appendChild(okLink);}
if(this.options.textBetweenControls&&(this.options.okLink||this.options.okButton)&&(this.options.cancelLink||this.options.cancelButton))
this.form.appendChild(document.createTextNode(this.options.textBetweenControls));if(this.options.cancelButton){var cancelButton=document.createElement("input");cancelButton.type="submit";cancelButton.value=this.options.cancelText;cancelButton.onclick=this.onclickCancel.bind(this);cancelButton.className='editor_cancel_button';this.form.appendChild(cancelButton);}
if(this.options.cancelLink){var cancelLink=document.createElement("a");cancelLink.href="#";cancelLink.appendChild(document.createTextNode(this.options.cancelText));cancelLink.onclick=this.onclickCancel.bind(this);cancelLink.className='editor_cancel editor_cancel_link';this.form.appendChild(cancelLink);}
if(this.options.textAfterControls)
this.form.appendChild(document.createTextNode(this.options.textAfterControls));},hasHTMLLineBreaks:function(string){if(!this.options.handleLineBreaks)return false;return string.match(/<br/i)||string.match(/<p>/i);},convertHTMLLineBreaks:function(string){return string.replace(/<br>/gi,"\n").replace(/<br\/>/gi,"\n").replace(/<\/p>/gi,"\n").replace(/<p>/gi,"");},createEditField:function(){var text;if(this.options.loadTextURL){text=this.options.loadingText;}else{text=this.getText();}
var obj=this;if(this.options.rows==1&&!this.hasHTMLLineBreaks(text)){this.options.textarea=false;var textField=document.createElement("input");textField.obj=this;textField.type="text";textField.name=this.options.paramName;textField.value=text;textField.style.backgroundColor=this.options.highlightcolor;textField.className='editor_field';var size=this.options.size||this.options.cols||0;if(size!=0)textField.size=size;if(this.options.submitOnBlur)
textField.onblur=this.onSubmit.bind(this);this.editField=textField;}else{this.options.textarea=true;var textArea=document.createElement("textarea");textArea.obj=this;textArea.name=this.options.paramName;textArea.value=this.convertHTMLLineBreaks(text);textArea.rows=this.options.rows;textArea.cols=this.options.cols||40;textArea.className='editor_field';if(this.options.submitOnBlur)
textArea.onblur=this.onSubmit.bind(this);this.editField=textArea;}
if(this.options.loadTextURL){this.loadExternalText();}
this.form.appendChild(this.editField);},getText:function(){return this.element.innerHTML;},loadExternalText:function(){Element.addClassName(this.form,this.options.loadingClassName);this.editField.disabled=true;new Ajax.Request(this.options.loadTextURL,Object.extend({asynchronous:true,onComplete:this.onLoadedExternalText.bind(this)},this.options.ajaxOptions));},onLoadedExternalText:function(transport){Element.removeClassName(this.form,this.options.loadingClassName);this.editField.disabled=false;this.editField.value=transport.responseText.stripTags();Field.scrollFreeActivate(this.editField);},onclickCancel:function(){this.onComplete();this.leaveEditMode();return false;},onFailure:function(transport){this.options.onFailure(transport);if(this.oldInnerHTML){this.element.innerHTML=this.oldInnerHTML;this.oldInnerHTML=null;}
return false;},onSubmit:function(){var form=this.form;var value=this.editField.value;this.onLoading();if(this.options.evalScripts){new Ajax.Request(this.url,Object.extend({parameters:this.options.callback(form,value),onComplete:this.onComplete.bind(this),onFailure:this.onFailure.bind(this),asynchronous:true,evalScripts:true},this.options.ajaxOptions));}else{new Ajax.Updater({success:this.element,failure:null},this.url,Object.extend({parameters:this.options.callback(form,value),onComplete:this.onComplete.bind(this),onFailure:this.onFailure.bind(this)},this.options.ajaxOptions));}
if(arguments.length>1){Event.stop(arguments[0]);}
return false;},onLoading:function(){this.saving=true;this.removeForm();this.leaveHover();this.showSaving();},showSaving:function(){this.oldInnerHTML=this.element.innerHTML;this.element.innerHTML=this.options.savingText;Element.addClassName(this.element,this.options.savingClassName);this.element.style.backgroundColor=this.originalBackground;Element.show(this.element);},removeForm:function(){if(this.form){if(this.form.parentNode)Element.remove(this.form);this.form=null;}},enterHover:function(){if(this.saving)return;this.element.style.backgroundColor=this.options.highlightcolor;if(this.effect){this.effect.cancel();}
Element.addClassName(this.element,this.options.hoverClassName)},leaveHover:function(){if(this.options.backgroundColor){this.element.style.backgroundColor=this.oldBackground;}
Element.removeClassName(this.element,this.options.hoverClassName)
if(this.saving)return;this.effect=new Effect.Highlight(this.element,{startcolor:this.options.highlightcolor,endcolor:this.options.highlightendcolor,restorecolor:this.originalBackground});},leaveEditMode:function(){Element.removeClassName(this.element,this.options.savingClassName);this.removeForm();this.leaveHover();this.element.style.backgroundColor=this.originalBackground;Element.show(this.element);if(this.options.externalControl){Element.show(this.options.externalControl);}
this.editing=false;this.saving=false;this.oldInnerHTML=null;this.onLeaveEditMode();},onComplete:function(transport){this.leaveEditMode();this.options.onComplete.bind(this)(transport,this.element);},onEnterEditMode:function(){},onLeaveEditMode:function(){},dispose:function(){if(this.oldInnerHTML){this.element.innerHTML=this.oldInnerHTML;}
this.leaveEditMode();Event.stopObserving(this.element,'click',this.onclickListener);Event.stopObserving(this.element,'mouseover',this.mouseoverListener);Event.stopObserving(this.element,'mouseout',this.mouseoutListener);if(this.options.externalControl){Event.stopObserving(this.options.externalControl,'click',this.onclickListener);Event.stopObserving(this.options.externalControl,'mouseover',this.mouseoverListener);Event.stopObserving(this.options.externalControl,'mouseout',this.mouseoutListener);}}};Ajax.InPlaceCollectionEditor=Class.create();Object.extend(Ajax.InPlaceCollectionEditor.prototype,Ajax.InPlaceEditor.prototype);Object.extend(Ajax.InPlaceCollectionEditor.prototype,{createEditField:function(){if(!this.cached_selectTag){var selectTag=document.createElement("select");var collection=this.options.collection||[];var optionTag;collection.each(function(e,i){optionTag=document.createElement("option");optionTag.value=(e instanceof Array)?e[0]:e;if((typeof this.options.value=='undefined')&&((e instanceof Array)?this.element.innerHTML==e[1]:e==optionTag.value))optionTag.selected=true;if(this.options.value==optionTag.value)optionTag.selected=true;optionTag.appendChild(document.createTextNode((e instanceof Array)?e[1]:e));selectTag.appendChild(optionTag);}.bind(this));this.cached_selectTag=selectTag;}
this.editField=this.cached_selectTag;if(this.options.loadTextURL)this.loadExternalText();this.form.appendChild(this.editField);this.options.callback=function(form,value){return"value="+encodeURIComponent(value);}}});Form.Element.DelayedObserver=Class.create();Form.Element.DelayedObserver.prototype={initialize:function(element,delay,callback){this.delay=delay||0.5;this.element=$(element);this.callback=callback;this.timer=null;this.lastValue=$F(this.element);Event.observe(this.element,'keyup',this.delayedListener.bindAsEventListener(this));},delayedListener:function(event){if(this.lastValue==$F(this.element))return;if(this.timer)clearTimeout(this.timer);this.timer=setTimeout(this.onTimerEvent.bind(this),this.delay*1000);this.lastValue=$F(this.element);},onTimerEvent:function(){this.timer=null;this.callback(this.element,$F(this.element));}};if(!Control)var Control={};Control.Slider=Class.create();Control.Slider.prototype={initialize:function(handle,track,options){var slider=this;if(handle instanceof Array){this.handles=handle.collect(function(e){return $(e)});}else{this.handles=[$(handle)];}
this.track=$(track);this.options=options||{};this.axis=this.options.axis||'horizontal';this.increment=this.options.increment||1;this.step=parseInt(this.options.step||'1');this.range=this.options.range||$R(0,1);this.value=0;this.values=this.handles.map(function(){return 0});this.spans=this.options.spans?this.options.spans.map(function(s){return $(s)}):false;this.options.startSpan=$(this.options.startSpan||null);this.options.endSpan=$(this.options.endSpan||null);this.restricted=this.options.restricted||false;this.maximum=this.options.maximum||this.range.end;this.minimum=this.options.minimum||this.range.start;this.alignX=parseInt(this.options.alignX||'0');this.alignY=parseInt(this.options.alignY||'0');this.trackLength=this.maximumOffset()-this.minimumOffset();this.handleLength=this.isVertical()?(this.handles[0].offsetHeight!=0?this.handles[0].offsetHeight:this.handles[0].style.height.replace(/px$/,"")):(this.handles[0].offsetWidth!=0?this.handles[0].offsetWidth:this.handles[0].style.width.replace(/px$/,""));this.active=false;this.dragging=false;this.disabled=false;if(this.options.disabled)this.setDisabled();this.allowedValues=this.options.values?this.options.values.sortBy(Prototype.K):false;if(this.allowedValues){this.minimum=this.allowedValues.min();this.maximum=this.allowedValues.max();}
this.eventMouseDown=this.startDrag.bindAsEventListener(this);this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.update.bindAsEventListener(this);this.handles.each(function(h,i){i=slider.handles.length-1-i;slider.setValue(parseFloat((slider.options.sliderValue instanceof Array?slider.options.sliderValue[i]:slider.options.sliderValue)||slider.range.start),i);Element.makePositioned(h);Event.observe(h,"mousedown",slider.eventMouseDown);});Event.observe(this.track,"mousedown",this.eventMouseDown);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);this.initialized=true;},dispose:function(){var slider=this;Event.stopObserving(this.track,"mousedown",this.eventMouseDown);Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);this.handles.each(function(h){Event.stopObserving(h,"mousedown",slider.eventMouseDown);});},setDisabled:function(){this.disabled=true;},setEnabled:function(){this.disabled=false;},getNearestValue:function(value){if(this.allowedValues){if(value>=this.allowedValues.max())return(this.allowedValues.max());if(value<=this.allowedValues.min())return(this.allowedValues.min());var offset=Math.abs(this.allowedValues[0]-value);var newValue=this.allowedValues[0];this.allowedValues.each(function(v){var currentOffset=Math.abs(v-value);if(currentOffset<=offset){newValue=v;offset=currentOffset;}});return newValue;}
if(value>this.range.end)return this.range.end;if(value<this.range.start)return this.range.start;return value;},setValue:function(sliderValue,handleIdx){if(!this.active){this.activeHandleIdx=handleIdx||0;this.activeHandle=this.handles[this.activeHandleIdx];this.updateStyles();}
handleIdx=handleIdx||this.activeHandleIdx||0;if(this.initialized&&this.restricted){if((handleIdx>0)&&(sliderValue<this.values[handleIdx-1]))
sliderValue=this.values[handleIdx-1];if((handleIdx<(this.handles.length-1))&&(sliderValue>this.values[handleIdx+1]))
sliderValue=this.values[handleIdx+1];}
sliderValue=this.getNearestValue(sliderValue);this.values[handleIdx]=sliderValue;this.value=this.values[0];this.handles[handleIdx].style[this.isVertical()?'top':'left']=this.translateToPx(sliderValue);this.drawSpans();if(!this.dragging||!this.event)this.updateFinished();},setValueBy:function(delta,handleIdx){this.setValue(this.values[handleIdx||this.activeHandleIdx||0]+delta,handleIdx||this.activeHandleIdx||0);},translateToPx:function(value){return Math.round(((this.trackLength-this.handleLength)/(this.range.end-this.range.start))*(value-this.range.start))+"px";},translateToValue:function(offset){return((offset/(this.trackLength-this.handleLength)*(this.range.end-this.range.start))+this.range.start);},getRange:function(range){var v=this.values.sortBy(Prototype.K);range=range||0;return $R(v[range],v[range+1]);},minimumOffset:function(){return(this.isVertical()?this.alignY:this.alignX);},maximumOffset:function(){return(this.isVertical()?(this.track.offsetHeight!=0?this.track.offsetHeight:this.track.style.height.replace(/px$/,""))-this.alignY:(this.track.offsetWidth!=0?this.track.offsetWidth:this.track.style.width.replace(/px$/,""))-this.alignY);},isVertical:function(){return(this.axis=='vertical');},drawSpans:function(){var slider=this;if(this.spans)
$R(0,this.spans.length-1).each(function(r){slider.setSpan(slider.spans[r],slider.getRange(r))});if(this.options.startSpan)
this.setSpan(this.options.startSpan,$R(0,this.values.length>1?this.getRange(0).min():this.value));if(this.options.endSpan)
this.setSpan(this.options.endSpan,$R(this.values.length>1?this.getRange(this.spans.length-1).max():this.value,this.maximum));},setSpan:function(span,range){if(this.isVertical()){span.style.top=this.translateToPx(range.start);span.style.height=this.translateToPx(range.end-range.start+this.range.start);}else{span.style.left=this.translateToPx(range.start);span.style.width=this.translateToPx(range.end-range.start+this.range.start);}},updateStyles:function(){this.handles.each(function(h){Element.removeClassName(h,'selected')});Element.addClassName(this.activeHandle,'selected');},startDrag:function(event){if(Event.isLeftClick(event)){if(!this.disabled){this.active=true;var handle=Event.element(event);var pointer=[Event.pointerX(event),Event.pointerY(event)];var track=handle;if(track==this.track){var offsets=Position.cumulativeOffset(this.track);this.event=event;this.setValue(this.translateToValue((this.isVertical()?pointer[1]-offsets[1]:pointer[0]-offsets[0])-(this.handleLength/2)));var offsets=Position.cumulativeOffset(this.activeHandle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);}else{while((this.handles.indexOf(handle)==-1)&&handle.parentNode)
handle=handle.parentNode;if(this.handles.indexOf(handle)!=-1){this.activeHandle=handle;this.activeHandleIdx=this.handles.indexOf(this.activeHandle);this.updateStyles();var offsets=Position.cumulativeOffset(this.activeHandle);this.offsetX=(pointer[0]-offsets[0]);this.offsetY=(pointer[1]-offsets[1]);}}}
Event.stop(event);}},update:function(event){if(this.active){if(!this.dragging)this.dragging=true;this.draw(event);if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);}},draw:function(event){var pointer=[Event.pointerX(event),Event.pointerY(event)];var offsets=Position.cumulativeOffset(this.track);pointer[0]-=this.offsetX+offsets[0];pointer[1]-=this.offsetY+offsets[1];this.event=event;this.setValue(this.translateToValue(this.isVertical()?pointer[1]:pointer[0]));if(this.initialized&&this.options.onSlide)
this.options.onSlide(this.values.length>1?this.values:this.value,this);},endDrag:function(event){if(this.active&&this.dragging){this.finishDrag(event,true);Event.stop(event);}
this.active=false;this.dragging=false;},finishDrag:function(event,success){this.active=false;this.dragging=false;this.updateFinished();},updateFinished:function(){if(this.initialized&&this.options.onChange)
this.options.onChange(this.values.length>1?this.values:this.value,this);this.event=null;}}
if(typeof Effect=='undefined')
throw("dragdrop.js requires including script.aculo.us' effects.js library");var Droppables={drops:[],remove:function(element){this.drops=this.drops.reject(function(d){return d.element==$(element)});},add:function(element){element=$(element);var options=Object.extend({greedy:true,hoverclass:null,tree:false},arguments[1]||{});if(options.containment){options._containers=[];var containment=options.containment;if((typeof containment=='object')&&(containment.constructor==Array)){containment.each(function(c){options._containers.push($(c))});}else{options._containers.push($(containment));}}
if(options.accept)options.accept=[options.accept].flatten();Element.makePositioned(element);options.element=element;this.drops.push(options);},findDeepestChild:function(drops){deepest=drops[0];for(i=1;i<drops.length;++i)
if(Element.isParent(drops[i].element,deepest.element))
deepest=drops[i];return deepest;},isContained:function(element,drop){var containmentNode;if(drop.tree){containmentNode=element.treeNode;}else{containmentNode=element.parentNode;}
return drop._containers.detect(function(c){return containmentNode==c});},isAffected:function(point,element,drop){return((drop.element!=element)&&((!drop._containers)||this.isContained(element,drop))&&((!drop.accept)||(Element.classNames(element).detect(function(v){return drop.accept.include(v)})))&&Position.within(drop.element,point[0],point[1]));},deactivate:function(drop){if(drop.hoverclass)
Element.removeClassName(drop.element,drop.hoverclass);this.last_active=null;},activate:function(drop){if(drop.hoverclass)
Element.addClassName(drop.element,drop.hoverclass);this.last_active=drop;},show:function(point,element){if(!this.drops.length)return;var affected=[];if(this.last_active)this.deactivate(this.last_active);this.drops.each(function(drop){if(Droppables.isAffected(point,element,drop))
affected.push(drop);});if(affected.length>0){drop=Droppables.findDeepestChild(affected);Position.within(drop.element,point[0],point[1]);if(drop.onHover)
drop.onHover(element,drop.element,Position.overlap(drop.overlap,drop.element));Droppables.activate(drop);}},fire:function(event,element){if(!this.last_active)return;Position.prepare();if(this.isAffected([Event.pointerX(event),Event.pointerY(event)],element,this.last_active))
if(this.last_active.onDrop){this.last_active.onDrop(element,this.last_active.element,event);return true;}},reset:function(){if(this.last_active)
this.deactivate(this.last_active);}}
var Draggables={drags:[],observers:[],register:function(draggable){if(this.drags.length==0){this.eventMouseUp=this.endDrag.bindAsEventListener(this);this.eventMouseMove=this.updateDrag.bindAsEventListener(this);this.eventKeypress=this.keyPress.bindAsEventListener(this);Event.observe(document,"mouseup",this.eventMouseUp);Event.observe(document,"mousemove",this.eventMouseMove);Event.observe(document,"keypress",this.eventKeypress);}
this.drags.push(draggable);},unregister:function(draggable){this.drags=this.drags.reject(function(d){return d==draggable});if(this.drags.length==0){Event.stopObserving(document,"mouseup",this.eventMouseUp);Event.stopObserving(document,"mousemove",this.eventMouseMove);Event.stopObserving(document,"keypress",this.eventKeypress);}},activate:function(draggable){if(draggable.options.delay){this._timeout=setTimeout(function(){Draggables._timeout=null;window.focus();Draggables.activeDraggable=draggable;}.bind(this),draggable.options.delay);}else{window.focus();this.activeDraggable=draggable;}},deactivate:function(){this.activeDraggable=null;},updateDrag:function(event){if(!this.activeDraggable)return;var pointer=[Event.pointerX(event),Event.pointerY(event)];if(this._lastPointer&&(this._lastPointer.inspect()==pointer.inspect()))return;this._lastPointer=pointer;this.activeDraggable.updateDrag(event,pointer);},endDrag:function(event){if(this._timeout){clearTimeout(this._timeout);this._timeout=null;}
if(!this.activeDraggable)return;this._lastPointer=null;this.activeDraggable.endDrag(event);this.activeDraggable=null;},keyPress:function(event){if(this.activeDraggable)
this.activeDraggable.keyPress(event);},addObserver:function(observer){this.observers.push(observer);this._cacheObserverCallbacks();},removeObserver:function(element){this.observers=this.observers.reject(function(o){return o.element==element});this._cacheObserverCallbacks();},notify:function(eventName,draggable,event){if(this[eventName+'Count']>0)
this.observers.each(function(o){if(o[eventName])o[eventName](eventName,draggable,event);});if(draggable.options[eventName])draggable.options[eventName](draggable,event);},_cacheObserverCallbacks:function(){['onStart','onEnd','onDrag'].each(function(eventName){Draggables[eventName+'Count']=Draggables.observers.select(function(o){return o[eventName];}).length;});}}
var Draggable=Class.create();Draggable._dragging={};Draggable.prototype={initialize:function(element){var defaults={handle:false,reverteffect:function(element,top_offset,left_offset){var dur=Math.sqrt(Math.abs(top_offset^2)+Math.abs(left_offset^2))*0.02;new Effect.Move(element,{x:-left_offset,y:-top_offset,duration:dur,queue:{scope:'_draggable',position:'end'}});},endeffect:function(element){var toOpacity=typeof element._opacity=='number'?element._opacity:1.0;new Effect.Opacity(element,{duration:0.2,from:0.7,to:toOpacity,queue:{scope:'_draggable',position:'end'},afterFinish:function(){Draggable._dragging[element]=false}});},zindex:1000,revert:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,snap:false,delay:0};if(!arguments[1]||typeof arguments[1].endeffect=='undefined')
Object.extend(defaults,{starteffect:function(element){element._opacity=Element.getOpacity(element);Draggable._dragging[element]=true;new Effect.Opacity(element,{duration:0.2,from:element._opacity,to:0.7});}});var options=Object.extend(defaults,arguments[1]||{});this.element=$(element);if(options.handle&&(typeof options.handle=='string'))
this.handle=this.element.down('.'+options.handle,0);if(!this.handle)this.handle=$(options.handle);if(!this.handle)this.handle=this.element;if(options.scroll&&!options.scroll.scrollTo&&!options.scroll.outerHTML){options.scroll=$(options.scroll);this._isScrollChild=Element.childOf(this.element,options.scroll);}
Element.makePositioned(this.element);this.delta=this.currentDelta();this.options=options;this.dragging=false;this.eventMouseDown=this.initDrag.bindAsEventListener(this);Event.observe(this.handle,"mousedown",this.eventMouseDown);Draggables.register(this);},destroy:function(){Event.stopObserving(this.handle,"mousedown",this.eventMouseDown);Draggables.unregister(this);},currentDelta:function(){return([parseInt(Element.getStyle(this.element,'left')||'0'),parseInt(Element.getStyle(this.element,'top')||'0')]);},initDrag:function(event){if(typeof Draggable._dragging[this.element]!='undefined'&&Draggable._dragging[this.element])return;if(Event.isLeftClick(event)){var src=Event.element(event);if((tag_name=src.tagName.toUpperCase())&&(tag_name=='INPUT'||tag_name=='SELECT'||tag_name=='OPTION'||tag_name=='BUTTON'||tag_name=='TEXTAREA'))return;var pointer=[Event.pointerX(event),Event.pointerY(event)];var pos=Position.cumulativeOffset(this.element);this.offset=[0,1].map(function(i){return(pointer[i]-pos[i])});Draggables.activate(this);Event.stop(event);}},startDrag:function(event){this.dragging=true;if(this.options.zindex){this.originalZ=parseInt(Element.getStyle(this.element,'z-index')||0);this.element.style.zIndex=this.options.zindex;}
if(this.options.ghosting){this._clone=this.element.cloneNode(true);Position.absolutize(this.element);this.element.parentNode.insertBefore(this._clone,this.element);}
if(this.options.scroll){if(this.options.scroll==window){var where=this._getWindowScroll(this.options.scroll);this.originalScrollLeft=where.left;this.originalScrollTop=where.top;}else{this.originalScrollLeft=this.options.scroll.scrollLeft;this.originalScrollTop=this.options.scroll.scrollTop;}}
Draggables.notify('onStart',this,event);if(this.options.starteffect)this.options.starteffect(this.element);},updateDrag:function(event,pointer){if(!this.dragging)this.startDrag(event);if(!this.options.quiet){Position.prepare();Droppables.show(pointer,this.element);}
Draggables.notify('onDrag',this,event);this.draw(pointer);if(this.options.change)this.options.change(this);if(this.options.scroll){this.stopScrolling();var p;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){p=[left,top,left+width,top+height];}}else{p=Position.page(this.options.scroll);p[0]+=this.options.scroll.scrollLeft+Position.deltaX;p[1]+=this.options.scroll.scrollTop+Position.deltaY;p.push(p[0]+this.options.scroll.offsetWidth);p.push(p[1]+this.options.scroll.offsetHeight);}
var speed=[0,0];if(pointer[0]<(p[0]+this.options.scrollSensitivity))speed[0]=pointer[0]-(p[0]+this.options.scrollSensitivity);if(pointer[1]<(p[1]+this.options.scrollSensitivity))speed[1]=pointer[1]-(p[1]+this.options.scrollSensitivity);if(pointer[0]>(p[2]-this.options.scrollSensitivity))speed[0]=pointer[0]-(p[2]-this.options.scrollSensitivity);if(pointer[1]>(p[3]-this.options.scrollSensitivity))speed[1]=pointer[1]-(p[3]-this.options.scrollSensitivity);this.startScrolling(speed);}
if(Prototype.Browser.WebKit)window.scrollBy(0,0);Event.stop(event);},finishDrag:function(event,success){this.dragging=false;if(this.options.quiet){Position.prepare();var pointer=[Event.pointerX(event),Event.pointerY(event)];Droppables.show(pointer,this.element);}
if(this.options.ghosting){Position.relativize(this.element);Element.remove(this._clone);this._clone=null;}
var dropped=false;if(success){dropped=Droppables.fire(event,this.element);if(!dropped)dropped=false;}
if(dropped&&this.options.onDropped)this.options.onDropped(this.element);Draggables.notify('onEnd',this,event);var revert=this.options.revert;if(revert&&typeof revert=='function')revert=revert(this.element);var d=this.currentDelta();if(revert&&this.options.reverteffect){if(dropped==0||revert!='failure')
this.options.reverteffect(this.element,d[1]-this.delta[1],d[0]-this.delta[0]);}else{this.delta=d;}
if(this.options.zindex)
this.element.style.zIndex=this.originalZ;if(this.options.endeffect)
this.options.endeffect(this.element);Draggables.deactivate(this);Droppables.reset();},keyPress:function(event){if(event.keyCode!=Event.KEY_ESC)return;this.finishDrag(event,false);Event.stop(event);},endDrag:function(event){if(!this.dragging)return;this.stopScrolling();this.finishDrag(event,true);Event.stop(event);},draw:function(point){var pos=Position.cumulativeOffset(this.element);if(this.options.ghosting){var r=Position.realOffset(this.element);pos[0]+=r[0]-Position.deltaX;pos[1]+=r[1]-Position.deltaY;}
var d=this.currentDelta();pos[0]-=d[0];pos[1]-=d[1];if(this.options.scroll&&(this.options.scroll!=window&&this._isScrollChild)){pos[0]-=this.options.scroll.scrollLeft-this.originalScrollLeft;pos[1]-=this.options.scroll.scrollTop-this.originalScrollTop;}
var p=[0,1].map(function(i){return(point[i]-pos[i]-this.offset[i])}.bind(this));if(this.options.snap){if(typeof this.options.snap=='function'){p=this.options.snap(p[0],p[1],this);}else{if(this.options.snap instanceof Array){p=p.map(function(v,i){return Math.round(v/this.options.snap[i])*this.options.snap[i]}.bind(this))}else{p=p.map(function(v){return Math.round(v/this.options.snap)*this.options.snap}.bind(this))}}}
var style=this.element.style;if((!this.options.constraint)||(this.options.constraint=='horizontal'))
style.left=p[0]+"px";if((!this.options.constraint)||(this.options.constraint=='vertical'))
style.top=p[1]+"px";if(style.visibility=="hidden")style.visibility="";},stopScrolling:function(){if(this.scrollInterval){clearInterval(this.scrollInterval);this.scrollInterval=null;Draggables._lastScrollPointer=null;}},startScrolling:function(speed){if(!(speed[0]||speed[1]))return;this.scrollSpeed=[speed[0]*this.options.scrollSpeed,speed[1]*this.options.scrollSpeed];this.lastScrolled=new Date();this.scrollInterval=setInterval(this.scroll.bind(this),10);},scroll:function(){var current=new Date();var delta=current-this.lastScrolled;this.lastScrolled=current;if(this.options.scroll==window){with(this._getWindowScroll(this.options.scroll)){if(this.scrollSpeed[0]||this.scrollSpeed[1]){var d=delta/1000;this.options.scroll.scrollTo(left+d*this.scrollSpeed[0],top+d*this.scrollSpeed[1]);}}}else{this.options.scroll.scrollLeft+=this.scrollSpeed[0]*delta/1000;this.options.scroll.scrollTop+=this.scrollSpeed[1]*delta/1000;}
Position.prepare();Droppables.show(Draggables._lastPointer,this.element);Draggables.notify('onDrag',this);if(this._isScrollChild){Draggables._lastScrollPointer=Draggables._lastScrollPointer||$A(Draggables._lastPointer);Draggables._lastScrollPointer[0]+=this.scrollSpeed[0]*delta/1000;Draggables._lastScrollPointer[1]+=this.scrollSpeed[1]*delta/1000;if(Draggables._lastScrollPointer[0]<0)
Draggables._lastScrollPointer[0]=0;if(Draggables._lastScrollPointer[1]<0)
Draggables._lastScrollPointer[1]=0;this.draw(Draggables._lastScrollPointer);}
if(this.options.change)this.options.change(this);},_getWindowScroll:function(w){var T,L,W,H;with(w.document){if(w.document.documentElement&&documentElement.scrollTop){T=documentElement.scrollTop;L=documentElement.scrollLeft;}else if(w.document.body){T=body.scrollTop;L=body.scrollLeft;}
if(w.innerWidth){W=w.innerWidth;H=w.innerHeight;}else if(w.document.documentElement&&documentElement.clientWidth){W=documentElement.clientWidth;H=documentElement.clientHeight;}else{W=body.offsetWidth;H=body.offsetHeight}}
return{top:T,left:L,width:W,height:H};}}
var SortableObserver=Class.create();SortableObserver.prototype={initialize:function(element,observer){this.element=$(element);this.observer=observer;this.lastValue=Sortable.serialize(this.element);},onStart:function(){this.lastValue=Sortable.serialize(this.element);},onEnd:function(){Sortable.unmark();if(this.lastValue!=Sortable.serialize(this.element))
this.observer(this.element)}}
var Sortable={SERIALIZE_RULE:/^[^_\-](?:[A-Za-z0-9\-\_]*)[_](.*)$/,sortables:{},_findRootElement:function(element){while(element.tagName.toUpperCase()!="BODY"){if(element.id&&Sortable.sortables[element.id])return element;element=element.parentNode;}},options:function(element){element=Sortable._findRootElement($(element));if(!element)return;return Sortable.sortables[element.id];},destroy:function(element){var s=Sortable.options(element);if(s){Draggables.removeObserver(s.element);s.droppables.each(function(d){Droppables.remove(d)});s.draggables.invoke('destroy');delete Sortable.sortables[s.element.id];}},create:function(element){element=$(element);var options=Object.extend({element:element,tag:'li',dropOnEmpty:false,tree:false,treeTag:'ul',overlap:'vertical',constraint:'vertical',containment:element,handle:false,only:false,delay:0,hoverclass:null,ghosting:false,quiet:false,scroll:false,scrollSensitivity:20,scrollSpeed:15,format:this.SERIALIZE_RULE,elements:false,handles:false,onChange:Prototype.emptyFunction,onUpdate:Prototype.emptyFunction},arguments[1]||{});this.destroy(element);var options_for_draggable={revert:true,quiet:options.quiet,scroll:options.scroll,scrollSpeed:options.scrollSpeed,scrollSensitivity:options.scrollSensitivity,delay:options.delay,ghosting:options.ghosting,constraint:options.constraint,handle:options.handle};if(options.starteffect)
options_for_draggable.starteffect=options.starteffect;if(options.reverteffect)
options_for_draggable.reverteffect=options.reverteffect;else
if(options.ghosting)options_for_draggable.reverteffect=function(element){element.style.top=0;element.style.left=0;};if(options.endeffect)
options_for_draggable.endeffect=options.endeffect;if(options.zindex)
options_for_draggable.zindex=options.zindex;var options_for_droppable={overlap:options.overlap,containment:options.containment,tree:options.tree,hoverclass:options.hoverclass,onHover:Sortable.onHover}
var options_for_tree={onHover:Sortable.onEmptyHover,overlap:options.overlap,containment:options.containment,hoverclass:options.hoverclass}
Element.cleanWhitespace(element);options.draggables=[];options.droppables=[];if(options.dropOnEmpty||options.tree){Droppables.add(element,options_for_tree);options.droppables.push(element);}
(options.elements||this.findElements(element,options)||[]).each(function(e,i){var handle=options.handles?$(options.handles[i]):(options.handle?$(e).getElementsByClassName(options.handle)[0]:e);options.draggables.push(new Draggable(e,Object.extend(options_for_draggable,{handle:handle})));Droppables.add(e,options_for_droppable);if(options.tree)e.treeNode=element;options.droppables.push(e);});if(options.tree){(Sortable.findTreeElements(element,options)||[]).each(function(e){Droppables.add(e,options_for_tree);e.treeNode=element;options.droppables.push(e);});}
this.sortables[element.id]=options;Draggables.addObserver(new SortableObserver(element,options.onUpdate));},findElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.tag);},findTreeElements:function(element,options){return Element.findChildren(element,options.only,options.tree?true:false,options.treeTag);},onHover:function(element,dropon,overlap){if(Element.isParent(dropon,element))return;if(overlap>.33&&overlap<.66&&Sortable.options(dropon).tree){return;}else if(overlap>0.5){Sortable.mark(dropon,'before');if(dropon.previousSibling!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,dropon);if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);Sortable.options(dropon.parentNode).onChange(element);}}else{Sortable.mark(dropon,'after');var nextElement=dropon.nextSibling||null;if(nextElement!=element){var oldParentNode=element.parentNode;element.style.visibility="hidden";dropon.parentNode.insertBefore(element,nextElement);if(dropon.parentNode!=oldParentNode)
Sortable.options(oldParentNode).onChange(element);Sortable.options(dropon.parentNode).onChange(element);}}},onEmptyHover:function(element,dropon,overlap){var oldParentNode=element.parentNode;var droponOptions=Sortable.options(dropon);if(!Element.isParent(dropon,element)){var index;var children=Sortable.findElements(dropon,{tag:droponOptions.tag,only:droponOptions.only});var child=null;if(children){var offset=Element.offsetSize(dropon,droponOptions.overlap)*(1.0-overlap);for(index=0;index<children.length;index+=1){if(offset-Element.offsetSize(children[index],droponOptions.overlap)>=0){offset-=Element.offsetSize(children[index],droponOptions.overlap);}else if(offset-(Element.offsetSize(children[index],droponOptions.overlap)/2)>=0){child=index+1<children.length?children[index+1]:null;break;}else{child=children[index];break;}}}
dropon.insertBefore(element,child);Sortable.options(oldParentNode).onChange(element);droponOptions.onChange(element);}},unmark:function(){if(Sortable._marker)Sortable._marker.hide();},mark:function(dropon,position){var sortable=Sortable.options(dropon.parentNode);if(sortable&&!sortable.ghosting)return;if(!Sortable._marker){Sortable._marker=($('dropmarker')||Element.extend(document.createElement('DIV'))).hide().addClassName('dropmarker').setStyle({position:'absolute'});document.getElementsByTagName("body").item(0).appendChild(Sortable._marker);}
var offsets=Position.cumulativeOffset(dropon);Sortable._marker.setStyle({left:offsets[0]+'px',top:offsets[1]+'px'});if(position=='after')
if(sortable.overlap=='horizontal')
Sortable._marker.setStyle({left:(offsets[0]+dropon.clientWidth)+'px'});else
Sortable._marker.setStyle({top:(offsets[1]+dropon.clientHeight)+'px'});Sortable._marker.show();},_tree:function(element,options,parent){var children=Sortable.findElements(element,options)||[];for(var i=0;i<children.length;++i){var match=children[i].id.match(options.format);if(!match)continue;var child={id:encodeURIComponent(match?match[1]:null),element:element,parent:parent,children:[],position:parent.children.length,container:$(children[i]).down(options.treeTag)}
if(child.container)
this._tree(child.container,options,child)
parent.children.push(child);}
return parent;},tree:function(element){element=$(element);var sortableOptions=this.options(element);var options=Object.extend({tag:sortableOptions.tag,treeTag:sortableOptions.treeTag,only:sortableOptions.only,name:element.id,format:sortableOptions.format},arguments[1]||{});var root={id:null,parent:null,children:[],container:element,position:0}
return Sortable._tree(element,options,root);},_constructIndex:function(node){var index='';do{if(node.id)index='['+node.position+']'+index;}while((node=node.parent)!=null);return index;},sequence:function(element){element=$(element);var options=Object.extend(this.options(element),arguments[1]||{});return $(this.findElements(element,options)||[]).map(function(item){return item.id.match(options.format)?item.id.match(options.format)[1]:'';});},setSequence:function(element,new_sequence){element=$(element);var options=Object.extend(this.options(element),arguments[2]||{});var nodeMap={};this.findElements(element,options).each(function(n){if(n.id.match(options.format))
nodeMap[n.id.match(options.format)[1]]=[n,n.parentNode];n.parentNode.removeChild(n);});new_sequence.each(function(ident){var n=nodeMap[ident];if(n){n[1].appendChild(n[0]);delete nodeMap[ident];}});},serialize:function(element){element=$(element);var options=Object.extend(Sortable.options(element),arguments[1]||{});var name=encodeURIComponent((arguments[1]&&arguments[1].name)?arguments[1].name:element.id);if(options.tree){return Sortable.tree(element,arguments[1]).children.map(function(item){return[name+Sortable._constructIndex(item)+"[id]="+
encodeURIComponent(item.id)].concat(item.children.map(arguments.callee));}).flatten().join('&');}else{return Sortable.sequence(element,arguments[1]).map(function(item){return name+"[]="+encodeURIComponent(item);}).join('&');}}}
Element.isParent=function(child,element){if(!child.parentNode||child==element)return false;if(child.parentNode==element)return true;return Element.isParent(child.parentNode,element);}
Element.findChildren=function(element,only,recursive,tagName){if(!element.hasChildNodes())return null;tagName=tagName.toUpperCase();if(only)only=[only].flatten();var elements=[];$A(element.childNodes).each(function(e){if(e.tagName&&e.tagName.toUpperCase()==tagName&&(!only||(Element.classNames(e).detect(function(v){return only.include(v)}))))
elements.push(e);if(recursive){var grandchildren=Element.findChildren(e,only,recursive,tagName);if(grandchildren)elements.push(grandchildren);}});return(elements.length>0?elements.flatten():[]);}
Element.offsetSize=function(element,type){return element['offset'+((type=='vertical'||type=='height')?'Height':'Width')];}
var Crossfade=Class.create();Crossfade.prototype={loaded:false,initialize:function(elm,options){var me=this,next,prev;this.elm=$(elm);this.counter=0;this.prevSlide=null;var t_opt={};for(t in Crossfade.Transition){var trans=Crossfade.Transition[t];if(trans.className&&this.elm.hasClassName(trans.className)){t_opt={transition:trans};break;}}
this.options=Object.extend(Object.clone(Crossfade.defaults),Object.extend(options||{},t_opt));this.options.interval=Math.max(2,this.options.interval);this.elm.makePositioned();this.slides=this.elm.immediateDescendants();if(this.options.random||this.elm.hasClassName(this.options.randomClassName)){this.slides.sort(function(a,b){return me.rndm(-1,1);});}
if(this.elm.id){next=$(this.elm.id+'-next');prev=$(this.elm.id+'-previous');if(next){Event.observe(next,'click',this.next.bind(this));}
if(prev){Event.observe(prev,'click',this.previous.bind(this));}}
this.loadSlide(this.slides[0],function(){me.options.transition.prepare(me);});this.loadSlide(this.slides[1]);if(this.options.autoStart){setTimeout(this.start.bind(this),this.rndm((this.options.interval-1)*1000,(this.options.interval+1)*1000));}},start:function(){this.ready=true;this.cycle()
return this.timer=new PeriodicalExecuter(this.cycle.bind(this),this.options.interval);},stop:function(){this.options.transition.cancel(this);this.timer.stop();},next:function(){this.options.transition.cancel(this);this.cycle();},previous:function(){this.options.transition.cancel(this);this.cycle(-1);},cycle:function(dir){if(!this.ready){return;}
this.ready=false;dir=(dir===-1)?dir:1;var me=this,prevSlide,nextSlide,opt,fade;prevSlide=this.slides[this.counter];this.counter=this.loopCount(this.counter+dir);if(this.counter==0){this.loaded=true;}
nextSlide=this.slides[this.counter];this.loadSlide(nextSlide,me.options.transition.cycle(prevSlide,nextSlide,me));if(!this.loaded){this.loadSlide(this.slides[this.loopCount(this.counter+1)]);}},loadSlide:function(slide,onload){var loaders=[],me=this,img,pnode,onloadFunction;onload=typeof onload==='function'?onload:function(){};onloadFunction=function(){onload();me.ready=true;};slide=$(slide);loaders=Selector.findChildElements(slide,[this.options.imageLoadSelector]);if(loaders.length&&loaders[0].href!==''){img=document.createElement('img');img.className='loadimage';img.onload=onloadFunction;img.src=loaders[0].href;loaders[0].parentNode.replaceChild(img,loaders[0]);}else{loaders=[];loaders=Selector.findChildElements(slide,[this.options.ajaxLoadSelector]);if(loaders.length&&loaders[0].href!==''){new Ajax.Updater(slide,loaders[0].href,{method:'get',onComplete:onloadFunction});}else{onloadFunction();}}},loopCount:function(c){if(c>=this.slides.length){c=0;}else if(c<0){c=this.slides.length-1}
return c;},rndm:function(min,max){return Math.floor(Math.random()*(max-min+1)+min);},timer:null,effect:null,ready:false};Crossfade.Transition={};Crossfade.Transition.Switch={className:'transition-switch',cycle:function(prev,next,show){show.slides.without(next).each(function(s){$(s).hide();})
$(next).show();},cancel:function(show){},prepare:function(show){show.slides.each(function(s,i){$(s).setStyle({display:(i===0?'block':'none')});});}};Crossfade.Transition.Crossfade={className:'transition-crossfade',cycle:function(prev,next,show){var opt=show.options;show.effect=new Effect.Parallel([new Effect.Fade(prev,{sync:true}),new Effect.Appear(next,{sync:true})],{duration:opt.duration,queue:'Crossfade',afterFinish:function(){show.slides.without(next).each(function(s){$(s).setStyle({opacity:0});})}});},cancel:function(show){if(show.effect){show.effect.cancel();}},prepare:function(show){show.slides.each(function(s,i){$(s).setStyle({opacity:(i===0?1:0),visibility:'visible'});});}};Crossfade.Transition.FadeOutFadeIn={className:'transition-fadeoutfadein',cycle:function(prev,next,show){var opt=show.options;show.effect=new Effect.Fade(prev,{duration:opt.duration/2,afterFinish:function(){show.effect=new Effect.Appear(next,{duration:opt.duration/2});show.slides.without(next).each(function(s){$(s).setStyle({opacity:0});})}});},cancel:function(show){if(show.effect){show.effect.cancel();}},prepare:function(show){show.slides.each(function(s,i){$(s).setStyle({opacity:(i===0?1:0),visibility:'visible'});});}};Effect.DoNothing=Class.create();Object.extend(Object.extend(Effect.DoNothing.prototype,Effect.Base.prototype),{initialize:function(){this.start({duration:0});},update:Prototype.emptyFunction});Crossfade.Transition.FadeOutResizeFadeIn={className:'transition-fadeoutresizefadein',cycle:function(prev,next,show){var opt=show.options;show.effect=new Effect.Fade(prev,{duration:(opt.duration-1)/2,afterFinish:function(){show.slides.without(next).each(function(s){$(s).setStyle({opacity:0});})
var slideDims=[next.getWidth(),next.getHeight()];var loadimg=Selector.findChildElements(next,['img.loadimage']);if(loadimg.length&&loadimg[0].offsetWidth&&loadimg[0].offsetHeight){slideDims[0]+=slideDims[0]<loadimg[0].offsetWidth?loadimg[0].offsetWidth:0;slideDims[1]+=slideDims[1]<loadimg[0].offsetHeight?loadimg[0].offsetHeight:0;}
var showDims=[show.elm.getWidth(),show.elm.getHeight()];var scale=[(showDims[0]>0&&slideDims[0]>0?slideDims[0]/showDims[0]:1)*100,(showDims[1]>0&&slideDims[1]>0?slideDims[1]/showDims[1]:1)*100];show.effect=new Effect.Parallel([(scale[0]===100?new Effect.DoNothing():new Effect.Scale(show.elm,scale[0],{sync:true,scaleY:false,scaleContent:false})),(scale[1]===100?new Effect.DoNothing():new Effect.Scale(show.elm,scale[1],{sync:true,scaleX:false,scaleContent:false}))],{duration:1,queue:'FadeOutResizeFadeIn',afterFinish:function(){show.effect=new Effect.Appear(next,{duration:(opt.duration-1)/2});}});}});},cancel:function(show){if(show.effect){show.effect.cancel();}},prepare:function(show){var slideDims=[$(show.slides[0]).getWidth(),$(show.slides[0]).getHeight()];show.elm.setStyle({width:slideDims[0]+'px',height:slideDims[1]+'px'});show.slides.each(function(s,i){$(s).setStyle({opacity:(i===0?1:0),visibility:'visible'});});}};Crossfade.defaults={autoLoad:true,autoStart:true,random:false,randomClassName:'random',selectors:['.crossfade'],imageLoadSelector:'a.loadimage',ajaxLoadSelector:'a.load',interval:5,duration:2,transition:Crossfade.Transition.Crossfade};Crossfade.setup=function(options){Object.extend(Crossfade.defaults,options);};Crossfade.load=function(){if(Crossfade.defaults.autoLoad){Crossfade.defaults.selectors.each(function(s){$$(s).each(function(c){return new Crossfade(c);});});}};if(window.FastInit){FastInit.addOnLoad(Crossfade.load);}else{Event.observe(window,'load',Crossfade.load);}
OpenLayers={singleFile:true};(function(){var singleFile=(typeof OpenLayers=="object"&&OpenLayers.singleFile);OpenLayers={_scriptName:(!singleFile)?"lib/OpenLayers.js":"OpenLayers.js",_getScriptLocation:function(){var scriptLocation="";var scriptName=OpenLayers._scriptName;var scripts=document.getElementsByTagName('script');for(var i=0;i<scripts.length;i++){var src=scripts[i].getAttribute('src');if(src){var index=src.lastIndexOf(scriptName);if((index>-1)&&(index+scriptName.length==src.length)){scriptLocation=src.slice(0,-scriptName.length);break;}}}
return scriptLocation;}};if(!singleFile){var jsfiles=new Array("OpenLayers/Util.js","OpenLayers/BaseTypes.js","OpenLayers/BaseTypes/Class.js","OpenLayers/BaseTypes/Bounds.js","OpenLayers/BaseTypes/Element.js","OpenLayers/BaseTypes/LonLat.js","OpenLayers/BaseTypes/Pixel.js","OpenLayers/BaseTypes/Size.js","OpenLayers/Console.js","Rico/Corner.js","Rico/Color.js","OpenLayers/Ajax.js","OpenLayers/Events.js","OpenLayers/Map.js","OpenLayers/Layer.js","OpenLayers/Icon.js","OpenLayers/Marker.js","OpenLayers/Marker/Box.js","OpenLayers/Popup.js","OpenLayers/Tile.js","OpenLayers/Tile/Image.js","OpenLayers/Tile/WFS.js","OpenLayers/Layer/Image.js","OpenLayers/Layer/SphericalMercator.js","OpenLayers/Layer/EventPane.js","OpenLayers/Layer/FixedZoomLevels.js","OpenLayers/Layer/Google.js","OpenLayers/Layer/VirtualEarth.js","OpenLayers/Layer/Yahoo.js","OpenLayers/Layer/HTTPRequest.js","OpenLayers/Layer/Grid.js","OpenLayers/Layer/MapServer.js","OpenLayers/Layer/MapServer/Untiled.js","OpenLayers/Layer/KaMap.js","OpenLayers/Layer/MultiMap.js","OpenLayers/Layer/Markers.js","OpenLayers/Layer/Text.js","OpenLayers/Layer/WorldWind.js","OpenLayers/Layer/WMS.js","OpenLayers/Layer/WMS/Untiled.js","OpenLayers/Layer/GeoRSS.js","OpenLayers/Layer/Boxes.js","OpenLayers/Layer/TMS.js","OpenLayers/Layer/TileCache.js","OpenLayers/Popup/Anchored.js","OpenLayers/Popup/AnchoredBubble.js","OpenLayers/Feature.js","OpenLayers/Feature/Vector.js","OpenLayers/Feature/WFS.js","OpenLayers/Handler.js","OpenLayers/Handler/Point.js","OpenLayers/Handler/Path.js","OpenLayers/Handler/Polygon.js","OpenLayers/Handler/Feature.js","OpenLayers/Handler/Drag.js","OpenLayers/Handler/RegularPolygon.js","OpenLayers/Handler/Box.js","OpenLayers/Handler/MouseWheel.js","OpenLayers/Handler/Keyboard.js","OpenLayers/Control.js","OpenLayers/Control/Attribution.js","OpenLayers/Control/ZoomBox.js","OpenLayers/Control/ZoomToMaxExtent.js","OpenLayers/Control/DragPan.js","OpenLayers/Control/Navigation.js","OpenLayers/Control/MouseDefaults.js","OpenLayers/Control/MousePosition.js","OpenLayers/Control/OverviewMap.js","OpenLayers/Control/KeyboardDefaults.js","OpenLayers/Control/PanZoom.js","OpenLayers/Control/PanZoomBar.js","OpenLayers/Control/ArgParser.js","OpenLayers/Control/Permalink.js","OpenLayers/Control/Scale.js","OpenLayers/Control/LayerSwitcher.js","OpenLayers/Control/DrawFeature.js","OpenLayers/Control/DragFeature.js","OpenLayers/Control/ModifyFeature.js","OpenLayers/Control/Panel.js","OpenLayers/Control/SelectFeature.js","OpenLayers/Geometry.js","OpenLayers/Geometry/Rectangle.js","OpenLayers/Geometry/Collection.js","OpenLayers/Geometry/Point.js","OpenLayers/Geometry/MultiPoint.js","OpenLayers/Geometry/Curve.js","OpenLayers/Geometry/LineString.js","OpenLayers/Geometry/LinearRing.js","OpenLayers/Geometry/Polygon.js","OpenLayers/Geometry/MultiLineString.js","OpenLayers/Geometry/MultiPolygon.js","OpenLayers/Geometry/Surface.js","OpenLayers/Renderer.js","OpenLayers/Renderer/Elements.js","OpenLayers/Renderer/SVG.js","OpenLayers/Renderer/VML.js","OpenLayers/Layer/Vector.js","OpenLayers/Layer/GML.js","OpenLayers/Format.js","OpenLayers/Format/XML.js","OpenLayers/Format/GML.js","OpenLayers/Format/KML.js","OpenLayers/Format/GeoRSS.js","OpenLayers/Format/WFS.js","OpenLayers/Format/WKT.js","OpenLayers/Format/JSON.js","OpenLayers/Format/GeoJSON.js","OpenLayers/Layer/WFS.js","OpenLayers/Control/MouseToolbar.js","OpenLayers/Control/NavToolbar.js","OpenLayers/Control/EditingToolbar.js");var allScriptTags="";var host=OpenLayers._getScriptLocation()+"lib/";for(var i=0;i<jsfiles.length;i++){if(/MSIE/.test(navigator.userAgent)||/Safari/.test(navigator.userAgent)){var currentScriptTag="<script src='"+host+jsfiles[i]+"'></script>";allScriptTags+=currentScriptTag;}else{var s=document.createElement("script");s.src=host+jsfiles[i];var h=document.getElementsByTagName("head").length?document.getElementsByTagName("head")[0]:document.body;h.appendChild(s);}}
if(allScriptTags)document.write(allScriptTags);}})();OpenLayers.VERSION_NUMBER="$Revision: 4899 $";OpenLayers.String={startsWith:function(str,sub){return(str.indexOf(sub)==0);},contains:function(str,sub){return(str.indexOf(sub)!=-1);},trim:function(str){return str.replace(/^\s*(.*?)\s*$/,"$1");},camelize:function(str){var oStringList=str.split('-');var camelizedString=oStringList[0];for(var i=1;i<oStringList.length;i++){var s=oStringList[i];camelizedString+=s.charAt(0).toUpperCase()+s.substring(1);}
return camelizedString;}};if(!String.prototype.startsWith){String.prototype.startsWith=function(sStart){OpenLayers.Console.warn("This method has been deprecated and will be removed in 3.0. "+"Please use OpenLayers.String.startsWith instead");return OpenLayers.String.startsWith(this,sStart);};}
if(!String.prototype.contains){String.prototype.contains=function(str){OpenLayers.Console.warn("This method has been deprecated and will be removed in 3.0. "+"Please use OpenLayers.String.contains instead");return OpenLayers.String.contains(this,str);};}
if(!String.prototype.trim){String.prototype.trim=function(){OpenLayers.Console.warn("This method has been deprecated and will be removed in 3.0. "+"Please use OpenLayers.String.trim instead");return OpenLayers.String.trim(this);};}
if(!String.prototype.camelize){String.prototype.camelize=function(){OpenLayers.Console.warn("This method has been deprecated and will be removed in 3.0. "+"Please use OpenLayers.String.camelize instead");return OpenLayers.String.camelize(this);};}
OpenLayers.Number={limitSigDigs:function(num,sig){var fig;if(sig>0){fig=parseFloat(num.toPrecision(sig));}else{fig=0;}
return fig;}};if(!Number.prototype.limitSigDigs){Number.prototype.limitSigDigs=function(sig){OpenLayers.Console.warn("This method has been deprecated and will be removed in 3.0. "+"Please use OpenLayers.Number.limitSigDigs instead");return OpenLayers.Number.limitSigDigs(this,sig);};}
OpenLayers.Function={bind:function(func,object){var args=Array.prototype.slice.apply(arguments,[2]);return function(){var newArgs=args.concat(Array.prototype.slice.apply(arguments,[0]));return func.apply(object,newArgs);};},bindAsEventListener:function(func,object){return function(event){return func.call(object,event||window.event);};}};if(!Function.prototype.bind){Function.prototype.bind=function(){OpenLayers.Console.warn("This method has been deprecated and will be removed in 3.0. "+"Please use OpenLayers.Function.bind instead");Array.prototype.unshift.apply(arguments,[this]);return OpenLayers.Function.bind.apply(null,arguments);};}
if(!Function.prototype.bindAsEventListener){Function.prototype.bindAsEventListener=function(object){OpenLayers.Console.warn("This method has been deprecated and will be removed in 3.0. "+"Please use OpenLayers.Function.bindAsEventListener instead");return OpenLayers.Function.bindAsEventListener(this,object);};}
OpenLayers.Class=function(){var Class=function(){if(arguments&&arguments[0]!=OpenLayers.Class.isPrototype){this.initialize.apply(this,arguments);}}
var extended={};var parent;for(var i=0;i<arguments.length;++i){if(typeof arguments[i]=="function"){parent=arguments[i].prototype;}else{parent=arguments[i];}
OpenLayers.Util.extend(extended,parent);}
Class.prototype=extended;return Class;}
OpenLayers.Class.isPrototype=function(){};OpenLayers.Class.create=function(){return function(){if(arguments&&arguments[0]!=OpenLayers.Class.isPrototype)
this.initialize.apply(this,arguments);}}
OpenLayers.Class.inherit=function(){var superClass=arguments[0];var proto=new superClass(OpenLayers.Class.isPrototype);for(var i=1;i<arguments.length;i++){if(typeof arguments[i]=="function"){var mixin=arguments[i];arguments[i]=new mixin(OpenLayers.Class.isPrototype);}
OpenLayers.Util.extend(proto,arguments[i]);}
return proto;}
OpenLayers.Util={};OpenLayers.Util.getElement=function(){var elements=[];for(var i=0;i<arguments.length;i++){var element=arguments[i];if(typeof element=='string'){element=document.getElementById(element);}
if(arguments.length==1){return element;}
elements.push(element);}
return elements;};if($==null){var $=OpenLayers.Util.getElement;}
OpenLayers.Util.extend=function(destination,source){if(destination&&source){for(var property in source){destination[property]=source[property];}
if(source.hasOwnProperty&&source.hasOwnProperty('toString')){destination.toString=source.toString;}}
return destination;};OpenLayers.Util.removeItem=function(array,item){for(var i=0;i<array.length;i++){if(array[i]==item){array.splice(i,1);}}
return array;};OpenLayers.Util.clearArray=function(array){var msg="OpenLayers.Util.clearArray() is Deprecated."+" Please use 'array.length = 0' instead.";OpenLayers.Console.warn(msg);array.length=0;};OpenLayers.Util.indexOf=function(array,obj){for(var i=0;i<array.length;i++){if(array[i]==obj)return i;}
return-1;};OpenLayers.Util.modifyDOMElement=function(element,id,px,sz,position,border,overflow,opacity){if(id){element.id=id;}
if(px){element.style.left=px.x+"px";element.style.top=px.y+"px";}
if(sz){element.style.width=sz.w+"px";element.style.height=sz.h+"px";}
if(position){element.style.position=position;}
if(border){element.style.border=border;}
if(overflow){element.style.overflow=overflow;}
if(typeof opacity!="undefined"&&opacity!=null){element.style.opacity=opacity;element.style.filter='alpha(opacity='+(opacity*100)+')';}};OpenLayers.Util.createDiv=function(id,px,sz,imgURL,position,border,overflow,opacity){var dom=document.createElement('div');if(imgURL){dom.style.backgroundImage='url('+imgURL+')';}
if(!id){id=OpenLayers.Util.createUniqueID("OpenLayersDiv");}
if(!position){position="absolute";}
OpenLayers.Util.modifyDOMElement(dom,id,px,sz,position,border,overflow,opacity);return dom;};OpenLayers.Util.createImage=function(id,px,sz,imgURL,position,border,opacity,delayDisplay){var image=document.createElement("img");if(!id){id=OpenLayers.Util.createUniqueID("OpenLayersDiv");}
if(!position){position="relative";}
OpenLayers.Util.modifyDOMElement(image,id,px,sz,position,border,null,opacity);if(delayDisplay){image.style.display="none";OpenLayers.Event.observe(image,"load",OpenLayers.Function.bind(OpenLayers.Util.onImageLoad,image));OpenLayers.Event.observe(image,"error",OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError,image));}
image.style.alt=id;image.galleryImg="no";if(imgURL){image.src=imgURL;}
return image;};OpenLayers.Util.setOpacity=function(element,opacity){OpenLayers.Util.modifyDOMElement(element,null,null,null,null,null,null,opacity);}
OpenLayers.Util.onImageLoad=function(){if(!this.viewRequestID||(this.map&&this.viewRequestID==this.map.viewRequestID)){this.style.backgroundColor=null;this.style.display="";}};OpenLayers.Util.onImageLoadErrorColor="pink";OpenLayers.IMAGE_RELOAD_ATTEMPTS=0;OpenLayers.Util.onImageLoadError=function(){this._attempts=(this._attempts)?(this._attempts+1):1;if(this._attempts<=OpenLayers.IMAGE_RELOAD_ATTEMPTS){this.originalSrc=this.src;this.src="images/a_pixel.gif";var that=this;window.setTimeout(function(){that.src=that.originalSrc},300);}
else{this.style.visibility="hidden";this.style.backgroundColor=OpenLayers.Util.onImageLoadErrorColor;}
this.style.display="";};OpenLayers.Util.alphaHack=function(){var arVersion=navigator.appVersion.split("MSIE");var version=parseFloat(arVersion[1]);var filter=false;try{filter=document.body.filters;}catch(e){}
return(filter&&(version>=5.5)&&(version<7));}
OpenLayers.Util.modifyAlphaImageDiv=function(div,id,px,sz,imgURL,position,border,sizing,opacity){OpenLayers.Util.modifyDOMElement(div,id,px,sz);var img=div.childNodes[0];if(imgURL){img.src=imgURL;}
OpenLayers.Util.modifyDOMElement(img,div.id+"_innerImage",null,sz,"relative",border);if(typeof opacity!="undefined"&&opacity!=null){div.style.opacity=opacity;div.style.filter='alpha(opacity='+(opacity*100)+')';}
if(OpenLayers.Util.alphaHack()){div.style.display="inline-block";if(sizing==null){sizing="scale";}
div.style.filter="progid:DXImageTransform.Microsoft"+".AlphaImageLoader(src='"+img.src+"', "+"sizingMethod='"+sizing+"')";if(typeof div.style.opacity!="undefined"&&div.style.opacity!=null){div.style.filter+=" alpha(opacity="+div.style.opacity*100+")";}
img.style.filter="progid:DXImageTransform.Microsoft"+".Alpha(opacity=0)";}};OpenLayers.Util.createAlphaImageDiv=function(id,px,sz,imgURL,position,border,sizing,opacity,delayDisplay){var div=OpenLayers.Util.createDiv();var img=OpenLayers.Util.createImage(null,null,null,null,null,null,null,false);div.appendChild(img);if(delayDisplay){img.style.display="none";OpenLayers.Event.observe(img,"load",OpenLayers.Function.bind(OpenLayers.Util.onImageLoad,div));OpenLayers.Event.observe(img,"error",OpenLayers.Function.bind(OpenLayers.Util.onImageLoadError,div));}
OpenLayers.Util.modifyAlphaImageDiv(div,id,px,sz,imgURL,position,border,sizing,opacity);return div;};OpenLayers.Util.upperCaseObject=function(object){var uObject={};for(var key in object){uObject[key.toUpperCase()]=object[key];}
return uObject;};OpenLayers.Util.applyDefaults=function(to,from){for(var key in from){if(to[key]==null){to[key]=from[key];}}};OpenLayers.Util.getParameterString=function(params){paramsArray=[];for(var key in params){var value=params[key];if((value!=null)&&(typeof value!='function')){var encodedValue;if(typeof value=='object'&&value.constructor==Array){var encodedItemArray=[];for(var itemIndex=0;itemIndex<value.length;itemIndex++){encodedItemArray.push(encodeURIComponent(value[itemIndex]));}
encodedValue=encodedItemArray.join(",");}
else{encodedValue=encodeURIComponent(value);}
paramsArray.push(encodeURIComponent(key)+"="+encodedValue);}}
return paramsArray.join("&");};OpenLayers.ImgPath='';OpenLayers.Util.getImagesLocation=function(){return OpenLayers.ImgPath||(OpenLayers._getScriptLocation()+"img/");};OpenLayers.Util.Try=function(){var returnValue=null;for(var i=0;i<arguments.length;i++){var lambda=arguments[i];try{returnValue=lambda();break;}catch(e){}}
return returnValue;}
OpenLayers.Util.getNodes=function(p,tagName){var nodes=OpenLayers.Util.Try(function(){return OpenLayers.Util._getNodes(p.documentElement.childNodes,tagName);},function(){return OpenLayers.Util._getNodes(p.childNodes,tagName);});return nodes;};OpenLayers.Util._getNodes=function(nodes,tagName){var retArray=[];for(var i=0;i<nodes.length;i++){if(nodes[i].nodeName==tagName){retArray.push(nodes[i]);}}
return retArray;};OpenLayers.Util.getTagText=function(parent,item,index){var result=OpenLayers.Util.getNodes(parent,item);if(result&&(result.length>0))
{if(!index){index=0;}
if(result[index].childNodes.length>1){return result.childNodes[1].nodeValue;}
else if(result[index].childNodes.length==1){return result[index].firstChild.nodeValue;}}else{return"";}};OpenLayers.Util.getXmlNodeValue=function(node){var val=null;OpenLayers.Util.Try(function(){val=node.text;if(!val)
val=node.textContent;if(!val)
val=node.firstChild.nodeValue;},function(){val=node.textContent;});return val;};OpenLayers.Util.mouseLeft=function(evt,div){var target=(evt.relatedTarget)?evt.relatedTarget:evt.toElement;while(target!=div&&target!=null){target=target.parentNode;}
return(target!=div);};OpenLayers.Util.rad=function(x){return x*Math.PI/180;};OpenLayers.Util.distVincenty=function(p1,p2){var a=6378137,b=6356752.3142,f=1/298.257223563;var L=OpenLayers.Util.rad(p2.lon-p1.lon);var U1=Math.atan((1-f)*Math.tan(OpenLayers.Util.rad(p1.lat)));var U2=Math.atan((1-f)*Math.tan(OpenLayers.Util.rad(p2.lat)));var sinU1=Math.sin(U1),cosU1=Math.cos(U1);var sinU2=Math.sin(U2),cosU2=Math.cos(U2);var lambda=L,lambdaP=2*Math.PI;var iterLimit=20;while(Math.abs(lambda-lambdaP)>1e-12&&--iterLimit>0){var sinLambda=Math.sin(lambda),cosLambda=Math.cos(lambda);var sinSigma=Math.sqrt((cosU2*sinLambda)*(cosU2*sinLambda)+
(cosU1*sinU2-sinU1*cosU2*cosLambda)*(cosU1*sinU2-sinU1*cosU2*cosLambda));if(sinSigma==0)return 0;var cosSigma=sinU1*sinU2+cosU1*cosU2*cosLambda;var sigma=Math.atan2(sinSigma,cosSigma);var alpha=Math.asin(cosU1*cosU2*sinLambda/sinSigma);var cosSqAlpha=Math.cos(alpha)*Math.cos(alpha);var cos2SigmaM=cosSigma-2*sinU1*sinU2/cosSqAlpha;var C=f/16*cosSqAlpha*(4+f*(4-3*cosSqAlpha));lambdaP=lambda;lambda=L+(1-C)*f*Math.sin(alpha)*(sigma+C*sinSigma*(cos2SigmaM+C*cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)));}
if(iterLimit==0)return NaN
var uSq=cosSqAlpha*(a*a-b*b)/(b*b);var A=1+uSq/16384*(4096+uSq*(-768+uSq*(320-175*uSq)));var B=uSq/1024*(256+uSq*(-128+uSq*(74-47*uSq)));var deltaSigma=B*sinSigma*(cos2SigmaM+B/4*(cosSigma*(-1+2*cos2SigmaM*cos2SigmaM)-
B/6*cos2SigmaM*(-3+4*sinSigma*sinSigma)*(-3+4*cos2SigmaM*cos2SigmaM)));var s=b*A*(sigma-deltaSigma);var d=s.toFixed(3)/1000;return d;};OpenLayers.Util.getParameters=function(url){url=url||window.location.href
if(url==null){url=window.location.href;}
var paramsString="";if(OpenLayers.String.contains(url,'?')){var start=url.indexOf('?')+1;var end=OpenLayers.String.contains(url,"#")?url.indexOf('#'):url.length;paramsString=url.substring(start,end);}
var parameters={};var pairs=paramsString.split(/[&;]/);for(var i=0;i<pairs.length;++i){var keyValue=pairs[i].split('=');if(keyValue[0]){var key=decodeURIComponent(keyValue[0]);var value=keyValue[1]||'';value=value.split(",");for(var j=0;j<value.length;j++){value[j]=decodeURIComponent(value[j]);}
if(value.length==1){value=value[0];}
parameters[key]=value;}}
return parameters;};OpenLayers.Util.getArgs=function(url){var err="The getArgs() function is deprecated and will be removed "+"with the 3.0 version of OpenLayers. Please instead use "+"OpenLayers.Util.getParameters().";OpenLayers.Console.warn(err);return OpenLayers.Util.getParameters(url);};OpenLayers.Util.lastSeqID=0;OpenLayers.Util.createUniqueID=function(prefix){if(prefix==null){prefix="id_";}
OpenLayers.Util.lastSeqID+=1;return prefix+OpenLayers.Util.lastSeqID;};OpenLayers.INCHES_PER_UNIT={'inches':1.0,'ft':12.0,'mi':63360.0,'m':39.3701,'km':39370.1,'dd':4374754};OpenLayers.INCHES_PER_UNIT["in"]=OpenLayers.INCHES_PER_UNIT.inches;OpenLayers.INCHES_PER_UNIT["degrees"]=OpenLayers.INCHES_PER_UNIT.dd;OpenLayers.DOTS_PER_INCH=72;OpenLayers.Util.normalizeScale=function(scale){var normScale=(scale>1.0)?(1.0/scale):scale;return normScale;};OpenLayers.Util.getResolutionFromScale=function(scale,units){if(units==null){units="degrees";}
var normScale=OpenLayers.Util.normalizeScale(scale);var resolution=1/(normScale*OpenLayers.INCHES_PER_UNIT[units]*OpenLayers.DOTS_PER_INCH);return resolution;};OpenLayers.Util.getScaleFromResolution=function(resolution,units){if(units==null){units="degrees";}
var scale=resolution*OpenLayers.INCHES_PER_UNIT[units]*OpenLayers.DOTS_PER_INCH;return Math.round(scale);};OpenLayers.Util.safeStopPropagation=function(evt){OpenLayers.Event.stop(evt,true);};OpenLayers.Util.pagePosition=function(forElement){var valueT=0,valueL=0;var element=forElement;var child=forElement;while(element){if(element==document.body){if(child&&child.style&&OpenLayers.Element.getStyle(child,'position')=='absolute'){break;}}
valueT+=element.offsetTop||0;valueL+=element.offsetLeft||0;child=element;try{element=element.offsetParent;}catch(e){OpenLayers.Console.error("OpenLayers.Util.pagePosition failed: element with id "+
element.id+" may be misplaced.");break;}}
element=forElement;while(element){valueT-=element.scrollTop||0;valueL-=element.scrollLeft||0;element=element.parentNode;}
return[valueL,valueT];};OpenLayers.Util.isEquivalentUrl=function(url1,url2,options){options=options||{};OpenLayers.Util.applyDefaults(options,{ignoreCase:true,ignorePort80:true,ignoreHash:true});urlObj1=OpenLayers.Util.createUrlObject(url1,options);urlObj2=OpenLayers.Util.createUrlObject(url2,options);for(var key in urlObj1){if(options.test){alert(key+"\n1:"+urlObj1[key]+"\n2:"+urlObj2[key]);}
var val1=urlObj1[key];var val2=urlObj2[key];switch(key){case"args":break;case"host":case"port":case"protocol":if((val1=="")||(val2=="")){break;}
default:if((key!="args")&&(urlObj1[key]!=urlObj2[key])){return false;}
break;}}
for(var key in urlObj1.args){if(urlObj1.args[key]!=urlObj2.args[key]){return false;}
delete urlObj2.args[key];}
for(var key in urlObj2.args){return false;}
return true;};OpenLayers.Util.createUrlObject=function(url,options){options=options||{};var urlObject={};if(options.ignoreCase){url=url.toLowerCase();}
var a=document.createElement('a');a.href=url;urlObject.host=a.host;var port=a.port;if(port.length<=0){var newHostLength=urlObject.host.length-(port.length);urlObject.host=urlObject.host.substring(0,newHostLength);}
urlObject.protocol=a.protocol;urlObject.port=((port=="80")&&(options.ignorePort80))?"":port;urlObject.hash=(options.ignoreHash)?"":a.hash;var queryString=a.search;if(!queryString){var qMark=url.indexOf("?");queryString=(qMark!=-1)?url.substr(qMark):"";}
urlObject.args=OpenLayers.Util.getParameters(queryString);if(((urlObject.protocol=="file:")&&(url.indexOf("file:")!=-1))||((urlObject.protocol!="file:")&&(urlObject.host!=""))){urlObject.pathname=a.pathname;var qIndex=urlObject.pathname.indexOf("?");if(qIndex!=-1){urlObject.pathname=urlObject.pathname.substring(0,qIndex);}}else{var relStr=OpenLayers.Util.removeTail(url);var backs=0;do{var index=relStr.indexOf("../");if(index==0){backs++
relStr=relStr.substr(3);}else if(index>=0){var prevChunk=relStr.substr(0,index-1);var slash=prevChunk.indexOf("/");prevChunk=(slash!=-1)?prevChunk.substr(0,slash+1):"";var postChunk=relStr.substr(index+3);relStr=prevChunk+postChunk;}}while(index!=-1)
var windowAnchor=document.createElement("a");var windowUrl=window.location.href;if(options.ignoreCase){windowUrl=windowUrl.toLowerCase();}
windowAnchor.href=windowUrl;urlObject.protocol=windowAnchor.protocol;var splitter=(windowAnchor.pathname.indexOf("/")!=-1)?"/":"\\";var dirs=windowAnchor.pathname.split(splitter);dirs.pop();while((backs>0)&&(dirs.length>0)){dirs.pop();backs--;}
relStr=dirs.join("/")+"/"+relStr;urlObject.pathname=relStr;}
if((urlObject.protocol=="file:")||(urlObject.protocol=="")){urlObject.host="localhost";}
return urlObject;};OpenLayers.Util.removeTail=function(url){var head=null;var qMark=url.indexOf("?");var hashMark=url.indexOf("#");if(qMark==-1){head=(hashMark!=-1)?url.substr(0,hashMark):url;}else{head=(hashMark!=-1)?url.substr(0,Math.min(qMark,hashMark)):url.substr(0,qMark);}
return head;};OpenLayers.Util.getBrowserName=function(){var browserName="";var ua=navigator.userAgent.toLowerCase();if(ua.indexOf("opera")!=-1){browserName="opera";}else if(ua.indexOf("msie")!=-1){browserName="msie";}else if(ua.indexOf("safari")!=-1){browserName="safari";}else if(ua.indexOf("mozilla")!=-1){if(ua.indexOf("firefox")!=-1){browserName="firefox";}else{browserName="mozilla";}}
return browserName;};OpenLayers.Popup=OpenLayers.Class({events:null,id:"",lonlat:null,div:null,size:null,contentHTML:"",backgroundColor:"",opacity:"",border:"",contentDiv:null,groupDiv:null,padding:5,map:null,initialize:function(id,lonlat,size,contentHTML,closeBox){if(id==null){id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");}
this.id=id;this.lonlat=lonlat;this.size=(size!=null)?size:new OpenLayers.Size(OpenLayers.Popup.WIDTH,OpenLayers.Popup.HEIGHT);if(contentHTML!=null){this.contentHTML=contentHTML;}
this.backgroundColor=OpenLayers.Popup.COLOR;this.opacity=OpenLayers.Popup.OPACITY;this.border=OpenLayers.Popup.BORDER;this.div=OpenLayers.Util.createDiv(this.id,null,null,null,null,null,"hidden");this.div.className='olPopup';this.groupDiv=OpenLayers.Util.createDiv(null,null,null,null,"relative",null,"hidden");var id=this.div.id+"_contentDiv";this.contentDiv=OpenLayers.Util.createDiv(id,null,this.size.clone(),null,"relative",null,"hidden");this.contentDiv.className='olPopupContent';this.groupDiv.appendChild(this.contentDiv);this.div.appendChild(this.groupDiv);if(closeBox){var closeSize=new OpenLayers.Size(17,17);var img=OpenLayers.Util.getImagesLocation()+"close.gif";var closeImg=OpenLayers.Util.createAlphaImageDiv(this.id+"_close",null,closeSize,img);closeImg.style.right=this.padding+"px";closeImg.style.top=this.padding+"px";this.groupDiv.appendChild(closeImg);var closePopup=function(e){this.hide();OpenLayers.Event.stop(e);}
OpenLayers.Event.observe(closeImg,"click",OpenLayers.Function.bindAsEventListener(closePopup,this));}
this.registerEvents();},destroy:function(){if(this.map!=null){this.map.removePopup(this);this.map=null;}
this.events.destroy();this.events=null;this.div=null;},draw:function(px){if(px==null){if((this.lonlat!=null)&&(this.map!=null)){px=this.map.getLayerPxFromLonLat(this.lonlat);}}
this.setSize();this.setBackgroundColor();this.setOpacity();this.setBorder();this.setContentHTML();this.moveTo(px);return this.div;},updatePosition:function(){if((this.lonlat)&&(this.map)){var px=this.map.getLayerPxFromLonLat(this.lonlat);if(px){this.moveTo(px);}}},moveTo:function(px){if((px!=null)&&(this.div!=null)){this.div.style.left=px.x+"px";this.div.style.top=px.y+"px";}},visible:function(){return OpenLayers.Element.visible(this.div);},toggle:function(){OpenLayers.Element.toggle(this.div);},show:function(){OpenLayers.Element.show(this.div);},hide:function(){OpenLayers.Element.hide(this.div);},setSize:function(size){if(size!=undefined){this.size=size;}
if(this.div!=null){this.div.style.width=this.size.w+"px";this.div.style.height=this.size.h+"px";}
if(this.contentDiv!=null){this.contentDiv.style.width=this.size.w+"px";this.contentDiv.style.height=this.size.h+"px";}},setBackgroundColor:function(color){if(color!=undefined){this.backgroundColor=color;}
if(this.div!=null){this.div.style.backgroundColor=this.backgroundColor;}},setOpacity:function(opacity){if(opacity!=undefined){this.opacity=opacity;}
if(this.div!=null){this.div.style.opacity=this.opacity;this.div.style.filter='alpha(opacity='+this.opacity*100+')';}},setBorder:function(border){if(border!=undefined){this.border=border;}
if(this.div!=null){this.div.style.border=this.border;}},setContentHTML:function(contentHTML){if(contentHTML!=null){this.contentHTML=contentHTML;}
if(this.contentDiv!=null){this.contentDiv.innerHTML=this.contentHTML;}},registerEvents:function(){this.events=new OpenLayers.Events(this,this.div,null,true);this.events.register("mousedown",this,this.onmousedown);this.events.register("mousemove",this,this.onmousemove);this.events.register("mouseup",this,this.onmouseup);this.events.register("click",this,this.onclick);this.events.register("mouseout",this,this.onmouseout);this.events.register("dblclick",this,this.ondblclick);},onmousedown:function(evt){this.mousedown=true;OpenLayers.Event.stop(evt,true);},onmousemove:function(evt){if(this.mousedown){OpenLayers.Event.stop(evt,true);}},onmouseup:function(evt){if(this.mousedown){this.mousedown=false;OpenLayers.Event.stop(evt,true);}},onclick:function(evt){OpenLayers.Event.stop(evt,true);},onmouseout:function(evt){this.mousedown=false;},ondblclick:function(evt){OpenLayers.Event.stop(evt,true);},CLASS_NAME:"OpenLayers.Popup"});OpenLayers.Popup.WIDTH=200;OpenLayers.Popup.HEIGHT=200;OpenLayers.Popup.COLOR="white";OpenLayers.Popup.OPACITY=1;OpenLayers.Popup.BORDER="0px";OpenLayers.Control=OpenLayers.Class({id:null,map:null,div:null,type:null,displayClass:"",active:null,handler:null,initialize:function(options){this.displayClass=this.CLASS_NAME.replace("OpenLayers.","ol").replace(/\./g,"");OpenLayers.Util.extend(this,options);this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},destroy:function(){if(this.handler){this.handler.destroy();}
this.map=null;},setMap:function(map){this.map=map;if(this.handler){this.handler.setMap(map);}},draw:function(px){if(this.div==null){this.div=OpenLayers.Util.createDiv();this.div.id=this.id;this.div.className=this.displayClass;}
if(px!=null){this.position=px.clone();}
this.moveTo(this.position);return this.div;},moveTo:function(px){if((px!=null)&&(this.div!=null)){this.div.style.left=px.x+"px";this.div.style.top=px.y+"px";}},activate:function(){if(this.active){return false;}
if(this.handler){this.handler.activate();}
this.active=true;return true;},deactivate:function(){if(this.active){if(this.handler){this.handler.deactivate();}
this.active=false;return true;}
return false;},CLASS_NAME:"OpenLayers.Control"});OpenLayers.Control.TYPE_BUTTON=1;OpenLayers.Control.TYPE_TOGGLE=2;OpenLayers.Control.TYPE_TOOL=3;var foundLocationsListArray=new Array();var generatedMap=null;var mapDefinitionList=null;var currImgFormat=0;var currWithCopyright=true;var pinLogoList=new Array();var polylinesList=new Array();var numericCriteriaList=new Array();var pixelPointList=new Array();var mapActionList=new Array();var inputPOIList=new Array();var inputAddressList=new Array();var geoCoordinatesList=new Array();var categoryList=new Array();var ititraceList=null;function Cost(price,currency){this.price=price;this.currency=currency;};function ItineraryPreferences(favourMotorways,avoidCrossingBorders,avoidTolls,avoidRoadTaxAreas,avoidOffroadConnections,avoidMountainPass){this.favourMotorways=favourMotorways;this.avoidCrossingBorders=avoidCrossingBorders;this.avoidTolls=avoidTolls;this.avoidRoadTaxAreas=avoidRoadTaxAreas;this.avoidOffroadConnections=avoidOffroadConnections;;this.avoidMountainPass=avoidMountainPass;};function ItineraryOptions(itiDate,vehicleType,itiType,itiPref,fuelCost,fuelConsumption){this.itiDate=itiDate;this.vehicleType=vehicleType;this.itiType=itiType;this.itiPref=itiPref;this.fuelCost=fuelCost;this.fuelConsumption=fuelConsumption;};function ExtendedPresentationOptions(detailLevel,language,instructionsFormat,tollCategory){this.detailLevel=detailLevel;this.language=language;this.instructionsFormat=instructionsFormat;this.tollCategory=tollCategory;};function ResponseOptions(responseElts,mapDefCalc,mainMapWidth,mainMapHeight,blocMapWidth,blocMapHeight){this.responseElts=responseElts;this.mapDefCalc=mapDefCalc;this.mainMapWidth=mainMapWidth;this.mainMapHeight=mainMapHeight;this.blocMapWidth=blocMapWidth;this.blocMapHeight=blocMapHeight;};function ItineraryRequest(locDefList,itiOptions,presentationOptions,responseOptions){this.locDefList=locDefList;this.itiOptions=itiOptions;this.presentationOptions=presentationOptions;this.responseOptions=responseOptions;};function DecodeItineraryTraceRequest(itiTrace,range){this.itiTrace=itiTrace;this.range=range;};function NumericCriteria(criteriaKey,criteriaValue,compOp){this.key=criteriaKey;this.val=criteriaValue;this.compOp=compOp;};function InputPOI(id,lat,lon){this.id=id;this.coord=new GeoCoordinates(lon,lat);};function InputAddress(address,cityName,stateName,postalCode,countryCode){this.address=address;this.cityName=cityName;this.countryCode=countryCode;this.postalCode=postalCode;this.stateName=stateName;};function MapDefinitionByID(MapId,MapWidth,MapHeight){this.MapId=MapId;this.MapWidth=MapWidth;this.MapHeight=MapHeight;};function MapDefinitionByScale(psize,center,MapWidth,MapHeight){this.psize=psize;this.center=center;this.MapWidth=MapWidth;this.MapHeight=MapHeight;};function MapDefinitionByRect(northWestPoint,southEastPoint,MapWidth,MapHeight){this.MapWidth=MapWidth;this.MapHeight=MapHeight;this.northWestPoint=northWestPoint;this.southEastPoint=southEastPoint;};function MapDefinitionList(byId,byRect,byScale){this.byId=byId;this.byRect=byRect;this.byScale=byScale;};function GeneratedMap(mapURL,copyright,mapDefinitions){this.mapURL=mapURL;this.copyright=copyright;this.mapDefinitions=mapDefinitions;this.zoomout=function anonymous(){var omapActionList=new Array();var mapAction=new MapAction(3,0);omapActionList[omapActionList.length]=mapAction;mapManagement_getMapByID(this.mapDefinitions.byId.MapId,this.mapDefinitions.byId.MapWidth,this.mapDefinitions.byId.MapHeight,omapActionList,currImgFormat,currWithCopyright,pinLogoList,polylinesList,ititraceList);};this.zoomin=function anonymous(){var omapActionList=new Array();var mapAction=new MapAction(2,0);omapActionList[omapActionList.length]=mapAction;mapManagement_getMapByID(this.mapDefinitions.byId.MapId,this.mapDefinitions.byId.MapWidth,this.mapDefinitions.byId.MapHeight,omapActionList,currImgFormat,currWithCopyright,pinLogoList,polylinesList,ititraceList);};this.move=function anonymous(dir){var omapActionList=new Array();var mapAction=null;if(dir==1){mapAction=new MapAction(0,0.5);omapActionList[omapActionList.length]=mapAction;}else if(dir==2){mapAction=new MapAction(0,0.5);omapActionList[omapActionList.length]=mapAction;mapAction=new MapAction(1,0.5);omapActionList[omapActionList.length]=mapAction;}else if(dir==3){mapAction=new MapAction(1,0.5);omapActionList[omapActionList.length]=mapAction;}else if(dir==4){mapAction=new MapAction(0,-0.5);omapActionList[omapActionList.length]=mapAction;mapAction=new MapAction(1,0.5);omapActionList[omapActionList.length]=mapAction;}else if(dir==5){mapAction=new MapAction(0,-0.5);omapActionList[omapActionList.length]=mapAction;}else if(dir==6){mapAction=new MapAction(0,-0.5);omapActionList[omapActionList.length]=mapAction;mapAction=new MapAction(1,-0.5);omapActionList[omapActionList.length]=mapAction;}else if(dir==7){mapAction=new MapAction(1,-0.5);omapActionList[omapActionList.length]=mapAction;}else if(dir==8){mapAction=new MapAction(0,0.5);omapActionList[omapActionList.length]=mapAction;mapAction=new MapAction(1,-0.5);omapActionList[omapActionList.length]=mapAction;}
mapManagement_getMapByID(this.mapDefinitions.byId.MapId,this.mapDefinitions.byId.MapWidth,this.mapDefinitions.byId.MapHeight,omapActionList,currImgFormat,currWithCopyright,pinLogoList,polylinesList,ititraceList);};this.setPixelSize=function anonymous(newPs){genMapByScale(newPs,this.mapDefinitions.byScale.center,this.mapDefinitions.byScale.MapWidth,this.mapDefinitions.byScale.MapHeight,null,currImgFormat,currWithCopyright,pinLogoList,polylinesList,ititraceList);};this.resize=function anonymous(x0,y0,x1,y1){var newPs=this.mapDefinitions.byScale.psize;if(parseInt(x1)==parseInt(x0)){newPs=this.mapDefinitions.byScale.psize;}else if(parseInt(x1)>parseInt(x0)){newPs=this.mapDefinitions.byScale.psize*((parseInt(x1)-parseInt(x0))/this.mapDefinitions.byScale.MapWidth);}else{newPs=this.mapDefinitions.byScale.psize*((parseInt(x0)-parseInt(x1))/this.mapDefinitions.byScale.MapWidth);}
var x=parseInt((parseInt(x0)+parseInt(x1))/2);var y=parseInt((parseInt(y0)+parseInt(y1))/2);var pixelPoint=new PixelPoint(x,y);var pixelsList=new Array();pixelsList[pixelsList.length]=pixelPoint;var geoCoordinatesList=mapManagement_pixelsToXY(this.mapDefinitions.byId,null,pixelsList);var newcenter=geoCoordinatesList[0];genMapByScale(newPs,newcenter,this.mapDefinitions.byScale.MapWidth,this.mapDefinitions.byScale.MapHeight,null,currImgFormat,currWithCopyright,pinLogoList,polylinesList,ititraceList);};};function FoundLocationFormat(order,bPhoto,bAddr,bAddrDetail,bMetanum,bMetaStr,bDescLst,bCatLst,datasheetContent,language){this.order=order;this.bPhoto=bPhoto;this.bAddr=bAddr;this.bAddrDetail=bAddrDetail;this.bMetanum=bMetanum;this.bMetaStr=bMetaStr;this.bDescLst=bDescLst;this.bCatLst=bCatLst;this.datasheetContent=datasheetContent;this.language=language;};function KeyValuePair(key,val){this.key=key;this.val=val;};function POI(poiDB,poilang,poiID,poiName,poiDatasheet,metanumList,metastringList,descriptionList,categories,photos){this.poiDB=poiDB;this.poilang=poilang;this.poiID=poiID;this.poiName=poiName;this.poiDatasheet=poiDatasheet;this.metanumList=metanumList;this.metastringList=metastringList;this.descriptionList=descriptionList;this.categories=categories;this.photos=photos;};function CoherenceDegreeInfo(streetCoherence,cityCoherence){this.streetCoherence=streetCoherence;this.cityCoherence=cityCoherence;};function AddressDetails(city,countryCode,countryLabel,district,gathering,officialCountryCode,state,streetLabel,streetNumber,zipCode){this.city=city;this.countryCode=countryCode;this.countryLabel=countryLabel;this.district=district;this.gathering=gathering;this.officialCountryCode=officialCountryCode;this.state=state;this.streetLabel=streetLabel;this.streetNumber=streetNumber;this.zipCode=zipCode;};function Address(coherenceDegreeInfo,formattedCityLine,formattedStreetLine,details){this.coherenceDegreeInfo=coherenceDegreeInfo;this.formattedCityLine=formattedCityLine;this.formattedStreetLine=formattedStreetLine;this.details=details;};function PixelPoint(x,y){this.x=x;this.y=y;};function GeoCoordinates(lon,lat){this.lat=lat;this.lon=lon;};function Location(locid,locType,geoCoord,address,poi){this.locid=locid;this.locationType=locType;this.geoCoord=geoCoord;this.address=address;this.poi=poi;};function FoundLocation(distance,duration,locDesc){this.distance=distance;this.duration=duration;this.locDesc=locDesc;};function FoundLocationList(searchStatus,size,foundLocations){this.searchStatus=searchStatus;this.size=size;this.foundLocations=foundLocations;};function PoiID(id,dbId,lang){this.id=id;this.dbId=dbId;this.lang=lang;};function LocDefinition(coord,locID,poiID){this.coord=coord;this.locID=locID;this.poiID=poiID;};function MapAction(type,value){this.type=type;this.value=value;};function InputTrace(color,thickness,pixelPointList,geoCoordinatesList){this.color=color;this.thickness=thickness;this.pixelPointList=pixelPointList;this.geoCoordinatesList=geoCoordinatesList;};function PinLogo(id,pixelPos,coord,displayMode,IconName,IconWidth,IconHeight,hotArea){this.id=id;this.pixelPos=pixelPos;this.coord=coord;this.displayMode=displayMode;this.IconName=IconName;this.IconWidth=IconWidth;this.IconHeight=IconHeight;this.hotArea=hotArea;};function FindNearbyDailyServicesParams(searchCenter,maxResult,maxDistance,categories){this.searchCenter=searchCenter;this.maxResult=maxResult;this.maxDistance=maxDistance;this.categories=categories;};function FindByKeywordsParams(keywords,maxResult,countryCode){this.keywords=keywords;this.maxResult=maxResult;this.countryCode=countryCode;};function FindNearbyByRoadParams(searchCenter,maxResult,maxDistance,maxDuration,mode,itineraryOptions){this.searchCenter=searchCenter;this.maxResult=maxResult;this.maxDistance=maxDistance;this.maxDuration=maxDuration;this.mode=mode;this.itineraryOptions=itineraryOptions;};function FindNearbyParams(searchCenter,maxResult,maxDistance){this.searchCenter=searchCenter;this.maxResult=maxResult;this.maxDistance=maxDistance;};function NumCriteriaDefinition(mode,numericCriteriaList){this.mode=mode;this.numericCriteriaList=numericCriteriaList;};function TextCriteriaDefinition(keywords,mode,scope){this.keywords=keywords;this.mode=mode;this.scope=scope;};function SearchCriteria(textCriteria,numCriteria){this.textCriteria=textCriteria;this.numCriteria=numCriteria;};function FindPOIRequest(searchDataset,searchParams,searchFilter,resultFormat){this.searchDataset=searchDataset;this.searchParams=searchParams;this.searchFilter=searchFilter;this.resultFormat=resultFormat;};function getxhr_object(){if(window.XMLHttpRequest){return new XMLHttpRequest();}else if(window.ActiveXObject){return new ActiveXObject("Microsoft.XMLHTTP");}else{return null;}};function mapManagement_pixelsToXY(mapDefByID,mapDefByScale,pixelsList){var xhr_object=getxhr_object();if(xhr_object==null)return;var methodName='pixelsToXY';params='method='+methodName;if((mapDefByID!=null)&&(typeof(mapDefByID)!="undefined")){params=params+"&mapDefByIdMapId="+mapDefByID.MapId+"&mapDefWidth="+mapDefByID.MapWidth+"&mapDefHeight="+mapDefByID.MapHeight;}
if((mapDefByScale!=null)&&(typeof(mapDefByScale)!="undefined")){params=params+"&mapDefps="+mapDefByScale.psize+"&mapDefcenterlon="+mapDefByScale.center.lon+"&mapDefcenterlat="+mapDefByScale.center.lat+"&mapDefWidth="+mapDefByScale.MapWidth+"&mapDefHeight="+mapDefByScale.MapHeight;}
if((typeof(pixelsList)!="undefined")){params=params+"&pixelsListSize="+pixelsList.length;for(var cpt=0;cpt<pixelsList.length;cpt++){params=params+"&x"+cpt+"="+pixelsList[cpt].x+"&y"+cpt+"="+pixelsList[cpt].y;}}
xhr_object.open("POST","lib/pixelsToXY.php",false);xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded");xhr_object.send(params);if(xhr_object.readyState==4){var items=new Array();var str=xhr_object.responseText;items=str.split('|');var idx=0;var lat=0;var lon=0;var geoCoordinatesList=new Array();if((pixelsList!=null)&&(typeof(pixelsList)!="undefined")){for(var cpt=0;cpt<pixelsList.length;cpt++){var cpti=0;var bfound=false;while((cpti<items.length)&&(bfound==false)){if(items[cpti].indexOf("lon"+cpt+":")!=-1){lon=parseFloat(items[cpti].substring(("lon"+cpt+":").length));lat=parseFloat(items[cpti+1].substring(("lat"+cpt+":").length));var coord=new GeoCoordinates(lon,lat);geoCoordinatesList[cpt]=coord;bfound=true;}
cpti=cpti+1;}
if(!bfound){geoCoordinatesList[cpt]=null;}}}
cpti=0;var errorMsg=null;var errorMsgDetail=null;while(cpti<items.length){if(items[cpti].indexOf("error:")!=-1){errorMsg=items[cpti].substring("error:".length);}else if(items[cpti].indexOf("errorDetail:")!=-1){errorMsgDetail=items[cpti].substring("errorDetail:".length);}
cpti=cpti+1;}
if((errorMsg!=null)||(errorMsgDetail!=null)){errorMsg='[method: '+methodName+'] '+errorMsg;displayError(errorMsg,errorMsgDetail);}
return geoCoordinatesList;}};function getParamsFromMapActionList(omapActionList){var _params='';if(omapActionList!=null){_params=_params+'&mapActionSize='+omapActionList.length;for(var cptj=0;cptj<omapActionList.length;cptj++){if(omapActionList[cptj]!=null){_params=_params+'&mapActionType'+cptj+'='+omapActionList[cptj].type;_params=_params+'&mapActionValue'+cptj+'='+omapActionList[cptj].value;}}}
return _params;};function getParamsFromPinLogoList(opinLogoList){var _params='';if(opinLogoList!=null){_params=_params+'&pinLogoSize='+opinLogoList.length;for(var cptk=0;cptk<opinLogoList.length;cptk++){if(opinLogoList[cptk]!=null){_params=_params+'&pinLogoID'+cptk+'='+opinLogoList[cptk].id;if(opinLogoList[cptk].pixelPos!=null){_params=_params+'&pinLogoX'+cptk+'='+opinLogoList[cptk].pixelPos.x+'&pinLogoY'+cptk+'='+opinLogoList[cptk].pixelPos.y;}
if(opinLogoList[cptk].coord!=null){_params=_params+'&pinLogoLon'+cptk+'='+opinLogoList[cptk].coord.lon+'&pinLogoLat'+cptk+'='+opinLogoList[cptk].coord.lat;}
_params=_params+'&pinLogoMode'+cptk+'='+opinLogoList[cptk].displayMode;_params=_params+'&pinLogoIconName'+cptk+'='+opinLogoList[cptk].IconName;_params=_params+'&pinLogoIconWidth'+cptk+'='+opinLogoList[cptk].IconWidth;_params=_params+'&pinLogoIconHeight'+cptk+'='+opinLogoList[cptk].IconHeight;_params=_params+'&pinLogohotArea'+cptk+'='+opinLogoList[cptk].hotArea;}}}
return _params;};function getParamsFromPolylinesList(opolylinesList){var _params='';if(opolylinesList!=null){_params=_params+'&polylinesSize='+opolylinesList.length;for(var cptl=0;cptl<opolylinesList.length;cptl++){if(opolylinesList[cptl]!=null){_params=_params+'&polylinesColor'+cptl+'='+opolylinesList[cptl].color;;_params=_params+'&polylinesThickness'+cptl+'='+opolylinesList[cptl].thickness;if(opolylinesList[cptl].pixelPointList!=null){_params=_params+'&polylinespixelPointListSize'+cptl+'='+opolylinesList[cptl].pixelPointList.length;for(var cptm=0;cptm<opolylinesList[cptl].pixelPointList.length;cptm++){if(opolylinesList[cptl].pixelPointList[cptm]!=null){_params=_params+'&polylinespixelPointList'+cptl+'X'+cptm+'='+opolylinesList[cptl].pixelPointList[cptm].x;_params=_params+'&polylinespixelPointList'+cptl+'Y'+cptm+'='+opolylinesList[cptl].pixelPointList[cptm].y;}}}
if(opolylinesList[cptl].geoCoordinatesList!=null){_params=_params+'&polylinesgeoCoordListSize'+cptl+'='+opolylinesList[cptl].geoCoordinatesList.length;for(var cptn=0;cptn<opolylinesList[cptl].geoCoordinatesList.length;cptn++){if(opolylinesList[cptl].geoCoordinatesList[cptn]!=null){_params=_params+'&polylinesgeoCoordList'+cptl+'Lon'+cptn+'='+opolylinesList[cptl].geoCoordinatesList[cptn].lon;_params=_params+'&polylinesgeoCoordList'+cptl+'Lat'+cptn+'='+opolylinesList[cptl].geoCoordinatesList[cptn].lat;}}}}}}
return _params;};function getParamsFromItitraceList(oititraceList){var _params='';if((oititraceList!=null)&&(typeof(oititraceList)!="undefined")){_params=_params+'&ititraceSize='+oititraceList.length;for(var cptm=0;cptm<oititraceList.length;cptm++){_params=_params+'&ititracePart'+cptm+'='+oititraceList[cptm];}}
return _params;};function displayGeneratedMap(methodName,xhr_object){if(xhr_object.readyState==4){var str=xhr_object.responseText;var items=new Array();var errorMsg=null;var errorMsgDetail=null;items=str.split('|');for(cpt=0;cpt<items.length;cpt++){if(items[cpt].indexOf("js:")!=-1){eval(items[cpt].substring("js:".length));map.routingFuncs.getGeneratedMap(generatedMap);return true;}else if(items[cpt].indexOf("error:")!=-1){errorMsg=items[cpt].substring("error:".length);}else if(items[cpt].indexOf("errorDetail:")!=-1){errorMsgDetail=items[cpt].substring("errorDetail:".length);}}
if((errorMsg!=null)||(errorMsgDetail!=null)){errorMsg='[method: '+methodName+'] '+errorMsg;displayError(errorMsg,errorMsgDetail);}}
return false;};function mapManagement_getMapByScale(ps,center,width,height,mapActionList,imgFormat,withCopyright,pinLogoList,polylinesList,oititraceList){var xhr_object=getxhr_object();if(xhr_object==null)return;currImgFormat=imgFormat;currWithCopyright=withCopyright;var methodName='getMapByScale';params='method='+methodName+'&ps='+ps+'&width='+width+'&height='+height+'&imgFormat='+imgFormat+'&withCopyright='+withCopyright;params=params+'&centerLon='+center.lon;params=params+'&centerLat='+center.lat;params=params+getParamsFromMapActionList(mapActionList);params=params+getParamsFromPinLogoList(pinLogoList);params=params+getParamsFromPolylinesList(polylinesList);params=params+getParamsFromItitraceList(oititraceList);xhr_object.open("POST","lib/getMapByScale.php",true);xhr_object.onreadystatechange=function anonymous(){displayGeneratedMap(methodName,xhr_object);};xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");xhr_object.send(params);};function mapManagement_getMapByID(mapId,width,height,mapActionList,imgFormat,withCopyright,pinLogoList,polylinesList,oititraceList){var xhr_object=getxhr_object();if(xhr_object==null)return;currImgFormat=imgFormat;currWithCopyright=withCopyright;var methodName='getMapByID';params='method='+methodName+'&mapId='+mapId+'&width='+width+'&height='+height+'&imgFormat='+imgFormat+'&withCopyright='+withCopyright;params=params+getParamsFromMapActionList(mapActionList);params=params+getParamsFromPinLogoList(pinLogoList);params=params+getParamsFromPolylinesList(polylinesList);params=params+getParamsFromItitraceList(oititraceList);xhr_object.open("POST","mapLibs/gastroTools/WS2Sample/lib/getMapByID.php",true);xhr_object.onreadystatechange=function anonymous(){displayGeneratedMap(methodName,xhr_object);};xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");xhr_object.send(params);};function getGeneratedMap(methodName,xhr_object){if(xhr_object.readyState==4){var str=xhr_object.responseText;var items=new Array();var errorMsg=null;var errorMsgDetail=null;items=str.split('|');for(cpt=0;cpt<items.length;cpt++){if(items[cpt].indexOf("js:")!=-1){eval(items[cpt].substring("js:".length));return generatedMap;return true;}else if(items[cpt].indexOf("error:")!=-1){errorMsg=items[cpt].substring("error:".length);}else if(items[cpt].indexOf("errorDetail:")!=-1){errorMsgDetail=items[cpt].substring("errorDetail:".length);}}
if((errorMsg!=null)||(errorMsgDetail!=null)){errorMsg='[method: '+methodName+'] '+errorMsg;displayError(errorMsg,errorMsgDetail);}}
return null;};function mapManagement_getMapByID_sync(mapId,width,height,mapActionList,imgFormat,withCopyright,pinLogoList,polylinesList,oititraceList){var xhr_object=getxhr_object();if(xhr_object==null)return;currImgFormat=imgFormat;currWithCopyright=withCopyright;var methodName='getMapByID';params='method='+methodName+'&mapId='+mapId+'&width='+width+'&height='+height+'&imgFormat='+imgFormat+'&withCopyright='+withCopyright;params=params+getParamsFromMapActionList(mapActionList);params=params+getParamsFromPinLogoList(pinLogoList);params=params+getParamsFromPolylinesList(polylinesList);params=params+getParamsFromItitraceList(oititraceList);xhr_object.open("POST","lib/getMapByID.php",false);xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");xhr_object.send(params);return getGeneratedMap(methodName,xhr_object);};function geocoding_getLocationList_sync(formid,mode,inputAddressList){var xhr_object=getxhr_object();if(xhr_object==null)return;params="size="+inputAddressList.length+"&mode="+mode;for(cpt=0;cpt<inputAddressList.length;cpt++){if(inputAddressList[cpt]!=null){params=params+'&address'+cpt+'='+encodeURIComponent(inputAddressList[cpt].address);params=params+'&cityName'+cpt+'='+encodeURIComponent(inputAddressList[cpt].cityName);params=params+'&countryCode'+cpt+'='+inputAddressList[cpt].countryCode;params=params+'&postalCode'+cpt+'='+inputAddressList[cpt].postalCode;params=params+'&stateName'+cpt+'='+encodeURIComponent(inputAddressList[cpt].stateName);if(typeof(inputAddressList[cpt].long)!="undefined"&&typeof(inputAddressList[cpt].lat)!="undefined"){params=params+'&coordX'+cpt+'='+encodeURIComponent(inputAddressList[cpt].long);params=params+'&coordY'+cpt+'='+encodeURIComponent(inputAddressList[cpt].lat);}}}
params=params+'&form='+formid;params=params+'&select=lstLocation';xhr_object.open("POST","mapLibs/gastroTools/WS2Sample/lib/getLocation.php",false);xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");xhr_object.send(params);if(xhr_object.readyState==4){var str=xhr_object.responseText;var items=new Array();var errorMsg=null;var errorMsgDetail=null;items=str.split('|');for(cpt=0;cpt<items.length;cpt++){if(items[cpt].indexOf("js:")!=-1){eval(items[cpt].substring("js:".length));}else if(items[cpt].indexOf("error:")!=-1){errorMsg=items[cpt].substring("error:".length);}else if(items[cpt].indexOf("errorDetail:")!=-1){errorMsgDetail=items[cpt].substring("errorDetail:".length);}}
if((errorMsg!=null)||(errorMsgDetail!=null)){errorMsg='[method: '+methodName+'] '+errorMsg;displayError(errorMsg,errorMsgDetail);return false;}else{return true;}}};function displayCalculatedRoute(calculatedRoute,itiRequest){if((calculatedRoute!=null)&&(typeof(calculatedRoute)!="undefined")){if(calculatedRoute.roadmap!=null)
showItineraryRoadmap(calculatedRoute.roadmap);if(calculatedRoute.mapId!=null)
showItineraryMap(calculatedRoute.mapId,itiRequest.responseOptions.mainMapWidth,itiRequest.responseOptions.mainMapHeight,calculatedRoute.ititrace);}};function getCalculatedRoute(methodName,xhr_object){if(xhr_object.readyState==4){var str=xhr_object.responseText;var items=new Array();items=str.split('|');var errorMsg=null;var errorMsgDetail=null;var oititraceList=null;var mapId=null;var roadmap=null;for(cpt=0;cpt<items.length;cpt++){if(items[cpt].indexOf("html:")!=-1){roadmap=items[cpt].substring("html:".length);}else if(items[cpt].indexOf("mapID:")!=-1){if(items[cpt].length>"mapID:".length){mapId=items[cpt].substring("mapID:".length);}}else if(items[cpt].indexOf("itiTraceSize:")!=-1){nbtrace=parseInt(items[cpt].substring("itiTraceSize:".length));oititraceList=new Array();for(var cpti=cpt+1;cpti<cpt+1+nbtrace;cpti++){oititraceList[oititraceList.length]=items[cpti].substring(("itiTracePart"+cpti+":").length);}
currentItiTrace=oititraceList;}else if(items[cpt].indexOf("error:")!=-1){errorMsg=items[cpt].substring("error:".length);}else if(items[cpt].indexOf("errorDetail:")!=-1){errorMsgDetail=items[cpt].substring("errorDetail:".length);}}
if((errorMsg!=null)||(errorMsgDetail!=null)){errorMsg='[method: '+methodName+'] '+errorMsg;displayError(errorMsg,errorMsgDetail);}else{return{roadmap:roadmap,mapId:mapId,ititrace:oititraceList}}}};function getParamsFromResponseOptions(oresponseOptions){var _params='';_params=_params+'&relt='+oresponseOptions.responseElts;_params=_params+'&mapdef='+oresponseOptions.mapDefCalc;_params=_params+'&mmw='+oresponseOptions.mainMapWidth;_params=_params+'&mmh='+oresponseOptions.mainMapHeight;_params=_params+'&dmw='+oresponseOptions.blocMapWidth;_params=_params+'&dmh='+oresponseOptions.blocMapHeight;return _params;};function getParamsFromLocDefList(olocDefList){var _params='';if(olocDefList!=null){_params=_params+'&locDefSize='+olocDefList.length;for(var cpti=0;cpti<olocDefList.length;cpti++){if((olocDefList[cpti].locID!=null)&&(typeof(olocDefList[cpti].locID)!="undefined")){_params=_params+'&locDefLocID'+cpti+'='+olocDefList[cpti].locID;}
if((olocDefList[cpti].poiID!=null)&&(typeof(olocDefList[cpti].poiID)!="undefined")){_params=_params+'&locDefPoiID'+cpti+'='+olocDefList[cpti].poiID.id;_params=_params+'&locDefPoiLang'+cpti+'='+olocDefList[cpti].poiID.lang;_params=_params+'&locDefPoiDB'+cpti+'='+olocDefList[cpti].poiID.dbId;}
if((olocDefList[cpti].coord!=null)&&(typeof(olocDefList[cpti].coord)!="undefined")){_params=_params+'&locDefCoordLon'+cpti+'='+olocDefList[cpti].coord.lon;_params=_params+'&locDefCoordLat'+cpti+'='+olocDefList[cpti].coord.lat;}}}
return _params;};function routeCalculation_getRoute(itiRequest){var xhr_object=getxhr_object();if(xhr_object==null)return;var methodName='getRoute';params='method='+methodName;params=params+'&itiDate='+itiRequest.itiOptions.itiDate;params=params+'&vType='+itiRequest.itiOptions.vehicleType;params=params+'&iType='+itiRequest.itiOptions.itiType;params=params+'&fmw='+itiRequest.itiOptions.itiPref.favourMotorways;params=params+'&acb='+itiRequest.itiOptions.itiPref.avoidCrossingBorders;params=params+'&at='+itiRequest.itiOptions.itiPref.avoidTolls;params=params+'&art='+itiRequest.itiOptions.itiPref.avoidRoadTaxAreas;params=params+'&aoc='+itiRequest.itiOptions.itiPref.avoidOffroadConnections;params=params+'&amp='+itiRequest.itiOptions.itiPref.avoidMountainPass;params=params+'&fprice='+itiRequest.itiOptions.fuelCost.price;params=params+'&fcurr='+itiRequest.itiOptions.fuelCost.currency;params=params+'&fcons1='+itiRequest.itiOptions.fuelConsumption[0];params=params+'&fcons2='+itiRequest.itiOptions.fuelConsumption[1];params=params+'&fcons3='+itiRequest.itiOptions.fuelConsumption[2];params=params+'&dL='+itiRequest.presentationOptions.detailLevel;params=params+'&lang='+itiRequest.presentationOptions.language;params=params+'&format='+itiRequest.presentationOptions.instructionsFormat;params=params+'&toll='+itiRequest.presentationOptions.tollCategory;params=params+getParamsFromResponseOptions(itiRequest.responseOptions);params=params+getParamsFromLocDefList(itiRequest.locDefList);xhr_object.open("POST","mapLibs/gastroTools/WS2Sample/lib/getRoute.php",true);xhr_object.onreadystatechange=function anonymous(){map.routingFuncs.routingCallback(getCalculatedRoute(methodName,xhr_object),itiRequest);};xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");xhr_object.send(params);};function routeCalculation_getRouteNonMotorized(itiRequest){var xhr_object=getxhr_object();if(xhr_object==null)return;var methodName='getRouteNonMotorized';params='method='+methodName;params=params+'&itiDate='+itiRequest.itiOptions.itiDate;params=params+'&vType='+itiRequest.itiOptions.vehicleType;params=params+'&dL='+itiRequest.presentationOptions.detailLevel;params=params+'&lang='+itiRequest.presentationOptions.language;params=params+'&format='+itiRequest.presentationOptions.instructionsFormat;params=params+getParamsFromResponseOptions(itiRequest.responseOptions);params=params+getParamsFromLocDefList(itiRequest.locDefList);xhr_object.open("POST","lib/getNonMotorizedRoute.php",true);xhr_object.onreadystatechange=function anonymous(){displayCalculatedRoute(getCalculatedRoute(methodName,xhr_object),itiRequest);};xhr_object.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=iso-8859-1");xhr_object.send(params);};var ViaM_ns=(document.layers?true:false);var ViaM_ie=(document.all?true:false);var ViaM_navig=navigator.userAgent;var ViaM_moz=(ViaM_navig.indexOf("Gecko")>=0?true:false);var ViaM_isClick=false;var ViaM_mouseStartX=-1;var ViaM_mouseStartY=-1;var ViaM_minX=0;var ViaM_maxX=0;var ViaM_minY=0;var ViaM_maxY=0;var isInit=false;var daDiv;var baseX;var baseY;var ViaM_SelectionDiv,ViaM_CrossDiv,map;var isMousedown=false;zOut0=new Image();zOut0.src="/gastroTools/WS2Sample/img/zoomNeg0.gif";zOut1=new Image();zOut1.src="/gastroTools/WS2Sample/img/zoomNeg1.gif";zIn0=new Image();zIn0.src="/gastroTools/WS2Sample/img/zoomPos0.gif";zIn1=new Image();zIn1.src="/gastroTools/WS2Sample/img/zoomPos1.gif";function get(obj)
{return document.getElementById(obj);};function repos(div,x,y,w,h)
{div.style.left=x;div.style.top=y;div.style.width=w;div.style.height=h;};isDrag=false;var daMap,mapHeight,mapTop,mapLeft,oImg,daDiv,bgOutDiv;function ViaM_init(o){if((o=="")||(o==null))
o="carteDyn";if(document.getElementById("carteDyn").style.left!=0)
document.getElementById("carteDyn").style.left=0;if(document.getElementById("carteDyn").style.top!=0)
document.getElementById("carteDyn").style.top=0;daMap=get("mapDiv");daMap.width=daMap.style.width;daMap.height=daMap.style.height;if(isDrag){daMap.style.cursor="move";}else{daMap.style.cursor="crosshair";}
mapLeft=0;mapTop=0;ratioMap=parseInt(daMap.width)/parseInt(daMap.height);navZoom=1;ViaM_SelectionDiv=document.createElement("DIV");ViaM_SelectionDiv.style.position="absolute";ViaM_SelectionDiv.id="ViaM_SelectionDiv";ViaM_SelectionDiv.style.height="1px";ViaM_SelectionDiv.style.width="1px";ViaM_SelectionDiv.style.visibility="hidden";ViaM_SelectionDiv.style.border="2px solid #FF0000";ViaM_SelectionDiv.style.zIndex=19;ViaM_SelectionDiv.innerHTML="<img src='img/s.gif' height=1 width=1>";daMap.appendChild(ViaM_SelectionDiv);if(get("mlNorth")){get("mlNorth").style.top=findPosition(daMap)[1]-parseInt(get("mlNorth").height)/2+1;get("mlNorth").style.left=findPosition(daMap)[0]+parseInt(daMap.width)/2-parseInt(get("mlNorth").width)/2;get("mlNorth").style.visibility="visible";}
if(get("mlWest")){get("mlWest").style.top=findPosition(daMap)[1]+parseInt(daMap.height)/2-parseInt(get("mlWest").height)/2;get("mlWest").style.left=findPosition(daMap)[0]-parseInt(get("mlWest").width)/2+1;get("mlWest").style.visibility="visible";}
if(get("mlSouth")){get("mlSouth").style.top=findPosition(daMap)[1]+parseInt(daMap.height)-parseInt(get("mlSouth").height)/2-1;get("mlSouth").style.left=findPosition(daMap)[0]+parseInt(daMap.width)/2-parseInt(get("mlSouth").width)/2;get("mlSouth").style.visibility="visible";}
if(get("mlEast")){get("mlEast").style.top=findPosition(daMap)[1]+parseInt(daMap.height)/2-parseInt(get("mlEast").height)/2;get("mlEast").style.left=findPosition(daMap)[0]+parseInt(daMap.width)-parseInt(get("mlEast").width)/2-1;get("mlEast").style.visibility="visible";}
if(get("mlNWVert")){get("mlNWVert").style.top=findPosition(daMap)[1]-parseInt(get("mlNWHor").height)/2;get("mlNWVert").style.left=findPosition(daMap)[0]-parseInt(get("mlNWVert").width)/2;get("mlNWVert").style.visibility="visible";get("mlNWHor").style.top=findPosition(daMap)[1]-parseInt(get("mlNWHor").height)/2;get("mlNWHor").style.left=findPosition(daMap)[0]+parseInt(get("mlNWVert").width)/2+1;get("mlNWHor").style.visibility="visible";}
if(get("mlSWVert")){get("mlSWVert").style.top=findPosition(daMap)[1]+parseInt(daMap.height)+parseInt(get("mlSWHor").height)/2-parseInt(get("mlSWVert").height);get("mlSWVert").style.left=findPosition(daMap)[0]-parseInt(get("mlSWVert").width)/2;get("mlSWVert").style.visibility="visible";get("mlSWHor").style.top=findPosition(daMap)[1]+parseInt(daMap.height)-parseInt(get("mlSWHor").height)/2;get("mlSWHor").style.left=findPosition(daMap)[0]+parseInt(get("mlNWVert").width)/2+1;get("mlSWHor").style.visibility="visible";}
if(get("mlSEVert")){get("mlSEVert").style.top=findPosition(daMap)[1]+parseInt(daMap.height)+parseInt(get("mlSEHor").height)/2-parseInt(get("mlSEVert").height);get("mlSEVert").style.left=findPosition(daMap)[0]+parseInt(daMap.width)-parseInt(get("mlSEVert").width)/2;get("mlSEVert").style.visibility="visible";get("mlSEHor").style.top=findPosition(daMap)[1]+parseInt(daMap.height)-parseInt(get("mlSEHor").height)/2;get("mlSEHor").style.left=findPosition(daMap)[0]+parseInt(daMap.width)-parseInt(get("mlSEHor").width)-parseInt(get("mlNWVert").width)/2;get("mlSEHor").style.visibility="visible";}
if(get("mlNEVert")){get("mlNEVert").style.top=findPosition(daMap)[1]-parseInt(get("mlNEHor").height)/2;get("mlNEVert").style.left=findPosition(daMap)[0]+parseInt(daMap.width)-parseInt(get("mlNWVert").width)/2;get("mlNEVert").style.visibility="visible";get("mlNEHor").style.top=findPosition(daMap)[1]-parseInt(get("mlNEHor").height)/2;get("mlNEHor").style.left=findPosition(daMap)[0]+parseInt(daMap.width)-parseInt(get("mlNWVert").width)/2-parseInt(get("mlNEHor").width);get("mlNEHor").style.visibility="visible";}
isInit=true;daMap=get(o);ViaM_minX=findPosition(daMap)[0];ViaM_maxX=ViaM_minX+parseInt(daMap.width);ViaM_minY=findPosition(daMap)[1];ViaM_maxY=ViaM_minY+parseInt(daMap.height);baseY=parseInt(daMap.style.top);baseX=parseInt(daMap.style.left);daMap.onmousedown=ViaM_mouseDown;daMap.onmousemove=ViaM_mouseMove;daMap.onmouseup=ViaM_mouseUp;ViaM_SelectionDiv.onmousemove=ViaM_mouseMove;ViaM_SelectionDiv.onmouseup=ViaM_mouseUp;};var mouseStartX;var mouseStartY;function ViaM_mouseDown(e){if(ViaM_moz)e.preventDefault();if((document.all)&&(get("skyFrame")))get("skyFrame").style.display="none";if((ViaM_ns&&e.which!=1)||(ViaM_ie&&event.button!=1)||(ViaM_moz&&e.which!=1)||isComputingMap){return true;}
if(isDrag){baseY=parseInt(daMap.style.top);baseX=parseInt(daMap.style.left);mouseStartX=(ViaM_moz?e.pageX:event.clientX+document.body.scrollLeft);mouseStartY=(ViaM_moz?e.pageY:event.clientY+document.body.scrollTop);isMousedown=true;}else{var ViaM_mouseX=(ViaM_moz?e.pageX:event.clientX+document.body.scrollLeft);var ViaM_mouseY=(ViaM_moz?e.pageY:event.clientY+document.body.scrollTop);ViaM_mouseStartX=ViaM_mouseX;ViaM_mouseStartY=ViaM_mouseY;ViaM_isClick=((ViaM_mouseStartX>=ViaM_minX)&&(ViaM_mouseStartX<=ViaM_maxX))&&((ViaM_mouseStartY>=ViaM_minY)&&(ViaM_mouseStartY<=ViaM_maxY)&&(!isComputingMap));isMousedown=true;if(ViaM_isClick){ViaM_showSelection(ViaM_mouseStartX,ViaM_mouseStartY);ViaM_SelectionDiv.style.visibility="visible";}}
return true;};var deltAxe;function ViaM_mouseMove(e){if((typeof(isMousedown)!="undefined")&&(isMousedown)){if(!isDrag){var ViaM_mouseX=(ViaM_moz?e.pageX:event.clientX+document.body.scrollLeft);var ViaM_mouseY=(ViaM_moz?e.pageY:event.clientY+document.body.scrollTop);if((ViaM_isClick)&&(!isComputingMap)){ViaM_showSelection(ViaM_mouseX,ViaM_mouseY);return false;}}else{daMap.style.left=parseInt(baseX)-mouseStartX+(ViaM_moz?e.pageX:event.clientX+document.body.scrollLeft);daMap.style.top=parseInt(baseY)-mouseStartY+(ViaM_moz?e.pageY:event.clientY+document.body.scrollTop);}}
return false;};function ViaM_mouseUp(e){if((ViaM_ns&&e.which!=1)||(ViaM_ie&&event.button!=1)||(ViaM_moz&&e.which!=1)||isComputingMap){return true;}
isMousedown=false;if(isDrag){ViaM_x0=-parseInt(daMap.style.left)+parseInt(daMap.width)/2;ViaM_y0=-parseInt(daMap.style.top)+parseInt(daMap.height)/2;if((generatedMap!=null)&&(typeof(generatedMap)!="undefined")){generatedMap.resize(ViaM_x0,ViaM_y0,ViaM_x0,ViaM_y0);}
return false;}
else{var ViaM_mouseX=(ViaM_ns||ViaM_moz?e.pageX:event.clientX+document.body.scrollLeft);var ViaM_mouseY=(ViaM_ns||ViaM_moz?e.pageY:event.clientY+document.body.scrollTop);if(ViaM_isClick){var ViaM_x1=ViaM_mouseStartX;var ViaM_x2=ViaM_mouseX;ViaM_x0=ViaM_mouseStartX-ViaM_minX;ViaM_y0=ViaM_mouseStartY-ViaM_minY;ViaM_x1=ViaM_mouseX-ViaM_minX;ViaM_y1=ViaM_mouseY-ViaM_minY;var ViaM_mouseMoved=(ViaM_x1!=ViaM_x0)||(ViaM_y1!=ViaM_y0);ViaM_urlact="";if(ViaM_mouseMoved){}
ViaM_SelectionDiv.style.visibility="hidden";if(((ViaM_x1>ViaM_x0)&&(ViaM_x1<ViaM_x0+5))||((ViaM_y1>ViaM_y0)&&(ViaM_y1<ViaM_y0+5))||((ViaM_x0>ViaM_x1)&&(ViaM_x0<ViaM_x1+5))||((ViaM_y0>ViaM_y1)&&(ViaM_y0<ViaM_y1+5))){ViaM_x1=ViaM_x0;ViaM_y1=ViaM_y0;}
if(ViaM_x1<0)ViaM_x1=0;if(ViaM_x1>daMap.width)ViaM_x1=daMap.width;if(ViaM_y1<0)ViaM_y1=0;if(ViaM_y1>daMap.height)ViaM_y1=daMap.height;if((generatedMap!=null)&&(typeof(generatedMap)!="undefined")){generatedMap.resize(ViaM_x0,ViaM_y0,ViaM_x1,ViaM_y1);}
ViaM_mouseStartX=-1;ViaM_mouseStartY=-1;}
ViaM_isClick=false;return false;}};function ViaM_showSelection(ViaM_mouseX,ViaM_mouseY){var ViaM_x1=ViaM_mouseStartX;var ViaM_x2=ViaM_mouseX;if(ViaM_x1>ViaM_x2){var ViaM_a=ViaM_x2;ViaM_x2=ViaM_x1;ViaM_x1=ViaM_a;}
if(ViaM_x1<ViaM_minX)ViaM_x1=ViaM_minX;if(ViaM_x2>ViaM_maxX)ViaM_x2=ViaM_maxX;var ViaM_y1=ViaM_mouseStartY;var ViaM_y2=ViaM_mouseY;if(ViaM_y1>ViaM_y2){ViaM_a=ViaM_y2;ViaM_y2=ViaM_y1;ViaM_y1=ViaM_a;}
if(ViaM_y1<ViaM_minY)ViaM_y1=ViaM_minY;if(ViaM_y2>ViaM_maxY)ViaM_y2=ViaM_maxY;ViaM_SelectionDiv.style.visibility="visible";ViaM_SelectionDiv.style.left=ViaM_x1-findPosition(daMap)[0];ViaM_SelectionDiv.style.top=ViaM_y1-findPosition(daMap)[1];ViaM_SelectionDiv.style.width=ViaM_x2-ViaM_x1;ViaM_SelectionDiv.style.height=ViaM_y2-ViaM_y1;};function roll(i,o){get(i).src="img/"+o+".gif";};function findPosition(oLink){if(oLink.offsetParent){for(var posX=0,posY=0;oLink.offsetParent;oLink=oLink.offsetParent){posX+=oLink.offsetLeft;posY+=oLink.offsetTop;}
return[posX,posY];}else{return[oLink.x,oLink.y];}};var ViaM_ns=false;var ViaM_moz=false;var ViaM_ie=false;var ViaM_saf=false;if(navigator.userAgent.indexOf("Firefox")!=-1){ViaM_moz=true;}else if(navigator.userAgent.indexOf("MSIE")!=-1){ViaM_ie=true;}else if(navigator.userAgent.indexOf("Netscape")!=-1){ViaM_ns=true;}else if(navigator.userAgent.indexOf("Safari")!=-1){ViaM_saf=true;}
function IsNumeric(sText){var ValidChars="-0123456789.";var IsNumber=true;var Char;for(i=0;i<sText.length&&IsNumber==true;i++){Char=sText.charAt(i);if(ValidChars.indexOf(Char)==-1){IsNumber=false;}}
return IsNumber;};function setElementOpacity(id,opacity){if((opacity==100)&&(ViaM_ie))
document.getElementById(id).style.filter="none";else if(ViaM_ie)
document.getElementById(id).style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+opacity+")";else if(ViaM_moz)
document.getElementById(id).style.MozOpacity=opacity/100;else
document.getElementById(id).style.opacity=opacity/100;};function disableFormElements(f){for(cpt=0;cpt<f.elements.length;cpt++){f.elements[cpt].disabled=true;}};function enableFormElements(f){for(cpt=0;cpt<f.elements.length;cpt++){f.elements[cpt].disabled=false;}};function showDocElement(id){if(document.getElementById(id)){document.getElementById(id).style.visibility='visible';}else{}};function hideDocElement(id){if(document.getElementById(id)){document.getElementById(id).style.visibility='hidden';}else{}};function displayDocElement(id){if(document.getElementById(id)){document.getElementById(id).style.display='';}else{}};function unDisplayDocElement(id){if(document.getElementById(id)){document.getElementById(id).style.display='none';}else{}};function showGeneratedMap(oGeneratedMap){if(document.getElementById('mapDiv')){var img=document.getElementById('carteDyn');img.style.height=oGeneratedMap.mapDefinitions.byId.MapHeight+"px";img.style.width=oGeneratedMap.mapDefinitions.byId.MapWidth+"px";img.src=oGeneratedMap.mapURL;}};function showItineraryMap(mapId,mapWidth,mapHeight,oititraceList){ititraceList=oititraceList;mapManagement_getMapByID(mapId,mapWidth,mapHeight,null,0,true,null,null,oititraceList);};function showItineraryDetailMap(mapId,mapWidth,mapHeight,oititraceList,mapdiv,carteDyn){ititraceList=oititraceList;var mainMap=generatedMap;var genMap=mapManagement_getMapByID_sync(mapId,mapWidth,mapHeight,null,currImgFormat,true,null,null,oititraceList);if(document.getElementById(mapdiv)){var mapDiv=document.getElementById(mapdiv);mapDiv.style.height=genMap.mapDefinitions.byId.MapHeight+"px";mapDiv.style.width=genMap.mapDefinitions.byId.MapWidth+"px";var img=document.getElementById(carteDyn);img.style.height=genMap.mapDefinitions.byId.MapHeight+"px";img.style.width=genMap.mapDefinitions.byId.MapWidth+"px";img.src=genMap.mapURL;displayDocElement(mapdiv);showDocElement(mapdiv);showDocElement(carteDyn);}
generatedMap=mainMap;};function showItineraryRoadmap(htmlCode){if(document.getElementById('ItineraryRoadMap')){showDocElement('ItineraryRoadMap');document.getElementById('ItineraryRoadMap').innerHTML=htmlCode;}};function hideMap(){unDisplayDocElement('mapDiv');hideDocElement('mapDiv');hideDocElement('carteDyn');hideDocElement('mapScaleBar');if(get("mlNorth")){get("mlNorth").style.visibility="hidden";}
if(get("mlWest")){get("mlWest").style.visibility="hidden";}
if(get("mlSouth")){get("mlSouth").style.visibility="hidden";}
if(get("mlEast")){get("mlEast").style.visibility="hidden";}
if(get("mlNWVert")){get("mlNWVert").style.visibility="hidden";get("mlNWHor").style.visibility="hidden";}
if(get("mlSWVert")){get("mlSWVert").style.visibility="hidden";get("mlSWHor").style.visibility="hidden";}
if(get("mlSEVert")){get("mlSEVert").style.visibility="hidden";get("mlSEHor").style.visibility="hidden";}
if(get("mlNEVert")){get("mlNEVert").style.visibility="hidden";get("mlNEHor").style.visibility="hidden";}};function displayError(errorMsg,errorMsgDetail){var date=new Date();var msg='<b>['+date.toUTCString()+']</b><br/> ';if((errorMsg!=null)&&(typeof(errorMsg)!="undefined")){msg+=errorMsg+'<br/><br/>';}
alert("error : one of step was not found");};function clearErrorBlockMessage(){document.getElementById("DivErrorBlockMessage").innerHTML="";};function genMapByID(mapId,width,height,mapActionList,imgFormat,withCopyright,pinLogoList,polylinesList,ititrace){mapManagement_getMapByID(mapId,width,height,mapActionList,imgFormat,withCopyright,pinLogoList,polylinesList,ititrace);};function genMapByScale(psize,coord,width,height,mapActionList,imgFormat,withCopyright,pinLogoList,polylinesList,ititrace){mapManagement_getMapByScale(psize,coord,width,height,mapActionList,imgFormat,withCopyright,pinLogoList,polylinesList,ititrace);};function setItineraryOptions(){var vehicleType=document.forms["GetRouteForm"].GetRoute_vehicleType;if((vehicleType.value=="2")||(vehicleType.value=="3")){unDisplayDocElement("TR_ItiType");unDisplayDocElement("TR_ItiPreferences");unDisplayDocElement("TR_ItiConsumption1");unDisplayDocElement("TR_ItiConsumption2");unDisplayDocElement("TR_tollCategory");}else{displayDocElement("TR_ItiType");displayDocElement("TR_ItiPreferences");displayDocElement("TR_ItiConsumption1");displayDocElement("TR_ItiConsumption2");displayDocElement("TR_tollCategory");}};function getRoute(f){var itiDate=f.elements["GetRoute_itiDate"].value;var vehicleType=f.elements["GetRoute_vehicleType"].value;var itiType=f.elements["GetRoute_itiType"].value;var favourMotorways=f.elements["GetRoute_favourMotorways"].checked;var avoidCrossingBorders=f.elements["GetRoute_avoidCrossingBorders"].checked;var avoidTolls=f.elements["GetRoute_avoidTolls"].checked;var avoidRoadTaxAreas=f.elements["GetRoute_avoidRoadTaxAreas"].checked;var avoidOffroadConnections=f.elements["GetRoute_avoidOffroadConnections"].checked;var avoidMountainPass=f.elements["GetRoute_avoidMountainPass"].checked;var itiPref=new ItineraryPreferences(favourMotorways,avoidCrossingBorders,avoidTolls,avoidRoadTaxAreas,avoidOffroadConnections,avoidMountainPass);var fuelCost=new Cost(f.elements["GetRoute_fuelPrice"].value,f.elements["GetRoute_fuelCurr"].value);var fuelConsumption=new Array();fuelConsumption[fuelConsumption.length]=f.elements["GetRoute_urbanConsumption"].value;fuelConsumption[fuelConsumption.length]=f.elements["GetRoute_roadConsumption"].value;fuelConsumption[fuelConsumption.length]=f.elements["GetRoute_highwayConsumption"].value;var itiOptions=new ItineraryOptions(itiDate,vehicleType,itiType,itiPref,fuelCost,fuelConsumption);var detailLevel=f.elements["GetRoute_detailLevel"].value;var language=f.elements["GetRoute_language"].value;var instructionsFormat=f.elements["GetRoute_format"].value;var tollCategory=f.elements["GetRoute_tollCategory"].value;var presentationOptions=new ExtendedPresentationOptions(detailLevel,language,instructionsFormat,tollCategory);var responseElts=f.elements["GetRoute_responseElements"].value;var mapDefCalc=f.elements["GetRoute_MapdefExpected"].value;var mainMapWidth=f.elements["GetRoute_MainMapWidth"].value;var mainMapHeight=f.elements["GetRoute_MainMapHeight"].value;var blocMapWidth=f.elements["GetRoute_DetailMapWidth"].value;var blocMapHeight=f.elements["GetRoute_DetailMapHeight"].value;var responseOptions=new ResponseOptions(responseElts,mapDefCalc,mainMapWidth,mainMapHeight,blocMapWidth,blocMapHeight);var itiRequest=new ItineraryRequest(locDefinitionList,itiOptions,presentationOptions,responseOptions);var vehicleType=document.forms["GetRouteForm"].GetRoute_vehicleType;if((vehicleType.value=="2")||(vehicleType.value=="3")){routeCalculation_getRouteNonMotorized(itiRequest);}else{routeCalculation_getRoute(itiRequest);}};var currentItiTrace=null;var locDefinitionList=new Array();function addLocDefinition(locId,tableName){var locDef=new LocDefinition(null,locId,null);insertLocDefinition(locDef,tableName);};function insertLocDefinition(locDef,tableName){locDefinitionList[locDefinitionList.length]=locDef;};function delLocDefinition(tableName){if(locDefinitionList.length>0){var tmpLocDefinitionList=new Array();for(cpt=0;cpt<locDefinitionList.length;cpt++){if(!document.getElementById('locDef'+cpt).checked){tmpLocDefinitionList[tmpLocDefinitionList.length]=locDefinitionList[cpt];}}
oTable=document.getElementById(tableName);nbitem=locDefinitionList.length;for(curr_row=nbitem;curr_row>0;curr_row--){oTable.deleteRow(curr_row);}
locDefinitionList=new Array();for(cpt=0;cpt<tmpLocDefinitionList.length;cpt++){insertLocDefinition(tmpLocDefinitionList[cpt],tableName);}}};function searchAddresse(inputAddress,mode,ambi){var oInputAddressList=new Array();oInputAddressList[oInputAddressList.length]=inputAddress;geocoding_getLocationList_sync(ambi,mode,oInputAddressList);if((foundLocationsListArray!=null)&&(foundLocationsListArray.length>0)){if(foundLocationsListArray[0].size==1){addLocDefinition(foundLocationsListArray[0].foundLocations[0].locDesc.locid,'StopoversTable');return true;}}
return false;};function showInputAddressFormLayer(){disableFormElements(document.forms["GetRouteForm"]);showDocElement('InputAddressFormLayer');var f=document.forms["InputAddressForm"];f.elements["InputAddressForm_add"].onclick=function(){var inputAddress=getInputAddress(f);closeInputAddressFormLayer(f);if(searchAddresse(inputAddress,0)){enableFormElements(document.forms["GetRouteForm"]);}};f.elements["InputAddressForm_cancel"].onclick=function(){closeInputAddressFormLayer(f);enableFormElements(document.forms["GetRouteForm"]);};};function showhideMapDefinifition(f){if(document.getElementById("GetRoute_MapdefExpected").value=="0"){unDisplayDocElement("TR_MapSize");unDisplayDocElement("TR_MainmapSize");unDisplayDocElement("TR_DetailmapSize");}else if(document.getElementById("GetRoute_MapdefExpected").value=="1"){displayDocElement("TR_MapSize");displayDocElement("TR_MainmapSize");unDisplayDocElement("TR_DetailmapSize");}else if(document.getElementById("GetRoute_MapdefExpected").value=="2"){displayDocElement("TR_MapSize");unDisplayDocElement("TR_MainmapSize");displayDocElement("TR_DetailmapSize");}else if(document.getElementById("GetRoute_MapdefExpected").value=="3"){displayDocElement("TR_MapSize");displayDocElement("TR_MainmapSize");displayDocElement("TR_DetailmapSize");}};function showItineraryTraceOptions(){var routeResponse=document.getElementById('GetRoute_responseElements');var selectedValue=routeResponse.options[routeResponse.selectedIndex].value;};function autoCompleter(idField,idSearchButton,sensibility,limitNbOfResults){this.field=$(idField);this.field.autoCompleter=this;this.searchButton=$(idSearchButton);this.sensibility=sensibility;this.limitNbOfResults=limitNbOfResults;this.listReady=false;this.listElements=new Array();this.positionInList=null;this.cityFieldHasFocus=false;this.autoCompleterIsOn=false;this.init();this.activate();};autoCompleter.prototype.init=function(){Event.observe(this.field,"focus",this.onFocus.bindAsEventListener(this));Event.observe(this.field,"blur",this.onBlur.bindAsEventListener(this));Event.observe(this.field,"keyup",this.inputChanged.bindAsEventListener(this));}
autoCompleter.prototype.onFocus=function(){this.cityFieldHasFocus=true;}
autoCompleter.prototype.onBlur=function(){this.cityFieldHasFocus=false;if(this.listReady&&this.positionInList!=null)
this.fillField(this.cityData[this.positionInList]);this.clearList();}
autoCompleter.prototype.activate=function(){this.autoCompleterIsOn=true;}
autoCompleter.prototype.deactivate=function(){this.autoCompleterIsOn=false;}
autoCompleter.prototype.inputChanged=function(e){if(this.autoCompleterIsOn==false)
return;e=(e)?e:((event)?event:null);Event.stop(e);var canSuggest=true;var t=this;var code=e.keyCode||e.charCode;switch(code){case Event.KEY_BACKSPACE:canSuggest=false;this.clearList();break;case 16:break;case 17:canSuggest=false;break;case 18:canSuggest=false;break;case Event.KEY_TAB:canSuggest=false;break;case Event.KEY_LEFT:canSuggest=false;break;case Event.KEY_RIGHT:canSuggest=false;break;case Event.KEY_UP:if(this.listReady)
this.moveInList("up");canSuggest=false;break;case Event.KEY_DOWN:if(this.listReady)
this.moveInList("down");canSuggest=false;break;case Event.KEY_RETURN:if(this.cityData&&this.listReady&&this.positionInList!=null){this.fillField(this.cityData[this.positionInList]);this.clearList();}
else if(!this.listReady&&this.positionInList==null&&this.field.cityData!=null){if(this.searchButton!=null)
this.searchButton.onclick();}
canSuggest=false;break;default:canSuggest=true;break;}
if(this.field.value.length==0)
this.field.cityData=null;if(canSuggest&&this.field.value.length>=this.sensibility){this.getList();}};autoCompleter.prototype.fillField=function(data){if(this.cityData){if(data['npa']!='')
this.field.value=data['npa']+" "+data['localite'];else
this.field.value=data['localite'];}
this.field.cityData=data;};autoCompleter.prototype.getList=function(){var cbFunction=(arguments.length>0)?arguments[0]:this.getListCallBack;var curObj=(arguments.length>0)?arguments[1]:this;this.requestId=Math.round(Math.random()*10000);var url="www.swissgeo.ch/api2/kamapGateway.php?action=getCity&requestId="+this.requestId+"&input="+this.field.value;if(bIsGastroLocal){url+="&region="+sRegion;}
new Ajax.Request("mapLibs/proxy.php?url="+encodeURIComponent(url),{onSuccess:cbFunction.bindAsEventListener(curObj)});};autoCompleter.prototype.getListCallBack=function(trsp){try{eval(trsp.responseText);}
catch(e){var cityData=null;}
if(this.requestId!=requestId)
return;if(cityData&&cityData.length>0&&this.cityFieldHasFocus){this.cityData=cityData;if(cityData.length==1){this.fillField(this.cityData[0]);this.clearList();}
else
this.createList();}
else if(cityData&&cityData.length==0&&this.cityFieldHasFocus){this.field.cityData=null;}
else if(!cityData){this.field.cityData=null;}};autoCompleter.prototype.moveInList=function(direction){if(this.positionInList==null)
this.positionInList=-1;if(direction=="up")
this.positionInList=(this.positionInList-1<0?0:--this.positionInList);else
this.positionInList=(this.positionInList+1>=this.cityData.length?(this.cityData.length-1):++this.positionInList);for(i=0;i<this.listElements.length;i++){this.listElements[i].className="element";}
this.listElements[this.positionInList].className="selected";};autoCompleter.prototype.createList=function(){var data=this.cityData;this.clearList();if(typeof this.autoCompleteDiv=="undefined"){this.autoCompleteDiv=$(document.createElement("div"));document.body.appendChild(this.autoCompleteDiv);var pos=this.findObjectPos(this.field);this.autoCompleteDiv.style.position="absolute";this.autoCompleteDiv.style.top=pos[1]+this.field.getHeight()+"px";this.autoCompleteDiv.style.left=pos[0]+"px";this.autoCompleteDiv.className="autoCompleteDiv";this.autoCompleteDiv.hide();}
var limit=data.length<=this.limitNbOfResults?data.length:this.limitNbOfResults;for(var i=0;i<limit;i++){var d=document.createElement("div");this.autoCompleteDiv.appendChild(d);d.className="element";d.cityData=data[i];Event.observe($(d),"mousedown",this.divOnMouseClick.bindAsEventListener(this));var a=document.createElement("a");d.appendChild(a);a.href="#";a.cityData=data[i];Event.observe($(a),"mousedown",this.divOnMouseClick.bindAsEventListener(this));a.innerHTML=data[i]['localite'];if(data[i]['npa']!='')
a.innerHTML=data[i]['npa']+" "+a.innerHTML;this.listElements[i]=d;}
this.hideSelectBoxesInIE6();this.autoCompleteDiv.show();this.moveInList("down");this.listReady=true;};autoCompleter.prototype.clearList=function(){if(typeof this.autoCompleteDiv!="undefined"){while(this.autoCompleteDiv.childNodes.length>0){this.autoCompleteDiv.removeChild(this.autoCompleteDiv.childNodes[0]);}
this.autoCompleteDiv.hide();}
this.unhideSelectBoxesInIE6();this.positionInList=null;this.listElements.splice(0,this.listElements.length);this.listReady=false;};autoCompleter.prototype.hideSelectBoxesInIE6=function(){if(!document.all)
return;var sels=$A(document.getElementsByName("bufferEntries"));for(var i=0;i<sels.length;i++){$(sels[i]).hide();}}
autoCompleter.prototype.unhideSelectBoxesInIE6=function(){if(!document.all)
return;var sels=$A(document.getElementsByName("bufferEntries"));for(var i=0;i<sels.length;i++){$(sels[i]).show();}}
autoCompleter.prototype.divOnMouseClick=function(e){e=(e)?e:((event)?event:null);var elem=Event.element(e);Event.stop(e);this.clearList();this.fillField(elem.cityData);return false;};autoCompleter.prototype.findObjectPos=function(obj){var curleft=curtop=0;if(obj.offsetParent){curleft=obj.offsetLeft;curtop=obj.offsetTop;while(obj=obj.offsetParent){curleft+=obj.offsetLeft;curtop+=obj.offsetTop;}}
return[curleft,curtop];};OpenLayers.Popup.COLOR="transparent";function gastroPopUp(e,POItype,oToAttach){if(map.queryPopUpDisabled)
return;if($d(map.gastroPopUp))
map.gastroPopUp.remove();this.oToAttach=oToAttach;map.gastroPopUp=this;if(typeof e.xy=="undefined"){if(typeof e=="string"||typeof e=="number")
gastroId=e;else
gastroId=Event.element(e).idItem;this.pos=null;if($d(POItype)&&POItype!=null)
var url="mapLibs/infoGetter.php?layers="+POItype+"&idItem="+gastroId+"&sessionType=infoGetter&lang="+appLanguage+"&dom="+TRdom;else
var url="mapLibs/infoGetter.php?layers=cat10&idItem="+gastroId+"&sessionType=infoGetter&lang="+appLanguage+"&dom="+TRdom;if($d(map.sessionId))
url+="&sessionId="+map.sessionId;if(map.name=="google")
url+="&srid=900913";map.queryPopUpDisabled=true;new OpenLayers.Ajax.Request(url,{method:"get",onSuccess:this.display.bindAsEventListener(this,true)});}
else{this.pos=map.getLonLatFromPixel(new OpenLayers.Pixel(e.xy.x,e.xy.y));this.buffer=this.getBufferAccordingToScale();var enabled="";for(var i=0;i<map.layers.length;i++){var layer=map.layers[i];if(!$d(layer.legend)||!$d(layer.legend.container))
continue;if(layer.legend.container=="leg_blocGastro1"||layer.legend.container=="leg_blocGastro2"||layer.legend.container=="leg_blocGastro_res"||layer.legend.container=="tourisme1"||layer.legend.container=="tourisme2"||layer.legend.container=="tourisme3"){if(layer.getVisibility()){if(enabled!="")
enabled+=","
enabled+=layer.params.g;}}}
if(enabled=="")
return;var url="mapLibs/infoGetter.php?layers="+enabled+"&locate="+Math.round(this.pos.lon)+","+Math.round(this.pos.lat)+"&buffer="+this.buffer+","+this.buffer+"&sessionType=infoGetter&lang="+appLanguage+"&dom="+TRdom;if(map.sessionId)
url+="&sessionId="+map.sessionId;if(map.name=="google")
url+="&srid=900913";map.queryPopUpDisabled=true;new OpenLayers.Ajax.Request(url,{method:"get",onSuccess:this.display.bindAsEventListener(this)});}
map.events.register('zoomend',this,this.remove.bind(this));}
gastroPopUp.prototype.display=function(trsp,bMouseOverToRemove){if(!bMouseOverToRemove)
map.queryPopUpDisabled=false;if(trsp.responseText=="null")
return;var div=$(document.createElement("div"));div.style.visibility="hidden";div.style.position="absolute";div.id="renderingPopUp";div.style.display='none';div.innerHTML=trsp.responseText;document.body.appendChild(div);var dim=div.getDimensions();document.body.removeChild(document.body.lastChild);var dimVp=$(map.div).getDimensions();if(this.pos==null){var vpCoords={x:(dimVp.width-dim.width)/2,y:(dimVp.height-dim.height)/2};}
else{var vpCoords=map.getViewPortPxFromLonLat(this.pos);var extent=map.getExtent();var quadrant=extent.determineQuadrant(this.pos);var offset=6;switch(quadrant){case"tl":if(vpCoords.x+dim.width>dimVp.width)
vpCoords.x=dimVp.width-dim.width;if(vpCoords.y+dim.height>dimVp.height)
vpCoords.y=dimVp.height-dim.height;vpCoords.x-=offset;vpCoords.y-=offset;break;case"tr":if(vpCoords.x-dim.width<0)
vpCoords.x=dim.width;if(vpCoords.y+dim.height>dimVp.height)
vpCoords.y=dimVp.height-dim.height;vpCoords.x+=offset;vpCoords.y-=offset;break;case"bl":if(vpCoords.x+dim.width>dimVp.width)
vpCoords.x=dimVp.width-dim.width;if(vpCoords.y-dim.height<0)
vpCoords.y=dim.height;vpCoords.x-=offset;vpCoords.y+=offset;break;case"br":if(vpCoords.x-dim.width<0)
vpCoords.x=dim.width;if(vpCoords.y-dim.height<0)
vpCoords.y=dim.height;vpCoords.x+=offset;vpCoords.y+=offset;break;default:break;}}
this.pos=map.getLonLatFromViewPortPx(vpCoords);this.popUp=new OpenLayers.Popup.Anchored("gastroPopUp",this.pos,new OpenLayers.Size(dim.width,dim.height),"");map.addPopup(this.popUp);this.popUp.div.innerHTML=trsp.responseText;this.popUp.div.style.cursor="default";this.popUp.div.style.filter="";if($d(this.oToAttach)){var elem=$(this.oToAttach.attachToId);if(elem!=null){for(var i in this.oToAttach){eval("elem."+i+" = this.oToAttach[i];");}}}
if(bMouseOverToRemove)
this.popUp.div.onmouseover=function(e){e=e?e:(event?event:null);if(Event.element(e))
Event.element(e).onmouseover=null;Event.stop(e);map.queryPopUpDisabled=false;};this.popUp.events.register('mousemove',null,function(ev){OpenLayers.Event.stop(ev)});if($("popUp_cat41")){var that=this;$("cff_dest").onclick=that.makePersistent.bind(that);$("cff_dep").onclick=that.makePersistent.bind(that);}
else{this.popUp.events.register('click',null,this.remove.bind(this));}}
gastroPopUp.prototype.makePersistent=function(){if($("cff_dep")&&$("cff_dest")){$("cff_dep").onclick=null;$("cff_dest").onclick=null;}
this.popUp.events.remove('mouseout');this.popUp.oldLock=map.queryPopUpDisabled;map.queryPopUpDisabled=true;this.popUp.onRemove=(function(){map.queryPopUpDisabled=this.oldLock}).bind(this.popUp);}
gastroPopUp.prototype.mouseOut=function(e){var toElem=e.relatedTarget||e.toElement;var thePopUp=$("gastroPopUp");while(toElem!=thePopUp&&toElem.nodeName!='BODY')
toElem=toElem.parentNode;if(toElem==thePopUp){clearTimeout(this.chronoRemove);}
else{this.chronoRemove=setTimeout(function(){map.gastroPopUp.remove();},300);}}
gastroPopUp.prototype.remove=function(){clearTimeout(this.chronoRemove);if($d(this.popUp)&&this.popUp!=null){map.removePopup(this.popUp);}
if(this.popUp&&this.popUp.onRemove)
this.popUp.onRemove();this.popUp=null;}
gastroPopUp.prototype.getBufferAccordingToScale=function(){var scale=Math.round((map.getScale()*10000))/10000;var res=100;switch(scale){case 1924726:res=13000;break;case 300000:res=2000;break;case 150000:res=1000;break;case 60000:res=400;break;case 30000:res=200;break;case 15000:res=100;break;case 7500:res=40;break;case 6000:res=30;break;case 4000:res=20;break;case 2000:res=10;break;default:res=100;}
return res;}
function largePopUp(id){map.largePopUp=this;var topPosition=null;if(arguments.length>1){topPosition=arguments[1];}
return this.createLargePopUp(id,topPosition);};largePopUp.prototype.createLargePopUp=function(id,topPosition){this.disableBody();dBody=$(document.body);var bodyWidth=dBody.getWidth();this.popUp=$(document.createElement("div"));document.body.appendChild(this.popUp);this.popUp.id=id;this.popUp.style.position="absolute";var popUpWidth=this.popUp.getWidth();this.popUp.style.left=(bodyWidth/2)-(popUpWidth/2)+"px";if(topPosition)
this.popUp.style.top=topPosition+"px";else
this.popUp.style.top="0px";if(document.all){var sels=document.getElementsByTagName("select");for(var i=0;i<sels.length;i++){sels[i].style.visibility="hidden";}}
return this;};largePopUp.prototype.setText=function(content){this.popUp.innerHTML=content;};largePopUp.prototype.disableBody=function(){this.disabler=document.createElement("div");document.body.appendChild(this.disabler);this.disabler.id="popUpDisabler";this.disabler.style.position="absolute";this.disabler.style.top="0px";this.disabler.style.left="0px";this.disabler.style.width="100%";this.disabler.style.height="100%";};largePopUp.prototype.destroy=function(){var t=this;document.body.removeChild($(this.popUp));document.body.removeChild($("popUpDisabler"));if(document.all){var sels=document.getElementsByTagName("select");for(var i=0;i<sels.length;i++){sels[i].style.visibility="visible";}}};function layerMixer(map,idWidget,idSlider,idSupport,idPlus,idMinus,oLayers,defaultVisibility){this.widgetDiv=$(idWidget);this.slider=$(idSlider);this.support=$(idSupport);this.plus=$(idPlus);this.minus=$(idMinus);this.widgetIsVisible=defaultVisibility;if(!this.widgetIsVisible)
this.widgetDiv.style.visibility="hidden";this.changingOpacity=false;this.chrono=null;this.refLayer=oLayers.refLayer;this.otherLayer=oLayers.otherLayer;this.init();return this;};layerMixer.prototype.init=function(){var t=this;this.support.makePositioned();this.support.setStyle({overflow:"visible"});Event.observe(this.support,"click",this.handleSupportClick.bindAsEventListener(this));this.slider.style.position="absolute";Event.observe(this.minus,"mousedown",function(){t.changingOpacity=true;t.increaseOpacity()});Event.observe(this.minus,"mouseup",function(){t.changingOpacity=false});Event.observe(this.minus,"mouseout",function(){t.changingOpacity=false});Event.observe(this.plus,"mousedown",function(){t.changingOpacity=true;t.decreaseOpacity()});Event.observe(this.plus,"mouseup",function(){t.changingOpacity=false});Event.observe(this.plus,"mouseout",function(){t.changingOpacity=false});this.supportWidth=this.support.getWidth();this.supportHeight=this.support.getHeight();this.sliderWidth=this.slider.getWidth();this.sliderHeight=this.slider.getHeight();this.vertSliderPos=-(Math.round((this.sliderHeight-this.supportHeight)/2));this.slider.style.top=this.vertSliderPos+"px";this.slider.style.left="0px";this.range={min:0,max:this.supportWidth-this.sliderWidth-2};this.dragSlider=new Draggable(this.slider.id,{constraint:"horizontal",starteffect:null,endeffect:null,snap:function(x,y){return[x<t.range.max?(x>t.range.min?x:t.range.min):t.range.max,0]},change:this.dragging.bind(t)});this.updateOpacity(1);map.events.register("zoomend",this,this.updateWidgetVisibility);};layerMixer.prototype.updateWidgetVisibility=function(){if(map.getScale()>300010){this.widgetIsVisible=false;this.widgetDiv.style.visibility="hidden";}
else{this.widgetIsVisible=true;this.widgetDiv.style.visibility="visible";}}
layerMixer.prototype.dragging=function(o){if(!this.otherLayer.getVisibility())
this.otherLayer.setVisibility(true);var pos=o.currentDelta()[0];var op=Math.abs(100-(Math.round((pos*100)/this.range.max)));this.updateOpacity(op/100);}
layerMixer.prototype.updateOpacity=function(op){if(op==1)
this.otherLayer.setVisibility(false);if(op==0)
this.refLayer.setVisibility(false);if(op!=1&&op!=0){if(!this.refLayer.getVisibility())
this.refLayer.setVisibility(true);if(!this.otherLayer.getVisibility())
this.otherLayer.setVisibility(true);}
this.refLayer.setOpacity(op);this.otherLayer.setOpacity(1-op);var swissNames=map.getLayerByGroupName("Swissnames");var streets=map.getLayerByGroupName("streetmap");if(map.layerSwitcher){if(op<0.5){map.layerSwitcher.toggleLayerVisibility(swissNames,false,{dontUpdateIcon:true});map.layerSwitcher.toggleLayerVisibility(streets,false,{dontUpdateIcon:true});}
else{map.layerSwitcher.toggleLayerVisibility(swissNames,swissNames.legend.checkbox.checked);map.layerSwitcher.toggleLayerVisibility(streets,streets.legend.checkbox.checked);}}}
layerMixer.prototype.increaseOpacity=function(){if(this.changingOpacity==false&&this.chrono!=null){clearTimeout(this.chrono);return;}
this.changingOpacity=true;var curOp=(typeof this.refLayer.opacity!="undefined"?this.refLayer.opacity:1);this.updateOpacity((curOp+0.05>1)?1:curOp+0.05);this.updateSliderPosition();var t=this;this.chrono=window.setTimeout(this.increaseOpacity.bind(t),50);}
layerMixer.prototype.decreaseOpacity=function(){if(this.changingOpacity==false&&this.chrono!=null){clearTimeout(this.chrono);return;}
if(!this.otherLayer.getVisibility())
this.otherLayer.setVisibility(true);this.changingOpacity=true;var curOp=(typeof this.refLayer.opacity!="undefined"?this.refLayer.opacity:1);this.updateOpacity((curOp-0.05<0)?0:curOp-0.05);this.updateSliderPosition();var that=this;this.chrono=window.setTimeout(this.decreaseOpacity.bind(that),50);}
layerMixer.prototype.updateSliderPosition=function(){if(typeof this.refLayer.opacity!="undefined"){var newPosX=Math.round((this.range.max/100)*((1-this.refLayer.opacity)*100));new Effect.Move("opacity_slider",{x:newPosX,y:this.slider.offsetTop,mode:"absolute",duration:0.1});}}
layerMixer.prototype.handleSupportClick=function(e){e=(e)?e:((event)?event:null);var src=Event.element(e);if(src!=this.support)
return;var relPos=(typeof(e.offsetX)!="undefined")?(e.offsetX):((typeof(e.layerX)!="undefined")?(e.layerX):null);if(relPos<8)
relPos=0;if(relPos>this.supportWidth-8)
relPos=this.supportWidth;var newOp=1-(Math.round((relPos*100)/this.supportWidth)/100);this.updateOpacity(newOp);this.updateSliderPosition()};function layerSwitcherGastro(){this.gastroLayers=[];this.draw();map.events.register("visibilitychanged",this,this.updateAllIcons);return this;}
layerSwitcherGastro.prototype.draw=function(){var layers=map.layers;for(var i=0;i<layers.length;i++){if(typeof layers[i].legend=="undefined")
continue;if(typeof layers[i].legend.linkedWith!="undefined"&&layers[i].legend.isMaster==false)
continue;var htmlElem=this.getHTMLForLayer(layers[i]);$(layers[i].legend.container).appendChild(htmlElem);layers[i].legendStatus=layers[i].getVisibility()?"checked":"unchecked";if(this.isGastroLayer(layers[i]))
this.gastroLayers.push(layers[i]);}}
layerSwitcherGastro.prototype.destroy=function(){var layers=map.layers;for(var i=0;i<layers.length;i++){if(typeof layers[i].legend!="undefined"&&typeof layers[i].legend.container!="undefined"){$(layers[i].legend.container).innerHTML="";}}
map.events.unregister("visibilitychanged",this,this.updateAllIcons);this.gastroLayers=null;}
layerSwitcherGastro.prototype.getHTMLForLayer=function(oLayer){var tableCreate=map.myUtils.createTable(null,1,2);oLayer.legend.legendTable=tableCreate.table;tableCreate.table.className="tableLayer";var content=tableCreate.content;content[0][0].className="checkbox";if(typeof oLayer.legend.imgSources=="undefined"){try{var checkbox=document.createElement("<input type='checkbox'>");}
catch(e){var checkbox=document.createElement("input");checkbox.type="checkbox";}
content[0][0].appendChild(checkbox);checkbox.oLayer=oLayer;checkbox.checked=oLayer.getVisibility();oLayer.legend.checkbox=checkbox;checkbox.style.cursor="pointer";Event.observe(checkbox,"click",function(e){map.layerSwitcher.toggleWithGastroRules(Event.element(e).oLayer,Event.element(e).oLayer.legendStatus=="checked"?false:true)});}
else{var img=document.createElement("img");content[0][0].appendChild(img);oLayer.legend.icon=img;img.oLayer=oLayer;img.className=oLayer.getVisibility()?"selected":"unselected";img.src=oLayer.getVisibility()?oLayer.legend.imgSources.selected:oLayer.legend.imgSources.unselected;img.border="0";img.width="16";img.height="16";img.style.cursor="pointer";Event.observe(img,"click",function(e){map.layerSwitcher.toggleWithGastroRules(Event.element(e).oLayer,Event.element(e).oLayer.legendStatus=="checked"?false:true)});}
content[0][1].style.paddingLeft="4px";var spanName=document.createElement("span");content[0][1].appendChild(spanName);oLayer.legend.labelSpan=spanName;spanName.className=oLayer.getVisibility()?"selected":"unselected";spanName.appendChild(document.createTextNode(oLayer.name));spanName.oLayer=oLayer;Event.observe(spanName,"click",function(e){map.layerSwitcher.toggleWithGastroRules(Event.element(e).oLayer,Event.element(e).oLayer.legendStatus=="checked"?false:true)});return tableCreate.table;}
layerSwitcherGastro.prototype.toggleWithGastroRules=function(oLayer,vis,options){if(this.isGastroLayer(oLayer)==false){this.toggleLayerVisibility(oLayer,vis,options);return;}
if(vis==false){this.toggleLayerVisibility(oLayer,vis,options);return;}
else{var gastroType=getType(oLayer);if(gastroType=="all"){for(var i=0;i<this.gastroLayers.length;i++){this.gastroLayers[i].legendStatus="unchecked";}}
else if(gastroType=="ggg"){for(var i=0;i<this.gastroLayers.length;i++){if(this.gastroLayers[i].legend.container!="leg_blocGastro2")
this.gastroLayers[i].legendStatus="unchecked";}}
else if(gastroType=="others"){for(var i=0;i<this.gastroLayers.length;i++){if(this.gastroLayers[i].legend.container=="leg_blocGastro2"||this.gastroLayers[i].legend.container=="leg_blocGastro_res"||this.gastroLayers[i].params.g=="cat100"||this.gastroLayers[i].params.g=="cat200"||this.gastroLayers[i].params.g=="cat300"){this.gastroLayers[i].legendStatus="unchecked";}}}
else if(gastroType=="resLayer"){for(var i=0;i<this.gastroLayers.length;i++){this.gastroLayers[i].legendStatus="unchecked";}}
oLayer.legendStatus="checked";for(var i=0;i<this.gastroLayers.length;i++){if(this.gastroLayers[i].legend.isMaster==true){this.gastroLayers[i].legend.linkedWith.setVisibility(this.gastroLayers[i].legendStatus=="checked"?true:false,true);}
this.gastroLayers[i].setVisibility(this.gastroLayers[i].legendStatus=="checked"?true:false,true);}
for(var i=0;i<this.gastroLayers.length;i++){this.updateIcon(this.gastroLayers[i]);}
if(this.isGastroLayer(oLayer)){if(!(typeof options!="undefined"&&options.noEvent==true))
map.events.triggerEvent("gastroLayersChanged");}}
function getType(lay){var ggg=[];if(TRdom==1){var all=["cat100"];var others=["cat101","cat102","cat103","cat104","cat105","cat106","cat107","cat108","cat109","cat110","cat111","cat112","cat113","cat114","cat115","cat116"];}
if(TRdom==2){var all=["cat200"];var others=["cat201","cat202","cat203","cat204","cat205","cat206","cat207","cat208","cat209","cat210"];}
if(TRdom==3){var all=["cat300"];var others=["cat301","cat302","cat303","cat304","cat305","cat306","cat307","cat308"];}
if(TRdom==1)var resLayer=["res100"];if(TRdom==2)var resLayer=["res200"];if(TRdom==3)var resLayer=["res300"];if(in_array(lay.params.g,all))
return"all";if(in_array(lay.params.g,ggg))
return"ggg";if(in_array(lay.params.g,others))
return"others";if(in_array(lay.params.g,resLayer))
return"resLayer";return"none";}}
layerSwitcherGastro.prototype.toggleLayerVisibility=function(oLayer,vis,options){var updateIcon=true;if(options&&options.dontUpdateIcon&&options.dontUpdateIcon==true)
updateIcon=false;oLayer.setVisibility(vis,true);if(oLayer.legend.isMaster==true)
oLayer.legend.linkedWith.setVisibility(vis,true);oLayer.legendStatus=vis?"checked":"unchecked";if(updateIcon){this.updateIcon(oLayer);}
if(this.isGastroLayer(oLayer)){if(!(typeof options!="undefined"&&options.noEvent==true))
map.events.triggerEvent("gastroLayersChanged");}}
layerSwitcherGastro.prototype.updateAllIcons=function(){var layers=map.layers;for(var i=0;i<layers.length;i++){if($d(layers[i].legend)){this.updateIcon(layers[i]);}}}
layerSwitcherGastro.prototype.updateIcon=function(oLayer){if($d(oLayer.legend.icon)){oLayer.legend.icon.src=oLayer.getVisibility()?oLayer.legend.imgSources.selected:oLayer.legend.imgSources.unselected;oLayer.legend.icon.className=oLayer.getVisibility()?"selected":"unselected";oLayer.legend.labelSpan.className=oLayer.getVisibility()?"selected":"unselected";}
else if($d(oLayer.legend.checkbox)){oLayer.legend.checkbox.checked=oLayer.getVisibility();oLayer.legend.checkbox.className=oLayer.getVisibility()?"selected":"unselected";oLayer.legend.labelSpan.className=oLayer.getVisibility()?"selected":"unselected";}
oLayer.legendStatus=oLayer.getVisibility()?"checked":"unchecked";}
layerSwitcherGastro.prototype.isGastroLayer=function(oLayer){if($d(oLayer.legend)&&$d(oLayer.legend.container)){if(oLayer.legend.container=="leg_blocGastro1"||oLayer.legend.container=="leg_blocGastro2"||oLayer.legend.container=="leg_blocGastro_res"){return true;}
else{return false;}}}
function navTool(){map.navTool=this;this.chrono=null;this.delay=50;this.isMoving=false;}
navTool.prototype.moving=function(e){x=y=0;var amount=15;if(arguments.length>1){x=arguments[0];y=arguments[1];}
else{Event.stop(arguments[0]);if(map.getScale()>310000)
return;var direction=Event.element(arguments[0]).getAttribute("alt");switch(direction){case"up":y=-amount;break;case"right":x=amount;break;case"left":x=-amount;break;case"down":y=amount;break;case"up-right":x=amount;y=-amount;break;case"up-left":x=y=-amount;break;case"down-right":x=y=amount;break;case"down-left":x=-amount;y=amount;break;default:alert("not found : "+direction);}}
if(map.getScale()>310000)
return;map.pan(x,y,true);this.isMoving=true;this.chrono=window.setTimeout(this.moving.bind(this,x,y),this.delay);}
navTool.prototype.stopMoving=function(e){Event.stop(e);window.clearTimeout(this.chrono);this.chrono=null;if(this.isMoving){this.isMoving=false;map.events.triggerEvent("moveend");}}
function progZoomer(map,idSlider,idSupport,idPlus,idMinus){this.map=map;this.map.progZoomer=this;this.nbScales=this.map.getNumZoomLevels();this.slider=$(idSlider);this.support=$(idSupport);this.plus=$(idPlus);this.minus=$(idMinus);this.init();return this;};progZoomer.prototype.destroy=function(){this.map.events.unregister("zoomend",this,this.update);Event.stopObserving(this.support,"click",this.listeners.forSupport);Event.stopObserving(this.plus,"click",this.listeners.forPlus);Event.stopObserving(this.minus,"click",this.listeners.forMinus);this.map.progZoomer=null;}
progZoomer.prototype.init=function(){this.support.makePositioned();this.support.setStyle({overflow:"visible"});this.listeners={"forSupport":this.handleSupportClick.bindAsEventListener(this),"forMinus":function(){map.zoomOut()},"forPlus":function(){map.zoomIn()}};Event.observe(this.support,"click",this.listeners.forSupport);Event.observe(this.plus,"click",this.listeners.forPlus);Event.observe(this.minus,"click",this.listeners.forMinus);this.slider.style.position="absolute";this.supportWidth=this.support.getWidth();this.supportHeight=this.support.getHeight();this.sliderWidth=this.slider.getWidth();this.sliderHeight=this.slider.getHeight();this.vertSliderPos=-(Math.round((this.sliderHeight-this.supportHeight)/2));this.slider.style.top=this.vertSliderPos+"px";this.slider.style.left="0px";var t=this;this.range={min:0,max:this.supportWidth-this.sliderWidth-2};this.dragSlider=new Draggable(this.slider.id,{constraint:"horizontal",starteffect:null,endeffect:null,snap:function(x,y){return[x<t.range.max?(x>t.range.min?x:t.range.min):t.range.max,0]},onEnd:this.dragEnd_zoom.bind(t)});this.map.events.register("zoomend",this,this.update);};progZoomer.prototype.dragEnd_zoom=function(o){var zoom=this.retrieveZoom(o.currentDelta()[0]);this.adjustSliderOnScale(zoom);map.zoomTo(zoom);}
progZoomer.prototype.retrieveZoom=function(deltaX){var nearestScale=Math.abs(Math.round((deltaX/this.range.max)*(this.nbScales-1)));return nearestScale;}
progZoomer.prototype.adjustSliderOnScale=function(scale){var moveX=scale*Math.round((this.range.max/(this.nbScales-1)));new Effect.Move("zoom_slider",{x:moveX,y:this.vertSliderPos,mode:"absolute",duration:0.5});}
progZoomer.prototype.update=function(){var currentScale=this.map.getZoom();this.adjustSliderOnScale(currentScale);};progZoomer.prototype.handleSupportClick=function(e){e=(e)?e:((event)?event:null);var src=Event.element(e);if(src!=this.support)
return;var relPos=(typeof(e.offsetX)!="undefined")?(e.offsetX):((typeof(e.layerX)!="undefined")?(e.layerX):null);if(relPos>this.range.max)
relPos=this.range.max;var zoom=this.retrieveZoom(relPos);this.adjustSliderOnScale(zoom);map.zoomTo(zoom);};function resultLayer(){var resLayer=new OpenLayers.Layer.KaMap(tra['layer_Results'],'http://kamap.swissgeo.ch/tourisme-rural/tile_resultLayer.php?',{g:'res'+(TRdom*100),map:'tourismerural',i:'png'},{buffer:1,isBaseLayer:false,visibility:false});resLayer.legend={container:"leg_blocGastro_res",imgSources:{selected:'http://ms1.swissgeo.ch/toolkit/getIcon.php?map=tourismerural&g=cat'+(TRdom*100)+'&icon_width=16&icon_height=16',unselected:'http://ms1.swissgeo.ch/toolkit/getIcon.php?map=tourismerural&g=cat'+(TRdom*100)+'&icon_width=16&icon_height=16&out=true'}};resLayer.getURL=function(bounds){var mapRes=this.map.getResolution();var scale=Math.round((this.map.getScale()*10000))/10000;var pX=Math.round(bounds.left/mapRes);var pY=-Math.round(bounds.top/mapRes);var timeStmp=(new Date()).getTime();var params={t:pY,l:pX,s:scale,timestamp:timeStmp,dom:TRdom};if($d(map.sessionId))
params.sessionId=map.sessionId;return this.getFullRequestString(params);}
return resLayer;}
var routingFunctions=function(){map.routingFuncs=this;};routingFunctions.prototype.go=function(dep,arr,dataResto){this.readyToGetRoute=true;this.dataResto=dataResto;this.getAddress(dep,"ambiguousLoc1");this.getAddress(arr,"ambiguousLoc2");if(this.readyToGetRoute){this.getRoute();}
return false;};routingFunctions.prototype.getAddress=function(input,ambi){var inputAddress=new InputAddress(input['adr'],input['loc'],input['region'],input['npa'],input['pays']);if(typeof(input['long'])!="undefined"&&typeof(input['lat'])!="undefined"){inputAddress.long=input['long'];inputAddress.lat=input['lat'];}
searchAddresse(inputAddress,0,ambi);if(foundLocationsListArray!=null&&foundLocationsListArray.length>0){if(foundLocationsListArray[0].foundLocations.length==0){alert("no result");this.readyToGetRoute=false;}
if(foundLocationsListArray[0].foundLocations.length==1){$(ambi).loc=foundLocationsListArray[0].foundLocations;var locDef=new LocDefinition(null,foundLocationsListArray[0].foundLocations[0].locDesc.locid,null);locDefinitionList[locDefinitionList.length]=locDef;}
if(foundLocationsListArray[0].foundLocations.length>1){this.readyToGetRoute=false;$(ambi).loc=foundLocationsListArray[0].foundLocations;this.displayChoicesForLocation();}}
else{this.readyToGetRoute=false;return false;}};routingFunctions.prototype.displayChoicesForLocation=function(){$("routingBloc_container").hide();$("ambiguousLocations").show();$("ambiguousLoc1").focus();};routingFunctions.prototype.validateLocations=function(){try{addLocDefinition($("ambiguousLoc1").loc[$("ambiguousLoc1").selectedIndex].locDesc.locid,'StopoversTable');addLocDefinition($("ambiguousLoc2").loc[$("ambiguousLoc2").selectedIndex].locDesc.locid,'StopoversTable');$("routing_ambiguousButton").disabled=true;this.getRoute();}
catch(e){alert(tra['general_erreur_departOuDestIntrouvable']);}};routingFunctions.prototype.getRoute=function(){var d=new Date();var jour=d.getDate();var mois=d.getMonth()+1;var annee=d.getYear()+1900;if(annee>3000)
annee=annee-1900;var itiDate=jour+"/"+mois+"/"+annee;var vehicleType=0;var itiType=0;var favourMotorways=false;var avoidCrossingBorders=false;var avoidTolls=false;var avoidRoadTaxAreas=false;var avoidOffroadConnections=false;var avoidMountainPass=false;var itiPref=new ItineraryPreferences(favourMotorways,avoidCrossingBorders,avoidTolls,avoidRoadTaxAreas,avoidOffroadConnections,avoidMountainPass);var fuelCost=new Cost("","");var fuelConsumption=new Array();fuelConsumption[fuelConsumption.length]="";fuelConsumption[fuelConsumption.length]="";fuelConsumption[fuelConsumption.length]="";var itiOptions=new ItineraryOptions(itiDate,vehicleType,itiType,itiPref,fuelCost,fuelConsumption);var detailLevel=1;switch(appLanguage){case"fr":var language="fra";break;case"de":var language="deu";break;case"it":var language="ita";break;case"en":var language="eng";break;}
var instructionsFormat=0;var tollCategory=1;var presentationOptions=new ExtendedPresentationOptions(detailLevel,language,instructionsFormat,tollCategory);var responseElts=3;var mapDefCalc=1;var mainMapWidth=600;var mainMapHeight=600;var blocMapWidth=200;var blocMapHeight=200;var responseOptions=new ResponseOptions(responseElts,mapDefCalc,mainMapWidth,mainMapHeight,blocMapWidth,blocMapHeight);var itiRequest=new ItineraryRequest(locDefinitionList,itiOptions,presentationOptions,responseOptions);if((vehicleType=="2")||(vehicleType=="3")){routeCalculation_getRouteNonMotorized(itiRequest);}
else{routeCalculation_getRoute(itiRequest);}
return false;};routingFunctions.prototype.routingCallback=function(calculatedRoute,itiRequest){$("routing_ambiguousButton").disabled=false;locDefinitionList.splice(0,locDefinitionList.length);if((typeof(calculatedRoute)!="undefined")&&(calculatedRoute!=null)){if(calculatedRoute.roadmap!=null){this.itiHtmlCode=calculatedRoute.roadmap;}
if(calculatedRoute.mapId!=null){this.getItineraryMap(calculatedRoute.mapId,itiRequest.responseOptions.mainMapWidth,itiRequest.responseOptions.mainMapHeight,calculatedRoute.ititrace);}}};routingFunctions.prototype.getItineraryMap=function(mapId,mapWidth,mapHeight,oititraceList){ititraceList=oititraceList;mapManagement_getMapByID(mapId,mapWidth,mapHeight,null,0,true,null,null,oititraceList);};routingFunctions.prototype.getGeneratedMap=function(oMap){var VMPopUp=new largePopUp("VMPopUp",20);var imgUrl=oMap.mapURL;var descrIti=this.itiHtmlCode.replace(/src=\"img\/iti/g,"src=\"mapLibs/gastroTools/WS2Sample/img/iti");var content="<div style='background:rgb(102,115,175); color:white;font-family:arial; position:relative;width:100%'><span style='margin-left:3px'>"+tra['routing_itineraire']+"</span><a href='javascript:map.largePopUp.destroy()'><img style='border:none; position:absolute; right:3px; top:1px; width:11px; height:11px;' src='mapLibs/images/popUpSchliessen.gif'></a></div>";content+="<div id='mapDiv'><div id='mapContainer'><a id='print' href='javascript:this.print()'>"+tra['general_imprimer']+"&nbsp;<img style='border:none' src='images/printit.png'></a><img id='dynCarte' src='"+imgUrl+"'>";content+="<div style='margin:auto; margin-bottom:30px; text-align:left; width:600px;'><ins>"+tra['routing_votreRestaurant']+"</ins>";content+="<br><strong>"+this.dataResto['nom_orga']+"<br>"+this.dataResto['nom']+" "+this.dataResto['prenom']+"</strong><br>"+this.dataResto['localite_18']+", "+this.dataResto['canton']+"</div>";content+="</div>";content+="<div id='iti'>"+descrIti+"</div></div>";VMPopUp.setText(content);};var customScalebar=function(id){this.scaleDiv=$(id);this.maxWidth=140;map.events.register("zoomend",this,this.update);this.update();};customScalebar.prototype.update=function(){var resol=map.getResolution();var result=(resol*(this.maxWidth))/1000;if(result>=1){var isKM=true;result=Math.round((resol*(this.maxWidth))/1000);if(result>=10){result=(Math.floor(result/10))*10;newWidth=Math.round((result*1000)/(resol));this.scaleDiv.style.width=newWidth+"px";}}
else{result=Math.round(resol*(this.maxWidth));if(result%50!=0){result=(Math.floor((result*2)/100))*50;newWidth=Math.round(result/resol);this.scaleDiv.style.width=newWidth+"px";}}
this.scaleDiv.innerHTML=result+(isKM?"km":"m");};function geoSearch(){this.searchMask=$("searchMask_tab0");this.keywordField=$("keyword_tab0");this.cityField=$("tab0_placeSearch_autoComplete");this.searchButton=$("goButton_tab0");this.searchContainer=$("searchResultsContainer");this.evidenceContainer=$("restoInEvidenceContainer");this.nbrpp=6;this.limitForPerf=24;this.searchIsForbidden=false;map.events.register("moveend",this,geoSearchMapMoved_check);map.events.register("gastroLayersChanged",this,function(){geoSearchMapMoved_check()});return this;}
geoSearch.prototype.disableGeoSearch=function(){var lastState=this.searchIsForbidden;this.searchIsForbidden=true;return lastState;}
geoSearch.prototype.restoreGeoSearch=function(bActivate){this.searchIsForbidden=bActivate;}
geoSearch.prototype.mapMoved=function(options){var extents=map.getExtent();var enabledLayers=this.getEnabledGastroLayers();var layersStr="";for(var i=0;i<enabledLayers.length;i++){if(i!=0)
layersStr+=",";layersStr+=enabledLayers[i].params.g;}
if(layersStr==""){this.clearSearch();this.showSearchMask();return;}
var url="mapLibs/infoGetter.php?layers="+layersStr;if(bIsGastroLocal){url+="&region="+sRegion;}
url+="&extents="+Math.round(extents.left)+","+Math.round(extents.bottom)+","+Math.round(extents.right)+","+Math.round(extents.top);url+="&sessionType=tab0&lang="+appLanguage;if($d(map.sessionId))
url+="&sessionId="+map.sessionId;if(this.limitForPerf){if(!(options&&options.ignoreLimit))
url+="&resNb="+this.limitForPerf;}
this.loading(true);new OpenLayers.Ajax.Request(url,{onSuccess:(function(trsp){this.loading(false);try{eval(trsp.responseText);}
catch(e){alert("EVAL FAILED");}
map.sessionId=sessionId;this.displayResults(data,0,this.nbrpp-1,options);if(options&&options.goDirectlyToPage)
this.changePage({page:options.goDirectlyToPage,allData:data},options);}).bind(this)});}
geoSearch.prototype.search=function(){var keyword=this.keywordField.value;var extents=map.getExtent();var hasValidKeyword=!(/^\s*$/g).test(keyword);var mainLayer="cat"+(TRdom*100);if(cityMode=='auto'){var cityData=this.cityField.cityData;var hasValidCityString=!(/^\s*$/g).test(this.cityField.value);var hasValidCityData=($d(cityData)&&cityData!=null);}
else{var reg=new RegExp("[,]+","g");var coords=$F(this.cityField).split(reg);var cityData=new Object();cityData['long']=coords[0];cityData['lat']=coords[1];var hasValidCityString=true;var hasValidCityData=true;}
if(!hasValidCityString&&!hasValidKeyword)
return;this.hideResultLayer();var enabledLayers=this.getEnabledGastroLayers();var layersStr="";for(var i=0;i<enabledLayers.length;i++){if(i!=0)
layersStr+=",";layersStr+=enabledLayers[i].params.g;}
if(layersStr==""){layersStr=mainLayer;}
var url="mapLibs/infoGetter.php?layers="+layersStr+"&sessionType=tab0&isNewSearch=true";if(bIsGastroLocal){url+="&region="+sRegion;}
if($d(map.sessionId))
url+="&sessionId="+map.sessionId;var hasCenteredOnCity=false;if(hasValidKeyword){for(var i=0;i<enabledLayers.length;i++){enabledLayers[i].setVisibility(false,true);}
if(hasValidCityString&&hasValidCityData){map.setCenter(new OpenLayers.LonLat(cityData['long'],cityData['lat']),getScaleAsInteger(30000),true,false,true);map.ovMapControl.update();hasCenteredOnCity=true;}
else{if(hasValidCityString){try{eval(this.getCityListSync(this.cityField.value));}
catch(e){alert("city not found (error with server)");return;}
if(cityData.length>0){this.cityField.cityData=cityData;map.setCenter(new OpenLayers.LonLat(cityData[0]['long'],cityData[0]['lat']),getScaleAsInteger(30000),true,false,true);map.ovMapControl.update();hasCenteredOnCity=true;}
else{alert("city not found");}}
else{var lastState=this.disableGeoSearch();map.zoomTo(0);this.restoreGeoSearch(lastState);}}
if(hasCenteredOnCity){var center=map.getCenter();var ext=map.getExtent();url+="&locate="+center.lon+","+center.lat;url+="&buffer="+Math.round(Math.abs(ext.right-center.lon))+","+Math.round(Math.abs(ext.top-center.lat));}
url+="&keyword="+getFormattedKeyword(this.keywordField.value);this.loading(true);new Ajax.Request(url,{onSuccess:this.queryCallback.bindAsEventListener(this)});}
else{if(hasValidCityString&&hasValidCityData){if(layersStr==mainLayer){var lastState=this.disableGeoSearch();map.layerSwitcher.toggleWithGastroRules(map.getLayerByGroupName(mainLayer),true);this.restoreGeoSearch(lastState);}
map.setCenter(new OpenLayers.LonLat(cityData['long'],cityData['lat']),getScaleAsInteger(30000));}
else{if(hasValidCityString){try{eval(this.getCityListSync(this.cityField.value));}
catch(e){alert("city not found (error with server)");return;}}
if(cityData.length>0){this.cityField.cityData=cityData;map.setCenter(new OpenLayers.LonLat(cityData[0]['long'],cityData[0]['lat']),getScaleAsInteger(30000));}
else{alert("city not found");}}}}
geoSearch.prototype.queryCallback=function(trsp){this.loading(false);try{eval(trsp.responseText);}
catch(e){alert("EVAL FAILED");}
map.sessionId=sessionId;if(!(/^\s*$/g).test(this.keywordField)){this.uncheckAllGastro(null);this.showResultLayer();}
this.displayResults(data,0,this.nbrpp-1);}
geoSearch.prototype.showResultLayer=function(){var resLayer=map.getLayerByGroupName('res'+(100*TRdom));$(resLayer.legend.container).show();map.layerSwitcher.toggleWithGastroRules(resLayer,true,{noEvent:true});$("leg_blocGastro").style.height="240px";}
geoSearch.prototype.hideResultLayer=function(){var resLayer=map.getLayerByGroupName('res'+(100*TRdom));$(resLayer.legend.container).hide();map.layerSwitcher.toggleWithGastroRules(resLayer,false,{noEvent:true});$("leg_blocGastro").style.height="220px";}
geoSearch.prototype.uncheckAllGastro=function(oLayerException){var layers=map.layers;for(var i=0;i<layers.length;i++){if($d(oLayerException)&&oLayerException!=null&&layers[i]==oLayerException)
continue;else{if($d(layers[i].legend)&&$d(layers[i].legend.container)&&isAGastroContainer(layers[i].legend.container)){layers[i].setVisibility(false,true);}}}
map.layerSwitcher.updateAllIcons();function isAGastroContainer(n){if(n=="leg_blocGastro_res"||n=="leg_blocGastro1"||n=="leg_blocGastro2")
return true;else
return false;}}
geoSearch.prototype.getCityListSync=function(input){var res="";this.requestId=Math.round(Math.random()*10000);new Ajax.Request("mapLibs/proxy.php?url="+encodeURIComponent("www.swissgeo.ch/api2/kamapGateway.php?action=getCity&requestId="+this.requestId+"&input="+escape(input)),{asynchronous:false,onSuccess:function(trsp){res=trsp.responseText}});return res;}
geoSearch.prototype.getEnabledGastroLayers=function(){var res=[];for(var i=0;i<map.layers.length;i++){var cur=map.layers[i];if(typeof cur.legend=="undefined")
continue;if(cur.legend.container=="leg_blocGastro1"||cur.legend.container=="leg_blocGastro2"||cur.legend.container=="leg_blocGastro_res"){if(cur.getVisibility())
res.push(map.layers[i]);}}
return res;}
geoSearch.prototype.displayResults=function(allData,lower,upper,options){this.clearSearch();upper=(upper>=allData.length)?allData.length-1:upper;var nbResults=upper-lower+1;var nbPages=Math.ceil(allData.length/this.nbrpp);var container=$(document.createElement("div"));this.searchContainer.appendChild(container);container.appendChild(getTitle());if(allData.length==0){var div=document.createElement("div");container.appendChild(div);div.className="blocInfoResto";div.style.background="rgb(239,244,251)";div.style.paddingTop="10px";div.style.paddingBottom="10px";var ct=map.myUtils.createTable(null,1,1);div.appendChild(ct.table);ct.content[0][0].innerHTML=tra['tab1_noResults'];}
for(var i=0;i<nbResults;i++){var restoBloc=this.getHTMLBlocForResto(allData[lower+i],allData);restoBloc.style.background=(i%2==0?"rgb(239,244,251)":"white");container.appendChild(restoBloc);}
if(!(options&&options.ignoreLimit)&&upper==allData.length-1&&allData.length>=this.limitForPerf){var currentPage=Math.floor(upper/this.nbrpp);var div=document.createElement("div");container.appendChild(div);div.style.textAlign="center";div.style.marginTop="6px";div.style.marginBottom="6px";var but=map.myUtils.createButton();but.className="gastroButton";but.style.width="auto";but.value=tra['general_montrerPlusDeRestaurants'];var that=this;Event.observe(but,"click",function(){that.getAllResults(currentPage+1)});div.appendChild(but);}
if(nbPages>1)
container.appendChild(this.createIndex(allData,lower,upper,options));this.showSearchResults();function getTitle(){var tableCreate=map.myUtils.createTable(null,1,3);var content=tableCreate.content;content[0].className="titleLine";content[0][0].className="tdTitle";content[0][0].innerHTML=tra['general_listeDesResultats'];var img=document.createElement("img");content[0][1].appendChild(img);content[0][1].className="tdImg";img.src="mapLibs/images/restartGastro.gif";Event.observe(img,"click",function(){window.location.href=window.location.protocol+"//"+window.location.host+window.location.pathname});var img=document.createElement("img");content[0][2].appendChild(img);content[0][2].className="tdImg";img.src="mapLibs/images/lupe.gif";Event.observe(img,"click",function(){$("searchMask_backToSearchResults").show();map.geoSearch.showSearchMask()});return tableCreate.table;}}
geoSearch.prototype.getAllResults=function(page){this.mapMoved({goDirectlyToPage:page,ignoreLimit:true});return this;}
geoSearch.prototype.putInEvidence=function(restoData,allData){while(this.evidenceContainer.childNodes.length>0){this.evidenceContainer.removeChild(this.evidenceContainer.childNodes[0]);}
var tableCreate=map.myUtils.createTable(null,1,3);this.evidenceContainer.appendChild(tableCreate.table);var content=tableCreate.content;content[0].className="titleLine";content[0][0].className="tdTitle";content[0][0].innerHTML=tra['tab1_headerText_restoDetail'];var img=document.createElement("img");content[0][1].appendChild(img);content[0][1].className="tdImg";img.src="mapLibs/images/restartGastro.gif";Event.observe(img,"click",function(){window.location.href=window.location.protocol+"//"+window.location.host});var img=document.createElement("img");content[0][2].appendChild(img);content[0][2].className="tdImg";img.src="mapLibs/images/trefferliste.gif";Event.observe(img,"click",function(){map.geoSearch.showSearchResults()});var restoBloc=this.getHTMLBlocForResto(restoData,allData);restoBloc.style.background="rgb(239,244,251)";restoBloc.imgRouting.src="mapLibs/images/routing_click.gif";Event.stopObserving(restoBloc.imgRouting,"mouseover",restoBloc.imgRouting.fct_over);Event.stopObserving(restoBloc.imgRouting,"mouseout",restoBloc.imgRouting.fct_normal);Event.stopObserving(restoBloc.imgRouting,"click",restoBloc.imgRouting.fct_click);Event.observe(restoBloc.imgRouting,"click",this.showSearchResults.bind(this));this.evidenceContainer.appendChild(restoBloc);this.showEvidenceContainer();var routingBloc=this.getRoutingHTMLForResto(restoData);this.evidenceContainer.appendChild(routingBloc);var but=map.myUtils.createButton();this.evidenceContainer.appendChild(but);but.value=tra['tab1_button_displayOtherResto'];but.className="gastroButton";but.style.width="100%";but.style.height="25px";but.style.marginTop="20px";Event.observe(but,"click",geoSearchMapMoved_check);}
geoSearch.prototype.getRoutingHTMLForResto=function(restoData){var th=this;var rBloc=document.createElement("div");rBloc.id="routingBloc";var tableCreate=map.myUtils.createTable(null,1,1);rBloc.appendChild(tableCreate.table);var content=tableCreate.content;tableCreate.table.className="title";content[0][0].innerHTML=tra['routing_itineraire'];var container=document.createElement("div");rBloc.appendChild(container);container.className="container";container.id="routingBloc_container";var tc=map.myUtils.createTable(null,6,1);container.appendChild(tc.table);var mainContent=tc.content;var nomPrenom=restoData['nom_orga']+"<br>"+restoData['nom']+' '+restoData['prenom'];var c1="<strong>"+tra['routing_adresseArrivee']+"</strong><br/>";c1+=nomPrenom+"<br/>";c1+=restoData['localite_18']+", "+restoData['canton'];mainContent[0][0].innerHTML=c1;mainContent[1][0].innerHTML="<strong>"+tra['routing_adresseDepart']+"</strong>";mainContent[1][0].style.paddingTop="10px";tc=map.myUtils.createTable(null,2,2);mainContent[2][0].appendChild(tc.table);mainContent[2][0].style.paddingTop="5px";tc.content[0][0].innerHTML=tra['routing_nomRue'];tc.content[0][1].innerHTML=tra['routing_noMaison'];var in1=document.createElement("input");in1.id="routingForm_rue";in1.style.width="140px";in1.onsubmit=function(e){map.geoSearch.goRouting(e)};tc.content[1][0].appendChild(in1);var in2=document.createElement("input");in2.id="routingForm_no";in2.style.width="30px";in2.onsubmit=function(e){map.geoSearch.goRouting(e)};tc.content[1][1].appendChild(in2);tc=map.myUtils.createTable(null,2,2);mainContent[3][0].style.paddingTop="5px";mainContent[3][0].appendChild(tc.table);tc.content[0][0].innerHTML=tra['routing_npa'];tc.content[0][1].innerHTML=tra['routing_localite'];var in1=document.createElement("input");in1.id="routingForm_npa";in1.style.width="50px";in1.onsubmit=function(e){map.geoSearch.goRouting(e)};tc.content[1][0].appendChild(in1);var in2=document.createElement("input");in2.id="routingForm_loc";in2.style.width="116px";in2.onsubmit=function(e){map.geoSearch.goRouting(e)};tc.content[1][1].appendChild(in2);tc=map.myUtils.createTable(null,1,1);mainContent[4][0].appendChild(tc.table);mainContent[4][0].style.paddingTop="15px";var sel=document.createElement("select");sel.id="routingForm_pays";sel.style.width="178px";sel.onsubmit=function(e){map.geoSearch.goRouting(e)};var countries=[["CHE",tra['general_suisse']],["FRA",tra['general_france']],["DEU",tra['general_allemagne']],["ITA",tra['general_italie']],["LIE",tra['general_liechtenstein']]];for(var i=0;i<countries.length;i++){var opt=document.createElement("option");sel.appendChild(opt);opt.value=countries[i][0];opt.innerHTML=countries[i][1];}
tc.content[0][0].appendChild(sel);tc=map.myUtils.createTable(null,1,1);mainContent[5][0].appendChild(tc.table);mainContent[5][0].style.paddingTop="15px";var but=map.myUtils.createButton();tc.content[0][0].appendChild(but);but.value=tra['general_calculerIti'];but.className="gastroButton";but.restoData=restoData;Event.observe(but,"click",map.geoSearch.goRouting.bindAsEventListener(map.geoSearch));var ambi=$(document.createElement("div"));rBloc.appendChild(ambi);ambi.id="ambiguousLocations";ambi.className="container";ambi.hide();var textTable=map.myUtils.createTable(null,1,1);ambi.appendChild(textTable.table);textTable.content[0][0].innerHTML=tra['routing_pleaseSelect'];var select=document.createElement("select");ambi.appendChild(select);select.id="ambiguousLoc1";select.style.margin="10px 0px";var select=document.createElement("select");ambi.appendChild(select);select.id="ambiguousLoc2";var button=map.myUtils.createButton();ambi.appendChild(button);button.id="routing_ambiguousButton";button.className="gastroButton";button.value=tra['general_calculerIti'];button.onclick=function(){map.routingFuncs.validateLocations()};button.style.marginTop="10px";return rBloc;}
geoSearch.prototype.goRouting=function(e){e=(e)?e:((event)?event:null);var restoData=Event.element(e).restoData;var dep=[];dep['adr']=$("routingForm_rue").value+" "+$("routingForm_no").value;dep['npa']=$("routingForm_npa").value;dep['loc']=$("routingForm_loc").value;dep['region']="";dep['pays']=$F($("routingForm_pays"));var arr=[];arr['long']=restoData['long'];arr['lat']=restoData['lat'];arr['adr']=restoData['adr'];arr['npa']=restoData['npa'];arr['loc']=restoData['loc'];arr['region']="";arr['pays']="CHE";map.routingFuncs.go(dep,arr,restoData);return false;}
geoSearch.prototype.getHTMLBlocForResto=function(restoData,allData){var divContainer=document.createElement("div");divContainer.className="blocInfoResto";var table=document.createElement("table");divContainer.appendChild(table);table.cellSpacing="0";table.cellPadding="0";table.style.emptyCells="show";var tbody=document.createElement("tbody");table.appendChild(tbody);if(restoData['nom_orga']!=""){var tr=document.createElement("tr");tbody.appendChild(tr);var td=document.createElement("td");tr.appendChild(td);td.colSpan=2;if(typeof clientIsLogged!="undefined"&&clientIsLogged==true){var tc=map.myUtils.createTable(null,1,2);td.appendChild(tc.table);tc.content[0][0].innerHTML="<b>"+restoData['nom']+"</b>";var img=document.createElement("img");img.src="mapLibs/images/modifyResto.png";img.alt=tra['modifyResto'];img.title=tra['modifyResto'];img.style.cursor="pointer";img.restoData=restoData;Event.observe(img,"click",function(e){new restoModification(Event.element(e).restoData)});tc.content[0][1].appendChild(img);tc.content[0][1].style.width="12px";}
else{td.innerHTML="<b>"+restoData['nom_orga']+"</b>";}}
if(restoData['nom']!=""||restoData['prenom']!=""){var tr=document.createElement("tr");tbody.appendChild(tr);var td=document.createElement("td");tr.appendChild(td);td.colSpan=2;if(restoData['nom']!=""&&restoData['prenom']!=""){var nomPrenom=restoData['nom']+' '+restoData['prenom'];}
else{var nomPrenom=restoData['nom']+restoData['prenom'];}
td.innerHTML="<b>"+nomPrenom+"</b>";}
if(restoData['localite_18']!=""){var tr=document.createElement("tr");tbody.appendChild(tr);var td=document.createElement("td");tr.appendChild(td);td.colSpan=2;var locCanton="";if(restoData['localite_18']!=""&&restoData['canton']!=""){locCanton=restoData['localite_18']+", "+restoData['canton'];}
else{locCanton=restoData['localite_18']+restoData['canton'];}
td.innerHTML=locCanton;}
if(typeof(restoData['prestations']=="Array"&&restoData['prestations'].length>0)){var tr=document.createElement("tr");tbody.appendChild(tr);var td=document.createElement("td");tr.appendChild(td);td.innerHTML='';for(var i=0;i<restoData['prestations'].length;i++){if(typeof(restoData['prestations'][i])!="undefined")
td.innerHTML+='<div><img height="11" width="11" border="0" align="absmiddle" src="images/coche.png"/>'+restoData['prestations'][i]+'</div>';}}
var tr=document.createElement("tr");tbody.appendChild(tr);var td=document.createElement("td");tr.appendChild(td);td.style.textAlign="right";var img=document.createElement("img");if(restoData['id']>0){img.data24=restoData;img.allData=allData;img.src="mapLibs/images/info_normal.gif";img.style.cursor="pointer";img.alt='Info';img.title='Info';Event.observe(img,"mouseover",function(e){Event.element(e).src="mapLibs/images/info_over.gif"});Event.observe(img,"mouseout",function(e){Event.element(e).src="mapLibs/images/info_normal.gif"});Event.observe(img,"mousedown",function(e){Event.element(e).src="mapLibs/images/info_click.gif"});Event.observe(img,"mouseup",function(e){Event.element(e).src="mapLibs/images/info_over.gif"});Event.observe(img,"click",map.search.showFullDetails.bindAsEventListener(map.search));}
else{img.src="mapLibs/images/a_pixel.gif";}
img.style.width="18px";img.style.padding="0px 2px";td.appendChild(img);var img=document.createElement("img");if(restoData['long']!=-1&&(restoData['quality_geom']==1||restoData['quality_geom']==4)){img.src="mapLibs/images/mapMe_normal.gif";img.restoData=restoData;img.style.cursor="pointer";Event.observe(img,"mouseover",function(e){Event.element(e).src="mapLibs/images/mapMe_over.gif"});Event.observe(img,"mouseout",function(e){Event.element(e).src="mapLibs/images/mapMe_normal.gif"});Event.observe(img,"mousedown",function(e){Event.element(e).src="mapLibs/images/mapMe_click.gif"});Event.observe(img,"mouseup",function(e){Event.element(e).src="mapLibs/images/mapMe_over.gif"});Event.observe(img,"mouseover",function(e){addRedMarker(e)});img.alt='Map';img.title='Map';}
else{img.src="mapLibs/images/a_pixel.gif";}
img.style.width="18px";img.style.padding="0px 2px";td.appendChild(img);var img=document.createElement("img");if(restoData['long']!=-1){divContainer.imgRouting=img;img.src="mapLibs/images/routing_normal.gif";img.style.cursor="pointer";img.restoData=restoData;img.allData=allData;img.fct_normal=function(e){Event.element(e).src="mapLibs/images/routing_normal.gif"};img.fct_over=function(e){Event.element(e).src="mapLibs/images/routing_over.gif"};img.fct_clicked=function(e){Event.element(e).src="mapLibs/images/routing_click.gif"}
img.fct_click=function(e){map.geoSearch.putInEvidence(Event.element(e).restoData,Event.element(e).allData)}
img.alt='Routing';img.title='Routing';Event.observe(img,"mouseover",img.fct_over);Event.observe(img,"mouseout",img.fct_normal);Event.observe(img,"mousedown",img.fct_clicked);Event.observe(img,"mouseup",img.fct_over);Event.observe(img,"click",img.fct_click);}
else{img.src="mapLibs/images/a_pixel.gif";}
img.style.width="18px";img.style.padding="0px 2px";td.appendChild(img);return divContainer;}
geoSearch.prototype.createIndex=function(allData,lower,upper,options){var nbPages=Math.ceil(allData.length/this.nbrpp);var curPage=Math.floor(lower/this.nbrpp);var container=document.createElement("div");container.className="index";if(curPage>0){container.appendChild(createPageLink("|<",0));container.appendChild(createPageLink("<<",(curPage-10<0?0:curPage-10)));container.appendChild(createPageLink("<",(curPage-1<0?0:curPage-1)));}
var lowerBound=(curPage-2<0)?0:curPage-2;var upperBound=(curPage+2>=nbPages)?nbPages-1:curPage+2;for(var i=lowerBound;i<=upperBound;i++){a=createPageLink((i+1),i);if(i==curPage)
a.style.fontWeight="bold";container.appendChild(a);}
if(curPage<nbPages-1){container.appendChild(createPageLink(">",(curPage+1>=nbPages?nbPages-1:curPage+1)));container.appendChild(createPageLink(">>",(curPage+10>=nbPages?nbPages-1:curPage+10)));container.appendChild(createPageLink(">|",nbPages-1));}
return container;function createPageLink(label,page){var a=document.createElement("a");a.innerHTML=label;a.href="#";a.allData=allData;a.page=page;a.onclick=function(){return false};Event.observe(a,"click",function(e){map.geoSearch.changePage({page:Event.element(e).page,allData:Event.element(e).allData},options);return false;});return a;}}
geoSearch.prototype.changePage=function(oData,options){var page=oData.page;var allData=oData.allData;var lower=page*this.nbrpp;var upper=lower+this.nbrpp-1;this.displayResults(allData,lower,upper,options);return false;}
geoSearch.prototype.showRestoInMap=function(id){var mainLayer="cat"+(100*TRdom);var url="mapLibs/infoGetter.php?layers="+mainLayer+"&idItem="+id+"&sessionType=tab0&lang="+appLanguage;if($d(map.sessionId))
url+="&sessionId="+map.sessionId;new Ajax.Request(url,{onSuccess:this.showRestoInMap_callback.bindAsEventListener(this)});}
geoSearch.prototype.showRestoInMap_callback=function(trsp){try{eval(trsp.responseText);}
catch(e){return;}
if(data.length>0){map.stateMachine.switchState("tab0-null",true);switchBottomTab($("tabTourisme_activer"));this.putInEvidence(data[0],[]);map.setCenter(new OpenLayers.LonLat(data[0]['long'],data[0]['lat']),4,true,false,true);map.ovMapControl.update();addRedMarker(new OpenLayers.LonLat(data[0]['long'],data[0]['lat']));}}
geoSearch.prototype.clearSearch=function(){while(this.searchContainer.childNodes.length>0){this.searchContainer.removeChild(this.searchContainer.childNodes[0]);}}
geoSearch.prototype.showSearchMask=function(){this.hideEvidenceContainer();this.hideSearchResults();this.searchMask.show();this.currentActivatedDiv="searchMask";}
geoSearch.prototype.hideSearchMask=function(){this.searchMask.hide();}
geoSearch.prototype.showSearchResults=function(){if(this.currentActivatedDiv&&this.currentActivatedDiv!="searchResults")
dhtmlHistory.saveState();this.hideEvidenceContainer();this.hideSearchMask();if(this.searchContainer.childNodes.length==0)
geoSearchMapMoved_check();this.searchContainer.show();this.currentActivatedDiv="searchResults";}
geoSearch.prototype.hideSearchResults=function(){this.searchContainer.hide();}
geoSearch.prototype.showEvidenceContainer=function(){this.hideSearchResults();this.hideSearchMask();this.evidenceContainer.show();this.currentActivatedDiv="evidenceContainer";}
geoSearch.prototype.hideEvidenceContainer=function(){this.evidenceContainer.hide();}
geoSearch.prototype.loading=function(bLoading){if(bLoading){$("geoSearch_sablier").show();this.searchButton.disabled=true;}
else{$("geoSearch_sablier").hide();this.searchButton.disabled=false;}}
function getFormattedKeyword(keyword){keyword=keyword.replace(/\s+\/\s+/g," ");keyword=keyword.replace(/\-/g," ");keyword=keyword.replace(/^\s+/g,"");keyword=keyword.replace(/\s+$/g,"");keyword=keyword.replace(/\s+/g,",");keyword=keyword.replace(/,+/g,",");var theKeywords=keyword.split(",");for(var i=0;i<theKeywords.length;i++){theKeywords[i]=escape(theKeywords[i]);}
keyword=theKeywords.join(",");return keyword;}
function myUtils(map){this.map=map;this.map.myUtils=this;}
myUtils.prototype.createTable=function(id,rows,cols){var table=document.createElement("table");if(id!=null&&id!="")
table.id=id;table.cellSpacing="0";table.cellPadding="0";var tbody=document.createElement("tbody");table.appendChild(tbody);table.body=tbody;var tableContent=new Array();for(var i=0;i<rows;i++){tr=document.createElement("tr");tbody.appendChild(tr);tableContent.push(tr);for(var j=0;j<cols;j++){td=document.createElement("td");tr.appendChild(td);tableContent[tableContent.length-1][j]=td;}}
return{table:table,content:tableContent};}
myUtils.prototype.createButton=function(){try{var button=document.createElement("<input type='button'>");}
catch(e){var button=document.createElement("input");button.type="button";}
return button;}
myUtils.prototype.findObjectPosition=function(obj){var curleft=curtop=0;if(obj.offsetParent){curleft=obj.offsetLeft;curtop=obj.offsetTop;while(obj=obj.offsetParent){curleft+=obj.offsetLeft;curtop+=obj.offsetTop;}}
return[curleft,curtop];}
myUtils.prototype.makeEnterSensitive=function(field,obj,fct){field.onkeyup=function(e){e=e?e:(event?event:null);var code=e.keyCode;if(code==Event.KEY_RETURN){fct.apply(obj);}}}
myUtils.prototype.isEmpty=function(text){return(/^\s*$/g).test(text);}
myUtils.prototype.blink=function(targets,delay,blinkCounter){if(blinkCounter==0)
return;for(var i=0;i<targets.length;i++){$(targets[i]).style.border="2px solid red";}
window.setTimeout(function(){for(var i=0;i<targets.length;i++){$(targets[i]).style.border="1px solid #6673AF";};window.setTimeout(function(){blink(targets,delay,--blinkCounter)},delay)},delay);}
myUtils.prototype.getPageSize=function(){var xScroll,yScroll;if(window.innerHeight&&window.scrollMaxY){xScroll=document.body.scrollWidth;yScroll=window.innerHeight+window.scrollMaxY;}
else if(document.body.scrollHeight>document.body.offsetHeight){xScroll=document.body.scrollWidth;yScroll=document.body.scrollHeight;}
else{xScroll=document.body.offsetWidth;yScroll=document.body.offsetHeight;}
var windowWidth,windowHeight;if(self.innerHeight){windowWidth=self.innerWidth;windowHeight=self.innerHeight;}
else if(document.documentElement&&document.documentElement.clientHeight){windowWidth=document.documentElement.clientWidth;windowHeight=document.documentElement.clientHeight;}
else if(document.body){windowWidth=document.body.clientWidth;windowHeight=document.body.clientHeight;}
if(yScroll<windowHeight){pageHeight=windowHeight;}
else{pageHeight=yScroll;}
if(xScroll<windowWidth){pageWidth=windowWidth;}
else{pageWidth=xScroll;}
arrayPageSize=new Array(pageWidth,pageHeight,windowWidth,windowHeight)
return arrayPageSize;}
myUtils.prototype.disableViewport=function(){if(this.disabler)
return;this.disabler=document.createElement("div");document.body.appendChild(this.disabler);this.disabler.style.background="white";this.disabler.style.opacity=0.7;this.disabler.style.mozOpacity=0.7;this.disabler.style.filter="Alpha(opacity=70)";this.disabler.id="popUpDisabler";this.disabler.style.position="absolute";this.disabler.style.top="0px";this.disabler.style.left="0px";this.disabler.style.width="100%";this.disabler.style.height=this.getPageSize()[1]+"px";this.disabler.style.zIndex=300;if(navigator.userAgent.toLowerCase().indexOf("msie 6.")!=-1){var aSelects=document.getElementsByTagName("select");for(var i=0;i<aSelects.length;i++){aSelects[i].style.visibility="hidden";}}}
myUtils.prototype.destroyViewportDisabler=function(){if(this.disabler)
document.body.removeChild(this.disabler);this.disabler=null;if(navigator.userAgent.toLowerCase().indexOf("msie 6.")!=-1){var aSelects=document.getElementsByTagName("select");for(var i=0;i<aSelects.length;i++){aSelects[i].style.visibility="visible";}}}
function search(){this.searchForm_simple=$("searchForm_simple");this.searchForm_fine=$("searchForm_fine");this.nbrpp=10;this.tabResults=$("tab_searchResults");this.tabDetails=$("tab_gastroDetails");this.goButtonTab1=$("goButton_tab1");this.goButtonTab2=$("goButton_tab2");this.currentIdGastro=null;return this;}
search.prototype.goSearch=function(){oForm=this.getCurrentForm();var sessionType=map.stateMachine.getCurrentTab();var keyword=oForm.keyword.value;var url="mapLibs/dataSearch.php?layers=cat"+(TRdom*100)+"&isNewSearch=true&sessionType="+sessionType+"&dom="+TRdom;if(bIsGastroLocal){url+="&region="+sRegion;}
url+="&"+oForm.serialize();var criterias=this.getCriterias(oForm);for(var i in criterias)
url+="&"+i+"="+criterias[i];if($d(map.sessionId))
url+="&sessionId="+map.sessionId;url+="&lang="+appLanguage;this.loading(this.getCurrentForm().id,true);var that=this;new OpenLayers.Ajax.Request(url,{onSuccess:function(trsp){that.searchCallback(trsp)}});};search.prototype.criteriasRegardingIndex=function(oForm){var crits="";var cats=[];var cui=[];var part=[];for(var i=0;i<this.keywordIndexTab1.links.length;i++){curNode=this.keywordIndexTab1.links[i];var keyword=oForm.keyword.value;var reg=new RegExp(curNode.innerHTML,"ig");if(reg.test(keyword)){if(!curNode.name)
continue;type=curNode.name.match(/category|food|special/)[0];value=curNode.name.match(/\d+/)[0];switch(type){case"category":cats.push(value);break;case"food":cui.push(value);break;case"special":part.push(value);break;}
oForm.keyword.value=keyword.replace(reg,"");}}
if(cats.length>0)
crits+=(crits==""?"":"&")+"cat="+cats.join(",");if(cui.length>0)
crits+=(crits==""?"":"&")+"cuisine="+cui.join(",");if(part.length>0)
crits+=(crits==""?"":"&")+"partic="+part.join(",");return crits;};search.prototype.getCriterias=function(oForm){var fields={};if(cityMode=='auto'){if($d(oForm.place.cityData)&&oForm.place.cityData!=null&&$d(oForm.place.cityData['long'])){fields.locate=oForm.place.cityData['long']+",";fields.locate+=oForm.place.cityData['lat'];}
else{if(!(/^\s*$/g).test($F(oForm.place))){try{eval(map.geoSearch.getCityListSync($F(oForm.place)));}
catch(e){alert("eval failed for getCityListSync");cityData=[];}
if(cityData.length>0){$(oForm.place).cityData=cityData[0];fields.locate=oForm.place.cityData['long']+",";fields.locate+=oForm.place.cityData['lat'];}}}}
else{fields.locate=$F(oForm.place);}
return fields;};search.prototype.searchCallback=function(trsp){this.loading(this.getCurrentForm().id,false);try{eval(trsp.responseText);map.sessionId=sessionId;}
catch(e){alert("Undefined error");data=[];}
if($d(data)&&data.length>0){this.removeResults();this.displayResults(data,0,this.nbrpp-1);}
else{this.displayError(tra['general_pasDeResultats']);}};search.prototype.displayError=function(msg){var t=this;var myTab=map.stateMachine.getCurrentTab();var myID='errorBox_'+myTab;var myDiv=$(myID);myDiv.innerHTML=msg;myDiv.style.display='block';new Effect.Highlight(myID,{startcolor:'#FF2222',endcolor:'#FFDEDE',transition:Effect.Transitions.linear,duration:1,queue:'front'});new Effect.Opacity(myID,{duration:1.0,transition:Effect.Transitions.linear,from:1.0,to:0.0,delay:5.0,queue:'end',afterFinish:t.resetBox});};search.prototype.resetBox=function(){var myTab=map.stateMachine.getCurrentTab();var myID='errorBox_'+myTab;myDiv=$(myID);myDiv.style.display=""
myDiv.style.background="";myDiv.style.opacity="";};search.prototype.getCurrentForm=function(){return(map.stateMachine.getCurrentTab()=="tab1"?this.searchForm_simple:this.searchForm_fine);};search.prototype.displayResults=function(allData,lower,upper){var oForm=this.getCurrentForm();var container=document.createElement("div");this.tabResults.appendChild(container);container.id="container_tab1_2_resultTable";var crTitle=map.myUtils.createTable(null,2,1);container.appendChild(crTitle.table);crTitle.table.className="mainTitle";var content=crTitle.content;if($d(oForm.place.cityData)&&oForm.place.cityData!=null){content[0][0].innerHTML=tra['tab2_res_titre1']+" "+oForm.place.cityData['localite'];content[0][0].className="td0";content[1][0].innerHTML=oForm.place.cityData['localite'];}
if(!(/^\s*$/g).test($F(oForm.keyword))){content[1][0].innerHTML+=content[1][0].innerHTML==""?"":" : ";content[1][0].innerHTML+=unescape(getFormattedKeyword($F(oForm.keyword)).replace(/,/g," "));}
nbRes=allData.length;content[1][0].innerHTML+=" ("+tra['general_trouves']+" "+nbRes+")";content[1][0].className="td1";upper=(upper>=allData.length)?allData.length-1:upper;var nbResults=upper-lower+1;var crTable=map.myUtils.createTable("tab1_2_resultTable",1+nbResults,4);container.appendChild(crTable.table);crTable.table.cellSpacing="0";crTable.table.cellPadding="0";crTable.table.border="0";var content=crTable.content;for(var i=0;i<nbResults;i++){var j=i;content[j].className="resultRowSep";content[j][0].style.verticalAlign="top";content[j][1].style.verticalAlign="top";content[j][2].style.verticalAlign="top";content[j][3].style.verticalAlign="middle";content[j][3].style.textAlign="right";content[j].restoData=allData[lower+i];if(allData[lower+i]['hasLabels']==1){var labeldiv=document.createElement("div");labeldiv.className="pictoLabel";var labelimg=document.createElement("img");labelimg.src='/images/gentiane.png';labelimg.width=43;labelimg.height=43;labeldiv.appendChild(labelimg);content[j][0].appendChild(labeldiv);labeldiv=null;labelimg=null;}
if(allData[lower+i]['thumbnail']!=""){var thumbdiv=document.createElement("div");thumbdiv.className="thumb";var thumbimg=document.createElement("img");thumbimg.src=allData[lower+i]['thumbnail'];thumbimg.width=allData[lower+i]['thumbnail_w'];thumbimg.height=allData[lower+i]['thumbnail_h'];if(allData[lower+i]['partner']>0){if(allData[lower+i]['url']!=""){var link=document.createElement("a");link.href=allData[lower+i]['url'];link.target="_blank";link.appendChild(thumbimg);thumbdiv.appendChild(link);thumbimg.style.cursor="pointer";}
else{thumbdiv.appendChild(thumbimg);}}
else{thumbimg.allData=allData;thumbimg.data24=allData[lower+i];Event.observe(thumbimg,"click",this.showFullDetails.bindAsEventListener(this));thumbdiv.appendChild(thumbimg);thumbimg.style.cursor="pointer";}
content[j][0].appendChild(thumbdiv);thumbdiv=null;thumbimg=null;}
var nomPrenom='';if(allData[lower+i]['nom']!=''&&allData[lower+i]['prenom']!=''){nomPrenom=allData[lower+i]['nom']+' '+allData[lower+i]['prenom'];}
else{nomPrenom=allData[lower+i]['nom']+allData[lower+i]['prenom'];}
var locCanton='';if(allData[lower+i]['localite_18']!=''&&allData[lower+i]['canton']!=''){locCanton=allData[lower+i]['localite_18']+', '+allData[lower+i]['canton'];}
else{locCanton=allData[lower+i]['localite_18']+allData[lower+i]['canton'];}
var nomPrenomLoc='';if(nomPrenom!=''&&locCanton!=''){nomPrenomLoc=nomPrenom+', '+locCanton;}
else{nomPrenomLoc=nomPrenom+locCanton;}
var fullInfo='';if(allData[lower+i]['nom_orga']!=""&&nomPrenomLoc!=""){fullInfo=allData[lower+i]['nom_orga']+'<br>'+nomPrenomLoc;}
else{fullInfo=allData[lower+i]['nom_orga']+nomPrenomLoc;}
nomPrenom=null;locCanton=null;nomPrenomLoc=null;if(allData[lower+i]['partner']>0){if(allData[lower+i]['url']!=""){var nameOrg=document.createElement("a");nameOrg.href=allData[lower+i]['url'];nameOrg.target="_blank";nameOrg.style.cursor="pointer";}
else{var nameOrg=document.createElement("span");}}
else{var nameOrg=document.createElement("a");nameOrg.href="#";nameOrg.allData=allData;nameOrg.data24=allData[lower+i];nameOrg.style.cursor="pointer";Event.observe(nameOrg,"click",this.showFullDetails.bindAsEventListener(this));}
nameOrg.innerHTML=fullInfo;fuullInfo=null;content[j][0].appendChild(nameOrg);if(allData[lower+i]['smallDescr']!='')content[j][0].innerHTML+='<br>'+allData[lower+i]['smallDescr'];nameOrg=null;if(allData[lower+i]['classement']!=""){content[j][1].innerHTML=allData[lower+i]['classement'];}
if(allData[lower+i]['prestations']!=""){content[j][1].innerHTML+=allData[lower+i]['prestations'];}
if(allData[lower+i]['pictos']!=""){content[j][2].innerHTML=allData[lower+i]['pictos'];}
if(allData[lower+i]['dossier']!=""){if(allData[lower+i]['partner']==""||allData[lower+i]['partner']==0){var link=document.createElement("a");link.className="buttongreen";var linkspan=document.createElement("span");linkspan.innerHTML=allData[lower+i]['dossier'];linkspan.allData=allData;linkspan.data24=allData[lower+i];link.appendChild(linkspan);Event.observe(linkspan,"click",this.showFullDetails.bindAsEventListener(this));link.style.cursor="pointer";content[j][3].appendChild(link);link=null;span=null;}}}
var tr=document.createElement("tr");crTable.table.body.appendChild(tr);tr.className="titre";var td=document.createElement("td");tr.appendChild(td);td.colSpan="5";td.innerHTML="&nbsp;";var temp=map.myUtils.createTable(null,1,2);container.appendChild(temp.table);var content=temp.content;content[0][0].style.width="50%";var index=this.createIndex(allData,lower,upper);content[0][0].appendChild(index);var but=map.myUtils.createButton();content[0][1].appendChild(but);content[0][1].style.textAlign="right";but.className="gastroButton";but.value=tra['general_afficherMasqueRecherche'];Event.observe(but,"click",function(){map.stateMachine.switchState(map.stateMachine.getCurrentTab()+"-null");});this.showResults();};search.prototype.showRestoOnMap=function(e){var lastState=map.geoSearch.disableGeoSearch();map.stateMachine.switchState("tab0-null",true);switchBottomTab($("tabTourisme_activer"));restoData=Event.element(e).restoData;map.setCenter(new OpenLayers.LonLat(restoData['long'],restoData['lat']),map.scales.length-1,true,false,true);map.ovMapControl.update();map.geoSearch.putInEvidence(restoData,[]);map.geoSearch.uncheckAllGastro();map.geoSearch.showResultLayer();map.geoSearch.restoreGeoSearch(lastState);addRedMarker(new OpenLayers.LonLat(restoData['long'],restoData['lat']));};search.prototype.displayMiniPopUp=function(e){var elem=Event.element(e);Event.stop(e);while(elem.nodeName!="TR"&&elem.nodeName!="BODY"){elem=elem.parentNode;}
var restoData=elem.restoData;if(document.body.miniPopUp)
this.removeMiniPopUp();var pos=map.myUtils.findObjectPosition(elem);var div=document.createElement("div");document.body.appendChild(div);div.style.position="absolute";div.style.left=pos[0]+$(elem).getWidth()+1+"px";div.style.top=pos[1]+"px";div.style.width="130px";document.body.miniPopUp=div;if(restoData['id_point_interet']!=0){var ligne_titre="rgb(102,115,175)";var ligne_light="rgb(225,235,247)";var ligne_dark="rgb(239,244,251)";}
else{var ligne_titre="rgb(183,183,183)";var ligne_light="rgb(245,245,245)";var ligne_dark="rgb(238,238,238)";}
var ct=map.myUtils.createTable(null,8,2);div.appendChild(ct.table);ct.table.cellSpacing="1";ct.table.style.borderSpacing="1px";for(var i=1;i<8;i++){ct.content[i].style.background=i%2==0?ligne_dark:ligne_light;ct.content[i][0].style.padding="2px";}
ct.content[0].removeChild(ct.content[0].lastChild);ct.content[1].removeChild(ct.content[1].lastChild);ct.content[7].removeChild(ct.content[7].lastChild);ct.content[0].style.background=ligne_titre;ct.content[0][0].style.padding="2px";ct.content[0][0].style.color="white";ct.content[0][0].colSpan=2;ct.content[0][0].innerHTML=tra['general_informations'];ct.content[1][0].colSpan=2;ct.content[1][0].innerHTML="&nbsp;";ct.content[2][0].innerHTML=tra['general_plAssises'];ct.content[2][1].innerHTML=restoData['pl_assises'];ct.content[3][0].innerHTML=tra['general_gaultMillau'];ct.content[3][1].innerHTML=restoData['gault_millau'];ct.content[4][0].innerHTML=tra['general_guideBleu'];ct.content[4][1].innerHTML=restoData['guide_bleu'];ct.content[5][0].innerHTML=tra['general_guideMichelin'];ct.content[5][1].innerHTML=restoData['michelin']==0?tra['general_non']:tra['general_oui'];ct.content[6][0].innerHTML=tra['general_guilde'];ct.content[6][1].innerHTML=restoData['guilde'];ct.content[7][0].colSpan=2;ct.content[7][0].innerHTML="&nbsp;";};search.prototype.removeMiniPopUp=function(){if(document.body.miniPopUp)
document.body.removeChild(document.body.miniPopUp);document.body.miniPopUp=null;};search.prototype.showFullDetails=function(e){if(typeof e=="number"){var allData=[];var data24=[];data24['id_point_interet']=e;}
else{var allData=Event.element(e).allData;var data24=Event.element(e).data24;}
this.currentIdGastro=data24['id_point_interet'];url="mapLibs/infoGetter.php?layers=cat"+(TRdom*100)+"&sessionType=tabDetails&dom="+TRdom;if(bIsGastroLocal){url+="&region="+sRegion;}
url+="&idItem="+data24['id_point_interet']+"&output=restoDetail";url+="&lang="+appLanguage;if($d(map.sessionId)&&map.sessionId!=null)
url+="&sessionId="+map.sessionId;var t=this;new OpenLayers.Ajax.Request(url,{onSuccess:(function(trsp){this.tabDetails.innerHTML=trsp.responseText;this.setNavPan(data24,allData);this.tabDetails.lastCallerState=map.stateMachine.getCurrentState();map.stateMachine.switchState(map.stateMachine.getCurrentTab()+"-det");new Ajax.Updater('photosTab1','get_photos.php?dom=1&id_objet='+data24['id_point_interet']);new Ajax.Updater('photosTab2','get_photos.php?dom=2&id_objet='+data24['id_point_interet']);new Ajax.Updater('photosTab3','get_photos.php?dom=3&id_objet='+data24['id_point_interet']);new Ajax.Updater('detailsubheb','get_detail_heb.php?id_objet='+data24['id_point_interet']);}).bindAsEventListener(map.search)});};search.prototype.hasMenu=function(){var url='hasMenu.php?id='+this.currentIdGastro;new OpenLayers.Ajax.Request(url,{onSuccess:function(transport){eval(transport.responseText);if(!hasMenu){$('menuLinkButton').style.display='none';$('sepBeforMenuLink').style.display='none';}
else{$('menuLinkButton').style.display="";$('sepBeforMenuLink').style.display="";}}});};search.prototype.setNavPan=function(data24,allData){var navPan=$("navPan");var temp=map.myUtils.createTable(null,1,4);navPan.appendChild(temp.table);var content=temp.content;var b1=map.myUtils.createButton();b1.value="<";b1.className="gastroButton";b1.style.fontSize="13px";content[0][0].appendChild(b1);content[0][0].style.width="163px";if(this.getPrevious24(data24['id_point_interet'],allData)!=null){b1.style.cursor="pointer";b1.style.color=null;b1.allData=allData;b1.data24=this.getPrevious24(data24['id_point_interet'],allData);Event.observe(b1,"click",this.showFullDetails.bindAsEventListener(this));}
else{b1.disabled=true;b1.style.color='#C0C0C0';}
var b2=map.myUtils.createButton();b2.value=">";b2.className="gastroButton";b2.style.fontSize="13px";content[0][1].appendChild(b2);content[0][1].style.width="138px";if(this.getNext24(data24['id_point_interet'],allData)!=null){b2.style.cursor="pointer";b2.style.color=null;b2.allData=allData;b2.data24=this.getNext24(data24['id_point_interet'],allData);Event.observe(b2,"click",this.showFullDetails.bindAsEventListener(this));}
else{b2.disabled=true;b2.style.color='#C0C0C0';}
var b3=map.myUtils.createButton();b3.value=tra['general_fermer'];b3.className="gastroButton";content[0][2].appendChild(b3);content[0][2].style.width="137px";content[0][2].style.textAlign="right";Event.observe(b3,"click",function(){map.stateMachine.switchState(map.search.tabDetails.lastCallerState.substr(0,4)+"-res")});var b4=map.myUtils.createButton();b4.value=tra['general_nouvelleRecherche'];b4.className="gastroButton";content[0][3].appendChild(b4);content[0][3].style.textAlign="right";Event.observe(b4,"click",function(){map.stateMachine.switchState(map.search.tabDetails.lastCallerState.substr(0,4)+"-null")});};search.prototype.getPrevious24=function(currentId24,allData){theGate24s=[];for(var i=0;i<allData.length;i++){if(allData[i]['id_point_interet']==currentId24){if(theGate24s.length>0)
return theGate24s[theGate24s.length-1];}
if(allData[i]['id_point_interet']>0)
theGate24s.push(allData[i]);}
return null;};search.prototype.getNext24=function(currentId24,allData){theGate24s=[];for(var i=allData.length-1;i>=0;i--){if(allData[i]['id_point_interet']==currentId24){if(theGate24s.length>0)
return theGate24s[theGate24s.length-1];}
if(allData[i]['id_point_interet']>0)
theGate24s.push(allData[i]);}
return null;};search.prototype.createIndex=function(allData,lower,upper){var container=document.createElement("div");var nbPages=Math.ceil(allData.length/this.nbrpp);var curPage=Math.floor(lower/this.nbrpp);if(curPage>0){container.appendChild(createPageLink("|< ",0));container.appendChild(createPageLink(" << ",(curPage-10<0?0:curPage-10)));container.appendChild(createPageLink(" < ",(curPage-1<0?0:curPage-1)));}
var lowerBound=(curPage-2<0)?0:curPage-2;var upperBound=(curPage+2>=nbPages)?nbPages-1:curPage+2;for(var i=lowerBound;i<=upperBound;i++){a=createPageLink(" "+(i+1)+" ",i);if(i==curPage)
a.style.fontWeight="bold";container.appendChild(a);}
if(curPage<nbPages-1){container.appendChild(createPageLink(" > ",(curPage+1>=nbPages?nbPages-1:curPage+1)));container.appendChild(createPageLink(" >> ",(curPage+10>=nbPages?nbPages-1:curPage+10)));container.appendChild(createPageLink(" >|",nbPages-1));}
return container;function createPageLink(label,page){var a=document.createElement("a");a.innerHTML=label;a.href="#";a.allData=allData;a.page=page;a.onclick=function(e){map.search.changePage(e);return false;};return a;}};search.prototype.changePage=function(e){e=e?e:(event?event:null);var elem=Event.element(e);var page=elem.page;var allData=elem.allData;var lower=page*this.nbrpp;var upper=lower+this.nbrpp-1;this.removeResults();this.displayResults(allData,lower,upper);return false;};search.prototype.removeResults=function(){while(this.tabResults.childNodes.length>0){this.tabResults.removeChild(this.tabResults.childNodes[0]);}};search.prototype.selectedInIndex=function(linkElem){this.searchForm_simple.keyword.value=linkElem.innerHTML+" ";$("tab1_index").hide();$("tab1_tipps").show();};search.prototype.showSearchMask=function(){map.stateMachine.switchState(map.stateMachine.getCurrentTab()+"-null");};search.prototype.showResults=function(){map.stateMachine.switchState(map.stateMachine.getCurrentTab()+"-res");};search.prototype.loading=function(formName,bLoading){if(bLoading){if(formName=="searchForm_simple"){$("searchForm_simple_sablier").style.visibility="visible";this.goButtonTab1.disabled=true;}
else{$("searchForm_fine_sablier").style.visibility="visible";this.goButtonTab2.disabled=true;}}
else{if(formName=="searchForm_simple"){$("searchForm_simple_sablier").style.visibility="hidden";this.goButtonTab1.disabled=false;}
else{$("searchForm_fine_sablier").style.visibility="hidden";this.goButtonTab2.disabled=false;}}};var map=SERVER=PATHNAME=GASTRO_BUFFER=null;var bIsGastroLocal=(sRegion!="")?true:false;var aMaxExtendBounds=[aBounds[0],aBounds[1],aBounds[2],aBounds[3]];var aScales=[1924726,300000,150000,60000,30000,15000,7500,6000,4000,2000];var iMaxScale="300012";var sPathTile="tile.php?', ";var aKeymapBounds=[aBounds[0],aBounds[1],aBounds[2],aBounds[3]];window.onload=function(){this.appLoaded=false;SERVER="http://"+window.location.host;var p=window.location.pathname.split("/");p[p.length-1]="";PATHNAME=p.join("/");GASTRO_BUFFER=1;if(bIsGastroLocal){aScales=findScalesByBounds(aBounds);iMaxScale=aScales[0];setMaxExtendBoundsAndKeymapBounds();sPathTile="tileLocal.php?', ";}
var mapOptions={controls:[],units:"m",projection:"EPSG:21781",maxExtent:new OpenLayers.Bounds(aMaxExtendBounds[0],aMaxExtendBounds[1],aMaxExtendBounds[2],aMaxExtendBounds[3]),scales:aScales,theme:null};map=new OpenLayers.Map('map',mapOptions);map.name="swissgeo";extendMapObject(map);new myUtils(map);new historyManager("tab0-null");new stateMachine(map,"tab0-null");var cache_server=["http://mc1.swissgeo.ch/ka-cache","http://mc2.swissgeo.ch/ka-cache","http://mc3.swissgeo.ch/ka-cache","http://mc4.swissgeo.ch/ka-cache"]
var created=[];var kaMapConf_basemap={map:"common",g:"basemap",tileWidth:256,tileHeight:256,metatileWidth:6,metatileHeight:6,i:"png"};var basemap=new OpenLayers.Layer.KaMapTileCache(tra['layer_basemap'],cache_server,kaMapConf_basemap,{format:"image/png",buffer:GASTRO_BUFFER,scales:[300000,150000,60000,30000,15000,7500,6000,4000,2000],isBaseLayer:false,visibility:false});created.push(basemap);var kaMapConf_ortho={map:"common",g:"orthophotos",tileWidth:256,tileHeight:256,metatileWidth:6,metatileHeight:6,i:"jpg"};var ortho=new OpenLayers.Layer.KaMapTileCache(tra['layer_orthophotos'],cache_server,kaMapConf_ortho,{format:"image/jpeg",resize:true,buffer:GASTRO_BUFFER,isBaseLayer:true,visibility:true});created.push(ortho);map.events.register("zoomend",null,function(){checkSwissmap([basemap,ortho])});var kaMapConf_streets={map:"common",g:"streetmap",tileWidth:256,tileHeight:256,metatileWidth:6,metatileHeight:6,i:"png"};var streets=new OpenLayers.Layer.KaMapTileCache(tra['layer_streets'],cache_server,kaMapConf_streets,{format:"image/png",opacity:0.4,isBaseLayer:false,visibility:false,buffer:GASTRO_BUFFER,scales:[300000,150000,60000,30000,15000,7500,6000,4000,2000]});var kaMapConf_streetLabels={map:"common",g:"streetmaplabel",tileWidth:256,tileHeight:256,metatileWidth:6,metatileHeight:6,i:"png"};var streetLabels=new OpenLayers.Layer.KaMapTileCache(tra['layer_streets']+"2",cache_server,kaMapConf_streetLabels,{format:"image/png",isBaseLayer:false,visibility:false,buffer:GASTRO_BUFFER,scales:[15000,7500,6000,4000,2000]});streets.legend={container:"leg_blocMaps",linkedWith:streetLabels,isMaster:true};created.push(streets);streetLabels.legend={container:"leg_blocMaps",linkedWith:streets,isMaster:false};created.push(streetLabels);var poi_layers={cat41:"tourisme1",cat44:"tourisme1",cat45:"tourisme1",cat46:"tourisme1",cat47:"tourisme1",cat61:"tourisme2",cat67:"tourisme2",cat64:"tourisme2",cat65:"tourisme2",cat66:"tourisme2",cat68:"tourisme2",cat71:"tourisme3",cat72:"tourisme3",cat73:"tourisme3"};var TRPOI=null;if(TRdom==1){TRPOI={cat100:"leg_blocGastro1",cat103:"leg_blocGastro1",cat110:"leg_blocGastro1",cat115:"leg_blocGastro1",cat107:"leg_blocGastro1",cat112:"leg_blocGastro1",cat114:"leg_blocGastro1",cat106:"leg_blocGastro1",cat111:"leg_blocGastro1",cat113:"leg_blocGastro1",cat101:"leg_blocGastro1",cat108:"leg_blocGastro1",cat109:"leg_blocGastro1",cat102:"leg_blocGastro1",cat105:"leg_blocGastro1",cat104:"leg_blocGastro1",cat116:"leg_blocGastro1"};}
if(TRdom==2){TRPOI={cat200:"leg_blocGastro1",cat203:"leg_blocGastro1",cat204:"leg_blocGastro1",cat209:"leg_blocGastro1",cat206:"leg_blocGastro1",cat207:"leg_blocGastro1",cat205:"leg_blocGastro1",cat201:"leg_blocGastro1",cat202:"leg_blocGastro1",cat208:"leg_blocGastro1",cat210:"leg_blocGastro1"};}
if(TRdom==3){TRPOI={cat300:"leg_blocGastro1",cat301:"leg_blocGastro1",cat302:"leg_blocGastro1",cat303:"leg_blocGastro1",cat304:"leg_blocGastro1",cat308:"leg_blocGastro1",cat305:"leg_blocGastro1",cat306:"leg_blocGastro1",cat307:"leg_blocGastro1"};}
toAdd={};for(var i in TRPOI){toAdd[i]=TRPOI[i];}
for(var i in poi_layers){toAdd[i]=poi_layers[i];}
TRPOI=null;poi_layers=null;var activeLayer="cat"+((TRdom*100)+TRsubdom);for(var i in toAdd){var mapFile='poi';if(toAdd[i].substring(0,14)=="leg_blocGastro"){mapFile='tourismerural';}
var toEval="var "+i+" = new OpenLayers.Layer.KaMap(\"";var name=tra['layer_'+i];toEval+=name+"\",'http://kamap.swissgeo.ch/tile.php?',";toEval+="{g: '"+i+"', map: '"+mapFile+"', i: 'png' ";if(bIsGastroLocal){toEval+=", region: '"+sRegion+"'";}
toEval+="}, ";toEval+="{buffer:"+GASTRO_BUFFER;toEval+="});";toEval+=i+".setIsBaseLayer(false);";if(i!=activeLayer){toEval+=i+".setVisibility(false);";}
else{toEval+=i+".setVisibility(true);";}
toEval+=i+".legend = {};";toEval+=i+".legend.container = \""+toAdd[i]+"\";";toEval+=i+".legend.imgSources = {selected : 'http://ms1.swissgeo.ch/toolkit/getIcon.php?map="+mapFile+"&g="+i+"&icon_width=16&icon_height=16', unselected : 'http://ms1.swissgeo.ch/toolkit/getIcon.php?map="+mapFile+"&g="+i+"&icon_width=16&icon_height=16&out=true'};";toEval+="created.push("+i+");";eval(toEval);}
var swissNames=new OpenLayers.Layer.KaMapTileCache(tra['layer_Swissnames'],cache_server,{map:"common",g:"Swissnames",tileWidth:256,tileHeight:256,metatileWidth:6,metatileHeight:6,i:"png"},{buffer:GASTRO_BUFFER,isBaseLayer:false,visibility:true,scales:[300000,150000,60000,30000,15000,7500,6000,4000,2000]});swissNames.legend={container:"leg_blocMaps"};created.push(swissNames);var ovLayer=new OpenLayers.Layer.Image("Swissmap",sKeyMapImage,new OpenLayers.Bounds(aKeymapBounds[0],aKeymapBounds[1],aKeymapBounds[2],aKeymapBounds[3]),new OpenLayers.Size(195,130),{projection:"EPSG:21781",numZoomLevels:1,units:"m",theme:null});map.addLayer(ovLayer);ovOptions={div:$("keymap"),size:new OpenLayers.Size(195,130),mapOptions:{theme:null}};ovMapCont=new OpenLayers.Control.OverviewMap(ovOptions);ovMapCont.isSuitableOverview=function(){return true};map.addControl(ovMapCont);map.ovMapControl=ovMapCont;map.removeLayer(ovLayer);ovMapCont.setRectPxBounds=function(pxBounds){var top=Math.max(pxBounds.top,0);var left=Math.max(pxBounds.left,0);var bottom=Math.min(pxBounds.top+Math.abs(pxBounds.getHeight()),this.ovmap.size.h-this.hComp);var right=Math.min(pxBounds.left+pxBounds.getWidth(),this.ovmap.size.w-this.wComp);var center=(new OpenLayers.Bounds(left,bottom,right,top)).getCenterPixel();if(parseInt(Math.max(right-left,0))<9){left=center.x-5;right=center.x+5;top=center.y-4;bottom=center.y+4;}
this.extentRectangle.style.top=parseInt(top)+'px';this.extentRectangle.style.left=parseInt(left)+'px';this.extentRectangle.style.height=parseInt(Math.max(bottom-top,0))+'px';this.extentRectangle.style.width=parseInt(Math.max(right-left,0))+'px';}
map.addLayers(created);new progZoomer(map,"zoom_slider","zoom_support","zoom_plus","zoom_minus");map.layerMixer=new layerMixer(map,"layerMixer_widget","opacity_slider","opacity_support","opacity_plus","opacity_minus",{refLayer:ortho,otherLayer:basemap});new customScalebar("scaleBarWidget");if(cityMode=='auto'){map.autoCompleter0=new autoCompleter("tab0_placeSearch_autoComplete","goButton_tab0",2,20);map.autoCompleter1=new autoCompleter("tab1_placeSearch_autoComplete","goButton_tab1",2,20);map.autoCompleter2=new autoCompleter("tab2_placeSearch_autoComplete","goButton_tab2",2,20);}
var resLayer=new resultLayer();map.addLayer(resLayer);var markersLayer=new OpenLayers.Layer.Markers("Markers");map.addLayer(markersLayer);map.events.register("gastroLayersChanged",null,function(){removeAllMarkers()});map.layerSwitcher=new layerSwitcherGastro();$("leg_blocGastro_res").childNodes[0].className="";$("leg_blocGastro_res").childNodes[0].style.width="50%";if(navigator.userAgent.toLowerCase().indexOf("msie 6.")!=-1)
$("leg_blocGastro_res").childNodes[0].style.marginLeft="10px";else
$("leg_blocGastro_res").childNodes[0].style.marginLeft="5px";$("leg_blocGastro_res").childNodes[0].style.marginTop="2px";$("leg_blocGastro_res").childNodes[0].style.marginBottom="1px";$("leg_blocGastro_res").childNodes[0].style.marginRight="0px";$("leg_blocGastro_res").getElementsByClassName("checkbox")[0].style.width="18px";map.layerSwitcher.updateIcon(map.getLayerByGroupName("Swissnames"));map.geoSearch=new geoSearch();map.search=new search();map.addControl(new OpenLayers.Control.MouseStopped(300,null,gastroPopUp_check));setMouseFunctions();new navTool();new routingFunctions();checkSwissmap([basemap,ortho]);map.ovMapControl.update();$(ovMapCont.mapDiv.id+"_OpenLayers_ViewPort").style.overflow="visible";OpenLayers.Util.onImageLoadErrorColor="transparent";OpenLayers.IMAGE_RELOAD_ATTEMPTS=2;OpenLayers.Util.alphaHack=function(){return false};if(typeof directCall!="undefined"&&directCall==true){var city=$F('tab1_placeSearch_autoComplete');if(city.match(/\d{4}/)!=null)
city=city.match(/\d{4}/)[0];$('tab1_placeSearch_autoComplete').value=city;map.search.goSearch();}
if(typeof idGastro!="undefined"&&idGastro>0){map.search.showFullDetails(idGastro);}
this.appLoaded=true;if(bIsGastroLocal){map.setOptions({restrictedExtent:new OpenLayers.Bounds(aBounds[0],aBounds[1],aBounds[2],aBounds[3])});$("layerMixer_widget").style.visibility="visible";}
$("tab1").hide();$("tab1").style.visibility="visible";$("tab0").show();}
function mapClicked(evt){if(map.getZoom()<map.getNumZoomLevels())
map.setCenter(map.getLonLatFromViewPortPx(evt.xy),map.zoom+1);}
function mapRightClicked(evt){if(map.getZoom()>0){map.setCenter(map.getLonLatFromViewPortPx(map.events.getMousePosition(evt)),map.zoom-1);}}
function mapDblClicked(evt){if(map.getZoom()>0)
map.setCenter(map.getLonLatFromViewPortPx(evt.xy));}
function checkSwissmap(layers){var scale=Math.round(map.getScale());if(scale>(iMaxScale-10)){for(var i=0;i<layers.length;i++){layers[i].lastOpacity=layers[i].opacity;if(layers[i].params.g=="orthophotos")
layers[i].setOpacity(1);}
for(i=0;i<map.controls.length;i++){if(map.controls[i].CLASS_NAME=="OpenLayers.Control.Navigation")
map.controls[i].deactivate();}
centerOnSwitzerland();document.getElementsByClassName("olControlOverviewMapExtentRectangle",$("keymap"))[0].style.border="none";}
else{for(var i=0;i<layers.length;i++){if($d(layers[i].lastOpacity)&&layers[i].lastOpacity!=null){layers[i].setOpacity(layers[i].lastOpacity);layers[i].lastOpacity=null;}}
for(i=0;i<map.controls.length;i++){if(map.controls[i].CLASS_NAME=="OpenLayers.Control.Navigation")
map.controls[i].activate();}
document.getElementsByClassName("olControlOverviewMapExtentRectangle",$("keymap"))[0].style.border="1px solid red";}}
function centerOnSwitzerland(){if(bIsGastroLocal){map.zoomToExtent(new OpenLayers.Bounds(aBounds[0],aBounds[1],aBounds[2],aBounds[3]));}else{map.setCenter(new OpenLayers.LonLat(648024,192341));}}
function geoSearchMapMoved_check(e){var goOn=true;if(map.getScale()>310000)
goOn=false;var now=(new Date()).getTime();if($d(map.geoSearch.lastSearchTime)){if(now-this.lastSearchTime<800){goOn=false;}}
if(map.geoSearch.searchIsForbidden)
goOn=false;if(goOn){map.geoSearch.lastSearchTime=now;map.geoSearch.mapMoved();}
else{map.geoSearch.showSearchMask();}}
function gastroPopUp_check(e){goOn=true;if(goOn){new gastroPopUp(e);}}
function switchBottomTab(tab){var tabs=['tabGastro_activer','tabTourisme_activer','tabMaps_activer'];for(var i=0;i<tabs.length;i++){$(tabs[i]).className="inactiveTab";$($(tabs[i]).getAttribute("target")).hide();}
tab.className="activeTab";$($(tab).getAttribute("target")).show();}
function displayTourismusCat(nb){$("tourisme1").hide();$("tourisme2").hide();$("tourisme3").hide();$("tourisme"+nb).show();$("tourismus_activer1").style.fontWeight="normal";$("tourismus_activer2").style.fontWeight="normal";$("tourismus_activer3").style.fontWeight="normal";$("tourismus_activer"+nb).style.fontWeight="bold";}
function addRedMarker(e){removeAllMarkers();if($d(e.lat)){var lon=e.lon;var lat=e.lat;}
else{var lon=Event.element(e).restoData['long'];var lat=Event.element(e).restoData['lat'];}
var size=new OpenLayers.Size(15,15);var offset=new OpenLayers.Pixel(-(size.w/2),-(size.h/2));var icon=new OpenLayers.Icon('mapLibs/images/tip.gif',size,offset);map.getLayerByName("Markers").addMarker(new OpenLayers.Marker(new OpenLayers.LonLat(lon,lat),icon));icon.imageDiv.firstChild.style.filter="";icon.imageDiv.style.filter="";}
function removeAllMarkers(){map.getLayerByName("Markers").clearMarkers();}
function $d(elem){if(typeof elem=="undefined")
return false;else
return true;}
function getScaleAsInteger(scaleNb){var res=0;for(var i=0;i<map.getNumZoomLevels();i++){if(scaleNb==map.scales[i]){res=i;}}
return res;}
function in_array(needle,arr){for(var i=0;i<arr.length;i++){if(needle==arr[i])
return true;}
return false;}
function getTS(){return(new Date()).getTime();}
function setMouseFunctions(){var nav=new OpenLayers.Control.Navigation();nav.defaultDblClick=function(){};map.chronoClick=null;map.events.register("dblclick",null,function(evt){if(map.chronoClick!=null){clearTimeout(map.chronoClick);map.chronoClick=null;mapDblClicked(evt);return;}});map.events.register("click",null,function(evt){if(map.chronoClick!=null){clearTimeout(map.chronoClick);map.chronoClick=null;mapDblClicked(evt);return;}
map.chronoClick=setTimeout(function(){map.chronoClick=null;mapClicked(evt)},220);});$("map").oncontextmenu=function(e){e=(e)?e:((event)?event:null);mapRightClicked(e);return false;}
map.addControl(nav);}
function extendMapObject(map){map.getLayerByName=function(name){var foundLayer=null;for(var i=0;i<this.layers.length;i++){var layer=this.layers[i];if(layer.name==name){foundLayer=layer;break;}}
return foundLayer;};map.getLayerByGroupName=function(name){var foundLayer=null;for(var i=0;i<map.layers.length;i++){if(typeof map.layers[i].params!="undefined"&&typeof map.layers[i].params.g!="undefined"){if(map.layers[i].params.g==name){foundLayer=map.layers[i];break;}}}
return foundLayer;};return;}
var unite="0.000352778";function findScalesByBounds(aBounds){var aScale;var iLargeur=aBounds[2]-aBounds[0];var iHauteur=aBounds[3]-aBounds[1];iLargeur=iLargeur/520;iHauteur=iHauteur/340;if(iLargeur>=iHauteur){aScale=getArrayOfScale(iLargeur/unite);}else{aScale=getArrayOfScale(iHauteur/unite);}
return aScale;}
function setMaxExtendBoundsAndKeymapBounds(){var largeurMaxEnUnite=(unite*520)*aScales[0];var hauteurMaxEnUnite=(unite*340)*aScales[0];aMaxExtendBounds[0]=aMaxExtendBounds[0]-(largeurMaxEnUnite/2);aMaxExtendBounds[1]=aMaxExtendBounds[1]-(hauteurMaxEnUnite/2);aMaxExtendBounds[2]=aMaxExtendBounds[2]+(largeurMaxEnUnite/2);aMaxExtendBounds[3]=aMaxExtendBounds[3]+(hauteurMaxEnUnite/2);var iLargeur=aBounds[2]-aBounds[0];var iHauteur=aBounds[3]-aBounds[1];var iLargeurToSupp=(largeurMaxEnUnite-iLargeur)/2;var iHauteurToSupp=(hauteurMaxEnUnite-iHauteur)/2;aKeymapBounds[0]=aKeymapBounds[0]-iLargeurToSupp;aKeymapBounds[1]=aKeymapBounds[1]-iHauteurToSupp;aKeymapBounds[2]=aKeymapBounds[0]+largeurMaxEnUnite;aKeymapBounds[3]=aKeymapBounds[1]+hauteurMaxEnUnite;}
function getArrayOfScale(iScale){var aDispoScales=[1700000,600000,300000,150000,60000,30000,15000,7500,6000,4000,2000];var index=0;for(var i=0;i<aDispoScales.length;i++){if(iScale<=aDispoScales[i]){index=i;}}
var aFinalScales=aDispoScales.slice(index,aDispoScales.length);return aFinalScales;}
function switchActiveTab(id){var children=$('domTabs').childElements();var tabId="";for(var i=0;i<children.length;i++){tabId=parseInt(children[i].id.substring(6,7));if(tabId==id){$('domTab'+tabId).className='current';$('detailTab'+tabId).style.display='';}
else{$('domTab'+tabId).className='';$('detailTab'+tabId).style.display='none';}}}
function stateMachine(oMap,beginState){oMap.stateMachine=this;this.oldStates=[];this.beginState=beginState;this.currentState=beginState;this.allTabs=["tab0","tab1","tab2","tab_searchResults","tab_gastroDetails"];this.allActivers=["tab0_activer","tab1_activer","tab2_activer"];$("tab0_activer").onclick=function(){map.stateMachine.switchState("tab0-null")};$("tab1_activer").onclick=function(){map.stateMachine.switchState("tab1-null")};$("tab2_activer").onclick=function(){map.stateMachine.switchState("tab2-null")};this.stateGraph=new Object();this.stateGraph["tab0-null"]=new Object();this.stateGraph["tab0-null"]["tab0-null"]=["reinitMap"];this.stateGraph["tab0-null"]["tab0-res"]=["forceToNull"];this.stateGraph["tab0-null"]["tab0-det"]=[];this.stateGraph["tab0-null"]["tab1-null"]=["copyFields"];this.stateGraph["tab0-null"]["tab1-res"]=[];this.stateGraph["tab0-null"]["tab1-det"]=["forceToNull"];this.stateGraph["tab0-null"]["tab2-null"]=["copyFields"];this.stateGraph["tab0-null"]["tab2-res"]=[];this.stateGraph["tab0-null"]["tab2-det"]=["forceToNull"];this.stateGraph["tab0-res"]=new Object();this.stateGraph["tab0-res"]["tab0-null"]=["forceToNull"];this.stateGraph["tab0-res"]["tab0-res"]=["forceToNull"];this.stateGraph["tab0-res"]["tab0-det"]=[];this.stateGraph["tab0-res"]["tab1-null"]=[];this.stateGraph["tab0-res"]["tab1-res"]=[];this.stateGraph["tab0-res"]["tab1-det"]=[];this.stateGraph["tab0-res"]["tab2-null"]=[];this.stateGraph["tab0-res"]["tab2-res"]=[];this.stateGraph["tab0-res"]["tab2-det"]=[];this.stateGraph["tab0-det"]=new Object();this.stateGraph["tab0-det"]["tab0-null"]=[];this.stateGraph["tab0-det"]["tab0-res"]=["forceToNull"];this.stateGraph["tab0-det"]["tab0-det"]=[];this.stateGraph["tab0-det"]["tab1-null"]=[];this.stateGraph["tab0-det"]["tab1-res"]=["forceToNull"];this.stateGraph["tab0-det"]["tab1-det"]=[];this.stateGraph["tab0-det"]["tab2-null"]=[];this.stateGraph["tab0-det"]["tab2-res"]=["forceToNull"];this.stateGraph["tab0-det"]["tab2-det"]=[];this.stateGraph["tab1-null"]=new Object();this.stateGraph["tab1-null"]["tab0-null"]=["copyFields","reinitMap"];this.stateGraph["tab1-null"]["tab0-res"]=["copyFields","reinitMap","forceToNull"];this.stateGraph["tab1-null"]["tab0-det"]=[];this.stateGraph["tab1-null"]["tab1-null"]=[];this.stateGraph["tab1-null"]["tab1-res"]=[];this.stateGraph["tab1-null"]["tab1-det"]=[];this.stateGraph["tab1-null"]["tab2-null"]=["copyFields"];this.stateGraph["tab1-null"]["tab2-res"]=["copyFields","forceToNull"];this.stateGraph["tab1-null"]["tab2-det"]=["copyFields","forceToNull"];this.stateGraph["tab1-res"]=new Object();this.stateGraph["tab1-res"]["tab0-null"]=["copyFields","reinitMap"];this.stateGraph["tab1-res"]["tab0-res"]=["copyFields","reinitMap","forceToNull"];this.stateGraph["tab1-res"]["tab0-det"]=[];this.stateGraph["tab1-res"]["tab1-null"]=[];this.stateGraph["tab1-res"]["tab1-res"]=[];this.stateGraph["tab1-res"]["tab1-det"]=[];this.stateGraph["tab1-res"]["tab2-null"]=["copyFields"];this.stateGraph["tab1-res"]["tab2-res"]=["copyFields","forceToNull"];this.stateGraph["tab1-res"]["tab2-det"]=["copyFields","forceToNull"];this.stateGraph["tab1-det"]=new Object();this.stateGraph["tab1-det"]["tab0-null"]=["copyFields","reinitMap"];this.stateGraph["tab1-det"]["tab0-res"]=["copyFields","reinitMap","forceToNull"];this.stateGraph["tab1-det"]["tab0-det"]=[];this.stateGraph["tab1-det"]["tab1-null"]=["clearFields"];this.stateGraph["tab1-det"]["tab1-res"]=[];this.stateGraph["tab1-det"]["tab1-det"]=[];this.stateGraph["tab1-det"]["tab2-null"]=["copyFields"];this.stateGraph["tab1-det"]["tab2-res"]=["copyFields","forceToNull"];this.stateGraph["tab1-det"]["tab2-det"]=["copyFields","forceToNull"];this.stateGraph["tab2-null"]=new Object();this.stateGraph["tab2-null"]["tab0-null"]=["copyFields","reinitMap"];this.stateGraph["tab2-null"]["tab0-res"]=["copyFields","reinitMap","forceToNull"];this.stateGraph["tab2-null"]["tab0-det"]=[];this.stateGraph["tab2-null"]["tab1-null"]=["copyFields"];this.stateGraph["tab2-null"]["tab1-res"]=["forceToNull"];this.stateGraph["tab2-null"]["tab1-det"]=["forceToNull"];this.stateGraph["tab2-null"]["tab2-null"]=[];this.stateGraph["tab2-null"]["tab2-res"]=[];this.stateGraph["tab2-null"]["tab2-det"]=[];this.stateGraph["tab2-res"]=new Object();this.stateGraph["tab2-res"]["tab0-null"]=["copyFields","reinitMap"];this.stateGraph["tab2-res"]["tab0-res"]=["copyFields","reinitMap","forceToNull"];this.stateGraph["tab2-res"]["tab0-det"]=[];this.stateGraph["tab2-res"]["tab1-null"]=["copyFields"];this.stateGraph["tab2-res"]["tab1-res"]=["copyFields","forceToNull"];this.stateGraph["tab2-res"]["tab1-det"]=["copyFields","forceToNull"];this.stateGraph["tab2-res"]["tab2-null"]=[];this.stateGraph["tab2-res"]["tab2-res"]=[];this.stateGraph["tab2-res"]["tab2-det"]=[];this.stateGraph["tab2-det"]=new Object();this.stateGraph["tab2-det"]["tab0-null"]=["copyFields","reinitMap"];this.stateGraph["tab2-det"]["tab0-res"]=["copyFields","reinitMap","forceToNull"];this.stateGraph["tab2-det"]["tab0-det"]=[];this.stateGraph["tab2-det"]["tab1-null"]=["copyFields"];this.stateGraph["tab2-det"]["tab1-res"]=["copyFields","forceToNull"];this.stateGraph["tab2-det"]["tab1-det"]=["copyFields","forceToNull"];this.stateGraph["tab2-det"]["tab2-null"]=["clearFields"];this.stateGraph["tab2-det"]["tab2-res"]=[];this.stateGraph["tab2-det"]["tab2-det"]=[];}
stateMachine.prototype.switchState=function(newState,dontApplyGraph){var actualState=this.getCurrentState();var tab_currentState=this.currentState.substr(0,4);var acc_currentState=this.currentState.substr(5,this.currentState.length-1);var tab_newState=newState.substr(0,4);var acc_newState=newState.substr(5,newState.length-1);for(var i=0;i<this.allTabs.length;i++){$(this.allTabs[i]).hide();}
for(var i=0;i<this.allActivers.length;i++){$(this.allActivers[i]).className="inactiveTab";}
$(tab_newState+"_activer").className="activeTab";$(tab_currentState+"_activer").onclick=function(){if(acc_currentState=="res"&&tab_newState=="tab0"){map.stateMachine.switchState(actualState,true);return;}
if(map.stateMachine.getCurrentAcc()=="det")
map.stateMachine.switchState(actualState,true);else
map.stateMachine.switchState(tab_currentState+"-null");};if("tab0_activer"!=(tab_currentState+"_activer"))
$("tab0_activer").onclick=function(){switchBottomTab($("tabGastro_activer"));map.stateMachine.switchState("tab0-null")};if("tab1_activer"!=(tab_currentState+"_activer"))
$("tab1_activer").onclick=function(){map.stateMachine.switchState("tab1-null")};if("tab2_activer"!=(tab_currentState+"_activer"))
$("tab2_activer").onclick=function(){map.stateMachine.switchState("tab2-null")};var actions=this.stateGraph[this.currentState][newState];if(dontApplyGraph)
actions=[];for(var i=0;i<actions.length;i++){if(actions[i]=="forceToNull"){newState=tab_newState+"-null";acc_newState="null";break;}}
switch(acc_newState){case"null":$(tab_newState).show();break;case"det":$("tab_gastroDetails").show();break;case"res":if($("tab_searchResults").childNodes[0]&&$("tab_searchResults").childNodes[0].nodeName=="DIV")
$("tab_searchResults").show();else
$(tab_newState).show();break;default:alert("not found : "+acc_newState+" (in function switchState)");}
if(actions.length>0){for(var i=0;i<actions.length;i++){switch(actions[i]){case"reinitMap":this.reinitMap();break;case"copyFields":this.copyFields(tab_currentState,tab_newState);break;case"clearFields":this.clearFields(tab_newState);break;case"centerOnCity":this.centerOnCity(tab_currentState);break;case"showResultLayerAndGeoSearch":this.showResultLayerAndGeoSearch(tab_currentState);break;case"forceToNull":break;default:;}}}
this.currentState=newState;if(dhtmlHistory&&map.historyManager)
dhtmlHistory.saveState();return false;}
stateMachine.prototype.getCurrentState=function(){return this.currentState;}
stateMachine.prototype.getCurrentTab=function(){return this.currentState.substr(0,4);}
stateMachine.prototype.getCurrentAcc=function(){return this.currentState.substr(5,this.currentState.length-1);}
stateMachine.prototype.reinitMap=function(){var mainLayer="cat"+((TRdom*100)+TRsubdom);map.geoSearch.uncheckAllGastro();map.getLayerByGroupName(mainLayer).setVisibility(true,true);map.zoomTo(0);map.layerSwitcher.updateAllIcons();map.geoSearch.clearSearch();map.geoSearch.showSearchMask();removeAllMarkers();map.geoSearch.hideResultLayer();$("searchMask_backToSearchResults").hide();}
stateMachine.prototype.copyFields=function(tabSrc,tabDest){var keyword="";var city="";cityData=null;switch(tabSrc){case"tab0":keyword=$("keyword_tab0").value;city=$("tab0_placeSearch_autoComplete").value;cityData=$("tab0_placeSearch_autoComplete").cityData;break;case"tab1":keyword=$("searchForm_simple").keyword.value;city=$("searchForm_simple").place.value;cityData=$("searchForm_simple").place.cityData;break;case"tab2":keyword=$("searchForm_fine").keyword.value;city=$("searchForm_fine").place.value;cityData=$("searchForm_fine").place.cityData;break;default:;}
switch(tabDest){case"tab0":$("keyword_tab0").value=keyword;$("tab0_placeSearch_autoComplete").value=city;$("tab0_placeSearch_autoComplete").cityData=cityData;break;case"tab1":$("searchForm_simple").keyword.value=keyword;$("searchForm_simple").place.value=city;$("searchForm_simple").place.cityData=cityData;break;case"tab2":$("searchForm_fine").keyword.value=keyword;$("searchForm_fine").place.value=city;$("searchForm_fine").place.cityData=cityData;break;default:;}}
stateMachine.prototype.clearFields=function(tab){switch(tab){case"tab0":$("keyword_tab0").value="";$("tab0_placeSearch_autoComplete").value="";$("tab0_placeSearch_autoComplete").cityData=null;break;case"tab1":$("searchForm_simple").reset();break;case"tab2":$("searchForm_fine").reset();break;}}
stateMachine.prototype.centerOnCity=function(tabSrc){var cityData=null;switch(tabSrc){case"tab1":cityData=$("searchForm_simple").place.cityData;break;case"tab2":cityData=$("searchForm_fine").place.cityData;break;default:alert("case not found in centerOnCity - stateMachine ("+tabSrc+")");}
if(cityData!=null&&typeof cityData['long']!="undefined"){map.setCenter(new OpenLayers.LonLat(cityData['long'],cityData['lat']),getScaleAsInteger(30000),true,false,true);map.ovMapControl.update();}}
stateMachine.prototype.showResultLayerAndGeoSearch=function(tabSrc){map.geoSearch.uncheckAllGastro(map.getLayerByGroupName("Results"));map.geoSearch.showResultLayer();geoSearchMapMoved_check();}
OpenLayers.ProxyHost="";OpenLayers.nullHandler=function(request){alert("Unhandled request return "+request.statusText);};OpenLayers.loadURL=function(uri,params,caller,onComplete,onFailure){if(OpenLayers.ProxyHost&&OpenLayers.String.startsWith(uri,"http")){uri=OpenLayers.ProxyHost+escape(uri);}
var success=(onComplete)?OpenLayers.Function.bind(onComplete,caller):OpenLayers.nullHandler;var failure=(onFailure)?OpenLayers.Function.bind(onFailure,caller):OpenLayers.nullHandler;new OpenLayers.Ajax.Request(uri,{method:'get',parameters:params,onComplete:success,onFailure:failure});};OpenLayers.parseXMLString=function(text){var index=text.indexOf('<');if(index>0){text=text.substring(index);}
var ajaxResponse=OpenLayers.Util.Try(function(){var xmldom=new ActiveXObject('Microsoft.XMLDOM');xmldom.loadXML(text);return xmldom;},function(){return new DOMParser().parseFromString(text,'text/xml');},function(){var req=new XMLHttpRequest();req.open("GET","data:"+"text/xml"+";charset=utf-8,"+encodeURIComponent(text),false);if(req.overrideMimeType){req.overrideMimeType("text/xml");}
req.send(null);return req.responseXML;});return ajaxResponse;};OpenLayers.Ajax={emptyFunction:function(){},getTransport:function(){return OpenLayers.Util.Try(function(){return new ActiveXObject('Msxml2.XMLHTTP')},function(){return new ActiveXObject('Microsoft.XMLHTTP')},function(){return new XMLHttpRequest()})||false;},activeRequestCount:0};OpenLayers.Ajax.Responders={responders:[],register:function(responderToAdd){for(var i=0;i<this.responders.length;i++)
if(responderToAdd==this.responders[i])
return;this.responders.push(responderToAdd);},dispatch:function(callback,request,transport,json){var responder;for(var i=0;i<this.responders.length;i++){responder=this.responders[i];if(responder[callback]&&typeof responder[callback]=='function'){try{responder[callback].apply(responder,[request,transport,json]);}catch(e){}}}}};OpenLayers.Ajax.Responders.register({onCreate:function(){OpenLayers.Ajax.activeRequestCount++;},onComplete:function(){OpenLayers.Ajax.activeRequestCount--;}});OpenLayers.Ajax.Base=function(){};OpenLayers.Ajax.Base.prototype={setOptions:function(options){this.options={'method':'post','asynchronous':true,'parameters':''};OpenLayers.Util.extend(this.options,options||{});},responseIsSuccess:function(){return this.transport.status==undefined||this.transport.status==0||(this.transport.status>=200&&this.transport.status<300);},responseIsFailure:function(){return!this.responseIsSuccess();}};OpenLayers.Ajax.Request=OpenLayers.Class(OpenLayers.Ajax.Base,{initialize:function(url,options){this.transport=OpenLayers.Ajax.getTransport();this.setOptions(options);this.request(url);},request:function(url){var parameters=this.options.parameters||'';if(parameters.length>0)parameters+='&_=';try{this.url=url;if(this.options.method=='get'&&parameters.length>0){this.url+=(this.url.match(/\?/)?'&':'?')+parameters;}
OpenLayers.Ajax.Responders.dispatch('onCreate',this,this.transport);this.transport.open(this.options.method,this.url,this.options.asynchronous);if(this.options.asynchronous){this.transport.onreadystatechange=OpenLayers.Function.bind(this.onStateChange,this);setTimeout(OpenLayers.Function.bind((function(){this.respondToReadyState(1)}),this),10);}
this.setRequestHeaders();var body=this.options.postBody?this.options.postBody:parameters;this.transport.send(this.options.method=='post'?body:null);if(!this.options.asynchronous&&this.transport.overrideMimeType){this.onStateChange();}}catch(e){this.dispatchException(e);}},setRequestHeaders:function(){var requestHeaders=['X-Requested-With','XMLHttpRequest','X-Prototype-Version','OpenLayers'];if(this.options.method=='post'&&!this.options.postBody){requestHeaders.push('Content-type','application/x-www-form-urlencoded');if(this.transport.overrideMimeType){requestHeaders.push('Connection','close');}}
if(this.options.requestHeaders){requestHeaders.push.apply(requestHeaders,this.options.requestHeaders);}
for(var i=0;i<requestHeaders.length;i+=2){this.transport.setRequestHeader(requestHeaders[i],requestHeaders[i+1]);}},onStateChange:function(){var readyState=this.transport.readyState;if(readyState!=1){this.respondToReadyState(this.transport.readyState);}},header:function(name){try{return this.transport.getResponseHeader(name);}catch(e){}},evalJSON:function(){try{return eval(this.header('X-JSON'));}catch(e){}},evalResponse:function(){try{return eval(this.transport.responseText);}catch(e){this.dispatchException(e);}},respondToReadyState:function(readyState){var event=OpenLayers.Ajax.Request.Events[readyState];var transport=this.transport,json=this.evalJSON();if(event=='Complete'){try{var responseSuccess=this.responseIsSuccess()?'Success':'Failure';(this.options['on'+this.transport.status]||this.options['on'+responseSuccess]||OpenLayers.Ajax.emptyFunction)(transport,json);}catch(e){this.dispatchException(e);}
var contentType=this.header('Content-type')||'';if(contentType.match(/^text\/javascript/i)){this.evalResponse();}}
try{(this.options['on'+event]||OpenLayers.Ajax.emptyFunction)(transport,json);OpenLayers.Ajax.Responders.dispatch('on'+event,this,transport,json);}catch(e){this.dispatchException(e);}
if(event=='Complete'){this.transport.onreadystatechange=OpenLayers.Ajax.emptyFunction;}},dispatchException:function(exception){if(this.options.onException){this.options.onException(this,exception);}else{throw exception;}
OpenLayers.Ajax.Responders.dispatch('onException',this,exception);}});OpenLayers.Ajax.Request.Events=['Uninitialized','Loading','Loaded','Interactive','Complete'];OpenLayers.Ajax.getElementsByTagNameNS=function(parentnode,nsuri,nsprefix,tagname){var elem=null;if(parentnode.getElementsByTagNameNS){elem=parentnode.getElementsByTagNameNS(nsuri,tagname);}else{elem=parentnode.getElementsByTagName(nsprefix+':'+tagname);}
return elem;};OpenLayers.Ajax.serializeXMLToString=function(xmldom){var serializer=new XMLSerializer();data=serializer.serializeToString(xmldom);return data;}
OpenLayers.Bounds=OpenLayers.Class({left:null,bottom:null,right:null,top:null,initialize:function(left,bottom,right,top){if(left!=null){this.left=parseFloat(left);}
if(bottom!=null){this.bottom=parseFloat(bottom);}
if(right!=null){this.right=parseFloat(right);}
if(top!=null){this.top=parseFloat(top);}},clone:function(){return new OpenLayers.Bounds(this.left,this.bottom,this.right,this.top);},equals:function(bounds){var equals=false;if(bounds!=null){equals=((this.left==bounds.left)&&(this.right==bounds.right)&&(this.top==bounds.top)&&(this.bottom==bounds.bottom));}
return equals;},toString:function(){return("left-bottom=("+this.left+","+this.bottom+")"
+" right-top=("+this.right+","+this.top+")");},toArray:function(){return[this.left,this.bottom,this.right,this.top];},toBBOX:function(decimal){if(decimal==null){decimal=6;}
var mult=Math.pow(10,decimal);var bbox=Math.round(this.left*mult)/mult+","+
Math.round(this.bottom*mult)/mult+","+
Math.round(this.right*mult)/mult+","+
Math.round(this.top*mult)/mult;return bbox;},getWidth:function(){return(this.right-this.left);},getHeight:function(){return(this.top-this.bottom);},getSize:function(){return new OpenLayers.Size(this.getWidth(),this.getHeight());},getCenterPixel:function(){return new OpenLayers.Pixel((this.left+this.right)/2,(this.bottom+this.top)/2);},getCenterLonLat:function(){return new OpenLayers.LonLat((this.left+this.right)/2,(this.bottom+this.top)/2);},add:function(x,y){if((x==null)||(y==null)){var msg="You must pass both x and y values to the add function.";OpenLayers.Console.error(msg);return null;}
return new OpenLayers.Bounds(this.left+x,this.bottom+y,this.right+x,this.top+y);},extend:function(object){var bounds=null;if(object){switch(object.CLASS_NAME){case"OpenLayers.LonLat":bounds=new OpenLayers.Bounds(object.lon,object.lat,object.lon,object.lat);break;case"OpenLayers.Geometry.Point":bounds=new OpenLayers.Bounds(object.x,object.y,object.x,object.y);break;case"OpenLayers.Bounds":bounds=object;break;}
if(bounds){if((this.left==null)||(bounds.left<this.left)){this.left=bounds.left;}
if((this.bottom==null)||(bounds.bottom<this.bottom)){this.bottom=bounds.bottom;}
if((this.right==null)||(bounds.right>this.right)){this.right=bounds.right;}
if((this.top==null)||(bounds.top>this.top)){this.top=bounds.top;}}}},containsLonLat:function(ll,inclusive){return this.contains(ll.lon,ll.lat,inclusive);},containsPixel:function(px,inclusive){return this.contains(px.x,px.y,inclusive);},contains:function(x,y,inclusive){if(inclusive==null){inclusive=true;}
var contains=false;if(inclusive){contains=((x>=this.left)&&(x<=this.right)&&(y>=this.bottom)&&(y<=this.top));}else{contains=((x>this.left)&&(x<this.right)&&(y>this.bottom)&&(y<this.top));}
return contains;},intersectsBounds:function(bounds,inclusive){if(inclusive==null){inclusive=true;}
var inBottom=(bounds.bottom==this.bottom&&bounds.top==this.top)?true:(((bounds.bottom>this.bottom)&&(bounds.bottom<this.top))||((this.bottom>bounds.bottom)&&(this.bottom<bounds.top)));var inTop=(bounds.bottom==this.bottom&&bounds.top==this.top)?true:(((bounds.top>this.bottom)&&(bounds.top<this.top))||((this.top>bounds.bottom)&&(this.top<bounds.top)));var inRight=(bounds.right==this.right&&bounds.left==this.left)?true:(((bounds.right>this.left)&&(bounds.right<this.right))||((this.right>bounds.left)&&(this.right<bounds.right)));var inLeft=(bounds.right==this.right&&bounds.left==this.left)?true:(((bounds.left>this.left)&&(bounds.left<this.right))||((this.left>bounds.left)&&(this.left<bounds.right)));return(this.containsBounds(bounds,true,inclusive)||bounds.containsBounds(this,true,inclusive)||((inTop||inBottom)&&(inLeft||inRight)));},containsBounds:function(bounds,partial,inclusive){if(partial==null){partial=false;}
if(inclusive==null){inclusive=true;}
var inLeft;var inTop;var inRight;var inBottom;if(inclusive){inLeft=(bounds.left>=this.left)&&(bounds.left<=this.right);inTop=(bounds.top>=this.bottom)&&(bounds.top<=this.top);inRight=(bounds.right>=this.left)&&(bounds.right<=this.right);inBottom=(bounds.bottom>=this.bottom)&&(bounds.bottom<=this.top);}else{inLeft=(bounds.left>this.left)&&(bounds.left<this.right);inTop=(bounds.top>this.bottom)&&(bounds.top<this.top);inRight=(bounds.right>this.left)&&(bounds.right<this.right);inBottom=(bounds.bottom>this.bottom)&&(bounds.bottom<this.top);}
return(partial)?(inTop||inBottom)&&(inLeft||inRight):(inTop&&inLeft&&inBottom&&inRight);},determineQuadrant:function(lonlat){var quadrant="";var center=this.getCenterLonLat();quadrant+=(lonlat.lat<center.lat)?"b":"t";quadrant+=(lonlat.lon<center.lon)?"l":"r";return quadrant;},wrapDateLine:function(maxExtent,options){options=options||{};var leftTolerance=options.leftTolerance||0;var rightTolerance=options.rightTolerance||0;var newBounds=this.clone();if(maxExtent){while(newBounds.left<maxExtent.left&&(newBounds.right-rightTolerance)<=maxExtent.left){newBounds=newBounds.add(maxExtent.getWidth(),0);}
while((newBounds.left+leftTolerance)>=maxExtent.right&&newBounds.right>maxExtent.right){newBounds=newBounds.add(-maxExtent.getWidth(),0);}}
return newBounds;},CLASS_NAME:"OpenLayers.Bounds"});OpenLayers.Bounds.fromString=function(str){var bounds=str.split(",");return OpenLayers.Bounds.fromArray(bounds);};OpenLayers.Bounds.fromArray=function(bbox){return new OpenLayers.Bounds(parseFloat(bbox[0]),parseFloat(bbox[1]),parseFloat(bbox[2]),parseFloat(bbox[3]));};OpenLayers.Bounds.fromSize=function(size){return new OpenLayers.Bounds(0,size.h,size.w,0);};OpenLayers.Bounds.oppositeQuadrant=function(quadrant){var opp="";opp+=(quadrant.charAt(0)=='t')?'b':'t';opp+=(quadrant.charAt(1)=='l')?'r':'l';return opp;};OpenLayers.Element={visible:function(element){return OpenLayers.Util.getElement(element).style.display!='none';},toggle:function(){for(var i=0;i<arguments.length;i++){var element=OpenLayers.Util.getElement(arguments[i]);var display=OpenLayers.Element.visible(element)?'hide':'show';OpenLayers.Element[display](element);}},hide:function(){for(var i=0;i<arguments.length;i++){var element=OpenLayers.Util.getElement(arguments[i]);element.style.display='none';}},show:function(){for(var i=0;i<arguments.length;i++){var element=OpenLayers.Util.getElement(arguments[i]);element.style.display='';}},remove:function(element){element=OpenLayers.Util.getElement(element);element.parentNode.removeChild(element);},getHeight:function(element){element=OpenLayers.Util.getElement(element);return element.offsetHeight;},getDimensions:function(element){element=OpenLayers.Util.getElement(element);if(OpenLayers.Element.getStyle(element,'display')!='none'){return{width:element.offsetWidth,height:element.offsetHeight};}
var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;els.visibility='hidden';els.position='absolute';els.display='';var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display='none';els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};},getStyle:function(element,style){element=OpenLayers.Util.getElement(element);var value=element.style[OpenLayers.String.camelize(style)];if(!value){if(document.defaultView&&document.defaultView.getComputedStyle){var css=document.defaultView.getComputedStyle(element,null);value=css?css.getPropertyValue(style):null;}else if(element.currentStyle){value=element.currentStyle[OpenLayers.String.camelize(style)];}}
var positions=['left','top','right','bottom'];if(window.opera&&(OpenLayers.Util.indexOf(positions,style)!=-1)&&(OpenLayers.Element.getStyle(element,'position')=='static')){value='auto';}
return value=='auto'?null:value;}};OpenLayers.LonLat=OpenLayers.Class({lon:0.0,lat:0.0,initialize:function(lon,lat){this.lon=parseFloat(lon);this.lat=parseFloat(lat);},toString:function(){return("lon="+this.lon+",lat="+this.lat);},toShortString:function(){return(this.lon+", "+this.lat);},clone:function(){return new OpenLayers.LonLat(this.lon,this.lat);},add:function(lon,lat){if((lon==null)||(lat==null)){var msg="You must pass both lon and lat values "+"to the add function.";OpenLayers.Console.error(msg);return null;}
return new OpenLayers.LonLat(this.lon+lon,this.lat+lat);},equals:function(ll){var equals=false;if(ll!=null){equals=((this.lon==ll.lon&&this.lat==ll.lat)||(isNaN(this.lon)&&isNaN(this.lat)&&isNaN(ll.lon)&&isNaN(ll.lat)));}
return equals;},wrapDateLine:function(maxExtent){var newLonLat=this.clone();if(maxExtent){while(newLonLat.lon<maxExtent.left){newLonLat.lon+=maxExtent.getWidth();}
while(newLonLat.lon>maxExtent.right){newLonLat.lon-=maxExtent.getWidth();}}
return newLonLat;},CLASS_NAME:"OpenLayers.LonLat"});OpenLayers.LonLat.fromString=function(str){var pair=str.split(",");return new OpenLayers.LonLat(parseFloat(pair[0]),parseFloat(pair[1]));};OpenLayers.Pixel=OpenLayers.Class({x:0.0,y:0.0,initialize:function(x,y){this.x=parseFloat(x);this.y=parseFloat(y);},toString:function(){return("x="+this.x+",y="+this.y);},clone:function(){return new OpenLayers.Pixel(this.x,this.y);},equals:function(px){var equals=false;if(px!=null){equals=((this.x==px.x&&this.y==px.y)||(isNaN(this.x)&&isNaN(this.y)&&isNaN(px.x)&&isNaN(px.y)));}
return equals;},add:function(x,y){if((x==null)||(y==null)){var msg="You must pass both x and y values to the add function.";OpenLayers.Console.error(msg);return null;}
return new OpenLayers.Pixel(this.x+x,this.y+y);},offset:function(px){var newPx=this.clone();if(px){newPx=this.add(px.x,px.y);}
return newPx;},CLASS_NAME:"OpenLayers.Pixel"});OpenLayers.Size=OpenLayers.Class({w:0.0,h:0.0,initialize:function(w,h){this.w=parseFloat(w);this.h=parseFloat(h);},toString:function(){return("w="+this.w+",h="+this.h);},clone:function(){return new OpenLayers.Size(this.w,this.h);},equals:function(sz){var equals=false;if(sz!=null){equals=((this.w==sz.w&&this.h==sz.h)||(isNaN(this.w)&&isNaN(this.h)&&isNaN(sz.w)&&isNaN(sz.h)));}
return equals;},CLASS_NAME:"OpenLayers.Size"});OpenLayers.Icon=OpenLayers.Class({url:null,size:null,offset:null,calculateOffset:null,imageDiv:null,px:null,initialize:function(url,size,offset,calculateOffset){this.url=url;this.size=(size)?size:new OpenLayers.Size(20,20);this.offset=offset?offset:new OpenLayers.Pixel(-(this.size.w/2),-(this.size.h/2));this.calculateOffset=calculateOffset;var id=OpenLayers.Util.createUniqueID("OL_Icon_");this.imageDiv=OpenLayers.Util.createAlphaImageDiv(id);},destroy:function(){OpenLayers.Event.stopObservingElement(this.imageDiv.firstChild);this.imageDiv.innerHTML="";this.imageDiv=null;},clone:function(){return new OpenLayers.Icon(this.url,this.size,this.offset,this.calculateOffset);},setSize:function(size){if(size!=null){this.size=size;}
this.draw();},draw:function(px){OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,this.size,this.url,"absolute");this.moveTo(px);return this.imageDiv;},setOpacity:function(opacity){OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,null,null,null,null,null,null,opacity);},moveTo:function(px){if(px!=null){this.px=px;}
if(this.imageDiv!=null){if(this.px==null){this.display(false);}else{if(this.calculateOffset){this.offset=this.calculateOffset(this.size);}
var offsetPx=this.px.offset(this.offset);OpenLayers.Util.modifyAlphaImageDiv(this.imageDiv,null,offsetPx);}}},display:function(display){this.imageDiv.style.display=(display)?"":"none";},CLASS_NAME:"OpenLayers.Icon"});OpenLayers.Control.MouseStopped=OpenLayers.Class.create();OpenLayers.Control.MouseStopped.prototype=OpenLayers.Class.inherit(OpenLayers.Control,{element:null,chrono:null,delay:1000,toCallObj:null,toCall:function(){},initialize:function(delay,objForCall,fctToCall){OpenLayers.Control.prototype.initialize.apply(this,arguments);this.delay=delay;this.toCallObj=objForCall;this.toCall=fctToCall;},mouseMoved:function(evt){if(this.chrono!=null){window.clearTimeout(this.chrono);}
var t=this;this.chrono=window.setTimeout(function(){t.toCall.apply(t.toCallObj,[evt])},this.delay);},mouseOut:function(evt){if(this.chrono!=null)
window.clearTimeout(this.chrono);},setMap:function(){OpenLayers.Control.prototype.setMap.apply(this,arguments);this.map.events.register('mousemove',this,this.mouseMoved);this.map.events.register('mouseout',this,this.mouseOut);},CLASS_NAME:"OpenLayers.Control.MouseStopped"});OpenLayers.Control.ZoomToMaxExtent=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_BUTTON,trigger:function(){if(this.map){this.map.zoomToMaxExtent();}},CLASS_NAME:"OpenLayers.Control.ZoomToMaxExtent"});OpenLayers.Event={observers:false,KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,element:function(event){return event.target||event.srcElement;},isLeftClick:function(event){return(((event.which)&&(event.which==1))||((event.button)&&(event.button==1)));},stop:function(event,allowDefault){if(!allowDefault){if(event.preventDefault){event.preventDefault();}else{event.returnValue=false;}}
if(event.stopPropagation){event.stopPropagation();}else{event.cancelBubble=true;}},findElement:function(event,tagName){var element=OpenLayers.Event.element(event);while(element.parentNode&&(!element.tagName||(element.tagName.toUpperCase()!=tagName.toUpperCase())))
element=element.parentNode;return element;},observe:function(elementParam,name,observer,useCapture){var element=OpenLayers.Util.getElement(elementParam);useCapture=useCapture||false;if(name=='keypress'&&(navigator.appVersion.match(/Konqueror|Safari|KHTML/)||element.attachEvent)){name='keydown';}
if(!this.observers){this.observers={};}
if(!element._eventCacheID){var idPrefix="eventCacheID_";if(element.id){idPrefix=element.id+"_"+idPrefix;}
element._eventCacheID=OpenLayers.Util.createUniqueID(idPrefix);}
var cacheID=element._eventCacheID;if(!this.observers[cacheID]){this.observers[cacheID]=[];}
this.observers[cacheID].push({'element':element,'name':name,'observer':observer,'useCapture':useCapture});if(element.addEventListener){element.addEventListener(name,observer,useCapture);}else if(element.attachEvent){element.attachEvent('on'+name,observer);}},stopObservingElement:function(elementParam){var element=OpenLayers.Util.getElement(elementParam);var cacheID=element._eventCacheID;this._removeElementObservers(OpenLayers.Event.observers[cacheID]);},_removeElementObservers:function(elementObservers){if(elementObservers){for(var i=elementObservers.length-1;i>=0;i--){var entry=elementObservers[i];var args=new Array(entry.element,entry.name,entry.observer,entry.useCapture);var removed=OpenLayers.Event.stopObserving.apply(this,args);}}},stopObserving:function(elementParam,name,observer,useCapture){useCapture=useCapture||false;var element=OpenLayers.Util.getElement(elementParam);var cacheID=element._eventCacheID;if(name=='keypress'){if(navigator.appVersion.match(/Konqueror|Safari|KHTML/)||element.detachEvent){name='keydown';}}
var foundEntry=false;var elementObservers=OpenLayers.Event.observers[cacheID];if(elementObservers){var i=0;while(!foundEntry&&i<elementObservers.length){var cacheEntry=elementObservers[i];if((cacheEntry.name==name)&&(cacheEntry.observer==observer)&&(cacheEntry.useCapture==useCapture)){elementObservers.splice(i,1);if(elementObservers.length==0){delete OpenLayers.Event.observers[cacheID];}
foundEntry=true;break;}
i++;}}
if(element.removeEventListener){element.removeEventListener(name,observer,useCapture);}else if(element&&element.detachEvent){element.detachEvent('on'+name,observer);}
return foundEntry;},unloadCache:function(){if(OpenLayers.Event.observers){for(var cacheID in OpenLayers.Event.observers){var elementObservers=OpenLayers.Event.observers[cacheID];OpenLayers.Event._removeElementObservers.apply(this,[elementObservers]);}
OpenLayers.Event.observers=false;}},CLASS_NAME:"OpenLayers.Event"};OpenLayers.Event.observe(window,'unload',OpenLayers.Event.unloadCache,false);if(window.Event){OpenLayers.Util.applyDefaults(window.Event,OpenLayers.Event);}else{var Event=OpenLayers.Event;}
OpenLayers.Events=OpenLayers.Class({BROWSER_EVENTS:["mouseover","mouseout","mousedown","mouseup","mousemove","click","dblclick","resize","focus","blur"],listeners:null,object:null,element:null,eventTypes:null,eventHandler:null,fallThrough:null,initialize:function(object,element,eventTypes,fallThrough){this.object=object;this.element=element;this.eventTypes=eventTypes;this.fallThrough=fallThrough;this.listeners={};this.eventHandler=OpenLayers.Function.bindAsEventListener(this.handleBrowserEvent,this);if(this.eventTypes!=null){for(var i=0;i<this.eventTypes.length;i++){this.addEventType(this.eventTypes[i]);}}
if(this.element!=null){this.attachToElement(element);}},destroy:function(){if(this.element){OpenLayers.Event.stopObservingElement(this.element);}
this.element=null;this.listeners=null;this.object=null;this.eventTypes=null;this.fallThrough=null;this.eventHandler=null;},addEventType:function(eventName){if(!this.listeners[eventName]){this.listeners[eventName]=[];}},attachToElement:function(element){for(var i=0;i<this.BROWSER_EVENTS.length;i++){var eventType=this.BROWSER_EVENTS[i];this.addEventType(eventType);OpenLayers.Event.observe(element,eventType,this.eventHandler);}
OpenLayers.Event.observe(element,"dragstart",OpenLayers.Event.stop);},register:function(type,obj,func){if(func!=null){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];if(listeners!=null){listeners.push({obj:obj,func:func});}}},registerPriority:function(type,obj,func){if(func!=null){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];if(listeners!=null){listeners.unshift({obj:obj,func:func});}}},unregister:function(type,obj,func){if(obj==null){obj=this.object;}
var listeners=this.listeners[type];if(listeners!=null){for(var i=0;i<listeners.length;i++){if(listeners[i].obj==obj&&listeners[i].func==func){listeners.splice(i,1);return true;}}}
return false;},remove:function(type){if(this.listeners[type]!=null){this.listeners[type]=[];}},triggerEvent:function(type,evt){if(evt==null){evt={};}
evt.object=this.object;evt.element=this.element;var listeners=(this.listeners[type])?this.listeners[type].slice():null;if((listeners!=null)&&(listeners.length>0)){for(var i=0;i<listeners.length;i++){var callback=listeners[i];var continueChain;if(callback.obj!=null){continueChain=callback.func.call(callback.obj,evt);}else{continueChain=callback.func(evt);}
if((continueChain!=null)&&(continueChain==false)){break;}}
if(!this.fallThrough){OpenLayers.Event.stop(evt,true);}}},handleBrowserEvent:function(evt){evt.xy=this.getMousePosition(evt);this.triggerEvent(evt.type,evt)},getMousePosition:function(evt){if(!this.element.offsets){this.element.offsets=OpenLayers.Util.pagePosition(this.element);this.element.offsets[0]+=(document.documentElement.scrollLeft||document.body.scrollLeft);this.element.offsets[1]+=(document.documentElement.scrollTop||document.body.scrollTop);}
return new OpenLayers.Pixel((evt.clientX+(document.documentElement.scrollLeft||document.body.scrollLeft))-this.element.offsets[0]
-(document.documentElement.clientLeft||0),(evt.clientY+(document.documentElement.scrollTop||document.body.scrollTop))-this.element.offsets[1]
-(document.documentElement.clientTop||0));},CLASS_NAME:"OpenLayers.Events"});OpenLayers.Popup.Anchored=OpenLayers.Class(OpenLayers.Popup,{relativePosition:null,anchor:null,initialize:function(id,lonlat,size,contentHTML,anchor,closeBox){var newArguments=new Array(id,lonlat,size,contentHTML,closeBox);OpenLayers.Popup.prototype.initialize.apply(this,newArguments);this.anchor=(anchor!=null)?anchor:{size:new OpenLayers.Size(0,0),offset:new OpenLayers.Pixel(0,0)};},draw:function(px){if(px==null){if((this.lonlat!=null)&&(this.map!=null)){px=this.map.getLayerPxFromLonLat(this.lonlat);}}
this.relativePosition=this.calculateRelativePosition(px);return OpenLayers.Popup.prototype.draw.apply(this,arguments);},calculateRelativePosition:function(px){var lonlat=this.map.getLonLatFromLayerPx(px);var extent=this.map.getExtent();var quadrant=extent.determineQuadrant(lonlat);return OpenLayers.Bounds.oppositeQuadrant(quadrant);},moveTo:function(px){this.relativePosition=this.calculateRelativePosition(px);var newPx=this.calculateNewPx(px);var newArguments=new Array(newPx);OpenLayers.Popup.prototype.moveTo.apply(this,newArguments);},setSize:function(size){OpenLayers.Popup.prototype.setSize.apply(this,arguments);if((this.lonlat)&&(this.map)){var px=this.map.getLayerPxFromLonLat(this.lonlat);this.moveTo(px);}},calculateNewPx:function(px){var newPx=px.offset(this.anchor.offset);var top=(this.relativePosition.charAt(0)=='t');newPx.y+=(top)?-this.size.h:this.anchor.size.h;var left=(this.relativePosition.charAt(1)=='l');newPx.x+=(left)?-this.size.w:this.anchor.size.w;return newPx;},CLASS_NAME:"OpenLayers.Popup.Anchored"});OpenLayers.Tile=OpenLayers.Class({EVENT_TYPES:["loadstart","loadend","reload"],events:null,id:null,layer:null,url:null,bounds:null,size:null,position:null,drawn:false,isLoading:false,initialize:function(layer,position,bounds,url,size){this.layer=layer;this.position=position;this.bounds=bounds;this.url=url;this.size=size;this.id=OpenLayers.Util.createUniqueID("Tile_");this.events=new OpenLayers.Events(this,null,this.EVENT_TYPES);},destroy:function(){this.layer=null;this.bounds=null;this.size=null;this.position=null;this.events.destroy();this.events=null;},draw:function(){this.clear();var maxExtent=this.layer.maxExtent;var withinMaxExtent=(maxExtent&&this.bounds.intersectsBounds(maxExtent,false));var mapExtent=this.layer.map.getExtent();var withinMapExtent=(mapExtent&&this.bounds.intersectsBounds(mapExtent,false));return((withinMaxExtent||this.layer.displayOutsideMaxExtent)&&(withinMapExtent||(this.layer.buffer!=0)));},moveTo:function(bounds,position,redraw){if(redraw==null){redraw=true;}
this.clear();this.bounds=bounds.clone();this.position=position.clone();if(redraw){this.draw();}},clear:function(){this.drawn=false;},getBoundsFromBaseLayer:function(position){OpenLayers.Console.warn("You are using the 'reproject' option "+"on the "+this.layer.name+" layer. This option is deprecated: "+"its use was designed to support displaying data over commercial "+"basemaps, but that functionality should now be achieved by using "+"Spherical Mercator support. More information is available from "+"http://trac.openlayers.org/wiki/SphericalMercator.");var topLeft=this.layer.map.getLonLatFromLayerPx(position);var bottomRightPx=position.clone();bottomRightPx.x+=this.size.w;bottomRightPx.y+=this.size.h;var bottomRight=this.layer.map.getLonLatFromLayerPx(bottomRightPx);if(topLeft.lon>bottomRight.lon){if(topLeft.lon<0){topLeft.lon=-180-(topLeft.lon+180);}else{bottomRight.lon=180+bottomRight.lon+180;}}
bounds=new OpenLayers.Bounds(topLeft.lon,bottomRight.lat,bottomRight.lon,topLeft.lat);return bounds;},CLASS_NAME:"OpenLayers.Tile"});OpenLayers.Control.OverviewMap=OpenLayers.Class(OpenLayers.Control,{id:"OverviewMap",element:null,ovmap:null,size:new OpenLayers.Size(180,90),layers:null,minRatio:8,maxRatio:32,mapOptions:null,initialize:function(options){this.layers=[];OpenLayers.Control.prototype.initialize.apply(this,[options]);},destroy:function(){if(!this.mapDiv){return;}
this.mapDiv.removeChild(this.extentRectangle);this.extentRectangle=null;this.rectEvents.destroy();this.rectEvents=null;this.ovmap.destroy();this.ovmap=null;this.element.removeChild(this.mapDiv);this.mapDiv=null;this.mapDivEvents.destroy();this.mapDivEvents=null;this.div.removeChild(this.element);this.element=null;this.elementEvents.destroy();this.elementEvents=null;if(this.maximizeDiv){OpenLayers.Event.stopObservingElement(this.maximizeDiv);this.div.removeChild(this.maximizeDiv);this.maximizeDiv=null;}
if(this.minimizeDiv){OpenLayers.Event.stopObservingElement(this.minimizeDiv);this.div.removeChild(this.minimizeDiv);this.minimizeDiv=null;}
this.map.events.unregister('moveend',this,this.update);this.map.events.unregister("changebaselayer",this,this.baseLayerDraw);OpenLayers.Control.prototype.destroy.apply(this,arguments);},draw:function(){OpenLayers.Control.prototype.draw.apply(this,arguments);if(!(this.layers.length>0)){if(this.map.baseLayer){var layer=this.map.baseLayer.clone();this.layers=[layer];}else{this.map.events.register("changebaselayer",this,this.baseLayerDraw);return this.div;}}
this.element=document.createElement('div');this.element.className=this.displayClass+'Element';this.element.style.display='none';this.mapDiv=document.createElement('div');this.mapDiv.style.width=this.size.w+'px';this.mapDiv.style.height=this.size.h+'px';this.mapDiv.style.position='relative';this.mapDiv.style.overflow='hidden';this.mapDiv.id=OpenLayers.Util.createUniqueID('overviewMap');this.extentRectangle=document.createElement('div');this.extentRectangle.style.position='absolute';this.extentRectangle.style.zIndex=1000;this.extentRectangle.style.overflow='hidden';this.extentRectangle.style.backgroundImage='url('+
OpenLayers.Util.getImagesLocation()+'blank.gif)';this.extentRectangle.className=this.displayClass+'ExtentRectangle';this.mapDiv.appendChild(this.extentRectangle);this.element.appendChild(this.mapDiv);this.div.appendChild(this.element);this.map.events.register('moveend',this,this.update);this.elementEvents=new OpenLayers.Events(this,this.element);this.elementEvents.register('mousedown',this,function(e){OpenLayers.Event.stop(e);});this.elementEvents.register('click',this,function(e){OpenLayers.Event.stop(e);});this.elementEvents.register('dblclick',this,function(e){OpenLayers.Event.stop(e);});this.rectEvents=new OpenLayers.Events(this,this.extentRectangle,null,true);this.rectEvents.register('mouseout',this,this.rectMouseOut);this.rectEvents.register('mousedown',this,this.rectMouseDown);this.rectEvents.register('mousemove',this,this.rectMouseMove);this.rectEvents.register('mouseup',this,this.rectMouseUp);this.rectEvents.register('click',this,function(e){OpenLayers.Event.stop(e);});this.rectEvents.register('dblclick',this,this.rectDblClick);this.mapDivEvents=new OpenLayers.Events(this,this.mapDiv);this.mapDivEvents.register('click',this,this.mapDivClick);if(!this.outsideViewport){this.div.className=this.displayClass+'Container';var imgLocation=OpenLayers.Util.getImagesLocation();var img=imgLocation+'layer-switcher-maximize.png';this.maximizeDiv=OpenLayers.Util.createAlphaImageDiv(this.displayClass+'MaximizeButton',null,new OpenLayers.Size(18,18),img,'absolute');this.maximizeDiv.style.display='none';this.maximizeDiv.className=this.displayClass+'MaximizeButton';OpenLayers.Event.observe(this.maximizeDiv,'click',OpenLayers.Function.bindAsEventListener(this.maximizeControl,this));this.div.appendChild(this.maximizeDiv);var img=imgLocation+'layer-switcher-minimize.png';this.minimizeDiv=OpenLayers.Util.createAlphaImageDiv('OpenLayers_Control_minimizeDiv',null,new OpenLayers.Size(18,18),img,'absolute');this.minimizeDiv.style.display='none';this.minimizeDiv.className=this.displayClass+'MinimizeButton';OpenLayers.Event.observe(this.minimizeDiv,'click',OpenLayers.Function.bindAsEventListener(this.minimizeControl,this));this.div.appendChild(this.minimizeDiv);var eventsToStop=['dblclick','mousedown'];for(var i=0;i<eventsToStop.length;i++){OpenLayers.Event.observe(this.maximizeDiv,eventsToStop[i],OpenLayers.Event.stop);OpenLayers.Event.observe(this.minimizeDiv,eventsToStop[i],OpenLayers.Event.stop);}
this.minimizeControl();}else{this.element.style.display='';}
if(this.map.getExtent()){this.update();}
return this.div;},baseLayerDraw:function(){this.draw();this.map.events.unregister("changebaselayer",this,this.baseLayerDraw);},rectMouseOut:function(evt){if(this.rectDragStart!=null){if(this.performedRectDrag){this.rectMouseMove(evt);var rectPxBounds=this.getRectPxBounds();if((rectPxBounds.top<=0)||(rectPxBounds.left<=0)||(rectPxBounds.bottom>=this.size.h-this.hComp)||(rectPxBounds.right>=this.size.w-this.wComp)){this.updateMapToRect();}else{return;}}
document.onselectstart=null;this.rectDragStart=null;}},rectMouseDown:function(evt){if(!OpenLayers.Event.isLeftClick(evt))return;this.rectDragStart=evt.xy.clone();this.performedRectDrag=false;OpenLayers.Event.stop(evt);},rectMouseMove:function(evt){if(this.rectDragStart!=null){var deltaX=this.rectDragStart.x-evt.xy.x;var deltaY=this.rectDragStart.y-evt.xy.y;var rectPxBounds=this.getRectPxBounds();var rectTop=rectPxBounds.top;var rectLeft=rectPxBounds.left;var rectHeight=Math.abs(rectPxBounds.getHeight());var rectWidth=rectPxBounds.getWidth();var newTop=Math.max(0,(rectTop-deltaY));newTop=Math.min(newTop,this.ovmap.size.h-this.hComp-rectHeight);var newLeft=Math.max(0,(rectLeft-deltaX));newLeft=Math.min(newLeft,this.ovmap.size.w-this.wComp-rectWidth);this.setRectPxBounds(new OpenLayers.Bounds(newLeft,newTop+rectHeight,newLeft+rectWidth,newTop));this.rectDragStart=evt.xy.clone();this.performedRectDrag=true;OpenLayers.Event.stop(evt);}},rectMouseUp:function(evt){if(!OpenLayers.Event.isLeftClick(evt))return;if(this.performedRectDrag){this.updateMapToRect();OpenLayers.Event.stop(evt);}
document.onselectstart=null;this.rectDragStart=null;},rectDblClick:function(evt){this.performedRectDrag=false;OpenLayers.Event.stop(evt);this.updateOverview();},mapDivClick:function(evt){var pxBounds=this.getRectPxBounds();var pxCenter=pxBounds.getCenterPixel();var deltaX=evt.xy.x-pxCenter.x;var deltaY=evt.xy.y-pxCenter.y;var top=pxBounds.top;var left=pxBounds.left;var height=Math.abs(pxBounds.getHeight());var width=pxBounds.getWidth();var newTop=Math.max(0,(top+deltaY));newTop=Math.min(newTop,this.ovmap.size.h-height);var newLeft=Math.max(0,(left+deltaX));newLeft=Math.min(newLeft,this.ovmap.size.w-width);this.setRectPxBounds(new OpenLayers.Bounds(newLeft,newTop+height,newLeft+width,newTop));this.updateMapToRect();OpenLayers.Event.stop(evt);},maximizeControl:function(e){this.element.style.display='';this.showToggle(false);if(e!=null){OpenLayers.Event.stop(e);}},minimizeControl:function(e){this.element.style.display='none';this.showToggle(true);if(e!=null){OpenLayers.Event.stop(e);}},showToggle:function(minimize){this.maximizeDiv.style.display=minimize?'':'none';this.minimizeDiv.style.display=minimize?'none':'';},update:function(){if(this.ovmap==null){this.createMap();}
if(!this.isSuitableOverview()){this.updateOverview();}
this.updateRectToMap();},isSuitableOverview:function(){var mapExtent=this.map.getExtent();var maxExtent=this.map.maxExtent;var testExtent=new OpenLayers.Bounds(Math.max(mapExtent.left,maxExtent.left),Math.max(mapExtent.bottom,maxExtent.bottom),Math.min(mapExtent.right,maxExtent.right),Math.min(mapExtent.top,maxExtent.top));var resRatio=this.ovmap.getResolution()/this.map.getResolution();return((resRatio>this.minRatio)&&(resRatio<=this.maxRatio)&&(this.ovmap.getExtent().containsBounds(testExtent)));},updateOverview:function(){var mapRes=this.map.getResolution();var targetRes=this.ovmap.getResolution();var resRatio=targetRes/mapRes;if(resRatio>this.maxRatio){targetRes=this.minRatio*mapRes;}else if(resRatio<=this.minRatio){targetRes=this.maxRatio*mapRes;}
this.ovmap.setCenter(this.map.center,this.ovmap.getZoomForResolution(targetRes));this.updateRectToMap();},createMap:function(){var options=OpenLayers.Util.extend({controls:[],maxResolution:'auto'},this.mapOptions);this.ovmap=new OpenLayers.Map(this.mapDiv,options);this.ovmap.addLayers(this.layers);this.ovmap.zoomToMaxExtent();this.wComp=parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-left-width'))+
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-right-width'));this.wComp=(this.wComp)?this.wComp:2;this.hComp=parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-top-width'))+
parseInt(OpenLayers.Element.getStyle(this.extentRectangle,'border-bottom-width'));this.hComp=(this.hComp)?this.hComp:2;},updateRectToMap:function(){if(this.map.units!='degrees'){if(this.ovmap.getProjection()&&(this.map.getProjection()!=this.ovmap.getProjection())){alert('The overview map only works when it is in the same projection as the main map');}}
var pxBounds=this.getRectBoundsFromMapBounds(this.map.getExtent());if(pxBounds){this.setRectPxBounds(pxBounds);}},updateMapToRect:function(){var pxBounds=this.getRectPxBounds();var lonLatBounds=this.getMapBoundsFromRectBounds(pxBounds);this.map.setCenter(lonLatBounds.getCenterLonLat(),this.map.zoom);},getRectPxBounds:function(){var top=parseInt(this.extentRectangle.style.top);var left=parseInt(this.extentRectangle.style.left);var height=parseInt(this.extentRectangle.style.height);var width=parseInt(this.extentRectangle.style.width);return new OpenLayers.Bounds(left,top+height,left+width,top);},setRectPxBounds:function(pxBounds){var top=Math.max(pxBounds.top,0);var left=Math.max(pxBounds.left,0);var bottom=Math.min(pxBounds.top+Math.abs(pxBounds.getHeight()),this.ovmap.size.h-this.hComp);var right=Math.min(pxBounds.left+pxBounds.getWidth(),this.ovmap.size.w-this.wComp);this.extentRectangle.style.top=parseInt(top)+'px';this.extentRectangle.style.left=parseInt(left)+'px';this.extentRectangle.style.height=parseInt(Math.max(bottom-top,0))+'px';this.extentRectangle.style.width=parseInt(Math.max(right-left,0))+'px';},getRectBoundsFromMapBounds:function(lonLatBounds){var leftBottomLonLat=new OpenLayers.LonLat(lonLatBounds.left,lonLatBounds.bottom);var rightTopLonLat=new OpenLayers.LonLat(lonLatBounds.right,lonLatBounds.top);var leftBottomPx=this.getOverviewPxFromLonLat(leftBottomLonLat);var rightTopPx=this.getOverviewPxFromLonLat(rightTopLonLat);var bounds=null;if(leftBottomPx&&rightTopPx){bounds=new OpenLayers.Bounds(leftBottomPx.x,leftBottomPx.y,rightTopPx.x,rightTopPx.y);}
return bounds;},getMapBoundsFromRectBounds:function(pxBounds){var leftBottomPx=new OpenLayers.Pixel(pxBounds.left,pxBounds.bottom);var rightTopPx=new OpenLayers.Pixel(pxBounds.right,pxBounds.top);var leftBottomLonLat=this.getLonLatFromOverviewPx(leftBottomPx);var rightTopLonLat=this.getLonLatFromOverviewPx(rightTopPx);return new OpenLayers.Bounds(leftBottomLonLat.lon,leftBottomLonLat.lat,rightTopLonLat.lon,rightTopLonLat.lat);},getLonLatFromOverviewPx:function(overviewMapPx){var size=this.ovmap.size;var res=this.ovmap.getResolution();var center=this.ovmap.getExtent().getCenterLonLat();var delta_x=overviewMapPx.x-(size.w/2);var delta_y=overviewMapPx.y-(size.h/2);return new OpenLayers.LonLat(center.lon+delta_x*res,center.lat-delta_y*res);},getOverviewPxFromLonLat:function(lonlat){var res=this.ovmap.getResolution();var extent=this.ovmap.getExtent();var px=null;if(extent){px=new OpenLayers.Pixel(Math.round(1/res*(lonlat.lon-extent.left)),Math.round(1/res*(extent.top-lonlat.lat)));}
return px;},CLASS_NAME:'OpenLayers.Control.OverviewMap'});OpenLayers.Handler=OpenLayers.Class({id:null,control:null,map:null,keyMask:null,active:false,evt:null,initialize:function(control,callbacks,options){OpenLayers.Util.extend(this,options);this.control=control;this.callbacks=callbacks;if(control.map){this.setMap(control.map);}
OpenLayers.Util.extend(this,options);this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");},setMap:function(map){this.map=map;},checkModifiers:function(evt){if(this.keyMask==null){return true;}
var keyModifiers=(evt.shiftKey?OpenLayers.Handler.MOD_SHIFT:0)|(evt.ctrlKey?OpenLayers.Handler.MOD_CTRL:0)|(evt.altKey?OpenLayers.Handler.MOD_ALT:0);return(keyModifiers==this.keyMask);},activate:function(){if(this.active){return false;}
var events=OpenLayers.Events.prototype.BROWSER_EVENTS;for(var i=0;i<events.length;i++){if(this[events[i]]){this.register(events[i],this[events[i]]);}}
this.active=true;return true;},deactivate:function(){if(!this.active){return false;}
var events=OpenLayers.Events.prototype.BROWSER_EVENTS;for(var i=0;i<events.length;i++){if(this[events[i]]){this.unregister(events[i],this[events[i]]);}}
this.active=false;return true;},callback:function(name,args){if(this.callbacks[name]){this.callbacks[name].apply(this.control,args);}},register:function(name,method){this.map.events.registerPriority(name,this,method);this.map.events.registerPriority(name,this,this.setEvent);},unregister:function(name,method){this.map.events.unregister(name,this,method);this.map.events.unregister(name,this,this.setEvent);},setEvent:function(evt){this.evt=evt;return true;},destroy:function(){this.deactivate();this.control=this.map=null;},CLASS_NAME:"OpenLayers.Handler"});OpenLayers.Handler.MOD_NONE=0;OpenLayers.Handler.MOD_SHIFT=1;OpenLayers.Handler.MOD_CTRL=2;OpenLayers.Handler.MOD_ALT=4;OpenLayers.Map=OpenLayers.Class({Z_INDEX_BASE:{BaseLayer:100,Overlay:325,Popup:750,Control:1000},EVENT_TYPES:["addlayer","removelayer","changelayer","movestart","move","moveend","zoomend","popupopen","popupclose","addmarker","removemarker","clearmarkers","mouseover","mouseout","mousemove","dragstart","drag","dragend","changebaselayer","gastroLayersChanged"],id:null,events:null,div:null,size:null,viewPortDiv:null,layerContainerOrigin:null,layerContainerDiv:null,layers:null,controls:null,popups:null,baseLayer:null,center:null,zoom:0,viewRequestID:0,tileSize:null,projection:"EPSG:4326",units:'degrees',resolutions:null,maxResolution:1.40625,minResolution:null,maxScale:null,minScale:null,maxExtent:null,minExtent:null,restrictedExtent:null,numZoomLevels:16,theme:null,fallThrough:false,initialize:function(div,options){this.setOptions(options);this.id=OpenLayers.Util.createUniqueID("OpenLayers.Map_");this.div=OpenLayers.Util.getElement(div);var id=this.div.id+"_OpenLayers_ViewPort";this.viewPortDiv=OpenLayers.Util.createDiv(id,null,null,null,"relative",null,"hidden");this.viewPortDiv.style.width="100%";this.viewPortDiv.style.height="100%";this.viewPortDiv.className="olMapViewport";this.div.appendChild(this.viewPortDiv);id=this.div.id+"_OpenLayers_Container";this.layerContainerDiv=OpenLayers.Util.createDiv(id);this.layerContainerDiv.style.zIndex=this.Z_INDEX_BASE['Popup']-1;this.viewPortDiv.appendChild(this.layerContainerDiv);this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES,this.fallThrough);this.updateSize();this.events.register("movestart",this,this.updateSize);if(OpenLayers.String.contains(navigator.appName,"Microsoft")){this.events.register("resize",this,this.updateSize);}else{OpenLayers.Event.observe(window,'resize',OpenLayers.Function.bind(this.updateSize,this));}
if(this.theme){var addNode=true;var nodes=document.getElementsByTagName('link');for(var i=0;i<nodes.length;++i){if(OpenLayers.Util.isEquivalentUrl(nodes.item(i).href,this.theme)){addNode=false;break;}}
if(addNode){var cssNode=document.createElement('link');cssNode.setAttribute('rel','stylesheet');cssNode.setAttribute('type','text/css');cssNode.setAttribute('href',this.theme);document.getElementsByTagName('head')[0].appendChild(cssNode);}}
this.layers=[];if(this.controls==null){if(OpenLayers.Control!=null){this.controls=[new OpenLayers.Control.Navigation(),new OpenLayers.Control.PanZoom(),new OpenLayers.Control.ArgParser(),new OpenLayers.Control.Attribution()];}else{this.controls=[];}}
for(var i=0;i<this.controls.length;i++){this.addControlToMap(this.controls[i]);}
this.popups=[];this.unloadDestroy=OpenLayers.Function.bind(this.destroy,this);OpenLayers.Event.observe(window,'unload',this.unloadDestroy);},unloadDestroy:null,destroy:function(){if(!this.unloadDestroy){return false;}
OpenLayers.Event.stopObserving(window,'unload',this.unloadDestroy);this.unloadDestroy=null;if(this.layers!=null){for(var i=this.layers.length-1;i>=0;--i){this.layers[i].destroy(false);}
this.layers=null;}
if(this.controls!=null){for(var i=this.controls.length-1;i>=0;--i){this.controls[i].destroy();}
this.controls=null;}
if(this.viewPortDiv){this.div.removeChild(this.viewPortDiv);}
this.viewPortDiv=null;this.events.destroy();this.events=null;},setOptions:function(options){this.tileSize=new OpenLayers.Size(OpenLayers.Map.TILE_WIDTH,OpenLayers.Map.TILE_HEIGHT);this.maxExtent=new OpenLayers.Bounds(-180,-90,180,90);this.theme=OpenLayers._getScriptLocation()+'theme/default/style.css';OpenLayers.Util.extend(this,options);},getTileSize:function(){return this.tileSize;},getLayer:function(id){var foundLayer=null;for(var i=0;i<this.layers.length;i++){var layer=this.layers[i];if(layer.id==id){foundLayer=layer;}}
return foundLayer;},setLayerZIndex:function(layer,zIdx){layer.setZIndex(this.Z_INDEX_BASE[layer.isBaseLayer?'BaseLayer':'Overlay']
+zIdx*5);},addLayer:function(layer){for(var i=0;i<this.layers.length;i++){if(this.layers[i]==layer){var msg="You tried to add the layer: "+layer.name+" to the map, but it has already been added";OpenLayers.Console.warn(msg);return false;}}
layer.div.style.overflow="";this.setLayerZIndex(layer,this.layers.length);if(layer.isFixed){this.viewPortDiv.appendChild(layer.div);}else{this.layerContainerDiv.appendChild(layer.div);}
this.layers.push(layer);layer.setMap(this);if(layer.isBaseLayer){if(this.baseLayer==null){this.setBaseLayer(layer);}else{layer.setVisibility(false);}}else{layer.redraw();}
this.events.triggerEvent("addlayer");},addLayers:function(layers){for(var i=0;i<layers.length;i++){this.addLayer(layers[i]);}},removeLayer:function(layer,setNewBaseLayer){if(setNewBaseLayer==null){setNewBaseLayer=true;}
if(layer.isFixed){this.viewPortDiv.removeChild(layer.div);}else{this.layerContainerDiv.removeChild(layer.div);}
OpenLayers.Util.removeItem(this.layers,layer);layer.removeMap(this);layer.map=null;if(setNewBaseLayer&&(this.baseLayer==layer)){this.baseLayer=null;for(i=0;i<this.layers.length;i++){var iLayer=this.layers[i];if(iLayer.isBaseLayer){this.setBaseLayer(iLayer);break;}}}
this.events.triggerEvent("removelayer");},getNumLayers:function(){return this.layers.length;},getLayerIndex:function(layer){return OpenLayers.Util.indexOf(this.layers,layer);},setLayerIndex:function(layer,idx){var base=this.getLayerIndex(layer);if(idx<0){idx=0;}else if(idx>this.layers.length){idx=this.layers.length;}
if(base!=idx){this.layers.splice(base,1);this.layers.splice(idx,0,layer);for(var i=0;i<this.layers.length;i++){this.setLayerZIndex(this.layers[i],i);}
this.events.triggerEvent("changelayer");}},raiseLayer:function(layer,delta){var idx=this.getLayerIndex(layer)+delta;this.setLayerIndex(layer,idx);},setBaseLayer:function(newBaseLayer){var oldExtent=null;if(this.baseLayer){oldExtent=this.baseLayer.getExtent();}
if(newBaseLayer!=this.baseLayer){if(OpenLayers.Util.indexOf(this.layers,newBaseLayer)!=-1){if(this.baseLayer!=null){this.baseLayer.setVisibility(false);}
this.baseLayer=newBaseLayer;this.viewRequestID++;this.baseLayer.visibility=true;var center=this.getCenter();if(center!=null){if(oldExtent==null){this.setCenter(center,this.getZoom(),false,true);}else{this.setCenter(oldExtent.getCenterLonLat(),this.getZoomForExtent(oldExtent,true),false,true);}}
this.events.triggerEvent("changebaselayer");}}},addControl:function(control,px){this.controls.push(control);this.addControlToMap(control,px);},addControlToMap:function(control,px){control.outsideViewport=(control.div!=null);control.setMap(this);var div=control.draw(px);if(div){if(!control.outsideViewport){div.style.zIndex=this.Z_INDEX_BASE['Control']+
this.controls.length;this.viewPortDiv.appendChild(div);}}},getControl:function(id){var returnControl=null;for(var i=0;i<this.controls.length;i++){var control=this.controls[i];if(control.id==id){returnControl=control;break;}}
return returnControl;},removeControl:function(control){if((control)&&(control==this.getControl(control.id))){if(!control.outsideViewport){this.viewPortDiv.removeChild(control.div)}
OpenLayers.Util.removeItem(this.controls,control);}},addPopup:function(popup,exclusive){if(exclusive){for(var i=0;i<this.popups.length;i++){this.removePopup(this.popups[i]);}}
popup.map=this;this.popups.push(popup);var popupDiv=popup.draw();if(popupDiv){popupDiv.style.zIndex=this.Z_INDEX_BASE['Popup']+
this.popups.length;this.layerContainerDiv.appendChild(popupDiv);}},removePopup:function(popup){OpenLayers.Util.removeItem(this.popups,popup);if(popup.div){try{this.layerContainerDiv.removeChild(popup.div);}
catch(e){}}
popup.map=null;},getSize:function(){var size=null;if(this.size!=null){size=this.size.clone();}
return size;},updateSize:function(){this.events.element.offsets=null;var newSize=this.getCurrentSize();var oldSize=this.getSize();if(oldSize==null)
this.size=oldSize=newSize;if(!newSize.equals(oldSize)){this.size=newSize;for(var i=0;i<this.layers.length;i++){this.layers[i].onMapResize();}
if(this.baseLayer!=null){var center=new OpenLayers.Pixel(newSize.w/2,newSize.h/2);var centerLL=this.getLonLatFromViewPortPx(center);var zoom=this.getZoom();this.zoom=null;this.setCenter(this.getCenter(),zoom);}}},getCurrentSize:function(){var size=new OpenLayers.Size(this.div.clientWidth,this.div.clientHeight);if(size.w==0&&size.h==0||isNaN(size.w)&&isNaN(size.h)){var dim=OpenLayers.Element.getDimensions(this.div);size.w=dim.width;size.h=dim.height;}
if(size.w==0&&size.h==0||isNaN(size.w)&&isNaN(size.h)){size.w=parseInt(this.div.style.width);size.h=parseInt(this.div.style.height);}
return size;},calculateBounds:function(center,resolution){var extent=null;if(center==null){center=this.getCenter();}
if(resolution==null){resolution=this.getResolution();}
if((center!=null)&&(resolution!=null)){var size=this.getSize();var w_deg=size.w*resolution;var h_deg=size.h*resolution;extent=new OpenLayers.Bounds(center.lon-w_deg/2,center.lat-h_deg/2,center.lon+w_deg/2,center.lat+h_deg/2);}
return extent;},getCenter:function(){return this.center;},getZoom:function(){return this.zoom;},pan:function(dx,dy){var centerPx=this.getViewPortPxFromLonLat(this.getCenter());var newCenterPx=centerPx.add(dx,dy);if(!newCenterPx.equals(centerPx)){var newCenterLonLat=this.getLonLatFromViewPortPx(newCenterPx);if(arguments.length>2)
this.setCenter(newCenterLonLat,map.getZoom(),true,false,true);else
this.setCenter(newCenterLonLat);}},setCenter:function(lonlat,zoom,dragging,forceZoomChange,noEvent){if(!this.center&&!this.isValidLonLat(lonlat)){lonlat=this.maxExtent.getCenterLonLat();}
if(this.restrictedExtent!=null){if(lonlat==null){lonlat=this.getCenter();}
if(zoom==null){zoom=this.getZoom();}
var resolution=null;if(this.baseLayer!=null){resolution=this.baseLayer.resolutions[zoom];}
var extent=this.calculateBounds(lonlat,resolution);if(!this.restrictedExtent.containsBounds(extent)){var maxCenter=this.restrictedExtent.getCenterLonLat();if(extent.getWidth()>this.restrictedExtent.getWidth()){lonlat=new OpenLayers.LonLat(maxCenter.lon,lonlat.lat);}else if(extent.left<this.restrictedExtent.left){lonlat=lonlat.add(this.restrictedExtent.left-
extent.left,0);}else if(extent.right>this.restrictedExtent.right){lonlat=lonlat.add(this.restrictedExtent.right-
extent.right,0);}
if(extent.getHeight()>this.restrictedExtent.getHeight()){lonlat=new OpenLayers.LonLat(lonlat.lon,maxCenter.lat);}else if(extent.bottom<this.restrictedExtent.bottom){lonlat=lonlat.add(0,this.restrictedExtent.bottom-
extent.bottom);}
else if(extent.top>this.restrictedExtent.top){lonlat=lonlat.add(0,this.restrictedExtent.top-
extent.top);}}}
var zoomChanged=forceZoomChange||((this.isValidZoomLevel(zoom))&&(zoom!=this.getZoom()));var centerChanged=(this.isValidLonLat(lonlat))&&(!lonlat.equals(this.center));if(zoomChanged||centerChanged||!dragging){if(!dragging&&!noEvent){this.events.triggerEvent("movestart");}
if(centerChanged){if((!zoomChanged)&&(this.center)){this.centerLayerContainer(lonlat);}
this.center=lonlat.clone();}
if((zoomChanged)||(this.layerContainerOrigin==null)){this.layerContainerOrigin=this.center.clone();this.layerContainerDiv.style.left="0px";this.layerContainerDiv.style.top="0px";}
if(zoomChanged){this.zoom=zoom;this.viewRequestID++;}
var bounds=this.getExtent();this.baseLayer.moveTo(bounds,zoomChanged,dragging);bounds=this.baseLayer.getExtent();for(var i=0;i<this.layers.length;i++){var layer=this.layers[i];if(!layer.isBaseLayer){var moveLayer;var inRange=layer.calculateInRange();if(layer.inRange!=inRange){layer.inRange=inRange;if(layer.visibility==true)
moveLayer=true;else
moveLayer=false;this.events.triggerEvent("changelayer");}else{moveLayer=(layer.visibility&&layer.inRange);}
if(moveLayer){layer.moveTo(bounds,zoomChanged,dragging);}}}
if(zoomChanged){for(var i=0;i<this.popups.length;i++){this.popups[i].updatePosition();}}
this.events.triggerEvent("move");if(zoomChanged){this.events.triggerEvent("zoomend");}}
if(!dragging&&!noEvent){this.events.triggerEvent("moveend");}},centerLayerContainer:function(lonlat){var originPx=this.getViewPortPxFromLonLat(this.layerContainerOrigin);var newPx=this.getViewPortPxFromLonLat(lonlat);if((originPx!=null)&&(newPx!=null)){this.layerContainerDiv.style.left=(originPx.x-newPx.x)+"px";this.layerContainerDiv.style.top=(originPx.y-newPx.y)+"px";}},isValidZoomLevel:function(zoomLevel){return((zoomLevel!=null)&&(zoomLevel>=0)&&(zoomLevel<this.getNumZoomLevels()));},isValidLonLat:function(lonlat){var valid=false;if(lonlat!=null){var maxExtent=this.getMaxExtent();valid=maxExtent.containsLonLat(lonlat);}
return valid;},getProjection:function(){var projection=null;if(this.baseLayer!=null){projection=this.baseLayer.projection;}
return projection;},getMaxResolution:function(){var maxResolution=null;if(this.baseLayer!=null){maxResolution=this.baseLayer.maxResolution;}
return maxResolution;},getMaxExtent:function(){var maxExtent=null;if(this.baseLayer!=null){maxExtent=this.baseLayer.maxExtent;}
return maxExtent;},getNumZoomLevels:function(){var numZoomLevels=null;if(this.baseLayer!=null){numZoomLevels=this.baseLayer.numZoomLevels;}
return numZoomLevels;},getExtent:function(){var extent=null;if(this.baseLayer!=null){extent=this.baseLayer.getExtent();}
return extent;},getResolution:function(){var resolution=null;if(this.baseLayer!=null){resolution=this.baseLayer.getResolution();}
return resolution;},getScale:function(){var scale=null;if(this.baseLayer!=null){var res=this.getResolution();var units=this.baseLayer.units;scale=OpenLayers.Util.getScaleFromResolution(res,units);}
return scale;},getZoomForExtent:function(bounds,closest){var zoom=null;if(this.baseLayer!=null){zoom=this.baseLayer.getZoomForExtent(bounds,closest);}
return zoom;},getZoomForResolution:function(resolution,closest){var zoom=null;if(this.baseLayer!=null){zoom=this.baseLayer.getZoomForResolution(resolution,closest);}
return zoom;},zoomTo:function(zoom){if(this.isValidZoomLevel(zoom)){this.setCenter(null,zoom);}},zoomIn:function(){this.zoomTo(this.getZoom()+1);},zoomOut:function(){this.zoomTo(this.getZoom()-1);},zoomToExtent:function(bounds){var center=bounds.getCenterLonLat();if(this.baseLayer.wrapDateLine){var maxExtent=this.getMaxExtent();bounds=bounds.clone();while(bounds.right<bounds.left){bounds.right+=maxExtent.getWidth();}
center=bounds.getCenterLonLat().wrapDateLine(maxExtent);}
this.setCenter(center,this.getZoomForExtent(bounds));},zoomToMaxExtent:function(){this.zoomToExtent(this.getMaxExtent());},zoomToScale:function(scale){var res=OpenLayers.Util.getResolutionFromScale(scale,this.baseLayer.units);var size=this.getSize();var w_deg=size.w*res;var h_deg=size.h*res;var center=this.getCenter();var extent=new OpenLayers.Bounds(center.lon-w_deg/2,center.lat-h_deg/2,center.lon+w_deg/2,center.lat+h_deg/2);this.zoomToExtent(extent);},getLonLatFromViewPortPx:function(viewPortPx){var lonlat=null;if(this.baseLayer!=null){lonlat=this.baseLayer.getLonLatFromViewPortPx(viewPortPx);}
return lonlat;},getViewPortPxFromLonLat:function(lonlat){var px=null;if(this.baseLayer!=null){px=this.baseLayer.getViewPortPxFromLonLat(lonlat);}
return px;},getLonLatFromPixel:function(px){return this.getLonLatFromViewPortPx(px);},getPixelFromLonLat:function(lonlat){return this.getViewPortPxFromLonLat(lonlat);},getViewPortPxFromLayerPx:function(layerPx){var viewPortPx=null;if(layerPx!=null){var dX=parseInt(this.layerContainerDiv.style.left);var dY=parseInt(this.layerContainerDiv.style.top);viewPortPx=layerPx.add(dX,dY);}
return viewPortPx;},getLayerPxFromViewPortPx:function(viewPortPx){var layerPx=null;if(viewPortPx!=null){var dX=-parseInt(this.layerContainerDiv.style.left);var dY=-parseInt(this.layerContainerDiv.style.top);layerPx=viewPortPx.add(dX,dY);if(isNaN(layerPx.x)||isNaN(layerPx.y)){layerPx=null;}}
return layerPx;},getLonLatFromLayerPx:function(px){px=this.getViewPortPxFromLayerPx(px);return this.getLonLatFromViewPortPx(px);},getLayerPxFromLonLat:function(lonlat){var px=this.getViewPortPxFromLonLat(lonlat);return this.getLayerPxFromViewPortPx(px);},CLASS_NAME:"OpenLayers.Map"});OpenLayers.Map.TILE_WIDTH=256;OpenLayers.Map.TILE_HEIGHT=256;OpenLayers.Marker=OpenLayers.Class({icon:null,lonlat:null,events:null,map:null,initialize:function(lonlat,icon){this.lonlat=lonlat;var newIcon=(icon)?icon:OpenLayers.Marker.defaultIcon();if(this.icon==null){this.icon=newIcon;}else{this.icon.url=newIcon.url;this.icon.size=newIcon.size;this.icon.offset=newIcon.offset;this.icon.calculateOffset=newIcon.calculateOffset;}
this.events=new OpenLayers.Events(this,this.icon.imageDiv,null);},destroy:function(){this.map=null;this.events.destroy();this.events=null;if(this.icon!=null){this.icon.destroy();this.icon=null;}},draw:function(px){return this.icon.draw(px);},moveTo:function(px){if((px!=null)&&(this.icon!=null)){this.icon.moveTo(px);}
this.lonlat=this.map.getLonLatFromLayerPx(px);},onScreen:function(){var onScreen=false;if(this.map){var screenBounds=this.map.getExtent();onScreen=screenBounds.containsLonLat(this.lonlat);}
return onScreen;},inflate:function(inflate){if(this.icon){var newSize=new OpenLayers.Size(this.icon.size.w*inflate,this.icon.size.h*inflate);this.icon.setSize(newSize);}},setOpacity:function(opacity){this.icon.setOpacity(opacity);},display:function(display){this.icon.display(display);},CLASS_NAME:"OpenLayers.Marker"});OpenLayers.Marker.defaultIcon=function(){var url=OpenLayers.Util.getImagesLocation()+"marker.png";var size=new OpenLayers.Size(21,25);var calculateOffset=function(size){return new OpenLayers.Pixel(-(size.w/2),-size.h);};return new OpenLayers.Icon(url,size,null,calculateOffset);};OpenLayers.Tile.Image=OpenLayers.Class(OpenLayers.Tile,{url:null,imgDiv:null,frame:null,initialize:function(layer,position,bounds,url,size){OpenLayers.Tile.prototype.initialize.apply(this,arguments);this.url=url;this.frame=document.createElement('div');this.frame.style.overflow='hidden';this.frame.style.position='absolute';},destroy:function(){if(this.imgDiv!=null){OpenLayers.Event.stopObservingElement(this.imgDiv.id);if(this.imgDiv.parentNode==this.frame){this.frame.removeChild(this.imgDiv);this.imgDiv.map=null;}}
this.imgDiv=null;if((this.frame!=null)&&(this.frame.parentNode==this.layer.div)){this.layer.div.removeChild(this.frame);}
this.frame=null;OpenLayers.Tile.prototype.destroy.apply(this,arguments);},draw:function(){if(this.layer!=this.layer.map.baseLayer&&this.layer.reproject){this.bounds=this.getBoundsFromBaseLayer(this.position);}
if(!OpenLayers.Tile.prototype.draw.apply(this,arguments)){return false;}
if(this.isLoading){this.events.triggerEvent("reload");}else{this.isLoading=true;this.events.triggerEvent("loadstart");}
if(this.imgDiv==null){this.initImgDiv();}
this.imgDiv.viewRequestID=this.layer.map.viewRequestID;this.url=this.layer.getURL(this.bounds);OpenLayers.Util.modifyDOMElement(this.frame,null,this.position,this.size);var imageSize=this.layer.getImageSize();if(this.layer.alpha){OpenLayers.Util.modifyAlphaImageDiv(this.imgDiv,null,null,imageSize,this.url);}else{this.imgDiv.src=this.url;OpenLayers.Util.modifyDOMElement(this.imgDiv,null,null,imageSize);}
this.drawn=true;return true;},clear:function(){OpenLayers.Tile.prototype.clear.apply(this,arguments);if(this.imgDiv){this.imgDiv.style.display="none";}},initImgDiv:function(){var offset=this.layer.imageOffset;var size=this.layer.getImageSize();if(this.layer.alpha){this.imgDiv=OpenLayers.Util.createAlphaImageDiv(null,offset,size,null,"relative",null,null,null,true);}else{this.imgDiv=OpenLayers.Util.createImage(null,offset,size,null,"relative",null,null,true);}
this.imgDiv.className='olTileImage';this.frame.appendChild(this.imgDiv);this.layer.div.appendChild(this.frame);if(this.layer.opacity!=null){OpenLayers.Util.modifyDOMElement(this.imgDiv,null,null,null,null,null,null,this.layer.opacity);}
this.imgDiv.map=this.layer.map;var onload=function(){if(this.isLoading){this.isLoading=false;this.events.triggerEvent("loadend");}}
OpenLayers.Event.observe(this.imgDiv,'load',OpenLayers.Function.bind(onload,this));},checkImgURL:function(){if(this.layer){var loaded=this.layer.alpha?this.imgDiv.firstChild.src:this.imgDiv.src;if(!OpenLayers.Util.isEquivalentUrl(loaded,this.url)){this.imgDiv.style.display="none";}}},CLASS_NAME:"OpenLayers.Tile.Image"});OpenLayers.Handler.Drag=OpenLayers.Class(OpenLayers.Handler,{started:false,dragging:false,last:null,start:null,oldOnselectstart:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);},down:function(evt){},move:function(evt){},up:function(evt){},out:function(evt){},mousedown:function(evt){var propagate=true;this.dragging=false;if(this.checkModifiers(evt)&&OpenLayers.Event.isLeftClick(evt)){this.started=true;this.start=evt.xy;this.last=evt.xy;this.map.div.style.cursor="move";this.down(evt);this.callback("down",[evt.xy]);OpenLayers.Event.stop(evt);if(!this.oldOnselectstart){this.oldOnselectstart=document.onselectstart;document.onselectstart=function(){return false;}}
propagate=false;}else{this.started=false;this.start=null;this.last=null;}
return propagate;},mousemove:function(evt){if(this.started){if(evt.xy.x!=this.last.x||evt.xy.y!=this.last.y){this.dragging=true;this.move(evt);this.callback("move",[evt.xy]);if(!this.oldOnselectstart){this.oldOnselectstart=document.onselectstart;document.onselectstart=function(){return false;}}
this.last=evt.xy;}}
return true;},mouseup:function(evt){if(this.started){this.started=false;this.dragging=false;this.map.div.style.cursor="";this.up(evt);this.callback("up",[evt.xy]);this.callback("done",[evt.xy]);document.onselectstart=this.oldOnselectstart;}
return true;},mouseout:function(evt){if(this.started&&OpenLayers.Util.mouseLeft(evt,this.map.div)){this.started=false;this.dragging=false;this.map.div.style.cursor="";this.out(evt);this.callback("out",[]);if(document.onselectstart){document.onselectstart=this.oldOnselectstart;}
this.callback("done",[evt.xy])}
return true;},click:function(evt){return(this.start==this.last);},activate:function(){var activated=false;if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.dragging=false;activated=true;}
return activated;},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.started=false;this.dragging=false;this.start=null;this.last=null;deactivated=true;}
return deactivated;},CLASS_NAME:"OpenLayers.Handler.Drag"});OpenLayers.Handler.Feature=OpenLayers.Class(OpenLayers.Handler,{geometryTypes:null,layerIndex:null,feature:null,initialize:function(control,layer,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,[control,callbacks,options]);this.layer=layer;},click:function(evt){var selected=this.select('click',evt);return!selected;},mousedown:function(evt){var selected=this.select('down',evt);return!selected;},mousemove:function(evt){this.select('move',evt);return true;},mouseup:function(evt){var selected=this.select('up',evt);return!selected;},dblclick:function(evt){var selected=this.select('dblclick',evt);return!selected;},select:function(type,evt){var feature=this.layer.getFeatureFromEvent(evt);var selected=false;if(feature){if(this.geometryTypes==null||(OpenLayers.Util.indexOf(this.geometryTypes,feature.geometry.CLASS_NAME)>-1)){if(!this.feature){this.callback('over',[feature]);}else if(this.feature!=feature){this.callback('out',[this.feature]);this.callback('over',[feature]);}
this.feature=feature;this.callback(type,[feature]);selected=true;}else{if(this.feature&&(this.feature!=feature)){this.callback('out',[this.feature]);this.feature=null;}
selected=false;}}else{if(this.feature){this.callback('out',[this.feature]);this.feature=null;}
selected=false;}
return selected;},activate:function(){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.layerIndex=this.layer.div.style.zIndex;this.layer.div.style.zIndex=this.map.Z_INDEX_BASE['Popup']-1;return true;}else{return false;}},deactivate:function(){if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){if(this.layer&&this.layer.div){this.layer.div.style.zIndex=this.layerIndex;}
return true;}else{return false;}},CLASS_NAME:"OpenLayers.Handler.Feature"});OpenLayers.Handler.Keyboard=OpenLayers.Class(OpenLayers.Handler,{KEY_EVENTS:["keydown","keypress","keyup"],eventListener:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.eventListener=OpenLayers.Function.bindAsEventListener(this.handleKeyEvent,this);},destroy:function(){this.deactivate();this.eventListener=null;OpenLayers.Handler.prototype.destroy.apply(this,arguments);},activate:function(){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){for(var i=0;i<this.KEY_EVENTS.length;i++){OpenLayers.Event.observe(window,this.KEY_EVENTS[i],this.eventListener);}
return true;}else{return false;}},deactivate:function(){var deactivated=false;if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){for(var i=0;i<this.KEY_EVENTS.length;i++){OpenLayers.Event.stopObserving(window,this.KEY_EVENTS[i],this.eventListener);}
deactivated=true;}
return deactivated;},handleKeyEvent:function(evt){if(this.checkModifiers(evt)){this.callback(evt.type,[evt.charCode||evt.keyCode]);}},CLASS_NAME:"OpenLayers.Handler.Keyboard"});OpenLayers.Handler.MouseWheel=OpenLayers.Class(OpenLayers.Handler,{wheelListener:null,mousePosition:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);this.wheelListener=OpenLayers.Function.bindAsEventListener(this.onWheelEvent,this);},destroy:function(){OpenLayers.Handler.prototype.destroy.apply(this,arguments);this.wheelListener=null;},onWheelEvent:function(e){if(!this.checkModifiers(e))return;var inMap=false;var elem=OpenLayers.Event.element(e);while(elem!=null){if(this.map&&elem==this.map.div){inMap=true;break;}
elem=elem.parentNode;}
if(inMap){var delta=0;if(!e){e=window.event;}
if(e.wheelDelta){delta=e.wheelDelta/120;if(window.opera){delta=-delta;}}else if(e.detail){delta=-e.detail/3;}
if(delta){if(this.mousePosition){e.xy=this.mousePosition;}
if(!e.xy){e.xy=this.map.getPixelFromLonLat(this.map.getCenter());}
if(delta<0){this.callback("down",[e,delta]);}else{this.callback("up",[e,delta]);}}
OpenLayers.Event.stop(e);}},mousemove:function(evt){this.mousePosition=evt.xy;},activate:function(evt){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){var wheelListener=this.wheelListener;OpenLayers.Event.observe(window,"DOMMouseScroll",wheelListener);OpenLayers.Event.observe(window,"mousewheel",wheelListener);OpenLayers.Event.observe(document,"mousewheel",wheelListener);return true;}else{return false;}},deactivate:function(evt){if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){var wheelListener=this.wheelListener;OpenLayers.Event.stopObserving(window,"DOMMouseScroll",wheelListener);OpenLayers.Event.stopObserving(window,"mousewheel",wheelListener);OpenLayers.Event.stopObserving(document,"mousewheel",wheelListener);return true;}else{return false;}},CLASS_NAME:"OpenLayers.Handler.MouseWheel"});OpenLayers.Layer=OpenLayers.Class({id:null,name:null,div:null,EVENT_TYPES:["loadstart","loadend","loadcancel","visibilitychanged"],events:null,map:null,isBaseLayer:false,alpha:false,displayInLayerSwitcher:true,visibility:true,attribution:null,inRange:false,imageSize:null,imageOffset:null,options:null,gutter:0,projection:null,units:null,scales:null,resolutions:null,maxExtent:null,minExtent:null,maxResolution:null,minResolution:null,numZoomLevels:null,minScale:null,maxScale:null,displayOutsideMaxExtent:false,wrapDateLine:false,initialize:function(name,options){this.addOptions(options);this.name=name;if(this.id==null){this.id=OpenLayers.Util.createUniqueID(this.CLASS_NAME+"_");this.div=OpenLayers.Util.createDiv();this.div.style.width="100%";this.div.style.height="100%";this.div.id=this.id;this.events=new OpenLayers.Events(this,this.div,this.EVENT_TYPES);}
if(this.wrapDateLine){this.displayOutsideMaxExtent=true;}},destroy:function(setNewBaseLayer){if(setNewBaseLayer==null){setNewBaseLayer=true;}
if(this.map!=null){this.map.removeLayer(this,setNewBaseLayer);}
this.map=null;this.name=null;this.div=null;this.options=null;if(this.events){this.events.destroy();}
this.events=null;},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer(this.name,this.options);}
OpenLayers.Util.applyDefaults(obj,this);obj.map=null;return obj;},setName:function(newName){if(newName!=this.name){this.name=newName;if(this.map!=null){this.map.events.triggerEvent("changelayer");}}},addOptions:function(newOptions){if(this.options==null){this.options={};}
OpenLayers.Util.extend(this.options,newOptions);OpenLayers.Util.extend(this,newOptions);},onMapResize:function(){},redraw:function(){var redrawn=false;if(this.map){this.inRange=this.calculateInRange();var extent=this.getExtent();if(extent&&this.inRange&&this.visibility){this.moveTo(extent,true,false);redrawn=true;}}
return redrawn;},moveTo:function(bounds,zoomChanged,dragging){var display=this.visibility;if(!this.isBaseLayer){display=display&&this.inRange;}
this.display(display);},setMap:function(map){if(this.map==null){this.map=map;this.maxExtent=this.maxExtent||this.map.maxExtent;this.projection=this.projection||this.map.projection;this.units=this.units||this.map.units;this.initResolutions();if(!this.isBaseLayer){this.inRange=this.calculateInRange();var show=((this.visibility)&&(this.inRange));this.div.style.display=show?"":"none";}
this.setTileSize();}},removeMap:function(map){},getImageSize:function(){return(this.imageSize||this.tileSize);},setTileSize:function(size){var tileSize=(size)?size:((this.tileSize)?this.tileSize:this.map.getTileSize());this.tileSize=tileSize;if(this.gutter){this.imageOffset=new OpenLayers.Pixel(-this.gutter,-this.gutter);this.imageSize=new OpenLayers.Size(tileSize.w+(2*this.gutter),tileSize.h+(2*this.gutter));}},getVisibility:function(){return this.visibility;},setVisibility:function(visibility,noEvent){if(visibility!=this.visibility){this.visibility=visibility;this.display(visibility);this.redraw();if(this.map!=null){this.map.events.triggerEvent("changelayer");}
if(!noEvent)
this.events.triggerEvent("visibilitychanged");}},display:function(display){if(display!=(this.div.style.display!="none")){this.div.style.display=(display)?"block":"none";}},calculateInRange:function(){var inRange=false;if(this.map){var resolution=this.map.getResolution();inRange=((resolution>=this.minResolution)&&(resolution<=this.maxResolution));}
return inRange;},setIsBaseLayer:function(isBaseLayer){if(isBaseLayer!=this.isBaseLayer){this.isBaseLayer=isBaseLayer;if(this.map!=null){this.map.events.triggerEvent("changelayer");}}},initResolutions:function(){var props=new Array('projection','units','scales','resolutions','maxScale','minScale','maxResolution','minResolution','minExtent','maxExtent','numZoomLevels','maxZoomLevel');var confProps={};for(var i=0;i<props.length;i++){var property=props[i];confProps[property]=this.options[property]||this.map[property];}
if((!confProps.numZoomLevels)&&(confProps.maxZoomLevel)){confProps.numZoomLevels=confProps.maxZoomLevel+1;}
if((confProps.scales!=null)||(confProps.resolutions!=null)){if(confProps.scales!=null){confProps.resolutions=[];for(var i=0;i<confProps.scales.length;i++){var scale=confProps.scales[i];confProps.resolutions[i]=OpenLayers.Util.getResolutionFromScale(scale,confProps.units);}}
confProps.numZoomLevels=confProps.resolutions.length;}else{confProps.resolutions=[];if(confProps.minScale){confProps.maxResolution=OpenLayers.Util.getResolutionFromScale(confProps.minScale,confProps.units);}else if(confProps.maxResolution=="auto"){var viewSize=this.map.getSize();var wRes=confProps.maxExtent.getWidth()/viewSize.w;var hRes=confProps.maxExtent.getHeight()/viewSize.h;confProps.maxResolution=Math.max(wRes,hRes);}
if(confProps.maxScale!=null){confProps.minResolution=OpenLayers.Util.getResolutionFromScale(confProps.maxScale);}else if((confProps.minResolution=="auto")&&(confProps.minExtent!=null)){var viewSize=this.map.getSize();var wRes=confProps.minExtent.getWidth()/viewSize.w;var hRes=confProps.minExtent.getHeight()/viewSize.h;confProps.minResolution=Math.max(wRes,hRes);}
if(confProps.minResolution!=null){var ratio=confProps.maxResolution/confProps.minResolution;confProps.numZoomLevels=Math.floor(Math.log(ratio)/Math.log(2))+1;}
for(var i=0;i<confProps.numZoomLevels;i++){var res=confProps.maxResolution/Math.pow(2,i)
confProps.resolutions.push(res);}}
confProps.resolutions.sort(function(a,b){return(b-a);});this.resolutions=confProps.resolutions;this.maxResolution=confProps.resolutions[0];var lastIndex=confProps.resolutions.length-1;this.minResolution=confProps.resolutions[lastIndex];this.scales=[];for(var i=0;i<confProps.resolutions.length;i++){this.scales[i]=OpenLayers.Util.getScaleFromResolution(confProps.resolutions[i],confProps.units);}
this.minScale=this.scales[0];this.maxScale=this.scales[this.scales.length-1];this.numZoomLevels=confProps.numZoomLevels;},getResolution:function(){var zoom=this.map.getZoom();return this.resolutions[zoom];},getExtent:function(){return this.map.calculateBounds();},getZoomForExtent:function(extent,closest){var viewSize=this.map.getSize();var idealResolution=Math.max(extent.getWidth()/viewSize.w,extent.getHeight()/viewSize.h);return this.getZoomForResolution(idealResolution,closest);},getDataExtent:function(){},getZoomForResolution:function(resolution,closest){var diff;var minDiff=Number.POSITIVE_INFINITY;for(var i=0;i<this.resolutions.length;i++){if(closest){diff=Math.abs(this.resolutions[i]-resolution);if(diff>minDiff){break;}
minDiff=diff;}else{if(this.resolutions[i]<resolution){break;}}}
return Math.max(0,i-1);},getLonLatFromViewPortPx:function(viewPortPx){var lonlat=null;if(viewPortPx!=null){var size=this.map.getSize();var center=this.map.getCenter();if(center){var res=this.map.getResolution();var delta_x=viewPortPx.x-(size.w/2);var delta_y=viewPortPx.y-(size.h/2);lonlat=new OpenLayers.LonLat(center.lon+delta_x*res,center.lat-delta_y*res);if(this.wrapDateLine){lonlat=lonlat.wrapDateLine(this.maxExtent);}}}
return lonlat;},getViewPortPxFromLonLat:function(lonlat){var px=null;if(lonlat!=null){var resolution=this.map.getResolution();var extent=this.map.getExtent();px=new OpenLayers.Pixel(Math.round(1/resolution*(lonlat.lon-extent.left)),Math.round(1/resolution*(extent.top-lonlat.lat)));}
return px;},setOpacity:function(opacity){if(opacity!=this.opacity){this.opacity=opacity;for(var i=0;i<this.div.childNodes.length;++i){var element=this.div.childNodes[i].firstChild;OpenLayers.Util.modifyDOMElement(element,null,null,null,null,null,null,opacity);}}},setZIndex:function(zIndex){this.div.style.zIndex=zIndex;},adjustBounds:function(bounds){if(this.gutter){var mapGutter=this.gutter*this.map.getResolution();bounds=new OpenLayers.Bounds(bounds.left-mapGutter,bounds.bottom-mapGutter,bounds.right+mapGutter,bounds.top+mapGutter);}
if(this.wrapDateLine){var wrappingOptions={'rightTolerance':this.getResolution()};bounds=bounds.wrapDateLine(this.maxExtent,wrappingOptions);}
return bounds;},CLASS_NAME:"OpenLayers.Layer"});OpenLayers.Control.DragPan=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,panned:false,draw:function(){this.handler=new OpenLayers.Handler.Drag(this,{"move":this.panMap,"done":this.panMapDone});},panMap:function(xy){this.panned=true;var deltaX=this.handler.last.x-xy.x;var deltaY=this.handler.last.y-xy.y;var size=this.map.getSize();var newXY=new OpenLayers.Pixel(size.w/2+deltaX,size.h/2+deltaY);var newCenter=this.map.getLonLatFromViewPortPx(newXY);this.map.setCenter(newCenter,null,this.handler.dragging);},panMapDone:function(xy){if(this.panned){this.panMap(xy);this.panned=false;}},CLASS_NAME:"OpenLayers.Control.DragPan"});OpenLayers.Handler.Box=OpenLayers.Class(OpenLayers.Handler,{dragHandler:null,initialize:function(control,callbacks,options){OpenLayers.Handler.prototype.initialize.apply(this,arguments);var callbacks={"down":this.startBox,"move":this.moveBox,"out":this.removeBox,"up":this.endBox};this.dragHandler=new OpenLayers.Handler.Drag(this,callbacks,{keyMask:this.keyMask});},setMap:function(map){OpenLayers.Handler.prototype.setMap.apply(this,arguments);if(this.dragHandler){this.dragHandler.setMap(map);}},startBox:function(xy){this.zoomBox=OpenLayers.Util.createDiv('zoomBox',this.dragHandler.start,null,null,"absolute","2px solid red");this.zoomBox.style.backgroundColor="white";this.zoomBox.style.filter="alpha(opacity=50)";this.zoomBox.style.opacity="0.50";this.zoomBox.style.fontSize="1px";this.zoomBox.style.zIndex=this.map.Z_INDEX_BASE["Popup"]-1;this.map.viewPortDiv.appendChild(this.zoomBox);this.map.div.style.cursor="crosshair";},moveBox:function(xy){var deltaX=Math.abs(this.dragHandler.start.x-xy.x);var deltaY=Math.abs(this.dragHandler.start.y-xy.y);this.zoomBox.style.width=Math.max(1,deltaX)+"px";this.zoomBox.style.height=Math.max(1,deltaY)+"px";if(xy.x<this.dragHandler.start.x){this.zoomBox.style.left=xy.x+"px";}
if(xy.y<this.dragHandler.start.y){this.zoomBox.style.top=xy.y+"px";}},endBox:function(end){var result;if(Math.abs(this.dragHandler.start.x-end.x)>5||Math.abs(this.dragHandler.start.y-end.y)>5){var start=this.dragHandler.start;var top=Math.min(start.y,end.y);var bottom=Math.max(start.y,end.y);var left=Math.min(start.x,end.x);var right=Math.max(start.x,end.x);result=new OpenLayers.Bounds(left,bottom,right,top);}else{result=this.dragHandler.start.clone();}
this.removeBox();this.map.div.style.cursor="";this.callback("done",[result]);},removeBox:function(){this.map.viewPortDiv.removeChild(this.zoomBox);this.zoomBox=null;},activate:function(){if(OpenLayers.Handler.prototype.activate.apply(this,arguments)){this.dragHandler.activate();return true;}else{return false;}},deactivate:function(){if(OpenLayers.Handler.prototype.deactivate.apply(this,arguments)){this.dragHandler.deactivate();return true;}else{return false;}},CLASS_NAME:"OpenLayers.Handler.Box"});OpenLayers.Layer.EventPane=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:true,isFixed:true,pane:null,mapObject:null,initialize:function(name,options){OpenLayers.Layer.prototype.initialize.apply(this,arguments);if(this.pane==null){this.pane=OpenLayers.Util.createDiv(this.div.id+"_EventPane");}},destroy:function(){this.mapObject=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},setMap:function(map){OpenLayers.Layer.prototype.setMap.apply(this,arguments);this.pane.style.zIndex=parseInt(this.div.style.zIndex)+1;this.pane.style.display=this.div.style.display;this.pane.style.width="100%";this.pane.style.height="100%";if(OpenLayers.Util.getBrowserName()=="msie"){this.pane.style.background="url("+OpenLayers.Util.getImagesLocation()+"blank.gif)";}
if(this.isFixed){this.map.viewPortDiv.appendChild(this.pane);}else{this.map.layerContainerDiv.appendChild(this.pane);}
this.loadMapObject();if(this.mapObject==null){this.loadWarningMessage();}},removeMap:function(map){if(this.pane&&this.pane.parentNode){this.pane.parentNode.removeChild(this.pane);this.pane=null;}
OpenLayers.Layer.prototype.removeMap.apply(this,arguments);},loadWarningMessage:function(){this.div.style.backgroundColor="darkblue";var viewSize=this.map.getSize();msgW=Math.min(viewSize.w,300);msgH=Math.min(viewSize.h,200);var size=new OpenLayers.Size(msgW,msgH);var centerPx=new OpenLayers.Pixel(viewSize.w/2,viewSize.h/2);var topLeft=centerPx.add(-size.w/2,-size.h/2);var div=OpenLayers.Util.createDiv(this.name+"_warning",topLeft,size,null,null,null,"auto");div.style.padding="7px";div.style.backgroundColor="yellow";div.innerHTML=this.getWarningHTML();this.div.appendChild(div);},getWarningHTML:function(){return"";},display:function(display){OpenLayers.Layer.prototype.display.apply(this,arguments);this.pane.style.display=this.div.style.display;},setZIndex:function(zIndex){OpenLayers.Layer.prototype.setZIndex.apply(this,arguments);this.pane.style.zIndex=parseInt(this.div.style.zIndex)+1;},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);if(this.mapObject!=null){var newCenter=this.map.getCenter();var newZoom=this.map.getZoom();if(newCenter!=null){var moOldCenter=this.getMapObjectCenter();var oldCenter=this.getOLLonLatFromMapObjectLonLat(moOldCenter);var moOldZoom=this.getMapObjectZoom();var oldZoom=this.getOLZoomFromMapObjectZoom(moOldZoom);if(!(newCenter.equals(oldCenter))||!(newZoom==oldZoom)){var center=this.getMapObjectLonLatFromOLLonLat(newCenter);var zoom=this.getMapObjectZoomFromOLZoom(newZoom);this.setMapObjectCenter(center,zoom);}}}},getLonLatFromViewPortPx:function(viewPortPx){var lonlat=null;if((this.mapObject!=null)&&(this.getMapObjectCenter()!=null)){var moPixel=this.getMapObjectPixelFromOLPixel(viewPortPx);var moLonLat=this.getMapObjectLonLatFromMapObjectPixel(moPixel)
lonlat=this.getOLLonLatFromMapObjectLonLat(moLonLat);}
return lonlat;},getViewPortPxFromLonLat:function(lonlat){var viewPortPx=null;if((this.mapObject!=null)&&(this.getMapObjectCenter()!=null)){var moLonLat=this.getMapObjectLonLatFromOLLonLat(lonlat);var moPixel=this.getMapObjectPixelFromMapObjectLonLat(moLonLat)
viewPortPx=this.getOLPixelFromMapObjectPixel(moPixel);}
return viewPortPx;},getOLLonLatFromMapObjectLonLat:function(moLonLat){var olLonLat=null;if(moLonLat!=null){var lon=this.getLongitudeFromMapObjectLonLat(moLonLat);var lat=this.getLatitudeFromMapObjectLonLat(moLonLat);olLonLat=new OpenLayers.LonLat(lon,lat);}
return olLonLat;},getMapObjectLonLatFromOLLonLat:function(olLonLat){var moLatLng=null;if(olLonLat!=null){moLatLng=this.getMapObjectLonLatFromLonLat(olLonLat.lon,olLonLat.lat);}
return moLatLng;},getOLPixelFromMapObjectPixel:function(moPixel){var olPixel=null;if(moPixel!=null){var x=this.getXFromMapObjectPixel(moPixel);var y=this.getYFromMapObjectPixel(moPixel);olPixel=new OpenLayers.Pixel(x,y);}
return olPixel;},getMapObjectPixelFromOLPixel:function(olPixel){var moPixel=null;if(olPixel!=null){moPixel=this.getMapObjectPixelFromXY(olPixel.x,olPixel.y);}
return moPixel;},CLASS_NAME:"OpenLayers.Layer.EventPane"});OpenLayers.Layer.FixedZoomLevels=OpenLayers.Class({initialize:function(){},initResolutions:function(){var props=new Array('minZoomLevel','maxZoomLevel','numZoomLevels');for(var i=0;i<props.length;i++){var property=props[i];this[property]=(this.options[property]!=null)?this.options[property]:this.map[property];}
if(this.minZoomLevel==null||(this.minZoomLevel<this.MIN_ZOOM_LEVEL)){this.minZoomLevel=this.MIN_ZOOM_LEVEL;}
var limitZoomLevels=this.MAX_ZOOM_LEVEL-this.minZoomLevel+1;if(this.numZoomLevels!=null){this.numZoomLevels=Math.min(this.numZoomLevels,limitZoomLevels);}
else{if(this.maxZoomLevel!=null){var zoomDiff=this.maxZoomLevel-this.minZoomLevel+1;this.numZoomLevels=Math.min(zoomDiff,limitZoomLevels);}else{this.numZoomLevels=limitZoomLevels;}}
this.maxZoomLevel=this.minZoomLevel+this.numZoomLevels-1;if(this.RESOLUTIONS!=null){var resolutionsIndex=0;this.resolutions=[];for(var i=this.minZoomLevel;i<this.numZoomLevels;i++){this.resolutions[resolutionsIndex++]=this.RESOLUTIONS[i];}}},getResolution:function(){if(this.resolutions!=null){return OpenLayers.Layer.prototype.getResolution.apply(this,arguments);}else{var resolution=null;var viewSize=this.map.getSize();var extent=this.getExtent();if((viewSize!=null)&&(extent!=null)){resolution=Math.max(extent.getWidth()/viewSize.w,extent.getHeight()/viewSize.h);}
return resolution;}},getExtent:function(){var extent=null;var size=this.map.getSize();var tlPx=new OpenLayers.Pixel(0,0);var tlLL=this.getLonLatFromViewPortPx(tlPx);var brPx=new OpenLayers.Pixel(size.w,size.h);var brLL=this.getLonLatFromViewPortPx(brPx);if((tlLL!=null)&&(brLL!=null)){extent=new OpenLayers.Bounds(tlLL.lon,brLL.lat,brLL.lon,tlLL.lat);}
return extent;},getZoomForResolution:function(resolution){if(this.resolutions!=null){return OpenLayers.Layer.prototype.getZoomForResolution.apply(this,arguments);}else{var extent=OpenLayers.Layer.prototype.getExtent.apply(this,[resolution]);return this.getZoomForExtent(extent);}},getOLZoomFromMapObjectZoom:function(moZoom){var zoom=null;if(moZoom!=null){zoom=moZoom-this.minZoomLevel;}
return zoom;},getMapObjectZoomFromOLZoom:function(olZoom){var zoom=null;if(olZoom!=null){zoom=olZoom+this.minZoomLevel;}
return zoom;},CLASS_NAME:"FixedZoomLevels.js"});OpenLayers.Layer.HTTPRequest=OpenLayers.Class(OpenLayers.Layer,{URL_HASH_FACTOR:(Math.sqrt(5)-1)/2,url:null,params:null,reproject:false,initialize:function(name,url,params,options){var newArguments=arguments;newArguments=[name,options];OpenLayers.Layer.prototype.initialize.apply(this,newArguments);this.url=url;this.params=OpenLayers.Util.extend({},params);},destroy:function(){this.url=null;this.params=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.HTTPRequest(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.prototype.clone.apply(this,[obj]);return obj;},setUrl:function(newUrl){this.url=newUrl;},mergeNewParams:function(newParams){this.params=OpenLayers.Util.extend(this.params,newParams);this.redraw();},selectUrl:function(paramString,urls){var product=1;for(var i=0;i<paramString.length;i++){product*=paramString.charCodeAt(i)*this.URL_HASH_FACTOR;product-=Math.floor(product);}
return urls[Math.floor(product*urls.length)];},getFullRequestString:function(newParams,altUrl){var url=altUrl||this.url;var allParams=OpenLayers.Util.extend({},this.params);allParams=OpenLayers.Util.extend(allParams,newParams);var paramsString=OpenLayers.Util.getParameterString(allParams);if(url instanceof Array){url=this.selectUrl(paramsString,url);}
var urlParams=OpenLayers.Util.upperCaseObject(OpenLayers.Util.getParameters(url));for(var key in allParams){if(key.toUpperCase()in urlParams){delete allParams[key];}}
paramsString=OpenLayers.Util.getParameterString(allParams);var requestString=url;if(paramsString!=""){var lastServerChar=url.charAt(url.length-1);if((lastServerChar=="&")||(lastServerChar=="?")){requestString+=paramsString;}else{if(url.indexOf('?')==-1){requestString+='?'+paramsString;}else{requestString+='&'+paramsString;}}}
return requestString;},CLASS_NAME:"OpenLayers.Layer.HTTPRequest"});OpenLayers.Layer.Image=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:true,url:null,extent:null,size:null,tile:null,aspectRatio:null,initialize:function(name,url,extent,size,options){this.url=url;this.extent=extent;this.size=size;OpenLayers.Layer.prototype.initialize.apply(this,[name,options]);this.aspectRatio=(this.extent.getHeight()/this.size.h)/(this.extent.getWidth()/this.size.w);},destroy:function(){if(this.tile){this.tile.destroy();this.tile=null;}
OpenLayers.Layer.prototype.destroy.apply(this,arguments);},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.Image(this.name,this.url,this.extent,this.size,this.options);}
obj=OpenLayers.Layer.prototype.clone.apply(this,[obj]);return obj;},setMap:function(map){if(this.options.maxResolution==null){this.options.maxResolution=this.aspectRatio*this.extent.getWidth()/this.size.w;}
OpenLayers.Layer.prototype.setMap.apply(this,arguments);},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);var firstRendering=(this.tile==null);if(zoomChanged||firstRendering){this.setTileSize();var ul=new OpenLayers.LonLat(this.extent.left,this.extent.top);var ulPx=this.map.getLayerPxFromLonLat(ul);if(firstRendering){this.tile=new OpenLayers.Tile.Image(this,ulPx,this.extent,null,this.tileSize);}else{this.tile.size=this.tileSize.clone();this.tile.position=ulPx.clone();}
this.tile.draw();}},setTileSize:function(){var tileWidth=this.extent.getWidth()/this.map.getResolution();var tileHeight=this.extent.getHeight()/this.map.getResolution();this.tileSize=new OpenLayers.Size(tileWidth,tileHeight);},setUrl:function(newUrl){this.url=newUrl;this.tile.draw();},getURL:function(bounds){return this.url;},CLASS_NAME:"OpenLayers.Layer.Image"});OpenLayers.Layer.Markers=OpenLayers.Class(OpenLayers.Layer,{isBaseLayer:false,markers:null,drawn:false,initialize:function(name,options){OpenLayers.Layer.prototype.initialize.apply(this,arguments);this.markers=[];},destroy:function(){this.clearMarkers();this.markers=null;OpenLayers.Layer.prototype.destroy.apply(this,arguments);},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.prototype.moveTo.apply(this,arguments);if(zoomChanged||!this.drawn){for(i=0;i<this.markers.length;i++){this.drawMarker(this.markers[i]);}
this.drawn=true;}},addMarker:function(marker){this.markers.push(marker);if(this.map&&this.map.getExtent()){marker.map=this.map;this.drawMarker(marker);}},removeMarker:function(marker){OpenLayers.Util.removeItem(this.markers,marker);if((marker.icon!=null)&&(marker.icon.imageDiv!=null)&&(marker.icon.imageDiv.parentNode==this.div)){this.div.removeChild(marker.icon.imageDiv);marker.drawn=false;}},clearMarkers:function(){if(this.markers!=null){while(this.markers.length>0){this.removeMarker(this.markers[0]);}}},drawMarker:function(marker){var px=this.map.getLayerPxFromLonLat(marker.lonlat);if(px==null){marker.display(false);}else{var markerImg=marker.draw(px);if(!marker.drawn){this.div.appendChild(markerImg);marker.drawn=true;}}},getDataExtent:function(){var maxExtent=null;if(this.markers&&(this.markers.length>0)){var maxExtent=new OpenLayers.Bounds();for(var i=0;i<this.markers.length;i++){var marker=this.markers[i];maxExtent.extend(marker.lonlat);}}
return maxExtent;},CLASS_NAME:"OpenLayers.Layer.Markers"});OpenLayers.Control.ZoomBox=OpenLayers.Class(OpenLayers.Control,{type:OpenLayers.Control.TYPE_TOOL,draw:function(){this.handler=new OpenLayers.Handler.Box(this,{done:this.zoomBox},{keyMask:this.keyMask});},zoomBox:function(position){if(position instanceof OpenLayers.Bounds){var minXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.left,position.bottom));var maxXY=this.map.getLonLatFromPixel(new OpenLayers.Pixel(position.right,position.top));var bounds=new OpenLayers.Bounds(minXY.lon,minXY.lat,maxXY.lon,maxXY.lat);this.map.zoomToExtent(bounds);}else{this.map.setCenter(this.map.getLonLatFromPixel(position),this.map.getZoom()+1);}},CLASS_NAME:"OpenLayers.Control.ZoomBox"});OpenLayers.Layer.Grid=OpenLayers.Class(OpenLayers.Layer.HTTPRequest,{tileSize:null,grid:null,singleTile:false,ratio:1.5,buffer:2,numLoadingTiles:0,initialize:function(name,url,params,options){OpenLayers.Layer.HTTPRequest.prototype.initialize.apply(this,arguments);this.events.addEventType("tileloaded");this.grid=[];},destroy:function(){this.clearGrid();this.grid=null;this.tileSize=null;OpenLayers.Layer.HTTPRequest.prototype.destroy.apply(this,arguments);},clearGrid:function(){if(this.grid){for(var iRow=0;iRow<this.grid.length;iRow++){var row=this.grid[iRow];for(var iCol=0;iCol<row.length;iCol++){var tile=row[iCol];this.removeTileMonitoringHooks(tile);tile.destroy();}}
this.grid=[];}},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.Grid(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.HTTPRequest.prototype.clone.apply(this,[obj]);if(this.tileSize!=null){obj.tileSize=this.tileSize.clone();}
obj.grid=[];return obj;},moveTo:function(bounds,zoomChanged,dragging){OpenLayers.Layer.HTTPRequest.prototype.moveTo.apply(this,arguments);bounds=bounds||this.map.getExtent();if(bounds!=null){var forceReTile=!this.grid.length||zoomChanged;var tilesBounds=this.getTilesBounds();if(this.singleTile){if(forceReTile||(!dragging&&!tilesBounds.containsBounds(bounds))){this.initSingleTile(bounds);}}else{if(forceReTile||!tilesBounds.containsBounds(bounds,true)){this.initGriddedTiles(bounds);}else{this.moveGriddedTiles(bounds);}}}},setTileSize:function(size){if(this.singleTile){var size=this.map.getSize().clone();size.h=parseInt(size.h*this.ratio);size.w=parseInt(size.w*this.ratio);}
OpenLayers.Layer.HTTPRequest.prototype.setTileSize.apply(this,[size]);},getGridBounds:function(){var msg="The getGridBounds() function is deprecated. It will be "+"removed in 3.0. Please use getTilesBounds() instead.";OpenLayers.Console.warn(msg);return this.getTilesBounds();},getTilesBounds:function(){var bounds=null;if(this.grid.length){var bottom=this.grid.length-1;var bottomLeftTile=this.grid[bottom][0];var right=this.grid[0].length-1;var topRightTile=this.grid[0][right];bounds=new OpenLayers.Bounds(bottomLeftTile.bounds.left,bottomLeftTile.bounds.bottom,topRightTile.bounds.right,topRightTile.bounds.top);}
return bounds;},initSingleTile:function(bounds){var center=bounds.getCenterLonLat();var tileWidth=bounds.getWidth()*this.ratio;var tileHeight=bounds.getHeight()*this.ratio;var tileBounds=new OpenLayers.Bounds(center.lon-(tileWidth/2),center.lat-(tileHeight/2),center.lon+(tileWidth/2),center.lat+(tileHeight/2));var ul=new OpenLayers.LonLat(tileBounds.left,tileBounds.top);var px=this.map.getLayerPxFromLonLat(ul);if(!this.grid.length){this.grid[0]=[];}
var tile=this.grid[0][0];if(!tile){tile=this.addTile(tileBounds,px);this.addTileMonitoringHooks(tile);tile.draw();this.grid[0][0]=tile;}else{tile.moveTo(tileBounds,px);}
this.removeExcessTiles(1,1);},initGriddedTiles:function(bounds){var viewSize=this.map.getSize();var minRows=Math.ceil(viewSize.h/this.tileSize.h)+
Math.max(1,2*this.buffer);var minCols=Math.ceil(viewSize.w/this.tileSize.w)+
Math.max(1,2*this.buffer);var extent=this.map.getMaxExtent();var resolution=this.map.getResolution();var tilelon=resolution*this.tileSize.w;var tilelat=resolution*this.tileSize.h;var offsetlon=bounds.left-extent.left;var tilecol=Math.floor(offsetlon/tilelon)-this.buffer;var tilecolremain=offsetlon/tilelon-tilecol;var tileoffsetx=-tilecolremain*this.tileSize.w;var tileoffsetlon=extent.left+tilecol*tilelon;var offsetlat=bounds.top-(extent.bottom+tilelat);var tilerow=Math.ceil(offsetlat/tilelat)+this.buffer;var tilerowremain=tilerow-offsetlat/tilelat;var tileoffsety=-tilerowremain*this.tileSize.h;var tileoffsetlat=extent.bottom+tilerow*tilelat;tileoffsetx=Math.round(tileoffsetx);tileoffsety=Math.round(tileoffsety);this.origin=new OpenLayers.Pixel(tileoffsetx,tileoffsety);var startX=tileoffsetx;var startLon=tileoffsetlon;var rowidx=0;do{var row=this.grid[rowidx++];if(!row){row=[];this.grid.push(row);}
tileoffsetlon=startLon;tileoffsetx=startX;var colidx=0;do{var tileBounds=new OpenLayers.Bounds(tileoffsetlon,tileoffsetlat,tileoffsetlon+tilelon,tileoffsetlat+tilelat);var x=tileoffsetx;x-=parseInt(this.map.layerContainerDiv.style.left);var y=tileoffsety;y-=parseInt(this.map.layerContainerDiv.style.top);var px=new OpenLayers.Pixel(x,y);var tile=row[colidx++];if(!tile){tile=this.addTile(tileBounds,px);this.addTileMonitoringHooks(tile);row.push(tile);}else{tile.moveTo(tileBounds,px,false);}
tileoffsetlon+=tilelon;tileoffsetx+=this.tileSize.w;}while((tileoffsetlon<=bounds.right+tilelon*this.buffer)||colidx<minCols)
tileoffsetlat-=tilelat;tileoffsety+=this.tileSize.h;}while((tileoffsetlat>=bounds.bottom-tilelat*this.buffer)||rowidx<minRows)
this.removeExcessTiles(rowidx,colidx);this.spiralTileLoad();},spiralTileLoad:function(){var tileQueue=[];var directions=["right","down","left","up"];var iRow=0;var iCell=-1;var direction=OpenLayers.Util.indexOf(directions,"right");var directionsTried=0;while(directionsTried<directions.length){var testRow=iRow;var testCell=iCell;switch(directions[direction]){case"right":testCell++;break;case"down":testRow++;break;case"left":testCell--;break;case"up":testRow--;break;}
var tile=null;if((testRow<this.grid.length)&&(testRow>=0)&&(testCell<this.grid[0].length)&&(testCell>=0)){tile=this.grid[testRow][testCell];}
if((tile!=null)&&(!tile.queued)){tileQueue.unshift(tile);tile.queued=true;directionsTried=0;iRow=testRow;iCell=testCell;}else{direction=(direction+1)%4;directionsTried++;}}
for(var i=0;i<tileQueue.length;i++){var tile=tileQueue[i]
tile.draw();tile.queued=false;}},addTile:function(bounds,position){},addTileMonitoringHooks:function(tile){tile.onLoadStart=function(){if(this.numLoadingTiles==0){this.events.triggerEvent("loadstart");}
this.numLoadingTiles++;};tile.events.register("loadstart",this,tile.onLoadStart);tile.onLoadEnd=function(){this.numLoadingTiles--;this.events.triggerEvent("tileloaded");if(this.numLoadingTiles==0){this.events.triggerEvent("loadend");}};tile.events.register("loadend",this,tile.onLoadEnd);},removeTileMonitoringHooks:function(tile){tile.events.unregister("loadstart",this,tile.onLoadStart);tile.events.unregister("loadend",this,tile.onLoadEnd);},moveGriddedTiles:function(bounds){var buffer=this.buffer||1;while(true){var tlLayer=this.grid[0][0].position;var tlViewPort=this.map.getViewPortPxFromLayerPx(tlLayer);if(tlViewPort.x>-this.tileSize.w*(buffer-1)){this.shiftColumn(true);}else if(tlViewPort.x<-this.tileSize.w*buffer){this.shiftColumn(false);}else if(tlViewPort.y>-this.tileSize.h*(buffer-1)){this.shiftRow(true);}else if(tlViewPort.y<-this.tileSize.h*buffer){this.shiftRow(false);}else{break;}};if(this.buffer==0){for(var r=0,rl=this.grid.length;r<rl;r++){var row=this.grid[r];for(var c=0,cl=row.length;c<cl;c++){var tile=row[c];if(!tile.drawn&&tile.bounds.intersectsBounds(bounds,false)){tile.draw();}}}}},shiftRow:function(prepend){var modelRowIndex=(prepend)?0:(this.grid.length-1);var modelRow=this.grid[modelRowIndex];var resolution=this.map.getResolution();var deltaY=(prepend)?-this.tileSize.h:this.tileSize.h;var deltaLat=resolution*-deltaY;var row=(prepend)?this.grid.pop():this.grid.shift();for(var i=0;i<modelRow.length;i++){var modelTile=modelRow[i];var bounds=modelTile.bounds.clone();var position=modelTile.position.clone();bounds.bottom=bounds.bottom+deltaLat;bounds.top=bounds.top+deltaLat;position.y=position.y+deltaY;row[i].moveTo(bounds,position);}
if(prepend){this.grid.unshift(row);}else{this.grid.push(row);}},shiftColumn:function(prepend){var deltaX=(prepend)?-this.tileSize.w:this.tileSize.w;var resolution=this.map.getResolution();var deltaLon=resolution*deltaX;for(var i=0;i<this.grid.length;i++){var row=this.grid[i];var modelTileIndex=(prepend)?0:(row.length-1);var modelTile=row[modelTileIndex];var bounds=modelTile.bounds.clone();var position=modelTile.position.clone();bounds.left=bounds.left+deltaLon;bounds.right=bounds.right+deltaLon;position.x=position.x+deltaX;var tile=prepend?this.grid[i].pop():this.grid[i].shift()
tile.moveTo(bounds,position);if(prepend){this.grid[i].unshift(tile);}else{this.grid[i].push(tile);}}},removeExcessTiles:function(rows,columns){while(this.grid.length>rows){var row=this.grid.pop();for(var i=0,l=row.length;i<l;i++){var tile=row[i];this.removeTileMonitoringHooks(tile)
tile.destroy();}}
while(this.grid[0].length>columns){for(var i=0,l=this.grid.length;i<l;i++){var row=this.grid[i];var tile=row.pop();this.removeTileMonitoringHooks(tile);tile.destroy();}}},onMapResize:function(){if(this.singleTile){this.clearGrid();this.setTileSize();this.initSingleTile(this.map.getExtent());}},getTileBounds:function(viewPortPx){var maxExtent=this.map.getMaxExtent();var resolution=this.getResolution();var tileMapWidth=resolution*this.tileSize.w;var tileMapHeight=resolution*this.tileSize.h;var mapPoint=this.getLonLatFromViewPortPx(viewPortPx);var tileLeft=maxExtent.left+(tileMapWidth*Math.floor((mapPoint.lon-
maxExtent.left)/tileMapWidth));var tileBottom=maxExtent.bottom+(tileMapHeight*Math.floor((mapPoint.lat-
maxExtent.bottom)/tileMapHeight));return new OpenLayers.Bounds(tileLeft,tileBottom,tileLeft+tileMapWidth,tileBottom+tileMapHeight);},CLASS_NAME:"OpenLayers.Layer.Grid"});OpenLayers.Control.Navigation=OpenLayers.Class(OpenLayers.Control,{dragPan:null,zoomBox:null,wheelHandler:null,initialize:function(options){OpenLayers.Control.prototype.initialize.apply(this,arguments);},activate:function(){this.dragPan.activate();this.wheelHandler.activate();this.zoomBox.activate();return OpenLayers.Control.prototype.activate.apply(this,arguments);},deactivate:function(){this.zoomBox.deactivate();this.dragPan.deactivate();this.wheelHandler.deactivate();return OpenLayers.Control.prototype.deactivate.apply(this,arguments);},draw:function(){this.map.events.register("dblclick",this,this.defaultDblClick);this.dragPan=new OpenLayers.Control.DragPan({map:this.map});this.zoomBox=new OpenLayers.Control.ZoomBox({map:this.map,keyMask:OpenLayers.Handler.MOD_SHIFT});this.dragPan.draw();this.zoomBox.draw();this.wheelHandler=new OpenLayers.Handler.MouseWheel(this,{"up":this.wheelUp,"down":this.wheelDown});this.activate();},defaultDblClick:function(evt){var newCenter=this.map.getLonLatFromViewPortPx(evt.xy);this.map.setCenter(newCenter,this.map.zoom+1);OpenLayers.Event.stop(evt);return false;},wheelChange:function(evt,deltaZ){var newZoom=this.map.getZoom()+deltaZ;if(!this.map.isValidZoomLevel(newZoom))return;var size=this.map.getSize();var deltaX=size.w/2-evt.xy.x;var deltaY=evt.xy.y-size.h/2;var newRes=this.map.baseLayer.resolutions[newZoom];var zoomPoint=this.map.getLonLatFromPixel(evt.xy);var newCenter=new OpenLayers.LonLat(zoomPoint.lon+deltaX*newRes,zoomPoint.lat+deltaY*newRes);this.map.setCenter(newCenter,newZoom);},wheelUp:function(evt){this.wheelChange(evt,1);},wheelDown:function(evt){this.wheelChange(evt,-1);},CLASS_NAME:"OpenLayers.Control.Navigation"});OpenLayers.Layer.KaMap=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,units:null,resolution:OpenLayers.DOTS_PER_INCH,DEFAULT_PARAMS:{i:'jpeg',map:''},initialize:function(name,url,params,options){var newArguments=[];newArguments.push(name,url,params,options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);this.params=(params?params:{});if(params){OpenLayers.Util.applyDefaults(this.params,this.DEFAULT_PARAMS);}},getURL:function(bounds){bounds=this.adjustBounds(bounds);var mapRes=this.map.getResolution();var scale=Math.round((this.map.getScale()*10000))/10000;var pX=Math.round(bounds.left/mapRes);var pY=-Math.round(bounds.top/mapRes);return this.getFullRequestString({t:pY,l:pX,s:scale});},addTile:function(bounds,position){var url=this.getURL(bounds);return new OpenLayers.Tile.Image(this,position,bounds,url,this.tileSize);},initGriddedTiles:function(bounds){var viewSize=this.map.getSize();var minRows=Math.ceil(viewSize.h/this.tileSize.h)+Math.max(1,2*this.buffer);var minCols=Math.ceil(viewSize.w/this.tileSize.w)+Math.max(1,2*this.buffer);var extent=this.map.getMaxExtent();var resolution=this.map.getResolution();var tilelon=resolution*this.tileSize.w;var tilelat=resolution*this.tileSize.h;var offsetlon=bounds.left;var tilecol=Math.floor(offsetlon/tilelon)-this.buffer;var tilecolremain=offsetlon/tilelon-tilecol;var tileoffsetx=-tilecolremain*this.tileSize.w;var tileoffsetlon=tilecol*tilelon;var offsetlat=bounds.top;var tilerow=Math.ceil(offsetlat/tilelat)+this.buffer;var tilerowremain=tilerow-offsetlat/tilelat;var tileoffsety=-(tilerowremain+1)*this.tileSize.h;var tileoffsetlat=tilerow*tilelat;tileoffsetx=Math.round(tileoffsetx);tileoffsety=Math.round(tileoffsety);this.origin=new OpenLayers.Pixel(tileoffsetx,tileoffsety);var startX=tileoffsetx;var startLon=tileoffsetlon;var rowidx=0;do{var row=this.grid[rowidx++];if(!row){row=[];this.grid.push(row);}
tileoffsetlon=startLon;tileoffsetx=startX;var colidx=0;do{var tileBounds=new OpenLayers.Bounds(tileoffsetlon,tileoffsetlat,tileoffsetlon+tilelon,tileoffsetlat+tilelat);var x=tileoffsetx;x-=parseInt(this.map.layerContainerDiv.style.left);var y=tileoffsety;y-=parseInt(this.map.layerContainerDiv.style.top);var px=new OpenLayers.Pixel(x,y);var tile=row[colidx++];if(!tile){tile=this.addTile(tileBounds,px);this.addTileMonitoringHooks(tile);row.push(tile);}else{tile.moveTo(tileBounds,px,false);}
tileoffsetlon+=tilelon;tileoffsetx+=this.tileSize.w;}while(tileoffsetlon<=bounds.right+tilelon*this.buffer||colidx<minCols)
tileoffsetlat-=tilelat;tileoffsety+=this.tileSize.h;}while(tileoffsetlat>=bounds.bottom-tilelat*this.buffer||rowidx<minRows)
this.removeExcessTiles(rowidx,colidx);this.spiralTileLoad();},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.KaMap(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);if(this.tileSize!=null){obj.tileSize=this.tileSize.clone();}
obj.grid=[];return obj;},getTileBounds:function(viewPortPx){var resolution=this.getResolution();var tileMapWidth=resolution*this.tileSize.w;var tileMapHeight=resolution*this.tileSize.h;var mapPoint=this.getLonLatFromViewPortPx(viewPortPx);var tileLeft=tileMapWidth*Math.floor(mapPoint.lon/tileMapWidth);var tileBottom=tileMapHeight*Math.floor(mapPoint.lat/tileMapHeight);return new OpenLayers.Bounds(tileLeft,tileBottom,tileLeft+tileMapWidth,tileBottom+tileMapHeight);},CLASS_NAME:"OpenLayers.Layer.KaMap"});OpenLayers.Layer.KaMapTileCache=OpenLayers.Class(OpenLayers.Layer.Grid,{isBaseLayer:true,units:null,resolution:OpenLayers.DOTS_PER_INCH,DEFAULT_PARAMS:{i:'jpeg',map:''},initialize:function(name,url,params,options){var newArguments=[];newArguments.push(name,url,{},options);OpenLayers.Layer.Grid.prototype.initialize.apply(this,newArguments);this.params=(params?params:{});if(params){OpenLayers.Util.applyDefaults(this.params,this.DEFAULT_PARAMS);}},getURL:function(bounds){var mapRes=this.map.getResolution();var scale=Math.round((this.map.getScale()*10000))/10000;var pX=Math.round(bounds.left/mapRes);var pY=-Math.round(bounds.top/mapRes);var metaTop=Math.floor(pX/(this.params.tileHeight*this.params.metatileHeight))*this.params.tileWidth*this.params.metatileWidth;var metaLeft=Math.floor(pY/(this.params.tileWidth*this.params.metatileWidth))*this.params.tileWidth*this.params.metatileWidth;pX=Math.floor(pX/this.params.tileWidth)*this.params.tileWidth;pY=Math.floor(pY/this.params.tileHeight)*this.params.tileHeight;var components=[this.params.map,scale,this.params.g,"def","t"+metaLeft,"l"+metaTop,"t"+pY+"l"+pX+"."+this.params.i];var path=components.join('/');var url=this.url;if(url instanceof Array){url=this.selectUrl(path,url);}
url=(url.charAt(url.length-1)=='/')?url:url+'/';return url+path;},addTile:function(bounds,position){var url=this.getURL(bounds);return new OpenLayers.Tile.Image(this,position,bounds,url,this.tileSize);},initGriddedTiles:function(bounds){var viewSize=this.map.getSize();var minRows=Math.ceil(viewSize.h/this.tileSize.h)+Math.max(1,2*this.buffer);var minCols=Math.ceil(viewSize.w/this.tileSize.w)+Math.max(1,2*this.buffer);var extent=this.map.getMaxExtent();var resolution=this.map.getResolution();var tilelon=resolution*this.tileSize.w;var tilelat=resolution*this.tileSize.h;var offsetlon=bounds.left;var tilecol=Math.floor(offsetlon/tilelon)-this.buffer;var tilecolremain=offsetlon/tilelon-tilecol;var tileoffsetx=-tilecolremain*this.tileSize.w;var tileoffsetlon=tilecol*tilelon;var offsetlat=bounds.top;var tilerow=Math.ceil(offsetlat/tilelat)+this.buffer;var tilerowremain=tilerow-offsetlat/tilelat;var tileoffsety=-(tilerowremain+1)*this.tileSize.h;var tileoffsetlat=tilerow*tilelat;tileoffsetx=Math.round(tileoffsetx);tileoffsety=Math.round(tileoffsety);this.origin=new OpenLayers.Pixel(tileoffsetx,tileoffsety);var startX=tileoffsetx;var startLon=tileoffsetlon;var rowidx=0;do{var row=this.grid[rowidx++];if(!row){row=[];this.grid.push(row);}
tileoffsetlon=startLon;tileoffsetx=startX;var colidx=0;do{var tileBounds=new OpenLayers.Bounds(tileoffsetlon,tileoffsetlat,tileoffsetlon+tilelon,tileoffsetlat+tilelat);var x=tileoffsetx;x-=parseInt(this.map.layerContainerDiv.style.left);var y=tileoffsety;y-=parseInt(this.map.layerContainerDiv.style.top);var px=new OpenLayers.Pixel(x,y);var tile=row[colidx++];if(!tile){tile=this.addTile(tileBounds,px);this.addTileMonitoringHooks(tile);row.push(tile);}else{tile.moveTo(tileBounds,px,false);}
tileoffsetlon+=tilelon;tileoffsetx+=this.tileSize.w;}while(tileoffsetlon<=bounds.right+tilelon*this.buffer||colidx<minCols)
tileoffsetlat-=tilelat;tileoffsety+=this.tileSize.h;}while(tileoffsetlat>=bounds.bottom-tilelat*this.buffer||rowidx<minRows)
this.removeExcessTiles(rowidx,colidx);this.spiralTileLoad();},clone:function(obj){if(obj==null){obj=new OpenLayers.Layer.KaMapTileCache(this.name,this.url,this.params,this.options);}
obj=OpenLayers.Layer.Grid.prototype.clone.apply(this,[obj]);if(this.tileSize!=null){obj.tileSize=this.tileSize.clone();}
obj.grid=[];return obj;},getTileBounds:function(viewPortPx){var resolution=this.getResolution();var tileMapWidth=resolution*this.tileSize.w;var tileMapHeight=resolution*this.tileSize.h;var mapPoint=this.getLonLatFromViewPortPx(viewPortPx);var tileLeft=tileMapWidth*Math.floor(mapPoint.lon/tileMapWidth);var tileBottom=tileMapHeight*Math.floor(mapPoint.lat/tileMapHeight);return new OpenLayers.Bounds(tileLeft,tileBottom,tileLeft+tileMapWidth,tileBottom+tileMapHeight);},CLASS_NAME:"OpenLayers.Layer.KaMapTileCache"});window.dhtmlHistory={initialize:function(){if(this.isIE){if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.fireOnNewListener=false;this.firstLoad=true;historyStorage.put(this.PAGELOADEDSTRING,true);}
else{this.fireOnNewListener=true;this.firstLoad=false;}}},addListener:function(listener){this.listener=listener;if(this.fireOnNewListener){this.fireHistoryEvent(this.currentLocation);this.fireOnNewListener=false;}},add:function(newLocation,historyData){if(this.isSafari){newLocation=this.removeHash(newLocation);historyStorage.put(newLocation,historyData);this.currentLocation=newLocation;window.location.hash=newLocation;this.putSafariState(newLocation);}else{var that=this;var addImpl=function(){if(that.currentWaitTime>0){that.currentWaitTime=that.currentWaitTime-that.WAIT_TIME;}
newLocation=that.removeHash(newLocation);if(document.getElementById(newLocation)){var e="Exception: History locations can not have the same value as _any_ IDs that might be in the document,"
+" due to a bug in IE; please ask the developer to choose a history location that does not match any HTML"
+" IDs in this document. The following ID is already taken and cannot be a location: "+newLocation;throw e;}
historyStorage.put(newLocation,historyData);that.ignoreLocationChange=true;that.ieAtomicLocationChange=true;that.currentLocation=newLocation;window.location.hash=newLocation;if(that.isIE){that.iframe.src="blank.html?"+newLocation;}
that.ieAtomicLocationChange=false;};window.setTimeout(addImpl,this.currentWaitTime);this.currentWaitTime=this.currentWaitTime+this.WAIT_TIME;}},isFirstLoad:function(){return this.firstLoad;},getVersion:function(){return"0.5";},getCurrentLocation:function(){if(this.isSafari){var currentLocation=this.getSafariState();}
else{var currentLocation=this.removeHash(window.location.hash);}
return currentLocation;},fireDebugMode:function(){var debugStyle={left:'auto',right:'auto',width:'800px',height:'100px',border:'1px solid black',position:'static'};for(var key in debugStyle){var val=debugStyle[key];if(typeof val=='string'){historyStorage.storageField.style[key]=val;if(this.isIE){this.iframe.style[key]=debugStyle[key];}
else if(this.isSafari){val=(key=='height'?'30px':val);this.safariStack.style[key]=val;}}}},PAGELOADEDSTRING:"DhtmlHistory_pageLoaded",WAIT_TIME:200,debugging:false,isIE:(document.all&&navigator.userAgent.toLowerCase().indexOf('msie')!=-1),isOpera:(navigator.userAgent.toLowerCase().indexOf('opera')!=-1),isSafari:(navigator.userAgent.toLowerCase().indexOf('safari')!=-1),listener:null,pollHandle:null,currentWaitTime:0,currentLocation:null,iframe:null,safariHistoryStartPoint:null,safariStack:null,ignoreLocationChange:null,fireOnNewListener:null,firstLoad:null,ieAtomicLocationChange:null,createIE:function(initialHash){if(this.isIE){this.WAIT_TIME=400;var rshIframeID="rshIDHistoryFrame";var rshIframeHTML='<iframe name="'+rshIframeID+'" id="'+rshIframeID+'" style="'+historyStorage.invisibilityStyles
+'" src="blank.html?'+initialHash+'"></iframe>';document.write(rshIframeHTML);this.iframe=document.getElementById(rshIframeID);}},createOpera:function(){if(this.isOpera){var imgHTML='<img src="javascript:location.href=\'javascript:dhtmlHistory.checkLocation();\';" style="visibility:hidden" />';document.write(imgHTML);}},createSafari:function(){if(this.isSafari){this.WAIT_TIME=400;this.safariHistoryStartPoint=history.length;var stackID="rshSafariStack";var stackHTML='<input type="text" style="'+historyStorage.invisibilityStyles+'" id="'+stackID+'" value="[]"/>';document.write(stackHTML);this.safariStack=document.getElementById(stackID);}},getSafariStack:function(){var r=this.safariStack.value;return historyStorage.parseJSON(r);},getSafariState:function(){var stack=this.getSafariStack();return stack[history.length-this.safariHistoryStartPoint-1];},putSafariState:function(newLocation){var stack=this.getSafariStack();stack[history.length-this.safariHistoryStartPoint]=newLocation;this.safariStack.value=historyStorage.toJSONString(stack);},create:function(){this.createSafari();this.createOpera();var initialHash=this.getCurrentLocation();this.currentLocation=initialHash;this.createIE(initialHash);var that=this;window.onunload=function(){that.firstLoad=null;};if(this.isIE){this.ignoreLocationChange=true;}else{if(!historyStorage.hasKey(this.PAGELOADEDSTRING)){this.ignoreLocationChange=true;this.firstLoad=true;historyStorage.put(this.PAGELOADEDSTRING,true);}else{this.ignoreLocationChange=false;this.fireOnNewListener=true;}}
var that=this;var locationHandler=function(){that.checkLocation();};this.pollHandle=setInterval(locationHandler,100);},fireHistoryEvent:function(newHash){var historyData=historyStorage.get(newHash);this.listener.call(null,newHash,historyData);},checkLocation:function(){if(!this.isIE&&this.ignoreLocationChange){this.ignoreLocationChange=false;return;}
if(!this.isIE&&this.ieAtomicLocationChange){return;}
var hash=this.getCurrentLocation();if(hash==this.currentLocation){return;}
this.ieAtomicLocationChange=true;if(this.isIE&&this.getIFrameHash()!=hash){this.iframe.src="blank.html?"+hash;}
else if(this.isIE){return;}
this.currentLocation=hash;this.ieAtomicLocationChange=false;this.fireHistoryEvent(hash);},getIFrameHash:function(){var doc=this.iframe.contentWindow.document;var hash=String(doc.location.search);if(hash.length==1&&hash.charAt(0)=="?"){hash="";}
else if(hash.length>=2&&hash.charAt(0)=="?"){hash=hash.substring(1);}
return hash;},removeHash:function(hashValue){var r;if(hashValue==null||hashValue==undefined){r=null;}
else if(hashValue==""){r="";}
else if(hashValue.length==1&&hashValue.charAt(0)=="#"){r="";}
else if(hashValue.length>1&&hashValue.charAt(0)=="#"){r=hashValue.substring(1);}
else{r=hashValue;}
return r;},iframeLoaded:function(newLocation){if(this.ignoreLocationChange){this.ignoreLocationChange=false;return;}
var hash=String(newLocation.search);if(hash.length==1&&hash.charAt(0)=="?"){hash="";}
else if(hash.length>=2&&hash.charAt(0)=="?"){hash=hash.substring(1);}
if(this.pageLoadEvent!=true){window.location.hash=hash;}
this.fireHistoryEvent(hash);}};window.historyStorage={put:function(key,value){this.assertValidKey(key);if(this.hasKey(key)){this.remove(key);}
this.storageHash[key]=value;this.saveHashTable();},get:function(key){this.assertValidKey(key);this.loadHashTable();var value=this.storageHash[key];return(value==undefined?null:value);},remove:function(key){this.assertValidKey(key);this.loadHashTable();delete this.storageHash[key];this.saveHashTable();},reset:function(){this.storageField.value="";this.storageHash={};},hasKey:function(key){this.assertValidKey(key);this.loadHashTable();return(typeof this.storageHash[key]!="undefined");},isValidKey:function(key){return typeof key=="string";},invisibilityStyles:'position: absolute; top: -1000px; left: -1000px; width: 1px; height: 1px;',storageHash:{},hashLoaded:false,storageField:null,setup:function(){var textareaID="rshStorageField";var textareaHTML='<textarea id="'+textareaID+'" style="'+this.invisibilityStyles+'"></textarea>';document.write(textareaHTML);this.storageField=document.getElementById(textareaID);},assertValidKey:function(key){if(!this.isValidKey(key)){throw"Please provide a valid key for window.historyStorage, key= "+key;}},loadHashTable:function(){if(!this.hashLoaded){var serializedHashTable=this.storageField.value;if(serializedHashTable!=""&&serializedHashTable!=null){this.storageHash=this.parseJSON(serializedHashTable);}
this.hashLoaded=true;}},saveHashTable:function(){this.loadHashTable();var serializedHashTable=this.toJSONString(this.storageHash);this.storageField.value=serializedHashTable;},toJSONString:function(s){return Object.toJSON(s);},parseJSON:function(s){return s.evalJSON();}};window.historyStorage.setup();window.dhtmlHistory.create();var historyManager=function(defaultState){map.historyManager=this;dhtmlHistory.initialize();dhtmlHistory.addListener(_historyChange);dhtmlHistory.historyDisabled=false;this.defaultState=defaultState;dhtmlHistory.saveState=function(){if(dhtmlHistory.disabled==true)
return;else{dhtmlHistory.add("history-"+getTS(),map.historyManager.recordTotalState());}}
return this;}
function _historyChange(newLoc,data){map.historyManager.historyChange(newLoc,data);}
historyManager.prototype.historyChange=function(newLoc,stateObject){if(!window.appLoaded){window.setTimeout(function(){map.historyManager.historyChange(newLoc,stateObject)},2000);return;}
dhtmlHistory.disabled=true;newLoc=newLoc.split(/\-/)[0];switch(newLoc){case"":map.stateMachine.switchState(this.defaultState,true);break;case"history":this.restoreTotalState(stateObject);break;}
dhtmlHistory.disabled=false;}
historyManager.prototype.recordTotalState=function(){var state={};state.currentState=map.stateMachine.getCurrentState();state.currentStateTab=map.stateMachine.getCurrentTab();if(state.currentStateTab=="tab0"){state.tab0={};state.tab0.map={};state.tab0.map.lon=map.getCenter().lon;state.tab0.map.lat=map.getCenter().lat;state.tab0.map.zoom=map.getZoom();state.tab0.map.enabledLayers=[];for(var i=0;i<map.layers.length;i++){if(map.layers[i].getVisibility())
state.tab0.map.enabledLayers.push(map.layers[i].id);}
if(map.geoSearch&&map.geoSearch.currentActivatedDiv){state.tab0.map.geoSearch_currentActivatedDiv=map.geoSearch.currentActivatedDiv;}
if(map.layerMixer)
state.tab0.map.opacity=map.layerMixer.refLayer.opacity;state.tab0.form={};state.tab0.form.keyword=$F("keyword_tab0");state.tab0.form.city=$F("tab0_placeSearch_autoComplete");state.tab0.form.cityData=$("tab0_placeSearch_autoComplete").cityData;}
if(state.currentStateTab=="tab1"){state.tab1={};state.tab1.form={};state.tab1.form.keyword=$("searchForm_simple").keyword.value;state.tab1.form.city=$("searchForm_simple").place.value;state.tab1.form.cityData=$("searchForm_simple").place.cityData;}
if(state.currentStateTab=="tab2"){state.tab2={};state.tab2.form={};state.tab2.form.keyword=$("searchForm_fine").keyword.value;state.tab2.form.category=$("searchForm_fine").category.selectedIndex;state.tab2.form.kitchen=$("searchForm_fine").kitchen.selectedIndex;state.tab2.form.spec=$("searchForm_fine").spec.selectedIndex;state.tab2.form.pl_assises_lower=$("searchForm_fine").pl_assises_lower.selectedIndex;state.tab2.form.pl_assises_upper=$("searchForm_fine").pl_assises_upper.selectedIndex;state.tab2.form.gaultMillau_lower=$("searchForm_fine").gaultMillau_lower.selectedIndex;state.tab2.form.gaultMillau_upper=$("searchForm_fine").gaultMillau_upper.selectedIndex;state.tab2.form.guideBleu_lower=$("searchForm_fine").guideBleu_lower.selectedIndex;state.tab2.form.guideBleu_upper=$("searchForm_fine").guideBleu_upper.selectedIndex;state.tab2.form.michelin=$("searchForm_fine").michelin.selectedIndex;state.tab2.form.city=$("searchForm_fine").place.value;state.tab2.form.cityData=$("searchForm_fine").place.cityData;}
return state;}
historyManager.prototype.restoreTotalState=function(stateObject){map.stateMachine.switchState(stateObject.currentState);if(stateObject.currentStateTab=="tab0"){map.setCenter(new OpenLayers.LonLat(stateObject.tab0.map.lon,stateObject.tab0.map.lat),stateObject.tab0.map.zoom,true,false,true);for(var i=0;i<map.layers.length;i++){if(in_array(map.layers[i].id,stateObject.tab0.map.enabledLayers))
map.layers[i].setVisibility(true);else
map.layers[i].setVisibility(false);}
map.layerSwitcher.updateAllIcons();if(map.layerMixer)
map.layerMixer.updateOpacity(stateObject.tab0.map.opacity);if(stateObject.tab0.map.geoSearch_currentActivatedDiv){switch(stateObject.tab0.map.geoSearch_currentActivatedDiv){case"searchMask":map.geoSearch.showSearchMask();break;case"searchResults":map.geoSearch.showSearchResults();break;case"evidenceContainer":map.geoSearch.showEvidenceContainer();break;}}
map.ovMapControl.update();}
if(stateObject.currentStateTab=="tab1"){$("searchForm_simple").keyword.value=stateObject.tab1.form.keyword;$("searchForm_simple").place.value=stateObject.tab1.form.city;$("searchForm_simple").place.cityData=stateObject.tab1.form.cityData;}
if(stateObject.currentStateTab=="tab2"){$("searchForm_fine").keyword.value=stateObject.tab2.form.keyword;$("searchForm_fine").category.selectedIndex=stateObject.tab2.form.category;$("searchForm_fine").kitchen.selectedIndex=stateObject.tab2.form.kitchen;$("searchForm_fine").spec.selectedIndex=stateObject.tab2.form.spec;$("searchForm_fine").pl_assises_lower.selectedIndex=stateObject.tab2.form.pl_assises_lower;$("searchForm_fine").pl_assises_upper.selectedIndex=stateObject.tab2.form.pl_assises_upper;$("searchForm_fine").gaultMillau_lower.selectedIndex=stateObject.tab2.form.gaultMillau_lower;$("searchForm_fine").gaultMillau_upper.selectedIndex=stateObject.tab2.form.gaultMillau_upper;$("searchForm_fine").guideBleu_lower.selectedIndex=stateObject.tab2.form.guideBleu_lower;$("searchForm_fine").guideBleu_upper.selectedIndex=stateObject.tab2.form.guideBleu_upper;$("searchForm_fine").michelin.selectedIndex=stateObject.tab2.form.michelin;$("searchForm_fine").place.value=stateObject.tab2.form.city;$("searchForm_fine").place.cityData=stateObject.tab2.form.cityData;}}