function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

var markers = {};
var map;
var infowindow;
var pindisplay = true;

function showMarkers() {
        zoomLevel = map.getZoom();
        
        $.each(markers, function(index, element){
					var pos = element[1].getPosition();
					if((element[0]<=zoomLevel && (!element[2] || element[2]>=zoomLevel)) || (roundNumber(pos.lat(),12)==roundNumber(map_options.center[0],12) && roundNumber(pos.lng(),12)==roundNumber(map_options.center[1],12) && map_options.maptype=='poi')) {
						
            element[1].setVisible(true);
					} else {
						element[1].setVisible(false);
					}
				});
    }
    
    function showWin(point, marker, nolog) {
		var showOnMap = "";
      	if (infowindow) infowindow.close();
      	var imgid = 'mapimg_'+new Date().getTime();
      	var detailid = 'details_'+new Date().getTime();
      	var ausflug = '';

    		var map_lang = "de";
    		if($('html').attr('lang')){
    			map_lang = $('html').attr('lang');
    		}
    		
    		var myTrip = 'zu Tour hinzufügen';
    		var myDetails = 'Details';
    		if(map_lang == "en"){
    			myTrip = 'Add to journey';
    			myDetails = 'Details';
    		}else if(map_lang == "it"){
    			myTrip = 'Aggiungi all´itinerario';
    			myDetails = 'Dettagli';
    		}
    		
      	if(point.model=='ARPoi') {
        	ausflug = "<a href='javascript:void(0);' onClick=\"individual_tour.add('"+point.model+'_'+point.id+"');\">"+ myTrip +"</a></p>";
      	} else if(point.model=='ARCity') {
      	
        	ausflug = "<a href='javascript:void(0);' onClick=\"individual_tour.add('"+point.model+'_'+point.id+"');\">"+ myTrip +"</a></p>";
      	}
		  var mylink = '';
		  var myhref = '';
      if(point.link != '') {
         mylink = "<p><a href='"+point.link+"'>"+ myDetails +"</a><br />";
         myhref = "href='"+point.link+"'";
      }
      
          var addon = point.model == 'ARHotel' ? (point.premium ? 'iw_box_partner' : 'iw_box_hotel') : '';
					
    infowindow = new google.maps.InfoWindow({
			
      content: "<div class='iw_box "+addon+"'><a "+myhref+" class='iw_box_img'><img id='"+imgid+"' width='75' height='75'/></a>"+
						"<h4>"+point.name+"</h4>"+
						"<h5>"+point.type+"</h5><div id='"+detailid+"' class='mappopup_details'></div>"+
						mylink+
						ausflug+
						"</div>"
			});
			
      
			infowindow.open(map, marker);
			
			if(typeof map_options.country != 'undefined') {
        map.panTo(marker.getPosition());
      }
			
			$.ajax({
        url: '/img/?name='+point.img,
        success: function(data) {
          setTimeout(function(){$('#'+imgid).attr('src', data);}, 10);
          setTimeout(function(){$('#'+imgid).attr('src', data);}, 100);
          setTimeout(function(){$('#'+imgid).attr('src', data);}, 200);
          setTimeout(function(){$('#'+imgid).attr('src', data);}, 300);
          setTimeout(function(){$('#'+imgid).attr('src', data);}, 400);
          setTimeout(function(){$('#'+imgid).attr('src', data);}, 800);
          setTimeout(function(){$('#'+imgid).attr('src', data);}, 1500);
          setTimeout(function(){$('#'+imgid).attr('src', data);}, 3000);
        }
      });
			
			if(point.model == 'ARHotel') {
         $.ajax({
            url: '/hotels/popup/?id='+point.id+'&language='+website_settings.language,
            success: function(data) {
                if(typeof nolog == 'undefined') {
                  logger.log(point.id, 'popup');
                }
                setTimeout(function(){$('#'+detailid).html(data);}, 10);
                setTimeout(function(){$('#'+detailid).html(data);}, 100);
                setTimeout(function(){$('#'+detailid).html(data);}, 200);
                setTimeout(function(){$('#'+detailid).html(data);}, 300);
                setTimeout(function(){$('#'+detailid).html(data);}, 400);
                setTimeout(function(){$('#'+detailid).html(data);}, 800);
                setTimeout(function(){$('#'+detailid).html(data);}, 1500);
                setTimeout(function(){$('#'+detailid).html(data);}, 3000);
                
            }
         });
      }
			
    }

$(document).ready(function(){
	
	if($('#location-map').length){
		
		var thisLocation = "";
		
		function initialize(el,zooml) {
			var latlng = new google.maps.LatLng(map_options.center[0], map_options.center[1]);
			var mapsZoom = map_options.zoom;
			if(zooml != 0){
				mapsZoom = map_options.zoom+zooml;
			}
			
			var myOptions = {
				zoom: mapsZoom,
				minZoom: 5,
				center: latlng,
				mapTypeControl: false,
				panControl: false,
				zoomControl: true,
				streetViewControl: false,
				zoomControl: true,
				zoomControlOptions: {
					style: google.maps.ZoomControlStyle.LARGE,
					position: google.maps.ControlPosition.LEFT_CENTER
				},
				scaleControl: false,				
				scrollwheel: false,
				mapTypeId: map_options.zoom > 10 ? google.maps.MapTypeId.ROADMAP : google.maps.MapTypeId.TERRAIN
			};
			map = new google.maps.Map(document.getElementById(el),myOptions);
			
			function centerScaleMap(px,py){
				map.setCenter(new google.maps.LatLng(px, py));
			}
			function setNewMarker(point){
			   
				iconSize = new Array(22,26,11,26);
				shadowSize = new Array(32,20,8,20);
				iconShadow = '/images/map/icon-shade.png';
				var showOnMap = "";
				if(point.icon.indexOf('region') != -1 || point.icon.indexOf('dark') != -1 || point.icon.indexOf('green') != -1){
					iconSize = new Array(24,24,12,24);
					shadowSize = new Array(38,26,14,21);
					iconShadow = '/images/map/icon-round-shade.png';
					//showOnMap = " <a href='javascript:centerScaleMap("+point.x+","+point.y+")'>Auf Karte vergrößern</a>";
				}
				point.icon = point.icon ? point.icon : 'icon-poi.png';
				var image = new google.maps.MarkerImage('/images/map/'+point.icon,
					new google.maps.Size(iconSize[0],iconSize[1]),
					new google.maps.Point(0,0),
					new google.maps.Point(iconSize[2],iconSize[3]));
				var shadow = new google.maps.MarkerImage(iconShadow,
					new google.maps.Size(shadowSize[0],shadowSize[1]),
					new google.maps.Point(0,0),
					new google.maps.Point(shadowSize[2],shadowSize[3]));

	    		var visible = false;
				
	    		if(point.zoom<=map_options.zoom) {
            visible = true;
  				}
		
	 			var marker = new google.maps.Marker({
	 				map: map,
	     			position: new google.maps.LatLng(point.x, point.y),
	     			visible: visible,
	     			shadow: shadow,
	     			icon: image,
	     			title: point.name
	 			});
	
				markers[point.model+'_'+point.id] = [point.zoom,marker,point.until,point];
	
				google.maps.event.addListener(marker, "click", function() {
					showWin(point, marker);
				});
				
				showMarkers();
				
				return marker;				
			}
			
			if(typeof map_options != 'undefined') {
				$.each(map_options.points, function(index, point) {
		            setNewMarker(point);
		        });
			}
			
			google.maps.event.addListener(map, 'zoom_changed', function() {
			    zoomLevel = map.getZoom();
				if(zoomLevel > 10){
					map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
				}else{
					map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
				}
				
				showMarkers(); 
			});
			
			/* POI CLICK EVENTS */
			if($('.poi-item .poi-showmap, .regions-item .regions-showmap').length){
				$('.poi-item .poi-showmap, .regions-item .regions-showmap').click(function(event){
					event.preventDefault();
					var el = this;
					window.setTimeout(function() {
						if(typeof markers[$(el).attr('rel')] != 'undefined') {
                map.setCenter(markers[$(el).attr('rel')][1].getPosition());
                map.setZoom(parseInt(markers[$(el).attr('rel')][3].zoom));
                showWin(markers[$(el).attr('rel')][3], markers[$(el).attr('rel')][1]);
            }
						$('html,body').animate({
							scrollTop: $('#content-map').offset().top-60
						}, 1000, function(){
							$('#location-map').animate({
								'opacity':0.2
							},220, function(){
								$('#location-map').animate({
									'opacity':1
								},110, function(){
								    
								});
							});
						});
						
					
					}, 200);
				});
			}
			
			/* SHOW HIDE PINS */
			if($('#map-pin-control')){
				$('#map-pin-control').click(function(event){
					event.preventDefault();
					if(pindisplay) {
  					$.each(markers, function(index, element){
  					 element[1].setVisible(false);
  					});
  					
  					pindisplay = false;
					} else {
            showMarkers();
            pindisplay = true;
          }
				});
			}
			
			if(typeof map_options.setactive != 'undefined' && map_options.setactive) {
        setTimeout(function() {
          showWin(markers[map_options.setactive][3], markers[map_options.setactive][1], true);
        }, 2000);
      }
			
		}
		
    
    
    initialize("location-map",0);
		
		
    
    
		
		if($('#map-zoom').length || $('#map-small').length || $('.poi-showmap').length){
			$('body').append('<div id="map-big"></div><div id="map-overlay"></div>');
			function makeItBig(zoomle){
				//$('#map-big').css({'width':$(window).width()-120,'height':$(window).height()-120,'opacity':0,'display':'block'});
				$('#map-big').css({'width':$(window).width()-120,'height':$(window).height()-120,'display':'block'});
				$('#map-overlay').css({'height':$(document).height(),'opacity':0,'display':'block'});
				$('#map-overlay').animate({
					'opacity':0.87
				}, 600, function() {
					initialize("map-big",zoomle);
					/*$('#map-big').animate({
						'opacity':1
					}, 600, function() {
					});*/
			  	});
			}
			if($('#map-zoom').length){
				$('#map-zoom').click(function(event){
					event.preventDefault();
					makeItBig(2);
				});
			}
			if($('#map-small').length){
				$('#map-small').click(function(event){
					event.preventDefault();
					makeItBig(2);
				});
			}
			if($('#poi-action .poi-showmap').length){
				$('.poi-showmap').click(function(event){
					event.preventDefault();
					makeItBig(2);
				});
			}
			$('#map-overlay').click(function(event){
				event.preventDefault();
				/*$('#map-big').animate({
					'opacity':0
				}, 700, function() {
					$('#map-big').css({'display':'none'});
			  	});*/
				$('#map-big').css({'display':'none'});
				$('#map-overlay').animate({
					'opacity':0
				}, 700, function() {
					$('#map-overlay').css({'display':'none'});
			  	});
			});
		}
		
	}
});
