﻿var $j = jQuery.noConflict();

//Add min and max prototype methods to all javascript arrays
Array.prototype.max = function () {
    return Math.max.apply(Math, this);
};

Array.prototype.min = function () {
    return Math.min.apply(Math, this);
};

Object.prototype.getElementWidth = function () {
    if (typeof this.clip !== "undefined") {
        return this.clip.width;
    } else {
        if (this.style.pixelWidth) {
            return this.style.pixelWidth;
        } else {
            return this.offsetWidth;
        }
    }
}

// Seperate latitudes and longitudes to individual arrays.
var latitudes = [];
var longitudes = [];
var gmarkers = [];
var latstore;
var longstore;
var schoolson = false;
var starbuckson = false;
var map;
var baseIcon;

if (communityData != '') {
    $j.each(communityData, function (index, value) {
        latitudes.push(parseFloat(value[0]));
        longitudes.push(parseFloat(value[1]));
    });

    var longitudeMin = longitudes.min();
    var longitudeMax = longitudes.max();
    var latitudeMin = latitudes.min();
    var latitudeMax = latitudes.max();

    var centerLongitude = longitudeMin + (longitudeMax - longitudeMin) / 2;
    var centerLatitude = latitudeMin + (latitudeMax - latitudeMin) / 2;
    var mapCenterPoint = new GLatLng(centerLatitude, centerLongitude);

    //var mapWidth = Element.getDimensions("map").width;

    var mapElement = document.getElementById('map');
    //var mapWidth = mapElement.getElementWidth();


    var mapSouthWestPoint = new GLatLng(latitudeMin, longitudeMin);
    var mapNorthEastPoint = new GLatLng(latitudeMax, longitudeMax);
    var mapBounds = new GLatLngBounds(mapSouthWestPoint, mapNorthEastPoint)
}


function communityHover(i) {
    if (gmarkers[i] != null)
        GEvent.trigger(gmarkers[i], "click");
}

function MapMoved() {
    var left = map.getBounds().getSouthWest().lat();
    var right = map.getBounds().getNorthEast().lat();

    var leftLong = map.getBounds().getSouthWest().lng();
    var rightLong = map.getBounds().getNorthEast().lng();
}

function load() {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    //GEvent.addListener(map, 'moveend', function() {
    //    MapMoved();
    //}); 

    var zoomLevel;
    if (longitudeMin == longitudeMax && latitudeMin == latitudeMax)
        zoomLevel = 13;
    else
        zoomLevel = map.getBoundsZoomLevel(mapBounds);
    map.setCenter(mapCenterPoint, zoomLevel);

    // Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    baseIcon = new GIcon();

    baseIcon.shadow = BasePath + "images/FlagShadow.png";
    baseIcon.iconSize = new GSize(27, 40);
    baseIcon.shadowSize = new GSize(41, 40);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    baseIcon.infoShadowAnchor = new GPoint(18, 25);

    mapload();
    if (schoolson) {
        schoolson = false;
        LoadSchools();
    }
    if (starbuckson) {
        starbuckson = false;
        LoadStarbucks();
    }
}

function mapload(param) {
    if (GBrowserIsCompatible()) {

        function importanceOrder(marker, b) {
            return GOverlay.getZIndex(marker.getPoint().lat()) +
                marker.importance * 1000000;
        }

        
        //if( MarkerNumbers )
        //{
        //    svOverlay = new GStreetviewOverlay();
        //    map.addOverlay(svOverlay);
        //}


        $j.each(communityData, function (index, position) {
            var commLatitude = position[0];
            var commLongitude = position[1];
            var builder = "<b>" + position[4] + "</b>";
            var address = "";
            if (position[5] != null && position[5] != "")
                address += position[5] + ", ";
            if (position[6] != null && position[6] != "")
                address += position[6] + ", ";
            if (position[8] != null && position[8] != "")
                address += position[8] + ", ";
            if (position[7] != null && position[7] != "")
                address += position[7] + " ";
            if (position[9] != null && position[9] != "")
                address += position[9];
            var bed = position[10];
            var phone = position[11];
            var bath = position[13];
            var feet = position[14];
            var price = position[15];
            var ID = position[21];
            var interest = position[12];
            var condo = position[22];
            var townhome = position[23];
            var activeadult = position[18];
            var masterplanned = position[19];
            var loft = position[24];
            var displayType = position[26];
            var masterPlanID = position[27];
            var greenhomes = position[28];
            var communityurl = position[29];
            var passthepr = position[30];
            var popunder = '';

            if (passthepr != "True") {
                var community = "<a href=javascript:winOpenCount('" + basePath + "directdetail.aspx?CommunityID=" + position[21] + "')>" + position[2] + "</a>";
                popunder = basePath + "directdetail.aspx?CommunityID=" + position[21];
            }
            else {
                var community = "<a href='" + communityurl + "' target='_blank'>" + position[2] + "</a>";
                popunder = communityurl;
            }

            //Create icon based upon community type
            var icon = new GIcon(baseIcon);
            var CommunityNum = "";
            if (position[25] != null)
                CommunityNum = position[25];

            //icon.iconSize.width = 12;
            //icon.iconSize.height = 11;

            if (masterplanned.toLowerCase() != "")
                icon.image = basePath + "images/FlagMP.png"; //icon.image = basePath + "images/pin.aspx?CommunityNum=" + CommunityNum + "&GraphicName=FlagMP.png&MarkerNumbers=" + MarkerNumbers; //Master Planned Communities
            else if ((condo.toLowerCase() == "on" || townhome.toLowerCase() == "on" || loft.toLowerCase() == "on") && (masterplanned == "off" || masterplanned == ""))
                icon.image = basePath + "images/FlagCondos.png"; //icon.image = basePath + "images/pin.aspx?CommunityNum=" + CommunityNum + "&GraphicName=FlagCondos.png&MarkerNumbers=" + MarkerNumbers; //Condos   
            else if (activeadult.toLowerCase() == "on" && (masterplanned == "off" || masterplanned == ""))
                icon.image = basePath + "images/FlagAA.png"; //icon.image = basePath + "images/pin.aspx?CommunityNum=" + CommunityNum + "&GraphicName=FlagAA.png&MarkerNumbers=" + MarkerNumbers; //Active Adult
            else if (greenhomes.toLowerCase() == "on" && (masterplanned == "off" || masterplanned == ""))
                icon.image = basePath + "images/FlagGreen.png"; //icon.image = basePath + "images/pin.aspx?CommunityNum=" + CommunityNum + "&GraphicName=FlagGreen.png&MarkerNumbers=" + MarkerNumbers; //Greem Homes
            else
                icon.image = basePath + "images/FlagSF.png"; //icon.image = basePath + "images/pin.aspx?CommunityNum=" + CommunityNum + "&GraphicName=FlagSF.png&MarkerNumbers=" + MarkerNumbers; //Single Family Icon

            //Create our marker based upon lat/long and icon
            //var marker = new GMarker(new GLatLng(commLatitude, commLongitude), icon);

            var marker = new GMarker(new GLatLng(commLatitude, commLongitude), { icon: icon, zIndexProcess: importanceOrder });
            marker.importance = 2;


            var html = "";

            if (displayType == "2")
                html = html + "<span style='font-family:Verdana;font-size:12px;'><a href='" + basePath + "masterplanneddetail.aspx?masterPlanID=" + masterPlanID + "' class='MasterPlanLink'>" + masterplanned + "</a><br>Presents<br>";
            else
                html = html + "<span style='font-family:Verdana;font-size:12px;'>";

            html = html + community + "<br>By " + builder + "<br><br>" + address + "<br>";

            if (bed != "" && bath != "")
                html = html + bed + " Bedrooms, " + bath + " Bathrooms <br>";
            else if (bed != "" && bath == "")
                html = html + bed + " Bedrooms<br>";
            else if (bed == "" && bath != "")
                html = html + bath + " Bathrooms <br>";

            if (feet != "" && feet != "0")
                html = html + feet + "<br>";

            if (price != "")
                html = html + price + "<br>";

            if (phone != "")
                html = html + "Community Phone - " + phone + "<br>";

            if (interest != "")
                html = html + interest;
            //"<br><a href=javascript:winOpenCount('" + basePath + "interestdetail.aspx?community=" + ID + "')><b><font color='#009a00'>Add Me To Interest List</font></b></a>"
            if (MarkerNumbers || includeExtras) {
                html = html + "<br><a href='javascript:OpenStreetView(" + commLatitude + "," + commLongitude + ");'>Street View</a>"
                html = html + "&nbsp;|&nbsp;<a href=javascript:GetBirdEyeMap('panoholder','pano'," + commLatitude + "," + commLongitude + ");>Bird's Eye View</a>"

            }
            html = html + "</span>"
            GEvent.addListener(marker, 'click', function () {
                marker.openInfoWindowHtml(html);
                winOpenCountUnder(popunder);
            });
            gmarkers[position[21]] = marker;
            map.addOverlay(marker);
        });

    }
}

function LoadSchools() {
    $j.each(schoolData, function (index, position) {
        var ncessch = position[0];
        var schnam07 = position[1];
        var mstree07 = position[2];
        var mcity07 = position[3];
        var mstate07 = position[4];
        var mzip07 = position[5];
        var member07 = position[6];
        var phone07 = position[7];
        var latitude = position[8];
        var longitude = position[9];


        if (schoolson == false) {
            //Create icon based upon community type
            var icon = new GIcon(baseIcon);
            icon.image = BasePath + "images/FlagApple.png";
            icon.shadow = '';  //BasePath + "images/FlagAppleShadow.png";
            icon.iconSize = new GSize(30, 30);
            //icon.shadowSize = new GSize(30, 30);

            //Create our marker based upon lat/long and icon
            var marker = new GMarker(new GLatLng(latitude, longitude), icon);

            var html = "";

            html = html + "<span style='font-family:Verdana;font-size:12px;'>" + schnam07 + "<br/>";
            html = html + mstree07 + "<br/>";
            html = html + mcity07 + ", " + mstate07 + " " + mzip07 + "<br/>";
            html = html + "Phone: " + phone07;

            html = html + "</span>"
            GEvent.addListener(marker, 'click', function() {
                marker.openInfoWindowHtml(html);
            });


            gmarkers[ncessch] = marker;
            map.addOverlay(marker);
        }
        else {
            map.removeOverlay(gmarkers[ncessch]);
        }

    });
    if (schoolson == false)
        schoolson = true;
    else
        schoolson = false;
        
    if (!schoolson) {
            if (document.aspnetForm.Map_01 != null) document.aspnetForm.Map_01.src = basePath + 'images/Map-01.gif';
    }
    if (schoolson) {
       if (document.aspnetForm.Map_01 != null) document.aspnetForm.Map_01.src = basePath + 'images/Map-01-Alt.gif';
    }
}

function LoadStarbucks() {
    $j.each(starbucksData, function (index, position) {
        var StoreNumber = position[0];
        var Address1 = position[1];
        var Address2 = position[2];
        var City = position[3];
        var State = position[4];
        var Zip = position[5];
        var Phone = position[6];
        var Wireless = position[7];
        var latitude = position[8];
        var longitude = position[9];


        if (starbuckson == false) {
            //Create icon based upon community type
            var icon = new GIcon(baseIcon);
            icon.image = BasePath + "images/FlagStarbucks.png";
            icon.shadow = '';  //BasePath + "images/FlagAppleShadow.png";
            icon.iconSize = new GSize(25, 25);
            //icon.shadowSize = new GSize(30, 30);

            //Create our marker based upon lat/long and icon
            var marker = new GMarker(new GLatLng(latitude, longitude), icon);


            var html = "";

            html = html + "<span style='font-family:Verdana;font-size:12px;'>" + Address1 + "<br/>";
            html = html + Address2 + "<br/>";
            html = html + City + ", " + State + " " + Zip + "<br/>";
            html = html + "Phone: " + Phone + "<br/>";
            if (Wireless == "Yes") html = html + "Wireless access point";

            html = html + "</span>"
            GEvent.addListener(marker, 'click', function() {
                marker.openInfoWindowHtml(html);
            });
            gmarkers[StoreNumber] = marker;
            map.addOverlay(marker);
        }
        else {
            map.removeOverlay(gmarkers[StoreNumber]);
        }
    });
    if (starbuckson == false)
        starbuckson = true;
    else
        starbuckson = false;
         if (!starbuckson) {
            if (document.aspnetForm.Map_02 != null) document.aspnetForm.Map_02.src = basePath + 'images/Map-02.gif';
        }
        if (starbuckson) {
            if (document.aspnetForm.Map_02 != null) document.aspnetForm.Map_02.src = basePath + 'images/Map-02-Alt.gif';
        }
}

function OpenStreetView(latitude, longitude) {
    var id = 'panoholder';
    var id2 = 'birdeyeholder';
    if (document.getElementById) { // DOM3 = IE5, NS6
        if (document.getElementById(id).style.display == 'none' || (latitude != latstore && longitude != longstore)) {
            hidediv(id2);
            showdiv(id);
            StartStreetView(latitude, longitude);
        }
        else if (latitude == latstore && longitude == longstore) {
            hidediv(id);
        }
    }
    else {
        if (document.layers) { // Netscape 4
            if (document.id.display == 'none' || (latitude != latstore && longitude != longstore)) {
                hidediv(id2);
                showdiv(id);
                StartStreetView(latitude, longitude);
            }
            else if (latitude == latstore && longitude == longstore) {
                hidediv(id);
            }
        }
        else { // IE 4
            if (document.all.id.style.display == 'none' || (latitude != latstore && longitude != longstore)) {
                hidediv(id2);
                showdiv(id);
                StartStreetView(latitude, longitude);
            }
            else if (latitude == latstore && longitude == longstore) {
                hidediv(id);
            }
        }
    }
    latstore = latitude;
    longstore = longitude;
}

function StartStreetView(latitude, longitude) {
    var myPano = new GStreetviewPanorama(document.getElementById("pano"));
    community = new GLatLng(latitude, longitude);
    myPOV = { yaw: 370.64659986187695, pitch: 0 };
    myPano.setLocationAndPOV(community, myPOV);

    GEvent.addListener(myPano, "error", handleNoFlash);
}

function GetBirdEyeMap(tableid, panid, latitude, longitude) {
    storeid = tableid;
    if (document.getElementById) { // DOM3 = IE5, NS6
        if (document.getElementById('birdeyeholder').style.display == 'none' || (latitude != latstore && longitude != longstore) || typestore != "birdeye") {
            hidediv('panoholder');
            showdiv('birdeyeholder');
            StartBirdEyeViewMap(latitude, longitude, 'birdeye');
            latstore = latitude;
            longstore = longitude;
            typestore = "birdeye";
        }
        else if (latitude == latstore && longitude == longstore) {
            hidediv('birdeyeholder');
            storeid = null;
            latstore = null;
            longstore = null;
            typestore = null;
        }
    }
    else {
        if (document.layers) { // Netscape 4
            if (document.birdeyeholder.display == 'none' || (latitude != latstore && longitude != longstore) || typestore != "birdeye") {
                hidediv('panoholder');
                showdiv('birdeyeholder');
                StartBirdEyeViewMap(latitude, longitude, 'birdeye');
                latstore = latitude;
                longstore = longitude;
                typestore = "birdeye";
            }
            else if (latitude == latstore && longitude == longstore) {
                hidediv('birdeyeholder');
                storeid = null;
                latstore = null;
                longstore = null;
                typestore = null;
            }
        }
        else { // IE 4
            if (document.all.birdeyeholder.style.display == 'none' || (latitude != latstore && longitude != longstore) || typestore != "birdeye") {
                hidediv('panoholder');
                showdiv('birdeyeholder');
                StartBirdEyeViewMap(latitude, longitude, 'birdeye');
                latstore = latitude;
                longstore = longitude;
                typestore = "birdeye";
            }
            else if (latitude == latstore && longitude == longstore) {
                hidediv('birdeyeholder');
                storeid = null;
                latstore = null;
                longstore = null;
                typestore = null;
            }
        }
    }

}

function StartBirdEyeViewMap(latitude, longitude, id) {
    birdeyemap = new VEMap(id);
    birdeyemap.LoadMap(new VELatLong(latitude, longitude), 10, VEMapStyle.BirdseyeHybrid);
    var pinLocation = new VELatLong(latitude, longitude);
    var pushpin = new VEShape(VEShapeType.Pushpin, pinLocation);
    birdeyemap.AddShape(pushpin);
}


function handleNoFlash(errorCode) {
    if (errorCode == 603) {
        document.getElementById('panoholder').style.display = "none";
        alert("Error: Flash doesn't appear to be supported by your browser");
        return;
    }
    if (errorCode == 600) {
        document.getElementById('panoholder').style.display = "none";
        alert("We're sorry, there is no available street view map for this community");
        return;
    }
}

function hidediv(id) {
    //safe function to hide an element with a specified id
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'none';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'none';
        }
        else { // IE 4
            document.all.id.style.display = 'none';
        }
    }
}

function showdiv(id) {
    //safe function to show an element with a specified id
    if (document.getElementById) { // DOM3 = IE5, NS6
        document.getElementById(id).style.display = 'block';
    }
    else {
        if (document.layers) { // Netscape 4
            document.id.display = 'block';
        }
        else { // IE 4
            document.all.id.style.display = 'block';
        }
    }
}

function setCookie(c_name, value, expiredays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + expiredays);
    document.cookie = c_name + "=" + escape(value) +
((expiredays == null) ? "" : ";expires=" + exdate.toGMTString());
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}
