var map;                        
var markers = [];    
var infowindow = new google.maps.InfoWindow();

var cities = {
  "vilnius": {
    "latitude":  54.6893865,
    "longitude": 25.2800243,
    "id": 49
  },
  "kaunas": {
    "latitude":  54.8968721,
    "longitude": 23.8924264,
    "id": 13
  },
  "klaipeda": {
    "latitude":  55.6985409,
    "longitude": 21.1473174,
    "id": 18
  },
  "siauliai": {
    "latitude":  55.9320758,
    "longitude": 23.3142194,
    "id": 36
  },
  "panevezys": {
    "latitude":  55.7374357,
    "longitude": 24.3703332,
    "id": 28
  }
};    


google.maps.Marker.prototype.myData = new Array();

google.maps.Marker.prototype.addMyData = function(mydata) {
    this.myData = mydata;
};

google.maps.Marker.prototype.getMyData = function() {  
    return this.myData
};    


google.maps.Map.prototype.markers = new Array();

google.maps.Map.prototype.addMarker = function(marker) {
    this.markers.push(marker);
};

google.maps.Map.prototype.getMarkers = function() {
    return this.markers
};

google.maps.Map.prototype.clearMarkers = function() {  
   	jQuery.each(this.markers, function() {  
		this.setMap(null);
	});

    this.markers = new Array();
};

google.maps.Map.prototype.setDefaultMarkersIcon = function() {  
   	jQuery.each(this.markers, function() { 
		if(this.getIcon().indexOf('blue'))
			this.setIcon('/img/site/map/default.png');
	});
};


function initialize() {     
	var myLatlng = new google.maps.LatLng(cities.vilnius.latitude, cities.vilnius.longitude);
	var myOptions = {
		zoom: 15,
		center: myLatlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		disableDefaultUI: true
	}
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);


  
	$('#GuideCity').change(function() {
		var city = new google.maps.LatLng(cities[$(this).val()]['latitude'], cities[$(this).val()]['longitude']); 
		
		map.setCenter(city);   
		map.setZoom(15);

		return false;
	});    
	
    
	$('#GuideSearch').keyup(function() {  
        $('#results_content .marker_href').each(function() {   
			if(($(this).text().toLowerCase()).indexOf($('#GuideSearch').val()) == 0)
				$(this).parent().show();
			else
				$(this).parent().hide();
    	});
	});    
	
	$('#GuideSearch').watermark('Pavadinimas...'); 


	$('#GuideMapType').change(function() {  
		map.setOptions( {mapTypeId: $(this).val() == 'map' ? google.maps.MapTypeId.ROADMAP : google.maps.MapTypeId.SATELLITE} );
	});    

    
	$('#GuideType').change(function() { 
		$('.nav').hide();
		$('#nav_'+$('#GuideType').val()).fadeIn(1000);  
	});
 
	$('#nav_'+$('#GuideType').val()).fadeIn(1000);  
		
           
	$('#nav_catalog a').click(function() {    
		
		$('#results_title').html($(this).text());
		
		if($('#results').css('display') != 'block')
			$('#results').fadeIn();
		
		cat = $(this).attr('rel');
		
		$('#nav_catalog a').removeClass('selected');

		$(this).addClass('selected');
		
		$('#loading').fadeOut(100); 
	
		$.ajax({
			url: "/get_places/"+cat+'/'+cities[$('#GuideCity').val()].id,
			beforeSend: function() { $('#loading').show() },    
			dataType: "json",   
			cache: false,
			success: function(json, textStatus){ setMarkers(json); $('#loading').hide();}
 		});
		
		
		map.setCenter(new google.maps.LatLng(cities[$('#GuideCity').val()].latitude, cities[$('#GuideCity').val()].longitude));   
		map.setZoom(15);
		
		return false;
	});   
	

	$('#coords_submit').click(function() { 
		$.post("/save_coords", $("#coords_form").serialize(), function(){ $('#dragged_message').fadeOut() }); 

 		return false;
	});
	
}


function setMarkers(json) {     
	
	map.clearMarkers();    
	
	infowindow.close(); 
    
    if($('#results_content ul').length == 0)
    	$('<ul></ul>').appendTo('#results_content');
    else
		$('#results_content ul').empty();
	
	jQuery.each(json, function() {   
  		place = new google.maps.LatLng(this.Coordinate.latitude, this.Coordinate.longitude);

		var marker = new google.maps.Marker({
			position: place, 
			draggable: true, 
			map: map,
			title: this.Company.name,   
        	icon : '/img/site/map/default.png'
		});  

		marker.addMyData(this);
		map.addMarker(marker);

		google.maps.event.addListener(marker, 'click', function() {
        	map.setDefaultMarkersIcon();

			if(marker.getIcon().indexOf('blue') == -1)
        		marker.setIcon('/img/site/map/default_blue.png');
        	else	
            	marker.setIcon('/img/site/map/default.png'); 

			map.setCenter(marker.getPosition());   
			
			place = marker.getMyData();

			infowindow.setContent(getPlaceHtml(marker.getMyData()));
			infowindow.setPosition(marker.getPosition());
			infowindow.open(map, marker); 
		});

		google.maps.event.addListener(marker, 'mouseover', function() {    
			if(marker.getIcon().indexOf('blue') == -1)
            	marker.setIcon('/img/site/map/default_yellow.png');
		});

		google.maps.event.addListener(marker, 'mouseout', function() {
			if(marker.getIcon().indexOf('blue') == -1)
            	marker.setIcon('/img/site/map/default.png');
		});

		google.maps.event.addListener(marker, 'dragend', function() {  
   			place  = marker.getMyData();
   			LatLng = marker.getPosition();  

			$('#dragged_message').fadeIn(); 
			$('#dragged_message #coords').html(LatLng.lat()+', '+LatLng.lng());   
			
			$('#CoordinateId').val(place.Company.id);
			$('#CoordinateLatitude').val(LatLng.lat());
			$('#CoordinateLongitude').val(LatLng.lng());
		});


        $('<li><a href="#" class="marker_href">'+this.Company.name+'</a></li>').appendTo('#results_content ul').find('.marker_href').click(function() {
        	map.setDefaultMarkersIcon();

			if(marker.getIcon().indexOf('blue') == -1)
        		marker.setIcon('/img/site/map/default_blue.png');
        	else	
            	marker.setIcon('/img/site/map/default.png'); 

			map.setCenter(marker.getPosition());   
			
			place = marker.getMyData();

			infowindow.setContent(getPlaceHtml(marker.getMyData()));
			infowindow.setPosition(marker.getPosition());
			infowindow.open(map, marker); 

        	return false;
        });  
	});    
}	
	
function getPlaceHtml(item) {
	str = '';
	str += '<div class="infowindow_content">';
	str += '<div class="title">'+item.Company.name+'</div>';
	str += '<div class="content">'+item.Company.address+'</div>';
	
	if(item.Company.telephone != 'null' && item.Company.telephone != '') {
		str += '<div class="content">'+item.Company.telephone+'</div>';
	}
		
	if(item.Company.url != 'null' && item.Company.telephone != '') {
		str += '<div class="content"><a href="http://'+item.Company.url+'" target="_blank">'+item.Company.url+'</a></div>';
	}
		
	//str += '<div class="content"><a href="#" onclick="setDraggableMarker">Keisti koordinates</a></div>';

	str += '<div class="content aright"><a href="http://einam.lt/'+item.Category.url+'/'+item.Company.id+'" class="read_more" target="_blank">Daugiau...</a></div>';
		
	str += '</div>';

	return str;
}        


function scrollWin(el_id){
	$('html, body').animate({
		scrollTop: $("#"+el_id).offset().top
	}, 1000);
}
