//Useful links:
// http://code.google.com/apis/maps/documentation/javascript/reference.html#Marker
// http://code.google.com/apis/maps/documentation/javascript/services.html#Geocoding
// http://jqueryui.com/demos/autocomplete/#remote-with-cache 
var center;
var radius = 5;
var map;
var markers;
function initialize(){
	//MAP

	//var map;
	var zoomLevel = (typeof(arguments[2]) == 'number') ? parseInt(arguments[2]) : 2;
	var placeLat = (arguments[0].length >= 3) ? arguments[0] : '42.733883';
	var placeLon = (arguments[1].length >= 3) ? arguments[1] : '25.48583';

	var latlng = new google.maps.LatLng(placeLat,placeLon);
	center = latlng;
	var options = {
		zoom: zoomLevel,
		center: latlng,
		streetViewControl: true,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	map = new google.maps.Map(document.getElementById("map_canvas"), options);
	
	$.ajax({
	    url: "index.php?menu=get-dealers",
	    cache: false,
	    dataType: "json",
	    success: function (data) {
			markers = data;
			setMarkers(map, data);
		}
	});
}

//var bounds = new LatLngBounds();
function fit(){
	map.panTo(bounds.getCenter()); 
	map.setZoom(map.getBoundsZoomLevel(bounds));
}

var markers;
function clickCountry(country){
	geocoder = new google.maps.Geocoder();
	
	var requestData = (country.attr('rel')  == 'mainCat') ? { "address": country.html() } : { "address": country.html()+", "+country.parent().parent().parent().parent().children('a').html() }

	$.ajax({
	    url: "geoCoder.php",
	    data: requestData,
	    cache: false,
	    dataType: "json",
	    success: function (data) {
            //debug(data);
			if(data['status'] == "OK"){
				var results = data['results'];
				
				var location = new google.maps.LatLng(results[0]['geometry']['location']['lat'], results[0]['geometry']['location']['lng']);
				var rectangle = new google.maps.Rectangle();
				map.setCenter(location);

				var ne = new google.maps.LatLng(results[0]['geometry']['bounds']['northeast']['lat'], results[0]['geometry']['bounds']['northeast']['lng']);
				var sw = new google.maps.LatLng(results[0]['geometry']['bounds']['southwest']['lat'], results[0]['geometry']['bounds']['southwest']['lng']);

				var bounds = new google.maps.LatLngBounds(sw,ne);
				
				map.fitBounds(bounds);
				var listener = google.maps.event.addListener(map, "idle", function() { 
				  map.setZoom( (country.attr('rel')  == 'mainCat') ? (map.getZoom()+1) : (map.getZoom()+3) );
				  map.setCenter(location);
				  google.maps.event.removeListener(listener); 
				});
				
				if(country.attr('rel')  == 'subCat'){
					var rId = country.attr('id').split('_')[1];
					//var cId = country.parent().parent().parent().parent().children('a').attr('id').split('_')[1];
					
					var selDealers = '';
					for(var i in markers[rId]){
						selDealers += '<li><a href="javascript:void(0);" onmouseout="outMarker('+markers[rId][i]["id"]+');" onmouseover="overMarker('+markers[rId][i]["id"]+');" onclick="showDealer('+markers[rId][i]["id"]+','+rId+')">'+markers[rId][i]['name']+'</a></li>';
					}
					$('#selectedDealers').html(selDealers);
					
				} else if(country.attr('rel')  == 'mainCat') {
					$('#selectedDealers').html(' ');
				}
				
				clearDealer();
				
				//Rectangle
				var rectOptions = {
				  strokeColor: "#FF0000",
				  strokeOpacity: 0.8,
				  strokeWeight: 2,
				  fillColor: "#FF0000",
				  fillOpacity: 0.35,
				  map: map,
				  bounds: bounds
				};
				//rectangle.setOptions(rectOptions);
			}
	    }
	});
}

var imageOver;
var sandMarkers = new Array();
var sandHtml = new Array();
var sandInfos = new Array();
function setMarkers(map, locations) {
	// Add markers to the map

	// Marker sizes are expressed as a Size of X,Y
	// where the origin of the image (0,0) is located
	// in the top left of the image.

	// Origins, anchor positions and coordinates of the marker
	// increase in the X direction to the right and in
	// the Y direction down.
	var hImage = new google.maps.MarkerImage('img/drag_logo_normal.png',
	  // This marker is 20 pixels wide by 32 pixels tall.
	  new google.maps.Size(25, 45),
	  // The origin for this image is 0,0.
	  new google.maps.Point(0,0),
	  // The anchor for this image is the base of the flagpole at 0,32.
	  new google.maps.Point(11, 44)
	);
	
	var oImage = new google.maps.MarkerImage('img/drag_logo_over.png',
	  // This marker is 20 pixels wide by 32 pixels tall.
	  new google.maps.Size(25, 45),
	  // The origin for this image is 0,0.
	  new google.maps.Point(0, 0),
	  // The anchor for this image is the base of the flagpole at 0,32.
	  new google.maps.Point(11, 44)
	);
	
	/*
	var shadow = new google.maps.MarkerImage('images/beachflag_shadow.png',
	  // The shadow image is larger in the horizontal dimension
	  // while the position and offset are the same as for the main image.
	  new google.maps.Size(37, 32),
	  new google.maps.Point(0,0),
	  new google.maps.Point(0, 32)
	);
	*/
	  // Shapes define the clickable region of the icon.
	  // The type defines an HTML <area> element 'poly' which
	  // traces out a polygon as a series of X,Y points. The final
	  // coordinate closes the poly by connecting to the first
	  // coordinate.
	var shape = {
	  coord: [8, 1, 15, 1, 24, 15, 24 , 22, 11, 44, 1, 24, 1, 16],
	  type: 'poly'
	};
	
	var hTemplate = 
		'<div class="box" style="background:none;padding:0;">'+
		'<div><strong>~name~</strong></div>'+
		'<div class="clear5"></div>'+
		'<div>~address~</div>'+
		'<div>~tel~</div>'+
		'<div><a href="http://~web~" target="_blank">~web~</div>'+
		'<div><a href="mailto:~mail~">~mail~</a></div>'+
		'</div>'
		;
		
	
	if(locations == null) locations = new Array();
	
	var zi = 0;
	for (i in locations) {		
		for (j in locations[i]) {
			var cTemplate = hTemplate;

			for(var p in locations[i][j])
			{	
				var re=eval("/~"+p+"~/g;");
				cTemplate = cTemplate.replace(re,locations[i][j][p]);
			}
			
			var infowindow = new google.maps.InfoWindow({
				content: "Loading..."
			});
			
			var myLatLng = new google.maps.LatLng(locations[i][j]['lat'], locations[i][j]['lon']);
			
			var hId = locations[i][j]['id'].toString();
			
			var hotelMarker = new google.maps.Marker({
				position: myLatLng,
				map: map,
				icon: hImage,
				shape: shape,
				title: locations[i][j]['name'],
				zIndex: zi,
				html: cTemplate,
				mainIcon:hImage,
				overIcon:oImage,
				mainZIndex: zi,
				id: hId,
				rid: i
			});
			google.maps.event.addListener(hotelMarker, 'click', function() {
				infowindow.setContent(this.html);
				infowindow.open(map,this);
				showInfo(this.rid, this.id);
			});
			google.maps.event.addListener(hotelMarker, 'mouseover', function() {
				this.setIcon(this.overIcon);
				this.setZIndex(1000);
			});
			google.maps.event.addListener(hotelMarker, 'mouseout', function() {
				this.setIcon(this.mainIcon);
				this.setZIndex(this.mainZIndex);
			});
			
			sandInfos[hId] = infowindow;
			sandMarkers[hId] = hotelMarker;
			sandHtml[hId] = cTemplate;
			
			zi++;
		}
	}
}

function showInfo(region, dealer){
	var dInfo = markers[region][dealer];
	
	$('#dealerName').html(dInfo['name']);
	$('#dealerAddress').html(dInfo['address']);
	$('#dealerTel').html(dInfo['tel']);
	$('#dealerInfo').html(dInfo['info']);
	
	$('#dealerMail a').html(dInfo['mail']);
	$('#dealerMail a').attr('href','mailto:'+dInfo['mail']);
	
	$('#dealerWeb a').html(dInfo['web']);
	$('#dealerWeb a').attr('href','http://'+dInfo['web']);
}

function clearDealer(){
	$('#dealerName').html(' ');
	$('#dealerAddress').html(' ');
	$('#dealerInfo').html(' ');
	$('#dealerTel').html(' ');
	$('#dealerMail a').html(' ');
	$('#dealerWeb a').html(' ');
}

function showDealer(id, region){
	for(i in sandInfos){
		if(typeof sandInfos[i].close == 'function') sandInfos[i].close();
	}
	map.panTo(sandMarkers[id].getPosition());
	sandInfos[id].setContent(sandHtml[id]);
	sandInfos[id].open(map, sandMarkers[id]);
	
	showInfo(region, id);
}
function overMarker(id){
	sandMarkers[id].setIcon(sandMarkers[id].overIcon);
	sandMarkers[id].setZIndex(1000);
}
function outMarker(id){
	sandMarkers[id].setIcon(sandMarkers[id].mainIcon);
	sandMarkers[id].setZIndex(sandMarkers[id].mainZIndex);
}
