// Copyright (c) 1996-1997 Athenia Associates.
// http://www.webreference.com/js/
// License is granted if and only if this entire
// copyright notice is included. By Tomer Shiran.

//google map api
var map;
var geocoder;
var newmarker;
var prevmarker;
var images = [
"http://maps.google.com/mapfiles/marker.png",
"http://maps.google.com/mapfiles/dd-start.png",
"http://maps.google.com/mapfiles/dd-end.png"
];
function load() {
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
		map = new GMap2(document.getElementById('map'));
		map.setCenter(new GLatLng(25.016104, 121.531750), 12);
		//map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		var lsc = new google.maps.LocalSearch();
		map.addControl(new google.maps.LocalSearch());
		searchLocations();
	}
}
function saveData() {
	var name = encodeURIComponent(document.getElementById("name").value);
	var address = encodeURIComponent(document.getElementById("address").value);
	var type = document.getElementById("type").value;
	var latlng = newmarker.getLatLng();
	var lat = latlng.lat();
	var lng = latlng.lng();
	var url = "http://www.bigsound.org/fuzzydoggie/phpsqlinfo_addrow.php?name=" + name + "&address=" + address +
	"&type=" + type + "&lat=" + lat + "&lng=" + lng;
	GDownloadUrl(url, function(data, responseCode) {
		if (responseCode == 200 && data.length <= 1) {
			newmarker.closeInfoWindow();
			document.getElementById("message").innerHTML = "已新增店家";
		searchLocationsNear(latlng);
		}
	});
}

function searchLocations() {
	var address = document.getElementById('addressInput').value;   
geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			alert(address + ' not found');
			} else {
				searchLocationsNear(latlng);
			}
		});
	}

function searchLocationsNear(center) {
	var radius = document.getElementById('radiusSelect').value;
	var searchUrl = 'http://www.bigsound.org/fuzzydoggie/phpsqlsearch_genxml.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName('marker');
		map.clearOverlays();

		var sidebar = document.getElementById('sidebar');
		sidebar.innerHTML = '';
		if (markers.length == 0) {
			sidebar.innerHTML = '附近沒有店家';
			//map.setCenter(new GLatLng(40, -100), 4);
			return;
		}

		var bounds = new GLatLngBounds();
		for (var i = 0; i < markers.length; i++) {
			var name = markers[i].getAttribute('name');
			var address = markers[i].getAttribute('address');
			var type = markers[i].getAttribute('type');
			var distance = parseFloat(markers[i].getAttribute('distance'));
			var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
			parseFloat(markers[i].getAttribute('lng')));

			var marker = createMarker(point, name, address, type);
			map.addOverlay(marker);
			var sidebarEntry = createSidebarEntry(marker, name, address, distance, type);
			sidebar.appendChild(sidebarEntry);
			bounds.extend(point);
		}
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	});
}

function createMarker(point, name, address, type) {
	var marker = new GMarker(point);
	var html = '<b>' + name + '</b> <br/>' + address+ '<br/>' + type;
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

function createSidebarEntry(marker, name, address, distance, type) {
	var div = document.createElement('div');
	var html = '<b>' + name + '</b> (' + distance.toFixed(1) + ')<br/>' + address+ '<br/>' + type;
	div.innerHTML = html;
	div.style.cursor = 'pointer';
	div.style.marginBottom = '5px';
	GEvent.addDomListener(div, 'click', function() {
		GEvent.trigger(marker, 'click');
	});
	GEvent.addDomListener(div, 'mouseover', function() {
		div.style.backgroundColor = '#eee';
	});
	GEvent.addDomListener(div, 'mouseout', function() {
		div.style.backgroundColor = '#fff';
	});
	return div;
}

function follow(imageInd){
	var dog = true;
	var noMore = false;

        if(prevmarker){
          map.removeOverlay(prevmarker);
        }
	var mouseMove = GEvent.addListener(map, 'mousemove', function(cursorPoint){
		if(!noMore){
			newmarker = new GMarker(cursorPoint,{draggable:true, autoPan:true});
			prevmarker = newmarker;
                        map.addOverlay(newmarker);
			newmarker.setImage(images[imageInd]);
			noMore = true;
			// This function deletes the marker when dragged outside map
			//GEvent.addListener(newmarker, 'drag', function(markerPoint){
				//if(!map.getBounds().containsLatLng(markerPoint)){
				//	map.removeOverlay(newmarker);
				//}
			//});
			GEvent.addListener(newmarker, "mouseup", function() {
				var html = "<table>" +
				"<tr><td>店名:</td> <td><input type='text' id='name'/> </td> </tr>" +
				"<tr><td>店址:</td> <td><input type='text' id='address'/></td> </tr>" +
				"<tr><td>型態:</td> <td><select id='type'>" +
				"<option value='酒吧' SELECTED>酒吧</option>" +
				"<option value='餐廳'>餐廳</option>" +
				"</select> </td></tr>" +
				"<tr><td></td><td><input type='button' value='新增店家' onclick='saveData()'/></td></tr>";

				newmarker.openInfoWindow(html);
			});
		}
		if(dog){
			newmarker.setLatLng(cursorPoint);
		}
	});
	var mapClick = GEvent.addListener(map, 'click', function(){
		dog = false;
		// 'mousemove' event listener is deleted to save resources
		GEvent.removeListener(mouseMove);
		GEvent.removeListener(mapClick);
	});
}




function openMusic(url, title){
var path = 'http://www.bigsound.org/fuzzydoggie/play.php?url=' + url + '&title=' + title
var spec = 'location=0, directories=0, menubar=0,toolbar=0, status=0, scrollbars=0, resizable=0, width=230 , height=45'
window.open(path,'_media',spec)
}

function setCookie (name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) + (expires ? "; expires=" + expires : "") +
        (path ? "; path=" + path : "") + (domain ? "; domain=" + domain : "") + (secure ? "secure" : "");
    document.cookie = curCookie;
}

function getCookie (name) {
    var prefix = name + '=';
    var c = document.cookie;
    var nullstring = '';
    var cookieStartIndex = c.indexOf(prefix);
    if (cookieStartIndex == -1)
        return nullstring;
    var cookieEndIndex = c.indexOf(";", cookieStartIndex + prefix.length);
    if (cookieEndIndex == -1)
        cookieEndIndex = c.length;
    return unescape(c.substring(cookieStartIndex + prefix.length, cookieEndIndex));
}

function deleteCookie (name, path, domain) {
    if (getCookie(name))
        document.cookie = name + "=" + ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") + "; expires=Thu, 01-Jan-70 00:00:01 GMT";
}

function fixDate (date) {
    var base = new Date(0);
    var skew = base.getTime();
    if (skew > 0)
        date.setTime(date.getTime() - skew);
}

function rememberMe (f) {
    var now = new Date();
    fixDate(now);
    now.setTime(now.getTime() + 365 * 24 * 60 * 60 * 1000);
    now = now.toGMTString();
    if (f.author != undefined)
       setCookie('mtcmtauth', f.author.value, now, '/', '', '');
    if (f.email != undefined)
       setCookie('mtcmtmail', f.email.value, now, '/', '', '');
    if (f.url != undefined)
       setCookie('mtcmthome', f.url.value, now, '/', '', '');
}

function forgetMe (f) {
    deleteCookie('mtcmtmail', '/', '');
    deleteCookie('mtcmthome', '/', '');
    deleteCookie('mtcmtauth', '/', '');
    f.email.value = '';
    f.author.value = '';
    f.url.value = '';
}

function hideDocumentElement(id) {
    var el = document.getElementById(id);
    if (el) el.style.display = 'none';
}

function showDocumentElement(id) {
    var el = document.getElementById(id);
    if (el) el.style.display = 'block';
}

var commenter_name;

function individualArchivesOnLoad(commenter_name) {


    hideDocumentElement('trackbacks-info');



    if (document.comments_form) {
        if (document.comments_form.email != undefined &&
            (mtcmtmail = getCookie("mtcmtmail")))
            document.comments_form.email.value = mtcmtmail;
        if (document.comments_form.author != undefined &&
            (mtcmtauth = getCookie("mtcmtauth")))
            document.comments_form.author.value = mtcmtauth;
        if (document.comments_form.url != undefined && 
            (mtcmthome = getCookie("mtcmthome")))
            document.comments_form.url.value = mtcmthome;
        if (mtcmtauth || mtcmthome) {
            document.comments_form.bakecookie.checked = true;
        } else {
            document.comments_form.bakecookie.checked = false;
        }
    }
}

function writeTypeKeyGreeting(commenter_name, entry_id) {

}



