var mapa; 
var gdir = false;
var showWindow = true;
var geocoder;
var keyMaps;
var location1 = false;
var location2 = false;
var location3 = false;
var location4 = false;
var marker = new Array();

function startMap(key, location1, location2, location3, location4, roadMap, addressTo)
{  
	keyMaps = key;
	//log((address1));
	//log(Base64.encode(address1));
	//log(Base64.decode('TGnFm2NpYXN0YSAxMDQsIMWBw7Nkxbo='));
	if(typeof roadMap!='undefined')
	{
		showWindow = false;
	}
	
	if(GBrowserIsCompatible())  
	{  
		mapa = new GMap2(document.getElementById('map_canvas')); 
		
		mapa.addMapType(G_HYBRID_MAP);		
		var mapControl = new GHierarchicalMapTypeControl();
		mapControl.clearRelationships();
		
		mapa.addControl(new GSmallMapControl());
		mapa.enableScrollWheelZoom();
		
		geocoder = new GClientGeocoder();

		if (typeof addressTo != 'undefined') 
		{
			if(location1)
				findLocation(location1, addressTo);
			else
				findAddress(address, addressTo);
		}
		//geocoder.getLocations(address, addAddressToMap);
		//geocoder.getLocations(location1, addLocationToMap);


		if(location1)
			addLocationToMap(location1, address1, 1);
		else if(address1)
			geocoder.getLocations(address1, addAddressToMap);
		if(location2)
			addLocationToMap(location2, address2, 2);
		else if(address2)
			geocoder.getLocations(address2, addAddressToMap);
		if(location3)
			addLocationToMap(location3, address3, 3);
		else if(address3)
			geocoder.getLocations(address3, addAddressToMap);
		if(location4)
			addLocationToMap(location4, address4, 3);
		else if(address4)
			geocoder.getLocations(address4, addAddressToMap);
	}  
}  

function findLocation(location, placeTo) {
	//var address;
	var addressTo;
	
	loc = location.split(',');
	point = new GLatLng(loc[0], loc[1]);
	
	geocoder.getLatLng(point,
		function(pt) 
		{
			if (!pt) 
				alert(point + " - nie umiem znaleźć adresu");
			else {
				address = pt;
				geocoder.getLatLng(placeTo,
					function(pt) 
					{
						if (!pt) 
							alert(placeTo + " - nie umiem znaleźć adresu");
						else {
							addressTo = pt;
							gdir = new GDirections(mapa, document.getElementById("directions"));
							gdir.load("from: " + addressTo + " to: " + address);
						}
					}
				);
			}
		}
	);
}

function findAddress(place, placeTo) {
	var address;
	var addressTo;
	geocoder.getLatLng(place,
		function(pt)
		{
			if (!pt)
				alert(place + " - nie umiem znaleźć adresu");
			else {
				address = pt;
				geocoder.getLatLng(placeTo,
					function(pt)
					{
						if (!pt)
							alert(placeTo + " - nie umiem znaleźć adresu");
						else {
							addressTo = pt;
							gdir = new GDirections(mapa, document.getElementById("directions"));
							gdir.load("from: " + addressTo + " to: " + address);
						}
					}
				);
			}
		}
	);
}

function addAddressToMap(response) {
	var icon1 = new GIcon();
	icon1.image = base + "img/gm-znacznik.png";	
	icon1.infoWindowAnchor = new GPoint(44,7); 			// punkt mocowania okienka
	icon1.iconAnchor = new GPoint(24,50); 				// -> patrz plik PNG
	icon1.iconSize = new GSize(53, 56);
	
	//mapa.clearOverlays();
	if (response=='undefined' || response.Status.code != 200) 
	{
		alert("Przepraszamy. Nie możemy zlokalizowac podanego adresu.");
	} 
	else 
	{
		var place;
		var marker;
		var point;
		var ngl;
		var html;
		
		place = response.Placemark[0];

		point = new GLatLng(place.Point.coordinates[1],
		                    place.Point.coordinates[0]);
		
		marker = new GMarker(point, {icon:icon1});
		//marker = new GMarker(point);
		mapa.setCenter(point, 10);
		mapa.addOverlay(marker);
	
		//marker.openInfoWindowHtml();
		
		ngl = '<strong>' + response.name + '</strong>';
		if(typeof dealerName!='undefined')
		{
			ngl = '<h3>'+dealerName+'</h3>'+ngl;
		}

		html = '<div id="gmaps-content">'+ngl;
		html+='<form><label>Pokaż trasę do tego miejsca od:</label><input type="text" id="gm-to" /><input class="submit" type="submit" value="pokaż" onclick="show_road(0, 0, \''+response.name+'\'); return false;" /></form>';
		html+='</div>';
		
		if (showWindow) {
			marker.openInfoWindowHtml(html);
			GEvent.addListener(marker, "click", function(){
				marker.openInfoWindowHtml(html);
			});
		}	
	}
}

function addLocationToMap(location, address, it) {
	var icon1 = new GIcon();
	icon1.image = base + "img/gm-znacznik.png";
	icon1.infoWindowAnchor = new GPoint(44,7); 			// punkt mocowania okienka
	icon1.iconAnchor = new GPoint(24,50); 				// -> patrz plik PNG
	icon1.iconSize = new GSize(53, 56);
	
	//mapa.clearOverlays();
	if (location=='undefined')
	{
		alert("Przepraszamy. Nie mozemy zlokalizowac podanego adresu.");
	}
	else
	{
		loc = location.split(',');
		point = new GLatLng(loc[0], loc[1]);
		
		marker[it] = new GMarker(point, {icon:icon1});
		//marker = new GMarker(point);
		mapa.setCenter(point, 10);
		mapa.addOverlay(marker[it]);

		//marker.openInfoWindowHtml();

		var ngl;
		var html;
		ngl = '<strong>' + address + '</strong>';
		if(typeof dealerName!='undefined')
		{
			ngl = '<h3>'+dealerName+'</h3>'+ngl;
		}

		html = '<div id="gmaps-content">'+ngl+'<form><label>Pokaż trasę do tego miejsca od:</label><input type="text" id="gm-to" /><input class="submit" type="submit" value="pokaż" onclick="show_road(\''+loc[0]+'\', \''+loc[1]+'\', \''+address+'\'); return false;" /></form></div>';

		if (showWindow) {
			marker[it].openInfoWindowHtml(html);
			GEvent.addListener(marker[it], "click", function(){
				marker[it].openInfoWindowHtml(html);
			});
		}
	}
}

function show_road(place_x, place_y, address){
	to = $('#gm-to').val();
	//gdir.load("from: " + place + " to: " + to);
	
	width = 800;
	height=600;

	//address_from = geocoder.getLocations(place);
	//alert(address_from);
	if(place_x == 0 || place_y == 0)
		url = base+ 'pages/gmaps_road_address.php?address_from='+(address)+'&address_to='+(to)+'&dealer_name='+(dealerName)+'&keyMaps='+keyMaps;
	else
		url = base+ 'pages/gmaps_road.php?location_from='+(place_x + ',' + place_y)+'&address_from='+(address)+'&address_to='+(to)+'&dealer_name='+(dealerName)+'&keyMaps='+keyMaps;
	
	width1=width/2;
	height1=height/2;
	x=screen.availWidth/2-width1;
	y=screen.availHeight/2-height1;
	var Win = window.open(url, "displayWindow",'width=' + width + ',height=' + height + ',resizable=0, scrollbars=1, menubar=no, status=1, left='+x+', top='+y );
	Win.focus();
}

var Base64 = {

	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;

		input = Base64._utf8_encode(input);

		while (i < input.length) {

			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);

			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;

			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}

			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

		}

		return output;
	},

	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;

		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

		while (i < input.length) {

			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));

			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;

			output = output + String.fromCharCode(chr1);

			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}

		}

		output = Base64._utf8_decode(output);

		return output;

	},

	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while ( i < utftext.length ) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}

}
