//  dev.dorf.com.au    ABQIAAAAkO2grYBoJ3eoLdcH9Kgk4xTUbFXu9U6tX-5faZHVzTs2Jn3qpBQ3aUEKKhszDTzwD_YDm-QZYAe5-Q
// dorf.com.au     ABQIAAAAkO2grYBoJ3eoLdcH9Kgk4xTUbFXu9U6tX-5faZHVzTs2Jn3qpBQ3aUEKKhszDTzwD_YDm-QZYAe5-Q
	var map;
    var geocoder;

    function load() {
      if (GBrowserIsCompatible()) {
        geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById('map'));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(-29.274398,133.775136), 4);
      }
    }

   function searchLocations() {
	if(document.getElementById('addressInput').value==""){
		alert("Please enter Suburb or Postcode");
		return false;
	}
	if(document.getElementById('stateSelect').value==""){
		alert('Please select State.');
		return false;
	}
     var address = document.getElementById('addressInput').value + "+" + document.getElementById('stateSelect').value + "+AU";
     geocoder.getLatLng(address, function(latlng) {
       if (!latlng) {
         alert(address + ' not found');
       } else {
		var radius = document.getElementById('radiusSelect').value;
         searchLocationsNear(latlng);
       }
     });
   }

   function searchLocationsNear(center) {
     var radius = document.getElementById('radiusSelect').value;
	 var storename = document.getElementById('storename').value;
     var searchUrl = '/StoreLocatorXML.asp?storename=' + storename + '&lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
     GDownloadUrl(searchUrl, function(data) {
       var xml = GXml.parse(data);
       var markers = xml.documentElement.getElementsByTagName('marker');
       map.clearOverlays();

       var sidebar = document.getElementById('sidebar');
       sidebar.innerHTML = '<a href="javascript:openPrintFriendlyView()" style="width:100%;text-align:left;display:block;"><img src="/images/btn_printstorelocations.gif" ></a><br />';
       if (markers.length == 0) {
         sidebar.innerHTML = "<p style='margin:10px;'>Sorry, no stores were found within this radius, please increase your radius search.<br />If you still cannot find a store near you, please <a href='/contact-us'>contact us</a><p>";
// 
//

		var address = document.getElementById('addressInput').value + "+" + document.getElementById('stateSelect').value + "+AU";
		geocoder.getLatLng(address, function(latlng) {
			var marker = new GMarker(latlng);
			map.addOverlay(marker);
			map.setCenter(latlng, 10);
			createCircle(latlng, radius*1000);
		});

//         map.setCenter(new GLatLng(-29.274398,133.775136), 4);
         return;
       }

       var bounds = new GLatLngBounds();
       for (var i = 0; i < markers.length; i++) {
         var phone = markers[i].getAttribute('phone');
         var fax = markers[i].getAttribute('fax');
         var website = markers[i].getAttribute('website');
         var name = markers[i].getAttribute('name');
         var address = markers[i].getAttribute('address');
         var distance = parseFloat(markers[i].getAttribute('distance'));
         var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                 parseFloat(markers[i].getAttribute('lng')));
         
         var marker = createMarker(point, name, address, website, phone, fax);
         map.addOverlay(marker);
         var sidebarEntry = createSidebarEntry(marker, name, address, distance, website);
         sidebar.appendChild(sidebarEntry);
         bounds.extend(point);
       }
	   //alert(bounds.getCenter());
       map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	   //createCircle(bounds.getCenter(), radius*1000);
     });
   }

    function createMarker(point, name, address, website,phone,fax) {
      var marker = new GMarker(point);
      var html = '<b>' + name + '</b> <br/>' + address+ '<br />phone : '+phone+'<br />fax : '+fax+'<br/><a href="'+website+'" target=_blank>' + website +'</a>';
      GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
      });
      return marker;
    }

    function createSidebarEntry(marker, name, address, distance, website) {
      var div = document.createElement('div');
      var html = '<b>' + name + '</b> (' + distance.toFixed(1) + 'km)<br/>' + address+ '<br/><a href="'+website+'" target=_blank>' + website +'</a>';
      div.innerHTML = html;
      div.style.cursor = 'pointer';
      div.style.marginBottom = '5px'; 
      GEvent.addDomListener(div, 'click', function() {
        GEvent.trigger(marker, 'click');
      });
/*
      GEvent.addDomListener(div, 'mouseover', function() {
        div.style.backgroundColor = '#eee';
      });
      GEvent.addDomListener(div, 'mouseout', function() {
        div.style.backgroundColor = '#fff';
      });
*/
      return div;
    }

























  var queryCenterOptions = new Object();
  var queryLineOptions = new Object();
 
queryCenterOptions.icon = new GIcon();
queryCenterOptions.icon.image = "http://jfno.net/images/centerArrow.png";
queryCenterOptions.icon.iconSize = new GSize(20,20);
queryCenterOptions.icon.shadowSize = new GSize(0, 0);
queryCenterOptions.icon.iconAnchor = new GPoint(10, 10);
queryCenterOptions.draggable = true;
queryCenterOptions.bouncy = false;
 
queryLineOptions.icon = new GIcon();
queryLineOptions.icon.image = "http://jfno.net/images/resizeArrow.png";
queryLineOptions.icon.iconSize = new GSize(25,20);
queryLineOptions.icon.shadowSize = new GSize(0, 0);
queryLineOptions.icon.iconAnchor = new GPoint(12, 10);
queryLineOptions.draggable = true;
queryLineOptions.bouncy = false;

function createCircle(point, radius) {
  singleClick = false;
  geoQuery = new GeoQuery();
  geoQuery.initializeCircle(radius, point, map);
//  myQueryControl.addGeoQuery(geoQuery);
  geoQuery.render();
}
 
function destination(orig, hdng, dist) {
  var R = 6371; // earth's mean radius in km
  var oX, oY;
  var x, y;
  var d = dist/R;  // d = angular distance covered on earth's surface
  hdng = hdng * Math.PI / 180; // degrees to radians
  oX = orig.x * Math.PI / 180;
  oY = orig.y * Math.PI / 180;
 
  y = Math.asin( Math.sin(oY)*Math.cos(d) + Math.cos(oY)*Math.sin(d)*Math.cos(hdng) );
  x = oX + Math.atan2(Math.sin(hdng)*Math.sin(d)*Math.cos(oY), Math.cos(d)-Math.sin(oY)*Math.sin(y));
 
  y = y * 180 / Math.PI;
  x = x * 180 / Math.PI;
  return new GLatLng(y, x);
}
 
function distance(point1, point2) {
  var R = 6371; // earth's mean radius in km
  var lon1 = point1.lng()* Math.PI / 180;
  var lat1 = point1.lat() * Math.PI / 180;
  var lon2 = point2.lng() * Math.PI / 180;
  var lat2 = point2.lat() * Math.PI / 180;
 
  var deltaLat = lat1 - lat2
  var deltaLon = lon1 - lon2
 
  var step1 = Math.pow(Math.sin(deltaLat/2), 2) + Math.cos(lat2) * Math.cos(lat1) * Math.pow(Math.sin(deltaLon/2), 2);
  var step2 = 2 * Math.atan2(Math.sqrt(step1), Math.sqrt(1 - step1));
  return step2 * R;
}
 
function GeoQuery() {
 
}

GeoQuery.prototype.CIRCLE='circle';
GeoQuery.prototype.COLORS=["#0000ff"];
var COLORI=0;
 
GeoQuery.prototype = new GeoQuery();
GeoQuery.prototype._map;
GeoQuery.prototype._type;
GeoQuery.prototype._radius;
GeoQuery.prototype._dragHandle;
GeoQuery.prototype._centerHandle;
GeoQuery.prototype._polyline;
GeoQuery.prototype._color ;
GeoQuery.prototype._control;
GeoQuery.prototype._points;
GeoQuery.prototype._dragHandlePosition;
GeoQuery.prototype._centerHandlePosition;
 
 
GeoQuery.prototype.initializeCircle = function(radius, point, map) {
    this._type = this.CIRCLE;
    this._radius = radius;
    this._map = map;
    this._dragHandlePosition = destination(point, 90, this._radius/1000);
    this._dragHandle = new GMarker(this._dragHandlePosition, queryLineOptions);
    this._centerHandlePosition = point;
    this._centerHandle = new GMarker(this._centerHandlePosition, queryCenterOptions);
    this._color = this.COLORS[COLORI++ % 3];
    //map.addOverlay(this._dragHandle);
    //map.addOverlay(this._centerHandle);
    var myObject = this;
    //GEvent.addListener (this._dragHandle, "dragend", function() {myObject.updateCircle(1);});
    //GEvent.addListener (this._dragHandle, "drag", function() {myObject.updateCircle(1);});
    //GEvent.addListener(this._centerHandle, "dragend", function() {myObject.updateCircle(2);});
    //GEvent.addListener(this._centerHandle, "drag", function() {myObject.updateCircle(2);});
}
 
GeoQuery.prototype.updateCircle = function (type) {
    this._map.removeOverlay(this._polyline);
    if (type==1) {
      this._dragHandlePosition = this._dragHandle.getPoint();
      this._radius = distance(this._centerHandlePosition, this._dragHandlePosition) * 1000;
      this.render();
    } else {
      this._centerHandlePosition = this._centerHandle.getPoint();
      this.render();
      this._dragHandle.setPoint(this.getEast());
    }
}
 
GeoQuery.prototype.render = function() {
  if (this._type == this.CIRCLE) {
    this._points = [];
    var distance = this._radius/1000;
    for (i = 0; i < 72; i++) {
      this._points.push(destination(this._centerHandlePosition, i * 360/72, distance) );
    }
    this._points.push(destination(this._centerHandlePosition, 0, distance) );
    //this._polyline = new GPolyline(this._points, this._color, 6);
    this._polyline = new GPolygon(this._points, this._color, 1, 1, this._color, 0.2);
    this._map.addOverlay(this._polyline)
    //this._control.render();
  }
}
 
GeoQuery.prototype.remove = function() {
  this._map.removeOverlay(this._polyline);
  this._map.removeOverlay(this._dragHandle);
  this._map.removeOverlay(this._centerHandle);
}
 
GeoQuery.prototype.getRadius = function() {
    return this._radius;
}
 
GeoQuery.prototype.getHTML = function() {
  return "<span><font color='"+ this._color + "''>" + this.getDistHtml() + "</font></span>";
}
 
GeoQuery.prototype.getDistHtml = function() {
  result = "<img src='http://jfno.net/images/close.gif' onClick='myQueryControl.remove(" + this._control.getIndex(this) + ");'/>Radius ";
  if (metric) {
    if (this._radius < 1000) {
      result += "in meters : " + this._radius.toFixed(1);
    } else {
      result += "in kilometers : " + (this._radius / 1000).toFixed(1);
    }
  } else {
    var radius = this._radius * 3.2808399;
    if (radius < 5280) {
      result += "in feet : " + radius.toFixed(1);
    } else {
      result += "in miles : " + (radius / 5280).toFixed(1);
    }
  }
  return result;   
}
 
GeoQuery.prototype.getNorth = function() {
  return this._points[0];
}
 
GeoQuery.prototype.getSouth = function() {
  return this._points[(72/2)];
}
 
GeoQuery.prototype.getEast = function() {
  return this._points[(72/4)];
}
 
GeoQuery.prototype.getWest = function() {
  return this._points[(72/4*3)];
}
