var map;
var lats = [];
var longs = [];
var points = [];
var hoursTabs = [];
var locationTabs = [];
var mapIcon = [];
var gmarkers = [];
var gmarkershtml = []; 
var htmlDescrip = []; 
var addresses = []; 
var plotAllBounds; // = new GLatLngBounds();     
var totalPoints;
var totalLats = 0;
var totalLongs = 0;
var listHTML = "";
var geocoder; // = new GClientGeocoder();
var directionsPanel;  
var directions; 
var fromPoint;
var toPoint; 
var fromAddress = ""; 
var toAddress = "";
var dir = "";
var circle;             // Object for zipcode radius shading
var circlecenter;;      // Centerpoint for zipcode Radius
var opacity = 0.3;      // Opacity for zipcode radius circle
var centerMarker;       
var circleUnits;
var circleRadius;

function mapInitialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("mapCanvas"));
        plotAllBounds = new GLatLngBounds();
        geocoder =   new GClientGeocoder();
        totalPoints = theData.points.length;
        if (window.attachEvent) {
            window.attachEvent("onbeforeunload", function() { GUnload; }); // THIS STUPID LINE TOOK 2 HOURS TO WRITE
        }  
        if (geocoder) {
            var theZip = gup("zip");
            if (theZip == "") theZip = "80134";        
            geocoder.getLatLng(
                theZip,
                function(point) {
                    if (!point) {
                        alert("zip not found");
                    } else {
                    map.setCenter(point, 14, G_PHYSICAL_MAP);
                    }
                }
            );
        }
        map.addControl(new GSmallMapControl(), new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 20)));
        map.addControl(new GMapTypeControl(), new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 10)));
  	    // Remove unwanted map overlays
  	    map.removeMapType(G_SATELLITE_MAP); 
  	    map.removeMapType(G_HYBRID_MAP); 
  	    map.addMapType(G_PHYSICAL_MAP);
  	    GEvent.addListener(map, "load", function() {
  	        initMap(); 
  	    });
    }
}

function initMap() {
    theRadius = gup("radius");
    if (showUS == 0 && showState == 0) {
        
        if (theRadius != "") {
            if (IsNumeric(theRadius) == true) {
                circlecenter = map.getCenter();
                drawCircle(theRadius);
            }
        }
    } else {
        if (showUS == 1) {
            var theUSPoint = new GLatLng(38.4902400, -94.2128910);
            map.setCenter(theUSPoint, 4, G_PHYSICAL_MAP);

        }
        if (showState == 1) {
            var theStatePoint = new GLatLng(stateLat, stateLong);
            map.setCenter(theStatePoint, stateZoom, G_PHYSICAL_MAP);
        }
    }

    
    plotAllBounds = new GLatLngBounds();
    var totalLats = 0;
    var totalLongs = 0;
    for (var i = 0; i < totalPoints; i++) {
        totalLats = totalLats + parseFloat(theData.points[i].lat);
        totalLongs = totalLongs + parseFloat(theData.points[i].long);
        var thePoint = new GLatLng(theData.points[i].lat, theData.points[i].long);
        plotAllBounds.extend(thePoint);
        createMarker(thePoint, i, "../siteImages/maps/numberedIcons/" + parseInt(i + 1) + ".png",0); //plot the point
    }
    for (var i = 0; i < theOutlierData.points.length; i++) {
        var thePoint = new GLatLng(theOutlierData.points[i].lat, theOutlierData.points[i].long);
        createMarker(thePoint, i, "../siteImages/maps/numberedIcons/blank.png",1); //plot the point
    }
    for (var i = 0; i < theHomeGalleryData.points.length; i++) {
        var thePoint = new GLatLng(theHomeGalleryData.points[i].lat, theHomeGalleryData.points[i].long);
        createMarker(thePoint, i, "../siteImages/maps/hgIcon.png", 2); //plot the point
    }
    if (theRadius == "") {
        // Center the map based on average of all points
        if (totalPoints != 0) {
            var avgLat = totalLats / totalPoints;
            var avgLong = totalLongs / totalPoints;
            var plotallzoom = map.getBoundsZoomLevel(plotAllBounds);
            if (plotallzoom > 15) plotallzoom = 15;
            var mapCenter = plotAllBounds.getCenter();
            map.setCenter(mapCenter, plotallzoom, G_PHYSICAL_MAP);
        }
    }

}

function createMarker(point, theIndex, theIcon, outlierFlag) {
    var marker;
    var icon = new GIcon();
    icon.image = theIcon;
    icon.iconSize = new GSize(23, 23);
    icon.shadow = "";
    icon.shadowSize = new GSize(0, 0);
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(16, 16);
    icon.infoShadowAnchor = new GPoint(0, 0);


        if (outlierFlag == 0) {
            var options = {
                draggable: false,
                bouncy: false,
                title: theData.points[theIndex].name + " " + theData.points[theIndex].startingPrice.toLowerCase(),
                icon: icon
            };
            marker = new GMarker(point, options);
        } else if (outlierFlag == 2) {
            var options = {
                draggable: false,
                bouncy: false,
                title: theHomeGalleryData.points[theIndex].name,
                icon: icon
            };
            marker = new GMarker(point, options);
        } else {
            var options = {
                draggable: false,
                bouncy: false,
                title: theOutlierData.points[theIndex].name + " " + theOutlierData.points[theIndex].startingPrice.toLowerCase(),
                icon: icon
            };
            marker = new GMarker(point, options);
        }
    // Add Info Card
        GEvent.addListener(marker, 'click', function() {
            if (outlierFlag == 0) {
                marker.openExtInfoWindow(
                 map,
                 "CommunityInfoCard",
                 "<div class=\"communityInfoCard png\"><a href=\"#\" onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class=\"x\"></a><div class=\"communityInfoCardImage\"><img src=\"" + theData.points[theIndex].infoCardImage + "\" /></div><div class=\"communityInfoCardInfo\"><strong>Homes " + theData.points[theIndex].startingPrice.toLowerCase() + "</strong><br />" + theData.points[theIndex].sizeRange + " sq. ft.<br/><br/> " + theData.points[theIndex].infoCardCopy + "<br/>" + theData.points[theIndex].address + "</div><a href=\"" + theData.points[theIndex].communityLink + "\">VIEW HOMES</a></div>",
                { beakOffset: -20, paddingX: 130, paddingY: 105 }
            );
            } else if (outlierFlag == 2) {
                marker.openExtInfoWindow(
                 map,
                 "CommunityInfoCard",
                 "<div class=\"communityInfoCard png\"><a href=\"#\" onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class=\"x\"></a><div class=\"communityInfoCardImage\"><img src=\"" + theHomeGalleryData.points[theIndex].infoCardImage + "\" /></div><div class=\"communityInfoCardInfo\">" + theHomeGalleryData.points[theIndex].name + "<br/><br/>"  + theHomeGalleryData.points[theIndex].address + "<br/><br/>"  + theHomeGalleryData.points[theIndex].hours + "</div><a href=\"../Discover-Home-Gallery/Channel-Landing.aspx?Overview=1\">VIEW HOME GALLERIES</a></div>",
                { beakOffset: -20, paddingX: 130, paddingY: 105 }
                );
            } else {
                marker.openExtInfoWindow(
                 map,
                 "CommunityInfoCard",
                 "<div class=\"communityInfoCard png\"><a href=\"#\" onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class=\"x\"></a><div class=\"communityInfoCardImage\"><img src=\"" + theOutlierData.points[theIndex].infoCardImage + "\" /></div><div class=\"communityInfoCardInfo\"><strong>Homes " + theOutlierData.points[theIndex].startingPrice.toLowerCase() + "s</strong><br />" + theOutlierData.points[theIndex].sizeRange + " sq. ft.<br/><br/> " + theOutlierData.points[theIndex].infoCardCopy + "<br/><br/>" + theOutlierData.points[theIndex].address + "</div><a href=\"" + theOutlierData.points[theIndex].communityLink + "\">VIEW HOMES</a></div>",
                { beakOffset: -20, paddingX: 130, paddingY: 105 }
            );
            }
        });

    if (outlierFlag == 0) {
        gmarkers[theIndex] = marker;
    } else if (outlierFlag == 2) {
        gmarkers[gmarkers.length + 1] = marker;
    } else {
        gmarkers[gmarkers.length + 1] = marker;
    }
    

    map.addOverlay(marker);
}


//function createMarker(point, theIndex, theIcon, outlierFlag) {
//    var marker;
//    var icon = new GIcon();
//    icon.image = theIcon;
//    icon.iconSize = new GSize(23, 23);
//    icon.shadow = "";
//    icon.shadowSize = new GSize(0, 0);
//    icon.iconAnchor = new GPoint(16, 16);
//    icon.infoWindowAnchor = new GPoint(16, 16);
//    icon.infoShadowAnchor = new GPoint(0, 0);
//    marker = new GMarker(point, icon);
//    // Add Info Card
//    GEvent.addListener(marker, 'click', function() {
//        if (outlierFlag == 0) {
//            marker.openExtInfoWindow(
//                 map,
//                 "CommunityInfoCard",
//                 "<div class=\"communityInfoCard png\"><a href=\"#\" onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class=\"x\"></a><div class=\"communityInfoCardImage\"><img src=\"" + theData.points[theIndex].infoCardImage + "\" /></div><div class=\"communityInfoCardInfo\"><strong>Homes " + theData.points[theIndex].startingPrice.toLowerCase() + "</strong><br />" + theData.points[theIndex].sizeRange + " sq. ft.<br/><br/> " + theData.points[theIndex].infoCardCopy + "<br/><br/>" + theData.points[theIndex].address + "</div><a href=\"" + theData.points[theIndex].communityLink + "\">VIEW HOMES</a></div>",
//                { beakOffset: -20, paddingX: 130, paddingY: 105 }
//            );
//        } else {
//            marker.openExtInfoWindow(
//                 map,
//                 "CommunityInfoCard",
//                 "<div class=\"communityInfoCard png\"><a href=\"#\" onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class=\"x\"></a><div class=\"communityInfoCardImage\"><img src=\"" + theOutlierData.points[theIndex].infoCardImage + "\" /></div><div class=\"communityInfoCardInfo\"><strong>Homes " + theOutlierData.points[theIndex].startingPrice.toLowerCase() + "s</strong><br />" + theOutlierData.points[theIndex].sizeRange + " sq. ft.<br/><br/> " + theOutlierData.points[theIndex].infoCardCopy + "<br/><br/>" + theOutlierData.points[theIndex].address + "</div><a href=\"" + theOutlierData.points[theIndex].communityLink + "\">VIEW HOMES</a></div>",
//                { beakOffset: -20, paddingX: 130, paddingY: 105 }
//            );
//        }
//    });
//    GEvent.addListener(marker, 'mouseover', function() {
//        if (outlierFlag == 0) {

//            var overPath = theIcon.replace(".png", "_h.png");
//            marker.remove();
//            createMarkerOver(point, theIndex, overPath, outlierFlag);
// 



//            marker.openExtInfoWindow(
//            map,
//             "infoCard",
//             "<div class='infoCard_contents2 png'><div class='cardBorder'><a href='#' onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class='cardClose'>close</a><div class='cardCopy'><strong>" + theData.points[theIndex].name + "</strong><br/>" + theData.points[theIndex].startingPrice.toLowerCase() + "<br/></div></div></div>",
//             { beakOffset: -20, paddingX: 130, paddingY: 105 }
//            );
//        } else {
//            marker.openExtInfoWindow(
//            map,
//             "infoCard",
//             "<div class='infoCard_contents2 png'><div class='cardBorder'><a href='#' onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class='cardClose'>close</a><div class='cardCopy'><strong>" + theOutlierData.points[theIndex].name + "</strong><br/>" + theOutlierData.points[theIndex].startingPrice.toLowerCase() + "<br/></div></div></div>",
//             { beakOffset: -20, paddingX: 130, paddingY: 105 }
//            );
//        }
//    });

//    
//    
//    gmarkers[theIndex] = marker; 
//    map.addOverlay(marker);
//}



function createMarkerOver(point, theIndex, theIcon, outlierFlag) {
    var marker;
    var icon = new GIcon();
    icon.image = theIcon;
    icon.iconSize = new GSize(23, 23);
    icon.shadow = "";
    icon.shadowSize = new GSize(0, 0);
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(16, 16);
    icon.infoShadowAnchor = new GPoint(0, 0);
    marker = new GMarker(point, icon);
    // Add Info Card
    GEvent.addListener(marker, 'click', function() {
        if (outlierFlag == 0) {
            marker.openExtInfoWindow(
                 map,
                 "CommunityInfoCard",
                 "<div class=\"communityInfoCard png\"><a href=\"#\" onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class=\"x\"></a><div class=\"communityInfoCardImage\"><img src=\"" + theData.points[theIndex].infoCardImage + "\" /></div><div class=\"communityInfoCardInfo\"><strong>Homes " + theData.points[theIndex].startingPrice.toLowerCase() + "</strong><br />" + theData.points[theIndex].sizeRange + " sq. ft.<br/><br/> " + theData.points[theIndex].infoCardCopy + "<br/><br/>" + theData.points[theIndex].address + "</div><a href=\"" + theData.points[theIndex].communityLink + "\">VIEW HOMES</a></div>",
                { beakOffset: -20, paddingX: 130, paddingY: 105 }
            );
        } else {
            marker.openExtInfoWindow(
                 map,
                 "CommunityInfoCard",
                 "<div class=\"communityInfoCard png\"><a href=\"#\" onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class=\"x\"></a><div class=\"communityInfoCardImage\"><img src=\"" + theOutlierData.points[theIndex].infoCardImage + "\" /></div><div class=\"communityInfoCardInfo\"><strong>Homes " + theOutlierData.points[theIndex].startingPrice.toLowerCase() + "s</strong><br />" + theOutlierData.points[theIndex].sizeRange + " sq. ft.<br/><br/> " + theOutlierData.points[theIndex].infoCardCopy + "<br/><br/>" + theOutlierData.points[theIndex].address + "</div><a href=\"" + theOutlierData.points[theIndex].communityLink + "\">VIEW HOMES</a></div>",
                { beakOffset: -20, paddingX: 130, paddingY: 105 }
            );
        }
    });
    GEvent.addListener(marker, 'mouseout', function() {
        if (outlierFlag == 0) {

            var oldPath = theIcon.replace("_h.png", ".png");
            createMarker(point, theIndex, oldPath, outlierFlag);
            marker.remove();
            map.closeExtInfoWindow(); 



        } else {
            createMarker(point, theIndex, theIcon, outlierFlag);
            marker.remove();
        }
    });


    gmarkers[theIndex] = marker;
    map.addOverlay(marker);
}



function centerOn(i) {
    
    gmarkers[i].openExtInfoWindow(
             map,
             "infoCard",
             "<div class=\"communityInfoCard\"><a href=\"#\" onfocus=\"this.blur();\" onclick='javascript:map.closeExtInfoWindow();return false' class=\"x\"></a><div class=\"communityInfoCardImage\"></div><div class=\"communityInfoCardInfo\"><strong>Homes from $220s</strong><br />2,100 - 2,950 sq. ft.<br /><br />Take advantage of special pricing for 3 and 4 bedroom homes.<br /><br />96th Avenue & Chambers Road<br />Aurora, CO<br />80016</div><a href=\"#\">VIEW HOMES</a></div>",
          { beakOffset: -20, paddingX: 130, paddingY: 105 }
    );
    map.setCenter(new GLatLng(parseFloat(theData.points[i].lat), parseFloat(theData.points[i].long)), 14);
}

function drawCircle(rad) {
    circleRadius = rad;
    circleUnits = 'MI';
    doDrawCircle();
}


function doDrawCircle() {
    circlecenter = map.getCenter();
    if (circle) {
        map.removeOverlay(circle);
    }

    var center = circlecenter;

    var bounds = new GLatLngBounds();


    var circlePoints = Array();

    with (Math) {
        if (circleUnits == 'KM') {
            var d = circleRadius / 6378.8; // radians
        }
        else { //miles
            var d = circleRadius / 3963.189; // radians
        }

        var lat1 = (PI / 180) * center.lat(); // radians
        var lng1 = (PI / 180) * center.lng(); // radians

        for (var a = 0; a < 361; a++) {
            var tc = (PI / 180) * a;
            var y = asin(sin(lat1) * cos(d) + cos(lat1) * sin(d) * cos(tc));
            var dlng = atan2(sin(tc) * sin(d) * cos(lat1), cos(d) - sin(lat1) * sin(y));
            var x = ((lng1 - dlng + PI) % (2 * PI)) - PI; // MOD function
            var point = new GLatLng(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI)));
            circlePoints.push(point);
            bounds.extend(point);
        }

        if (d < 1.5678565720686044) {
            circle = new GPolygon(circlePoints, '#000000', 1, 0.25, '#000000', 0.25);
        }
        else {
            circle = new GPolygon(circlePoints, '#000000', 1, 0.25);
        }
        map.addOverlay(circle);

        map.setZoom(map.getBoundsZoomLevel(bounds));
    }
}

function IsNumeric(sText) {
    var ValidChars = "0123456789";
    var IsNumber = true;
    var Char;
    for (i = 0; i < sText.length && IsNumber == true; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1) {
            IsNumber = false;
        }
    }
    return IsNumber;
}





