var opentrigger=0;
var MARKERS=[];
var GMAP=false;
var ACTIVE=false;

function mapcenter(){
  var bounds = new GLatLngBounds();
  if(MARKERS.length){
    for(var i in MARKERS) bounds.extend(MARKERS[i].getLatLng());
    var zoom = GMAP.getBoundsZoomLevel(bounds);
    GMAP.setCenter(bounds.getCenter(), zoom);
  }
};

function activemarker(i){
  jQuery('.mapitem').removeClass('gselected');
  var item = jQuery('.mpi'+i).addClass('gselected');
  
  var selectedicon = new GIcon(G_DEFAULT_ICON);
	selectedicon.image = "/images/markers/selected.png";
  if(MARKERS.length && MARKERS[i]){
    if(ACTIVE) GMAP.removeOverlay(ACTIVE);
    ACTIVE = new GMarker(MARKERS[i].getLatLng(),{icon:selectedicon});		
	  GMAP.addOverlay(ACTIVE);
  }
};
/**
 * container_id - container div id
 * config
 *   - list_id
 *   - centre_point
 *   - zoom
 */
function gmap(container_id, config){
  MARKERS=[];
  this.markers=[];
  this.container_id = container_id;
  if(typeof(markers) != "undefined") this.markers = markers;
  if(typeof(config) != "undefined") this.config = jQuery.extend({}, this.config, config);
  //call the init function
  this.init();
  //fetch the markers
  if(this.config.list_id) this.markers_from_list();
  else if(this.config.latlng) this.markers_from_latlng();
  //draw the markers
  this.draw_markers();
};
//container for the google_map
gmap.prototype.container_id="";
//the map object
gmap.prototype.map=false;
//the markers array
gmap.prototype.markers=[];
//bounding box
gmap.prototype.bounds=false;
//config values
gmap.prototype.config={
                        "list_id":"google_listing",
                        "child":"mapitem",
                        "location":"location",
                        "latlng":"latlng",
                        "centre_point":false,
                        "zoom":12,
                        "icon_image_base":"/images/markers/marker",
                        "icon_image_type":".png",
                        "click":"a.move"
                      };
//create the map
gmap.prototype.init = function(){
  if(GBrowserIsCompatible() && jQuery('#'+this.container_id).length){
    GMAP = this.map = new GMap2(document.getElementById(this.container_id));
    this.map.setUIToDefault();
		this.map.enableScrollWheelZoom();
		GEvent.clearInstanceListeners(this.map);
		this.map.clearOverlays();
		this.map.setCenter(new GLatLng(54.67383096593114,-3.515625), 5);
		jQuery(this.config.click).click(function(){
      var item = jQuery(this).parent().parent().parent().parent('.mapitem')[0];
      GEvent.trigger(MARKERS[item.__val], "click");
   		scrollTo(0,150);
      return false;
    });
    
  }
};
//find all marker values
gmap.prototype.markers_from_list = function(){
  var found = jQuery('#'+this.config.list_id).find("."+this.config.child), len=found.length;
  for(var i=0; i<len; i++){    
    found[i].__val=i;
    jQuery(found[i]).addClass('mpi'+i);
    if(jQuery(found[i]).hasClass('nobg') ){}
    else jQuery(found[i]).find("h3 a").css({'background':"url('"+this.config.icon_image_base+(i+1)+this.config.icon_image_type+"') no-repeat top left",'list-style-type':'none','margin-left':"0",'padding-left':'25px'});
    this.markers.push({"obj":found[i], "location":jQuery(found[i]).find('.'+this.config.location).html(), "latlng":jQuery(found[i]).find('.'+this.config.latlng).html()});
  }
};

gmap.prototype.markers_from_latlng = function(){
  this.markers.push({"obj":false,"location":this.config.latlng});
};
//use local search
gmap.prototype.draw_markers = function(){    
  for(var mk in this.markers){
    var pos =parseInt(mk)+1;
    var img = this.config.icon_image_base+pos+this.config.icon_image_type;
    var gmark = new gmarker(this.map, mk, this.markers[mk], img);
    if(typeof(this.markers[mk].latlng) == "string" && this.markers[mk].latlng.length) gmark.draw();
    else gmark.search();
  }
  var timedfunc = function(){mapcenter();};
  setTimeout(timedfunc, 1300);
};

function gmarker(map, i, obj, icon_image){
  this.map = map;
  this.pos=i;
  this.obj = obj;
  this.icon_image = icon_image;
};
gmarker.prototype.map=false;
gmarker.prototype.pos=false;
gmarker.prototype.obj=false;
gmarker.prototype.icon_image=false;

gmarker.prototype.draw = function(){

  this.obj.latlng = this.obj.latlng.split(",");
  
  var baseIcon = new GIcon(G_DEFAULT_ICON);
  baseIcon.iconSize = new GSize(20, 34);
  baseIcon.shadowSize = new GSize(37, 34);
  baseIcon.iconAnchor = new GPoint(9, 34);
  baseIcon.infoWindowAnchor = new GPoint(9, 2);
  baseIcon.image = this.icon_image;
  
	/*this will need a work on when we get the latlong coordinates*/
  var title = jQuery(this.obj.obj).find('.ptitle').html();
  var latlng = new GLatLng(this.obj.latlng[0], this.obj.latlng[1]);
  MARKERS[this.pos] = new GMarker(latlng, {icon:baseIcon, title:title});
  MARKERS[this.pos].bindInfoWindowHtml("<div class='bubble'>"+jQuery(this.obj.obj).find('.bubble').html()+"</div>");
  var pos = this.pos;
  GEvent.addListener(MARKERS[this.pos], 'click', function(overlay, latlang) {
		activemarker(pos);
	});
  this.map.addOverlay(MARKERS[this.pos]);
  mapcenter();
  
};
gmarker.prototype.search = function(){
  var marker=this;
  var search = new google.search.LocalSearch();
  search.setSearchCompleteCallback(null, function(){
    var found = search.results[0];
    marker.obj.latlng = found.lat+","+found.lng;
    marker.draw();
  });
  search.execute(this.obj.location+",UK");
}


