var iconBlue = new GIcon();
iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconBlue.iconSize = new GSize(12, 20);
iconBlue.shadowSize = new GSize(22, 20);
iconBlue.iconAnchor = new GPoint(6, 20);
iconBlue.infoWindowAnchor = new GPoint(5, 1);

var iconRed = new GIcon();
iconRed.image = 'http://labs.google.com/ridefinder/images/mm_20_red.png';
iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconRed.iconSize = new GSize(12, 20);
iconRed.shadowSize = new GSize(22, 20);
iconRed.iconAnchor = new GPoint(6, 20);
iconRed.infoWindowAnchor = new GPoint(5, 1);

var iconYellow = new GIcon();
iconYellow.image = 'http://labs.google.com/ridefinder/images/mm_20_yellow.png';
iconYellow.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconYellow.iconSize = new GSize(12, 20);
iconYellow.shadowSize = new GSize(22, 20);
iconYellow.iconAnchor = new GPoint(6, 20);
iconYellow.infoWindowAnchor = new GPoint(5, 1);

var iconGreen = new GIcon();
iconGreen.image = 'http://labs.google.com/ridefinder/images/mm_20_green.png';
iconGreen.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
iconGreen.iconSize = new GSize(12, 20);
iconGreen.shadowSize = new GSize(22, 20);
iconGreen.iconAnchor = new GPoint(6, 20);
iconGreen.infoWindowAnchor = new GPoint(5, 1);


var map = null;
var geocoder = null;
var trafficInfo = null;
var directions = null;
var weather = { };
top.mapnodes = { };


function load() {
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
		trafficInfo = new GTrafficOverlay();
		if ( trafficState == 0 ) trafficInfo.hide();
		else $('nav-traffic-switch').value = 'Hide';
		map = new GMap2(document.getElementById("map"));
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.addOverlay(trafficInfo);
		window.setTimeout(setupWeatherMarkers, 0);
		//map.addControl(new GOverviewMapControl());
		// scroll
		//map.enableScrollWheelZoom();
		// create a local search control and add it to your map
		var lsc = new google.maps.LocalSearch();
		map.addControl(new google.maps.LocalSearch());
		// center the map
		var x = centerpos["x"];
		var y = centerpos["y"];
		map.setCenter(new GLatLng(parseFloat(x), parseFloat(y)), 10);

		// figure out filter count
		var cnt = 0;
		for ( var i in filterCats ) cnt += 1;
		for ( var i in locations ) {
			var point = new GLatLng(parseFloat(locations[i]["latitude"]), parseFloat(locations[i]["longitude"]));
			var marker = createMarker(point, i);
			mapnodes[i] = marker;
			if ( cnt == 0 ) {
				map.addOverlay(mapnodes[i]);
			} else {
				for ( var j in locations[i]['cats'] ) {
					if ( typeof(filterCats[j]) != 'undefined' ) {
						map.addOverlay(mapnodes[i]);
					}
				}
			}
		}

		// set my location
		setMyLoc();

		// open info box if requested
		if ( ( dirsfrom == 'me' || dirsfrom > 0 ) && ( dirsto == 'me' || dirsto > 0 ) ) {
			var f = ( dirsfrom == 'me' ? myloc.address : locations[dirsfrom]['address'] );
			var t = ( dirsto   == 'me' ? myloc.address : locations[dirsto  ]['address'] );
			getDirections(f, t, trafficState);
		} else if ( dirsfrom == 'me' || dirsfrom > 0 ) {
			openMarker(dirsfrom, 'from');
		} else if ( dirsto == 'me' || dirsto > 0 ) {
			openMarker(dirsto, 'to');
		} else if ( loc == 'me' || loc > 0 ) {
			openMarker(loc, 'info');
		//} else if ( myloc ) {
			//openMarker('me', 'info');
		}
/*
		GDownloadUrl("xml.php", function(data) {
			var xml = GXml.parse(data);
			var centerpos = xml.documentElement.getElementsByTagName("centerpos")[0];
			var x = centerpos.getAttribute("coordx");
			var y = centerpos.getAttribute("coordy");
			map.setCenter(new GLatLng(parseFloat(x), parseFloat(y)), 10);
			var markers = xml.documentElement.getElementsByTagName("marker");
			for (var i = 0; i < markers.length; i++) {
				var id = markers[i].getAttribute("id");
				var name = markers[i].getAttribute("name");
				var address = markers[i].getAttribute("address");
				var type = markers[i].getAttribute("type");
				var cat  = markers[i].getAttribute("cats");
				var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
				parseFloat(markers[i].getAttribute("lng")));
				var marker = createMarker(point, name, address, type);
				top.mapnodes[id] = marker;
				map.addOverlay(marker);
			}
		});
*/
	}
}

function openMarkerCleanup(id, view) {
	if ( $('map-directions-from') )
		$('map-directions-from').onkeypress = DirectionsEnterKey;
	if ( $('map-directions-to') )
		$('map-directions-to').onkeypress = DirectionsEnterKey;
}

function openMarker(id, view) {
	if ( !mapnodes[id] ) {
		alert('Marker not found. Please try another.');
		return;
	}
	mapnodes[id].openInfoWindowHtml(buildMarker(id, view));
	openMarkerCleanup(id, view);
}

function createMarker(point, id) {
	var marker = new GMarker( point, ( id == 'me' ? iconGreen : iconRed ) );
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(buildMarker(id, 'info'));
		openMarkerCleanup(id, 'info');
	});
	return marker;
}

function buildDirectionsLinks(id, rawaddress, view) {
	// directions
	var dirs = "<div class='map_loc_dir'>";
	if ( view == 'info' ) {
		dirs +=
			"<div>Get directions: " +
			"<a href='?to=" +  id + "' onclick='openMarker(\"" +  id + "\", \"to\");return false;'>To here</a> &middot " +
			"<a href='?to=" +  id + "' onclick='openMarker(\"" +  id + "\", \"from\");return false;'>From here</a>" +
			"</div>"
		;
	} else {
		var fullurl = '?';
		if ( view == 'to' ) {
			fullurl += 'from=me&to=' + id;
		} else {
			fullurl += 'from=' + id + '&to=me';
		}
		dirs +=
          '<div class="map-directions">' +
            ( myloc && id != 'me' ? '<div id="map-directions-myloc"><a href="' + fullurl + '" onclick="$(\'map-directions-' + ( view == 'to' ? 'from' : 'to' ) + '\').value=myloc.address;return false;">Use My Location</a></div>' : '' ) +
            '<div class="map-directions-label">' + ( view == 'to' ? 'Starting Address:' : 'Ending Address:' ) + '</div>' +
            '<input class="' + ( view != 'to' ? 'hidden' : 'wideinput' ) + '" type="text" id="map-directions-from" value="' + ( view != 'to' ? rawaddress : '' ) + '" />' +
            '<input class="' + ( view == 'to' ? 'hidden' : 'wideinput' ) + '" type="text" id="map-directions-to" value="' + ( view == 'to' ? rawaddress : '' ) + '" />' +
            '<div class="map-directions-label">OR select one of the existing locations:</div>' +
            '<select class="wideinput" size="1" onchange="if (this.value != \'\') $(\'map-directions-' + ( view == 'to' ? 'from' : 'to' ) + '\').value=this.value;$(\'map-directions-' + ( view == 'to' ? 'from' : 'to' ) + '\').disabled=(this.value != \'\');if($(\'map-directions-myloc\')) $(\'map-directions-myloc\').className=(this.value == \'\' ? \'block\' : \'hidden\');">' +
            '<option value="">Select Location...</option>'
		;
		if ( myloc && id != 'me' ) dirs += '<option value="' + myloc.address + '">&raquo; My Location &laquo;</option>';
		for ( var i in locations ) {
			dirs += '<option value="' + locations[i]['address'] + '">' + locations[i]['name'] + '</option>';
		}
		dirs +=
            '</select>' +
            '<div>' +
              '<span style="float: right;">' +
                '<input type="button" id="map-directions-get" value="Get Directions" onclick="getDirections($(\'map-directions-from\').value, $(\'map-directions-to\').value, $(\'map-directions-traffic\').checked);" />' +
              '</span>' +
              '<label>' +
                '<input type="checkbox" id="map-directions-traffic" value="1"' + ( trafficState == '1' ? ' checked="checked"' : '' ) + ' />' +
                'Show Traffic' +
              '</label>' +
            '</div>' +
            '<div class="map_directions_back"><a href="?loc=' + id + '" onclick="openMarker(\'' +  id + '\', \'info\');return false;">&laquo; Back</a></div>' +
          '</div>'
		;
	}
	dirs += "</div>";
	return dirs;
}

function buildMarker(id, view) {
	if ( id == 'me' ) {
		var rawaddress = myloc['address'];
		var address = breakAddress(rawaddress);
		var baloon =
			"<div class='map_myloc'>Home</div>" +
			"<div class='map_loc_title'>My Location</div>" +
			"<div class='map_loc_address'>" + address + "</div>" +
			buildDirectionsLinks(id, rawaddress, view);
		;
	} else {
		var rawaddress = locations[id]['address'];
		var address = locations[id]['htmladdress'];
		var arr = [ ];
		for ( var i in locations[id]['cats'] ) {
			var c = categories[i];
			arr.push('<a href="?cat=' + i + '" onclick="toggleCat(' + i + ');return false;">' + c.name + '</a>');
		}
		var incats = arr.join('</li><li>');
		/* BUILDING BALOON */
		var baloon = "";
		// thumbnail
		if ( locations[id]['img'] == 1 ) baloon += "<div class='map_loc_img'><img src='images/locations/" + id + ".jpg' border='1' width='100' /></div>";
		// title
		baloon += "<div class='map_loc_title'>" + locations[id]['name'] + "</div>";
		// address
		baloon += "<div class='map_loc_address'>" + address + "</div>";
		// phone
		if ( locations[id]['phone'] != '' ) baloon += "<div class='map_loc_phone'>" + locations[id]['phone'] + "</div>";
		// url
		if ( locations[id]['url'] != '' ) baloon += "<div class='map_loc_url'><a href='" + locations[id]['url'] + "'>Visit Web Site</a></div>";
		// summary
		if ( locations[id]['summary'] != null ) baloon += "<div class='map_loc_summary'>" + locations[id]['summary'] + "</div>";
		// blog
		if ( locations[id]['blogid'] > 0 ) baloon += "<div class='map_loc_more'><a href='/article/" + locations[id]['bloglink'] + "/'>More Info</a></div>";
		// categories
		baloon +=
			"<div class='map_loc_cats'>" +
			"<div>Categories:</div>" +
			"<ul class='map_cat_list'><li>" + incats + "</li></ul>" +
			"</div>"
		;
		// directions
		baloon += buildDirectionsLinks(id, rawaddress, view);
		// break
		if ( locations[id]['img'] == 1 ) baloon += "<div style='clear: both;'></div>";
	}
	baloon = "<div class='map_loc'>" + baloon + "</div>";
	return baloon;
}

function setMyLoc() {
    if ( myloc ) {
    	var point = new GLatLng(parseFloat(myloc["latitude"]), parseFloat(myloc["longitude"]));
    	var marker = createMarker(point, 'me');
    	mapnodes['me'] = marker;
    	map.addOverlay(marker);
    } else if ( typeof(mapnodes['me']) != 'undefined' ) {
    	map.removeOverlay(mapnodes['me']);
    	delete mapnodes['me'];
    }
}

var filterID = 0;
function removeMarker(id, lnk) {
	if ( id == filterID ) {
		// show all
		for ( var i in mapnodes ) {
			map.addOverlay(mapnodes[i]);
		}
		lnk.innerHTML = 'Hide Other';
		filterID = 0;
	} else {
		// hide all except this category
		for ( var i in locations ) {
			if ( typeof(locations[i]['cats'][id]) != 'undefined' ) {
				map.addOverlay(mapnodes[i]);
			} else {
				map.removeOverlay(mapnodes[i]);
			}
		}
		lnk.innerHTML = 'Show All';
		filterID = id;
	}
}

function filterMarkers() {
	var cnt = 0;
	for ( var i in filterCats ) cnt += 1;
	if ( cnt == 0 ) {
		// show all
		for ( var i in mapnodes ) {
			map.addOverlay(mapnodes[i]);
		}
	} else {
		// hide all
		for ( var i in locations ) {
			map.removeOverlay(mapnodes[i]);
		}
		// except these categories
		for ( var i in locations ) {
			for ( var j in locations[i]['cats'] ) {
				if ( typeof(filterCats[j]) != 'undefined' ) {
					map.addOverlay(mapnodes[i]);
					//alert(i);
				}
			}
		}
	}
}

// addAddressToMap() is called when the geocoder returns an
// answer.  It adds a marker to the map with an open info window
// showing the nicely formatted version of the address and the country code.
function addAddressToMap(response) {
	if ( !response || response.Status.code != 200 ) {
		alert("Sorry, we were unable to find that address. Please try another.");
	} else {
		place = response.Placemark[0];
		myloc = {
			"latitude" : place.Point.coordinates[1],
			"longitude" : place.Point.coordinates[0],
			"address" : place.address.replace(/, USA/, '')
		};
		var cookieval = myloc.latitude + '|' + myloc.longitude + '|' + myloc.address;
		setcookie('myloc', cookieval, 60 * 60 * 24 * 365 * 2); // valid for 2 years
		setMyLoc();
		openMarker('me', 'info');
		$('nav-myloc-input').value = myloc.address;
		if ( $('map-directions-from').value == '' ) $('map-directions-from').value = myloc.address;
		$('nav-myloc-enter').className = 'hidden';
		$('nav-myloc-found').className = 'block';
		$('nav-myloc-change').className = 'inline';
		$('nav-myloc-link').innerHTML = breakAddress(myloc.address);
	}
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the form
// and adds a marker to the map at that location.
function showAddress(address) {
	if ( address == '' ) {
		setcookie('myloc', '', 0); // valid until now -> kill the cookie
		$('nav-myloc-enter').className = 'block';
		$('nav-myloc-change').className = 'inline';
		$('nav-myloc-found').className = 'hidden';
		$('nav-myloc-link').innerHTML = '';
		if ( mapnodes['me'] ) {
			map.removeOverlay(mapnodes['me']);
			delete mapnodes['me'];
		}
		return;
	}
	geocoder.getLocations(address, addAddressToMap);
}

function breakAddress(address) {
	var arr = address.split(', ');
	if ( arr.length == 3 || ( arr.length == 4 && arr[3] == 'USA' ) ) {
		address =
			arr[0] + "<br />" +
			arr[1] + ", " + arr[2]
		;
	}
	return address;
}

function toggleTraffic() {
	if ( trafficState == 1 ) {
		trafficInfo.hide();
		$('nav-traffic-switch').value = site_strings['map-traffic-show'];
		if ( $('map-directions-traffic') )
			$('map-directions-traffic').checked = false;
		//map.removeOverlay(trafficInfo);
		trafficState = 0;
	} else {
		trafficInfo.show();
		$('nav-traffic-switch').value = site_strings['map-traffic-hide'];
		if ( $('map-directions-traffic') )
			$('map-directions-traffic').checked = true;
		//map.addOverlay(trafficInfo);
		trafficState = 1;
	}
	if ( $('map-directions-traffic') )
		$("map-directions-traffic").checked = ( trafficState == 1 );
}

function toggleWeather() {
	if ( weatherState == 1 ) {
		weatherInfo.hide();
		$('nav-weather-switch').value = site_strings['map-weather-show'];
		//map.removeOverlay(weatherInfo);
		toggleState = 0;
	} else {
		weatherInfo.show();
		$('nav-weather-switch').value = site_strings['map-weather-hide'];
		//map.addOverlay(weatherInfo);
		toggleState = 1;
	}
}

function getDirections(from, to, traffic) {
	if ( traffic && trafficState == 0 ) {
		toggleTraffic();
	} else if ( !traffic && trafficState == 1 ) {
		toggleTraffic();
	}
	directionsPanel = $("nav-directions-result");
	$("nav-directions").className = 'block';
	directions = new GDirections(map, directionsPanel);
	directions.load('from ' + from + ' to ' + to);
}


function getWeatherMarkers(n) {
	var batch = [];
	for (var i = 0; i < n; ++i) {
		batch.push(new GMarker(getRandomPoint(), { icon: getWeatherIcon() }));
	}
	return batch;
}

function setupWeatherMarkers() {
/*	mgr = new MarkerManager(map);
	mgr.addMarkers(getWeatherMarkers(20), 3);
	mgr.addMarkers(getWeatherMarkers(200), 6);
	mgr.addMarkers(getWeatherMarkers(1000), 8);
	mgr.refresh();
*/}

function MyLocationEnterKey(evt) {
	var evt = ( evt ? evt : ( event ? event : null ) );
	if ( !evt ) return true;
	var node = ( evt.target ? evt.target : ( evt.srcElement ? evt.srcElement : null ) );
	// 13 == ENTER
	if ( evt.keyCode == 13 && node.type == "text" )  {
		showAddress(node.value);
		// nope, don't submit
		return false;
	}
}

function DirectionsEnterKey(evt) {
	var evt = ( evt ? evt : ( event ? event : null ) );
	if ( !evt ) return true;
	var node = ( evt.target ? evt.target : ( evt.srcElement ? evt.srcElement : null ) );
	// 13 == ENTER
	if ( evt.keyCode == 13 && node.type == "text" )  {
		getDirections($('map-directions-from').value, $('map-directions-to').value, $('map-directions-traffic').checked);
		// nope, don't submit
		return false;
	}
}

function toggleCat(id) {
	var rel = $('nav-locations-' + id);
	toggleClass('nav-locations-' + id, 'nav_category_locations', 'hidden');
	var showing = ( rel.className != 'hidden' );
	if ( showing ) {
		filterCats[id] = id;
	} else {
		if ( typeof(filterCats[id]) != 'undefined' ) {
			delete filterCats[id];
		}
	}
	filterMarkers();
}


function maploc_submit() {
	// check if ANY field is blank
	var post = $('maplocaddform').serialize(true);
	for ( var i in post ) {
		if ( i != 'events' && post[i] == '' ) {
			alert('Sva polja moraju biti popunjena.')
			$('maplocaddform').elements[i].focus();
			return false;
		}
	}
	if ( $('addnamefield').name == '' ) {
		alert('Lokacija nema naziv? Kako da je zovemo onda? :)')
		$('addnamefield').focus();
		return false;
	}
	bar_loader_show('Šaljem podatke...');
	// return true; // don't use ajax
	new Ajax.Request(
		apiurl('maplocadd'),
		{
			//method: 'get',
			parameters: $('maplocaddform').serialize(true),
			onSuccess: function(response) {
				var xml = api_handle(response);
				var res = node_value(xml.getElementsByTagName('res')[0]);
				if ( res == 1 ) {
					// disable the save button
					$('maplocaddsubmit').disabled = true;
					window.setTimeout("window.location.href='/mapa/';", 2000);
				} else {
					var err = node_value(xml.getElementsByTagName('err')[0]);
					// do something with error code here?
				}
			},
			onFailure: function() { bar_error_show('API call failed, something went wrong...') }
		}
	);
	return false;
}

