// JavaScript Document
//vars
var itemlist = [];
var markers = [];
var infowindows = [];
var map;

$(document).ready(function(){

  	//$("#tab_popular").tabs();
	$("#tab_category").tabs({ fxSlide: true });

	var myOptions = {
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

	map = new google.maps.Map(document.getElementById("location_map"), myOptions);
	var geocoder = new google.maps.Geocoder();
	//set mapcenter
	$.getJSON("/json/get_location_data",function(data){
		if (geocoder) {
      		geocoder.geocode( { 'address': data.location +', '+data.country}, function(results, status) {
        		if (status == google.maps.GeocoderStatus.OK) {
          			map.setCenter(results[0].geometry.location);
        		} else {
                                map.setCenter(new google.maps.LatLng(data.lat_loc, data.lng_loc));
        		}
      		});
    	}
	});

	$.getJSON("/json/get_location_items",
        function(data){
		  itemlist = data.items;
          $.each(data.items, function(i,item){
			var img = '/media/images/map-icons/'+item.tid+'.png';
                        var imgorig = '/media/images/map-icons/'+item.tid+'_orig.png';
			//add to list
			$('#cat-'+item.tid).append('&bull; <a href="#" onclick="moveMapTo('+i+')">'+item.nimi+'</a>&nbsp;&nbsp;&nbsp;');
			//add marker
			var marker = new google.maps.Marker({
				position: new google.maps.LatLng(item.lat, item.lng),
				map: map,
				title: item.nimi,
				clickable: true,
   			    icon: img
   		    });

			var infocontent = '<a id="marker_title" href="/'+sitelang+'/'+data.location+'/ravintola/'+item.URL+'">'+item.nimi+'</a>' +
                            '<br/>Lähiosoite: <strong>'+item.lahiosoite+'</strong>' +
                            '<br/>Tyyppi: <strong>'+item.tyyppinimi+'</strong>' +
                            '<br/>Tiedot on katsottu <strong>'+item.katsottu+'</strong> kertaa.';

			var infowindow = new google.maps.InfoWindow({
    			content: infocontent
			});

			google.maps.event.addListener(marker, 'click', function() {
  				infowindow.open(map,marker);
			});

			markers[i] = marker;
			infowindows[i] = infowindow;



        });
    });
});

function moveMapTo(index) {
	map.setCenter(new google.maps.LatLng(Number(itemlist[index].lat), Number(itemlist[index].lng)));
	infowindows[index].open(map,markers[index]);
}



