﻿var map = null;
var geocoder = null;
var pagestart = 1;
var pageend = 0;
var pagenum = 1;
var pagecount = 30;
var locationfiltercategory = "";
var locationfiltercategoryname = "";
var curminlon = 0;
var curmaxlon = 0;
var curminlat = 0;
var curmaxlat = 0;
var curcenterlat = 0;
var curcenterlng = 0;
var curzoom = 12;
var markers = new Array();
var tempindx = 0;
var curneighborhoodid = "0";
var mapcoltop = 0;
var lastOffset = 0;

var baseIcon = new GIcon();
baseIcon.shadow = "http://media.ombrosbrands.com/Markers/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

var MapToolTip = document.createElement("div");
    
function setupmap()
{
    map = new GMap2(document.getElementById("mapContainer"));
    
    map.addControl(new GLargeMapControl3D());
    map.addControl(new GMapTypeControl());
    
    GEvent.bind(this.map, "moveend", this, onMapMoveend);
    
    //Prevent zoomout
    var mt = map.getMapTypes();
    for (var i=0; i<mt.length; i++)
    {
        mt[i].getMinimumResolution = function() {return 10;}
    }
    
    geocoder = new GClientGeocoder();
    
    
    document.getElementById("mapContainer").appendChild(this.MapToolTip);
    this.MapToolTip.style.visibility="hidden";
    
    var publisherID = 'pub-6818287547163744';
    var adsManagerOptions = {
    maxAdsOnMap : 1,
    style: 'adunit',
    channel: '6923121967'
    };
    adsManager = new GAdsManager(map, publisherID, adsManagerOptions);
    adsManager.enable();

    
}


function setupmaplocation(lat, lng, zoom)
{
    if(window.location.href.match('#'))
	{
	    var url = window.location.href.substring(window.location.href.indexOf('#') + 1);
	    if (url.length > 8)
	    {
	        var nlat = url.split(',')[0];
	        var nlng = url.split(',')[1];
	        var nzoom = url.split(',')[2];
	        this.map.setCenter(new GLatLng(nlat, nlng), parseInt(nzoom));
	    }
	    else
        {
            this.map.setCenter(new GLatLng(lat, lng), zoom);
        }
    }
    else
    {
        this.map.setCenter(new GLatLng(lat, lng), zoom);
    }
    
    
    document.getElementById('mapColumn').style.position = "relative";
    this.mapcoltop = findPos(document.getElementById('mapColumn'))[1];
    window.onscroll = document.documentElement.onscroll = setMenuOffset;
    setMenuOffset();
}


function showloading()
{
    document.getElementById("LoadingWindow").style.visibility = "visible";
}

function hideloading()
{
    document.getElementById("LoadingWindow").style.visibility = "hidden";
}


onMapMoveend = function()
{
    var adjBounds = getAdjustedMapBounds();
    loadLocations(adjBounds['minlon'], adjBounds['maxlon'], adjBounds['minlat'], adjBounds['maxlat']);
}


function getAdjustedMapBounds()
{
    var adjBounds = {};
    var topDead = 25;
    var leftDead = 10;
    var rightDead = 5;
    var bounds = this.map.getBounds();
    var lonPerPix = (bounds.getNorthEast().lng() - bounds.getSouthWest().lng())/document.getElementById("mapContainer").clientWidth;
    var latPerPix = (bounds.getNorthEast().lat() - bounds.getSouthWest().lat())/document.getElementById("mapContainer").clientHeight;
	
    adjBounds['minlon'] = bounds.getSouthWest().lng() + leftDead*lonPerPix;
    adjBounds['maxlon'] = bounds.getNorthEast().lng() - rightDead*lonPerPix;
    adjBounds['minlat'] = bounds.getSouthWest().lat();
    adjBounds['maxlat'] = bounds.getNorthEast().lat() - topDead*latPerPix;
    return adjBounds;
};


function loadLocations(minlon, maxlon, minlat, maxlat)
{
    this.curcenterlat = this.map.getCenter().lat();
    this.curcenterlng = this.map.getCenter().lng();
    this.curzoom = this.map.getZoom();
    
    this.curminlon = minlon;
    this.curmaxlon = maxlon;
    this.curminlat = minlat;
    this.curmaxlat = maxlat;
    
    showloading();
    
    //Update URL
	if(window.location.href.match('#'))
	{
	    var currUrl = window.location.href.split('#')[0];
    }
    else
    {
        var currUrl = window.location.href;
    }
    window.location.href = currUrl+'#'+curcenterlat+','+curcenterlng+','+curzoom;    
    
    
    //Load Neighborhood
    GDownloadUrl("restHandler.ashx?method=GetNeighborhoodDisplay&Longitude=" + this.map.getCenter().lng() + "&Latitude=" + this.map.getCenter().lat(), function(data, responseCode)
    {
        if (data){
        
            var neighborhoodnam = data;
            
            if (neighborhoodnam.length > 1)
            {
                document.getElementById("mapneighborhood").innerHTML = "Map centered on <b>" + neighborhoodnam + "</b>";
            }
            else
            {
                document.getElementById("mapneighborhood").innerHTML = "";
            }
        }
        else
        {
            document.getElementById("mapneighborhood").innerHTML = "";
        }
    });
    
    
    //Load all map markers
    GDownloadUrl("restHandler.ashx?method=GetLocationsByLatLong&MinLongitude=" + minlon + "&MaxLongitude=" + maxlon + "&MinLatitude=" + minlat + "&MaxLatitude=" + maxlat + "&Count=" + pagecount + "&StartAt=" + this.pagestart + "&FilterCategoryID=" + locationfiltercategory, function(data, responseCode)
    {
        //Insert location adds
        $(document).ready(function() 
        { 
            if (jQuery.browser.msie== true && document.getElementById('locads_container_default') && document.getElementById('locads_content'))
            {
               $('#locads_content').appendTo($('#locads_container_default')); 
            }
        });
    
        //Clear all
        if (this.map.getInfoWindow().isHidden() == true)
        {
            this.map.clearOverlays.call(this.map);
        }
    
        var lochtml = new StringBuilder();
        
        //Parse XML
        var xml = GXml.parse(data);
        
        //Markers
        var locations = xml.documentElement.getElementsByTagName("loc");
        for (var i = 0; i < locations.length; i++)
        {
            var indx = i + 1;
            this.lastid = locations[i].getAttribute("id");
            
            //Map points
            this.map.addOverlay(createMarker(new GLatLng(parseFloat(locations[i].getAttribute("lat")), parseFloat(locations[i].getAttribute("lng"))), indx, locations[i].getAttribute("id"), locations[i].getAttribute("nam"), locations[i].getAttribute("ad1"), locations[i].getAttribute("c"), locations[i].getAttribute("st"), locations[i].getAttribute("zip"), locations[i].getAttribute("ph")));
            
            
            //Locations
            var bgcolor = "#ffffff";
            if (locations[i].getAttribute("sid") != "0")
            {
                bgcolor = "#fffedc";
            }
            
            lochtml.append("<div id=\"location" + locations[i].getAttribute("id") + "\" style=\"margin-bottom: 2px; border-bottom: solid 1px #999999; padding: 6px 0px 6px 0px; background-color: " + bgcolor + ";\" onmouseover=\"showMapTooltip(markers[" + indx + "])\" onmouseout=\"hideMapTooltip()\">");
            
            lochtml.append("<div class=\"standardp2\" style=\"padding-left: 16px;\"><span style=\"margin-left: -16px;\">" + indx + ". </span><a href=\"Location.aspx?LocationID=" + locations[i].getAttribute("id") + "\"><b>" + locations[i].getAttribute("nam") + "</b></a></div>");
            
            if (locations[i].getAttribute("mid") != 0) { lochtml.append("<span style=\"float: right; padding: 6px 2px 0px 0px;\"><a href=\"Location.aspx?LocationID=" + locations[i].getAttribute("id") + "\"><img src=\"http://media.ombrosbrands.com/LocationMedia/Small_" + locations[i].getAttribute("mid") + ".jpg\" style=\"border: solid 1px #999999; padding: 1px;\"></a></span>"); };
            
            lochtml.append("<div style=\"padding: 4px 0px 0px 16px;\">");
            lochtml.append("<div class=\"standard\">" + locations[i].getAttribute("ad1") + "</div>");
            lochtml.append("<div class=\"standard\">" + locations[i].getAttribute("c") + ", " + locations[i].getAttribute("st") + " " + locations[i].getAttribute("zip") + "</div>");
            if (locations[i].getAttribute("ph").length > 0) { lochtml.append("<div class=\"standard\">" + locations[i].getAttribute("ph") + "</div>"); }
            lochtml.append("<div class=\"standardm1\"><a href=\"Location.aspx?LocationID=" + locations[i].getAttribute("id") + "\">See details...</a></div>");
            
            lochtml.append("<div class=\"standardm1\" style=\"padding-top: 6px;\">Been here? <a href=\"javascript:addComment(" + locations[i].getAttribute("id") + ");\" title=\"Add a comment or a review about this place.\">Add a comment...</a></div>");
            lochtml.append("</div>");
            
            lochtml.append("</div>");
            
            
            if (jQuery.browser.msie == true && indx == 3)
            {
                lochtml.append("<div style=\"margin-bottom: 2px; border-bottom: solid 1px #999999; padding: 8px 0px 6px 4px;\">");
                lochtml.append("<div id=\"locads_container\"></div>");
                lochtml.append("</div>");
            }
            
        }
        
        //Set locations
        //lochtml.append("</table>");
        document.getElementById("locationsContainer").innerHTML = lochtml.toString();;
        
        
        //Insert location adds
        $(document).ready(function() 
        { 
            if (jQuery.browser.msie == true && document.getElementById('locads_container') && document.getElementById('locads_content'))
            {
                $('#locads_content').appendTo($('#locads_container'));
            }
        });
        
        
        //counts and pagination
        var startdispcount = 0;
        
        if (i == 0)
        {
            //no items
            this.pagestart = 0;
            this.pageend = 0;
            
            document.getElementById("locationsContainer").innerHTML = "<br><span class=\"headerRed\">No locations? Try a larger search radius.</span> <a href=\"javascript:this.map.zoomOut()\">zoom out</a><br><br>Suggestions for improving the results:<br><ul><li>Try a new location.</li><li>Drag the map around with your mouse to see other areas.</li><li>Remove and categories you might have selected.</li></ul><br><br>";
        }
        else if (pagenum > 1)
        {
            //second plus page
            this.pageend = this.pagestart + i - 1;
        } 
        else
        {
            //first page
            this.pagestart = 1;
            this.pageend = i;
        }
        
        document.getElementById("locationdisplaycounttop").innerHTML = pagestart + " to " + pageend + " of " + xml.documentElement.getAttribute("total");
        document.getElementById("locationdisplaycountbottom").innerHTML = document.getElementById("locationdisplaycounttop").innerHTML;
        
        //Previous
        if (this.pagestart > 1)
        {
            document.getElementById("locationPreviousbottom").innerHTML = "<a href=\"javascript:loadLocationsPrevious()\">Previous</a>"
        }
        else
        {
            document.getElementById("locationPreviousbottom").innerHTML = "<span style=\"color: #999999;\">Previous</span>"
        }
        
        //Next
        if (this.pageend < parseInt(xml.documentElement.getAttribute("total")))
        {
            document.getElementById("locationNextbottom").innerHTML = "<a href=\"javascript:loadLocationsNext()\">Next</a>"
        }
        else
        {
            document.getElementById("locationNextbottom").innerHTML = "<span style=\"color: #999999;\">Next</span>"
        }
        
        hideloading();
        
    });
    
    
    //Load Nearby Neighborhoods
    GDownloadUrl("restHandler.ashx?method=GetNearbyNeighborhoods&Longitude=" + this.map.getCenter().lng() + "&Latitude=" + this.map.getCenter().lat(), function(data, responseCode)
    {
        var nhtml = new StringBuilder();
        if (data){
            var xml = GXml.parse(data);
            var neighborhoods = xml.documentElement.getElementsByTagName("neighborhood");
            for (var i = 0; i < neighborhoods.length; i++)
            {
                nhtml.append('<div><a href="Finder.aspx?City=' + escape(neighborhoods[i].getAttribute('city')) + '&State=' + neighborhoods[i].getAttribute('state') + '&Neighborhood=' + escape(neighborhoods[i].getAttribute('nam')) + '">' + neighborhoods[i].getAttribute('nam') + '</a></div>');
            }
            
            document.getElementById("neighborhoodContainer").innerHTML = nhtml;
        }
    });

}


function loadLocationsNext()
{
    hideMapTooltip();
    document.getElementById('mapColumn').style.top = 0;
    scroll(0,0);

    this.map.clearOverlays.call(this.map);
    this.pagestart = this.pageend + 1;
    pagenum++;
    loadLocations(curminlon, curmaxlon, curminlat, curmaxlat);
}


function loadLocationsPrevious()
{
    hideMapTooltip();
    document.getElementById('mapColumn').style.top = 0;
    scroll(0,0);

    this.map.clearOverlays.call(this.map);
    this.pagestart = this.pageend - pagecount;
    pagenum--;
    loadLocations(curminlon, curmaxlon, curminlat, curmaxlat);
}


function filterCategory(categoryid, nam)
{
    document.getElementById("locationsBrowsingFor").innerHTML = "Browsing for <em><a href=\"javascript:clearfilterCategory();\" title=\"remove " + nam + " search\"><span style=\"color: red;\">X</span> " + nam + "</a></em>"
    
    this.locationfiltercategoryname = nam;
    this.locationfiltercategory = categoryid;
    loadLocations(curminlon, curmaxlon, curminlat, curmaxlat);
}

function filterCategoryEx(categoryid, nam)
{
    document.getElementById("locationsBrowsingFor").innerHTML = "Browsing for <em><a href=\"javascript:clearfilterCategory();\" title=\"remove " + nam + " search\"><span style=\"color: red;\">X</span> " + nam + "</a></em>"
    
    this.locationfiltercategoryname = nam;
    this.locationfiltercategory = categoryid;
}

function clearfilterCategory()
{
    document.getElementById("locationsBrowsingFor").innerHTML = "Browsing for <em>all</em> places"
    
    this.locationfiltercategoryname = "";
    this.locationfiltercategory = "";
    loadLocations(curminlon, curmaxlon, curminlat, curmaxlat);
}


function createMarker(latlong, indx, id, nam, address1, city, state, postalcode, phone)
{
    var icon = new GIcon(baseIcon);
    icon.image = "http://media.ombrosbrands.com/Markers/marker" + indx + ".png";
    
    var markeropts = new Object;
    markeropts.title = "Click for more information on " + nam;
    markeropts.icon = icon;
    
    var marker = new GMarker(latlong, markeropts);
    
    var html = new StringBuilder();
    html.append("<table width=140 cellpadding=0 cellspacing=0 border=0 style=\"background-color:#ffffff; border:1px gray solid;padding-right: 6px; padding-left: 6px; padding-bottom: 6px; padding-top: 6px\"><tr><td nowrap>");
    html.append("<span class=\"headerRed\">" + indx + ". " + nam + "</span>");
    html.append("<br>" + address1);
    html.append("<br>" + city + ", " + state + " " + postalcode);
    if (phone.length > 0)
    {
        html.append("<br>" + phone);
    }
    html.append("</td></tr></table>");
    marker.tooltip = html;
    
    markers[indx] = marker;
    
    GEvent.addListener(marker, "click", function() 
    {
        window.location = "Location.aspx?LocationID=" + id;
    });
    
    GEvent.addListener(marker,"mouseover", function()
    {
        showMapTooltip(marker);
    });
       
    GEvent.addListener(marker,"mouseout", function()
    {
        hideMapTooltip();
    });     
      
    return marker;
}


function showMapTooltip(marker)
{
    this.MapToolTip.innerHTML = marker.tooltip;
	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
	var anchor=marker.getIcon().iconAnchor;
	var width=marker.getIcon().iconSize.width;
	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width - this.MapToolTip.clientWidth - 10,- offset.y + point.y +anchor.y + 2));
	pos.apply(this.MapToolTip);
	this.MapToolTip.style.visibility = 'visible';
	
}

function hideMapTooltip()
{
    this.MapToolTip.style.visibility="hidden";
}


function selectMarker(indx, latlong)
{
    this.tempindx = indx;
    this.map.panTo(latlong);
    setTimeout("GEvent.trigger(markers[tempindx], 'click')", 500);
}


function zoomMarker(indx, latlong)
{
    this.tempindx = indx;
    this.map.setCenter(latlong, 16);
    setTimeout("GEvent.trigger(markers[tempindx], 'click')", 500);
}


function mapZoom(pluslevel)
{
    this.map.setZoom(pluslevel + this.map.getZoom());
}


function gotoAddress(address)
{
    if (address == "" || !geocoder)
    {
        showModalWindow("Invalid Location", "<div style=\"padding: 12px;\"><span class=\"headerRed\">Sorry, but we didn't understand the location you entered.</span><br>We accept locations in the following forms:<br><br><ul><li>121 West 15th ave, New York, NY</li><li>New York, NY</li><li>New York, NY 10023</li><li>10023</li></ul><br>Also, it's possible we don't have a listing for the address, city or state. In that case, you should try adding a zip, or try a larger nearby city.</div>", 240, 440);
    }
    else
    {
        geocoder.getLatLng(address, function(point)
        {
            if (!point)
            {
                showModalWindow("Invalid Location", "<div style=\"padding: 12px;\"><span class=\"headerRed\">Sorry, but we didn't understand the location you entered.</span><br>We accept locations in the following forms:<br><br><ul><li>121 West 15th ave, New York, NY</li><li>New York, NY</li><li>New York, NY 10023</li><li>10023</li></ul><br>Also, it's possible we don't have a listing for the address, city or state. In that case, you should try adding a zip, or try a larger nearby city.</div>", 240, 440);
            }
            else
            {
                map.setCenter(point, this.map.getZoom());
            }
        });
    }
}

function gotoLatLng(lat, lng)
{
    this.map.setCenter(new GLatLng(lat, lng), 14);
}


function createPageLink(url)
{
    var link = url + "?Latitude=" + this.map.getCenter().lat() + "&Longitude=" + this.map.getCenter().lng();
    showModalWindow("Link to this page", "<div style=\"padding: 12px;\"><img align=\"absMiddle\" src=\"images/icon_link32.gif\" /><span class=\"headerRed\">Create a link to this page</span><br /><hr color=\"gray\" noshade=\"noshade\" size=\"1\" /><span style=\"color: dimgray\" class=standardm1>If you would like to create a link to this page simply copy the entire URL below.</span><br /><br /><textarea name=\"link\" rows=\"6\" cols=\"20\" class=\"standardm1\" style=\"width:370px;\">" + link + "</textarea></div>", 220, 400);
}


function verifyLocation(locationid)
{
    GDownloadUrl("restHandler.ashx?method=VerifyLocation&LocationID=" + locationid, function(data, responseCode)
    {
        document.getElementById("verify" + locationid).innerHTML = "<span style=\"color: gray\">verified</span>";
    });
}


function toggleChangeLocation()
{
    if (document.getElementById("ChangeLocation").style.display == 'block')
    {
        
        hideChangeLocation();
    }
    else
    {
        showChangeLocation();
    }
}

function showChangeLocation()
{
    $('#ChangeLocation').show('fast');
}

function hideChangeLocation()
{
    $('#ChangeLocation').hide('fast');
}


function setMenuOffset() { 
	var mapcol = document.getElementById('mapColumn');
	if (!mapcol) return;
	
	var currentOffset = document.documentElement.scrollTop || document.body.scrollTop; // body for Safari
	var startPos = parseInt(0);
	var desiredOffset = this.mapcoltop - currentOffset;
	
	var scrollDown = 0;
	if (lastOffset < currentOffset)
	{
	    scrollDown = 1;
	}
	else
	{
	    scrollDown = 0;
	}
	lastOffset = currentOffset;
	
	var bottomStop = findPos(document.getElementById('spanBottom'))[1];
	var bottomMap = findPos(document.getElementById('neighborhoodContainer'))[1] + 160;
	
	if (bottomMap > bottomStop && scrollDown==1)
	{
        
	}
	else if (desiredOffset >= 0)
	{
		desiredOffset = 0;
		$(mapcol).animate({top: desiredOffset + 'px'},10);
		//mapcol.style.top = desiredOffset + 'px';
    }
    else
    {
        desiredOffset = Math.abs(desiredOffset);
        $(mapcol).animate({top: desiredOffset + 'px'},10);
        //mapcol.style.top = desiredOffset + 6 + 'px';
    }
    
}