// action layer
var selectedPoint = null;

function openSearch(province){
	if($('searchCtr').className == "closed"){
		$('searchCtr').className = "open";
		$('centerCol').className = "screened";
	}
		if(province != ''){
			load(province);
		}
	}

function closeSearch(){
		
		$('searchCtr').className = "closed";
		$('centerCol').className = "twoCol";		

	}

function toggleHelp(){
		
		$('help').toggle();
		
		if($('btn_help').hasClassName('show')){
			$('btn_help').className = "hide";
		}else{
			$('btn_help').className = "show";
			$('btn_help').setAttribute('title', 'hide help');
		}
		
		return false;	

	}



	var isDevString = 'false';
 	var map;
    var geocoder;
	var side_bar_html = "";
    
      // arrays to hold copies of the markers and html used by the side_bar
      // because the function closure trick doesnt work there
      var gmarkers = [];
      var gmarkerInfos = [];
      var htmls = [];
      var i = 0;




function load(province, isDev) {
	isDevString = (isDev) ? 'true' : 'false';
		if (GBrowserIsCompatible()) {
      map = new GMap2(document.getElementById("map"));
			map.addControl(new GSmallMapControl());
			var center;
			switch(province){
				case('bc'):
					center = new GLatLng(54, -124);
					break;
				case('ab'):
					center = new GLatLng(54, -115);
					break;
				case('sk'):
					center = new GLatLng(54, -105);
					break;
				case('mb'):
					center = new GLatLng(54, -98);
					break;
				case('qc'):
					center = new GLatLng(51, -72);
					break;
			}
      map.setCenter(center, 4);
     	t_marker = new GMarker(center, {draggable: true});
			

			GEvent.addListener(t_marker, "click", function() {
					
					var helptext = "<div id='help'>" + $('helptext').innerHTML + "</div>"									   
					t_marker.openInfoWindowHtml(helptext);
			 });

			var actionURL = document.searchForm.action;

			GEvent.addListener(t_marker, "dragend", function() {
				 var newlat = t_marker.getPoint().lat();
				 var newlng = t_marker.getPoint().lng();
			
			
			rURL = actionURL + "?q=" + newlat + "," + newlng;
			//pop embed in new window or regular style
			if(location.href == "http://usedoilrecycling.com/dropoffembed.php"){
				newwindow = window.open( rURL,'results');
				if (window.focus){
					newwindow.focus();
					}
			}else{
				location.href = rURL;
			}
				

			}); 			
			
			map.addOverlay(t_marker);
			
			geocoder = new GClientGeocoder();
		

			GEvent.trigger(t_marker, "click");


		}
    }

    // addAddressToMap() is called when the geocoder returns an
    // answer.  
function addAddressToMap(response) {
      //clear out all markers
			map.clearOverlays();

      if (!response || response.Status.code != 200) {
		  
		  var alerttext = (language == "en") ? "Sorry, we couldn't find that location" : "desoles, nous pouvons pas trouve l'endroit.";
        alert(alerttext);
		
		
      } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);

				selectedPoint = point;

        marker = new GMarker(point, {draggable: true});

				GEvent.addListener(marker, "dragend", function() {
					 var newlat = marker.getPoint().lat()
					 var newlng = marker.getPoint().lng()
					 map.setCenter(new GLatLng(newlat,newlng), 12);
					//$('q').value = newlat + ', ' + newlng;
					createXMLmarksByProximity(6, true);
  			});

        map.addOverlay(marker);
				map.setCenter(point, 11);

				//var newlat = marker.getPoint().lat();
				//var newlng = marker.getPoint().lng();
				createXMLmarksByProximity(6, false);
      }
    }

    // showLocation() is called when you click on the Search button
    // in the form.  It geocodes the address entered into the form
    // and adds a marker to the map at that location.
    function showLocation() {
      var address = $('q').value;
			if(address != ""){
 				geocoder.getLocations(address, addAddressToMap);
			}
     
    }

   // findLocation() is used to enter the sample addresses into the form.
    function findLocation(address) {
      $('q').value = address;
      showLocation();
    }	

      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        	gmarkers[i].openInfoWindowHtml(gmarkerInfos[i], {maxWidth:75});
					var newlat = gmarkers[i].getPoint().lat()
					var newlng = gmarkers[i].getPoint().lng()
					map.setCenter(new GLatLng(newlat,newlng), 16);
  				//map.panTo(new GLatLng(newlat,newlng));
					//gmarkers[i].showMapBlowup(15, "");	
      }



	
			function createNamedMarker(point, name, address, tel, info, collects) {

      var blueIcon = new GIcon();
          blueIcon.iconSize=new GSize(21,33);
					blueIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
          blueIcon.shadowSize = new GSize(37, 34);
          blueIcon.iconAnchor=new GPoint(10,33);
          blueIcon.infoWindowAnchor=new GPoint(11,0);
					blueIcon.infoShadowAnchor = new GPoint(16, 20);


			  var icon = new GIcon(blueIcon, "/_images/common/pins/b_" + (i+1) + ".png", 
				null, "");
			  
			  var locations = new GMarker(point, icon);
				gmarkers[i] = locations;
        htmls[i] = name;	
				var divnum = i;
			  
				//build info window html code
				var daddr = address.replace(/(<([^>]+)>)/ig,", ");
				var saddr = $('q').getValue(); 
				
				var theword = (language == "en") ? "Directions" : "Itineraires";
				var mapslink = '<a class="mapslink" href="http://maps.google.ca/maps?ie=UTF8&hl=' + language + '&saddr=' + saddr + '&daddr=' + daddr + '">' + theword + '</a>';
				var infowindow = '<div class="infowindow"><b>' + name + '</b><p>' + mapslink + '</p></div>';
				gmarkerInfos[i] = infowindow;

				GEvent.addListener(locations, "click", function() {
						locations.openInfoWindowHtml(infowindow, {maxWidth:75});
						openOne(divnum);					
			  });
				side_bar_html += '<div class="loc Ctr" onclick="myclick(' + i + ');openOne(' + i + ');">';
				side_bar_html += '<div class="info"><span>' + (i+1) + '</span><h3>' + name + '</h3>';
				side_bar_html += '<address>' + address + '<br />' + mapslink +'<br />' + tel + '</address><p>' + info + '</p></div>';
				side_bar_html += '<div class="collects">' + collects +'</div><div class="cl"></div></div>';
				i++;
			  return locations;
			}


//read XML file and display markers
function createXMLmarksByProximity(length, dragged){
			
			//clear the results html file
			side_bar_html = "";
			$('results').innerHTML = side_bar_html;

			//find out what the limits value is set to on the results page
			length = $('limitsddl').getValue();

			//clear arrays and pointer
      gmarkers.length = 0;
      htmls.length = 0;
      i = 0;

			//clear out the points that are there
			map.clearOverlays();

			//create a bounds object
			var bounds = new GLatLngBounds();
			
			//put the location point back in the middle

			if(selectedPoint != null && !dragged){
				c_point = selectedPoint;
			}else{
				c_point = map.getCenter();
			}
			c_marker = new GMarker(c_point, {draggable: true});

				GEvent.addListener(c_marker, "dragend", function() {
					 var newlat = c_marker.getPoint().lat()
					 var newlng = c_marker.getPoint().lng()
					 map.setCenter(new GLatLng(newlat,newlng), 12);
					//$('q').value = newlat + ', ' + newlng;
					createXMLmarksByProximity(6, true);
  			});
        map.addOverlay(c_marker);

			//add location to bounds object
			bounds.extend(c_point);

			//build query for locations
			var newlat = c_marker.getPoint().lat()
			var newlng = c_marker.getPoint().lng()
			//$('q').value = newlat + ', ' + newlng;
			var query = "/_Posch/getlocationresult.php?lat=" + newlat + "&lng=" + newlng + "&return=" + length + "&isdev=" + isDevString;
		 // Read the data from the database
      var request = GXmlHttp.create();
      request.open("GET", query, true);
      
			request.onreadystatechange = function() {
        if (request.readyState == 4) {
          var xmlDoc = request.responseXML;
          // obtain the array of markers and loop through it
          var markers = xmlDoc.documentElement.getElementsByTagName("marker");
          
          for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(lat,lng);
            
						//add point to bounds object
						bounds.extend(point);

						var name = GXml.value(markers[i].getElementsByTagName("name")[0]);
						
						var address = GXml.value(markers[i].getElementsByTagName("address")[0]);
						var tel = GXml.value(markers[i].getElementsByTagName("telephone")[0]);
						var info = GXml.value(markers[i].getElementsByTagName("hours")[0]);
						

						//parse the data for what the location collects
						var colTag = markers[i].getElementsByTagName("collects")[0];
						var oil = colTag.getAttribute('oil');
						var filters = colTag.getAttribute('filters');
						var containers = colTag.getAttribute('containers');
						
						if(language == "en"){
							var collects = '<div title="collects oil" class="yesno '+oil+'"></div>';
							collects += '<div title="collects filters" class="yesno '+filters+'"></div>';
							collects += '<div title="collects containers" class="yesno '+containers+'"></div>';
						}else{
							var collects = '<div title="r&#233;cup&#232;re les huiles" class="yesno '+oil+'"></div>';
							collects += '<div title="r&#233;cup&#232;re les filtres" class="yesno '+filters+'"></div>';
							collects += '<div title="r&#233;cup&#232;re les contenants" class="yesno '+containers+'"></div>';
						}


            // create the marker
            var marker = createNamedMarker(point,name,address,tel,info,collects);
            map.addOverlay(marker);
          }

        }
				//set zoom and center for bounds
				map.setZoom(map.getBoundsZoomLevel(bounds));
				map.setCenter(bounds.getCenter());
				
				
				//hide the default column
				$('defaultCol').hide();
				// put the assembled side_bar_html contents into the side_bar div
				$('results').innerHTML = side_bar_html;
      }

      request.send(null);

}


function closeAll(){
	var divs = document.getElementsByClassName('on',$('results'));
	for(var i=0;i<divs.length;i++){
		divs[i].removeClassName('on');
	}
}


function openOne(j){
	closeAll();
	var divs = document.getElementsByClassName('Ctr', $('results'));
	divs[j].addClassName('on');

}

