// A function to create the marker and set up the event window
      function createMarker(point,name,html,author) {
        var marker = new GMarker(point, {icon:iconRed});
		
		
		GEvent.addListener(marker,'mouseover',function(){
	marker.setImage(preload[2].src);
	});

		GEvent.addListener(marker,'mouseout',function(){
	marker.setImage(preload[0].src);
	});
		
        GEvent.addListener(marker, "click", function() {
			theCenter=map.getCenter();
          marker.openInfoWindowHtml(html);
        });
  	GEvent.addListener(marker, 'infowindowclose',
  		function(){
			map.setCenter(theCenter);
  			});	
        gmarkers[i] = marker;
        htmls[i] = html;
        side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '<\/a><br />';
		side_bar_html += '<div class="halfLine">&nbsp;</div>';
        i++;
        return marker;
      }
	  
      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        gmarkers[i].openInfoWindowHtml(htmls[i]);
		theCenter=map.getCenter();
      }
	  
    //<![CDATA[

    if (GBrowserIsCompatible()) {
      var side_bar_html = "";
	  var paging_html = "";
      var gmarkers = [];
      var htmls = [];

      // create the map
      var map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng( 43.907787,-79.359741), 10);
	map.addMapType(G_SATELLITE_3D_MAP);

	
function getStatePoint(address,xoom) {
	address=address+',US';
	var geodog = new GClientGeocoder();
  geodog.getLatLng(
    address,
    function(point) {
        map.setCenter(point, xoom);
      
    }
  );
}	
	
	
      // A function to read the data
      function getStories(subSort,sortBy,startLocal,increment,centerLat,centerLng,zoomDog) {
		  if(subSort=='none'){
			subSort='USA';
			xoom=3;
		  }
		  else{
			xoom=6;
		  }
		  getStatePoint(subSort,xoom);
		  document.getElementById("message").innerHTML = "";
		  if(centerLat==null){
			centerLat=43.907787;
		  }
		  if(centerLng==null){
			centerLng=-79.359741;
		  }
		  if(zoomDog==null){
			zoomDog=5;
		  }
        var point = new GLatLng(centerLat,centerLng);
        map.setCenter(point,zoomDog);
		  end = startLocal + increment;
		window.subSort=subSort;
		window.sortBy=sortBy;
		
		//change this
		//var sortBy='state';
		
		
        var url="sort.php?category="+subSort+"&sortBy="+sortBy+"&start="+startLocal+"&increment="+increment;
        var request = GXmlHttp.create();
        request.open("GET", url, 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");
            // hide the info window, otherwise it still stays open where the removed marker used to be
            map.getInfoWindow().hide();
            
            map.clearOverlays();
            
            // empty the array
            gmarkers = [];

            // reset the side_bar
            side_bar_html="";
			
			window.sortingBy=sortBy;
			window.varGenre=subSort;
			
            for (var i = 0; i < markers.length; i++) {
              // obtain the attribues of each marker
				 window.countTotal = parseFloat(markers[i].getAttribute("count"));
              var lat = parseFloat(markers[i].getAttribute("lat"));
              var lng = parseFloat(markers[i].getAttribute("lng"));
              var point = new GLatLng(lat,lng);
              
              var label = markers[i].getAttribute("label");
			  var author = markers[i].getAttribute("author");
			  var authorID = markers[i].getAttribute("authorID");
			  
			  var views = markers[i].getAttribute("views");
			  var votes = markers[i].getAttribute("votes");
			  var genre = markers[i].getAttribute("genre");
			  var rating = markers[i].getAttribute("rating");
			  var city = markers[i].getAttribute("city");
			  var country = markers[i].getAttribute("country");
			  var html = 'Feed:&nbsp;'+markers[i].getAttribute("html")+'</span><br />Views:&nbsp;'+views+'<br />City:&nbsp;'+city+'<br />Format:&nbsp;'+genre+'</span>';
              // create the marker
              var marker = createMarker(point,label,"<span style='width:400px;display:block;'>"+html+"</span>",author);
              map.addOverlay(marker);
            }

            // put the assembled side_bar_html contents into the side_bar div
			if(countTotal)
				startLocal=1;
			if(countTotal<end)
				end=countTotal;
			window.markersCount=markers.length;
			if(markers.length==0){
			document.getElementById("feeds").innerHTML = 'No Feeds Yet';
			}
			else{
            document.getElementById("feeds").innerHTML = side_bar_html;
			}
			if(pageFlag!=1){
			//document.getElementById("feeds").innerHTML = startLocal+'&nbsp;- '+end+'&nbsp;of&nbsp;'+countTotal;
	
		  window.tempStart = 1;
		 if ( countTotal )
		 {
		 tempStart = startLocal+1;
		 }
		 nextStart = tempStart+increment;		
		 if ( nextStart <= (countTotal) )
		 {
			
			//document.getElementById("feeds").innerHTML += '<a onclick="pageForward();">&nbsp;&gt;&gt; </a>&nbsp;&nbsp;&nbsp;&nbsp;<a onclick="skipToEnd();">&gt;|&nbsp;End</a>';
		 }}
			
	
          }
        }

        request.send(null);
      }
      
      // When initially loaded, do this
      getStories("none","views",0,10);
      //alert(start);
	  window.boner=start;
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

    //]]>

var imageSource = [
"http://www.google.com/intl/en_ALL/mapfiles/marker.png",//0 default
"http://esa.ilmari.googlepages.com/markeryellow.png",//1 yellow
"http://www.google.com/uds/samples/places/temp_marker.png",//2 turquoise
"http://www.google.com/intl/en_ALL/mapfiles/iw1.png"//Info window
]
var preload = [];
for(var i=0;i<imageSource.length;i++){
preload.push(new Image);
preload[i].src = imageSource[i];
}
	
    var iconRed = new GIcon(); 
    iconRed.image = "images/markerred.png";
    //iconRed.shadow = 'images/markerred.png';
    iconRed.iconSize = new GSize(16, 26);
    iconRed.shadowSize = new GSize(22, 20);
    iconRed.iconAnchor = new GPoint(6, 20);
    iconRed.infoWindowAnchor = new GPoint(5, 1);

    var iconYellow = new GIcon(); 
    iconYellow.image = "images/markeryellow.png";
    //iconYellow.shadow = 'images/markeryellow.png';
    iconYellow.iconSize = new GSize(16, 26);
    iconYellow.shadowSize = new GSize(22, 20);
    iconYellow.iconAnchor = new GPoint(6, 20);
    iconYellow.infoWindowAnchor = new GPoint(5, 1);
   
    var iconTurquoise = new GIcon(); 
    iconTurquoise.image = "images/markerturquoise.png";
    //iconTurquoise.shadow = 'images/markerturquoise.png';
    iconTurquoise.iconSize = new GSize(16, 26);
    iconTurquoise.shadowSize = new GSize(22, 20);
    iconTurquoise.iconAnchor = new GPoint(6, 20);
    iconTurquoise.infoWindowAnchor = new GPoint(5, 1);
	
  function addMarkerRed(latitude,longitude,description)
  {
  	var marker = new GMarker(new GLatLng(latitude,longitude), {icon:iconRed});

		GEvent.addListener(marker,'mouseover',function(){
	marker.setImage(preload[2].src);
	});

  	GEvent.addListener(marker,'mouseout',function(){
	marker.setImage(preload[0].src);
	});
  	GEvent.addListener(marker, 'click',
  		function(){
  			marker.openInfoWindowHtml(description);
  			});
		
  		//map.addOverlay(marker);
  		//return marker;
  	}
  function highlightButton(button){
	  document.getElementById("rating").className="btn";
	  document.getElementById("lowrating").className="btn";
	  document.getElementById("mostviewed").className="btn";
	  document.getElementById("newest").className="btn";
	  document.getElementById("comedy").className="btn";
	  document.getElementById("horror").className="btn";
	  document.getElementById("food").className="btn";
	  document.getElementById("people").className="btn";
	  document.getElementById("adventure").className="btn";
	  document.getElementById("nature").className="btn";
	  document.getElementById("enraged").className="btn";
	  document.getElementById("poetic").className="btn";
	  document.getElementById("topical").className="btn";
	  document.getElementById("science").className="btn";
	  document.getElementById("place").className="btn";
	button.className = "btnClicked";
  }

  
      var geo;
    var reasons=[];

  
       // ====== Create a Client Geocoder ======
      geo = new GClientGeocoder(); 

      // ====== Array for decoding the failure codes ======
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
    

      // ====== Plot a marker after positive reponse to "did you mean" ======
      function place(lat,lng) {
        var point = new GLatLng(lat,lng);
        map.setCenter(point,14); 
        map.addOverlay(new GMarker(point));
        document.getElementById("message").innerHTML = "";
      }

      // ====== Geocoding ======
      function showAddress(a,b,c,d) {
        var searchCity = document.getElementById("searchCity").value;
        // ====== Perform the Geocoding ======        
        geo.getLocations(searchCity, function (result)
          {
            map.clearOverlays(); 
            if (result.Status.code == G_GEO_SUCCESS) {
				if(result.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality)
					returnedCity=result.Placemark[0].AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
				else
					returnedCity='unknown';
              // ===== If there was more than one result, "ask did you mean" on them all =====
              if (result.Placemark.length > 1) { 
                document.getElementById("message").innerHTML = "Did you mean:";
                // Loop through the results
                for (var i=0; i<result.Placemark.length; i++) {
                  var p = result.Placemark[i].Point.coordinates; //use p[1],p[0] as lat,lng
					
                  document.getElementById("message").innerHTML += "<br>"+(i+1)+": <a href='javascript:getStories(\""+a+"\",\""+b+"\",\""+c+"\",\""+d+"\","+p[1]+","+p[0]+",13)'>"+ result.Placemark[i].address+"<\/a>";

                }
              }
              // ===== If there was a single marker =====
              else {
                document.getElementById("message").innerHTML = "";
				var p = result.Placemark[0].Point.coordinates; //use p[1],p[0] as lat,lng
				getStories(returnedCity,b,c,d,p[1],p[0],13);
              }
            }
            // ====== Decode the error status ======
            else {
              var reason="Code "+result.Status.code;
              if (reasons[result.Status.code]) {
                reason = reasons[result.Status.code]
              } 
              alert('Could not find "'+searchCity+ '" ' + reason);
            }
          }
        );
      }