        $(document).ready(function() {

			// JC - Use ajax to populate the data every n seconds.
      var refreshId = setInterval(function() {
        $("div.alternateContent.middlesex").load('includes/edWaitTimes.cfm?location=Middlesex&randval='+ Math.random());
        $("div.alternateContent.shoreline").load('includes/edWaitTimes.cfm?location=Shoreline&randval='+ Math.random());
        $("div.alternateContent.marlborough").load('includes/edWaitTimes.cfm?location=Marlborough&randval='+ Math.random());
      }, 120000);

      // JC - Find all external links and set their target to new window (leaves clean XHTML and doesn't affect links like mailto).
      $("a").filter(function() {
        return this.hostname && this.hostname != location.hostname;
      }).each(function() {
        var title = $(this).attr("title");
        title += " [This will open in an external window]";
        title = $.trim(title);
        $(this).attr("title", title);
        $(this).attr("target","_new");
      });

      // JC - Use ajax (json) to check if data is older than 25 minutes. If yes, display custom message that the service is temporarily down
      function checkWaitTimes() {
        $.getJSON('includes/edWaitTimesJson.cfm?randval='+ Math.random(), function(data) {
          if (data.status != "200" || data.updatedMinutesAgo >= 25) {
            $("#outageContent").css('display', 'block').html("<span>Currently unavailable due to system maintenance.</span><span>Please check back shortly</span>");
            $("#mainContent").css('display', 'none');
          } else {
            $("#outageContent").css('display', 'none').html("");
            $("#mainContent").css('display', 'block');
          }
        });
      };
			checkWaitTimes(); // Call on first page load
      var refreshId2 = setInterval(function() {checkWaitTimes()}, 300000); // repeat every 5 minutes
    
                
                $('#tip').qtip({
   content: '<p class="tippy"><strong>How is the Current Waiting Time calculated?</strong><br /><br />The Current Waiting Time is the actual length of time from "door to doc". <a target="_blank" href="http://middlesexhospital.org/our-services/hospital-services/emergency-medicine/wait-time/triage/what-do-these-wait-times-mean">More</a><br /><br /><strong>Why do some patients get seen first, even if they arrived after me?</strong><br /><br />Patients who arrive with life threatening and more serious injuries and ailments are seen before those with non-life threatening problems. <a target="_blank" href="http://middlesexhospital.org/our-services/hospital-services/emergency-medicine/wait-time/triage/what-do-these-wait-times-mean">More</a><br /><br /><strong>What is Express Care?</strong><br /><br />Express Care is meant for those patients who have injuries and ailments that need to be treated, but are not very serious or life threatening.  <a target="_blank" href="http://middlesexhospital.org/our-services/hospital-services/emergency-medicine/wait-time/triage/what-do-these-wait-times-mean">More</a></p>',

        position: { adjust: { x: -200, y: 0 } },
	style: { 
		background: '#F8F8F8',
		color: 'black',
		width: 350,
		tip: 'topLeft',
		border: {
		         color: '#E3E3E3',
		         width: 1,
         		 radius: 3

		},

		name: 'light' // Inherit from preset style   
	}
	,
	show: { when: { event: 'click' } },
	hide: { when: 'unfocus', 
		fixed: true 
		}
})




                setupInitalMarkers();
                
         
                $(window).keypress(function(e) {
                    if(e.keyCode == 13) {
                            handleAddressSubmit();
                    }
                });

                $("#searchButtonLink").click(function () {
                        handleAddressSubmit();
                });
                

                /*
	locations["ms"]="Middlesex ED";
	locations["mb"]="Marlborough ED";
	locations["sl"]="Shoreline ED";
	*/
        var flashvars = {};
	flashvars.locationID = "ms";
	flashvars.pathToXML = "xml/current_time.cfm";
        var params = {};
        params.wmode = "transparent";
        swfobject.embedSWF("flash_middlesex_clock.swf", "flash_middlesex_clock", "210", "112", "9.0.0","expressInstall.swf",flashvars,params);

        var flashvars = {};
	flashvars.locationID = "mb";
	flashvars.pathToXML = "xml/current_time.cfm";
        var params = {};
        params.wmode = "transparent";
        swfobject.embedSWF("flash_middlesex_clock.swf", "flash_marlborough_clock", "210", "112", "9.0.0","expressInstall.swf",flashvars,params);

        var flashvars = {};
	flashvars.locationID = "sl";
	flashvars.pathToXML = "xml/current_time.cfm";
        var params = {};
        params.wmode = "transparent";
        swfobject.embedSWF("flash_middlesex_clock.swf", "flash_shoreline_clock", "210", "112", "9.0.0","expressInstall.swf",flashvars,params);

        });

        function setupInitalMarkers() {
                
                if (GBrowserIsCompatible()) {
                // Initialize the map.

               // Middlesex 41.553554,-72.586155
               // Shoreline (41.3286315107747, -72.42805480957031)
               // Marlborough (41.63299006652702, -72.46109962463379)

               // Moodus (good center point) (41.502843, -72.450318)

                map = new GMap2(document.getElementById("gMap"));
                map.addControl(new GLargeMapControl());
                map.setCenter(new GLatLng(41.502843, -72.450318), 9);

                var homeaddress = getSubmittedAddressForGmapDirections();
                
                if (homeaddress != "") {
               //         alert("homeaddress:" + homeaddress + ":");
                //        alert($("a.midLink")[0].href);
                        $("a.midLink")[0].href = 'http://maps.google.com/maps?f=d&amp;source=s_d&amp;saddr=' + homeaddress + ' &amp;daddr=28+Crescent+Street,+Middletown,+CT+06457&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=41.555065,-72.647114&amp;sspn=0.00957,0.017874&amp;ie=UTF8';                
                        $("a.marlLink")[0].href = 'http://maps.google.com/maps?f=d&amp;source=s_d&amp;saddr=' + homeaddress + '&amp;daddr=12+Jones+Hollow+Road,+Marlborough,+CT+06447&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=41.327745,-72.428064&amp;sspn=0.009604,0.017874&amp;ie=UTF8'; 
                
                        $("a.shoreLink")[0].href = 'http://maps.google.com/maps?f=d&amp;source=s_d&amp;saddr=' + homeaddress + '&amp;daddr=260+Westbrook+Road,+Essex,+CT+06426&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=41.555065,-72.647114&amp;sspn=0.00957,0.017874&amp;ie=UTF8';

                }
                
                

                var point = new GLatLng(41.555065, -72.647114);
                var html = "<strong>Middlesex Hospital</strong><br />";
                html += "28 Crescent Street<br />Middletown, CT 06457<br />";
                html += "Phone: (860) 358-6000<br />";
                html += '<a target="_blank" href="http://maps.google.com/maps?f=d&amp;source=s_d&amp;saddr=' + homeaddress + ' &amp;daddr=28+Crescent+Street,+Middletown,+CT+06457&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=41.555065,-72.647114&amp;sspn=0.00957,0.017874&amp;ie=UTF8" id="midLink">Directions</a></br>';
                
                var marker1 = new GMarker(point);             
                
                var point2 = new GLatLng(41.3286315107747, -72.42805480957031);
                
                var html2= "<strong>Shoreline Medical Center</strong><br />";
                html2 += "260 Westbrook Road<br />Essex, CT 06426<br />";
                html2 += "Phone: (860) 358-3700<br />";
                html2 += '<a target="_blank" href="http://maps.google.com/maps?f=d&amp;source=s_d&amp;saddr=' + homeaddress + '&amp;daddr=260+Westbrook+Road,+Essex,+CT+06426&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=41.555065,-72.647114&amp;sspn=0.00957,0.017874&amp;ie=UTF8" id="shoreLink">Directions</a></br>';

                var marker2 = new GMarker(point2);             

                var point3 = new GLatLng(41.63299006652702, -72.46109962463379);
                var html3 = "<strong>Marlborough Medical Center</strong><br />";
                html3 += "12 Jones Hollow Road<br />Marlborough, CT 06447<br />";
                html3 += "Phone: (860) 358-3200<br />";
                html3 += '<a target="_blank" href="http://maps.google.com/maps?f=d&amp;source=s_d&amp;saddr=' + homeaddress + '&amp;daddr=12+Jones+Hollow+Road,+Marlborough,+CT+06447&amp;hl=en&amp;geocode=&amp;mra=ls&amp;sll=41.327745,-72.428064&amp;sspn=0.009604,0.017874&amp;ie=UTF8" id="marlLink">Directions</a></br>';
                var marker3 = new GMarker(point3);             

                GEvent.addListener(marker1, "click", function() {
                        marker1.openInfoWindowHtml(html);
                });
                GEvent.addListener(marker2, "click", function() {
                        marker2.openInfoWindowHtml(html2);
                });
                GEvent.addListener(marker3, "click", function() {
                        marker3.openInfoWindowHtml(html3);
                });

                map.addOverlay(marker1);
                map.addOverlay(marker2);
                map.addOverlay(marker3);
                }
        }

        function getSubmittedAddressForGmapDirections()
        {
                var fixed = "";
                if (jQuery.trim($("#addressInput").val()).length > 0 ||
                        jQuery.trim($("#stateInput").val()).length > 0 || 
                        jQuery.trim($("#zipInput").val()).length > 0 )
                {
                      return escape( jQuery.trim($("#addressInput").val())) + ",+" + jQuery.trim(escape($("#stateInput").val())) + ",+" + jQuery.trim(escape($("#zipInput").val())); } else {
                        return fixed;
                }
        }

        function handleAddressSubmit() {
                setupInitalMarkers(); // call this again to blank out any submitted pins
                var addr = $("#addressInput").val() + " " + $("#stateInput").val() + ", " + $("#zipInput").val()
                showAddress(addr);
        }

        function showAddress(address) {
        var geocoder = new GClientGeocoder();
        geocoder.getLatLng(
            address,
            function(point) {
              if (!point) {
          //      alert(address + " not found");
              } else {
                //var marker = new GMarker(point);
                //        alert("got new marker point");
                var personsHomeIcon = new GIcon(G_DEFAULT_ICON);
                personsHomeIcon.image = "img/home.png";
                markerOptions = {icon:personsHomeIcon};
                var marker = new GMarker(point,markerOptions);
                map.addOverlay(marker);
                // call this here as call is async 
                // and need to make sure we have value...
                reCenterAndZoom(point);
              }
            }
          );

        }
       
        function reCenterAndZoom(yourHousePoint) {
                //alert("in reCenterAndZoom with yourHousePoint as " + yourHousePoint);
          var point = new GLatLng(41.555065, -72.647114);
          var point2 = new GLatLng(41.3286315107747, -72.42805480957031);
          var point3 = new GLatLng(41.63299006652702, -72.46109962463379);
          allPointsArray = new Array();
          allPointsArray[0] = point;
          allPointsArray[1] = point2;
          allPointsArray[2] = point3;
          allPointsArray[3] = yourHousePoint;


          // Ok, now we re-center and re-zoom
          var latlngbounds = new GLatLngBounds();
          for ( var i = 0; i < allPointsArray.length; i++ )
          {
            latlngbounds.extend( allPointsArray[i] );
          }
          map.setCenter( latlngbounds.getCenter( ), map.getBoundsZoomLevel( latlngbounds ) );
  
        }



        $(document.body).unload(function() {
                if (GBrowserIsCompatible()) {
                        GUnload();
                }
        });


