/*  relies on:
       https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js
       http://maps.google.com/maps/api/js?sensor=false
*/

var googlemaps = new Array();

function googlemaps_init(divid,address,mapoptions){
   var map;
   var geocoder;

   var sanitized_divid = divid.replace(/-/,'_');

   mapoptions = mapoptions || function(){try{return(eval(sanitized_divid+'_mapoptions'));}catch(e){return(null);}}() || null;

   this.refresh = function(){
      google.maps.event.trigger(map,'resize'); 
   }

   function setup_map(results,status){
      if(status==google.maps.GeocoderStatus.OK){
         latlng = results[0].geometry.location;

         var options = Array();

         if(mapoptions){
            options = mapoptions;
            if(!options['mapTypeId']){
               options['mapTypeId']=google.maps.MapTypeId.ROADMAP;
            }
            if(!options['zoom']){
               options['zoom']=13;
            }
            options['center']=latlng;
         }else{
            options = {
               'zoom':13,
               'center': latlng,
               'mapTypeId':google.maps.MapTypeId.ROADMAP
            };
         }

         map = new google.maps.Map(document.getElementById(divid),options);

         var marker = new google.maps.Marker({'map':map,'position':latlng});
      }else{
         alert('no success: '+status);
      }
   }

   geocoder = new google.maps.Geocoder();

   if(address){
      geocoder.geocode({'address':address},setup_map);
   }else{
      try{
         var pat = /googlemaps\-address_([^\s]+)/;
         var classes = $('#'+divid).attr('class');

         var raw = pat.exec(classes);

         if(raw){
            var address = raw[1];

            address = address.replace(/_/g,' ');
            address = address.replace(/\-\-\-/g,', ');
            address = address.replace(/\-\-/g,', ');
            address = address.replace(/\-/g,' ');

            geocoder.geocode({'address':address},setup_map);
         }else{
            alert('#'+divid+' has not been initialized, no address could be determined');
         }
      }catch(e){
         alert("googlemaps_init: "+e);
      }
   }

   googlemaps[divid]=this;
}

var togooglemaps = new Array();

function togooglemaps_init(id,settings){
   settings = settings || {'default-button':'top_left'};

   function calc_width(){
      var pat = /(\d*)/;

      var width = 0;
 
      width+=parseInt(pat.exec($('#'+id).css('width')));
      width+=parseInt(pat.exec($('#'+id).css('padding-left')));
      width+=parseInt(pat.exec($('#'+id).css('padding-right')));
      width+=parseInt(pat.exec($('#'+id).css('margin-left')));
      width+=parseInt(pat.exec($('#'+id).css('margin-right')));
      width+=parseInt(pat.exec($('#'+id).css('border-left-width')));
      width+=parseInt(pat.exec($('#'+id).css('border-right-width')));

      return(width); 
   }

   function calc_height(){
      var pat = /(\d*)/;

      var height = 0;

      height+=parseInt(pat.exec($('#'+id).css('height')));
      height+=parseInt(pat.exec($('#'+id).css('padding-top')));
      height+=parseInt(pat.exec($('#'+id).css('padding-bottom')));
      height+=parseInt(pat.exec($('#'+id).css('margin-top')));
      height+=parseInt(pat.exec($('#'+id).css('margin-bottom')));
      height+=parseInt(pat.exec($('#'+id).css('border-top-width')));
      height+=parseInt(pat.exec($('#'+id).css('border-bottom-width')));

      return(height);
   }

   var count = 0;
   this.toggle = function(showhide){
      var img = $('#'+id); var map = $('#'+id+'-map');
      $('#'+id+'-wrap').removeClass('img').addClass('map');
      if(showhide || ++count%2==0){
         var inter = img;
         img = map; map = inter;
         $('#'+id+'-wrap').removeClass('map').addClass('img');
      }
      img.animate({'opacity': 0.0},1000,function(){
         map.css('z-index','2');
         img.css('z-index','1').css('opacity','1.0');
      });

      //default-button
      if(count%2==0){
         $('#'+id+'-default-button').html(button_contents['on']);
         $('#'+id+'-default-button').removeClass('off').addClass('on');
      }else{
         $('#'+id+'-default-button').html(button_contents['off']);
         $('#'+id+'-default-button').removeClass('on').addClass('off');
      }
   }

   this.resize = function(height,width){
      $('#'+id+'-wrap').animate({'height':height,'width':width},1000,googlemaps[id+'-map'].refresh);
   }

   this.restore = function(){
      $('#'+id+'-wrap').animate({'height':orig_height,'width':orig_width},1000,googlemaps[id+'-map'].refresh);
   }

   var address = settings['address'];

   if(!address){
      try{
         var pat = /googlemaps\-address_([^\s]+)/;
         var classes = $('#'+id).attr('class');

         var raw = pat.exec(classes);

         if(raw){
            address = raw[1];
  
            address = address.replace(/\-\-\-/g,', ');
            address = address.replace(/\-\-/g,', ');
            address = address.replace(/\-/g,' ');
         }else{
            alert('#'+id+'-map has not been initialized, no address could be determined');
         }
      }catch(e){
         alert("togooglemaps_init: "+e);
      }
   }
   this.address = address; 

   var pretty_address = address.replace(/_/,'<br>');
   this.pretty_address = pretty_address;

   var orig_height = calc_height(), orig_width = calc_width();

   var wrap_css = "height:"+orig_height+"px;width:+"+orig_width+"px;position:relative;";

   var map_css = "position:absolute;height:100%;width:100%;z-index:1;";
   var map_html = "<div id='"+id+"-map' class='googlemaps-map' style='"+map_css+"'></div>";

   var button_css ={ '.googlemaps-button':"position:absolute;z-index:3;margin:5px;",
                     '.googlemaps-button.on':"bottom:0px;right:0px;background-color:#000000;color:#ffffff;opacity:0.7;padding:5px;-moz-border-radius:1em;",
                     '.googlemaps-button.off':"top:0px;right:0px;background-color:#ff0000;"
   };

   var button_js = {  };

   var button_attributes={ 'onclick':"togooglemaps[\""+id+"\"].toggle();",
                           'id':id+"-default-button",
                           'class':"googlemaps-button on"
   };

   var button_contents={ 'on':pretty_address,
                         'off':"x"
   }
 
   var button_initial_content = "on";
   var button_quote = "'";
   var button_tag = "div";

   var button_html = ("<"+button_tag+" ");
   for(var i in button_attributes){
      button_html+=(" "+i+"="+button_quote+button_attributes[i]+button_quote+" ");
   }
   button_html+=(" >"+button_contents[button_initial_content]+"</"+button_tag+">");

   button_style="<style type='text/css'>";
   for(var i in button_css){
      button_style+=(i+"{"+button_css[i]+";} ");
   }
   button_style+="</style>";

   try{
      eval(button_js);
   }catch(e){
      alert(e);
   }

   $(button_style).insertBefore($('#'+id));

   var wrap_html = "<div id='"+id+"-wrap' class='googlemaps-wrap' style='"+wrap_css+"'>"+map_html+button_html+"</div>";
   
   $('#'+id).parent().append(wrap_html);
   $('#'+id+'-wrap').insertBefore('#'+id);
   $('#'+id+'-wrap').css('display','block');
   $('#'+id).appendTo($('#'+id+'-wrap'));

   $('#'+id).css('position','absolute').css('z-index','2');

   if(address){
      googlemaps_init(id+'-map',address);
   }else{
      alert("togooglemaps_init: "+e);
   }
   
   togooglemaps[id]=this;
}

function init_togooglemaps(){
      $('.togooglemaps').each(function(){
      try{
         var id;
         if(!(id = $(this).attr('id'))){
            id='togooglemaps-'+Math.floor(Math.random()*1000000);
            $(this).attr('id',id);

            function safetyLoop(){
               if(!document.getElementById(id)){
                  setTimeout(safetyLoop,250);
                  return;
               }
               togooglemaps_init(id);
            };
            safetyLoop();
            return;
         }
         togooglemaps_init(id);
      }catch(e){
         alert("init_togooglemaps: "+e);
      }
   });
}

function init_googlemaps(){
   $('.googlemaps').each(function(){
      try{
         var id;
         if(!(id = $(this).attr('id'))){
            id='googlemaps-'+Math.floor(Math.random()*1000000);
            $(this).attr('id',id);

            function safetyLoop(){
               if(!document.getElementById(id)){
                  setTimeout(safetyLoop,250);
                  return;
               }
               googlemaps_init(id);
               return;
            };
            safetyLoop();
            return;
         }
         googlemaps_init(id);
      }catch(e){
         alert("init_googlemaps: "+e);
      }
   });
}

$(document).ready(init_googlemaps);
$(document).ready(init_togooglemaps);

