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;
var cluster;

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(); 
  	    });
    }
    
     if($.browser.msie && $.browser.version < 7) {        
        $(".mapLinkImg").each(function(){
            var imgSrc = $(this).attr("src");
            $(this).attr("src", "/common/images/blank.gif");
            $(this).css("filter", "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgSrc + "', sizing='scale')");
        });
    }
}

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;
    
    var marker, markersArray = [];
    
    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);
        // marker = createMarker(thePoint, i, "/common/images/pin" + parseInt(i + 1) + ".png",0);
        marker = createMarker(thePoint, i, "/common/images/cgmapimg.php?img=pin&x=8&y=4&txt=" + parseInt(i + 1), 0);
        markersArray.push(marker);
    }
    for (var i = 0; i < theOutlierData.points.length; i++) {
        var thePoint = new GLatLng(theOutlierData.points[i].lat, theOutlierData.points[i].long);
        if($.browser.msie && $.browser.version < 7) {
            // marker = createMarker(thePoint, i, "/common/images/pin_00.png?i=" + parseInt(i + 1) ,1);
            marker = createMarker(thePoint, i, "/common/images/pin.png?i=" + parseInt(i + 1), 1);
        }
        else {
        	// marker = createMarker(thePoint, i, "/common/images/pin_0.png?i=" + parseInt(i + 1) ,1);
        	marker = createMarker(thePoint, i, "/common/images/pin.png?i=" + parseInt(i + 1), 1);
        }  
        markersArray.push(marker);
    }
    for (var i = 0; i < theHomeGalleryData.points.length; i++) {
        var thePoint = new GLatLng(theHomeGalleryData.points[i].lat, theHomeGalleryData.points[i].long);
        var hgMarker =  createMarker(thePoint, i, "/common/images/HG_logo.png", 2); 
        map.addOverlay(hgMarker);
    }
    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);
        }
    }  

    //alert();
    cluster=new ClusterMarker(map, { markers:markersArray} );       
    //cluster.intersectPadding = 0;  //this will determine the number (neg or pos) in pixels that surround each marker's icon to determine if it intersects with any nearby markers. 
    cluster.clusterMarkerTitle='%count communities See details';
    
    cluster.clusterMarkerClick = function(args) {         
        cluster.defaultClickAction=function(){
	    	map.setCenter(args.clusterMarker.getLatLng(), map.getBoundsZoomLevel(args.clusterMarker.clusterGroupBounds))
		    map.closeExtInfoWindow();
		    delete cluster.defaultClickAction;
        }
        
        var html = '<div class=\"communityClusterInfoCard png\"><a href=\"#\" onfocus=\"this.blur();\" onclick="javascript:map.closeExtInfoWindow();return false" class=\"x\"></a><div class="communityClusterInfoCardInfo"><div class="communityClusterInfoCardHeader"><img src="' + args.clusterMarker.getIcon().image + '"><div>We have more than one community in this area!<br/><a href="#" onclick="cluster.defaultClickAction()" >Click to zoom.</a></div></div><ul>';                        
        for(var i = 0; i< args.clusteredMarkers.length; i++) {
            var communityIndex = (args.clusteredMarkers[i].getIcon().image.replace("/common/images/pin","").replace(".png","")) - 1;
            if(communityIndex > -1) {            
                if($.browser.msie && $.browser.version < 7) {                   
                    html += '<li><img src="/common/images/blank.gif" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + args.clusteredMarkers[i].getIcon().image + '\', sizing=\'scale\')" alt="" class="png"/>' + '<span class="txt"><a href="' + theData.points[communityIndex].communityLink + '">' + theData.points[communityIndex].name + '</a> - <span>' +  theData.points[communityIndex].startingPrice + '</span></span></li>';
                }
                else {
                    html += '<li><img src="' + args.clusteredMarkers[i].getIcon().image + '" alt="" class="png"/>' + '<span class="txt"><a href="' + theData.points[communityIndex].communityLink + '">' + theData.points[communityIndex].name + '</a> - <span>' +  theData.points[communityIndex].startingPrice + '</span></span></li>';            
                }
            }
            else {                            
                if($.browser.msie && $.browser.version < 7) {                   
                    communityIndex = (args.clusteredMarkers[i].getIcon().image.replace("/common/images/pin.png?i=","")) - 1;               
                    html += '<li><img src="/common/images/blank.gif" style="filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/common/images/pin.png\', sizing=\'scale\')" alt="" class="png"/>' + '<span class="txt"><a href="' + theData.points[communityIndex].communityLink + '">' + theData.points[communityIndex].name + '</a> - <span>' +  theData.points[communityIndex].startingPrice + '</span></span></li>';
                }
                else {                
                    communityIndex = (args.clusteredMarkers[i].getIcon().image.replace("/common/images/pin.png?i=","")) - 1;               
                    html += '<li><img src="/common/images/pin.png" alt="" class="png"/>' + '<span class="txt"><a href="' + theData.points[communityIndex].communityLink + '">' + theData.points[communityIndex].name + '</a> - <span>' +  theData.points[communityIndex].startingPrice + '</span></span></li>'            
                }
            }
        }
        html += '</ul></div></div>';
                
        args.clusterMarker.openExtInfoWindow(
            map,
            "CommunityInfoCard",
            html,
            { beakOffset: -20, paddingX: 130, paddingY: 105 }
        );
        
        var mylist = $('.communityClusterInfoCard ul');
        var listitems = mylist.children('li').get();
        listitems.sort(function(a, b) {
            var compA = $(a).attr("class") - 0;
            var compB = $(b).attr("class") - 0;
            return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
        })
        $.each(listitems, function(idx, itm) { mylist.append(itm); });        
    }; 
    cluster.fitMapToMarkers();    
}

function newMarker(markerLocation, theIndex) {
    var marker=new GMarker(markerLocation, {title:'Marker['+theIndex+']'});
    GEvent.addListener(marker, 'click', function() {        
       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 }
        );
    });
    return marker;
}

function createMarker(point, theIndex, theIcon, outlierFlag) {
    var marker;
    var icon = new GIcon();
    icon.image = theIcon;
    icon.iconSize = new GSize(22, 33);
    icon.shadow = "/common/images/pin_shadow.png";
    icon.shadowSize = new GSize(37, 33);
    icon.iconAnchor = new GPoint(11, 33);
    icon.infoWindowAnchor = 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) {
       icon.iconSize = new GSize(30, 30);
        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 }
        );
        }
    });
    
    GEvent.addListener(marker, 'mouseover', function() {
        if(outlierFlag!=2) {
            if(!($.browser.msie && $.browser.version < 7)) {
              // $("img[src*='" +  icon.image.replace("../","") +"']").attr("src", icon.image.replace(".png", "_hover.png"));
              $("img[src*='" +  icon.image.replace("../","") +"']").attr("src", icon.image.replace("pin", "pin_hover"));            	
            }
        }        
    });
    
    GEvent.addListener(marker, 'mouseout', function() {
        if(outlierFlag!=2) {
            if(!($.browser.msie && $.browser.version < 7)) {
             $("img[src*='" +  icon.image.replace("../","").replace("pin", "pin_hover") +"']").attr("src", icon.image); 
            }
        }
    });

    if (outlierFlag == 0) {
        gmarkers[theIndex] = marker;
    } else if (outlierFlag == 2) {
        gmarkers[gmarkers.length + 1] = marker;
    } else {
        gmarkers[gmarkers.length + 1] = marker;
    }
    
    return 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;
}

