/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
/*
 * jQuery Tooltip plugin 1.3
 *
 * http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/
 * http://docs.jquery.com/Plugins/Tooltip
 *
 * Copyright (c) 2006 - 2008 Jörn Zaefferer
 *
 * $Id: jquery.tooltip.js 5741 2008-06-21 15:22:16Z joern.zaefferer $
 * 
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */;(function($){var helper={},current,title,tID,IE=$.browser.msie&&/MSIE\s(5\.5|6\.)/.test(navigator.userAgent),track=false;$.tooltip={blocked:false,defaults:{delay:200,fade:false,showURL:true,extraClass:"",top:15,left:15,id:"tooltip"},block:function(){$.tooltip.blocked=!$.tooltip.blocked;}};$.fn.extend({tooltip:function(settings){settings=$.extend({},$.tooltip.defaults,settings);createHelper(settings);return this.each(function(){$.data(this,"tooltip",settings);this.tOpacity=helper.parent.css("opacity");this.tooltipText=this.title;$(this).removeAttr("title");this.alt="";}).mouseover(save).mouseout(hide).click(hide);},fixPNG:IE?function(){return this.each(function(){var image=$(this).css('backgroundImage');if(image.match(/^url\(["']?(.*\.png)["']?\)$/i)){image=RegExp.$1;$(this).css({'backgroundImage':'none','filter':"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+image+"')"}).each(function(){var position=$(this).css('position');if(position!='absolute'&&position!='relative')$(this).css('position','relative');});}});}:function(){return this;},unfixPNG:IE?function(){return this.each(function(){$(this).css({'filter':'',backgroundImage:''});});}:function(){return this;},hideWhenEmpty:function(){return this.each(function(){$(this)[$(this).html()?"show":"hide"]();});},url:function(){return this.attr('href')||this.attr('src');}});function createHelper(settings){if(helper.parent)return;helper.parent=$('<div id="'+settings.id+'"><h3></h3><div class="body"></div><div class="url"></div></div>').appendTo(document.body).hide();if($.fn.bgiframe)helper.parent.bgiframe();helper.title=$('h3',helper.parent);helper.body=$('div.body',helper.parent);helper.url=$('div.url',helper.parent);}function settings(element){return $.data(element,"tooltip");}function handle(event){if(settings(this).delay)tID=setTimeout(show,settings(this).delay);else
show();track=!!settings(this).track;$(document.body).bind('mousemove',update);update(event);}function save(){if($.tooltip.blocked||this==current||(!this.tooltipText&&!settings(this).bodyHandler))return;current=this;title=this.tooltipText;if(settings(this).bodyHandler){helper.title.hide();var bodyContent=settings(this).bodyHandler.call(this);if(bodyContent.nodeType||bodyContent.jquery){helper.body.empty().append(bodyContent)}else{helper.body.html(bodyContent);}helper.body.show();}else if(settings(this).showBody){var parts=title.split(settings(this).showBody);helper.title.html(parts.shift()).show();helper.body.empty();for(var i=0,part;(part=parts[i]);i++){if(i>0)helper.body.append("<br/>");helper.body.append(part);}helper.body.hideWhenEmpty();}else{helper.title.html(title).show();helper.body.hide();}if(settings(this).showURL&&$(this).url())helper.url.html($(this).url().replace('http://','')).show();else
helper.url.hide();helper.parent.addClass(settings(this).extraClass);if(settings(this).fixPNG)helper.parent.fixPNG();handle.apply(this,arguments);}function show(){tID=null;if((!IE||!$.fn.bgiframe)&&settings(current).fade){if(helper.parent.is(":animated"))helper.parent.stop().show().fadeTo(settings(current).fade,current.tOpacity);else
helper.parent.is(':visible')?helper.parent.fadeTo(settings(current).fade,current.tOpacity):helper.parent.fadeIn(settings(current).fade);}else{helper.parent.show();}update();}function update(event){if($.tooltip.blocked)return;if(event&&event.target.tagName=="OPTION"){return;}if(!track&&helper.parent.is(":visible")){$(document.body).unbind('mousemove',update)}if(current==null){$(document.body).unbind('mousemove',update);return;}helper.parent.removeClass("viewport-right").removeClass("viewport-bottom");var left=helper.parent[0].offsetLeft;var top=helper.parent[0].offsetTop;if(event){left=event.pageX+settings(current).left;top=event.pageY+settings(current).top;var right='auto';if(settings(current).positionLeft){right=$(window).width()-left;left='auto';}helper.parent.css({left:left,right:right,top:top});}var v=viewport(),h=helper.parent[0];if(v.x+v.cx<h.offsetLeft+h.offsetWidth){left-=h.offsetWidth+20+settings(current).left;helper.parent.css({left:left+'px'}).addClass("viewport-right");}if(v.y+v.cy<h.offsetTop+h.offsetHeight){top-=h.offsetHeight+20+settings(current).top;helper.parent.css({top:top+'px'}).addClass("viewport-bottom");}}function viewport(){return{x:$(window).scrollLeft(),y:$(window).scrollTop(),cx:$(window).width(),cy:$(window).height()};}function hide(event){if($.tooltip.blocked)return;if(tID)clearTimeout(tID);current=null;var tsettings=settings(this);function complete(){helper.parent.removeClass(tsettings.extraClass).hide().css("opacity","");}if((!IE||!$.fn.bgiframe)&&tsettings.fade){if(helper.parent.is(':animated'))helper.parent.stop().fadeTo(tsettings.fade,0,complete);else
helper.parent.stop().fadeOut(tsettings.fade,complete);}else
complete();if(settings(this).fixPNG)helper.parent.unfixPNG();}})(jQuery);
(function($){$.fn.editable=function(target,options){var settings={target:target,name:'value',id:'id',type:'text',width:'auto',height:'auto',event:'click',onblur:'cancel',loadtype:'GET',loadtext:'Loading...',placeholder:'Click to edit',loaddata:{},submitdata:{},ajaxoptions:{}};if(options){$.extend(settings,options);}
var plugin=$.editable.types[settings.type].plugin||function(){};var submit=$.editable.types[settings.type].submit||function(){};var buttons=$.editable.types[settings.type].buttons||$.editable.types['defaults'].buttons;var content=$.editable.types[settings.type].content||$.editable.types['defaults'].content;var element=$.editable.types[settings.type].element||$.editable.types['defaults'].element;var reset=$.editable.types[settings.type].reset||$.editable.types['defaults'].reset;var callback=settings.callback||function(){};var onsubmit=settings.onsubmit||function(){};var onreset=settings.onreset||function(){};var onerror=settings.onerror||reset;if(!$.isFunction($(this)[settings.event])){$.fn[settings.event]=function(fn){return fn?this.bind(settings.event,fn):this.trigger(settings.event);}}
$(this).attr('title',settings.tooltip);settings.autowidth='auto'==settings.width;settings.autoheight='auto'==settings.height;return this.each(function(){var self=this;var savedwidth=$(self).width();var savedheight=$(self).height();if(!$.trim($(this).html())){$(this).html(settings.placeholder);}
$(this)[settings.event](function(e){if(self.editing){return;}
$(self).removeAttr('title');if(0==$(self).width()){settings.width=savedwidth;settings.height=savedheight;}else{if(settings.width!='none'){settings.width=settings.autowidth?$(self).width():settings.width;}
if(settings.height!='none'){settings.height=settings.autoheight?$(self).height():settings.height;}}
if($(this).html().toLowerCase().replace(/;/,'')==settings.placeholder.toLowerCase().replace(/;/,'')){$(this).html('');}
self.editing=true;self.revert=$(self).html();$(self).html('');var form=$('<form />');if(settings.cssclass){if('inherit'==settings.cssclass){form.attr('class',$(self).attr('class'));}else{form.attr('class',settings.cssclass);}}
if(settings.style){if('inherit'==settings.style){form.attr('style',$(self).attr('style'));form.css('display',$(self).css('display'));}else{form.attr('style',settings.style);}}
var input=element.apply(form,[settings,self]);var input_content;if(settings.loadurl){var t=setTimeout(function(){input.disabled=true;content.apply(form,[settings.loadtext,settings,self]);},100);var loaddata={};loaddata[settings.id]=self.id;if($.isFunction(settings.loaddata)){$.extend(loaddata,settings.loaddata.apply(self,[self.revert,settings]));}else{$.extend(loaddata,settings.loaddata);}
$.ajax({type:settings.loadtype,url:settings.loadurl,data:loaddata,async:false,success:function(result){window.clearTimeout(t);input_content=result;input.disabled=false;}});}else if(settings.data){input_content=settings.data;if($.isFunction(settings.data)){input_content=settings.data.apply(self,[self.revert,settings]);}}else{input_content=self.revert;}
content.apply(form,[input_content,settings,self]);input.attr('name',settings.name);buttons.apply(form,[settings,self]);$(self).append(form);plugin.apply(form,[settings,self]);$(':input:visible:enabled:first',form).focus();if(settings.select){input.select();}
input.keydown(function(e){if(e.keyCode==27){e.preventDefault();reset.apply(form,[settings,self]);}});var t;if('cancel'==settings.onblur){input.blur(function(e){t=setTimeout(function(){reset.apply(form,[settings,self]);},500);});}else if('submit'==settings.onblur){input.blur(function(e){t=setTimeout(function(){form.submit();},200);});}else if($.isFunction(settings.onblur)){input.blur(function(e){settings.onblur.apply(self,[input.val(),settings]);});}else{input.blur(function(e){});}
form.submit(function(e){if(t){clearTimeout(t);}
e.preventDefault();if(false!==onsubmit.apply(form,[settings,self])){if(false!==submit.apply(form,[settings,self])){if($.isFunction(settings.target)){var str=settings.target.apply(self,[input.val(),settings]);$(self).html(str);self.editing=false;callback.apply(self,[self.innerHTML,settings]);if(!$.trim($(self).html())){$(self).html(settings.placeholder);}}else{var submitdata={};submitdata[settings.name]=input.val();submitdata[settings.id]=self.id;if($.isFunction(settings.submitdata)){$.extend(submitdata,settings.submitdata.apply(self,[self.revert,settings]));}else{$.extend(submitdata,settings.submitdata);}
if('PUT'==settings.method){submitdata['_method']='put';}
$(self).html(settings.indicator);var ajaxoptions={type:'POST',data:submitdata,url:settings.target,success:function(result,status){$(self).html(result);self.editing=false;callback.apply(self,[self.innerHTML,settings]);if(!$.trim($(self).html())){$(self).html(settings.placeholder);}},error:function(xhr,status,error){onerror.apply(form,[settings,self,xhr]);}}
$.extend(ajaxoptions,settings.ajaxoptions);$.ajax(ajaxoptions);}}}
$(self).attr('title',settings.tooltip);return false;});});this.reset=function(form){if(this.editing){if(false!==onreset.apply(form,[settings,self])){$(self).html(self.revert);self.editing=false;if(!$.trim($(self).html())){$(self).html(settings.placeholder);}
$(self).attr('title',settings.tooltip);}}}});};$.editable={types:{defaults:{element:function(settings,original){var input=$('<input type="hidden"></input>');$(this).append(input);return(input);},content:function(string,settings,original){$(':input:first',this).val(string);},reset:function(settings,original){original.reset(this);},buttons:function(settings,original){var form=this;if(settings.submit){if(settings.submit.match(/>$/)){var submit=$(settings.submit).click(function(){if(submit.attr("type")!="submit"){form.submit();}});}else{var submit=$('<button type="submit" />');submit.html(settings.submit);}
$(this).append(submit);}
if(settings.cancel){if(settings.cancel.match(/>$/)){var cancel=$(settings.cancel);}else{var cancel=$('<button type="cancel" />');cancel.html(settings.cancel);}
$(this).append(cancel);$(cancel).click(function(event){if($.isFunction($.editable.types[settings.type].reset)){var reset=$.editable.types[settings.type].reset;}else{var reset=$.editable.types['defaults'].reset;}
reset.apply(form,[settings,original]);return false;});}}},text:{element:function(settings,original){var input=$('<input />');if(settings.width!='none'){input.width(settings.width);}
if(settings.height!='none'){input.height(settings.height);}
input.attr('autocomplete','off');$(this).append(input);return(input);}},textarea:{element:function(settings,original){var textarea=$('<textarea />');if(settings.rows){textarea.attr('rows',settings.rows);}else{textarea.height(settings.height);}
if(settings.cols){textarea.attr('cols',settings.cols);}else{textarea.width(settings.width);}
$(this).append(textarea);return(textarea);}},select:{element:function(settings,original){var select=$('<select />');$(this).append(select);return(select);},content:function(string,settings,original){if(String==string.constructor){eval('var json = '+string);for(var key in json){if(!json.hasOwnProperty(key)){continue;}
if('selected'==key){continue;}
var option=$('<option />').val(key).append(json[key]);$('select',this).append(option);}}
$('select',this).children().each(function(){if($(this).val()==json['selected']||$(this).text()==original.revert){$(this).attr('selected','selected');};});}}},addInputType:function(name,input){$.editable.types[name]=input;}};})(jQuery);// -*- mode: javascript; indent-tabs-mode: t -*-

function from_map_type_to_int(map_type)
{
	if(map_type == G_HYBRID_MAP) { 
		return 2;
	}
	if(map_type == G_SATELLITE_MAP) { 
		return 1;
	}
	return 0; // G_NORMAL_MAP
}

function from_int_to_map_type(integer)
{
	if(integer == 2) { return G_HYBRID_MAP; }
	if(integer == 1) { return G_SATELLITE_MAP; }
	return G_NORMAL_MAP; // 0 
}

function List(map)
{
	this.map=map;

	this.lat=parseFloat($.cookie('t')) || 12.9;
	this.lng=parseFloat($.cookie('g')) || -24.6;
	this.zoom=parseInt($.cookie('z'),10) || 2;
	this.map_type=parseInt($.cookie('m'),10) || 0;

	$.cookie('t',this.lat);
	$.cookie('g',this.lng);
	$.cookie('z',this.zoom);
	$.cookie('m',this.map_type);

	// these will not fire up an event
	this.map.setCenter(new GLatLng(this.lat,this.lng), this.zoom);
	this.map.setMapType(from_int_to_map_type(this.map_type))

	// initial horizontal resize
	var w=parseInt($.cookie('w'),10) || $('#mapD').width();
	var h=parseInt($.cookie('h'),10) || 440;

	log('initial size: '+$('#map').width()+','+$('#map').height());
	$('#map').width(w);
	$('#map').height(h);
	log('initial resize: '+$('#map').width()+','+$('#map').height());
	// initial resize should not be considered modification
	$.cookie('w',$('#map').width());
	$.cookie('h',$('#map').height());
	this.map.checkResize();

	// the setCenter is needed before the resize to allow 
	// for a correct resizing (do not know why) and after
	// the resize to really center the map where it should be 
	// centered
	this.map.setCenter(new GLatLng(this.lat,this.lng), this.zoom);

	this.posts=[];
	var n=$.cookie('n');
	$('#posts li').remove(); //removes AdWords pre-text with ours
	for(var i=0;i<n;i++) 
	{
		var vals={};
		for(var v in post_fields) {
			var in_cookie = $.cookie(""+post_fields[v]+i);
			if (in_cookie) {
				vals[v] = in_cookie.replace(/\+/g,' ');
			}
		}
		vals.index=i;
		var p=new Post(vals);
		p.show(this.map);
		this.posts[i]=p;
	}

	if(this.posts.length===0) {
		$('#postsPane').hide();
	}

	$('#gotoPane').hide();
	if(this.domain()==window.location.href && this.posts.length!==0) {
		$('#gotoPane').show();
	}

	this.check_all_inside();
}

List.prototype.clear_posts = function() {
	var whoami=this;
	$("<div>Really?</div>").dialog({
		title: "Delete all notes?",
		modal: true,
		buttons: {
			Ok: function() { 
				$(this).dialog('destroy'); 
				for(var i=0;i<whoami.posts.length;i++) {
					whoami.posts[i].free(whoami.map);
				}
				$.cookie('n',0);
				whoami.posts=[];
				$('#postsPane').hide();
				whoami.modified();
			},
			Cancel: function() { $(this).dialog('destroy'); }
		}
	});
};

List.prototype.new_post = function(lat,lng) {
	var whoami=this;
	var point=new GLatLng(lat,lng);
	_geocoder.getLocations(point, function(addresses) {
		var addr="";
		if(addresses.Status.code == 200) {
			addr = addresses.Placemark[0].address;
		}
		whoami.input(point, addr, function(what) { 
			if(what!=="") {
				whoami.create_post({lat: lat, lng: lng, text: what, address: addr});
			}
		});
	});
};

List.prototype.create_post = function(vals) {
	vals.index=this.posts.length;
	var p=new Post(vals);
	p.show(this.map);
	this.posts.push(p);
	$('#postsPane').show();
	this.modified();
	$.cookie('n',this.posts.length);
};

List.prototype.delete_post = function(index) {
	this.map.closeInfoWindow();
	var whoami=this;
	$("<div>"+whoami.posts[index].text+"</div>").dialog({
		title: "Delete?",
		modal: true,
		buttons: {
			Ok: function() { 
				$(this).dialog('destroy'); 
				for(var i=index;i<whoami.posts.length;i++) {
					whoami.posts[i].free(whoami.map);
				}
				log("length A:"+whoami.posts.length);
				whoami.posts.splice(index,1);
				log("length B:"+whoami.posts.length);
				for(var j=index;j<whoami.posts.length;j++)
				{
					whoami.posts[j].reindex(j);
					whoami.posts[j].show(whoami.map);
				}
				$.cookie('n', whoami.posts.length);
				if(whoami.posts.length===0) {
					$('#postsPane').hide();
				}
				whoami.modified();
			},
			Cancel: function() { $(this).dialog('destroy'); }
		}
	});
};

List.prototype.reorder_posts = function() {
	var z=$("#posts li").map(function(){ return $(this).attr('iid'); }).get();
	var i;
	for(i=0;i<this.posts.length;i++) {
		this.posts[i].free(this.map);
	}

	var nposts=[];
	for(i=0;i<z.length;i++) {
		nposts.push(this.posts[z[i]]);
	}
	this.posts=nposts;

	for(i=0;i<this.posts.length;i++)
	{
		this.posts[i].reindex(i);
		this.posts[i].show(this.map);
	}
	this.modified();
};

List.prototype.show_post = function(index) {
	log("just showed a post "+index);
	this.posts[index].show_popup();
};

List.prototype.move_post = function(index) {
	this.posts[index].change_position_to_marker();
	this.modified();
};

List.prototype.move_map = function(lat,lng,zoom,type) {
	log('moved map to '+lat+','+lng+' '+zoom);
	this.lat=lat;
	this.lng=lng;
	this.zoom=zoom;
	this.map_type=from_map_type_to_int(type);
	$.cookie('t',lat);
	$.cookie('g',lng);
	$.cookie('z',zoom);
	$.cookie('m',this.map_type);
	this.modified();
	this.check_all_inside();
};

List.prototype.center = function() {
	var t=0.0;
	var g=0.0;
	var b=new GLatLngBounds();
	for(var i=0;i<this.posts.length;i++) {
		var tt=parseFloat(this.posts[i].lat);
		var gg=parseFloat(this.posts[i].lng);
		t=t+tt;
		g=g+gg;
		b.extend(new GLatLng(tt,gg));
	}
	t=t/this.posts.length;
	g=g/this.posts.length;

	var z=this.map.getBoundsZoomLevel(b);
	this.map.setCenter(new GLatLng(t,g),z);
};

List.prototype.center_here = function(index) {
	log('center around '+index);
	this.map.closeInfoWindow();
	this.map.setCenter(this.posts[index].marker.getLatLng(), this.map.getZoom());
	this.modified();
};

List.prototype.domain = function() {
	var dom=window.location.href;
	log('href: '+dom);
	dom=dom.replace(/#$/,"");
	dom=dom.replace(/\?.*$/,"");
	log('domain: '+dom);
	return dom;
};

List.prototype.encode_cookie_param = function(x) {
	return x+'='+encodeURIComponent($.cookie(x)||0);
};

List.prototype.get_url = function() {
	var s=['t','g','z','h','w','n','m'];
	var t=[];
	for(var c in s) {
		t.push(this.encode_cookie_param(s[c]));
	}
	for(var i=0;i<$.cookie('n');i++) {
		for(var v in post_fields) {
			t.push(this.encode_cookie_param(post_fields[v]+i));
		}
	}
	var url=this.domain()+'?'+t.join('&');
	log(url);
	return url;
};

List.prototype.show_embedding = function() {
	var url = _list.get_url();
	url=url+"&e=1";
	log('url: '+url);
	var w=$('#map').width()+10;
	var h=$('#map').height()+10;
	var frame="<div>&lt;iframe src='"+url+"' "+
		"width='"+w+"' height='"+h+"' scrolling='no' frameborder='0'&gt;"+
		"&lt;/iframe&gt;</div>";
	$(frame).dialog({
		title: "Copy to your blog",
		modal: true,
		width: w,
		close: function() { $(this).dialog('destroy'); }
	});
	log('show embedding:'+frame);
};

List.prototype.download_kml = function() {
	var url = _list.get_url()+"&k=1";
	log('download kml :'+url);
	window.open(url);
};

List.prototype.input = function(point, title, save) {
	if (point) {
		var epane = Post.prototype.edit_pane(save, point, title);
		this.map.openInfoWindow(point, epane, { 
			onOpenFn: function() { epane.$toFocus.focus(); }
		});
	}
};

List.prototype.resize_map = function() { 
	$.cookie('w',$('#map').width());
	$.cookie('h',$('#map').height());
	this.map.checkResize();
	this.modified();
};

List.prototype.modified = function() {
	$('#gotoPane').show(3000);
};

List.prototype.toggle_length = function() {
	$('#posts li').toggleClass('ohidden');
};

List.prototype.check_all_inside = function() {
	var b=this.map.getBounds();
	var all_inside=true;
	for(var i=0;i<this.posts.length;i++)
	{
		var p=new GLatLng(this.posts[i].lat,this.posts[i].lng);
		if(!b.containsLatLng(p)) {
			all_inside=false;
		}
	}
	if(!all_inside) {
		$('#some_not_visible').show();
	}
	else {
		$('#some_not_visible').hide();
	}
};
// -*- mode: javascript; indent-tabs-mode: t -*-

post_fields={ lat: "t",lng: "g",text: "x"};

function Post(vals) {
	for(var v in post_fields) {
		this[v] = vals[v] || null;
	}
	this.index=vals.index;
	this.address = 'none';
	if (vals.address) {
		this.address = vals.address;
		this.popup=this.build_popup();
	}
	else {
		this.popup=this.build_popup();
		this.set_address();
	}
	this.marker=this.build_marker();
	this.element=this.build_element();
	this.save();
}

Post.prototype.reindex = function(index) {
	this.index=index;
	this.marker=this.build_marker();
	this.element=this.build_element();
	this.popup=this.build_popup();
	this.save();
};

Post.prototype.set_address = function() {
	var point=new GLatLng(this.lat, this.lng);
	var whoami = this;
	_geocoder.getLocations(point, function(addresses) {
		var addr="(address not found)";
		if(addresses.Status.code == 200) {
			addr = addresses.Placemark[0].address;
		}
		whoami.address = addr;
		whoami.title.html(addr);
	});
};

Post.prototype.change_position_to_marker = function() {
	var point=this.marker.getLatLng();
	this.lat=point.lat();
	this.lng=point.lng();
	this.set_address();
	this.save();
};

Post.prototype.change_text = function(new_text) {
	log('change_text '+this.text+' for '+new_text);
	this.text=new_text;
	$('span',this.element).html(new_text);
	this.popup=this.build_popup();
	this.save();
};

Post.prototype.edit_pane = function(save, point, title, value) {
	point = point || this.marker.getLatLng();
	value = value || '';

	var pane = $("<span></span>");
	$("<div class='epaneTitle'>" + title + "</div>").appendTo(pane);
	$("<div class='epaneCoord'> [" + point.lat() + 
		', ' + point.lng() + ']</div>').appendTo(pane);

	var note = $("<textarea name='note' rows='3' cols='28' maxlength='300' " +
				 " value='" + value + "'/>");
	note.appendTo(pane);
	$("<div class='epaneButton'>").append(
		$("<button type='submit'>post " +
		  "</button>").bind("click",
							function() {
								save(note[0].value);
								_map.closeInfoWindow();
							})).appendTo(pane);
	pane[0].$toFocus = note[0];
	return pane[0];
};

Post.prototype.build_element = function() {
	var index=this.index; // required for closure
	var el=$("<li></li>").attr("iid",index).
		addClass('ohidden').
		addClass('move').
		tooltip({showURL: false}).
		append("<span class='listText' title='Click to show, drag to reorder'>"+
			this.letter()+". "+this.text+"</div>").
		click(function() {_list.show_post(index);  });

	return el;
};

Post.prototype.build_popup = function() {
	var index = this.index;
	var whoami = this;
	var popup = $("<div/>");

	this.title = $("<div/>").
		addClass('epaneTitle').
		html(this.address).
		appendTo(popup);

	$("<div/>").
		addClass('epaneCoord').
		html(' ['+this.lat + ', ' + this.lng + ']').
		appendTo(popup);

	$("<div/>").
		addClass('bubbleText').
		html(this.text).
		attr('id',index).
		editable(function(value, settings) {
			whoami.change_text(value);
			return value;
			}, { 
				type: 'textarea',
				submit: 'OK',
				rows: 3
		}).
		appendTo(popup);

	var delPane = $("<div/>").
		addClass('delPane').
		appendTo(popup);

	$("<a/>").
		attr({ href: '#'}).
		addClass('delLink').
		click(function() { _list.delete_post(index); }).
		html($("<img>").attr({ src: 'delete.png',
			title: 'Delete this note',
			alt: '[delete]'
		})).
		appendTo(delPane);

	$("<a/>").
		attr({ href: '#'}).
		addClass('delLink').
		click(function() {
				var g="http://maps.google.com/maps?daddr=";
				var t=$(whoami.title).html();
				window.open(g+encodeURIComponent(t));
			}).
		html($("<img>").attr({ src: 'goto.png',
			title: 'Driving directions?',
			alt: '[driving directions]'
		})).
		appendTo(delPane);

	return popup[0];
};

Post.prototype.build_marker = function() {
	var index=this.index; // required for closure
	var icon = new GIcon(base_icon);
	icon.image = '/green.'+index+'.png';
	var opts= { 
		draggable: true,
		icon: icon
	};
	var marker=new GMarker(new GLatLng(this.lat,this.lng),opts);
	GEvent.addListener(marker, "click", function() { _list.show_post(index); });
	GEvent.addListener(marker, "dragend", function() { _list.move_post(index); });
	return marker;
};

Post.prototype.free = function(map) {
	map.removeOverlay(this.marker);
	$(this.element).remove();
	for(var v in post_fields) {
		$.cookie(post_fields[v]+this.index,null);
	}
};

// this assumes it goes after all elements in posts (via append)
Post.prototype.show = function(map) {
	$("#posts").append(this.element);
	map.addOverlay(this.marker);
};

Post.prototype.show_popup = function() {
	this.marker.openInfoWindow(this.popup);
};

Post.prototype.letter = function() {
	var order=this.index;
	if(order >=0 && order < 26) {
		return String.fromCharCode("A".charCodeAt(0) + order);
	}
	if(order >=26 && order < 26+26) {
		return String.fromCharCode("a".charCodeAt(0) + (order-26));
	}
	if(order >=26+26 && order < 26+26+10) {
		return String.fromCharCode("0".charCodeAt(0) + (order-26-26));
	}
	return '%';
};

Post.prototype.save = function() {
	for(var v in post_fields) {
		$.cookie(post_fields[v]+this.index,this[v]);
	}
};
// -*- mode: javascript; indent-tabs-mode: t -*-

var _map=null;
var _geocoder = null;
var _list=null;

function ButtonBar() { }
ButtonBar.prototype = new GControl();
ButtonBar.prototype.getDefaultPosition = function() {
	return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(2, 17));
};

ButtonBar.prototype.initialize = function(map) {
	var bar = document.createElement("span");
	var back=$("<a>edit this map @ notamap</a>").
		css("float","right").
		css("cursor","pointer");

 	bar.appendChild(back[0]);
 	GEvent.addDomListener(back[0],"click",function() { 
		window.open(_list.get_url()+"&e=0"); 
	});

	map.getContainer().appendChild(bar);
	return bar;
};

$(window).unload(function() { GUnload(); });

$(function() {

	if(!GBrowserIsCompatible()) {
		alert('This browser is not compatible with this application');
		return;
	}

	var mapOptions = {
		googleBarOptions : {
			style : "new",
			adsOptions: {
				client: "partner-pub-8693105947059467:5ip9kq9w652",
				channel: "notamap search",
				adsafe: "high",
				language: "en"
			}
		}
	}
	_map = new GMap2($("#map")[0], mapOptions);
	_map.enableGoogleBar();

	_geocoder = new GClientGeocoder();

	base_icon = new GIcon(G_DEFAULT_ICON);
	base_icon.shadow = "/shadow50.png";
	base_icon.iconSize = new GSize(20, 34);
	base_icon.shadowSize = new GSize(37, 34);
	base_icon.iconAnchor = new GPoint(9, 34);
	base_icon.infoWindowAnchor = new GPoint(9, 2);

	//_map.addControl(new GSmallMapControl());
	_map.addControl(new GLargeMapControl());
	_map.addControl(new GMapTypeControl());
	_map.enableScrollWheelZoom();
	// stop propagation of scroll to scroll page
	// i.e. if mouse wheel is used on map, page will not scroll
	if (_map.addEventListener) {
		_map.addEventListener("DOMMouseScroll", function(e) { 
			e.preventDefault(); 
		}, false);
	}
	else if (_map.attachEvent) {
		_map.attachEvent("onmousewheel", function() { 
			event.returnValue = false; 
		});
	}

	var e=parseInt($.cookie('e'),10) || 0;
	if(e==1) {
		_map.addControl(new ButtonBar());
	}

	_list=new List(_map);

	GEvent.addListener(_map, "click", function(overlay,latlng) {
		if(latlng!=null) {
			_list.new_post(latlng.lat(),latlng.lng());
		}
	});
	GEvent.addListener(_map, "moveend", function() {
		var c=_map.getCenter();
		_list.move_map(c.lat(),c.lng(),_map.getZoom(),_map.getCurrentMapType());
	});
	GEvent.addListener(_map, "maptypechanged", function() {
		var c=_map.getCenter();
		_list.move_map(c.lat(),c.lng(),_map.getZoom(),_map.getCurrentMapType());
	});
	
	$('#search').submit(function(e) {
		e.preventDefault();		
		if(!_geocoder) { return; }
		var address=$('#address').val();
		_geocoder.getLatLng(address,function(p) {
			if (p) 
			{
				var z=_map.getZoom();
				if(z<13) { z=13; }
				_map.setCenter(p, z); 
				_list.new_post(p.lat(), p.lng());
			}
		});
	});

	$("#posts").sortable({ stop: function() { _list.reorder_posts(); } });
	$('a img').tooltip({showURL: false});
	$('#some_not_visible').tooltip({showURL: false});

	$("#info").dialog({
		title: 'NotAMap',
		width: 500,
		autoOpen: false,
		modal: true
	});

	$('#map').resizable({ 
		autoHide: true, 
		stop: function(e, ui) { _list.resize_map(); }
	});
});

function about() {
	$("#info").dialog('open');
}

function log(x) {
	//$('#data').html(x+"<br/>"+$('#data').html());
}

function go_to_here() {
 	var url=_list.get_url();
 	if(!window.sidebar && window.external) // we are in explorer
	{
		if(url.length < 2000) {
			location =  url;
		} else {
			$("<div>Unfortunately, Explorer cant handle urls so big. Consider using Firefox</div>").dialog({
				title: "Problem",
				modal: true,
				buttons: {
					Ok: function() { $(this).dialog('destroy'); }
				}
			});
		}
	}
	else {
		location =  url;
	}
}

