
//Google's code checks if the browser is compatible//
if (GBrowserIsCompatible()) {

	var markerPlaced = 0;
	var called = 0;
	//Initialize arrays to store variables for xml driven pins//
    var side_bar_html = "";
    var gmarkers = [];  
    var htmls = [];   
    var groups=[];
    var codes =[];
    var points =[];
    var names =[];
    var infotabs =[];
    var photos =[];
    var i = 0;
    // arrays to hold variants of the info window html with get direction forms open//
    var to_htmls = [];
    var from_htmls = [];
    
   //pulls the building code from the URL if there is one//
   var buildcode = gup('building');
   

    // Define the different pin icons//
    var redIcon = new GIcon(G_DEFAULT_ICON);
    redIcon.image="http://www.pp.wmich.edu/images/pin_red.png";
    var yellowIcon = new GIcon(G_DEFAULT_ICON);
    yellowIcon.image="http://www.pp.wmich.edu/images/pin_yellow.png";
    var cyanIcon = new GIcon(G_DEFAULT_ICON);
    cyanIcon.image="http://www.pp.wmich.edu/images/pin_cyan.png";
    var greenIcon = new GIcon(G_DEFAULT_ICON);
    greenIcon.image="http://www.pp.wmich.edu/images/pin_green.png";
    var blueIcon = new GIcon(G_DEFAULT_ICON);
    blueIcon.image="http://www.pp.wmich.edu/images/pin_blue.png";
    var purpleIcon = new GIcon(G_DEFAULT_ICON);
    purpleIcon.image="http://www.pp.wmich.edu/images/pin_purple.png";
    var blackIcon = new GIcon(G_DEFAULT_ICON);
    blackIcon.image="http://www.pp.wmich.edu/images/pin_black.png";
    var whiteIcon = new GIcon(G_DEFAULT_ICON);
    whiteIcon.image="http://www.pp.wmich.edu/images/pin_white.png";
	

  
    
    // ===========================================================
    // A function to create the marker and set up the event window
    //============================================================
    function createMarker(point,name,html,group,customIcon,code,photo) {
    html = '<div style="width:250px;">'+html;	// this specifies the width of the bubble
    //sets the marker's color//
    //if (undefined = customIcon) { customIcon = 'blueIcon'; } //
    var markerOptions;
    if (customIcon == 'red') {
        markerOptions= {icon:redIcon};
    } else if (customIcon == 'yellow') {
        markerOptions= {icon:yellowIcon};
    } else if (customIcon == 'cyan') {
        markerOptions= {icon:cyanIcon};
    } else if (customIcon == 'green') {
        markerOptions= {icon:greenIcon};
    } else if (customIcon == 'blue') {
        markerOptions= {icon:blueIcon};
    } else if (customIcon == 'purple') {
        markerOptions= {icon:purpleIcon};
    } else if (customIcon == 'black') {
        markerOptions= {icon:blackIcon};
    } else if (customIcon == 'white') {
        markerOptions= {icon:whiteIcon};
    }
    var marker = new GMarker(point, markerOptions);
    // The info window version with the "to here" form open
    to_htmls[i] = html + '<br>Directions: <b>To here</b> - <a href="javascript:fromhere(' + i + ')">From here</a>' +
        '<br>Start address:<form action="javascript:getDirections()">' +
        '<input type="text" size="40" maxlength="40" name="saddr" id="saddr" value="" /><br>' +
        '<input value="Get directions" type="submit">' +
        '<input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
        '"/>';
    // The info window version with the "to here" form open
    from_htmls[i] = html + '<br>Directions: <a href="javascript:tohere(' + i + ')">To here</a> - <b>From here</b>' +
        '<br>End address:<form action="javascript:getDirections()">' +
        '<input type="text" size="40" maxlength="40" name="daddr" id="daddr" value="" /><br>' +
        '<input value="Get Directions" type="submit">' +
        '<input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
        '"/>';
    // The inactive version of the direction info
    html = html + '<br>Directions: <a href="javascript:tohere('+i+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a>';
    html = html + '</div>';

    //Listener to check if a marker has been clicked on the map//
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowTabsHtml(infoTabs);
    });
    
    // save the info we need to use later for the side_bar into the arrays//
    gmarkers[i] = marker;
    htmls[i] = html;
    groups[i] = group;
    codes[i] = code;
    points[i] = point;
    names[i] = name;
    photos[i] = photo;

    //The array of tabs for the info window//
	var infoTabs =
	[
      new GInfoWindowTab("Info", html),
      new GInfoWindowTab("Photo", photo)
	];    
	infotabs[i] = infoTabs
	 i++;
    
    } // end createMarker
    
    // ===== request the directions ===== //
    function getDirections() {
    var saddr = document.getElementById("saddr").value
    var daddr = document.getElementById("daddr").value
    gdir.load("from: "+saddr+" to: "+daddr);
    
    } // end getDirections

    // ========================================================================
    // This function picks up the click and opens the corresponding info window
    //=========================================================================
    function myclick(i) {
    gmarkers[i].openInfoWindowHtml(htmls[i]);
    } // end myclick 

    // ==========================================
    // functions that open the directions forms
    //==========================================
    function tohere(i) {
    gmarkers[i].openInfoWindowHtml(to_htmls[i]);
    } // end tohere

      
    function fromhere(i) {
    gmarkers[i].openInfoWindowHtml(from_htmls[i]);
    } // end fromhere
	
    

  //=============================================================
  //This function goes through the array of markers
  //and displays pins that match the value sent in from dropdowns
  //or search bar
  //=============================================================
  function placeMarkers(value)
  {
	  if(called == 1)
	  {
		  called = 0;
	   	  
   	  }
   	  else{
	  var counter = 0;
	  
	//reloads page if arrays are null because IE is terrible.// 
	if(names[0] == null || groups[0] == null || codes[0] == null)
	{
		rld();
	}
	  
	 
    for(var k = 0; k < gmarkers.length;k++)
    {
	 
     //checks the value against the group type--for the category dropdown//
      if (groups[k] == value)
      {
        map.addOverlay(gmarkers[k]);
        markerPlaced = 0;
      }
      //checks the value against the building code--for the Building list dropdown//
      else if (codes[k] == value)
      {
	    
        map.addOverlay(gmarkers[k]);
        map.panTo(points[k]);
        gmarkers[k].openInfoWindowTabsHtml(infotabs[k]);
        markerPlaced = 0;
      }
      
      //used to prevent problems with a lack of building code in URL and//
      //the ----- option being selected in the dropdowns//
      else if(value == "" || value == null)
      {markerPlaced = -1;
	      break;}
      
      //checks the value against the building's name--for the search bar//
      else if(names[k].toUpperCase().indexOf(value.toUpperCase()) != -1)
      {
	    
	  
	    map.addOverlay(gmarkers[k]);
        map.panTo(points[k]);
        gmarkers[k].openInfoWindowTabsHtml(infotabs[k]);
        markerPlaced = 0;
        
       
      }
      
      //Increments a counter if nothing matches//
      else if(value != groups[k] && value != codes[k] && value != names[k])
      {	
	      counter++; 
	      
	  }  
    }   
  	
    //if the counter equals the amount of markers there are (i.e. there were no matches),//
    //display a message saying that there were no results>
     
	if(counter == gmarkers.length)
      {	
	   document.getElementById('inputval').blur();
    	showStatus('<div style="text-align:right">close [X]</div><span style="font-size:16pt;">Your search for '+document.getElementById('inputval').value+' returned no results.</span>','greyout',350);    
        document.getElementById('button').focus();
       
        
      }     
    
   }
  } //end placeMarkers

  function checkBoth()
  {
	
	 		placeMarkers(document.getElementById('hiddenval').value);
   			if (markerPlaced == -1)
   			{
	   			//alert("markerPlaced = -1");
	   			placeMarkers(document.getElementById('inputval').value);  
			} 
	
  }

  
  // ====================================================================
  // Remove the overlay of pins and reset the catergoy and building list.
  //=====================================================================
  function clearMarkers()
  {
    map.clearOverlays();
    gdir.clear();
    document.getElementById('catlist').selectedIndex = 0;
    document.getElementById('buildlist').selectedIndex = 0;
    document.getElementById('hiddenval').value = '';
    document.getElementById('inputval').value = '';
    map.panTo(new GLatLng(42.282904, -85.609700));
    document.getElementById('inputval').focus();
   
  } // end clearMarkers

  
   //========================================================
   //Makes hitting enter to submit the search form possible.
   //========================================================
   function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
	    setTimeout("checkBoth()",1000);
	
   return false;
   }
else
   return true;
}//end submitenter
  
  
  // =================================================
  // Convert the google x,y,zoom to the quadkey tiling
  //==================================================
  function tileToQuadKey (x,y,zoom) {	// converts google x,y,zoom
    var quad="";				//  to virtual earth quadkey
    for (var i = zoom;i > 0;i--) {	//  tiling name
      var mask = 1 << (i-1);
      var cell = 0;
      if ((x & mask) != 0)
        cell++;
      if ((y & mask) != 0)
        cell += 2;
      quad += cell;
    }
    return quad;
  } // end tileToQuadKey

  //=====================================================================================================
  // This chunk initializes the map, loads the tiles for each overlay, and enables the switching of maps
  //=====================================================================================================
  
  //creates the yellow outline used on some maps//
   var wmuBound = new GGeoXml("http://www.pp.wmich.edu/buildings/WMU_Boundaries.kml?Bldg=141");      
   //creates the actual map object and places it in the "map" DIV//
    var map = new GMap2(document.getElementById("map"));
    // define general map 
    map.setCenter(new GLatLng(42.282904, -85.609700), 15, wmuMap);
    map.addControl(new GLargeMapControl());    
    map.addControl(new GScaleControl());
    map.enableScrollWheelZoom();
    map.enableContinuousZoom();
    // add regional copyright information along the bottom, as defined by a box and zoom level
    var copyright = new GCopyright(1,
        new GLatLngBounds(
            new GLatLng(42.274070,-85.623965), //these are the SWcorner lat longs
            new GLatLng(42.292588,-85.594579)  //these are the NE corenr lat longs
        ), 13, "Board of Trustees");
    var copyrightCollection = new GCopyrightCollection('Western Michigan University:');
    copyrightCollection.addCopyright(copyright);
    
    // define the regular map's tile overlay//
    var wmuTileOverlay = new GTileLayer(copyrightCollection,13,17);
    //used so the tiles have clear backgrounds in IE//
    wmuTileOverlay.isPng=function() {return true;}
    //loads the tiles for the regular WMU map//
    wmuTileOverlay.getTileUrl=function(a,b){
      var condition="x";
      if (condition == 'xx') {
        if (b==12 && a.x>=1073 && a.x<=1074 && a.y>=1516 && a.y<= 1516) {
          //return "wmuTiles/x12/Tile_12_"+a.x+"_"+a.y+".png";
          return "CutTiles/x12/Tile_5_"+a.x+"_"+a.y+".png";
        } else if (b==13 && a.x>=2147 && a.x<=2148 && a.y>=3032 && a.y<= 3032) {
          //return "wmuTiles/x13/Tile_13_"+a.x+"_"+a.y+".png";
          return "CutTiles/x13/Tile_4_"+a.x+"_"+a.y+".png";
        } else if (b==14 && a.x>=4295 && a.x<=4296 && a.y>=6064 && a.y<= 6065) {
          //return "wmuTiles/x14/Tile_14_"+a.x+"_"+a.y+".png";
          return "CutTiles/x14/Tile_3_"+a.x+"_"+a.y+".png";
        } else if (b==15 && a.x>=8590 && a.x<=8593 && a.y>=12128 && a.y<= 12130) {
          //return "wmuTiles/x15/Tile_15_"+a.x+"_"+a.y+".png";
          return "CutTiles/x15/Tile_2_"+a.x+"_"+a.y+".png";
        } else if (b==16 && a.x>=17180 && a.x<=17186 && a.y>=24256 && a.y<= 24260) {
          //return "wmuTiles/x16/Tile_16_"+a.x+"_"+a.y+".png";
          return "CutTiles/x16/Tile_1_"+a.x+"_"+a.y+".png";
        } else if (b==17 && a.x>=34360 && a.x<=34371 && a.y>=48512 && a.y<= 48521) {
          //return "wmuTiles/x17/Tile_17_"+a.x+"_"+a.y+".png";
          return "CutTiles/x17/Tile_0_"+a.x+"_"+a.y+".png";
        } else {
        return "http://www.google.com/mapfiles/transparent.gif";
        }
      } else {
        return "wmuTiles/1_Default/Layer_NewLayer/"+tileToQuadKey(a.x,a.y,b)+".png";
      }
    }
    
    //loads the tiles for the Accessibility layer//
    var AccessTileOverlay = new GTileLayer(copyrightCollection,13,17);
    AccessTileOverlay.isPng=function() {return true;}
    AccessTileOverlay.getTileUrl=function(a,b)
    {
	    return "wmuTiles/4_Accessibility/Layer_NewLayer/"+tileToQuadKey(a.x,a.y,b)+".png";
	}
	//loads the tiles for the Parking layer//
	var ParkingTileOverlay = new GTileLayer(copyrightCollection,13,17);
    ParkingTileOverlay.isPng=function() {return true;}
    ParkingTileOverlay.getTileUrl=function(a,b)
    {
	    return "wmuTiles/3_Parking/Layer_NewLayer/"+tileToQuadKey(a.x,a.y,b)+".png";
	}
	//loads the tiles for the Mobility Layer//
	var MobilityTileOverlay = new GTileLayer(copyrightCollection,13,17);
    MobilityTileOverlay.isPng=function() {return true;}
    MobilityTileOverlay.getTileUrl=function(a,b)
    {
	    return "wmuTiles/5_Mobility/Layer_NewLayer/"+tileToQuadKey(a.x,a.y,b)+".png";
	}
  
    //Creates normal WMU map//
    var wmuMap = new GMapType([G_NORMAL_MAP.getTileLayers()[0], wmuTileOverlay],
      G_NORMAL_MAP.getProjection(), 'WMU',{errorMessage:"Out of Bounds"});              
    map.addMapType(wmuMap);
    map.setMapType(wmuMap);
	
    //Creates WMU map with satellite//
    var wmuMap2 = new GMapType([G_HYBRID_MAP.getTileLayers()[0], wmuTileOverlay],
      G_HYBRID_MAP.getProjection(), 'w/ Sat.',{errorMessage:"Out of Bounds"});              
    map.addMapType(wmuMap2);   
    
     //Creates Parking Map // 
    var wmuMap3 = new GMapType([G_SATELLITE_MAP.getTileLayers()[0], ParkingTileOverlay], 
      G_SATELLITE_MAP.getProjection(), 'Parking', {errorMessage: "Out of Bounds"});
    map.addMapType(wmuMap3);

    //Creates Accessibility map//
    var wmuMap4 = new GMapType([G_SATELLITE_MAP.getTileLayers()[0], AccessTileOverlay], 
      G_SATELLITE_MAP.getProjection(),'Accessibility', {errorMessage: "Out of Bounds"});
	map.addMapType(wmuMap4);

	//Creates Mobility Map//
	var wmuMap5 = new GMapType([G_SATELLITE_MAP.getTileLayers()[0], MobilityTileOverlay], 
      G_SATELLITE_MAP.getProjection(),'Mobility', {errorMessage: "Out of Bounds"});
	map.addMapType(wmuMap5);
	
	//makes map type a subset of the first//
    var hierachMap = new GHierarchicalMapTypeControl();
    
    //adds other map types to the main WMU map hierarchy//
    hierachMap.addRelationship(wmuMap,wmuMap2,"w/ Satellite");
    hierachMap.addRelationship(wmuMap,wmuMap3,"Parking");
    hierachMap.addRelationship(wmuMap,wmuMap4,"Accessibility");
    hierachMap.addRelationship(wmuMap,wmuMap5,"Mobility");
    map.addControl(hierachMap);
    
    //Listener to load a different legend depending on the current map type//
    GEvent.addListener(map, "maptypechanged", function() 
    {
        if(map.getCurrentMapType() == wmuMap)
		{		
			map.removeOverlay(wmuBound);
			document.getElementById('legend').innerHTML = '<img src="images/MainLegend.png" id ="legendpic" alt="legend" style="width: 745px;"/>';
		}
		else if(map.getCurrentMapType() == wmuMap2)
		{
			map.removeOverlay(wmuBound);
			document.getElementById('legend').innerHTML = '<img src="images/MainLegend.png" id ="legendpic" alt="legend" style="width: 745px;"/>';
		}
		else if(map.getCurrentMapType() == wmuMap3)
		{		
			map.addOverlay(wmuBound);
			map.removeOverlay(wmuBound);
			document.getElementById('legend').innerHTML = '<img src="images/ParkingLegend.png" id ="legendpic" alt="legend" style="width: 745px;"/>';
		}
		else if(map.getCurrentMapType() == wmuMap4)
		{		
			map.addOverlay(wmuBound);
			map.removeOverlay(wmuBound);
			document.getElementById('legend').innerHTML = '<img src="images/AccessibilityLegend.png" id ="legendpic" alt="legend" style="width: 745px;"/>';
		}
		else if(map.getCurrentMapType() == wmuMap5)
		{		
			map.addOverlay(wmuBound);
			map.removeOverlay(wmuBound);
			document.getElementById('legend').innerHTML = '<img src="images/MobilityLegend.png" id ="legendpic" alt="legend" style="width: 745px;"/>';
		}
		else if(map.getCurrentMapType() == G_NORMAL_MAP)
		{		
			map.removeOverlay(wmuBound);
			document.getElementById('legend').innerHTML = '<img src="images/MainLegend.png" id ="legendpic" alt="legend" style="width: 745px;"/>';
		}
		else if(map.getCurrentMapType() == G_SATELLITE_MAP)
		{		
			map.removeOverlay(wmuBound);
			document.getElementById('legend').innerHTML = '<img src="images/MainLegend.png" id ="legendpic" alt="legend" style="width: 745px;"/>';
		}
		else if(map.getCurrentMapType() == G_HYBRID_MAP)
		{		
			map.removeOverlay(wmuBound);
			document.getElementById('legend').innerHTML = '<img src="images/MainLegend.png" id ="legendpic" alt="legend" style="width: 745px;"/>';
		}
    })//end addListener
    
   	//========================================================================================================================================================
   	//========================================================================================================================================================
		
	
    // === create a GDirections Object === //
    var gdir=new GDirections(map, document.getElementById("directions"));
    
    // === Array for decoding the failure codes ===//
    var reasons=[];
    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.";
    reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
    reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
    reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

    // === catch Directions errors ===//
    GEvent.addListener(gdir, "error", function() {
      var code = gdir.getStatus().code;
      var reason="Code "+code;
      if (reasons[code]) {
          reason = reasons[code]
      } 
      alert("Failed to obtain directions, "+reason);
    });

     //=================================================================   
    //This pulls the pins from the XML page once and puts them in arrays
    //==================================================================
	  var request = GXmlHttp.create();
    //tell the request where to retrieve data from  
    request.open('GET', 'allbldg.xml', true);
	  //tell the request what to do when the state changes
	 
	  request.onreadystatechange = function() 
	  {			
        if (request.readyState == 4) 
        {
          //var xmlDoc = GXml.parse(request.responseXML);
          var xmlDoc = GXml.parse(request.responseText);
          var markers = xmlDoc.documentElement.getElementsByTagName("marker");
          for (var j = 0; j < markers.length; j++) 
          {
            // obtain the attribues of each marker	              
            var code = markers[j].getAttribute("code");
            var lat = parseFloat(markers[j].getAttribute("lat"));
            var lng = parseFloat(markers[j].getAttribute("lng"));
            var point = new GLatLng(lat,lng);	              
            var html = markers[j].getAttribute("html");
            var label = markers[j].getAttribute("label");
            var group = markers[j].getAttribute("group_map");
            var customIcon = markers[j].getAttribute("icon");
            var photo = markers[j].getAttribute("html2");
            // create the marker	              
            createMarker(point,label,html,group,customIcon,code,photo);	
          }
          //If there's a building code in the URL, the marker is placed at startup//
          placeMarkers(buildcode);
        } //if  
        
      } //function

     request.send(null);
      
   
  } else {
     alert("Sorry, the Google Maps API is not compatible with this browser");
  } // end if gmapcompatible
  
  function rld() {
document.location.reload()
}

  
  	//============================================================//
	//Used to pull the building code from the URL
	//============================================================//
	function gup(name)
	{
  		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  		var regexS = "[\\?&]"+name+"=([^&#]*)";
  		var regex = new RegExp( regexS );
  		var results = regex.exec( window.location.href );
  		if( results == null )
    
  		return "";
  		else
   
  		return results[1];
	}//end gup


    //================================================================
    //Used to display the help boxes and the no-results box.
    //================================================================
    function showStatus(message,id, margin) 
    {
  		if (id == 0)
    		{id = 'status';} 
  
  
  		document.getElementById(id).innerHTML="<div style='opacity:1.0;filter: alpha(opacity=100); position: absolute; left:35%; top:0; margin-top: " + margin + "px; width:350px; padding:2px; background:#efe;  border: 2px solid #630; '><strong>"+message+"</strong></div>";
  		document.getElementById(id).style.visibility="visible";
  
 
	}//end showStatus
	
  //====================================================================
  //Used to clear the help boxes and the no-results box.
  //====================================================================
	function clearStatus(id) {
	if (id == null)
	{id = 'status';}
  document.getElementById(id).style.visibility="hidden";
  if(id == 'greyout')
  document.getElementById('inputval').select();
	}//end clearStatus
