// ==UserScript==
// @name          Google Maps in Flickr
// @version	  2.2.1
// @description   GMiF - Display Google Maps in flickr
// @namespace     http://flickr.yuan.cc/
// @include       http://www*.flickr.com/photos/*
// @include       http://flickr.com/photos/*

// Whats New
// =========
// v2.2.1 21/7/05 Temporary fix to replace GM APIs with cookies and XMLHttpRequest 
// v2.2   19/7/05 Add an option dialog box to GMiF. Current options are:
//		  1. Customized description/comment (with MACRO support)
//		  2. Default map type: Map or Satellite
//		  3. Enable/disable japandatumhacks
// v2.1.1 16/7/05 Fix the map shift problem between WGS84 Datum and Tokyo Datum
// v2.1   14/7/05 Upgrade to maps.11.js to show Japanese map 
//		  Change the pin color of nearby photos to blue
//		  Non-owner can't place marker
// v2.0   13/7/05 Named GMiF officially
//		  Get nearby photos from http://www.geobloggers.com/makeXML.cfm
//		  Geocoded photos are supported
//		  Fly-To feature for Google Earth is added
// v1.7   12/7/05 Steeev added functions to add geotags, comments, and desc at a click-at-once
// v1.6   11/7/05 A toolbar with Lat/Lon box,favorite places,some map controls,and etc...
// v1.5.1  8/7/05 Fix the comments overlap problem caused by a transparent gif photo
// v1.5    6/7/05 A toolbar is added above gmap. (large map, hide map, lengthen map)
// v1.4    6/7/05 CK hide gmap div instead of deleting div
// v1.4    6/7/05 CK add an internal link to jump down to the map
// v1.3    5/7/05 Billy fixed a bug that occured when a picture was posted in the comments of an image
// v1.2    5/7/05 Billy fixed the gmap resize problem and put gmap under the photo
// v1.1    4/7/05 Fix photo notes overlay problem
// v1.0    3/7/05 Capability to add geotags and post to geobloggers
// v0.9    2/7/05 Upgrade to maps.10.js
// v0.1   28/6/05 Initial release, embed gmap into flickr
//
// Description
// ===========
// This script will display Google Maps if the photo is geotagged. 
//
// Official Group: http://www.flickr.com/groups/flickr_tools/
// GeoTagging Flickr group: http://www.flickr.com/groups/geotagging/
// Geobloggers: http://www.geobloggers.com/ 
//
// Credits
// =======
// v0.1 Created by .CK ( http://www.flickr.com/photos/ckyuan/ )
//    - Initial product
// v1.2 Modified by Billy ( http://www.flickr.com/photos/cowfish/ )
//    - Have Gmap to appear under flickr photo and fix Gmap resize problem
//    - Fix many bugs in v1.2 v2.1
// v1.4 Suggestion from Steeev ( http://www.flickr.com/photos/steeev/ )
//    - Add internal link to jump down to the map
// v1.7 Code contribution from Steeev ( http://www.flickr.com/photos/steeev/ )
//    - 1 click add of geotags
//    - 1 click add of description or comment
//    - 1 click post to geobloggers (and get response whether it worked or failed)
//      or alternatively 1 click to do all the above functions :)
//
// ==/UserScript==

(function() {

var container, googlemaps, panel, metapanel, permalink, printheader, photodiv, photo_id, ps_photo_id, tables, insertPoint, marker, lat='',lon='', zoom=4;
var title, photo, img_t;
var _mapjsLoaded=false, _mapLoaded=false, _geocoded=false, _height, _isowner,_cadaddtag;
var geobloggers_text = '<a href="http://www.geobloggers.com">Map of Location</a>';
var exif = new Object();
var _GMAPI = false;

function init() {

	var a,i,splits,tag,marked=false;

	_cadaddtag = (document.getElementById('tagadderlink')) ? true: false;
	for (var x in photo_hash) {
	    if( !document.getElementById('photoImgDiv'+x) ) continue;
	    photo_id = x;
	    photo = photo_hash[x];
//	    title = photo.title;
	    title =  document.getElementById('title_div'+x).innerHTML;
	    _isowner = photo.isOwner;
	    if( title == undefined ) title = '';
	    img_t = 'http://photos'+photo.server+'.flickr.com/'+x+'_'+photo.secret+'_t.jpg';
	    while( photo.tags_rawA && photo.tags_rawA.length > 0 ) {
		tag = photo.tags_rawA.pop();
		splits = tag.split('=')
		if( splits[0] == 'geo:lat' ) lat = 1*splits[1];
		if( splits[0] == 'geo:lon' ) lon = 1*splits[1];
		if( splits[0] == 'geocoded' ) _geocoded = true;
	    }
	}
	if( lat=='' || lon=='' ) {
	    if( getCookie('geo:lat') && getCookie('geo:lon') ) {
		lat = 1*getCookie('geo:lat');
		lon = 1*getCookie('geo:lon');
		zoom = 4;
	    } else {
		lat = 0;
		lon = -180;
		zoom = 16;
	    }
	} else marked = true;
//	if( _geocoded ) getExif(photo);
	getExif(photo);
	photodiv = document.getElementById('photoImgDiv'+photo_id);
	if( !photodiv ) return;
	descdiv = document.getElementById('description_div'+photo_id);
	tables = document.getElementsByTagName('table');
	for( var t in tables ) {
	    if( tables[t].className == 'UnderPhoto' ) insertPoint = tables[t];
	}
	if(descdiv && descdiv.nextSibling) insertPoint = descdiv.nextSibling;

	var js = document.createElement("script");
	js.language = "javascript";
	js.src = "http://flickr.yuan.cc/gmif/maps.js";
	document.body.appendChild(js);
	_mUsePrintLink='';
	_mSiteName = '';
	_mapjsLoaded = true;

	panel = document.createElement("div");
	metapanel = document.createElement("div");
	permalink = document.createElement("div");
	printheader = document.createElement("div");
	panel.setAttribute('id','panel');
	metapanel.setAttribute('id','metapanel');
	permalink.setAttribute('id','permalink');
	printheader.setAttribute('id','printheader');

	var gmap = document.createElement("a");
	var gimg = document.createElement("img");
	var gname = document.createElement("a");

	gimg.src = 'http://photos16.flickr.com/22099286_cbf504ef03_o.gif';
	gimg.onmouseover = function() { gimg.src = 'http://photos16.flickr.com/22099285_9dae358e13_o.gif'; }
	gimg.onmouseout = function() { gimg.src = 'http://photos16.flickr.com/22099286_cbf504ef03_o.gif'; }
	gmap.appendChild(gimg);
	gmap.href = '#gmap';
	gname.setAttribute('name','gmap');
	insertPoint.parentNode.insertBefore(gname, insertPoint);

	var largemap = function() {
	    var url = 'http://maps.google.com/maps?ll=' + myMapApp.map.getCenterLatLng().y + ',' + myMapApp.map.getCenterLatLng().x + '&spn=' + myMapApp.map.getSpanLatLng().width + ',' + myMapApp.map.getSpanLatLng().height + '&hl=en';
	    window.open(url,'_blank');
	}
	var hidemap = function() {
	    container.style.visibility = 'hidden';
	    _height = document.defaultView.getComputedStyle(container,null).getPropertyValue('height');
	    container.style.width='0px';
	    container.style.height='0px';
	    gmap.onclick = showmap;
	    gmap.href = 'javascript:;';
	}
	var recentermap = function() {
	    myMapApp.map.centerAndZoom(new GPoint(lon, lat), zoom);
	}
	var gotomap = function() {
	    var lon = 1*document.getElementById("gmap_lon").value;
	    var lat = 1*document.getElementById("gmap_lat").value;
	    myMapApp.map.centerAndZoom(new GPoint(lon, lat), zoom);
	}
	var addfaves = function() {
	    var i;
	    var _favs = document.getElementById("favs_select");
	    var o = document.createElement('option');
	    var lon = myMapApp.map.getCenterLatLng().x;
	    var lat = myMapApp.map.getCenterLatLng().y;
	    var zoom = myMapApp.map.getZoomLevel();
	    var place = prompt('Name the place');
	    var favs_num = 1*GMiF_getValue('favs_num',0);
	    var xy = lat+','+lon+','+zoom;
	    for(i=0; i<favs_num; i++) {
		if( GMiF_getValue('favs_place_'+i) == place ) break;
		if( GMiF_getValue('favs_place_'+i) == false ) break;
		if( GMiF_getValue('favs_place_'+i) == 'false' ) break;
	    }
	    GMiF_setValue('favs_place_'+i, place);
	    GMiF_setValue('favs_xy_'+i, xy);
	    if( favs_num<=i ) GMiF_setValue('favs_num',1*favs_num+1);
	    o.innerHTML = place;
	    o.value = xy;
	    _favs.add(o,null);
	    _favs.selectedIndex = _favs.length-1;
	}
	var gotofav = function() {
	    var re = /([\d\.-]+),([\d\.-]+),([\d\.-]+)/;
	    var m = re.exec(this.value);
	    var lat = 1*m[1];
	    var lon = 1*m[2];
	    var zoom = (m.length==4) ? m[3] : 4;
	    myMapApp.map.centerAndZoom(new GPoint(lon, lat), zoom);
	}
	var showmap = function() { 
	    if( !_mapLoaded ) {

		var _linkto = document.createElement('input');
		_linkto.type = 'button';
		_linkto.value = 'Google Maps';
		_linkto.setAttribute('class','SmallButt');
		_linkto.onclick = largemap;

		var _flyto = document.createElement('input');
		_flyto.type = 'button';
		_flyto.value = 'Fly To';
		_flyto.setAttribute('class','SmallButt');
		_flyto.onclick = function() {
		    var flat = myMapApp.map.getCenterLatLng().y;
		    var flon = myMapApp.map.getCenterLatLng().x;
		    var url = document.location;
//		    document.location = 'http://flickr.yuan.cc/gmif/makeKML.php?lat=' + flat + '&lon=' + flon + '&img=' + img_t + '&title=' + title + '&url=' + url;
		    document.location = 'http://www.roblog.com/flickrfly.php';
		}

		var _nearby = document.createElement('input');
		_nearby.type = 'button';
		_nearby.value = 'Nearby Photos';
		_nearby.setAttribute('class','SmallButt');
		_nearby.onclick = getNearbyPhotos;

		var _hide = document.createElement('input');
		_hide.type = 'button';
		_hide.value = 'Hide Map';
		_hide.setAttribute('class','SmallButt');
		_hide.onclick = hidemap;

		var _lengthen = document.createElement('input');
		_lengthen.type = 'button';
		_lengthen.value = 'Lengthen Map';
		_lengthen.setAttribute('class','SmallButt');
		_lengthen.onclick = function() {
		    var len = 1 * myMapApp.mapContainer.style.height.substring(0,myMapApp.mapContainer.style.height.indexOf('px')) + 50;
		    resizeMap(len);
		}

		var _shorten = document.createElement('input');
		_shorten.type = 'button';
		_shorten.value = 'Shorten Map';
		_shorten.setAttribute('class','SmallButt');
		_shorten.onclick = function() {
		    var len = 1 * myMapApp.mapContainer.style.height.substring(0,myMapApp.mapContainer.style.height.indexOf('px')) - 50;
		    resizeMap(len);
		}

		var _center = document.createElement('input');
		_center.type = 'button';
		_center.value = 'Recenter';
		_center.setAttribute('class','SmallButt');
		_center.onclick = recentermap;

		var _options = document.createElement('input');
		_options.setAttribute('id','gmap_optbutton');
		_options.type = 'button';
		_options.value = 'Options';
		_options.setAttribute('class','SmallButt');

		var _lat = document.createElement('input');
		_lat.id = 'gmap_lat';
		_lat.type = 'text';
		_lat.size = '9';
		_lat.setAttribute('style','font: 10px Arial');

		var _lon = document.createElement('input');
		_lon.id = 'gmap_lon';
		_lon.type = 'text';
		_lon.size = '9';
		_lon.setAttribute('style','font: 10px Arial');

		var _goto = document.createElement('input');
		_goto.type = 'button';
		_goto.value = 'Goto';
		_goto.setAttribute('class','SmallButt');
		_goto.onclick = gotomap;

		var _addfav = document.createElement('input');
		_addfav.type = 'button';
		_addfav.value = 'Add Fav';
		_addfav.setAttribute('class','SmallButt');
		_addfav.onclick = addfaves;

		var _delfav = document.createElement('input');
		_delfav.type = 'button';
		_delfav.value = 'Del Fav';
		_delfav.setAttribute('class','SmallButt');
		_delfav.onclick = function() {
		    var _favs = document.getElementById("favs_select");
		    var place = _favs.options[_favs.selectedIndex].text;
		    for(var k=0; k<1*GMiF_getValue('favs_num',0); k++) {
			if( place == GMiF_getValue('favs_place_'+k) ) {
			    GMiF_setValue('favs_place_'+k, false);
			    GMiF_setValue('favs_xy_'+k, false);
			}
		    }
		    _favs.remove(_favs.selectedIndex);
		}

		var _delallfav = document.createElement('input');
		_delallfav.type = 'button';
		_delallfav.value = 'Del All';
		_delallfav.setAttribute('class','SmallButt');
		_delallfav.onclick = function() {
		    var _favs = document.getElementById("favs_select");
		    var len = 1*_favs.options.length;
		    _favs.selectedIndex = 0;
		    GMiF_setValue('favs_num', 0);
		    for(var k=1; k<len; k++) _favs.remove(1);
		}

		var _favs = document.createElement('select');
		_favs.id = 'favs_select';
		_favs.value = 'Add to faves';
		_favs.setAttribute('class','SmallButt');
		_favs.style.backgroundColor = '#ffffff';
		_favs.style.color = '#000000';
		_favs.onchange = gotofav;
		var o = document.createElement('option');
		o.innerHTML = 'Saved Places';
		_favs.add(o,null);
		for(var k=0; k<1*GMiF_getValue('favs_num', 0); k++) {
		    var place = GMiF_getValue('favs_place_' + k);
		    var xy = GMiF_getValue('favs_xy_' + k);
		    if( place == undefined || !place || !xy || place == 'false' ) continue;
		    var o = document.createElement('option');
		    o.innerHTML = place;
		    o.value = xy;
		    _favs.add(o,null);
		}

		var _optionsdiv = document.createElement('div');
		_optionsdiv.setAttribute('id','gmap_options');
		_optionsdiv.style.position = 'absolute';
		_optionsdiv.style.top = '50px';
		_optionsdiv.style.left = '100px';
		_optionsdiv.style.zIndex = 80000;
		_optionsdiv.style.width = '300px';
		_optionsdiv.style.height = '200px';
		_optionsdiv.style.border = '2px solid #cc8';
		_optionsdiv.style.backgroundColor = '#ffffd3';
		_optionsdiv.style.margin = '2px';
		_optionsdiv.style.padding = '5px';
		_optionsdiv.style.display = 'none';
		var str = '<a id="option_close" href="javascript:;" onClick=""><img src="http://www.google.com/mapfiles/close.gif" border="0" align="right" style="border:0px;background:transparent;"></a>';
		str += '<p align="center"><big><b>GMiF Options</b></big></p>';
		str += 'Photo description/comment to be added: <br />';
		str += '<textarea id="option_desc" rows=5 cols=40 style="font-size:11px;"></textarea><br />';
		str += 'Default Map Type: <input id="option_map" type=radio name="default_map" value="map">Map ';
		str += '<input id="option_sat" type=radio name="default_map" value="sat">Satellite<br />';
		str += '<input id="option_jphacks" type=checkbox checked> Enable Japan Datum Hacks<br />';
		str += '<p align=center>';
		str += '<input id="option_save" type=button class="SmallButt" value="Save"> ';
		str += '<input id="option_cancel" type=button class="SmallButt" value="Cancel"></p>';
		_optionsdiv.innerHTML = str;

		googlemaps = document.createElement('div');
		container = document.createElement('div');
		container.setAttribute('id','container');
		container.style.width = '500px';
		container.style.height = _height;
		container.appendChild(document.createElement('br'));
		container.appendChild(document.createTextNode('Lat: '));
		container.appendChild(_lat);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(document.createTextNode('Lon: '));
		container.appendChild(_lon);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_goto);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_favs);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_addfav);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_delfav);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_delallfav);
		container.appendChild(document.createElement('br'));
		container.appendChild(_linkto);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_flyto);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_nearby);
		container.appendChild(document.createTextNode(' '));
//		container.appendChild(_hide);
		container.appendChild(_options);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_lengthen);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_shorten);
		container.appendChild(document.createTextNode(' '));
		container.appendChild(_center);
		container.appendChild(document.createElement('br'));
		container.appendChild(googlemaps);
		googlemaps.appendChild(_optionsdiv);
		insertPoint.parentNode.insertBefore(container, gname.nextSibling);
//		if( _geocoded && exif.lat != undefined ) {
		if( exif.lat != undefined && exif.lon != undefined ) {
		    lat = exif.lat;
		    lon = exif.lon;
		    zoom = 4;
		    marked = true;
		}

		// initial GMap
		initMap(title,img_t,zoom,marked);
		_mapLoaded = true;

		// initial options
		if( GMiF_getValue('option_desc') == undefined )
		    GMiF_setValue('option_desc', geobloggers_text);
		else geobloggers_text = GMiF_getValue('option_desc');
		document.getElementById("option_desc").value = geobloggers_text;
		if( GMiF_getValue('option_maptype') == undefined ) {
		    document.getElementById("option_map").checked = true;
		    GMiF_setValue('option_maptype','map');
		} else {
		    if( GMiF_getValue('option_maptype') == 'map' ) 
			 document.getElementById("option_map").checked = true;
		    else document.getElementById("option_sat").checked = true;
		}
		if( GMiF_getValue('option_jphacks') || 
		    GMiF_getValue('option_jphacks') == undefined ) {
		    document.getElementById("option_jphacks").checked = true;
		    _SATELLITE_TYPE.japanDatumHack = true;
		    GMiF_setValue('option_jphacks', true);
		} else {
		    _SATELLITE_TYPE.japanDatumHack = false;
		}
		var map_show_options = function() {
		    var o = document.getElementById("gmap_options");
		    var mlen = 1*myMapApp.mapContainer.style.height.substring(0,myMapApp.mapContainer.style.height.indexOf('px'));
		    var olen = 1*o.style.height.substring(0,o.style.height.indexOf('px')) + 
			       1*o.style.top.substring(0,o.style.top.indexOf('px'));
		    if( mlen < olen+50 ) resizeMap(olen+50);
		    o.style.display = 'block';
		    this.onclick = map_hide_options;
		}
		var map_hide_options = function() {
		    var o = document.getElementById("gmap_options");
		    o.style.display = 'none';
		    document.getElementById("gmap_optbutton").onclick = map_show_options;
		}
		_options.onclick = map_show_options;
		document.getElementById("option_close").onclick = map_hide_options;
		document.getElementById("option_cancel").onclick = map_hide_options;
		document.getElementById("option_save").onclick = function() {
		    geobloggers_text = document.getElementById("option_desc").value;
		    GMiF_setValue('option_desc',geobloggers_text);
		    if( document.getElementById("option_map").checked ) 
			GMiF_setValue('option_maptype', 'map');
		    else GMiF_setValue('option_maptype', 'sat');
		    if( document.getElementById("option_jphacks").checked ) {
			GMiF_setValue('option_jphacks', true);
			_SATELLITE_TYPE.japanDatumHack = true;
		    } else {
			GMiF_setValue('option_jphacks', false);
			_SATELLITE_TYPE.japanDatumHack = false;
		    }
		    map_hide_options();
		}
	    } else {
		container.style.visibility = 'visible';
		container.style.width='500px';
		container.style.height = _height;
	    }
	    gmap.href = '#gmap';
	    gmap.onclick = hidemap;
	}
	gmap.onclick = showmap;
	document.getElementById('button_bar').appendChild(gmap);
}

function initMap(title,img,zoom,marked) {

    lon = 1*lon; lat = 1*lat;
    myMapApp = new _MapsApplication(googlemaps, panel, metapanel, permalink, printheader, createMapSpecs());
    myMapApp.loadMap();
//    _SATELLITE_TYPE.japanDatumHack = true;
//    myMapApp.map.setMapType(_SATELLITE_TYPE);
    if( GMiF_getValue('option_maptype') == undefined ) {
	document.getElementById("option_map").checked = true;
	GMiF_setValue('option_maptype','map');
    } else {
	if( GMiF_getValue('option_maptype') == 'map' ) 
	    document.getElementById("option_map").checked = true;
	else {
	    document.getElementById("option_sat").checked = true;
	    myMapApp.map.setMapType(_SATELLITE_TYPE);
	}
    }

    myMapApp.map.centerAndZoom(new GPoint(lon, lat), zoom);

    if( marked ) {
	var point = new GPoint(lon,lat);
	marker = createMarker(point,title,img,'','','','',0,true);
	myMapApp.map.addOverlay(marker);
    }

    GEvent.addListener(myMapApp.map, 'click', function(overlay, point) {
	if (overlay) {
//	    myMapApp.map.removeOverlay(overlay);
	} else if (point && _cadaddtag) {
//	    myMapApp.map.clearOverlays();
	    if( marker!=null && !marker.lock || _isowner ) {
		myMapApp.map.removeOverlay(marker);
		delete marker;
	    }
	    marker = createMarker(point,title,img,'','','','',0,false);
	    myMapApp.map.addOverlay(marker);
	    GMiF_setValue('geo:lon', point.x);
	    GMiF_setValue('geo:lat', point.y);
	}
    });

    GEvent.addListener(myMapApp.map, "moveend", function() {
	var center = myMapApp.map.getCenterLatLng();
	var x = Math.round(center.x * 1000000) / 1000000.0;
	var y = Math.round(center.y * 1000000) / 1000000.0;
	document.getElementById("gmap_lon").value = x;
	document.getElementById("gmap_lat").value = y;
    });

    window.addEventListener("resize",resizeMap,true);
    resizeMap(500);
    var center = myMapApp.map.getCenterLatLng();
    var x = Math.round(center.x * 1000000) / 1000000.0;
    var y = Math.round(center.y * 1000000) / 1000000.0;
    document.getElementById("gmap_lon").value = x;
    document.getElementById("gmap_lat").value = y;
}

function resizeMap(len) {
	if( !len ) len = 500;
	myMapApp.mapContainer.style.height = len + 'px'; 
	myMapApp.map.onResize();
}

function createMarker(point,title,img,url,username,userurl,datetaken,mode,locked) {

    var icon = new GIcon();
    if( mode == 0 ) icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
    else icon.image = "http://labs.google.com/ridefinder/images/mm_20_blue.png";
    icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);
    var marker = new GMarker(point, icon);
    marker.lock = locked;
    var html = "<h4>" + title + "</h4>";
    html += '<small>' + datetaken + '</small>';
    var x = Math.round(point.x * 1000000) / 1000000.0;
    var y = Math.round(point.y * 1000000) / 1000000.0;
    html += '<table border=0><tr><td>';
    if(mode==1) html += '<a href="' + url + '">';
    html += '<img width=100 height=75 src="' + img + '" align=left />';
    if(mode==1) html += '</a>';
    html += '</td><td nowrap>';
    if(mode==1) html += '<p>Author: <a href="' + userurl + '">' + username + '</a></p>';
    html += '<p><small>Lon: ' + x + '<br />';
    html += 'Lat: ' + y + '</small></p>';
    if( mode == 0 ) {		// plaec new marker
	html += '<a href="javascript:;" onClick="addgeotags(' + point.y + ',' + point.x + ');return false">Add geo tags</a><br />';
	html += '<a href="javascript:;" onClick="window.addtodescription();">Add Description</a><br/>' ; //var desc_div=_ge(\'description_div'+photo_id+'\');desc_div.startEditing();
	html += '<a href="javascript:;" onClick="addcomment();return false;">Add Comment</a><br/>';
	html += '<a href="javascript:;" onClick="postToGeoBloggers(); return false;"; //var geoblog_post = document.createElement(\'img\');geoblog_post.width=0;geoblog_post.height=0;geoblog_post.src=\'http://www.geobloggers.com/\';document.body.appendChild(geoblog_post);">Post to Geobloggers</a>';
	html += '<p><a href="javascript:;" onClick="robogeotagger(' + point.y + ',' + point.x + ');return false;">RoboGeoTagger - Do it All!</a></p>' ; //busysignal(\'RoboGeoTagger, Adding Description - Please Wait.\',\'start\');
    }
    if(mode==1) html += '<a href="' + url + '">Go to photo</a>';

    html += '</td></tr></table>';
    GEvent.addListener(marker, "click", function() {
	marker.openInfoWindowHtml(html);
    });

    return marker;
}

function getExif(photo) {

    var str = ''+document.location;
    if( str.match('www.flickr.com') ) www = 'www.';
    else www = '';
    GMiF_xmlhttpRequest({
	method: 'GET',
	url: 'http://' + www + 'flickr.com/services/rest/?method=flickr.photos.getExif&api_key=bc60075f4ce963fab3fac473d0741fe8&photo_id=' + photo.id,
	headers: {
	    'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey GMap in Flickr',
	    'Accept': 'application/atom+xml,application/xml,text/xml'
	},
	onload: function(result) {
	    var i,lat,lon,lat0,lat1,lat2,lon0,lon1,lon2,lat_sign,lon_sign;
	    var parser = new DOMParser();
	    var dom = parser.parseFromString(result.responseText, "application/xml");
	    var tag_exif = dom.getElementsByTagName('exif');

	    for(i=0; i<tag_exif.length; i++) {
		if( tag_exif[i].getAttribute('tagspace') != 'GPS' ) continue;
		if( tag_exif[i].getAttribute('label') == 'North or South Latitude' ) {
		    if( tag_exif[i].getElementsByTagName('raw').item(0).firstChild.data=='N') lat_sign=1;
		    if( tag_exif[i].getElementsByTagName('raw').item(0).firstChild.data=='S') lat_sign=-1;
		}
		if( tag_exif[i].getAttribute('label') == 'East or West Longitude' ) {
		    if( tag_exif[i].getElementsByTagName('raw').item(0).firstChild.data=='E') lon_sign=1;
		    if( tag_exif[i].getElementsByTagName('raw').item(0).firstChild.data=='W') lon_sign=-1;
		}
		if( tag_exif[i].getAttribute('label') == 'Latitude' ) {
		    lat_raw = tag_exif[i].getElementsByTagName('raw').item(0).firstChild.data;
		    lat0 = lat_raw.split(',')[0].split('/')[0] / lat_raw.split(',')[0].split('/')[1];
		    lat1 = lat_raw.split(',')[1].split('/')[0] / lat_raw.split(',')[1].split('/')[1];
		    lat2 = lat_raw.split(',')[2].split('/')[0] / lat_raw.split(',')[2].split('/')[1];
		    lat = lat_sign * ((lat2/60+lat1)/60 + lat0);
		}
		if( tag_exif[i].getAttribute('label') == 'Longitude' ) {
		    lon_raw = tag_exif[i].getElementsByTagName('raw').item(0).firstChild.data;
		    lon0 = lon_raw.split(',')[0].split('/')[0] / lon_raw.split(',')[0].split('/')[1];
		    lon1 = lon_raw.split(',')[1].split('/')[0] / lon_raw.split(',')[1].split('/')[1];
		    lon2 = lon_raw.split(',')[2].split('/')[0] / lon_raw.split(',')[2].split('/')[1];
		    lon = lon_sign * ((lon2/60+lon1)/60 + lon0);
		}
	    }
	    exif.lat = lat;
	    exif.lon = lon;
	}
    });
}

init();

function macro(str) {

    var flat = myMapApp.map.getCenterLatLng().y;
    var flon = myMapApp.map.getCenterLatLng().x;
    var url = document.location;
//    var flyto = 'http://flickr.yuan.cc/gmif/makeKML.php?lat=' + flat + '&lon=' + flon + '&img=' + img_t + '&title=' + title + '&url=' + url;
    var flyto = 'http://www.roblog.com/flickrfly.php';
    var mapurl = 'http://maps.google.com/maps?ll=' + myMapApp.map.getCenterLatLng().y + ',' + myMapApp.map.getCenterLatLng().x + '&spn=' + myMapApp.map.getSpanLatLng().width + ',' + myMapApp.map.getSpanLatLng().height + '&hl=en';

    var rExp = /{FLYTO_KML}/gi;
    var flyto_text = 'Google Earth';
    str = str.replace(rExp, flyto_text.link(flyto))
    rExp = /{GMAP_URL}/gi;
    var gmap_text = '<a href="' + mapurl + '" target=_blank>Google Maps</a>';
    str = str.replace(rExp, gmap_text);

    return str;
}

busysignal = function(message,command) {
    if (command == 'start')
      photo_notes.EXT.start_comming(message); return false;
    if (command == 'stop')
      photo_notes.EXT.stop_comming(1); return false;
}

window.addtodescription = function() {

    var new_text = macro(geobloggers_text);
    var desc_div=eval('description_div'+photo_id);
    desc_div.startEditing();
    textyarea=window.getElementByName('content');
    if (textyarea.value.length)
        textyarea.value=textyarea.value + '\n' + new_text; 
    else
        textyarea.value = new_text;
    textyarea.parentNode.parentNode.display_div.saveChanges(textyarea.parentNode);
}

addcomment = function () {

    var new_text = macro(geobloggers_text);
    urlarr = location.href.split('/');
    ps_photo_id = photo_id; //urlarr[5];
    user_id=urlarr[4];
//    comment=encodeURIComponent('<a href=\"http://www.geobloggers.com\">Location</a>');
    comment=encodeURIComponent(new_text);

    var str = ''+document.location;
    if( str.match('www.flickr.com') ) www = 'www.';
    GMiF_xmlhttpRequest({
      method: 'POST',
      url: 'http://' + www + 'flickr.com/photos/' + user_id + '/' + ps_photo_id + '/',
      headers: {
        'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
        'Content-type': 'application/x-www-form-urlencoded',
        'Accept': 'application/atom+xml,application/xml,text/xml',
        'Referer': 'http://flickr.com/photos/' + user_id + '/' + ps_photo_id + '/',
      },
      data: 'addcomment=1&message=' + comment + '&submit=POST+COMMENT&magic_cookie='+global_auth_hash,
      onload: function(responseDetails) {

          //if (responseDetails.responseText.match(comment))
          //    alert('comment added successfully!');
          //else
          //    alert('comment add failed!');
          ;
      }
    });
}

addgeotags = function (lat,lon) {
    //tagrs_addTag(ps_photo_id, \'geo:lat=' + parseFloat(point.y).toFixed(6) + ' geo:lon=' + parseFloat(point.x).toFixed(6) + ' geotagged\');
    ps_photo_id = photo_id;
    tagrs_addTag(ps_photo_id, 'geotagged geo:lat=' + parseFloat(lat).toFixed(6) + ' geo:lon=' + parseFloat(lon).toFixed(6));
}

postToGeoBloggers = function () {
    urlarr = location.href.split('/');
    ps_photo_id= photo_id //urlarr[5];
    user_id=urlarr[4];

    thisphotoURL="http://photos" + photo_hash[ps_photo_id].server + '.flickr.com/' + ps_photo_id + "_" + photo_hash[ps_photo_id].secret + "_s.jpg";
    //alert(thisphotoURL);
    waitingMsg('Posting to Geobloggers......');

    GMiF_xmlhttpRequest({
      method: 'GET',
      url: 'http://www.geobloggers.com',
      headers: {
        'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
        'Accept': 'application/atom+xml,application/xml,text/xml',
        'Referer': 'http://flickr.com/photos/' + user_id + '/' + ps_photo_id + '/',
      },
      onload: function(responseDetails) {
          //alert('Request for Atom feed returned ' + responseDetails.status +
          //    ' ' + responseDetails.statusText + '\n\n' +
	  googlemaps.removeChild(document.getElementById('gbinfo'));

          if (responseDetails.responseText.match(thisphotoURL))
                alert('Image successfully added to GeoBloggers.com');
          else
                alert('Add to GeoBloggers.com failed, try manual adding via clicking the geobloggers link.');
          busysignal('','stop');
      }
    });
}

robogeotagger = function (lat,lon) {
    //busysignal('RoboGeoTagger, Adding GeoTags - Please Wait.','start');
    addgeotags( lat , lon );
    //busysignal('','stop');
    //busysignal('RoboGeoTagger, Adding Description - Please Wait.','start');
    if( _isowner ) window.addtodescription();
    else window.addcomment();
    //busysignal('','stop');
    //busysignal('RoboGeoTagger, Posting to GeoBloggers - Please Wait.','start');
    postToGeoBloggers();
    //busysignal('','stop');
    return false;
}

window.getElementByName = function(elementName)
{
   var element = null;
   for(formIndex=0; formIndex < document.forms.length; formIndex++)
   {
      for(elementIndex=0; elementIndex < document.forms[formIndex].elements.length; elementIndex++)
      {
         if(document.forms[formIndex].elements[elementIndex].name == elementName)
         {
            element = document.forms[formIndex].elements[elementIndex];
            break;
         }
      }
   }
   return element;
}

function waitingMsg(msg) {

    var postinfo = document.createElement('div');
    postinfo.setAttribute('id','gbinfo');
    postinfo.className = 'td_note_white';
    postinfo.style.position = 'absolute';
    postinfo.style.top = '100px';
    postinfo.style.left = '150px';
    postinfo.style.zIndex = 50000;
    postinfo.style.width = '200px';
    postinfo.style.height = '20px';
    postinfo.style.padding = '8px';
    postinfo.style.background = 'transparent';
    var str = '<table padding=0 cellspacing=0>';
    str += '<tr><td class="td_note_white"><img src="http://www.flickr.com/images/pulser2.gif" border=0 align=left style="border:0px;" /></td><td class="td_note_white"><strong>';
    str += msg;
    str += '</strong></td></tr>';
    str += '</table>';
    postinfo.innerHTML = str;
    googlemaps.appendChild(postinfo);
    myMapApp.map.closeInfoWindow();
}

var getNearbyPhotos = function () {

    var bounds = myMapApp.map.getBoundsLatLng();

    waitingMsg('Getting nearby photos from Geobloggers......');
    GMiF_xmlhttpRequest({
	method: 'GET',
	url: 'http://www.geobloggers.com/makeXML.cfm?range=' + bounds.minX + ',' + bounds.minY + ',' + bounds.maxX + ',' + bounds.maxY + '&mode=googleXML&iMaxRecords=25',
	headers: {
	    'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey GMap in Flickr',
	    'Accept': 'application/atom+xml,application/xml,text/xml'
	},
	onload: function(result) {
	    googlemaps.removeChild(document.getElementById('gbinfo'));
	    var title='',userurl,username,url,img,datetaken,point,mkr,i,glat,glon;
	    var parser = new DOMParser();
	    var dom = parser.parseFromString(result.responseText, "application/xml");
	    var places = dom.getElementsByTagName('location');
	    for(i=0; i<places.length; i++) {
		if( places[i].getElementsByTagName('info').item(0).getElementsByTagName('title').item(0).firstChild ) {
		    title = places[i].getElementsByTagName('info').item(0).getElementsByTagName('title').item(0).firstChild.data;
		}
		datetaken = places[i].getElementsByTagName('info').item(0).getElementsByTagName('datetaken').item(0).firstChild.data;
		username = places[i].getElementsByTagName('info').item(0).getElementsByTagName('username').item(0).firstChild.data;
		url = 'http://' + places[i].getElementsByTagName('url').item(0).firstChild.data;
		userurl = 'http://' + places[i].getElementsByTagName('userurl').item(0).firstChild.data;
		img = 'http://' + places[i].getElementsByTagName('img').item(0).firstChild.data;
		glat = 1*places[i].getElementsByTagName('point').item(0).getAttribute('lat');
		glon = 1*places[i].getElementsByTagName('point').item(0).getAttribute('lng');
		if( glat != lat || glon != lon ) {
		point = new GPoint(glon,glat);
		    mkr = createMarker(point,title,img,url,username,userurl,datetaken,1,false);
		    myMapApp.map.addOverlay(mkr);
		}
	    }
	}
    });
}

function GMiF_getValue(key, defaultValue) {

    if(_GMAPI) return GM_setValue(key, defaultValue);
    else {
	if( getCookie(key) == undefined ) return defaultValue;
	else {
	    setCookie(key, getCookie(key),1000);
	    return getCookie(key);
	}
//	else return eval(getCookie(key));
    }
}

function GMiF_setValue(key,value) {

    if(_GMAPI) GM_setValue(key, value);
    else setCookie(key,value,1000);
}

function GMiF_xmlhttpRequest(req) {

    if(_GMAPI) GM_xmlhttpRequest(req); 
    else {
	var xmlhttp = new XMLHttpRequest();
	xmlhttp.onreadystatechange = function() {
	    if (xmlhttp.readyState==4) {
		if (xmlhttp.status==200) {
		    req.onload(xmlhttp);
		}
	    }
	}
	xmlhttp.open(req.method, req.url, true);
	xmlhttp.send(null);
    }
}
})();
