//zmiana typu mapy
function updateImage() 
{
	var baseUrl = "http://maps.google.com/staticmap?";
	var params = [];
	
	if (map.getCurrentMapType() == G_SATELLITE_MAP) {
		params.push("maptype=satellite");
	}
	
	if (map.getCurrentMapType() == G_PHYSICAL_MAP) {
		params.push("maptype=terrain");
	}

	params.push("zoom=" + map.getZoom());
	params.push("size=523x550");
}

// wstawianie punktow na mapie
function createMarker(y, x, icon, type, tmp, address) 
{
	var point = new GLatLng(y, x);
	var marker = new GMarker(point, gicons[icon]);
	
	if(type == 'city')
	{
		GEvent.addListener(marker, "click", function() 
		{
			eval("showAddress( '"+ address +"' )");	
		});	
					
		GEvent.addListener(marker, "mouseover", function() 
		{
			eval("document.getElementById('li_location_a_" + tmp +"').style.textDecoration = 'underline'");	
		});						
					
		GEvent.addListener(marker, "mouseout", function() 
		{
			eval("document.getElementById('li_location_a_" + tmp +"').style.textDecoration = 'none'");	
		});		
	
	}
	else
	{
		GEvent.addListener(marker, "click", function() 
		{
				marker.openInfoWindowHtml("<div id = 'shopInfoBox'><div id = '"+ y +"_"+ x +"'><\/div><\/div>");			
				loadInfo(y, x, 'tools/location/shopInfoBox.php'); 
				//map.setCenter(point, 14);
		});
	}
	
	gmarkers.push(marker);	
	map.addOverlay(marker);	

	return marker;
}

//akcje wykonaywane podczas event'ow na mapie
function doOnEvenet()
{
	document.getElementById("message").innerHTML = '<!-- -->';
	if(!startP)
	{
		clearResults();
		tOut = window.setTimeout("loadShops('box_center')", 150);
	}
	else
	{
		startP = false;
	}
}

//wyszukiwanie lokalizacji
function showAddress(cords, pushedButton) 
{
	buttonSearch = pushedButton;

	if(cords)
	{
		var search = cords.toString();
	}
	else
	{
		var search = 	document.getElementById("addressTEXT").value;
		startP = true;
		//jesli pole jest puste to czysczenie
		if(!search)
		{
			clearResults(1);
			loadShops();
			return;
		}
		
		search = search + ", Polska";
	}

	//wyczyszczenie wszystkich oznaczen z poprzedniego wyszukiwania
	map.clearOverlays(); 
	
    geocoder.getLocations(search, function (result)
    { 
		if (result.Status.code == G_GEO_SUCCESS) 
		{			
			kup = result;
			var p = result.Placemark[0].Point.coordinates;
			if(result.Placemark.length > 1)
			{
				//document.getElementById("message").innerHTML = "Ilość miejscowości: " + result.Placemark.length;
			}
		
			var list = document.getElementById("locationListCont");

			list.innerHTML = '';
			
			if(result.Placemark.length > 1)
			{				
				var html2 = "<ul>";
				
				var tmp;
				for (var i=0; i<result.Placemark.length; i++) 
				{
					var p = result.Placemark[i].Point.coordinates;
					var point = new GLatLng(p[1],p[0]);
					
					result.Placemark[i].address = result.Placemark[i].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName + ', '+ result.Placemark[i].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName + ", " + result.Placemark[i].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
					
					tmp = i + 1;
					
					html2 += "<li><a id = 'li_location_a_"+ tmp +"' href = 'javascript:showAddress(\"" + result.Placemark[i].address +  "\")' title = 'Przejdź do lokalizacji: " +  result.Placemark[i].address + "'>" + tmp +". "+ result.Placemark[i].address;
					html2 += "<\/a><\/li>";

					createMarker(p[1], p[0], "loc" + tmp, 'city', tmp, result.Placemark[i].address);
				}
				
				html2 += "<\/ul>";
				
				list.innerHTML += html2;
				makeScroll();
				
				//zoom na PL
				centerMap(51.919438, 19.145136, 6);
			}
			else
			{
				//loadShops(p);	
				//user na mapie
				userLocation = new GLatLng(p[1],p[0]);
				centerMap(p[1], p[0], 11);
				
				//map.setCenter(userLocation, 11);
				loadShops(p);
			}
		}
		else 
		{
			var reason="Code "+result.Status.code;
           
		   if (reasons[result.Status.code]) 
			{
				reason = reasons[result.Status.code]
			} 
			
			alert('Nie znaleziono "'+search+ '" ' + reason);
		}
	});
}


function loadShops(locationId, error)
{			
	var box = map.getBounds();
	
		if(!locationId)
		{
			makeSearch('tools/location/locations.php', 'locationListCont', 0, 0, box.getSouthWest().x, box.getSouthWest().y, box.getNorthEast().x, box.getNorthEast().y, selectedId);
		}
		else
		{
			if(locationId == 'box_center')
			{
				locationId = new Array(map.getCenter().lat(), map.getCenter().lng());
			}
			
			makeSearch('tools/location/locations.php', 'locationListCont', locationId[1], locationId[0], box.getSouthWest().x, box.getSouthWest().y, box.getNorthEast().x, box.getNorthEast().y, selectedId);	
		}
	
		tOut2 = window.setTimeout("markShops()", 1000);
	
	return;
}

//zaznaczanei punktow na mapie
function markShops()
{
	var box = map.getBounds();
	var dest = document.getElementById("locationListCont");	
	var html = '<ul>';
	
	//user na mapie
	if(userLocation) map.addOverlay(new GMarker(userLocation, gicons["user"]));	
	
	if(ajaxRes)
	{
		zoom = (startP_first) ? 15 : 11;
		//alert(ajaxRes.length);
		var msg = document.getElementById('message');
		for(var i = 0; i < ajaxRes.length; i++)
		{
			var marker = createMarker(ajaxRes[i]['pos_x'], ajaxRes[i]['pos_y'], ajaxRes[i]['loc_type']);
			
			//dz - w nowej wersji kolorujemy co 2 wiersz
			var extraCls = (i % 2 == 0) ? ' class="highlight"' : '';
			
			html += "<li"+extraCls+"><a href = 'javascript:centerMap(" + ajaxRes[i]['pos_x'] + ", " + ajaxRes[i]['pos_y'] +  ", 14);' title = 'Wskaż na mapie lokalizajcę'><span class='name'>"+ ajaxRes[i]['name'] +" "+ ajaxRes[i]['city'] +"</span><span class='address'>, " +ajaxRes[i]['address'] +"</span><\/a><\/li>";
		}
			
		if(zoom < 11 || startP_first)
		{
			//przesuniesie mapy i pokazanie najblizszego punktu
			if(startP_first)
			{
				marker.openInfoWindowHtml("<div id = 'shopInfoBox'><div id = '"+ startP[0] +"_"+ startP[1] +"'><\/div><\/div>");			
				loadInfo(startP[0], startP[1], 'tools/location/shopInfoBox.php'); 				
				centerMap(startP[0],startP[1], zoom);
			}
			else
			{
				centerMap(ajaxRes[0]['pos_x'],ajaxRes[0]['pos_y'], zoom);
			}
			
			startP_first = false;
			selectedId = 0;
		}
		
		msg.innerHTML = 'Ilość punktów sprzedaży: ' + ajaxRes.length;	
		
		if(allCount){
			msg.innerHTML += ' z ' + allCount + ' (nawiguj i zobacz więcej)';
		}
		
		ajaxRes = '';	
		buttonSearch = false;	
	}
	else
	{
		//oddalenie jesli bark punktów
		/*
		if(userLocation)
		{
			var t = userLocation.toString();
			t = t.replace('(', '');
			t = t.replace(')', '');
			t = t.split(', ');
			
			tOut = setTimeout("centerMap("+ t[0] +", "+ t[1]+", 8)", 150);
		}
		*/
		
		
		if(userLocation && buttonSearch)
		{
			var t = prepareCords(userLocation);
			
			buttonSearch = false;			
			
			tOut = setTimeout("centerMap("+ t[0] +", "+ t[1]+", 8)", 150);
		}	
		else
		{
			//var t = prepareCords(map.getCenter());
		
			//tOut = setTimeout("centerMap("+ t[0] +", "+ t[1]+", 8)", 150);
		}
		
		//html += "<li>brak<\/li>";
	}
	
	html += "<\/ul>";
	dest.innerHTML += html;
	
	makeScroll();
	
	return;
}

//centrowanie mapy
function centerMap(x, y, zoom)
{
	map.setCenter(new GLatLng(x, y), zoom);
}

function prepareCords(cords)
{
	var t = cords.toString();
	t = t.replace('(', '');
	t = t.replace(')', '');
	t = t.split(', ');
	
	return t;
}

//czyszczenie wynikow i srodkowanie mapy
function clearResults(center)
{
	map.clearOverlays();
	var dest = document.getElementById("locationListCont").innerHTML = '';
	//document.getElementById("message").innerHTML = '&nbsp;';	
	
	if (tOut) 
	{
		window.clearTimeout(tOut);
	}
	
	if (tOut2) 
	{
		window.clearTimeout(tOut2);
	}
	
	if(center)
	{
		//zoom na PL
		centerMap(51.919438,19.145136, 6);		
	}
}


function ucwords( str ) 
{
    return (str+'').replace(/^(.)|\s(.)/g, function ( $1 ) { return $1.toUpperCase ( ); } );
}

function clearAttribs()
{
		var clearCSS = [];
		clearCSS[0] = 'amtc_option_0';
		clearCSS[1] = 'amtc_option_1';
		clearCSS[2] = 'amtc_option_2';
	
		for(var i = 0; i < clearCSS.length; i++)
		{
			var el = document.getElementById(clearCSS[i]);
			
			if(!el)
			{
				i = clearCSS.length;
				setTimeout("clearAttribs()", 1000);
				return;
			}
			else
			{
				el.style.fontSize = '9px';
				document.getElementById(clearCSS[i]).setAttribute('class', clearCSS[i]);
			}
		}
		
		var parent = document.getElementById('amtc_option_0').parentNode;
		parent.className = 'mapNavigBox';
}

//wstawienie scrolla w box
function makeScroll()
{
	var locationsScroll = new verticalScroll($('locationListCont'), $('locationListScroll')); 
}

//pobranie danych z bazy
function makeSearch(link, dest, pos_x, pos_y, min_y, min_x, max_y, max_x, selected)
{

	var d = document.getElementById(dest);
	advAJAX.post({
        url: "/" + link,
        unique: false,
		pos_x: pos_x,
		pos_y: pos_y,
		min_x: min_x, 
		min_y: min_y, 
		max_x: max_x, 
		max_y: max_y,
		locId: selected,

		onInitialization : function(obj) {
	     // d.innerHTML = "<div style='width: 309px; text-align: center;' id='bodyLoader'><img src='/images/googleMap/loaderRed.gif' style='margin-top:80px;'\/><\/div>";
		},
		onRetry : function(obj) {
		 // d.innerHTML = "<div style='width: 309px; text-align: center;' id='bodyLoader'><img src='/images/googleMap/loaderRed.gif' style='margin-top:80px;'\/><\/div>";
		},
		onRetryDelay : function(obj) { 
		 // d.innerHTML = "<div style='width: 309px; text-align: center;' id='bodyLoader'><img src='/images/googleMap/loaderRed.gif' style='margin-top:80px;'\/><\/div>";
		},        

		onSuccess: function(obj){
		
		d.innerHTML = "";
			
		if(!obj.responseText)
		{
			d.innerHTML += '';
			return
		}

		eval("var res = " + obj.responseText);
		
		if(res.list){
			ajaxRes = res.list;
			allCount = res.count;
		}else{
			ajaxRes = res;
			allCount = 0;
		}
		
		return;
        },
        onError: function(obj){
            //alert(obj);
        }
    });
}

//wczytanie danych do okienka
function loadInfo(x, y, link, error)
{	
	if(!y || !x)
	{
		return false;
	}
	
	var field = document.getElementById(x + '_' + y);
	
	//dziwne bo za pierwszym kliknieciem nie widzi jeszcze diva i trzeba chwile zaczekaĂ„â€Ą ... prawdopodobnie wczytuje tlo "chmurki"
	if(!field && !error)
	{	
		setTimeout("loadInfo('"+ x +"', '"+ y +"', '"+ link +"', 1)", 2000);
		return false;
	}
	
	if(field)
	{	
		advAJAX.post({
			url: "/" + link,
			parameters : {
			  "pos_x" : x,
			  "pos_y" : y
			},
			onInitialization :function(obj) { /*field.innerHTML = "<div style='width: 200px; text-align: center;' id='bodyLoader'><img src='/images/googleMap/loader.gif' style='margin-top:80px;'\/><\/div>";*/ },
			onSuccess : function(obj) { 
			
			field.innerHTML = obj.responseText; 			
			}, 
			
			onError : function(obj) { alert("Error: " + obj.status); }
		});
	}
	else
	{
		setTimeout("loadInfo('"+ x +"', '"+ y +"', '"+ link +"')", 2000);
		return false;
	}
}

//wyslanie maila
var formHTML;

function recommend(locId, email, link, field)
{	
	field = document.getElementById(field);
	
	if(!locId || !email || !field)
	{
		return false;
	}
		
	if(!formHTML)
	{
		formHTML = field.innerHTML;
	}
	
	advAJAX.post({
			url: "/" + link,
			"parameters" : {
			 "locationId" : locId,
			"recommend" : email
		},
		onInitialization :function(obj) { field.innerHTML = "<img src='/images/googleMap/loader.gif' style='margin-top:80px;'\/>"; },
		onSuccess : function(obj) { 
			
		field.innerHTML = obj.responseText; 			
		}, 
			
		onError : function(obj) { alert("Error: " + obj.status); }
	});
}

function load() {

	if (GBrowserIsCompatible()) 
	{
		geocoder = new GClientGeocoder();
		map = new GMap2(document.getElementById("map"));
		
		map.enableScrollWheelZoom();

		//start z PL
		centerMap(51.919438, 19.145136, 6);
		
		var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(3,15));
		var botLeft = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(15,40));		
		
		var topRight = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(15,15));
		var topLeft = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(15,15));	

		
		map.addMapType(G_PHYSICAL_MAP);
		map.removeMapType(G_HYBRID_MAP);
//		map.addControl(new GSmallMapControl(), botLeft);
//		map.addControl(new GMapTypeControl(), bottomRight);
		map.addControl(new GSmallMapControl(), topLeft);
		map.addControl(new GMapTypeControl(), topRight);
		
		GEvent.addListener(map, "moveend", function(marker, point) { updateImage(); });
		GEvent.addListener(map, "maptypechanged", function(marker, point) { updateImage(); });
		GEvent.addListener(map, "dragend", function() {doOnEvenet();});	
		GEvent.addListener(map, "zoomend", function() {doOnEvenet();} );		
				
		if(startP)
		{
			//alert(1);
			loadShops(startP);
		}
		else if(!keyWord)
		{
			//loadShops();
		}
		
		updateImage();
		contentFit.setup(false);
	}
}
