function customMarkerOption() {
  var customIcon = new GIcon(G_DEFAULT_ICON);
  customIcon.image = "/images/google_map_marker.png";
  imageWidth = 19;
  imageHeight = 22;
  customIcon.iconSize = new GSize(imageWidth, imageHeight);
  customIcon.iconAnchor = new GPoint(0, imageWidth);
  customIcon.shadow = null;
  return { icon:customIcon };
}

var markerOptions = customMarkerOption();

function build_map(map, elementId, centerLatitude, centerLongitude, zoomLevel) {
  if (!map){

    var map_div = document.getElementById(elementId);
    if (!map_div) return;
    map = new GMap2(map_div);

    mapTypes = map.getMapTypes();
    for (i in mapTypes)
    mapTypes[i].getMinimumResolution = function() {return 1;}
    map.setCenter(new GLatLng(centerLatitude, centerLongitude), zoomLevel);
    map.enableScrollWheelZoom();
	map.addControl(new GLargeMapControl());
  }
  return map;
}

function info(marker, appearance_id, author_id) {
	map.closeExtInfoWindow();
	$.get("/author_appearance_info",{"appearance_id" : appearance_id ,"author_id" : author_id},function(data){
		marker.openExtInfoWindow(map, "info_window", data, {beakOffset: 1});
 tb_init('.map_bubble.appearances a.thickbox');
 });
}


function addAuthorAppearancesMarker(author_appearances, author_id) {
  var markers = new Array();	
  for (j in author_appearances) {
    var point = new GLatLng(parseFloat(author_appearances[j][0]),
    parseFloat(author_appearances[j][1]));
    marker = new GMarker(point,markerOptions);
    map.addOverlay(marker);
    markers[author_appearances[j][2]] = marker;
    GEvent.addListener(marker, "click", GEvent.callbackArgs(window,info, marker, author_appearances[j][2], author_id));
  }

  return markers;
}






/* ExtInfoWindow Class, v1.0
   Copyright (c) 2007, Joe Monahan (http://www.seejoecode.com)
   Licensed under the Apache License, Version 2.0 */
function ExtInfoWindow(marker,windowId,html,opt_opts){this.html_=html;this.marker_=marker;this.infoWindowId_=windowId;this.options_=opt_opts==null?{}:opt_opts;this.ajaxUrl_=this.options_.ajaxUrl==null?null:this.options_.ajaxUrl;this.callback_=this.options_.ajaxCallback==null?null:this.options_.ajaxCallback;this.borderSize_=this.options_.beakOffset==null?0:this.options_.beakOffset;this.paddingX_=this.options_.paddingX==null?0+this.borderSize_:this.options_.paddingX+this.borderSize_;this.paddingY_=this.options_.paddingY==null?0+this.borderSize_:this.options_.paddingY+this.borderSize_;this.map_=null;this.container_=document.createElement("div");this.container_.style.position="relative";this.container_.style.display="none";this.contentDiv_=document.createElement("div");this.contentDiv_.id=this.infoWindowId_+"_contents";this.contentDiv_.innerHTML=this.html_;this.contentDiv_.style.display="block";this.contentDiv_.style.visibility="hidden";this.wrapperDiv_=document.createElement("div");}ExtInfoWindow.prototype=new GOverlay();ExtInfoWindow.prototype.initialize=function(map){this.map_=map;this.defaultStyles={containerWidth:this.map_.getSize().width/2,borderSize:1};this.wrapperParts={tl:{t:0,l:0,w:0,h:0,domElement:null},t:{t:0,l:0,w:0,h:0,domElement:null},tr:{t:0,l:0,w:0,h:0,domElement:null},l:{t:0,l:0,w:0,h:0,domElement:null},r:{t:0,l:0,w:0,h:0,domElement:null},bl:{t:0,l:0,w:0,h:0,domElement:null},b:{t:0,l:0,w:0,h:0,domElement:null},br:{t:0,l:0,w:0,h:0,domElement:null},beak:{t:0,l:0,w:0,h:0,domElement:null},close:{t:0,l:0,w:0,h:0,domElement:null}};for(var i in this.wrapperParts){var tempElement=document.createElement("div");tempElement.id=this.infoWindowId_+"_"+i;tempElement.style.visibility="hidden";document.body.appendChild(tempElement);tempElement=document.getElementById(this.infoWindowId_+"_"+i);var tempWrapperPart=eval("this.wrapperParts."+i);tempWrapperPart.w=parseInt(this.getStyle_(tempElement,"width"));tempWrapperPart.h=parseInt(this.getStyle_(tempElement,"height"));document.body.removeChild(tempElement);}for(var i in this.wrapperParts){if(i=="close"){this.wrapperDiv_.appendChild(this.contentDiv_);}var wrapperPartsDiv=null;if(this.wrapperParts[i].domElement==null){wrapperPartsDiv=document.createElement("div");this.wrapperDiv_.appendChild(wrapperPartsDiv);}else{wrapperPartsDiv=this.wrapperParts[i].domElement;}wrapperPartsDiv.id=this.infoWindowId_+"_"+i;wrapperPartsDiv.style.position="absolute";wrapperPartsDiv.style.width=this.wrapperParts[i].w+"px";wrapperPartsDiv.style.height=this.wrapperParts[i].h+"px";wrapperPartsDiv.style.top=this.wrapperParts[i].t+"px";wrapperPartsDiv.style.left=this.wrapperParts[i].l+"px";this.wrapperParts[i].domElement=wrapperPartsDiv;}this.map_.getPane(G_MAP_FLOAT_PANE).appendChild(this.container_);this.container_.id=this.infoWindowId_;var containerWidth=this.getStyle_(document.getElementById(this.infoWindowId_),"width");this.container_.style.width=(containerWidth==null?this.defaultStyles.containerWidth:containerWidth);this.map_.getContainer().appendChild(this.contentDiv_);this.contentWidth=this.getDimensions_(this.container_).width;this.contentDiv_.style.width=this.contentWidth+"px";this.contentDiv_.style.position="absolute";this.container_.appendChild(this.wrapperDiv_);GEvent.bindDom(this.container_,"mousedown",this,this.onClick_);GEvent.bindDom(this.container_,"dblclick",this,this.onClick_);GEvent.bindDom(this.container_,"DOMMouseScroll",this,this.onClick_);GEvent.trigger(this.map_,"extinfowindowopen");if(this.ajaxUrl_!=null){this.ajaxRequest_(this.ajaxUrl_);}};ExtInfoWindow.prototype.onClick_=function(e){if(navigator.userAgent.toLowerCase().indexOf("msie")!=-1&&document.all){window.event.cancelBubble=true;window.event.returnValue=false;}else{e.stopPropagation();}};ExtInfoWindow.prototype.remove=function(){if(this.map_.getExtInfoWindow()!=null){GEvent.trigger(this.map_,"extinfowindowbeforeclose");GEvent.clearInstanceListeners(this.container_);if(this.container_.outerHTML){this.container_.outerHTML="";}if(this.container_.parentNode){this.container_.parentNode.removeChild(this.container_);}this.container_=null;GEvent.trigger(this.map_,"extinfowindowclose");this.map_.setExtInfoWindow_(null);}};ExtInfoWindow.prototype.copy=function(){return new ExtInfoWindow(this.marker_,this.infoWindowId_,this.html_,this.options_);};ExtInfoWindow.prototype.redraw=function(force){if(!force||this.container_==null){return;}var contentHeight=this.contentDiv_.offsetHeight;this.contentDiv_.style.height=contentHeight+"px";this.contentDiv_.style.left=this.wrapperParts.l.w+"px";this.contentDiv_.style.top=this.wrapperParts.tl.h+"px";this.contentDiv_.style.visibility="visible";this.wrapperParts.tl.t=0;this.wrapperParts.tl.l=0;this.wrapperParts.t.l=this.wrapperParts.tl.w;this.wrapperParts.t.w=(this.wrapperParts.l.w+this.contentWidth+this.wrapperParts.r.w)-this.wrapperParts.tl.w-this.wrapperParts.tr.w;this.wrapperParts.t.h=this.wrapperParts.tl.h;this.wrapperParts.tr.l=this.wrapperParts.t.w+this.wrapperParts.tl.w;this.wrapperParts.l.t=this.wrapperParts.tl.h;this.wrapperParts.l.h=contentHeight;this.wrapperParts.r.l=this.contentWidth+this.wrapperParts.l.w;this.wrapperParts.r.t=this.wrapperParts.tr.h;this.wrapperParts.r.h=contentHeight;this.wrapperParts.bl.t=contentHeight+this.wrapperParts.tl.h;this.wrapperParts.b.l=this.wrapperParts.bl.w;this.wrapperParts.b.t=contentHeight+this.wrapperParts.tl.h;this.wrapperParts.b.w=(this.wrapperParts.l.w+this.contentWidth+this.wrapperParts.r.w)-this.wrapperParts.bl.w-this.wrapperParts.br.w;this.wrapperParts.b.h=this.wrapperParts.bl.h;this.wrapperParts.br.l=this.wrapperParts.b.w+this.wrapperParts.bl.w;this.wrapperParts.br.t=contentHeight+this.wrapperParts.tr.h;this.wrapperParts.close.l=this.wrapperParts.tr.l+this.wrapperParts.tr.w-this.wrapperParts.close.w-this.borderSize_;this.wrapperParts.close.t=this.borderSize_;this.wrapperParts.beak.t=this.wrapperParts.bl.t+this.wrapperParts.bl.h+this.borderSize_-12;for(var i in this.wrapperParts){if(i=="close"){this.wrapperDiv_.insertBefore(this.contentDiv_,this.wrapperParts[i].domElement);}var wrapperPartsDiv=null;if(this.wrapperParts[i].domElement==null){wrapperPartsDiv=document.createElement("div");this.wrapperDiv_.appendChild(wrapperPartsDiv);}else{wrapperPartsDiv=this.wrapperParts[i].domElement;}wrapperPartsDiv.id=this.infoWindowId_+"_"+i;wrapperPartsDiv.style.position="absolute";wrapperPartsDiv.style.width=this.wrapperParts[i].w+"px";wrapperPartsDiv.style.height=this.wrapperParts[i].h+"px";wrapperPartsDiv.style.top=this.wrapperParts[i].t+"px";wrapperPartsDiv.style.left=this.wrapperParts[i].l+"px";if(i=="beak"){wrapperPartsDiv.style.zIndex=3000;}this.wrapperParts[i].domElement=wrapperPartsDiv;}this.wrapperParts.beak.st;var currentMarker=this.marker_;var thisMap=this.map_;GEvent.addDomListener(this.wrapperParts.close.domElement,"click",function(){thisMap.closeExtInfoWindow();});var pixelLocation=this.map_.fromLatLngToDivPixel(this.marker_.getPoint());this.container_.style.position="absolute";var markerIcon=this.marker_.getIcon();this.container_.style.left=(pixelLocation.x-markerIcon.iconAnchor.x+markerIcon.infoWindowAnchor.x)+"px";this.container_.style.top=(pixelLocation.y-this.wrapperParts.bl.h-contentHeight-this.wrapperParts.tl.h-this.wrapperParts.beak.h-markerIcon.iconAnchor.y+markerIcon.infoWindowAnchor.y+this.borderSize_+15)+"px";this.container_.style.display="block";if(this.map_.getExtInfoWindow()!=null){this.repositionMap_();}};ExtInfoWindow.prototype.resize=function(){var tempElement=this.contentDiv_.cloneNode(true);tempElement.id=this.infoWindowId_+"_tempContents";tempElement.style.visibility="hidden";tempElement.style.height="auto";document.body.appendChild(tempElement);tempElement=document.getElementById(this.infoWindowId_+"_tempContents");var contentHeight=tempElement.offsetHeight;document.body.removeChild(tempElement);this.contentDiv_.style.height=contentHeight+"px";var contentWidth=this.contentDiv_.offsetWidth;var pixelLocation=this.map_.fromLatLngToDivPixel(this.marker_.getPoint());var oldWindowHeight=this.wrapperParts.t.domElement.offsetHeight+this.wrapperParts.l.domElement.offsetHeight+this.wrapperParts.b.domElement.offsetHeight;var oldWindowPosTop=this.wrapperParts.t.domElement.offsetTop;this.wrapperParts.l.domElement.style.height=contentHeight+"px";this.wrapperParts.r.domElement.style.height=contentHeight+"px";var newPosTop=this.wrapperParts.b.domElement.offsetTop-contentHeight;this.wrapperParts.l.domElement.style.top=newPosTop+"px";this.wrapperParts.r.domElement.style.top=newPosTop+"px";this.contentDiv_.style.top=newPosTop+"px";windowTHeight=parseInt(this.wrapperParts.t.domElement.style.height);newPosTop-=windowTHeight;this.wrapperParts.close.domElement.style.top=newPosTop+this.borderSize_+"px";this.wrapperParts.tl.domElement.style.top=newPosTop+"px";this.wrapperParts.t.domElement.style.top=newPosTop+"px";this.wrapperParts.tr.domElement.style.top=newPosTop+"px";this.repositionMap_();};ExtInfoWindow.prototype.repositionMap_=function(){var mapNE=this.map_.fromLatLngToDivPixel(this.map_.getBounds().getNorthEast());var mapSW=this.map_.fromLatLngToDivPixel(this.map_.getBounds().getSouthWest());var markerPosition=this.map_.fromLatLngToDivPixel(this.marker_.getPoint());var panX=0;var panY=0;var paddingX=this.paddingX_;var paddingY=this.paddingY_;var infoWindowAnchor=this.marker_.getIcon().infoWindowAnchor;var iconAnchor=this.marker_.getIcon().iconAnchor;var windowT=this.wrapperParts.t.domElement;var windowL=this.wrapperParts.l.domElement;var windowB=this.wrapperParts.b.domElement;var windowR=this.wrapperParts.r.domElement;var windowBeak=this.wrapperParts.beak.domElement;var offsetTop=markerPosition.y-(-infoWindowAnchor.y+iconAnchor.y+this.getDimensions_(windowBeak).height+this.getDimensions_(windowB).height+this.getDimensions_(windowL).height+this.getDimensions_(windowT).height+this.paddingY_);if(offsetTop<mapNE.y){panY=mapNE.y-offsetTop;}else{var bottom_padding=15;var offsetBottom=markerPosition.y+this.paddingY_+bottom_padding;if(offsetBottom>=mapSW.y){panY=-(offsetBottom-mapSW.y);}}var offsetAfterBorder=4;var offsetRight=Math.round(markerPosition.x+this.getDimensions_(this.container_).width+this.getDimensions_(windowR).width+this.paddingX_+infoWindowAnchor.x-iconAnchor.x+this.borderSize_+offsetAfterBorder);if(offsetRight>mapNE.x){panX=-(offsetRight-mapNE.x);}else{var left_padding=65;var offsetLeft=-(Math.round((0-this.marker_.getIcon().iconSize.width/2)+this.getDimensions_(windowL).width+this.borderSize_+this.paddingX_)-markerPosition.x-infoWindowAnchor.x+iconAnchor.x)-left_padding;if(offsetLeft<mapSW.x){panX=mapSW.x-offsetLeft;}}if(panX!=0||panY!=0&&this.map_.getExtInfoWindow()!=null){this.map_.panBy(new GSize(panX,panY));}};ExtInfoWindow.prototype.ajaxRequest_=function(url){var thisMap=this.map_;var thisCallback=this.callback_;GDownloadUrl(url,function(response,status){var infoWindow=document.getElementById(thisMap.getExtInfoWindow().infoWindowId_+"_contents");if(response==null||status==-1){infoWindow.innerHTML='<span class="error">ERROR: The Ajax request failed to get HTML content from "'+url+'"</span>';}else{infoWindow.innerHTML=response;}if(thisCallback!=null){thisCallback();}thisMap.getExtInfoWindow().resize();GEvent.trigger(thisMap,"extinfowindowupdate");});};ExtInfoWindow.prototype.getDimensions_=function(element){var display=this.getStyle_(element,"display");if(display!="none"&&display!=null){return{width:element.offsetWidth,height:element.offsetHeight};}var els=element.style;var originalVisibility=els.visibility;var originalPosition=els.position;var originalDisplay=els.display;els.visibility="hidden";els.position="absolute";els.display="block";var originalWidth=element.clientWidth;var originalHeight=element.clientHeight;els.display=originalDisplay;els.position=originalPosition;els.visibility=originalVisibility;return{width:originalWidth,height:originalHeight};};ExtInfoWindow.prototype.getStyle_=function(element,style){var found=false;style=this.camelize_(style);var value=element.style[style];if(!value){if(document.defaultView&&document.defaultView.getComputedStyle){var css=document.defaultView.getComputedStyle(element,null);value=css?css[style]:null;}else{if(element.currentStyle){value=element.currentStyle[style];}}}if((value=="auto")&&(style=="width"||style=="height")&&(this.getStyle_(element,"display")!="none")){if(style=="width"){value=element.offsetWidth;}else{value=element.offsetHeight;}}return(value=="auto")?null:value;};ExtInfoWindow.prototype.camelize_=function(element){var parts=element.split("-"),len=parts.length;if(len==1){return parts[0];}var camelized=element.charAt(0)=="-"?parts[0].charAt(0).toUpperCase()+parts[0].substring(1):parts[0];for(var i=1;i<len;i++){camelized+=parts[i].charAt(0).toUpperCase()+parts[i].substring(1);}return camelized;};GMap.prototype.ExtInfoWindowInstance_=null;GMap.prototype.ClickListener_=null;GMap.prototype.InfoWindowListener_=null;GMarker.prototype.openExtInfoWindow=function(map,cssId,html,opt_opts){if(map==null){throw"Error in GMarker.openExtInfoWindow: map cannot be null";return false;}if(cssId==null||cssId==""){throw"Error in GMarker.openExtInfoWindow: must specify a cssId";return false;}map.closeInfoWindow();if(map.getExtInfoWindow()!=null){map.closeExtInfoWindow();}if(map.getExtInfoWindow()==null){map.setExtInfoWindow_(new ExtInfoWindow(this,cssId,html,opt_opts));if(map.ClickListener_==null){map.ClickListener_=GEvent.addListener(map,"click",function(event){if(!event&&map.getExtInfoWindow()!=null){map.closeExtInfoWindow();}});}if(map.InfoWindowListener_==null){map.InfoWindowListener_=GEvent.addListener(map,"infowindowopen",function(event){if(map.getExtInfoWindow()!=null){map.closeExtInfoWindow();}});}map.addOverlay(map.getExtInfoWindow());}};GMarker.prototype.closeExtInfoWindow=function(map){if(map.getExtInfWindow()!=null){map.closeExtInfoWindow();}};GMap2.prototype.getExtInfoWindow=function(){return this.ExtInfoWindowInstance_;};GMap2.prototype.setExtInfoWindow_=function(extInfoWindow){this.ExtInfoWindowInstance_=extInfoWindow;};GMap2.prototype.closeExtInfoWindow=function(){if(this.getExtInfoWindow()!=null){this.ExtInfoWindowInstance_.remove();}};

//gigya.services.socialize.verbose = true;

(function($) {
	$.fn.share_appearance = function(api_key, message) {
			
		return this.each(function() {
			
			var provider = $(this).attr('rel');
			
			var api = {
				APIKey:api_key,
				enabledProviders:provider
			};
			
			var context = { api:api, message:message, provider:provider, selector:this }
			
			alert_if_debugging('getUserInfo', api);
			gigya.services.socialize.getUserInfo(api, { context:context, callback:get_user_info_callback });
	
		});
	};
	
	function alert_if_debugging(method, api, message)
	{
		if(document.location.search.indexOf("gigya_debug=true") > 0)
		{
			if(message) alert('calling: ' + method + '\nenabledProviders: ' + api.enabledProviders + '\nmessage: ' + message)
			if(!message) alert('calling: ' + method + '\nenabledProviders: ' + api.enabledProviders)
		}
	}
	
	function set_box_text(heading, message)
	{
		$('div.share_appearance h2').text(heading);
		$('div.share_appearance p').text(message);
	}
	
	function invalid_response(response)
	{
		/* DEBUG *** for some reason these callbacks get called twice sometimes

		msg = 'status: ' + response.status;
		msg = msg + '\nstatusMessage: ' + response.statusMessage;
		msg = msg + '\noperation: ' + response.operation;
		msg = msg + '\ncontext: ' + response.context;
		if(response.user)
		{
			msg = msg + '\nuserName: ' + response.user.firstName;
			msg = msg + '\nUID: ' + response.user.UID;
		}
		alert(msg)
		
		*/
		
		if(response.status != 'OK')
		{
			set_box_text('Sorry, there was an error', response.statusMessage)
			return true;
		}
		
		return false;
	}
	
	function get_user_info_callback(response)
	{
		if(invalid_response(response)) return;
		
		$(response.context.selector).click(function(e) {
			
			/* DEBUG *** the click only occurs once
			
			alert('icon clicked')
			alert(api.enabledProviders)
			//gigya.services.socialize.disconnect(api);
			*/
			
			set_box_text('Please wait...', 'Posting your message.')
			if(response.user.identities[response.context.provider])
			{
				alert_if_debugging('setStatus', response.context.api, response.context.message);
				gigya.services.socialize.setStatus(response.context.api, {status:response.context.message, callback: set_status_callback });
			}
			else
			{
				var context = { api:response.context.api, message:response.context.message }

				alert_if_debugging('connect', response.context.api);
				gigya.services.socialize.connect(response.context.api, { provider: response.context.provider, callback: connect_callback, context: context })
			}
			
		});
	}
	
	function connect_callback(response)
	{
		if(invalid_response(response)) return;
		
		alert_if_debugging('setStatus', response.context.api, response.context.message);
		gigya.services.socialize.setStatus(response.context.api, {status:response.context.message, callback: set_status_callback });
	}
	
	function set_status_callback(response)
	{
		if(invalid_response(response)) return;
		set_box_text('The event has been posted', 'Click on another network below to post again or close the window')
	}

})(jQuery);

var map = null;
var author_id_to_markers = {};

function initialize_map() {
  if (GBrowserIsCompatible()) {
    map = build_map(map, "local_appearances_map", pageMapsCenterLatitude, pageMapsCenterLongitude, pageMapsZoomLevel);
    for (var author_id in author_appearances) {
      show_author_markers(author_id, author_appearances)
    }
  }
}

function show_author_markers(author_id, author_appearances_hash) {
  var author_appearances = author_appearances_hash[author_id];
  if (author_appearances != null) {
    author_id_to_markers[author_id] = addAuthorAppearancesMarker(author_appearances, author_id);
  }
}

$(document).ready(function() {
  initialize_map();
  $(".map_it").click(function() {
    var map_it_id = this.id;
    var appearance_id = $("#" + map_it_id).attr("appearance_id");
    var author_id = $("#" + map_it_id).attr("author_id");
    info(author_id_to_markers[author_id][appearance_id], appearance_id, author_id);
  });
});