/* $Id$ */

// Atomic Ant Simplemap module
// Julian Thompson 2009
// julian@atomicant.co.uk
// www.atomicant.co.uk
// 
// jquery.simplemap1.0-min.js v1.1.0


(function($){$.fn.simplemap=function(settings){function getsettings(el){return jQuery.data(el,'simplemap.settings');}
function getsetting(el,name){return eval("jQuery.data(el,'simplemap.settings')."+name);}
function setsettings(el,values){return jQuery.data(el,'simplemap.settings',values);}
function setsetting(el,name,value){var settings=getsettings(el);settings[name]=value;setsettings(el,settings);}
function initialize(el){var settings=getsettings(el);var options={};if(settings.allowedtypes){var allowedtypes=new Array();for(var i in settings.allowedtypes){allowedtypes[allowedtypes.length]=getmaptype(settings.allowedtypes[i]);}
options={mapTypes:allowedtypes};}
var map=new GMap2(el,options);map.setCenter(new GLatLng(settings.mapcenterlat,settings.mapcenterlng),parseInt(settings.zoomlevel));map.addControl(new GSmallMapControl());map.addControl(new GMapTypeControl());var maptype=getmaptype(settings.maptype);map.setMapType(maptype);map.simplemap=el;map.simplemapid=$(el).attr('id');map.simplemapmarkers=[];if(settings.markers){var openinfo=(settings.markers.length==1)
for(var i in settings.markers){var marker=$.extend({},settings.markers[i]);var markerobj=addmarker(map,marker);if(openinfo){openinfo=false;markercontent(map,markerobj);}}
updatemarkerlist(map);}
if(settings.editmode){map.addControl(new aaPane());GEvent.addListener(map,"moveend",function(){listener_map_moved(this);});GEvent.addListener(map,"zoomend",function(oldzoom,newzoom){listener_map_zoomend(this,newzoom);});GEvent.addListener(map,"maptypechanged",function(){listener_map_typechanged(this);});GEvent.addListener(map,"click",function(overlay,latlng){listener_map_clicked(this,latlng)});setformevents(map);}
return map;}
function getmaptype(maptypename){var types={'map':G_NORMAL_MAP,'satellite':G_SATELLITE_MAP,'hybrid':G_HYBRID_MAP};var maptype=types[maptypename];return(maptype)?maptype:G_NORMAL_MAP;}
function addmarker(mapobj,marker){var settings=getsettings(mapobj.simplemap);var index=mapobj.simplemapmarkers.length+1;if(!marker.point)marker.point=new GLatLng(marker.lat,marker.lng);var markerprops=(settings.editmode)?{draggable:true}:{};if(marker.icon){var markerIcon=new GIcon(G_DEFAULT_ICON);if(marker.icon.image){if(marker.icon.image.path)markerIcon.image=marker.icon.image.path;if(marker.icon.image.width&&marker.icon.image.height){var iiw=parseInt(marker.icon.image.width);var iih=parseInt(marker.icon.image.height);markerIcon.iconSize=new GSize(iiw,iih);markerIcon.imageMap=[0,0,iiw,0,iiw,iih,0,iih];}}
if(marker.icon.shadow){if(marker.icon.shadow.path)markerIcon.shadow=marker.icon.shadow.path;if(marker.icon.shadow.width&&marker.icon.shadow.height){var shw=parseInt(marker.icon.shadow.width);var shh=parseInt(marker.icon.shadow.height);markerIcon.shadowSize=new GSize(shw,shh);}}
if(marker.icon.iconanchor){if(marker.icon.iconanchor.x&&marker.icon.iconanchor.y){var iax=parseInt(marker.icon.iconanchor.x);var iay=parseInt(marker.icon.iconanchor.y);markerIcon.iconAnchor=new GPoint(iax,iay);}}
if(marker.icon.infoanchor){if(marker.icon.infoanchor.x&&marker.icon.infoanchor.y){var inax=parseInt(marker.icon.infoanchor.x);var inay=parseInt(marker.icon.infoanchor.y);markerIcon.infoWindowAnchor=new GPoint(inax,inay);}}
log(markerIcon);markerprops.icon=markerIcon;if(settings.editmode)markerprops.draggable=true;}
var mapmarker=new GMarker(marker.point,markerprops);mapmarker.value=index;marker.index=index;marker.markerobj=mapmarker;marker.title=trim(marker.title);mapobj.addOverlay(mapmarker);if(settings.editmode){GEvent.addListener(mapmarker,"click",function(evt){editmarker(mapobj,marker);});GEvent.addListener(mapmarker,"dragstart",function(){mapobj.closeInfoWindow();});GEvent.addListener(mapmarker,"dragend",function(){editmarker(mapobj,marker);});}else{if(!(emptystring(marker.title)&&emptystring(marker.content))){GEvent.addListener(mapmarker,"click",function(evt){markercontent(mapobj,marker);});}}
log(marker.title);mapobj.simplemapmarkers[index]=marker;updatemarkerlist(mapobj);return marker;}
function deletemarker(mapobj,marker){mapobj.closeInfoWindow();mapobj.removeOverlay(marker.markerobj);marker.deleted=true;updatemarkerlist(mapobj);}
function centermarker(mapobj,marker){mapobj.closeInfoWindow();mapobj.panTo(marker.point);}
function editmarker(mapobj,marker){var mapid=mapobj.simplemapid;var elementprefix='edit-'+mapid+'-marker'+marker.index;var containerobj=document.createElement("div");containerobj.id=elementprefix;containerobj.setAttribute('class','edit-marker-window');var titleinputobj=document.createElement("input");titleinputobj.id=elementprefix+'-title';titleinputobj.setAttribute('class','edit-marker-title');titleinputobj.type="text";titleinputobj.value=marker.title;var contentinputobj=document.createElement("textarea");contentinputobj.id=elementprefix+'-content';contentinputobj.setAttribute('class','edit-marker-content');contentinputobj.value=marker.content;var buttonscontainerobj=document.createElement("div");buttonscontainerobj.setAttribute('class','form-item');var savebuttonobj=document.createElement("input");savebuttonobj.id=elementprefix+'-savebutton';savebuttonobj.setAttribute('class','edit-marker-save');savebuttonobj.type="button";savebuttonobj.value='Save';savebuttonobj.onclick=function(){updatemarker(mapobj,marker)};buttonscontainerobj.appendChild(savebuttonobj);var deletebuttonobj=document.createElement("input");deletebuttonobj.id=elementprefix+'-deletebutton';deletebuttonobj.setAttribute('class','edit-marker-delete');deletebuttonobj.type="button";deletebuttonobj.value='Delete';deletebuttonobj.onclick=function(){deletemarker(mapobj,marker)};buttonscontainerobj.appendChild(deletebuttonobj);containerobj.appendChild(createformitem(titleinputobj,'Title'));containerobj.appendChild(createformitem(contentinputobj,'Content'));containerobj.appendChild(buttonscontainerobj);marker.markerobj.openInfoWindow(containerobj,{maxWidth:300,buttons:{close:{show:4}}});}
function updatemarker(mapobj,marker){var mapid=mapobj.simplemapid;var elementprefix='edit-'+mapid+'-marker'+marker.index;marker.title=trim($('#'+elementprefix+'-title').val());marker.content=trim($('#'+elementprefix+'-content').val());mapobj.closeInfoWindow();updatemarkerlist(mapobj);}
function createformitem(inputelementobj,labeltext){var formitem=document.createElement("div");formitem.setAttribute('class','form-item');if(labeltext){var labelobj=document.createElement("label");labelobj.setAttribute('for',inputelementobj.id);var labeltextobj=document.createTextNode(labeltext);labelobj.appendChild(labeltextobj);formitem.appendChild(labelobj);}
formitem.appendChild(inputelementobj);return formitem;}
function listener_map_clicked(mapobj,latlng){if(mapobj.clckTimeOut){window.clearTimeout(mapobj.clckTimeOut);mapobj.clckTimeOut=null;return listener_map_doubleclicked(mapobj,latlng);}else{mapobj.clckTimeOut=window.setTimeout(function(){window.clearTimeout(mapobj.clckTimeOut);mapobj.clckTimeOut=null;listener_map_singleclicked(mapobj,latlng)},500);}}
function listener_map_singleclicked(mapobj,latlng){if(!latlng)return true;var marker={title:'',content:'',lat:latlng.lat(),lng:latlng.lng(),point:latlng};var marker=addmarker(mapobj,marker);editmarker(mapobj,marker);}
function updatemap(mapobj,cleanaddress){var mapid=mapobj.simplemap.id;var itemprefix='#edit-'+mapid+'-';var centeraddressid=itemprefix+'centeraddress';var centerlatid=itemprefix+'advanced-centerlat';var centerlngid=itemprefix+'advanced-centerlng';if(cleanaddress['responsecode']==200){var newlat=cleanaddress['lat'];var newlng=cleanaddress['lon'];$(centerlatid).val(newlat);$(centerlngid).val(newlng);$(centeraddressid).removeClass('error');mapobj.panTo(cleanaddress['glatlng']);var zoommap=getsetting(mapobj.simplemap,'accuracyzoommap');var zoomlevel=zoommap[(cleanaddress['accuracy'])];log('accuracy : '+cleanaddress['accuracy']+':'+zoomlevel);}else{$(centerlatid).val(0);$(centerlngid).val(0);$(centeraddressid).addClass('error');mapobj.setCenter(new GLatLng(0,0));mapobj.setZoom(2);}}
function updatemapfromcoords(mapobj){var mapid=mapobj.simplemap.id;var itemprefix='#edit-'+mapid+'-';var centeraddressid=itemprefix+'centeraddress';var centerlatid=itemprefix+'advanced-centerlat';var centerlngid=itemprefix+'advanced-centerlng';var newlat=$(centerlatid);var newlng=$(centerlngid);var newlatlng=new GLatLng(newlat,newlon);mapobj.panTo(cleanaddress['glatlng'])}
function updateaddress(mapobj,address){var mapid=mapobj.simplemap.id;var itemprefix='#edit-'+mapid+'-';var editcenteraddressid=itemprefix+'centeraddress';if(!address){address='';$(editcenteraddressid).addClass('error');}else{$(editcenteraddressid).removeClass('error');}
$(editcenteraddressid).val(address);}
function listener_map_doubleclicked(mapobj,latlng){return false;}
function listener_map_moved(mapobj){updateform(mapobj);var mapcenter=mapobj.getCenter();$(mapobj.simplemap).parsecoordinate(mapobj,mapcenter,updateaddress);}
function listener_map_zoomend(mapobj,oldzoom,newzoom){updateform(mapobj);}
function listener_map_typechanged(mapobj){updateform(mapobj);}
function updateform(mapobj){var mapid=mapobj.simplemapid;var mapcenter=mapobj.getCenter();$('#edit-'+mapid+'-advanced-centerlat').val(mapcenter.lat());$('#edit-'+mapid+'-advanced-centerlng').val(mapcenter.lng());$('#edit-'+mapid+'-advanced-zoomlevel').val(mapobj.getZoom());$('#edit-'+mapid+'-advanced-type').val(strtolower(mapobj.getCurrentMapType().getName()));}
function setformevents(mapobj){var mapid=mapobj.simplemap.id;var itemprefix='#edit-'+mapid+'-';var edittitleid=itemprefix+'location-title';var editcenteraddressid=itemprefix+'centeraddress';var editcenterlatid=itemprefix+'advanced-centerlat';var editcenterlngid=itemprefix+'advanced-centerlng';var editallowedtypes='.allowedtypes input';$(editcenteraddressid).keypress(function(event){updatevaluetimer(2000,'updatemapcenteraddress',this,mapobj);return true;});$(editcenterlatid).keypress(function(event){updatevaluetimer(2000,'updatelatitude',this,mapobj);return(iscoordinatecharacter(event));});$(editcenterlngid).keypress(function(event){updatevaluetimer(2000,'updatelongitude',this,mapobj);return(iscoordinatecharacter(event));});$(editcenterlngid).keypress(function(event){updatevaluetimer(2000,'updatelongitude',this,mapobj);return(iscoordinatecharacter(event));});$(editallowedtypes).click(function(event){listener_allowed_types_changed(this,mapobj);});}
function listener_allowed_types_changed(el,mapobj){var currenttype=mapobj.getCurrentMapType();var value=getmaptype($(el).val());if($(el).attr('checked')){mapobj.addMapType(value);}else{if(currenttype==value){$(el).attr('checked',true);}else{mapobj.removeMapType(value);}}
updateform(mapobj);}
function updatemapcenteraddress(element,mapobj){$(element).parseaddress(mapobj,updatemap);}
function updateblocktitle(element,titleelement,id){$(titleelement).html('Block '+id+' - '+$(element).val());}
function updatelatitude(element,mapobj){var value=number_limit($(element).val(),-90,90)
$(element).val(value);}
function updatelongitude(element,mapobj){var value=number_limit($(element).val(),-180,180)
$(element).val(value);}
function number_limit(value,min,max){var value=parseFloat(value);if(isNaN(value))value=0;if(value>max)return max;if(value<min)return min;return value;}
function iscoordinatecharacter(event){var char=event.which;return((char>=48&&char<=57)||char==46||char==8||char==13||char==0);}
function updatevaluetimer(timer,callback,element){var timerdata=jQuery.data(element,'aatypetimer');if(timerdata){if(timerdata.timeoutindex)clearTimeout(timerdata.timeoutindex);jQuery.removeData(element,'aatypetimer');}
var args=Array.prototype.slice.call(arguments);var params={};params.timer=args.shift();params.callback=args.shift();params.args=args;params.timeoutindex=setTimeout(function(){updatevaluetimercallback(element)},timer);;jQuery.data(element,'aatypetimer',params)}
function updatevaluetimercallback(element){var timerdata=jQuery.data(element,'aatypetimer');if(timerdata){clearTimeout(timerdata.timeoutindex);var func=eval(timerdata.callback);if(typeof func=='function'){func.apply(element,timerdata.args);}else{log('value timer invalid callback :'+timerdata.callback);}
jQuery.removeData(element,'aatypetimer');}}
function markercontent(mapobj,marker){if(markerhascontent(marker)){var markercontentid=mapobj.simplemapid+'-marker-'+marker.index;var content='<div class="markercontent" id="'+markercontentid+'">';content+=(marker.title!='')?'<div class="locationtitle">'+marker.title+'</div>':'';content+=(marker.title!='')?'<div class="locationcontent">'+nl2br(marker.content)+'</div>':'';content+='</div>';marker.markerobj.openInfoWindowHtml(content,{maxWidth:300});}}
function markerhascontent(marker){if((trim(marker.title))==''&&(trim(marker.content)==''))return false;return true;}
function viewmarker(mapobj,index){var marker=mapobj.simplemapmarkers[index];if(marker){markercontent(mapobj,marker);}}
function updatemarkerlist(mapobj){var mapid=mapobj.simplemapid;var markerlistwrapper='#edit-'+mapid+'-markers .markerlist';$(markerlistwrapper).empty();var markerlist=getallmarkers(mapobj);var markercount=0;if(markerlist){for(var i in markerlist){var marker=markerlist[i];if(!marker.deleted){addmarkerrow(mapobj,marker,markercount+1);markercount++;}}
$('#edit-'+mapid+'-markers .edit-marker-row:last').addClass('last');}
if(markercount==0){$(markerlistwrapper).html('<div class="empty-text">You don\'t have any markers.</div>');}}
function getallmarkers(mapobj){if(mapobj.simplemapmarkers){return mapobj.simplemapmarkers;}
return false;}
function addmarkerrow(mapobj,marker,markercount){var mapid=mapobj.simplemapid;var markerlistwrapper='#edit-'+mapid+'-markers .markerlist';var markerindex=marker.index;var markerwrapperid='edit-'+mapid+'-markers-'+markerindex;var mapidedit=(mapid=='simplemapnew')?'simplemapID':mapid;var markeridtext='  <span class="markerstyleid">('+mapidedit+'-marker'+markercount+')</span>';var container=document.createElement("div");container.setAttribute('class','edit-marker-row');container.id=markerwrapperid;var titleobj=document.createElement("div");titleobj.setAttribute('class','edit-marker-row-title');titleobj.onclick=function(){centermarker(mapobj,marker)};titleobj.innerHTML=((marker.title=='')?'Untitled '+markercount:nl2br(marker.title))+markeridtext;container.appendChild(titleobj);var deleteobj=document.createElement("div");deleteobj.innerHTML='<span>Delete</span>';deleteobj.setAttribute('class','edit-marker-row-delete');deleteobj.onclick=function(){deletemarker(mapobj,marker)};container.appendChild(deleteobj);var editobj=document.createElement("div");editobj.innerHTML='<span>Edit</span>';editobj.setAttribute('class','edit-marker-row-edit');editobj.onclick=function(){editmarker(mapobj,marker)};container.appendChild(editobj);var clearobj=document.createElement("div");clearobj.setAttribute('class','clearboth');container.appendChild(clearobj);var formobj=document.createElement("input");formobj.type="hidden";formobj.value=marker.title;formobj.name='edit-'+mapid+'[markers]['+markerindex+'][title]';container.appendChild(formobj);var formobj=document.createElement("input");formobj.type="hidden";formobj.value=marker.content;formobj.name='edit-'+mapid+'[markers]['+markerindex+'][content]';container.appendChild(formobj);var formobj=document.createElement("input");formobj.type="hidden";formobj.value=marker.lat;formobj.name='edit-'+mapid+'[markers]['+markerindex+'][lat]';container.appendChild(formobj);var formobj=document.createElement("input");formobj.type="hidden";formobj.value=marker.lng;formobj.name='edit-'+mapid+'[markers]['+markerindex+'][lng]';container.appendChild(formobj);$(markerlistwrapper).append(container);}
function nl2br(text){var breakTag='<br>';return(text+'').replace(/([^>]?)\n/g,'$1'+breakTag+'\n');}
function emptystring(text){return(trim(text)=='');}
function trim(str){return str.replace(/^\s\s*/,'').replace(/\s\s*$/,'');}
function strtolower(str){return(str+'').toLowerCase();}
function log(element){if(window.console){console.log(element);}}
this.each(function(){el=$(this);if(GBrowserIsCompatible&&GBrowserIsCompatible()){options=$.extend({},$.fn.simplemap.defaults,settings);options.id=el.attr('id');setsettings(this,options);initialize(this);}});return this;};$.fn.simplemap.defaults={title:'',mapcenterlat:52.530032,mapcenterlng:-0.127094,zoomlevel:15,editmode:true,markers:[],accuracyzoommap:{0:2,1:6,2:6,3:7,4:9,5:10,6:12,7:13,8:15,9:15}};$.fn.simplemap.settings={};function aaPane(){};aaPane.prototype=function(){return new GControl(false,false)};aaPane.prototype.initialize=function(map){var athis=this;athis.panel=document.createElement("div");athis.panel.style.height="20px";athis.panel.style.textAlign='left';athis.panel.style.fontSize='10px';athis.panel.style.color='#ffffff';athis.panel.innerHTML='<a href="http://www.atomicant.co.uk" target="_blank">Simplemap - Atomic Ant Limited 2009</a>';map.getContainer().appendChild(athis.panel);return athis.panel;};aaPane.prototype.getDefaultPosition=function(){return new GControlPosition(G_ANCHOR_BOTTOM_LEFT,new GSize(100,5));};aaPane.prototype.allowSetVisibility=function(){};aaPane.prototype.printable=function(){};aaPane.prototype.selectable=function(){};aaPane.prototype.getPanel=function(){return athis.panel;};$.fn.parsecoordinate=function(mapobj,latlng,respondwith){var geocoder=new GClientGeocoder();geocoder.getLocations(latlng,function(response){var returnaddress=false;var responsecode=response.Status.code;if(responsecode==200){var address=response.Placemark[0];returnaddress=address.address;}
respondwith(mapobj,returnaddress);});};$.fn.parseaddress=function(mapobj,respondwith){function placemark_get_detail(response,path){if(response.Placemark&&typeof(response.Placemark)=='object'){try{var detail=eval('response.Placemark[0].'+path);return detail;}catch(e){}}
return'';}
function address_get_detail(response,path){return placemark_get_detail(response,'AddressDetails.'+path)}
function get_lat_lon(response,coord){var Point=placemark_get_detail(response,'Point');if(Point!=''){if(coord=='lat'){return Point.coordinates[1];}else if(coord=='lon'){return Point.coordinates[0];}else{var points=new Array();points['lat']=Point.coordinates[1];points['lon']=Point.coordinates[0];return points;}}
return false;}
var address=this.val();var geocoder;geocoder=new GClientGeocoder();geocoder.getLocations(address,function(response){var cleanaddress=new Array();var responsecode=response.Status.code;if(responsecode==200){console.log(response);cleanaddress['address']=cleanaddress['country']=address_get_detail(response,'Country.CountryName');;cleanaddress['state']=address_get_detail(response,'Country.AdministrativeArea.AdministrativeAreaName');cleanaddress['city']=address_get_detail(response,'Country.AdministrativeArea.Locality.LocalityName');cleanaddress['street']=address_get_detail(response,'Country.AdministrativeArea.Locality.Thoroughfare.ThoroughfareName');cleanaddress['zip']=address_get_detail(response,'Country.AdministrativeArea.Locality.PostalCode.PostalCodeNumber');cleanaddress['lat']=get_lat_lon(response,'lat');cleanaddress['lon']=get_lat_lon(response,'lon');cleanaddress['glatlng']=new GLatLng(cleanaddress['lat'],cleanaddress['lon']);cleanaddress['accuracy']=address_get_detail(response,'Accuracy');}
cleanaddress['responsecode']=responsecode;respondwith(mapobj,cleanaddress);});};})(jQuery);$(document).ready(function(){var settingspath='Drupal.settings.simplemap';$('.mapcanvas').each(function(i){var mapid=$(this).attr('id');var settings=(eval(settingspath+'.'+mapid));if(!settings)settings={};$(this).simplemap(settings);});});