var baseIcon,plusIcon,map,cluster = false;

function onloadBeforeMaps(params) {
	$('.js_input').each(function(){inputTransform(this)});
	$('.js_mapInput').each(function(){mapInputDraw(this)});
	if ($('.js_textCut').length>sys.leadParagraphsMin)
		$('.js_textCut').each(function(){textCutPrepare(this);});
	sys.domain = window.location.host.explode('.').slice(-2).join('.');

	if (typeof(params.popUp)!='undefined')
		popUpSearchOpen(params.popUp);
	};
	
function onloadAfterMaps() {
	baseIcon = new GIcon();
	baseIcon.image = "http://s."+sys.domain+"/icon.png"
	baseIcon.iconSize = new GSize(17, 23);
	baseIcon.iconAnchor = new GPoint(7, 24);
	baseIcon.infoWindowAnchor = new GPoint(5, 12);
	baseIcon.imageMap = new Array(0,15,0,9,10,0,16,0,24,11,24,15);

	plusIcon = new GIcon();
	plusIcon.image = "http://s."+sys.domain+"/iconplus.png"
	plusIcon.iconSize = new GSize(19, 25);
	plusIcon.iconAnchor = new GPoint(7, 24);
	plusIcon.infoWindowAnchor = new GPoint(10, 10);
	plusIcon.imageMap = new Array(0,15,0,9,10,0,16,0,24,11,24,15);

	document.body.onunload=GUnload;
	
	$('.js_map').each(function() {
		m = this;
		settings = m.innerHTML.uncomment(true);
		markers = settings.markers;
		settings.div = m;
		mapShow(settings,undefined);
		});
	};

///////////////////////////////////////////////////////////////////////////////

function getSelfHTML(_this) {
	return document.createElement('div').appendChild(_this.cloneNode(true)).parentNode.innerHTML;
	};
	
String.prototype.uncomment = function(evaluate) {
	var text = this;
	text = text.match(/<!--(.+?)-->/g).toString();
	text = $.trim(text.substr(4,text.length-7));
	evaluate = typeof(evaluate)=='undefined' ? false : evaluate;
	if (evaluate) {
		text = 'text='+text+';';
		eval(text);
		};
	return text;
	};
	
String.prototype.explode = function(delimiter) {
	if (typeof(delimiter)=='undefined') delimiter = ',';
	str = this.split(delimiter);
	arr = new Array();
	for (i=0;i<str.length;i++) {
		str[i] = $.trim(str[i]);
		if (str[i].length) arr.push(str[i]);
		};
	return arr;
	};
	
Array.prototype.implode = function(glue) {
	var arr = this;
	var arr2 = new Array();
	for (i=0;i<arr.length;i++) {
		var elm = $.trim(arr[i].toString());
		if (elm.length) arr2.push(elm);
		};
	return arr2.join(glue);
	};

function insertAtCursor(myField, myValue) {
	if (document.selection) { // IE
		myField.focus();
		var sel = document.selection.createRange();
		sel.text = myValue;
		} else if (myField.selectionStart || myField.selectionStart == '0') { // Mozilla
			var len = myField.value.length;
			var startPos = myField.selectionStart;
			var endPos = myField.selectionEnd;
			myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos,len);
			} else {
				myField.value += myValue;
				};
	};
	
function replaceInTextarea(textarea) {
	if (document.selection)	{ // code for IE
		textarea.focus();
		var sel = document.selection.createRange();
		sel.text = '<ref>' + sel.text + '</ref>';
		} else { // code for Mozilla
			var len = textarea.value.length;
			var start = textarea.selectionStart;
			var end = textarea.selectionEnd;
			var sel = textarea.value.substring(start, end);
			var replace = '<ref>' + sel + '</ref>';
			textarea.value =  textarea.value.substring(0,start) + replace + textarea.value.substring(end,len);
			};
	return false;
	};
	
function mathBase62(num) {
	var out,t,a;
	var base = 62;
	var index = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".substr(0,base);
	num = parseInt(num);
	out = "";
	for (t = Math.floor(Math.log(num) / Math.log(base));t>=0;t--) {
		a = Math.floor(num / Math.pow(base,t));
		out = out.toString()+index.substr(a,1);
		num = num - (a*Math.pow(base,t));
		};
	return out;
	};
	
///////////////////////////////////////////////////////////////////////////////
///// AJAX

function ajax(action,obj,method,fn,params,noLoadingMsg) {
	var obj = typeof(obj)=='string' ? $('#'+obj)[0] : $(obj);
	if (typeof(method) != 'string') method = 'GET';
	if (typeof(fn) != 'function') 	fn = function() {};
	if (typeof(params) != 'string') params = '';
	if (typeof(noLoadingMsg)=='undefined') var noLoadingMsg = false;
	if (!noLoadingMsg) $(obj).html(lang.loading);
	$.ajax({'success':function(data,textStatus){$(obj).html(data); fn(data);},'url':action,'data':params,'type':method.toUpperCase()});
	return false;
	};

function formAjaxSubmit(form,obj,fn,action) {
	var fn = typeof(fn)!='undefined' ? fn : function() {};
	var action = typeof(action)!='undefined' ? action : form.action;
	return ajax(action,obj,form.method.toUpperCase(),fn,$(form).serialize());
	};

///////////////////////////////////////////////////////////////////////////////
///// popUps
	
function popUpOpen(isFullScreen) {
	$('#curtain').html("<iframe src=''></iframe>").show();
	$('#layer').html("<div id='layerClose'></div><div id='layer2' class='"+(isFullScreen ? 'full' : 'compact')+"'><div id='layer2cell'><div id='layerValign'></div><div id='layer2div'><div id='layer3'></div></div><div id='layer2notes'></div></div></div>").show();
	$('#layerClose').html(String.fromCharCode(215)).bind('click',popUpClose);
 	$(document).bind('keydown',function(event) {
		switch (event.which) {
			case 27: popUpClose(); return false;
			};
		});
	return false;
	};
	
function popUpClose() {
	$('#curtain,#layer').hide().html('');
	return false;
	};
	
function popUpHTML(htmlOrClass,fn,isFullScreen) {
	if (typeof(isFullScreen)=='undefined') isFullScreen = false;
	popUpOpen(isFullScreen);
	if (typeof(htmlOrClass)=='object') htmlOrClass = htmlOrClass.innerHTML;
	$('#layer3').html(htmlOrClass);
	if (typeof(fn)!='undefined') fn();
	return false;
	};
	
function popUpGet(url,fn) {
	popUpOpen();
	return ajax(url,$('#layer3'),false,fn);
	};
	
function popUpPost(form,fn) {
	var fn = typeof(fn)!='undefined' ? fn : function() {};
	return ajax(form.action,'layer3','POST',fn,$(form).serialize());
	};
	
function popUpImage(_this,options) {
	var original = options.original;
	var html = "<img alt='' src='"+_this.href+"' />";
	if (typeof(original)!='undefined')
		html+= "<br /><small><a href='"+original+"'>"+lang.fullsize+"</a></small>";
	return popUpHTML(html);
	};
	
function popUpMap(settings,fn) {
	if (typeof(settings)=='undefined') settings = {};
	if (typeof(fn)=='undefined') fn = function() {};
	mapHTML = "<div id='layerMap'>"+lang.loading+"</div>";
	if (settings.addingAllowed)	mapHTML+= "<div class='pt'><small>"+lang.clckmap+"</small></div>";
	return popUpHTML(mapHTML,function(){settings.div = $('#layer3')[0];mapShow(settings,fn);},true);
	};
	
function popUpIframe(url) {
	return popUpHTML("<iframe name='layerIframe' id='layerIframe' src='"+url+"'></iframe>");
	};
	
function popUpSearchOpen(params) {
	$('.js_popUpFile'+params.fileID+':eq(0)').trigger('click');
	};

function popUpLargeImage(settings,link) {
	settings.allowKeyboard = true;
	var html = "<div id='popUpLargeImage'></div>";
	return popUpHTML(html,function() {
		$('#popUpLargeImage').maptilia(settings);
		},true);
	};
	
///////////////////////////////////////////////////////////////////////////////
///// Old maps

jQuery.fn.maptilia = function(conf) {
	var fnConf,fnHTML,fnEvents,fnDrag,fnPics,fnMove,fnView,fnPics,fnCenter;

	// #############################################################################
	
	fnConf = function(li,conf) {
		conf = jQuery.extend({
			moveDelta:200,moveDeltaFast:1000,dragCoefficient:2,dragJitterThreshold:10,
			overlays:[],view:{},start:false,allowKeyboard:false,linkTmpl:false,
			markerURL:'http://s.zurbu.net/icon.png'
			},conf);
		conf.totalParts = conf.xCount*conf.yCount;
		conf.totalHeight = conf.partHeight*conf.yCount;
		conf.totalWidth = conf.partWidth*conf.xCount;
		$.each(conf,function(k,v){li.data(k,v);});
		};
			
	// #############################################################################
			
	fnHTML = function(li) {
		var tableHTML = '';
		for (var i=1;i<=li.data('totalParts');i++) {
			if (!((i-1)%li.data('xCount'))) tableHTML+= '<tr>';
			tableHTML+= '<td></td>';
			if (!(i%li.data('xCount'))) tableHTML+= '</tr>';
			};
		li.html("<div><table>"+tableHTML+"</table><address /></div><fieldset><table><tr><td><button /></td><td><button /><button /></td><td><button /></td></tr></table></fieldset>");
		jQuery('div table td',li).html(document.createElement('div'));
		jQuery('>fieldset>table button',li)
			.each(function(k,v){$(v).html(String.fromCharCode([9668,9650,9660,9658][k]))});
		jQuery('> div table td div',li).width(li.data('partWidth')).height(li.data('partHeight'))
			.each(function(i){$(this).data('url',li.data('path').replace('{id}',(i+1)));});
		if (li.data('links')) {
			li.append("<fieldset><ol></ol></fieldset>");
			jQuery.each(li.data('links'),function(k,v) {
				jQuery('>fieldset:eq(1)>ol',li)
					.append("<li><span><a href='"+v.url+"'>"+v.title+"</a></span></li>");
				});
			};
		};
		
	// #############################################################################
	
	fnDrag = function(e) {
		var li,il,it,d;
		d = jQuery(e.data);
		if (Math.abs(il=e.pageX-d[0].data('initLeft'))>=d[3])
			fnMove(0,il*d[2],d[1]);
		if (Math.abs(it=e.pageY-d[0].data('initTop'))>=d[3])
			fnMove(1,it*d[2],d[1]);
		};
	
	// #############################################################################
		
	fnCenter = function(li) {
		var args = Array.prototype.slice.call(arguments).slice(1),sc=jQuery('>div',li);
		args.push({top:li.data('totalHeight')/2,left:li.data('totalWidth')/2});
		jQuery.each(args,function(k,v) {
			if (v) {
				if (typeof(v.top)=='undefined')
					v = maptitliaPointToCoords(li,v);
				var l=li.data('totalWidth')-li.width(),t=li.data('totalHeight')-li.height();
				v.top = v.top - sc.height()/2;
				v.left = v.left - sc.width()/2;
				if (v.top<0)
					v.top=0;
				if (v.top>t)
					v.top=t;
				if (v.left<0)
					v.left=0;
				if (v.left>l)
					v.left=l;
				sc.scrollLeft(v.left).scrollTop(v.top);
				return false;
				};
			});
		};
	
	// #############################################################################

	fnView = function(li,sc) {
		var x1,x2,y1,y2,j,i,id,view,tiles,xc,yc,pw,ph=0;
		view = {
			'left':sc.scrollLeft(),'right':sc.scrollLeft()+li.width(),
			'top':sc.scrollTop(),'bottom':sc.scrollTop()+li.height(),
			'tiles':[]
			};
		xc=li.data('xCount');
		yc=li.data('yCount');
		pw=li.data('partWidth');
		ph=li.data('partHeight');
		tiles = $('table div',sc);
		x1 = Math.floor(view.left/pw)+1;
		x2 = Math.floor(view.right/pw)+1;
		if (x2 > xc)
			x2 = xc
		y1 = Math.floor(view.top/ph);
		y2 = Math.floor(view.bottom/ph);
		if (y2 == yc)
			y2 = yc-1;
		for (j=y1;j<y2+1;j++)
			for (i=x1;i<x2+1;i++)
				view.tiles.push($(tiles[j*xc+i-1]));
		li.data('view',view);
		};

	// #############################################################################

	fnPics = function(li) {
		jQuery.each(li.data('view').tiles,function(){
			var data = this.data('url');
			if (typeof(data)!='undefined')
				this.css('backgroundImage','url('+data+')').removeData('url');
			});
		};
	
	// #############################################################################
	
	fnMove = function(isVertical,delta,sc) {
		delta = Math.round(delta);
		isVertical ? sc.scrollTop(sc.scrollTop()-delta) : sc.scrollLeft(sc.scrollLeft()-delta);
		};
	
	// #############################################################################
	
	fnEvents = function(li) {
		var sc=jQuery('>div',li),buttons=jQuery('>fieldset>table button',li)
			,fieldsets=jQuery('>fieldset>*',li)
			,dragData=[li,sc,li.data('dragCoefficient'),li.data('dragJitterThreshold')];
		li	.bind('mousedown',dragData,function(e){jQuery(e.target).bind('mousemove',e.data,fnDrag);})
			.bind('mouseout mouseup',function(e){jQuery(e.target).unbind('mousemove',fnDrag);})
			.bind('mousedown mousemove',function(e){li.data('initLeft',e.pageX).data('initTop',e.pageY);})
			.dblclick(function(e) {
				var x,y,off=sc.offset();
				x=e.pageX+sc.scrollLeft()-Math.round(off.left);
				y=e.pageY+sc.scrollTop()-Math.round(off.top);
				maptiliaOverlaysAdd(li,[{'type':'marker','left':x,'top':y}],1).trigger('click');
				})
			.mouseleave(function(){fieldsets.fadeOut();})
			.mouseenter(function(){fieldsets.fadeIn();});
		if (jQuery.browser.msie)
			li.bind('selectstart',function(){return false;});
		sc.scroll(function(){
			fnView(li,sc);
			fnPics(li);
			});
		var moves=[[0,1],[1,1],[1,-1],[0,-1]],delta=li.data('moveDelta');
		jQuery.each(buttons,function(k,v){$(v).click(function(){return fnMove(moves[k][0],moves[k][1]*delta,sc);})});
		if (li.data('allowKeyboard'))
			jQuery(document).keydown(function(e) {
				var md=delta,mdf=li.data('moveDeltaFast'),move=0;
				switch (e.which) {
					case 33: move = [1,mdf]; break;
					case 34: move = [1,-mdf]; break;
					case 35: move = [0,-mdf]; break;
					case 36: move = [0,mdf]; break;
					case 37: move = [0,md]; break;
					case 38: move = [1,md]; break;
					case 39: move = [0,-md]; break;
					case 40: move = [1,-md]; break;
					};
				if (move)
					fnMove(move[0],move[1],sc)
			});
		};
	
	// #############################################################################
	
	return this.each(function(key,li){
		var sc=jQuery('>div',li),li=jQuery(li);
		fnConf(li,conf);
		fnHTML(li);
		maptiliaCSS(li,1);
		fnEvents(li);
		fnCenter(li,(li.data('start')?maptiliaPointToCoords(li,li.data('start')):0));
		fnView(li,sc);
		fnPics(li);
		maptiliaOverlaysAdd(li,li.data('overlays'),1);
		maptiliaOverlaysDraw(li);
		});
	};



function maptiliaPointToCoords(li,v) {
	v.top = parseInt(Math.floor(v.point / li.data('totalWidth')));
	v.left = parseInt(v.point % li.data('totalWidth'));
	return v;
	};
	
function maptiliaCoordsToPoint(li,v) {
	v.point = parseInt(v.top*li.data('totalWidth')+v.left);
	return v;
	};

function maptiliaOverlaysAdd(li,overlays,doReplace) {
	var overlaysNew = doReplace ? [] : jQuery.makeArray(li.data('overlays'));
	jQuery.each(overlays,function(k,v) {
		if (typeof(v.top)=='undefined')
			v = maptiliaPointToCoords(li,v);
		if (v.top<=li.data('totalHeight') && v.left<=li.data('totalWidth') && v.left>=0 && v.top>=0)
			overlaysNew.push(v);
		});
	li.data('overlays',overlaysNew);
	return maptiliaOverlaysDraw(li);
	};
	
function maptiliaOverlaysDraw(li) {
	var ol = jQuery('>div>address',li).empty();
	jQuery.each(li.data('overlays'),function(){
		switch (this.type) {
			case 'marker':
				ol.append(jQuery(document.createElement('var'))
					.css({top:this.top,left:this.left})
					.data('link',li.data('linkTmpl')
						.replace('{p}',mathBase62(maptiliaCoordsToPoint(li,{left:this.left,top:this.top}).point)))
					.html("<span><a /></span>")
					.click(function(e){
						var link=jQuery(this).data('link');
						if (jQuery.browser.msie && jQuery.browser.version<7) {
							prompt('',link);
							} else {
								$('a',jQuery('span',this).toggle()).attr('href',link).html(link)
									.click(function(e){e.stopPropagation();});
								};
						})
					);
				break;
			};
		});
	maptiliaCSS(li,false);
	return jQuery('>div>address var',li);
	};


function maptiliaCSS(li,isInitial) {
	var fieldsets=jQuery('>fieldset',li),sc=jQuery('> div',li);
	if (isInitial) {
		li.css({position:'relative',width:'100%',height:'100%',overflow:'hidden','user-select':'none'
			,'-moz-user-select':'none','-webkit-user-select':'none','-ms-user-select':'none'});
		jQuery('table',li).css({borderCollapse:'collapse'});
		jQuery('table td',li).css({padding:'0'});
		sc.css({overflow:'hidden',height:'100%',width:'100%',position:'absolute'});
		if (jQuery.browser.mozilla) {
			sc.css({position:'relative'});
			jQuery('table td div',sc).css({overflow:'hidden'});
			};
		jQuery('>address',sc).css({position:'absolute',left:'0',top:'0',cursor:'-moz-grab'})
			.width(li.data('totalWidth')).height(li.data('totalHeight'));
		fieldsets.css({position:'absolute',width:'1px',height:'1px'});
		jQuery('>*',fieldsets).css({position:'absolute'});
		fieldsets.eq(0).css({left:'15px',top:'10px'});
		jQuery('>table td',fieldsets.eq(0)).css({verticalAlign:'bottom'});
		jQuery('>table button',fieldsets.eq(0)).css({color:'#369',textDecoration:'none',border:'1px outset #999','text-align':'center',margin:'2px 1px 2px 0',height:'25px',width:'23px',fontFamily:'courier new',display:'block',fontSize:'19px',cursor:'pointer',background:'#fff',padding:'0',lineHeight:'25px',textShadow:'#ccc 1px 1px 10px','-moz-border-radius':'5px','-webkit-border-radius':'5px','border-radius':'5px'});
		fieldsets.eq(1).css({left:'15px',bottom:'20px'});
		jQuery('>ol',fieldsets.eq(1)).css({bottom:'0',padding:'0',margin:'0',whiteSpace:'nowrap',fontSize:'11px',fontFamily:'arial',minHeight:'1%'});
		jQuery('>ol li',fieldsets.eq(1)).css({whiteSpace:'nowrap',margin:'0 6px 0 0',padding:'2px 5px 3px 6px',background:'#fff','-moz-border-radius':'5px','-webkit-border-radius':'5px','border-radius':'5px',listStyle:'none',opacity:'.9',filter:'alpha(opacity=90)',border:'1px outset #ddd',display:'inline-block'});
		if ($.browser.msie)
			$('>ol li',fieldsets.eq(1)).css({display:'inline',zoom:'1'});
		jQuery('>ol li a',fieldsets.eq(1)).css({color:'#369'});
		};
	jQuery('var',li).css({position:'absolute',display:'block',width:'17px',height:'23px',margin:'-23px 0 0 -9px',background:"url("+li.data('markerURL')+")",cursor:'pointer'});
	jQuery('var span',li).css({position:'absolute',margin:'-15px 0 0 20px',display:'none',background:'#fff','-moz-border-radius':'5px','-webkit-border-radius':'5px','border-radius':'5px',listStyle:'none',opacity:'.9',filter:'alpha(opacity=90)',border:'1px outset #ddd',padding:'3px',fontSize:'11px',fontStyle:'normal',fontFamily:'arial',whiteSpace:'nowrap'});
	jQuery('var span a',li).css({color:'#369'});
	jQuery('var span input',li).css({fontSize:'11px'});
	if (jQuery.browser.msie && jQuery.browser.version<7) {
		jQuery('> ol',fieldsets).css({zoom:'1'});
		jQuery('var',li).css({background:'none',filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, src='"+li.data('markerURL')+"')"});
		};
	};
	
	

///////////////////////////////////////////////////////////////////////////////
///// Google maps	

/* ClusterMarker Version 1.2.1 A marker manager for the Google Maps API http://googlemapsapi.martinpearman.co.uk/clustermarker Copyright Martin Pearman 2008. Last updated 2nd February 2008. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. */ function ClusterMarker(_1,_2){this._map=_1;this._mapMarkers=[];this._iconBounds=[];this._clusterMarkers=[];this._eventListeners=[];if(typeof (_2)==="undefined"){_2={};}this.borderPadding=(_2.borderPadding)?_2.borderPadding:256;this.clusteringEnabled=(_2.clusteringEnabled===false)?false:true;if(_2.clusterMarkerClick){this.clusterMarkerClick=_2.clusterMarkerClick;}if(_2.clusterMarkerIcon){this.clusterMarkerIcon=_2.clusterMarkerIcon;}else{this.clusterMarkerIcon=new GIcon();this.clusterMarkerIcon.image="http://maps.google.com/mapfiles/arrow.png";this.clusterMarkerIcon.iconSize=new GSize(39,34);this.clusterMarkerIcon.iconAnchor=new GPoint(9,31);this.clusterMarkerIcon.infoWindowAnchor=new GPoint(9,31);this.clusterMarkerIcon.shadow="http://www.google.com/intl/en_us/mapfiles/arrowshadow.png";this.clusterMarkerIcon.shadowSize=new GSize(39,34);}this.clusterMarkerTitle=(_2.clusterMarkerTitle)?_2.clusterMarkerTitle:"Click to zoom in and see %count markers";if(_2.fitMapMaxZoom){this.fitMapMaxZoom=_2.fitMapMaxZoom;}this.intersectPadding=(_2.intersectPadding)?_2.intersectPadding:0;if(_2.markers){this.addMarkers(_2.markers);}GEvent.bind(this._map,"moveend",this,this._moveEnd);GEvent.bind(this._map,"zoomend",this,this._zoomEnd);GEvent.bind(this._map,"maptypechanged",this,this._mapTypeChanged);};ClusterMarker.prototype.addMarkers=function(_3){var i;if(!_3[0]){var _5=[];for(i in _3){_5.push(_3[i]);}_3=_5;}for(i=_3.length-1;i>=0;i--){_3[i]._isVisible=false;_3[i]._isActive=false;_3[i]._makeVisible=false;}this._mapMarkers=this._mapMarkers.concat(_3);};ClusterMarker.prototype._clusterMarker=function(_6){function $newClusterMarker(_7,_8,_9){return new GMarker(_7,{icon:_8,title:_9});};var _a=new GLatLngBounds(),i,_c,_d=[],_e,_f=this,_10=this._mapMarkers;for(i=_6.length-1;i>=0;i--){_e=_10[_6[i]];_e.index=_6[i];_a.extend(_e.getLatLng());_d.push(_e);}_c=$newClusterMarker(_a.getCenter(),this.clusterMarkerIcon,this.clusterMarkerTitle.replace(/%count/gi,_6.length));_c.clusterGroupBounds=_a;this._eventListeners.push(GEvent.addListener(_c,"click",function(){_f.clusterMarkerClick({clusterMarker:_c,clusteredMarkers:_d});}));_c._childIndexes=_6;for(i=_6.length-1;i>=0;i--){_10[_6[i]]._parentCluster=_c;}return _c;};ClusterMarker.prototype.clusterMarkerClick=function(_11){this._map.setCenter(_11.clusterMarker.getLatLng(),this._map.getBoundsZoomLevel(_11.clusterMarker.clusterGroupBounds));};ClusterMarker.prototype._filterActiveMapMarkers=function(){var _12=this.borderPadding,_13=this._map.getZoom(),_14=this._map.getCurrentMapType().getProjection(),_15,_16,_17,_18,_19,_1a,_1b=this._map.getBounds(),i,_1d,_1e=[],_1f,_20=this._mapMarkers,_21=this._iconBounds;if(_12){_15=_14.fromLatLngToPixel(_1b.getSouthWest(),_13);_16=new GPoint(_15.x-_12,_15.y+_12);_17=_14.fromPixelToLatLng(_16,_13);_18=_14.fromLatLngToPixel(_1b.getNorthEast(),_13);_19=new GPoint(_18.x+_12,_18.y-_12);_1a=_14.fromPixelToLatLng(_19,_13);_1b.extend(_17);_1b.extend(_1a);}this._activeMarkersChanged=false;if(typeof (_21[_13])==="undefined"){this._iconBounds[_13]=[];this._activeMarkersChanged=true;for(i=_20.length-1;i>=0;i--){_1d=_20[i];_1d._isActive=_1b.containsLatLng(_1d.getLatLng())?true:false;_1d._makeVisible=_1d._isActive;if(_1d._isActive){_1e.push(i);}}}else{for(i=_20.length-1;i>=0;i--){_1d=_20[i];_1f=_1d._isActive;_1d._isActive=_1b.containsLatLng(_1d.getLatLng())?true:false;_1d._makeVisible=_1d._isActive;if(!this._activeMarkersChanged&&_1f!==_1d._isActive){this._activeMarkersChanged=true;}if(_1d._isActive&&typeof (_21[_13][i])==="undefined"){_1e.push(i);}}}return _1e;};ClusterMarker.prototype._filterIntersectingMapMarkers=function(){var _22,i,j,_25=this._map.getZoom(),_26=this._mapMarkers,_27=this._iconBounds;for(i=_26.length-1;i>0;i--){if(_26[i]._makeVisible){_22=[];for(j=i-1;j>=0;j--){if(_26[j]._makeVisible&&_27[_25][i].intersects(_27[_25][j])){_22.push(j);}}if(_22.length!==0){_22.push(i);for(j=_22.length-1;j>=0;j--){_26[_22[j]]._makeVisible=false;}this._clusterMarkers.push(this._clusterMarker(_22));}}}};ClusterMarker.prototype.fitMapToMarkers=function(){var _28=this._mapMarkers,_29=new GLatLngBounds(),i;for(i=_28.length-1;i>=0;i--){_29.extend(_28[i].getLatLng());}var _2b=this._map.getBoundsZoomLevel(_29);if(this.fitMapMaxZoom&&_2b>this.fitMapMaxZoom){_2b=this.fitMapMaxZoom;}this._map.setCenter(_29.getCenter(),_2b);this.refresh();};ClusterMarker.prototype._mapTypeChanged=function(){this.refresh(true);};ClusterMarker.prototype._moveEnd=function(){if(!this._cancelMoveEnd){this.refresh();}else{this._cancelMoveEnd=false;}};ClusterMarker.prototype._preCacheIconBounds=function(_2c,_2d){var _2e=this._map.getCurrentMapType().getProjection(),i,_30,_31,_32,_33,_34,_35,_36,_37,_38=this.intersectPadding,_39=this._mapMarkers;for(i=_2c.length-1;i>=0;i--){_30=_39[_2c[i]];_31=_30.getIcon().iconSize;_32=_2e.fromLatLngToPixel(_30.getLatLng(),_2d);_33=_30.getIcon().iconAnchor;_34=new GPoint(_32.x-_33.x-_38,_32.y-_33.y+_31.height+_38);_35=new GPoint(_32.x-_33.x+_31.width+_38,_32.y-_33.y-_38);_36=_2e.fromPixelToLatLng(_34,_2d);_37=_2e.fromPixelToLatLng(_35,_2d);this._iconBounds[_2d][_2c[i]]=new GLatLngBounds(_36,_37);}};ClusterMarker.prototype.refresh=function(_3a){var i,_3c,_3d=this._map.getZoom(),_3e=this._filterActiveMapMarkers();if(this._activeMarkersChanged||_3a){this._removeClusterMarkers();if(this.clusteringEnabled&&_3d<this._map.getCurrentMapType().getMaximumResolution()){if(_3e.length>0){this._preCacheIconBounds(_3e,_3d);}this._filterIntersectingMapMarkers();}for(i=this._clusterMarkers.length-1;i>=0;i--){this._map.addOverlay(this._clusterMarkers[i]);}for(i=this._mapMarkers.length-1;i>=0;i--){_3c=this._mapMarkers[i];if(!_3c._isVisible&&_3c._makeVisible){this._map.addOverlay(_3c);_3c._isVisible=true;}if(_3c._isVisible&&!_3c._makeVisible){this._map.removeOverlay(_3c);_3c._isVisible=false;}}}};ClusterMarker.prototype._removeClusterMarkers=function(){var i,j,_41=this._map,_42=this._eventListeners,_43=this._clusterMarkers,_44,_45=this._mapMarkers;for(i=_43.length-1;i>=0;i--){_44=_43[i]._childIndexes;for(j=_44.length-1;j>=0;j--){delete _45[_44[j]]._parentCluster;}_41.removeOverlay(_43[i]);}for(i=_42.length-1;i>=0;i--){GEvent.removeListener(_42[i]);}this._clusterMarkers=[];this._eventListeners=[];};ClusterMarker.prototype.removeMarkers=function(){var i,_47=this._mapMarkers,_48=this._map;for(i=_47.length-1;i>=0;i--){if(_47[i]._isVisible){_48.removeOverlay(_47[i]);}delete _47[i]._isVisible;delete _47[i]._isActive;delete _47[i]._makeVisible;}this._removeClusterMarkers();this._mapMarkers=[];this._iconBounds=[];};ClusterMarker.prototype.triggerClick=function(_49){var _4a=this._mapMarkers[_49];if(_4a._isVisible){GEvent.trigger(_4a,"click");}else{if(_4a._isActive){var _4b=_4a._parentCluster._childIndexes,_4c=true,_4d,i,_4f=this._map.getZoom(),_50,_51=this._iconBounds,_52=this._map.getCurrentMapType().getMaximumResolution();while(_4c&&_4f<_52){_4c=false;_4f++;if(typeof (_51[_4f])==="undefined"){_51[_4f]=[];this._preCacheIconBounds(_4b,_4f);}else{_4d=[];for(i=_4b.length-1;i>=0;i--){if(typeof (_51[_4f][_4b[i]])==="undefined"){_4d.push(_4b[i]);}}if(_4d.length>=1){this._preCacheIconBounds(_4d,_4f);}}for(i=_4b.length-1;i>=0;i--){_50=_4b[i];if(_50!==_49&&_51[_4f][_50].intersects(_51[_4f][_49])){_4c=true;break;}}}this._map.setCenter(_4a.getLatLng(),_4f);this.triggerClick(_49);}else{this._map.setCenter(_4a.getLatLng());this.triggerClick(_49);}}};ClusterMarker.prototype._zoomEnd=function(){this._cancelMoveEnd=true;this.refresh(true);};

function refreshMarkers(markers) {
	cluster.removeMarkers();
	cluster.addMarkers(markers);
	cluster.refresh();	
	};

function mapStaticImage(lat,lng) {
	return "<img src='http://maps.google.com/staticmap?zoom=10&amp;size=200x140&amp;maptype=roadmap&amp;markers="+lat+","+lng+",midorange&amp;key="+sys.mapCode+"' alt='' width='200' height='140' />";
	};

function mapMarker(markerPlace,settings) {
	var point = new GLatLng(markerPlace[0],markerPlace[1]);
	var marker = new GMarker(point, {icon:baseIcon});

	GEvent.addListener(marker, "click", function() {
		var coords = marker.getPoint();
		switch (typeof(markerPlace[2])) {
			case 'object':
				var link = markerPlace[2];
				link = "<a href='"+link[0]+"' style='font-size:20px;font-family:georgia;font-style:italic;letter-spacing:1px;'>"+link[1]+"</a>";
				marker.openInfoWindowHtml(link,{'maxWidth':120});
				break;
			case 'undefined':
				if (typeof(settings.urlTemplate)!='undefined' && settings.urlTemplate) {
					url = settings.urlTemplate+coords.lat()+':'+coords.lng()+'/ajax?isAjax=1';
						// this should be server-scripted
					ajax(url,settings.infoBlock,'GET');					
				};
				break;
			};
		});


	return marker;
	};
	
function mapCoordsSplit(coords) {
	var lat, lng, coords;
	coords = coords.split(',',2);
	if (coords.length == 2) {
		lat = parseFloat($.trim(coords[0]));
		lng = parseFloat($.trim(coords[1]));
		} else
			lat = lng = 0;
	return {'lat':lat,'lng':lng};
	};

function mapInputDraw(inputField) {
	var input = inputField.parentNode;
	input.id = inputField.id+'_fieldset';
	var coords = mapCoordsSplit(inputField.value);
	var div = input.getElementsByTagName('div');
	$(inputField).hide();

	if (!div.length) {
		input.innerHTML+= '<div></div>';
		div = input.getElementsByTagName('div')[0];
		} else 
			div = div[0];
			
	div.innerHTML = (coords.lat || coords.lng)
		? mapStaticImage(coords.lat,coords.lng)
		: lang.emp;	
	div.innerHTML+= "<br /><small><span onclick='mapEdit(\""+input.id+"\")'>"+lang.edit+"</span>"+((coords.lat || coords.lng) ? " | <span onclick='mapEditDelete(\""+input.id+"\")'>"+lang.del+"</span>" : '')+"</small>";
	};

function mapPutMarker(point,fields,markers) {
	var marker = new GMarker(point, {icon:baseIcon});
	if (fields.length) {
		var coords = (Math.round(marker.getPoint().lat()*10000)/10000)+', '+(Math.round(marker.getPoint().lng()*10000)/10000);
		$('#'+fields[0])[0].title = coords;
		};
	var markers = [marker] || markers;
	refreshMarkers(markers);
	};
	
function mapEditDelete(inputID) {
	mapInputDraw($('#'+inputID+' input').val('')[0]);
	};
	
function mapEdit(inputID) {
	var input = $('#'+inputID);	
	var inputField = $('input',input)[0];
	var coords = mapCoordsSplit(inputField.value);
	var markers = (coords.lat || coords.lng) ? [[coords.lat,coords.lng]] : [];
	var settings = {'addingAllowed':true,'markers':markers,'functionNotes':{'fields':[inputField],'input':input}};
	var fn = function(point,functionNotes) {
		functionNotes.fields[0].value = point.lat()+', '+point.lng();
		mapInputDraw(functionNotes.fields[0]);
		popUpClose();
		};
	return popUpMap(settings,fn);
	};
	
function mapAddLink(field) {
	fn = function(point) {
		mapPutMarker(point,[],[]);
		map.setCenter(point,(map.getZoom()>14 ? map.getZoom() : 14));
		if (confirm(lang.isitok)) {
			insertAtCursor($('#'+field)[0],' <geo>'+(Math.round(point.lat() * 10000) / 10000)+','+(Math.round(point.lng() * 10000) / 10000)+'</geo> ');
			popUpClose();
			} else {
				refreshMarkers([]);
				};
		};
	settings = {addingAllowed:true};
	return popUpMap(settings,fn,true);
	};
	
function mapSettings(settings) {
	if (typeof(settings.div)=='undefined')
		settings.div = $("#layerMap")[0];
	if (typeof(settings.markers)=='undefined')
		settings.markers = [];
	if (typeof(settings.urlTemplate)=='undefined')
		settings.urlTemplate = false;
	if (typeof(settings.addingAllowed)=='undefined')
		settings.addingAllowed = false;
	if (typeof(settings.functionNotes)=='undefined')
		settings.functionNotes = {};
	if (typeof(settings.type)=='undefined')
		settings.type = G_NORMAL_MAP;
	settings.zoom = (sys.lat || sys.lng) ? 10 : 1;
	for (i=0;i<settings.markers.length;i++)
		settings.markers[i] = mapMarker(settings.markers[i],settings);
	return settings;
	};
	
function mapShow(settings,fn) {
	if (GBrowserIsCompatible()) {
	
		settings = mapSettings(settings);
		
		map = new GMap2(settings.div);
		map.setCenter(new GLatLng(sys.lat,sys.lng),settings.zoom)
		map.addMapType(G_PHYSICAL_MAP);		
		map.addMapType(G_MAPMAKER_NORMAL_MAP);	
		if (!settings.addingAllowed)
			map.addMapType(G_SATELLITE_3D_MAP);
	    map.addControl(new GLargeMapControl3D());
		map.setMapType(settings.type);

		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		map.enableDoubleClickZoom();
		new GKeyboardHandler(map);

		hierarchy = new GHierarchicalMapTypeControl(); 
		hierarchy.addRelationship(G_NORMAL_MAP, G_MAPMAKER_NORMAL_MAP, lang.usermap, false);
		hierarchy.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, null, false);
		hierarchy.addRelationship(G_SATELLITE_MAP, G_PHYSICAL_MAP, null, false);
		if (!settings.addingAllowed)
			hierarchy.addRelationship(G_SATELLITE_MAP, G_SATELLITE_3D_MAP, null, false);
		map.addControl(hierarchy);
		
		if (settings.addingAllowed) {
			GEvent.addListener(map,"click",function(overlay,point){
				fn(point,settings.functionNotes);
				if (!overlay) {
					mapPutMarker(point,settings.addingAllowed,settings.markers);
					};
				});
			}; 
			
		GEvent.addListener(map,"movestart",function(){cluster.refresh();});	
			
		cluster = {markers:settings.markers, clusterMarkerIcon:plusIcon, clusterMarkerTitle:'%count',fitMapMaxZoom:14};
		cluster = new ClusterMarker(map,cluster);
		cluster.refresh();
		cluster.fitMapToMarkers();

	    function myclick(i) {
			GEvent.trigger(gmarkers[i], "click");
			};

		return map;
		};
	};
	
///////////////////////////////////////////////////////////////////////////////
///// TEXTS

function textCutPrepare(_parent) {
	var readMore = "<p class='readMore'><span onclick='return textCut(this.parentNode.parentNode,1);'>"+lang.readmore+"</span></p>";
	var readLess = "<p class='readMore'><span onclick='return textCut(this.parentNode.parentNode,0);'>"+lang.readless+"</span></p>";	
	var children = _parent.children;
	if (children.length>sys.leadParagraphs) {
		var full = new Array();
		for (var i=0;i<children.length;i++)
			full.push(getSelfHTML(children[i]));
		var lead = full.slice(0,sys.leadParagraphs).join('')+readMore;
		full = full.join('')+readLess;
		_parent.shorten = {'lead':lead,'full':full};
		} else
			_parent.shorten = false;
	textCut(_parent,false);
	return false;
	};

function textCut(_parent,showFull) {
	if (_parent.shorten)
		_parent.innerHTML = showFull ? _parent.shorten.full : _parent.shorten.lead;
	return false;
	};

///////////////////////////////////////////////////////////////////////////////
///// CSV inputs
	
function inputTransform(mainInput) {
	var data,list,listTitle,fieldset;

	data = $('#'+mainInput.title)[0];
	
	fieldset = mainInput.parentNode;	
	fieldset.id = mainInput.id+"_fieldset";
	fieldset.className = 'js_input';
	fieldset.clueURL = $('.js_inputClueURL',data)[0].value;
	
	list = $.makeArray($('.js_inputList',data));
	if (typeof(list)=='undefined') 
		list = [];
	for (j=0;j<list.length;j++) {
		listTitle = list[j].title+': ';
		list[j] = (typeof(list[j])!='undefined') ? list[j].value.explode() : false;
		for (i=0;i<list[j].length;i++) {
			list[j][i] = "<span onclick='inputAddRemove(1,this.innerHTML,\""+fieldset.id+"\")'>"+list[j][i]+"</span>";
			};
		list[j] = list[j].length ? "<div class='select'>"+listTitle+list[j].join(', ')+"</div>" : '';
		};
	list = list.join('');
	
	data.parentNode.removeChild(data);

	html = "<input type='text' id='"+mainInput.id+"' name='"+mainInput.id+"' value='"+mainInput.value+"' />";
	html+= "<span id='"+mainInput.id+"_list' class='inputList'></span><span class='input2'><input type='text' name='"+mainInput.id+"_input' id='"+mainInput.id+"_input' size='24' autocomplete='off' onkeyup='inputClueList(event,\""+fieldset.id+"\");' onblur='inputAddRemove(1,this.value,\""+fieldset.id+"\"); $(\"#"+fieldset.id+"\_clue\").hide();return false;' onclick='inputClueList(event,\""+fieldset.id+"\");' value='' /><hr /><ul id='"+mainInput.id+"_clue' class='clue'><li></li></ul></span>";
	html+= list;

	fieldset.innerHTML = html;
	
	
	fieldset.mainInput = mainInput;
	fieldset.clueInput = $('#'+mainInput.id+'_input')[0];
	fieldset.clueList = $('#'+mainInput.id+'_clue')[0];
	fieldset.selectList = $('#'+mainInput.id+'_list')[0];

	$('#'+mainInput.id).hide();
		//.bind('mouseover change',function(){inputCurrent(this.parentNode);});

	inputCurrent(fieldset);
	
	return true;
	};
	
	
function inputCurrent(fieldset) {
	fieldset = $('#'+fieldset.id)[0];
	var tags = $('#'+fieldset.mainInput.id)[0].value.explode();
	for (i=0;i<tags.length;i++) {
		tags[i] = "<span>"+tags[i]+"</span><del onclick='inputAddRemove(0,\""+tags[i]+"\",\""+fieldset.id+"\")'>"+String.fromCharCode(215)+"</del>";
		};
	fieldset.selectList.innerHTML = tags.join(' ');
	};
	

function inputClueScroll(fieldset,up) {
	var clueItems, text, sel;

	clueItems = $('li',$(fieldset.clueList));
	
	for (i=0;i<clueItems.length;i++) {
		if (clueItems[i].className=='sel') {
			sel = up ? (i ? i-1 : clueItems.length-1) : ((i==clueItems.length-1) ? 0 : i+1);
			clueItems[i].className = '';
			clueItems[sel].className = 'sel';
			
			text = $.trim(clueItems[sel].innerHTML);
			$(fieldset.clueInput).val(text);
			return text;
			};
		};
	sel = up ? clueItems.length-1 : 0;
	clueItems[sel].className = 'sel';
	$($('#'+fieldset)[0].clueInput).val($.trim(clueItems[sel].innerHTML))[0].focus();
	return text;
	};

function inputClueList(event,fieldset) {
	var clueInput,clueList,keyCode,input;
	fieldset = $('#'+fieldset)[0];
	clueInput = $(fieldset.clueInput)[0];
	clueList = $(fieldset.clueList)[0];

	if (window.event) event = window.event;
	keyCode = (event.keyCode ? event.keyCode : event.which ? event.which : null);
	
 	switch (keyCode) {
		case 27: 
		case 39: 
			$(clueList).empty().hide(); return false;
		case 38: fieldset.clue = inputClueScroll(fieldset,1); return false;
		case 40: fieldset.clue = inputClueScroll(fieldset,0); return false;
		case 13: return false;
		};
		
	input = clueInput.value.split(',');
	if (input.length>1) {
		return inputAddRemove(1,input[0],fieldset.id);
		};
	input = $.trim(input[0]);
	
	if (input.length<2) {
		$(clueList).fadeOut('fast');
		return false;
		};

	$(clueList).html('');
	cluesText = clues = [];

	clueURL = fieldset.clueURL.replace('%s',encodeURIComponent(input));
	ajax(clueURL,clueList,'GET',function() {
		fieldset.clues = clueList.innerHTML.explode();
		fieldset.clues.length ? $(clueList).fadeIn('fast') : $(clueList).fadeOut('fast');
		cluesText = '';
		for (i=0;i<fieldset.clues.length;i++) {
			cluesText+= "<li onclick='inputAddRemove(1,this.innerHTML,\""+fieldset.id+"\");'>";
			cluesText+= fieldset.clues[i]+"</li>";
			};
		$(fieldset.clueList).html(cluesText);
		});
	};

function inputAddRemove(addOrNot,tag,fieldset) {
	fieldset = $('#'+fieldset)[0];
	tag = $.trim(tag.replace(',',''));
	if (!tag.length) return;
	inputID = fieldset.mainInput.id;
	tagsOld = $('#'+inputID)[0].value.explode();
	if (addOrNot) {
		if ($.inArray(tag,tagsOld)==-1) {
			tagsOld.push(tag);		
			};
		tagsNew = tagsOld;
		} else {
			tagsNew = [];
			for (i=0;i<tagsOld.length;i++) {
				if (tagsOld[i]!=tag) tagsNew.push(tagsOld[i]);
				};			
			};
	tagsNew.sort();
	tagsNew = tagsNew.implode(', ');
	tagsNew+= tagsNew.length ? ', ' : '';
	$('#'+inputID).val(tagsNew).blur();
	inputCurrent(fieldset);
	$(fieldset.clueList).hide();
	$(fieldset.clueInput).val('').focus();
	};

///////////////////////////////////////////////////////////////////////////////
///// misc	

function pervertEm(mailarray) {
	var email = mailarray.join('');
	document.write(email.replace("%40",String.fromCharCode(64)).link('ma'+""+'ilto:'+email));
	};

function reallyDelete(_this) {
	$('#curtain').show();
	if (_this.checked && !confirm(lang.rDel))
		_this.checked = false;
	$('#curtain').hide();
	};
	
function emptyDate(name) {
	$('#'+name+',#'+name+'-m'+',#'+name+'-y'+',#'+name+'-bc').val('');
	};


