var txSolarplantsPi1 = {
	loading: false,
	icons: {},
	loadedComments: {},
	commentForms: {},
	searchFormFx: false,
	slimboxEnabled: {},
	clusteringEnabled: false,
	
	
	setupMap:	function(toggleSearch, showSearchForm) {
		var point = new GLatLng(46.9127509564, 8.19580078125);
		
		if(toggleSearch == true) {
			this.searchFormFx = new Fx.Slide($('solarplants-search')).hide();
		
			$$('#solarplants-search-header a').addEvent('click', function(event){
				new Event(event).stop();
				
				txSolarplantsPi1.searchFormFx.toggle();
	 		});
		}
		
		this.map = new GMap2($('map'));

		this.map.setCenter(point, 8);
		
		this.map.setUIToDefault();
		this.map.setMapType(G_PHYSICAL_MAP );
		
		new GKeyboardHandler(this.map);

		this.setupIcons();
		
		if(showSearchForm) {
			this.initForm();
			this.geocodeClient = new GClientGeocoder();
			this.geocodeClient.setBaseCountryCode('ch');
		}
		
		this.setupClustering();
		
		this.initMarkers();
	},
	
	setupMapSingle: function(plant, zoom) {
		var point = new GLatLng(plant.latitude, plant.longitude);
		
		this.map = new GMap2($('map'));

		this.map.setCenter(point, zoom);
		
		this.map.setUIToDefault();
		this.map.setMapType(G_PHYSICAL_MAP );
		
		this.setupIcons();
		
		var marker = this.createMarkerAndDrawOnMap(plant, true);
		
		GEvent.addListener(marker, "dragend", function() {
			$("tx_solarplants_pi2data_latitude").value = marker.getLatLng().lat();
			$("tx_solarplants_pi2data_longitude").value = marker.getLatLng().lng();
			GEvent.trigger(marker, 'click');
		});
		
		GEvent.addListener(marker, "dragstart", function() {
			marker.closeInfoWindow();
		});
		
		GEvent.trigger(marker, 'click');
	},

	setupIcons: function() {
		this.icons['cluster'] = new GIcon(G_DEFAULT_ICON);
		this.icons['cluster'].image = "/typo3conf/ext/solarplants/res/markerCluster.png";
		this.icons['cluster'].iconSize = new GSize(18, 15);
		this.icons['cluster'].iconAnchor = new GPoint(7, 7);
		this.icons['cluster'].shadow = "/typo3conf/ext/solarplants/res/markerClusterShadow.png";
		this.icons['cluster'].shadowSize = new GSize(18,15);
		this.icons['cluster'].printImage = this.icons['cluster'].image;
		this.icons['cluster'].mozPrintImage = this.icons['cluster'].image;
		this.icons['cluster'].printShadow = this.icons['cluster'].shadow;
		this.icons['cluster'].infoWindowAnchor = new GPoint(7, 7);
		
		this.icons[1] = new GIcon(G_DEFAULT_ICON);
		this.icons[1].image = "/typo3conf/ext/solarplants/res/markerRealised.png";
		this.icons[1].iconSize = new GSize(10, 10);
		this.icons[1].iconAnchor = new GPoint(5, 5);
		this.icons[1].shadow = "/typo3conf/ext/solarplants/res/markerShadow.png";
		this.icons[1].shadowSize = new GSize(10,10);
		this.icons[1].printImage = this.icons[1].image;
		this.icons[1].mozPrintImage = this.icons[1].image;
		this.icons[1].printShadow = this.icons[1].shadow;
		this.icons[1].infoWindowAnchor = new GPoint(5, 5);
		
		this.icons[2] = new GIcon(G_DEFAULT_ICON);
		this.icons[2].image = "/typo3conf/ext/solarplants/res/markerPlaned.png";
		this.icons[2].iconSize = new GSize(10, 10);
		this.icons[2].iconAnchor = new GPoint(5, 5);
		this.icons[2].shadow = "/typo3conf/ext/solarplants/res/markerShadow.png";
		this.icons[2].shadowSize = new GSize(10,10);
		this.icons[2].printImage = this.icons[2].image;
		this.icons[2].mozPrintImage = this.icons[2].image;
		this.icons[2].printShadow = this.icons[2].shadow;
		this.icons[2].infoWindowAnchor = new GPoint(5, 5);
 	},
	
 	setupClustering: function() {
 		this.cluster = new ClusterMarker(this.map, {
			clusterMarkerTitle : txSolarplantsPi1LLL.clickZoom,
			clusterMarkerIcon: this.icons['cluster'],
			intersectPadding: 10
		});
		
		this.clusteringEnabled = true;
 	},
 	
 	initForm: function() {
 		$('solarplants-search-form').addEvent('submit', function(event){
			new Event(event).stop();
			
			txSolarplantsPi1.search();
 		});
 		
 		$('solarplants-search-location').addEvent('focus', function(event){
 			this.value = '';
 		});
 		
 		$('solarplants-search-location').addEvent('blur', function(event){
 			if(this.value == '') {
 				this.value = txSolarplantsPi1LLL.defaultLocation;
 			}
 		});
	},
	
	search: function() {
		if(this.loading == true) {
			return false;
		}
		
		var submit = $('solarplants-search-submit');
		if(submit) {
			submit.set({
				'value' : txSolarplantsPi1LLL.searchLoading,
				'disabled': 'disabled'
			});
		}
		
		this.loading = true;
	
		var location = $('solarplants-search-location').value;
		if(location && location!=txSolarplantsPi1LLL.defaultLocation) {
			this.geocodeLocation(location);
		} else {
			this.refreshMarkers();
		}	
	},
	
	geocodeLocation: function(location) {
		this.geocodeClient.getLocations(location+', Schweiz', function(response) {
			if (response && response.Status.code == 200) {
				
				var latLonBox = response.Placemark[0].ExtendedData.LatLonBox;
				var sw = new GLatLng(latLonBox.west,latLonBox.south);
				var ne = new GLatLng(latLonBox.east,latLonBox.north);
	
				var zoom = txSolarplantsPi1.map.getBoundsZoomLevel(new GLatLngBounds(sw, ne));
	
				txSolarplantsPi1.map.setCenter(new GLatLng(response.Placemark[0].Point.coordinates[1], response.Placemark[0].Point.coordinates[0]), zoom);
			}
			
			txSolarplantsPi1.refreshMarkers();
		});
	},
 	
 	initMarkers: function() {
 		this.refreshMarkers();
 	},
 	
 	refreshMarkers: function() {
 		this.map.clearOverlays();
 		this.loadedComments = {};
 		this.commentForms = {};
 		this.slimboxEnabled = {};
 		
 		
 		var request = new Request.JSON({
			'url' : 'index.php?eID=tx_solarplants_pi1&lang='+txSolarplantsLang,
			onComplete: function(jsonObj) {
				this.setMarkers(jsonObj);
				
				var submit = $('solarplants-search-submit');
				if(submit) {
					submit.set({
						'value' : txSolarplantsPi1LLL.searchSubmit,
						'disabled': ''
					});
				}
				
				this.loading = false;
			}.bind(this)
		}).post($('solarplants-search-form'));
 	},
 	
	setMarkers: function(jsonObj) {
		this.markersOnMap = [];

		var length = jsonObj.length;
		var i=0;
		for(i=0; i < length; i++) {
			if(!jsonObj[i].uid) {
				break;
			}
			
			var marker = this.createMarkerAndDrawOnMap(jsonObj[i], false);
			this.markersOnMap.push(marker);
		}

		//enable clustering for markers
		if(this.clusteringEnabled == true) {
			this.refreshClustering();
		}
	},
	
	refreshClustering: function() {
		this.cluster.removeMarkers();
		this.cluster.addMarkers(this.markersOnMap);
		this.cluster.refresh(true);
	},
	
	createMarkerAndDrawOnMap: function(markerObj, draggable) {
		var options = {
			icon: this.icons[markerObj.status_code],
			draggable: draggable
		};
	
		var marker = new GMarker(new GLatLng(markerObj.latitude, markerObj.longitude), options);
		
		marker.bindInfoWindowTabsHtml(this.createMarkerTabs(markerObj), {maxWidth: 500});
		
		marker.markerObj = markerObj;
		
		GEvent.addListener(marker, "infowindowopen", function() {
			txSolarplantsPi1.getComments(marker.markerObj);
			txSolarplantsPi1.initMarkerSlimbox(marker.markerObj.uid);
		});
		
		GEvent.addListener(marker, "infowindowclose", function() {
			if(txSolarplantsPi1.commentForms[marker.markerObj.uid]) {
				//if there is an open form hide it
				txSolarplantsPi1.commentForms[marker.markerObj.uid].hide();
			}
		});
		
		if(this.clusteringEnabled == false) {
			this.map.addOverlay(marker);
		}
		
		return marker;
	},
	
	createMarkerTabs: function(markerObj) {
		tabs = [];
		
		tabs.push(this.createMarkerTabDetail(markerObj));
		
		var images = markerObj.images;

		if(images.length > 0) {
			tabs.push(this.createMarkerTabImages(images, markerObj.uid));
		}
		
		if(markerObj.uid != null) {
			tabs.push(this.createMarkerTabComments(markerObj));
		}
		return tabs;
	},
	
	createMarkerTabDetail: function(markerObj) {
		var tabHtml = '<div class="solarplants-tooltip-tab-content">'
			+ '<h3>'+markerObj.plant_type+' '+markerObj.capacity+'</h3>'
			+ '<p><strong>'+markerObj.title+'</strong></p>'
			+ '<p>('+markerObj.status+markerObj.additional_info+')'
			+ markerObj.waitinglist_kev+'</p>';
			
		if(markerObj.plant_type_number == 2) {
			tabHtml = tabHtml
				+ '<p>'+markerObj.planed_capacity+'</p>';
		}
		
		tabHtml = tabHtml	
			+ '<p>'+markerObj.description.replace(/([^>]?)\n/g, '$1<br />\n')+'</p>'
			+ '</div>';
	
		return new GInfoWindowTab(txSolarplantsPi1LLL.tooltipLabel1, tabHtml);
	},
	
	createMarkerTabImages: function(images, uid) {
		var tabHtml = '<div id="solarplants-tooltip-tab2-'+uid+'" class="solarplants-tooltip-tab-content">';
	
		var j = 1;
		var imgClass = '';
		
		var i;
		var length = images.length;
		for(i=0; i<length; i++) {
			if(!images[i].thumb) {
				break;
			}
			
			switch(j) {
				case 1:
					imgClass = 'first';
					j++;
				break;
				case 3:
					imgClass = 'last';
					j++;
				break;
				default:
					imgClass = 'normal';
					j++;
				break;
			}
			
			tabHtml = tabHtml+'<a href="'+images[i].orig+'" target="_blank"><img class="'+imgClass+'" src="'+images[i].thumb+'"  /></a>';
		
			if(j == 4) {
				tabHtml = tabHtml+'<div class="clear">&nbsp;</div>';
				j = 1;
			}
		}
		
		tabHtml = tabHtml+'</div>';

		return new GInfoWindowTab(txSolarplantsPi1LLL.tooltipLabel2, tabHtml);
	},
	
	createMarkerTabComments: function(markerObj) {
		var uid = markerObj.uid;
	
		tabHtml = '<div id="solarplants-tooltip-tab3-'+uid+'" class="solarplants-tooltip-tab-content">'
			+ '<div id="solarplants-tooltip-comments-add-'+uid+'" class="solarplants-tooltip-comments-add"><a onclick="return txSolarplantsPi1.toggleCommentsForm(\''+uid+'\'); return false;" href="#">'+txSolarplantsPi1LLL.formCommentAdd+'</a></div>'
			+ '<div id="solarplants-tooltip-comments-'+uid+'" class="solarplants-tooltip-comments"></div>'
			+ '</div>';
	
		return new GInfoWindowTab(txSolarplantsPi1LLL.tooltipLabel3, tabHtml);
	},
	
	toggleCommentsForm: function(uid) {
		if(!this.commentForms[uid]) {
			this.createCommentsForm(uid);
		}
		
		this.commentForms[uid].toggle();
		
		return false;
	},
	
	createCommentsForm: function(uid) {
		var form  = new Element('form', {
			'id': 'solarplants-tooltip-comments-form-'+uid
		});
		
		new Element('label', {
			'class': 'solarplants_tooltip-comments-form-label',
			'html' : txSolarplantsPi1LLL.formCommentName
		}).injectInside(form);
		
		new Element('input', {
			'type': 'text',
			'class': 'solarplants_tooltip-comments-form-input',
			'name': 'tx_solarplants_pi1[comment_name]'
		}).injectInside(form);
		
		new Element('label', {
			'class': 'solarplants_tooltip-comments-form-label',
			'html' : txSolarplantsPi1LLL.formCommentText
		}).injectInside(form);
		
		new Element('textarea', {
			'class': 'solarplants_tooltip-comments-form-input',
			'name': 'tx_solarplants_pi1[comment_text]'
		}).injectInside(form);
		
		new Element('input', {
			'type': 'hidden',
			'name': 'tx_solarplants_pi1[comment_date]'
		}).injectInside(form);
		
		new Element('input', {
			'type': 'hidden',
			'name': 'tx_solarplants_pi1[parent_uid]',
			'value': uid
		}).injectInside(form);
		
		new Element('input', {
			'type': 'submit',
			'class': 'solarplants_tooltip-comments-form-input solarplants_tooltip-comments-form-submit',
			'name': 'tx_solarplants_pi1[comment_submit]',
			'value': txSolarplantsPi1LLL.formCommentSubmit
		}).injectInside(form);
		
		new Element('div', {
			'class': 'clear',
			'html': '&nbsp;'
		}).injectInside(form);
		
		form.addEvent('submit', function(event){
			new Event(event).stop();
			
			txSolarplantsPi1.sendCommentForm(this);
 		}.bind(uid));
		
 		form.injectInside($('solarplants-tooltip-comments-add-'+uid));
 		
		this.commentForms[uid] = new Fx.Slide(form);
		this.commentForms[uid].hide();
	},
	
	sendCommentForm: function(uid) {
		var request = new Request.JSON({
			'url' : 'index.php?eID=tx_solarplants_pi1&type=postComment',
			onComplete: function(jsonObj) {
				this.completeCommentForm(jsonObj);
			}.bind(this)
		}).post($('solarplants-tooltip-comments-form-'+uid));
	},
	
	completeCommentForm: function(jsonObj) {
		var uid = jsonObj.uid;
	
		this.commentForms[uid].slideOut().chain(function(jsonObj){
			var uid = jsonObj.uid;
				
			$('solarplants-tooltip-comments-form-'+uid).dispose();
			this.commentForms[uid] = false;
			
			if(jsonObj.comment) {
				var commentDiv = this.addSingleComment(uid, jsonObj.comment, 'top');
				new Fx.Slide(commentDiv).hide().slideIn();
			}
		}.pass(jsonObj, this));
	},
	
	getComments: function(markerObj) {
		var uid = markerObj.uid;
		
		if(this.loadedComments[uid] || uid == null) {
			//comments already loaded return	
			return true;
		} 
		
		this.loadedComments[uid] = true;

		if(markerObj.comments == '0') {
			//no comments display text
			var div = new Element('div', {
				'class': 'solarplants-tooltip-comments-comment',
				'id': 'solarplants-tooltip-comments-no-comment-'+uid
			});
			
			new Element('p', {
				'html': txSolarplantsPi1LLL.noComments
			}).injectInside(div);

			div.injectInside($('solarplants-tooltip-comments-'+uid));
		} else {
			var request = new Request.JSON({
				'url' : 'index.php?eID=tx_solarplants_pi1&type=getComments&tx_solarplants_pi1[showUid]='+uid,
				onComplete: function(jsonObj) {
					this.addComments(jsonObj);
				}.bind(this)
			}).send();
		}	
	},
	
	addComments: function(jsonObj) {
		var i;
		var length = jsonObj.comments.length; 
		for(i=0; i<length; i++) {
			if(!jsonObj.comments[i].uid) {
				break;
			}
			this.addSingleComment(jsonObj.uid, jsonObj.comments[i], 'bottom');
		}
	},
	
	addSingleComment: function(markerUid, commentObj, where) {
		var noComment = $('solarplants-tooltip-comments-no-comment-'+markerUid);
		if(noComment) {
			noComment.dispose();
		}
		
		var div = new Element('div', {
			'class': 'solarplants-tooltip-comments-comment'
		});
		
		var header = new Element('h6', {
			'html': commentObj.name+' '
		}).injectInside(div);
		
		new Element('span', {
			'html': commentObj.date,
			'class': 'solarplants-tooltip-comments-comment-date'
		}).injectInside(header);
		
		new Element('p', {
			'html': commentObj.text.replace(/([^>]?)\n/g, '$1<br />\n'),
			'class': 'solarplants-tooltip-comments-comment-text'
		}).injectInside(div);

		div.inject($('solarplants-tooltip-comments-'+markerUid), where);
		
		return div;
	},
	
	initMarkerSlimbox: function(uid) {
		if(this.slimboxEnabled[uid]) {
			return false;
		}
		
		this.slimboxEnabled[uid] = true;
		if($$('#solarplants-tooltip-tab2-'+uid+' a').length > 0) {
			$$('#solarplants-tooltip-tab2-'+uid+' a').slimbox();
		}
	}
}
