
var PrirodaKarlovarskaUI = function() {
	
	// privates
	var editMode = false;
	

	function addAsteriskForRequired()
	{
		$('form label.required').each(function () {
			$(this).html($(this).text() + '<span>*</span>');
		});
	}



	function fixFormLabels()
	{
		$('label img').click(function() {
			$(this).parent().trigger('click');
		});
	}
	


	function searchFieldStyling()
	{
		$('#q').attr('value', 'Hledaný výraz…')
			.css('color', '#777')
			.bind('focus', function() {
				if ($(this).attr('value') != 'Hledaný výraz…')
					return;
				$(this).attr('value', '').css('color', '#000');
			})
			.bind('blur', function() {
				if ($(this).attr('value'))
					return;
				$(this).attr('value', 'Hledaný výraz…').css('color', '#777');
			});
		$('#search form').bind('submit', function() {
			if ($('#q').attr('value') == '' || $('#q').attr('value') == 'Hledaný výraz…') {
				alert('Zadejte hledaný výraz…');
				return false;
			}
		});
	}
	


	function fadeOutFlashes()
	{
		setTimeout(function() {
			$('.flash').slideUp(750);
		}, 4000);
	}



	// publics
	return {

		init: function() {
			// volani rutin
			fixFormLabels();
			searchFieldStyling();
			addAsteriskForRequired();
			fadeOutFlashes();
		},
	

	
		/*** Google mapa **************************************************************/
		Map: function() {
			
			// privates
			var gm = google.maps;
			
			// druhy znacek
			var markImgs = {
				zivocich: new gm.MarkerImage(baseUri + 'images/mask/mark-zivocich.png', new gm.Size(21, 32), new gm.Point(0, 0), new gm.Point(10, 30)),
				rostlina: new gm.MarkerImage(baseUri + 'images/mask/mark-rostlina.png', new gm.Size(21, 32), new gm.Point(0, 0), new gm.Point(10, 30)),
				houba:    new gm.MarkerImage(baseUri + 'images/mask/mark-houba.png', new gm.Size(21, 32), new gm.Point(0, 0), new gm.Point(10, 30)),

				hrady_zamky_zriceniny: new gm.MarkerImage(baseUri + 'images/mask/mark-hrady-zamky-zriceniny.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35)),
				cirkevni_pamatky:      new gm.MarkerImage(baseUri + 'images/mask/mark-cirkevni-pamatky.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35)),
				jine_pamatky:          new gm.MarkerImage(baseUri + 'images/mask/mark-jine-pamatky.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35)),
				technicke_pamatky:     new gm.MarkerImage(baseUri + 'images/mask/mark-technicke-pamatky.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35)),
				chranena_uzemi:        new gm.MarkerImage(baseUri + 'images/mask/mark-chranena-uzemi.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35)),
				rozhledny:             new gm.MarkerImage(baseUri + 'images/mask/mark-rozhledny.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35)),
				vojenske_pamatky:      new gm.MarkerImage(baseUri + 'images/mask/mark-vojenske-pamatky.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35)),
				pamatne_stromy:        new gm.MarkerImage(baseUri + 'images/mask/mark-pamatne-stromy.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35)),
				naucne_stezky:         new gm.MarkerImage(baseUri + 'images/mask/mark-naucne-stezky.png', new gm.Size(24, 37), new gm.Point(0, 0), new gm.Point(12, 35))
			}
			var markShadow = new gm.MarkerImage(baseUri + 'images/mask/mark-shadow.png', new gm.Size(38, 24), new gm.Point(0, 0), new gm.Point(2, 20));
			
			var map;



			function getFinds(url)
			{
				var findTypeKeys = {
					1: 'rostlina',
					2: 'zivocich',
					3: 'houba'
				};
				
				$.getJSON(url, function(data) {
					$.each(data.marks, function(i, mark) {
						var ll, typ, druh;
						$.each(mark, function(col, value) {
							switch (col) {
							case 'latitude_longitude':
								ll = value.replace(new RegExp("[\\s}{]+", "g"), "").split(',');
								break;
							case 'typ':
								typ = findTypeKeys[value];
								break;
							case 'druh':
								druh = value;
								break;
							}
						});
						// vlozeni znacky a praporku s obsahem
						var marker = placeMark(new gm.LatLng(ll[0], ll[1]), typ, druh);
						gm.event.addListener(marker, 'click', function() {
							$.get(url, { id: mark.id }, function(html) {
								//alert(html);
								var infoWindow = new gm.InfoWindow({
									content: html,
									maxWidth: 400
								});
								infoWindow.open(map, marker);
							}, 'html');
						});
					});
				});
			}
			


			function getPoints(url)
			{
				var findTypeKeys = {
					1: 'hrady_zamky_zriceniny',
					2: 'cirkevni_pamatky',
					3: 'jine_pamatky',
					4: 'technicke_pamatky',
					5: 'chranena_uzemi',
					6: 'rozhledny',
					7: 'vojenske_pamatky',
					8: 'pamatne_stromy',
					9: 'naucne_stezky'
				};
				
				$.getJSON(url, function(data) {
					$.each(data.marks, function(i, mark) {
						var ll, typ, druh;
						$.each(mark, function(col, value) {
							switch (col) {
							case 'latitude_longitude':
								ll = value.replace(new RegExp("[\\s}{]+", "g"), "").split(',');
								break;
							case 'kategorie':
								typ = findTypeKeys[value];
								break;
							case 'nazev':
								druh = value;
								break;
							}
						});
						// vlozeni znacky a praporku s obsahem
						var marker = placeMark(new gm.LatLng(ll[0], ll[1]), typ, druh);
						gm.event.addListener(marker, 'click', function() {
							$.get(url, { id: mark.id }, function(html) {
								//alert(html);
								var infoWindow = new gm.InfoWindow({
									content: html,
									maxWidth: 400
								});
								infoWindow.open(map, marker);
							}, 'html');
						});
					});
				});
			}

			
			
			function bindEvents()
			{
				// umisteni znacky
				gm.event.addListener(map, 'click', function(e) {
					addMark(e.latLng);
				});
				
				// vybrani znacky pro umisteni
				$('#add-marks a').click(function() {
					editMode = !editMode;

					var markEl = $(this).parents('dl').hasClass('karlovarsko') ? 'img' : 'span';
					$(markEl, $(this).parents('dl')).css('visibility', 'visible');
					markImg = $(markEl, $(this).parent('dd'));
					markImg.css('visibility', 'hidden')
						.clone()
						.attr('id', markImg.attr('id').replace(/^mark-/, 'cursor-'))
						.appendTo('body')
						.addClass('cursor');
					
					return false;
				});
				
				// rezim editace znacky
				$('#edit-link').live('click', function() {
					$.get($(this).attr('href'), function(data) {
						for (var i in data.snippets) {
							jQuery.updateSnippet(i, data.snippets[i]);
						}
						shiftMap();
					});
					return false;
				});
				
				// zobrazeni vybrane znacky nad mapou pri kurzoru mysi 
				$('body').bind('mouseover', function() {
					$('.cursor').css('visibility', 'hidden');
				});
				$('#map-container').bind('mouseenter', function() {
					$('.cursor').css('visibility', 'visible');
				}).bind('mousemove', function(e) {
					$('.cursor').css({
						visibility: 'visible',
						left: e.pageX - 10,
						top:  e.pageY - 41
					});
				});
			}
			
			
			
			function addMark(location)
			{
				if (!editMode)
					return false;
				
				var type = $('.cursor').attr('id').replace(/^cursor-/, '').replace(/-/g, '_');
				$('.cursor').remove();
				var marker = placeMark(location, type, '(bez titulku)', true);
				$('span[id=mark-' + type + ']').css('visibility', 'visible')
				putFindDetailsInForm(location, type);
				
				shiftMap(location);
				
				// editace nove znacky
				gm.event.addListener(marker, 'dragend', function(e) {
					putFindDetailsInForm(this.get_position(), type);
				});
				
				editMode = false;
			}
			
			
			
			function shiftMap(location)
			{
				// zmenseni mapy vlevo
				$(map.getDiv()).animate({
					width: '50%'/*,
					borderRight: '1px solid #000'*/
				}, 700, 'swing', function() {
					// zacentrovani na novou znacky
					google.maps.event.trigger(map, 'resize');
					if (location) {
						map.panTo(location); 
					}
					$('#find-wrapper').slideDown(300);
				});
			}
			
			
			
			function putFindDetailsInForm(location, type)
			{
				$('input[name=latitude_longitude]').val(location.toString().replace(/\(/, '').replace(/\)/, ''));
				$('select[name=typ]').val(type);
				$('select[name=kategorie]').val(type);
			}
			
			
			
			function placeMark(location, type, title, isNew)
			{
				return new google.maps.Marker({
					position: location, 
					title:    title,
					icon:     eval('markImgs.' + type),
					shadow:   markShadow,
					map:      map,
					draggable: (isNew) ? true : false
				});
			}


		
			// publics
			return {
	
				// Inicializace
				init: function(lat, lon) {
                    
                    if (lat && lon) {
                        var lat = lat;
                        var lon = lon;
                        var zoom = 15;
                    } else {
                        var lat = 50.150506;
                        var lon = 12.987213;
                        var zoom = 10;
                    }
					
					// mapa
					var centerLatLng = new gm.LatLng(lat, lon);
					var mapOptions = {
						zoom: zoom,
						center: centerLatLng,
						mapTypeId: gm.MapTypeId.ROADMAP,
					};
					map = new gm.Map(document.getElementById('map-container'), mapOptions);
					
					// Udalosti
					bindEvents();
					
					return this;
				},
				
				
				
				placeFinds: function(url) {
					getFinds(url);
				},



				placePoints: function(url) {
					getPoints(url);
				},
				
				
				
				_otherPublicFunction: function() {
				}
			};
		}()
		
	};
}();

