﻿
/* global vars */
var map = null;
var mapOptions = {
    // zoom: 13,
    //mapTypeId: google.maps.MapTypeId.ROADMAP
    mapTypeId: google.maps.MapTypeId.TERRAIN
    , scrollwheel: false
    ,streetViewControl: true
};
var countyMapOptions = {
    // zoom: 13,
    mapTypeId: google.maps.MapTypeId.TERRAIN
    , scrollwheel: false
    , streetViewControl: true
};

var gmarkers = [];
var infowindow = new google.maps.InfoWindow({
    //content: 'the 411'
    size: new google.maps.Size(320,320)
});

var streetViewPanorama = null;
var sv = new google.maps.StreetViewService();


/* info window content */

function GetServiceDataForInfoWindow(map, locationInfo) {
    var communityid = locationInfo[0];
    var yahooWoeID = locationInfo[2];
    GetYahooData(baseurl, communityid, yahooWoeID);
}

// Yahoo weather data.
function GetYahooData(baseurl, communityid, communityArea) {

    var imgresult = baseurl + "images/vacation-rentals/weather_from_weather_source.gif";
    var requesturl = baseurl + "ajax/community-maps/GetYahooData.aspx";
    var temperature = '';

    $.get(requesturl,
        { area: '' + communityArea + '' },
     function(data) {

         try {

             if (window.DOMParser) {
                
                 parser = new DOMParser();
                 xmlDoc = parser.parseFromString(data, "text/xml");
                 //alert("xml: " + xmlDoc.documentElement.nodeName);
                 // shows the node name.  
                // temperature = xmlDoc.documentElement.getElementsByTagName("temperature")[0].nodeName;
                 temperature =  xmlDoc.documentElement.getElementsByTagName("temperature")[0].firstChild.nodeValue;
                 imgresult = xmlDoc.getElementsByTagName("weathericon")[0].firstChild.nodeValue;
                 
                 
                 $("#weatherHeading_" + communityid).html('Currently ');
               
                 $("#infoWeatherData_" + communityid).html('' + temperature + '');
                 
                 $("#imgweather_" + communityid).attr('src', imgresult);

             }
             else // Internet Explorer
             {

                 //<?xml version=""1.0""?><weather><temperature>{0}</temperature>
                 //     <weathericon>{1}</weathericon></weather>  
                 xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
                 xmlDoc.async = "false";
                 xmlDoc.loadXML(data);

                $("#weatherHeading_" + communityid).html('Currently ');
               
                 //var tst = xmlDoc.documentElement.tagName;
                 temperature = xmlDoc.documentElement.childNodes[0].text
                 $("#infoWeatherData_" + communityid).html('' + temperature + '');

                 imgresult = xmlDoc.documentElement.childNodes[1].text;
                 $("#imgweather_" + communityid).attr('src', imgresult);

             }
         }
         catch (err) {

            //  alert('exception: ' + err);

             // the containing span for the image and temperature.
             //$("#infoWeatherData").hide();
         }

     });

}

/* map markers and overlays */
/* AddLocationsToMap is the main entry point for the map draw. */
function AddLocationsToMap(locations, mapCorners) {

    // Initialize the map
    var swLatLng = mapCorners[0];
    var neLatLng = mapCorners[1];

    if (searchCountyName == '') {
        // Counties
        map = new google.maps.Map(document.getElementById("map"), countyMapOptions);
    }
    else {
        map = new google.maps.Map(document.getElementById("map"), mapOptions);
    }
 
    if (pagename == 'neighborhood-maps/default.aspx' || pagename == 'neighborhoods/default.aspx') {

        if (searchCountyName == 'Manatee') {
            var center = new google.maps.LatLng(27.479035, -82.401581);
            var zoomlevel = 10;
            map.setCenter(center);
            map.setZoom(zoomlevel);
        }
        else if (searchCountyName == 'Charlotte') {
            var center = new google.maps.LatLng(26.940435, -82.099457);
            var zoomlevel = 10;
            map.setCenter(center);
            map.setZoom(zoomlevel);
        }
        else if (searchCountyName == 'gulfCoastIslands') {
            var center = new google.maps.LatLng(27.181203, -82.501659);
            var zoomlevel = 10;
            map.setCenter(center);
            map.setZoom(zoomlevel);
        }
        else if (searchCountyName == '') {
            // center the county map the way we want it.
            var center = new google.maps.LatLng(27.274893, -82.191925);
            var zoomlevel = 9;
            map.setCenter(center);
            map.setZoom(zoomlevel);
        }
        else {
            // Let google determine the zoom and fit.
            var sw = new google.maps.LatLng(swLatLng[0], swLatLng[1]);
            var ne = new google.maps.LatLng(neLatLng[0], neLatLng[1]);
            var bounds = new google.maps.LatLngBounds(sw, ne);
            map.fitBounds(bounds);
        }
    }
    else {

        // neighborhood pages.
        var sw = new google.maps.LatLng(swLatLng[0], swLatLng[1]);
        var ne = new google.maps.LatLng(neLatLng[0], neLatLng[1]);
        var bounds = new google.maps.LatLngBounds(sw, ne);
        map.fitBounds(bounds);
    }
    google.maps.event.addListener(map, 'click', function() {
        infowindow.close();
        // Show all of the markers.
        for (var i = 0; i < gmarkers.length; i++) {
            gmarkers[i].setVisible(true);
        }
    });
    // Show all of the markers.    
    google.maps.event.addListener(infowindow, 'closeclick', function() {
        for (var i = 0; i < gmarkers.length; i++) {
            gmarkers[i].setVisible(true);
        }
    });
 
    // Add the markers and overlays.
    SetMarkers(map, locations);
    AddPolygons(map, locations);
}

function AddPolygons(map, locations) {

    var fillcolor = ['#768FA5'];
    
    // Manually select the colors for the counties and areas.
    // Neighborhoods just loop thru the 3 base colors.
    if (searchCountyName == '') {
        // Counties
        fillcolor = ['#002D56', '#385B7B', '#768FA5'];//, '#BADBEE' '#01528A';
    }
    else if(searchCountyName == 'Sarasota')
    {
    // sarasota county
      var  BirdKey = '#01528A';
      var  CaseyKey = '#419ECA';
      var  Englewood = '#002D56';
      var  LakewoodRanch = '#BADBEE';
      var  Laurel = '#002D56';
      var  LidoKey = '#BADBEE' ;
      var  LongboatKey =  '#01528A';
      var  ManasotaKey = '#385B7B';
      var  Nokomis = '#385B7B';
      var  NorthPort ='#BADBEE' ;
      var  Osprey = '#385B7B';
      var  PalmerRanch = '#BADBEE';
      var  Plantation = '#385B7B';
      var  SarasotaEast = '#002D56';
      var  SarasotaWest = '#385B7B';
      var  SiestaKey = '#01528A';
      var  StArmandsCircle = '#002D56';
      var UniversityPark = '#002D56';
      var  Venice = '#01528A';
      var  VeniceIsland = '#BADBEE';
        
       fillcolor = [
         BirdKey
        ,CaseyKey
        ,Englewood
        ,LakewoodRanch
        ,Laurel
        ,LidoKey
        ,LongboatKey
        ,ManasotaKey
        ,Nokomis
        ,NorthPort
        ,Osprey
        ,PalmerRanch
        ,Plantation
        ,SarasotaEast
        ,SarasotaWest
        ,SiestaKey
        ,StArmandsCircle
        ,UniversityPark
        ,Venice
        ,VeniceIsland
       ];
    }
    else if (searchCountyName == 'Manatee')
    {
        //   fillcolor = ['#002D56', '#385B7B', '#768FA5'];//, '#BADBEE' '#01528A';
        var AnnaMariaIsland = '#01528A';
        var Bradenton = '#768FA5';
        var BradentonBeach = '#002D56';
        var BradentonEast = '#385B7B';
        var BradentonWest = '#002D56';
        var EastManatee = '#002D56';
        var Ellenton = '#BADBEE';
        var HolmesBeach = '#768FA5';
        var IMGAcademies = '#01528A';
        var LakewoodRanch = '#01528A';
        var LongboatKey =  '#BADBEE';
        var Palmetto = '#385B7B';
        var Parrish =  '#01528A';
        var UniversityPark =  '#768FA5';
       
           fillcolor = [
            AnnaMariaIsland
            ,Bradenton
            ,BradentonBeach
            ,BradentonEast
            ,BradentonWest
            ,EastManatee
            ,Ellenton
            ,HolmesBeach
            ,IMGAcademies
            ,LakewoodRanch
            ,LongboatKey
            ,Palmetto
            ,Parrish
            ,UniversityPark
           ];
            
    }
    else if (searchCountyName == 'Charlotte')
    {
        fillcolor = ['#002D56', '#385B7B', '#01528A' , '#002D56', '#768FA5', '#01528A', '#768FA5'];
   
    }
    else
    {
         fillcolor = ['#002D56', '#385B7B', '#768FA5'];
    }
    // Set the colors on the map. 
    var strokecolor = '#FFFFFF';
    for (var i = 0; i < locations.length; i++) {

        var community = locations[i];
        var boundaries = community[2];
        var communityPolygon = new google.maps.Polygon({
            paths: boundaries,
            strokeColor: strokecolor,
            strokeOpacity: 0.8,
            strokeWeight: 2.0,
            fillColor: fillcolor[i % fillcolor.length],
            fillOpacity: 0.7
        });
        communityPolygon.setMap(map);
    }

   // }

//    else {

//        var strokecolor = '#7777CC';
//        var fillcolor = '#CCCCff';
//        for (var i = 0; i < locations.length; i++) {

//            var community = locations[i];
//            var boundaries = community[2];
//            var communityPolygon = new google.maps.Polygon({
//                paths: boundaries,
//                strokeColor: strokecolor,
//                strokeOpacity: 0.8,
//                strokeWeight: 2.0,
//                fillColor: fillcolor,
//                fillOpacity: 0.2
//            });
//            communityPolygon.setMap(map);
//        }
//    }
}

/*
*
* General purpose map functions.
*/

/*
* SetMarkers - adds an array of locations to the map as markers.
* map:  the map we are adding markers to
* locations: [[locations] [map boundaries]]
*/
function SetMarkers(map, locations) {

    for (var i = 0; i < locations.length; i++) {

        var community = locations[i];
                
        var locationInfo = community[0];
                
        var centerpoint = community[1];
        var cLatLng = new google.maps.LatLng(centerpoint[0], centerpoint[1]);
        var html = community[3];

        AddMarkerToMap(i + 1, locationInfo, cLatLng, html, map);
    }
}

function MSMarkerClick(i) {
google.maps.event.trigger(gmarkers[i], 'click');
}

/*
*  count: 1-based marker number
*  locationInfo: [id,'name','altos city']
*  cLatLng:  google LatLng postion for the marker
*  html:  the infowindow html for this marker
*  map:  the map we are adding the marker to
*
*/
function AddMarkerToMap(count, locationInfo, cLatLng, html, map) {

    var shadow;
    var image;
    var marker;
    var id = locationInfo[0];
    var title = locationInfo[1];
 
    if (title == 'Manatee' || title == 'Sarasota' || title == 'Charlotte') {

        var imageDirectory = '';
        var imageAnchorManatee = null;
        var imageAnchorSarasota = null;
        var imageAnchorCharlotte = null;
        
        var imageSizeManatee = null;
        var imageSizeSarasota = null;
        var imageSizeCharlotte = null;
        
        if (pagename == 'properties/search.aspx'){
               imageDirectory = '/images/map/small/';
               
               imageAnchorManatee = new google.maps.Point(60,10);
               imageAnchorSarasota = new google.maps.Point(40, 0);
               imageAnchorCharlotte = new google.maps.Point(35, 10);
               
               imageSizeManatee =  new google.maps.Size(100, 20);
               imageSizeSarasota =  new google.maps.Size(116, 20);
               imageSizeCharlotte = new google.maps.Size(100, 20);
               
        }
        else{
               imageDirectory = '/images/map/';
           
              // imageAnchorManatee = new google.maps.Point(80,25);
               imageAnchorManatee = new google.maps.Point(60, 15);
              
              // imageAnchorSarasota = new google.maps.Point(60, 0);
               imageAnchorSarasota = new google.maps.Point(35, -10);
              

              // imageAnchorCharlotte = new google.maps.Point(60, 0);
               imageAnchorCharlotte = new google.maps.Point(25, 10);
           

            imageSizeManatee =  new google.maps.Size(200, 100);
            imageSizeSarasota =  new google.maps.Size(116, 60);
            imageSizeCharlotte = new google.maps.Size(200, 100);
        }
            
        if (title == 'Manatee') {
        
            //  cLatLng = new google.maps.LatLng(27.508271, -82.468185);
            image = new google.maps.MarkerImage(imageDirectory + title + '.png',
                //  image size 
                  imageSizeManatee,
                // The image origin. 
                  new google.maps.Point(0, 0),
                // The imageanchor. - this pixel is positioned at the marker lat/lng
                  imageAnchorManatee);
        }
        if (title == 'Sarasota') {

            //cLatLng = new google.maps.LatLng(27.133702, -82.451019);
            //image = '/images/map/' + title + '.png';
            image = new google.maps.MarkerImage(imageDirectory + title + '.png',
            //  image size 
             imageSizeSarasota,
            // The image origin. 
              new google.maps.Point(0, 0),
            // The imageanchor. - this pixel is positioned at the marker lat/lng
              imageAnchorSarasota);
        }
        if (title == 'Charlotte') {
            //cLatLng = new google.maps.LatLng(26.853479,-81.938782);
            image = new google.maps.MarkerImage(imageDirectory + title + '.png',
            //  image size 
              imageSizeCharlotte,
            // The image origin. 
              new google.maps.Point(0, 0),
            // The imageanchor. - this pixel is positioned at the marker lat/lng
              imageAnchorCharlotte);
        }


        marker = new google.maps.Marker({
            position: cLatLng,
            map: map,
            icon: image,
            title: title
        });

        google.maps.event.addListener(marker, 'click', function() {
            
            // County marker click handler.
            if (pagename == 'neighborhood-maps/default.aspx') {

                ResizeColorbox(baseurl + pagename + "?name=" + title + "&type=County", "1000px", "700px");
            }
            else if (pagename == 'properties/search.aspx') {
                var searchRedirectURL = baseurl + "properties/" +   title.toLowerCase() + "-county-areas/";
                window.location.href = searchRedirectURL;
            }
            else {

                window.location.href = baseurl + "areas/" + title.toLowerCase() + "-county-areas/";

            }
        });

    }
    else {

        shadow = new google.maps.MarkerImage('/images/map/shadow50.png',
          new google.maps.Size(37, 34),
        // the origin for the image,
          new google.maps.Point(0, 0),
        // the anchor point for images attached 
          new google.maps.Point(8, 18));

        image = new google.maps.MarkerImage('/images/map/iconr' + count + '.png',
        //  20px by 32px 
          new google.maps.Size(20, 34),
        // The image origin. 
          new google.maps.Point(0, 0),
        // The imageanchor.
          new google.maps.Point(10, 17));
        marker = new google.maps.Marker({
            position: cLatLng,
            map: map,
            icon: image,
            title: title
        , shadow: shadow
        });

        google.maps.event.addListener(marker, 'click', function() {

            infowindow.setContent(html);
            GetServiceDataForInfoWindow(map, locationInfo)
            infowindow.open(map, marker);

            
            if ($("#ctl00_cphMainPage_pnlCommunityList").length != 0) {
                // Position the rhs info to be fully viewable in the panel.
                $("#ctl00_cphMainPage_pnlCommunityList").scrollTo($(".marker" + count), 800);
            }
            else {
                $("#pnlCommunityList").scrollTo($(".marker" + count), 800);

            }

            // Highlight the description rows that we just focused.
            $("tr").removeClass("highlighted");
            $(".marker" + count).addClass("highlighted");

            // Hide all of the markers except the selected one.
            for (var i = 0; i < gmarkers.length; i++) {

                if (gmarkers[i] != marker) {
                    gmarkers[i].setVisible(false);
                }
            }
            marker.setVisible(true);

        });

    } // end else
    gmarkers.push(marker);
   
   
    // add a call on the marker image link in the rhs list that triggers the map marker click handler
   // $("#marker" + gmarkers.length).attr('href', 'javascript: myclick(' + (gmarkers.length - 1) + ');');

     // NOTE: settting the click function changes the page focus when the hrefs are clicked.
     // Setting the href as below does not do this?  
     // Have to create this string here to make the parameter to myclick static on this marker number.  
     //var markernumber = '' + (gmarkers.length - 1) + '';
     //$(".marker" + gmarkers.length + "-link").click(function() { myclick(markernumber); });
     
     
     $(".marker" + gmarkers.length + "-link").attr('href', 'javascript: MSMarkerClick(' + (gmarkers.length - 1) + ');');


} //end AddMarkerToMap


function ResizeColorbox(targetURL, width, height) {
    parent.$.fn.colorbox({ width: width, height: height,
        iframe: true, href: targetURL
    });
    $.fn.colorbox.resize();
}

/*
*  Street view and street view service call functions.
*/
function AddStreetview(marker) {
    var newpos = marker.getPosition();
    newpos = new google.maps.LatLng(newpos.lat(), newpos.lng());
    sv.getNearestPanorama(newpos, 50,
                function(data, status) {
                    if (status == google.maps.StreetViewStatus.OK) {
                        //alert('returned ok');
                        processSVData(data, status, id);
                    }
                    else if (status == google.maps.StreetViewStatus.ZERO_RESULTS) {
                        // a little over 1 mile.
                        sv.getNearestPanorama(newpos, 1805, function(data, status) {
                            if (status == google.maps.StreetViewStatus.OK) {
                                processSVData(data, status, id);
                            } else if (status == google.maps.StreetViewStatus.ZERO_RESULTS) {
                                //  go up to 5 miles. 
                                sv.getNearestPanorama(newpos, 8046, processSVStatus);
                            }
                        });
                    }
                    else {
                        //alert('some other status (unknown error)');
                    }
                }
            );
}

function processSVStatus(data, status) {
    if (status == google.maps.StreetViewStatus.OK) {
        processSVData(data, status);

    }
//    else if (status == google.maps.StreetViewStatus.ZERO_RESULTS) {
//        alert('no results found')
//       
//    }
//    else {
//        alert('some other status (unknown error)');
//    }
}

function processSVData(data, status, id) {

    if (status == google.maps.StreetViewStatus.OK) {
//        var marker = new google.maps.Marker({
//            position: data.location.latLng,
//            map: map,
//            title: data.location.description
//        });

//        google.maps.event.addListener(marker, 'click', function() {

//            var markerPanoID = data.location.pano;
//            // Set the Pano to use the passed panoID 
//            panorama.setPano(markerPanoID);
//            panorama.setPov({
//                heading: 270,
//                pitch: 0,
//                zoom: 1
//            });
//            panorama.setVisible(true);
        //        });


        var streetviewOptions = {
            position: data.location.latLng 
            //, addressControl: true
			   , navigationControl: true
			   , pov: {
			       heading: 34,
			       pitch: 10,
			       zoom: .5
			   }
		};

		
        // Show the streetview in an info window (with appropriately named div).
		var mystreetview = document.getElementById("street_view_" + id);
		if (mystreetview != null) {
		    // set street view in the info window.
            streetViewPanorama = new google.maps.StreetViewPanorama(
					mystreetview,
					streetviewOptions
				);
		}
       
       //    OR
       // Show the streetview on the map.
		var mystreetview = map.getStreetView();
		if (mystreetview != null) {

		    mystreetview.setPosition(data.location.latLng);
		    mystreetview.setPov({
		        heading: 34,
		        pitch: 10,
		        zoom: .5
		    });
		    mystreetview.setVisible(true);
		    // End show streetview on map.
        }
    }
}

