/* 
 * map functions.
 */
 
 var link ="http://www.agroclimate.org/forecasts/LGMI/JPGraph.php?";
var map;
// === Default values to use if there is no cookie ===
var lat = 32.342841356393016;
var lng = -82.28759765625;
var zoom = 6;
var maptype = 3;
var countyPoints = null;
var vectMarkers = [];
var option;

// === Some cookie parameters ===
var cookiename = "mapinfo";  // name for this cookie
var expiredays = 7;          // number of days before cookie expiry

if (GBrowserIsCompatible() ){
    
    function lmap(){
        if(document.getElementById("map")){
            // === Look for the cookie ===
//            if (document.cookie.length>0) {
//                cookieStart = document.cookie.indexOf(cookiename + "=");
//                if (cookieStart!=-1) {
//                    cookieStart += cookiename.length+1; 
//                    cookieEnd=document.cookie.indexOf(";",cookieStart);
//                    if (cookieEnd==-1) {
//                        cookieEnd=document.cookie.length;
//                    }
//                    cookietext = document.cookie.substring(cookieStart,cookieEnd);
//                    // == split the cookie text and create the variables ==
//                    bits = cookietext.split("|");
//                    lat = parseFloat(bits[0]);
//                    lng = parseFloat(bits[1]);
//                    zoom = parseInt(bits[2]);
//                    maptype = parseInt(bits[3]);
//                } 
//            }
            //alert(lat+" "+lng+" "+zoom+" "+maptype);
            // === Display the map ===
            map = new GMap2(document.getElementById("map"));  			
            map.setCenter(new GLatLng(lat,lng),zoom);
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            
            // === Set up the map types exactly like Google Maps ===
            // Add the Terrain Map Type
            map.addMapType(G_PHYSICAL_MAP);

            map.setMapType(map.getMapTypes()[maptype]);
            //alert(G_PHYSICAL_MAP);
    
            // Return the map to the saved position
            GEvent.addListener(map, "infowindowclose", function() {
                map.returnToSavedPosition();
            });
            
            // === Get the stations and create the markers
            icon = new GIcon();
            icon.iconAnchor = new GPoint(12, 12);
            

            GDownloadUrl("getStations.php", function(data, responseCode) {
                var xml = GXml.parse(data);
                var markers = xml.documentElement.getElementsByTagName("station");
                vectMarkers = [];		
    
                    for (var i = 0; i < markers.length; i++) {			
                        var lat = parseFloat(markers[i].getAttribute("lat"));
                        var lng = parseFloat(markers[i].getAttribute("lng"));
                        var name = markers[i].getAttribute("name"); 
                        var county = markers[i].getAttribute("county");
						var locID = markers[i].getAttribute("locID");
						var LGMI = markers[i].getAttribute("LGMI");
						var Count = markers[i].getAttribute("Count");
                          
                        var point =   new GLatLng(lat,lng);     						
                        var title = "<font color='black' size='2'>"+name + " Station</font>";
						
			//alert(LGMI);
                        
                        marker = createMarker(point, title, icon, county, lat, lng, locID, LGMI, Count);
                        vectMarkers[locID] = marker; //.push(marker);
                        map.addOverlay(vectMarkers[locID]);   
											   					 			  						
                    }    
                });
            
            function createMarker(point, title, icon, county, lat, lng, locID, LGMI, Count) {                
                icon.iconSize = new GSize(18, 18);
                icon.iconAnchor = new GPoint(9,9);
                icon.infoWindowAnchor = new GPoint(5, 8);
                var marker;       
		
		
                var recommendation = '<br><br><b><a href="#" onClick =window.open("http://www.agroclimate.org/forecasts/LGMI/JPGraph.php?COOPID='+locID+'","newwin",["width=577,height=418"])>&raquo;&raquo; Click here for the Graph &laquo;&laquo;</a></b>';
                var information = "";
				
		if(Count > 3 )
			icon.image = "images/coopLGMIx.png";
		else if(LGMI<=-1.5)
			icon.image = "images/LGMI-20.png";
		else if(LGMI<=-1.0)
			icon.image = "images/LGMI-15.png";
		else if(LGMI<=-0.5)
			icon.image = "images/LGMI-10.png";
		else if(LGMI <=0.5)
			icon.image = "images/LGMI-05.png";
		else if(LGMI <=1.0)
			icon.image = "images/LGMI05.png";
		else if(LGMI <=1.5)
			icon.image = "images/LGMI10.png";
		else
			icon.image = "images/LGMI20.png";
		
		

		marker = new PdMarker(point,icon);
                
                marker.setId(locID);
                // Set the transparency of the tooltip (100 is opaque)
                marker.setOpacity(100);
                // Mouseover event for tooltip
                GEvent.addListener(marker, "mouseover", function() {
					if(Count >= 3) {
	                    marker.setTooltip("<b><h3>"+title+"<hr>County: "+county+"<br/><br/>Data Missing</h3></b>");					
					} else {
	                    marker.setTooltip("<b><h3>"+title+"<hr>County: "+county+"</h3></b>");					
					} 
                });	
               
                           
                  GEvent.addListener(marker, 'click', function() {
		     var width = window.screen.width/2;
			 var height = window.screen.height/2;
                    //markerClicked(marker);
		if(Count <=3)
		{			
		 if(typeof(countMyself.counter) == "undefined")
		    {countMyself.counter = 1;
		    }
		 if(countMyself.counter%2 != 0)
		   {
		  
		   if(countMyself.counter != 1)
		   	 { 
			  countMyself.win1.close();	}
			 
		   var win = window.open(link+"COOPID="+locID+"&w="+(width)+"&h="+(height),"newwin1",["width="+(width-20)+",height=448,screenX=0,screenY=100"]);
		 
		   countMyself.counter = countMyself.counter+1;
		   countMyself.win1 = win;
		   countMyself.win2.setFocus();
		   win.setFocus();
		   		   		  
		  }
		 else
		  {
		   if(countMyself.counter != 2)
		  	 {
			 countMyself.win2.close();
			 
			 }
		  var win= window.open(link+"COOPID="+locID+"&w="+(width)+"&h="+(height),"newwin2",["width="+(width-20)+",height=448,screenX="+(width+100)+",screenY=100"]);
		
		  countMyself.counter = countMyself.counter+1;
		  countMyself.win2 = win;
		  countMyself.win1.setFocus();
		  win.setFocus();
		 
		  }
		 }
		 		 

	
/*
                    var maxContentDiv = document.createElement('div');
                    maxContentDiv.innerHTML = 'Loading...';
                    map.savePosition();
                    locID = marker.getId();
                    stationCredit = '';
                    
                    marker.openInfoWindowHtml("<div style='padding:5px' id='divballoon'><table border=0 width='100%'><tr><td align='left'>"+stationCredit+
                        "</td><td align='left'><b>"+title+"</b></td></table><hr><center><h2></h2>"+ recommendation +
                        "</center></div>",
                    {maxContent: maxContentDiv, 
                        maxTitle: title});

                    var iw = map.getInfoWindow();
					
                    GEvent.addListener(iw, "maximizeclick", function() {
                        
                            maxContentDiv.innerHTML = "http://www.agroclimate.org/forecasts/LGMI/JPGraph.php?COOPID="+locID;
                                                
                    });
					
                    // Maximize the window immediately
                    GEvent.trigger(map, "maximizeclick");
                    //map.getInfoWindow().maximize();
*/
                });
    
                return marker;
            }
        } 
    }
    // === Set the cookie before exiting ===
    function setCookieMap() {
        //alert("cookie");
        maptype = 0;
        for (var i=0;i<map.getMapTypes().length;i++) {
            //alert(i);
            if (map.getCurrentMapType() == map.getMapTypes()[i]) {
                maptype = i;
            }
        }
        var cookietext = cookiename+"="+map.getCenter().lat()+"|"+map.getCenter().lng()+"|"+map.getZoom()+"|"+maptype;
        //alert(cookietext);
        if (expiredays) {
            var exdate=new Date();
            exdate.setDate(exdate.getDate()+expiredays);
            cookietext += ";expires="+exdate.toGMTString();
        }
        // == write the cookie ==
        document.cookie=cookietext;
        // == Call GUnload() on exit ==
        GUnload();
    }
	function countMyself() {
    // Check to see if the counter has been initialized
  		var counter = 1;
		var win1;
		var win2;
	
	}


    function drawCounty(station) {
        GDownloadUrl("getCountycoordinates.php?station="+station, function(data, responseCode) {
            var xml = GXml.parse(data);
            var points = xml.documentElement.getElementsByTagName("point");
            vPoints = [];
            for (var i = 0; i < points.length; i++) {
                var lat = parseFloat(points[i].getAttribute("lat"));
                var lng = parseFloat(points[i].getAttribute("lng"));
                var point = new GLatLng(lat,lng);
                vPoints.push(point);
            }            
            countyPoints = new GPolygon(vPoints, "#ff0000", 3, 0.3, "#FFFF00", 0.3);
            map.addOverlay(countyPoints);
        });
    }
    function goCounty(station) {
        GDownloadUrl("getCountyCentroid.php?station="+station, function(data, responseCode) {
            var xml = GXml.parse(data);
            var points = xml.documentElement.getElementsByTagName("point");            
            var lat = parseFloat(points[0].getAttribute("lat"));
            var lng = parseFloat(points[0].getAttribute("lng"));
            map.setCenter(new GLatLng(lat,lng)); 
        });
    }
    function removeLimits() {
        if(countyPoints != null) {
            map.removeOverlay(countyPoints);
            countyPoints = null;
        }
    }
    function drawOrClean() {
        map.closeInfoWindow();
        removeLimits();
        if(document.getElementById('viewcounty').innerHTML.indexOf("Clean")>=0) {
            document.getElementById('viewcounty').innerHTML='Draw the limits of County';
        } else {
            goCounty(document.getElementById('station').value);
            drawCounty(document.getElementById('station').value);
            document.getElementById('viewcounty').innerHTML='Clean the limits of County';
        }   
	}

function Zoom(option) {      
	   	map.setZoom(7);	
		
		if(option == 0)
		{
		 map.panTo(new GLatLng(32.93492866908233,-86.649169921875));
		 
		}
		else if(option == 2)
		{
		 map.panTo(new GLatLng(32.79651010951669,-83.2763671875));
		
		}
		else if(option == 1)
		{
		 map.panTo(new GLatLng(28.738763971370293,-81.62841796875));
		
		}
		else if(option == 4)
		{
		 map.panTo(new GLatLng(33.95247360616281,-80.66162109375));
		
		}
		else if(option == 3)
		{
		 map.panTo(new GLatLng(35.817813158696616,-78.211669921875));
		 
		}
		else if(option == 5)
		{
		map.setZoom(6);
		 map.panTo(new GLatLng(32.342841356393016,-82.28759765625));
		 	
		 
		}
		
		
		
		
		
    }
	

    function stationChanged(station) {
        locID = station;
        removeLimits();
        document.getElementById('viewcounty').textContent='Draw the limits of County';
        goCounty(station);
        //vectMarkers[station].blink(true,20);
        GEvent.trigger(vectMarkers[station], "click");
    }
    function markerClicked(marker) {
        document.getElementById(marker.getId()).selected = true;
    }
}

