var map;
var polygones = new Object();
var colors    = new Object();
var countries = new Object();
var polylines = new Object();
var country ;
var rules= {
	'.country input' : function(el) {
		el.onchange = function() {
		 	var id = el.id.split('_');
			var countryid = id[1];
			new Ajax.Request('./kml.class.php?countryid=' + countryid + '&checked=' + el.checked, {
 	 				method: 'post',
  					onSuccess: function(transport) {
  						var res = eval(transport.responseText);
    					console.log(res);
    					var bounds = polygons[countryid].getBounds();
						setTimeout(function() {
						map.setZoom(map.getBoundsZoomLevel(bounds)-1); 
						map.setCenter(bounds.getCenter()); 
						},1000);
				}
					});
					
					
					
					
		  }
		},
		'#all' : function(el) {
			el.onclick = function() {
//				$$('.country input').each(function(land){land.checked='true';});
				new Ajax.Request('./kml.class.php?getall=_', {
 	 				method: 'get',
 	 				onLoading : function() {Element.show('rad');},
  					onSuccess: function(transport) {
  						$('map').style.width = '575px';
  						setTimeout(function(){Effect.Fade('rad')},2000);
  						Element.hide('db');
  						eval(transport.responseText);
  							
  					}
  				});
			}
		}
};

Event.observe(window, 'load', init_app);
Event.observe(window, 'unload', GUnload);

function init_app(event) {
  Behaviour.register(rules);
  Behaviour.apply(rules);
  
  map = new GMap2($("map"));
  GEvent.addListener(map,"click", function(overlay,latlng) {     
        if (overlay) {
       		$('info').innerHTML  = countries[country];
			var bounds = polygons[country].getBounds();
			map.setZoom(map.getBoundsZoomLevel(bounds)); 
			map.setCenter(bounds.getCenter()); 
		}
   });
  map.addControl(new GMenuMapTypeControl(true,false));
  map.setMapType(G_HYBRID_MAP);
  map.addControl(new YSliderControl());
  map.setCenter(new GLatLng(0.507563, -10.797715), 2);
}


//// END of local //////////////
// === A method for testing if a point is inside a polygon
// === Returns true if poly contains point
// === Algorithm shamelessly stolen from http://alienryderflex.com/polygon/ 
GPolygon.prototype.Contains = function(point) {
var j=0;
var oddNodes = false;
var x = point.lng();
var y = point.lat();
for (var i=0; i < this.getVertexCount(); i++) {
  j++;
  if (j == this.getVertexCount()) {j = 0;}
  if (((this.getVertex(i).lat() < y) && (this.getVertex(j).lat() >= y))
  || ((this.getVertex(j).lat() < y) && (this.getVertex(i).lat() >= y))) {
	if ( this.getVertex(i).lng() + (y - this.getVertex(i).lat())
	/  (this.getVertex(j).lat()-this.getVertex(i).lat())
	*  (this.getVertex(j).lng() - this.getVertex(i).lng())<x ) {
	  oddNodes = !oddNodes
	}
  }
}
return oddNodes;
}


// == Some global variables ==
var YSLIDERLENGTH = 55;       // maximum length that the knob can move (slide height minus knob height)
var MAXZOOM = 15

// == Create a Custom GControl ==
function YSliderControl() { }
YSliderControl.prototype = new GControl();

// == This function positions the slider to match the specified zoom level ==
YSliderControl.prototype.setSlider = function(zoom) {
var top = Math.round((YSLIDERLENGTH/MAXZOOM*zoom));
this.slide.top = top;
this.knob.style.top = top+"px";
//GLog.write("Map was zoomed to:"+zoom+" new Knob position:"+top);
}

// == This function reads the slider and sets the zoom level ==
YSliderControl.prototype.setZoom = function() {
var z=Math.round(this.slide.top*MAXZOOM/YSLIDERLENGTH);
this.map.setZoom(z);
//GLog.write("New knob position:"+this.slide.top+" new zoom: "+z);
}


// == This gets called bu the API when addControl(new YSlider()) is used ==
YSliderControl.prototype.initialize = function(map) {
// obtain Function Closure on a reference to "this"
var that=this;
// store a reference to the map so that we can call setZoom() on it
this.map = map;

// Is this MSIE, if so we need to use AlphaImageLoader
var agent = navigator.userAgent.toLowerCase();
if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){this.ie = true} else {this.ie = false}

// create the background graphic as a <div> containing an image
var container = document.createElement("div");
container.style.width="19px";
container.style.height="74px";

// Handle transparent PNG files in MSIE
if (this.ie) {
  var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='yslide.png', sizingMethod='scale');";
  container.innerHTML = '<div style="height:74px; width:19px; ' +loader+ '" ></div>';
} else {
  container.innerHTML = '<img src="yslide.png"  width=19 height=74 >';
}

// create the knob as a GDraggableObject
// Handle transparent PNG files in MSIE
if (this.ie) {
  var loader = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='yknob.png', sizingMethod='scale');";
  this.knob = document.createElement("div"); 
  this.knob.style.height="19px";
  this.knob.style.width="19px";
  this.knob.style.filter=loader;
} else {
  this.knob = document.createElement("img"); 
  this.knob.src = "yknob.png";
  this.knob.height = "19";
  this.knob.width = "19";
}
container.appendChild(this.knob);
this.slide=new GDraggableObject(this.knob, {container:container});

// attach the control to the map
map.getContainer().appendChild(container);

// Listen for other things changing the zoom level and move the slider
GEvent.addListener(map, "zoomend", function(a,b) {that.setSlider(b)});

// Listen for the slider being moved and set the zoom level
GEvent.addListener(this.slide, "dragend", function() {that.setZoom()});

return container;
}

// == Set the default position for the control ==
YSliderControl.prototype.getDefaultPosition = function() {
return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}



