var ICON_PATH = "/assets/images/ameneties/";
var PRIMARY_LOCATION_ICON = ICON_PATH + "community.png";
var SCHOOL_ICON = ICON_PATH + "school.png";
var ENTERTAINMENT_ICON = ICON_PATH + "entertainment.png";
var GENERAL_ICON = ICON_PATH + "general.png";
var PARKS_ICON = ICON_PATH + "parks.png";
var PUBLIC_SERVICE_ICON = ICON_PATH + "publicservice.png";
var SHOPPING_ICON = ICON_PATH + "shopping.png";
var TRASPORTATION_ICON = ICON_PATH + "transportation.png";
var gmap;
var gmarkers = [];

function setCustomUI(map)
{
	customUI = map.getDefaultUI();
	customUI.maptypes.satellite = false;
	customUI.maptypes.hybrid = false;
	customUI.maptypes.physical = false;
	customUI.controls.largemapcontrol3d = true;
	//map.addControl(new GOverviewMapControl(new GSize(150, 150)));
	map.setUI(customUI);
}

function getCommunity(communityId) {
    if (communityId > 0) {
        AmenetiesMapService.GetCommunity(communityId, SuccessfulCommunityCallback);
    }
}

function SuccessfulCommunityCallback(result) 
{
    jsonData = eval(result);
    if (GBrowserIsCompatible()) {
        gmap = new GMap2(document.getElementById("map_canvas"));
        getCommunityIconOverlay(gmap, jsonData, PRIMARY_LOCATION_ICON);

        //remove the default map controls
        setCustomUI(gmap);
    }
}

function getCommunityIconOverlay(map, community, icon) {
    point = new GLatLng(community.Latitude, community.Longitude);
	map.setCenter(point, 13);
	
	//setup our icon
	primIcon = new GIcon();
	primIcon.image = icon;
	primIcon.iconSize = new GSize(30, 41);
	primIcon.iconAnchor = new GPoint(1, 1);
	primIcon.infoWindowAnchor = new GPoint(1, 5);
	markerOptions = { icon:primIcon };

	//lets get out location information
	htmlInfo = getHTMLForBaloon(community);
	var directions = getHTMLForDirectionsTab(community);

	marker = new GMarker(point, markerOptions);
	var infoTabs = [new GInfoWindowTab("Details", htmlInfo), new GInfoWindowTab("Directions", directions)];
	
	map.addOverlay(marker);
	//GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml(infoTabs); })
	GEvent.addListener(marker, "mouseover", function() { marker.openInfoWindowTabsHtml(infoTabs); })

}

function getAmenityIconOverlay(map, amenity, icon) {
    point = new GLatLng(amenity.Latitude, amenity.Longitude);

    //setup our icon
    primIcon = new GIcon();
    primIcon.image = icon;
    primIcon.iconSize = new GSize(30, 41);
    primIcon.iconAnchor = new GPoint(1, 1);
    primIcon.infoWindowAnchor = new GPoint(1, 5);
    markerOptions = { icon: primIcon };
    
    //lets get out location information
    var htmlInfo = getHTMLForBaloon(amenity);
    var directions = getHTMLForDirectionsTab(amenity);

    var marker = new GMarker(point, markerOptions);
    marker.id = amenity.SubCategoryId;
    gmarkers.push(marker);
    
    var infoTabs = [new GInfoWindowTab("Details", htmlInfo), new GInfoWindowTab("Directions", directions)];

//    GEvent.addListener(marker, "click", function() { marker.openInfoWindowTabsHtml(infoTabs); })
	GEvent.addListener(marker, "mouseover", function() { marker.openInfoWindowTabsHtml(infoTabs); })
    
    map.addOverlay(marker);
}

function getPointsForSubCategory(map, subCat, lat, lon, communityId) {
    if (subCat.checked) {
        AmenetiesMapService.GetMapPointsForSubCategory(parseInt(subCat.name), lat, lon, 10, communityId, SucceededCallback);
    }

    if (!subCat.checked) {
        if (gmarkers.length > 0) {
            for (i = 0; i < gmarkers.length; i++) {
                if (gmarkers[i].id == subCat.name) {
                    gmap.removeOverlay(gmarkers[i]);
                }
            }
        }
    }
}

function SucceededCallback(result)
{
    if (result.length > 0) {
        for (i = 0; i < result.length; i++) {
            getAmenityIconOverlay(gmap, result[i], getIconForCat(result[i].CategoryId));
        }
    }
}

function resetCheckBoxes() {
    $("form#form1 INPUT[type='checkbox']").attr('checked', false);
    $("#firstpane div.accordian_menu_head").siblings("div.menu_body").slideUp("slow")
    $("#firstpane div.accordian_menu_head").removeClass("accordian_menu_head_active");
}



function getIconForCat(catId) {
    switch (catId) {
        case 1:
            return GENERAL_ICON;
            break;

        case 2:
            return PUBLIC_SERVICE_ICON;
            break;

        case 3:
            return ENTERTAINMENT_ICON;
            break;

        case 4:
            return TRASPORTATION_ICON;
            break;

        case 5:
            return SCHOOL_ICON;
            break;

        case 6:
            return SHOPPING_ICON;
            break;

        case 7:
            return PARKS_ICON;
            break;

    }
}

function getHTMLForBaloon(amenity)
{
    output = "<div id='gmdetails'>";
    if (amenity.ImageURL) { output += "<img src='/assets/images/category/" + amenity.ImageURL + "'/><br/>"; }
    if (amenity.Title) { output += "<img src='/assets/images/collection/" + communityCollection + "/" + removeSpaces(amenity.Title) + "/search_thumb.jpg'/><br/>";}
    if (amenity.Title) { output += "<b class='Location'>" + amenity.Title + "</b><br />"; }
    if (amenity.AmenityDesc) { output += "<b class='Location'>" + amenity.AmenityDesc + "</b><br />"; }
	if (amenity.Address) { output += "<span class='address'>" + amenity.Address; }
	if (amenity.City) { output += " " + amenity.City + ""; }
	if (amenity.State) { output += ", " + amenity.State + " "; }
	if (amenity.Phone) { output += " " + amenity.Phone + " "; }
	if (amenity.AlternateUrl) { output += "<br />" + "<a href=" + amenity.AlertnateUrl + " target='_blank'>visit website</a></p></span><br /><br />"; }
	if (amenity.AmenityURL) { output += "<br />" + "<a href=" + amenity.AmenityURL + " target='_blank'>visit website</a></p></span><br /><br />"; }
	
	return output;
}

function getHTMLForDirectionsTab(amenity) {
    output = "<div id='gmdetails'>";
    if (amenity.AmenityDesc) { output = "<div style='width:150px;height:95px;color:#000;'><span style='font-size:14px;font-weight:bold;'>" + amenity.AmenityDesc + "</span>"; }
    if (amenity.Title) { output = "<div style='width:150px;height:95px;color:#000;'><span style='font-size:14px;font-weight:bold;'>" + amenity.Title + "</span>"; }
    output += "<br /><br /><span style='font-size:9px;'>start address:</span><br /><input type='text' id='uxStartAddress' name='uxStartAddress' style='width:200px' onload='this.focus()'/>";
    output += "<br /><input type='button' id='uxDirections' value='Get Directions' onclick='showDirections();'/>";
    output += "<input type='hidden' id='uxDestinationAddress' name='uxDestinationAddress' value='" + amenity.Address + ", " + amenity.City + ", " + amenity.State + "' />";
    if (amenity.AmenityDesc) { output += "<input type='hidden' id='uxDestName' name='uxDestName' value='" + amenity.AmenityDesc + "' />" };
    if (amenity.Title) { output += "<input type='hidden' id='uxDestName' name='uxDestName' value='" + amenity.Title + "' />" };

    return output;
}

function showDirections() {
    getDirections();
    $("#directionsPanel").css({ display: "block" });
    $("#directionsPanel").css({ zindex: "998" });
    $("#menu").css({ display: "none" });
}

function hideDirections() {
    $("#directionsPanel").css({ display: "none" });
    $("#directionsPanel").css({ zindex: "996" });
    $("#menu").css({ display: "block" });
}

function getDirections() {
    
    var directions = null;
    var fmaddr = $("#uxStartAddress").val();
    var toaddr = $("#uxDestinationAddress").val();
    var amenityName = $("#uxDestName").val();

    if (!directions) {
        directions = new GDirections(gmap);
    }

    GEvent.addListener(directions, "addoverlay", function() {

        var route = directions.getRoute(0);
        var bounds = new GLatLngBounds();
        var disp = "";

        disp = disp + " <h2 style='margin:0'>Directions</h2><h4 style='padding:5px;'>" + fmaddr + "</h4>" + directions.getDistance().html + " about " + directions.getDuration().html + "<br />";
        disp = disp + "<table width='100%' style='padding-right:5px;padding-left:5px;' cellspacing='0'>";

        // Start looping through the turn by turn elements.
        for (i = 0; i < route.getNumSteps(); i++) {
            var stp = route.getStep(i);
            bounds.extend(stp.getLatLng());
            var clr = (i % 2) ? "#fff" : "#fff";

            disp = disp + "<tr valign='top'><td style='background:" + clr + ";'>" + stp.getDescriptionHtml() + "</td>";
            disp = disp + "<td style='background:" + clr + ";'>" + stp.getDistance().html + "</td></tr>";
        }

        disp = disp + "<tr><td colspan='2'><h4 style='padding:5px;'>" + amenityName + "</h4><a href='#' onclick='javascript:printPage();'><img src='/assets/images/collection/" + communityCollection + "/buttons/print.gif'/></a><a href='#' id='uxCloseDirections' onclick='hideDirections();' style='margin-bottom:10px;margin-left:200px;margin-top:-23px;float:right;'><img src='/assets/images/collection/" + communityCollection + "/buttons/close.gif' /></a></td></tr></table>";
        $("#directionsPanel").html(disp);

        gmap.setZoom(gmap.getBoundsZoomLevel(bounds));
        gmap.setCenter(bounds.getCenter());
    });

    GEvent.addListener(directions, "error", function() {
        alert("Could not generate a route for the current start and end addresses");
        hideDirections();
    });

    directions.load("from: " + fmaddr + " to: " + toaddr, { preserveViewport: true, getSteps: true });
}

function removeSpaces(string) {
    return string.split(' ').join('');
}
