/**
 * CENTRE THE LOADING MESSAGE
 **/
jQuery.fn.centerScreen=function(loaded){if(!jQuery(loaded).length)return;var obj=this;if(!loaded){obj.css('top',($(window).height()*0.3)-(this.height()*0.3));obj.css('left',$(window).width()/2-this.width()/2);$(window).resize(function(){obj.centerScreen(!loaded);});}else{obj.stop();obj.animate({top:$(window).height()/2-this.height()/2,left:$(window).width()/2-this.width()/2},200,'linear');}};

jQuery.merge_options = function(main, extra1, extra2){ 
  return $.extend({}, main, extra1, extra2);
};
/**
 * Ajax loading functions for the maps
 */ 
$(document).ajaxStart(function(ajaxevent){ $('#ajaxBusy').show().centerScreen();});
$(document).ajaxStop(function(){$('#ajaxBusy').hide();});
$(document).ajaxError(function(){$('#ajaxBusy').hide();});
/*
	MODIFIED ClusterMarker Version 1.3.2
	A marker manager for the Google Maps API
	http://googlemapsapi.martinpearman.co.uk/clustermarker
	Copyright Martin Pearman 2008
	Last updated 29th September 2008
	This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
	This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
	You should have received a copy of the GNU General Public License along with this program.  If not, see <http://www.gnu.org/licenses/>.	
*/
function ClusterMarker($map,$options){this._map=$map;this._mapMarkers=[];this._iconBounds=[];this._clusterMarkers=[];this._eventListeners=[];this.moveend_listener=undefined;this.zoomend_listener=undefined;this.maptypechanged_listener=undefined;if(typeof($options)==='undefined'){$options={};}
this.borderPadding=($options.borderPadding)?$options.borderPadding:256;this.clusteringEnabled=($options.clusteringEnabled===false)?false:true;if($options.clusterMarkerClick){this.clusterMarkerClick=$options.clusterMarkerClick;}
if($options.clusterMarkerIcon){this.clusterMarkerIcon=$options.clusterMarkerIcon;}else{this.clusterMarkerIcon=new GIcon();this.clusterMarkerIcon.image='http://maps.google.com/mapfiles/arrow.png';this.clusterMarkerIcon.iconSize=new GSize(39,34);this.clusterMarkerIcon.iconAnchor=new GPoint(9,31);this.clusterMarkerIcon.infoWindowAnchor=new GPoint(9,31);this.clusterMarkerIcon.shadowSize=new GSize(0,0);}
this.clusterMarkerTitle=($options.clusterMarkerTitle)?$options.clusterMarkerTitle:'Click to zoom in and see %count dealers';if($options.fitMapMaxZoom){this.fitMapMaxZoom=$options.fitMapMaxZoom;}
this.intersectPadding=($options.intersectPadding)?$options.intersectPadding:0;if($options.markers){this.addMarkers($options.markers);}
this.moveend_listener=GEvent.bind(this._map,'moveend',this,this._moveEnd);this.zoomend_listener=GEvent.bind(this._map,'zoomend',this,this._zoomEnd);this.maptypechanged_listener=GEvent.bind(this._map,'maptypechanged',this,this._mapTypeChanged);};ClusterMarker.prototype.clear_listeners=function(){GEvent.removeListener(this.moveend_listener);GEvent.removeListener(this.zoomend_listener);GEvent.removeListener(this.maptypechanged_listener);};ClusterMarker.prototype.addMarkers=function($markers){var i;if(!$markers[0]){var $numArray=[];for(i in $markers){$numArray.push($markers[i]);}
$markers=$numArray;}
for(i=$markers.length-1;i>=0;i--){$markers[i]._isVisible=false;$markers[i]._isActive=false;$markers[i]._makeVisible=false;}
this._mapMarkers=this._mapMarkers.concat($markers);};ClusterMarker.prototype._clusterMarker=function($clusterGroupIndexes){function $newClusterMarker($location,$icon,$title){return new GMarker($location,{icon:$icon,title:$title});}
var $clusterGroupBounds=new GLatLngBounds(),i,$clusterMarker,$clusteredMarkers=[],$marker,$this=this,$mapMarkers=this._mapMarkers;for(i=$clusterGroupIndexes.length-1;i>=0;i--){$marker=$mapMarkers[$clusterGroupIndexes[i]];$marker.index=$clusterGroupIndexes[i];$clusterGroupBounds.extend($marker.getLatLng());$clusteredMarkers.push($marker);}
this.clusterMarkerIcon.image=this.clusterMarkerIcon.image.replace('%count',$clusterGroupIndexes.length);$clusterMarker=$newClusterMarker($clusterGroupBounds.getCenter(),this.clusterMarkerIcon,this.clusterMarkerTitle.replace(/%count/gi,$clusterGroupIndexes.length));$clusterMarker.clusterGroupBounds=$clusterGroupBounds;this._eventListeners.push(GEvent.addListener($clusterMarker,'click',function(){$this.clusterMarkerClick({clusterMarker:$clusterMarker,clusteredMarkers:$clusteredMarkers});}));$clusterMarker._childIndexes=$clusterGroupIndexes;for(i=$clusterGroupIndexes.length-1;i>=0;i--){$mapMarkers[$clusterGroupIndexes[i]]._parentCluster=$clusterMarker;}
return $clusterMarker;};ClusterMarker.prototype.clusterMarkerClick=function($args){this._map.setCenter($args.clusterMarker.getLatLng(),this._map.getBoundsZoomLevel($args.clusterMarker.clusterGroupBounds));};ClusterMarker.prototype._filterActiveMapMarkers=function(){var $borderPadding=this.borderPadding,$mapZoomLevel=this._map.getZoom(),$mapProjection=this._map.getCurrentMapType().getProjection(),$mapPointSw,$activeAreaPointSw,$activeAreaLatLngSw,$mapPointNe,$activeAreaPointNe,$activeAreaLatLngNe,$activeAreaBounds=this._map.getBounds(),i,$marker,$uncachedIconBoundsIndexes=[],$oldState,$mapMarkers=this._mapMarkers,$iconBounds=this._iconBounds;if($borderPadding){$mapPointSw=$mapProjection.fromLatLngToPixel($activeAreaBounds.getSouthWest(),$mapZoomLevel);$activeAreaPointSw=new GPoint($mapPointSw.x-$borderPadding,$mapPointSw.y+$borderPadding);$activeAreaLatLngSw=$mapProjection.fromPixelToLatLng($activeAreaPointSw,$mapZoomLevel);$mapPointNe=$mapProjection.fromLatLngToPixel($activeAreaBounds.getNorthEast(),$mapZoomLevel);$activeAreaPointNe=new GPoint($mapPointNe.x+$borderPadding,$mapPointNe.y-$borderPadding);$activeAreaLatLngNe=$mapProjection.fromPixelToLatLng($activeAreaPointNe,$mapZoomLevel);$activeAreaBounds.extend($activeAreaLatLngSw);$activeAreaBounds.extend($activeAreaLatLngNe);}
this._activeMarkersChanged=false;if(typeof($iconBounds[$mapZoomLevel])==='undefined'){this._iconBounds[$mapZoomLevel]=[];this._activeMarkersChanged=true;for(i=$mapMarkers.length-1;i>=0;i--){$marker=$mapMarkers[i];$marker._isActive=$activeAreaBounds.containsLatLng($marker.getLatLng())?true:false;$marker._makeVisible=$marker._isActive;if($marker._isActive){$uncachedIconBoundsIndexes.push(i);}}}else{for(i=$mapMarkers.length-1;i>=0;i--){$marker=$mapMarkers[i];$oldState=$marker._isActive;$marker._isActive=$activeAreaBounds.containsLatLng($marker.getLatLng())?true:false;$marker._makeVisible=$marker._isActive;if(!this._activeMarkersChanged&&$oldState!==$marker._isActive){this._activeMarkersChanged=true;}
if($marker._isActive&&typeof($iconBounds[$mapZoomLevel][i])==='undefined'){$uncachedIconBoundsIndexes.push(i);}}}
return $uncachedIconBoundsIndexes;};ClusterMarker.prototype._filterIntersectingMapMarkers=function(){var $clusterGroup,i,j,$mapZoomLevel=this._map.getZoom(),$mapMarkers=this._mapMarkers,$iconBounds=this._iconBounds;for(i=$mapMarkers.length-1;i>0;i--)
{if($mapMarkers[i]._makeVisible){$clusterGroup=[];for(j=i-1;j>=0;j--){if($mapMarkers[j]._makeVisible&&$iconBounds[$mapZoomLevel][i].intersects($iconBounds[$mapZoomLevel][j])){$clusterGroup.push(j);}}
if($clusterGroup.length!==0){$clusterGroup.push(i);for(j=$clusterGroup.length-1;j>=0;j--){$mapMarkers[$clusterGroup[j]]._makeVisible=false;}
this._clusterMarkers.push(this._clusterMarker($clusterGroup));}}}};ClusterMarker.prototype.fitMapToMarkers=function(){var $mapMarkers=this._mapMarkers,$markersBounds=new GLatLngBounds(),i;for(i=$mapMarkers.length-1;i>=0;i--){$markersBounds.extend($mapMarkers[i].getLatLng());}
var $fitMapToMarkersZoom=this._map.getBoundsZoomLevel($markersBounds);if(this.fitMapMaxZoom&&$fitMapToMarkersZoom>this.fitMapMaxZoom){$fitMapToMarkersZoom=this.fitMapMaxZoom;}
this._map.setCenter($markersBounds.getCenter(),$fitMapToMarkersZoom);this.refresh();};ClusterMarker.prototype._mapTypeChanged=function(){this.refresh(true);};ClusterMarker.prototype._moveEnd=function(){if(!this._cancelMoveEnd){this.refresh();}else{this._cancelMoveEnd=false;}};ClusterMarker.prototype._preCacheIconBounds=function($indexes,$mapZoomLevel){var $mapProjection=this._map.getCurrentMapType().getProjection(),i,$marker,$iconSize,$iconAnchorPoint,$iconAnchorPointOffset,$iconBoundsPointSw,$iconBoundsPointNe,$iconBoundsLatLngSw,$iconBoundsLatLngNe,$intersectPadding=this.intersectPadding,$mapMarkers=this._mapMarkers;for(i=$indexes.length-1;i>=0;i--){$marker=$mapMarkers[$indexes[i]];$iconSize=$marker.getIcon().iconSize;$iconAnchorPoint=$mapProjection.fromLatLngToPixel($marker.getLatLng(),$mapZoomLevel);$iconAnchorPointOffset=$marker.getIcon().iconAnchor;$iconBoundsPointSw=new GPoint($iconAnchorPoint.x-$iconAnchorPointOffset.x-$intersectPadding,$iconAnchorPoint.y-$iconAnchorPointOffset.y+$iconSize.height+$intersectPadding);$iconBoundsPointNe=new GPoint($iconAnchorPoint.x-$iconAnchorPointOffset.x+$iconSize.width+$intersectPadding,$iconAnchorPoint.y-$iconAnchorPointOffset.y-$intersectPadding);$iconBoundsLatLngSw=$mapProjection.fromPixelToLatLng($iconBoundsPointSw,$mapZoomLevel);$iconBoundsLatLngNe=$mapProjection.fromPixelToLatLng($iconBoundsPointNe,$mapZoomLevel);this._iconBounds[$mapZoomLevel][$indexes[i]]=new GLatLngBounds($iconBoundsLatLngSw,$iconBoundsLatLngNe);}};ClusterMarker.prototype.refresh=function($forceFullRefresh){var i,$marker,$zoomLevel=this._map.getZoom(),$uncachedIconBoundsIndexes=this._filterActiveMapMarkers();if(this._activeMarkersChanged||$forceFullRefresh){this._removeClusterMarkers();if(this.clusteringEnabled&&$zoomLevel<this._map.getCurrentMapType().getMaximumResolution()){if($uncachedIconBoundsIndexes.length>0){this._preCacheIconBounds($uncachedIconBoundsIndexes,$zoomLevel);}
this._filterIntersectingMapMarkers();}
for(i=this._clusterMarkers.length-1;i>=0;i--){this._map.addOverlay(this._clusterMarkers[i]);}
for(i=this._mapMarkers.length-1;i>=0;i--){$marker=this._mapMarkers[i];if(!$marker._isVisible&&$marker._makeVisible){this._map.addOverlay($marker);$marker._isVisible=true;}
if($marker._isVisible&&!$marker._makeVisible){this._map.removeOverlay($marker);$marker._isVisible=false;}}}};ClusterMarker.prototype._removeClusterMarkers=function(){var i,j,$map=this._map,$eventListeners=this._eventListeners,$clusterMarkers=this._clusterMarkers,$childIndexes,$mapMarkers=this._mapMarkers;for(i=$clusterMarkers.length-1;i>=0;i--){$childIndexes=$clusterMarkers[i]._childIndexes;for(j=$childIndexes.length-1;j>=0;j--){delete $mapMarkers[$childIndexes[j]]._parentCluster;}
$map.removeOverlay($clusterMarkers[i]);}
for(i=$eventListeners.length-1;i>=0;i--){GEvent.removeListener($eventListeners[i]);}
this._clusterMarkers=[];this._eventListeners=[];};ClusterMarker.prototype.removeMarkers=function(){var i,$mapMarkers=this._mapMarkers,$map=this._map;for(i=$mapMarkers.length-1;i>=0;i--){if($mapMarkers[i]._isVisible){$map.removeOverlay($mapMarkers[i]);}
delete $mapMarkers[i]._isVisible;delete $mapMarkers[i]._isActive;delete $mapMarkers[i]._makeVisible;}
this._removeClusterMarkers();this._mapMarkers=[];this._iconBounds=[];};ClusterMarker.prototype.triggerClick=function($index){var $marker=this._mapMarkers[$index];if($marker._isVisible){GEvent.trigger($marker,'click');}
else if($marker._isActive){var $clusteredMarkersIndexes=$marker._parentCluster._childIndexes,$intersectDetected=true,$uncachedIconBoundsIndexes,i,$mapZoomLevel=this._map.getZoom(),$clusteredMarkerIndex,$iconBounds=this._iconBounds,$mapMaxZoomLevel=this._map.getCurrentMapType().getMaximumResolution();while($intersectDetected&&$mapZoomLevel<$mapMaxZoomLevel){$intersectDetected=false;$mapZoomLevel++;if(typeof($iconBounds[$mapZoomLevel])==='undefined'){$iconBounds[$mapZoomLevel]=[];this._preCacheIconBounds($clusteredMarkersIndexes,$mapZoomLevel);}else{$uncachedIconBoundsIndexes=[];for(i=$clusteredMarkersIndexes.length-1;i>=0;i--){if(typeof($iconBounds[$mapZoomLevel][$clusteredMarkersIndexes[i]])==='undefined'){$uncachedIconBoundsIndexes.push($clusteredMarkersIndexes[i]);}}
if($uncachedIconBoundsIndexes.length>=1){this._preCacheIconBounds($uncachedIconBoundsIndexes,$mapZoomLevel);}}
for(i=$clusteredMarkersIndexes.length-1;i>=0;i--){$clusteredMarkerIndex=$clusteredMarkersIndexes[i];if($clusteredMarkerIndex!==$index&&$iconBounds[$mapZoomLevel][$clusteredMarkerIndex].intersects($iconBounds[$mapZoomLevel][$index])){$intersectDetected=true;break;}}};this._map.setCenter($marker.getLatLng(),$mapZoomLevel);this.triggerClick($index);}else{this._map.setCenter($marker.getLatLng());this.triggerClick($index);}};ClusterMarker.prototype._zoomEnd=function(){this._cancelMoveEnd=true;this.refresh(true);};

/** 
 * ICONS
 */
(function($) {  
  $.icon ={
    defaults:{},
    create:function(options){
      var opts = $.merge_options($.icon.defaults, options), icon = new GIcon(G_DEFAULT_ICON);
      if(opts.image) icon.image = opts.image;
      if(opts.dimensions){
        icon.iconSize = new GSize(opts.dimensions.x, opts.dimensions.y);
        icon.imageMap = [0,0, opts.dimensions.x,0, opts.dimensions.x,opts.dimensions.y, 0,opts.dimensions.y];
        if(opts.shadowsize) icon.shadowSize=new GSize(opts.shadowsize.x,opts.shadowsize.y);
        else icon.shadowSize=new GSize(0,0);
      }
      return icon;
    }
  };
})(jQuery);

/**
 * FACILITY LINKS
 */
(function($) {  
  $.facilities ={
    defaults:{available:[{'trigger':'.facilities_used_cars', 'location':"/vehicles/used"}, 
                         {'trigger':'.facilities_sales', 'location':"/vehicles/new-cars"},
                         {'trigger':'.facilities_service', 'location':"/book-a-service"},
                         {'trigger':'.facilities_parts', 'location':"/book-a-service"}
                        ]
              },
    hash:{},
    create:function(options){
      $.facilities.unbind();
      $.facilities.hash.options = $.merge_options($.facilities.defaults, options);
      for(var nm in $.facilities.hash.options.available){
        var facility = $.facilities.hash.options.available[nm];
        jQuery(facility.trigger).attr('href', facility.location);
      }
    },
    unbind:function(){
      $.facilities.hash.options = $.facilities.defaults;
      for(var nm in $.facilities.hash.options.available){
        jQuery($.facilities.hash.options.available[nm].trigger).unbind("click");
      }
    }
  };
})(jQuery);
/**
 * WINDOWS
 */
(function($) {
  
  $.infowindow ={
    hash:{},
    defaults:{fetch:{method:"get", url:"/details.json?id=", timeout:4000, data_type:"json"}, window_options:{maxWidth:450} },
    fetch:function(options){
      $.infowindow.hash.options = $.merge_options($.infowindow.defaults, options);
      jQuery.ajax({
  	    type:$.infowindow.hash.options.fetch.method,
        url:$.infowindow.hash.options.fetch.url + $.infowindow.hash.options.querystring,
        timeout: $.infowindow.hash.options.fetch.timeout,
        dataType: $.infowindow.hash.options.fetch.data_type,
        success:function(response){
          $.infowindow.create(response[0]);
          $.infowindow.open();
          $.infowindow.close();
        },
        error:function(){}
      }); 
    },
    create:function(data){
      $.infowindow.hash.options.tabs = [];
      var remote_tabs = data.tabs;
      for(var tname in remote_tabs) $.infowindow.hash.options.tabs.push(new GInfoWindowTab(tname, remote_tabs[tname]));
    },
    open:function(){
      $.infowindow.hash.options.info_window = $.infowindow.hash.options.gmarker.openInfoWindowTabsHtml($.infowindow.hash.options.tabs, $.infowindow.hash.options.window_options);
      $.infowindow.hash.options.info_window_open = GEvent.addListener($.infowindow.hash.options.gmarker, "infowindowopen", 
        function(){
          $.obb_map.save();
          $.facilities.create();
        }
      );
    },
    close:function(){
      GEvent.addListener($.infowindow.hash.options.gmarker, "infowindowclose", 
        function(){
          $.facilities.unbind();
          GEvent.removeListener($.infowindow.hash.options.info_window_open);
          $.obb_map.load();
        }
      );
    }
  };
    
})(jQuery);

/** 
 * MARKERS
 */
(function($) {
  $.marker = {
    hash:{},
    defaults:{latitude:54.67383096593114, longitude:-3.515625, title:'Click For More Details...', double_click_zoom:15},
    create:function(options){
      $.marker.hash.options = $.merge_options($.marker.defaults, options);
      marker = new GMarker(new GLatLng($.marker.hash.options.latitude, $.marker.hash.options.longitude), {icon:jQuery.icon.create(), title:$.marker.hash.options.title});
      return marker; 
    },
    trigger:function(gmarker, data, options){
      GEvent.addListener(gmarker, "click", function(){jQuery.marker.clicked(gmarker, data, options);});
      return gmarker;
    },
    double_clicked:function(marker){
      $.obb_map.center(false, marker.getLatLng(), $.marker.hash.options.double_click_zoom);
    },
    clicked:function(gmarker, data, options){
      $.infowindow.fetch({gmarker:gmarker, querystring: data.id});
    }
  };  
  var opts = $.marker.hash.options;
})(jQuery);

(function($) {
  $.cluster = {  
    hash:{},
    defaults:{icons:false},
    create:function(gmap, gmarkers){
      var cluster_marker_obj = new ClusterMarker(gmap, { markers:gmarkers} );
	    cluster_marker_obj.fitMapToMarkers();
	    return cluster_marker_obj;
    }   
  };
})(jQuery);


(function($) {
  $.obb_map = {  
    hash:{},
    defaults:{container: "google_map", lat:54.67383096593114, lng:-3.515625, zoom:5, fetchmarkers:{method:"get", url:"/markers.json",timeout:4000,data_type:"json"}},
    create:function(options){
      $.obb_map.hash.options = $.merge_options($.obb_map.defaults, options);
      $.obb_map.hash.map_obj = new google.maps.Map2(document.getElementById($.obb_map.hash.options.container));      
      $.obb_map.center($.obb_map.hash.map_obj,new GLatLng($.obb_map.hash.options.lat, $.obb_map.hash.options.lng), $.obb_map.hash.options.zoom);
      $.obb_map.hash.map_obj.setUIToDefault();
		  $.obb_map.hash.map_obj.enableScrollWheelZoom();
		  return $.obb_map.hash.map_obj;
    },
    center:function(gmap,latlng, zoom){
      if(!gmap) gmap = $.gmap.hash[0].map;
      gmap.setCenter(latlng, zoom);
    },
    save:function(gmap){
      if(!gmap) gmap = $.gmap.hash[0].map;
      gmap.savePosition();
    },
    load:function(gmap){
      if(!gmap) gmap = $.gmap.hash[0].map;
      gmap.returnToSavedPosition();
    },
    add_markers:function(gmap, markers){
      if(!gmap) gmap = $.gmap.hash[0].map;
      for(var pos in markers){
        gmap.removeOverlay(markers[pos]);
        gmap.addOverlay(markers[pos]);
      }
    },
    clear_markers:function(gmap){
      if(!gmap) gmap = $.gmap.hash[0].map;
      gmap.clearOverlays();
    }
  };
})(jQuery);
 
/**
 * MAP
 */ 
(function($) {

	$.fn.gmap = function(options){
		return this.each(function(){		
			//check dependancies && not in use atm
			if(this._kick_ass || !$.gmap.compatible()) return;
			this._kick_ass = 'obb';
			//setup params
			var params = $.merge_options($.fn.gmap.defaults, options);
			//create this point the array			
			H[0] = {params:params, map_container:this};
			$.gmap.init(H[0]);
		  //run the map plugin
			$.gmap.load(H[0]);
		});	
	};
	
	$.gmap = {
		hash:{},//data
		compatible:function(){
		  if(typeof(GBrowserIsCompatible) == "function" && typeof(jQuery) != "undefined") return GBrowserIsCompatible();
		  else return false;
		},
		init:function(hash){
		  hash.map = $.obb_map.create();		  
		},
    load:function(hash){
      var fetch = $.obb_map.defaults.fetchmarkers;
      hash.markers = [];      
      jQuery.ajax({
        type:fetch.method,
        url:fetch.url,
        timeout: fetch.timeout,
        dataType: fetch.data_type,
        success:function(response){
          for(var primval in response) hash.markers.push( $.marker.trigger($.marker.create(response[primval]), response[primval]) );
          $.gmap.after_load(hash);
        },
        error:function(){}
      });
    },   
	  after_load:function(hash){
	    if(hash.params.use_clustering) $.cluster.create(hash.map, hash.markers);
	    else $.obb_map.add_markers(hash.map,hash.markers);
	  }
	};
	
	$.fn.gmap.defaults = {use_clustering:false};
  var H=$.gmap.hash;
	
})(jQuery);

