var map;
var icons = new Object();
var icons8bit = new Object();

if (typeof(GIcon) != 'undefined') {
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = "http://www.google.com/mapfiles/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);
	
	var cmapApparelIcon = new GIcon();
	cmapApparelIcon.image = staticAssetPrefix + "/res/img/24/apparel.png";
	cmapApparelIcon.shadow = staticAssetPrefix + "/res/img/cmap_shad.png";
	cmapApparelIcon.iconSize = new GSize(30, 25);
	cmapApparelIcon.shadowSize = new GSize(40, 25);
	cmapApparelIcon.iconAnchor = new GPoint(12, 25);
	cmapApparelIcon.infoWindowAnchor = new GPoint(15, 13);
	icons['Apparel'] = cmapApparelIcon;
	icons8bit['Apparel'] = 'apparel.png';
	
	var cmapKidsIcon = new GIcon(cmapApparelIcon);
	cmapKidsIcon.image = staticAssetPrefix + "/res/img/24/baby.png";
	icons['Baby, Kids & Toys'] = cmapKidsIcon;
	icons8bit['Baby, Kids & Toys'] = 'baby.png';
	
	var cmapBooksIcon = new GIcon(cmapApparelIcon);
	cmapBooksIcon.image = staticAssetPrefix + "/res/img/24/books.png";
	icons['Books & Magazines'] = cmapBooksIcon;
	icons8bit['Books & Magazines'] = 'books.png';
	
	var cmapComputersIcon = new GIcon(cmapApparelIcon);
	cmapComputersIcon.image = staticAssetPrefix + "/res/img/24/computers.png";
	icons['Computers & Software'] = cmapComputersIcon;
	icons8bit['Computers & Software'] = 'computers.png';
	
	var cmapDeptIcon = new GIcon(cmapApparelIcon);
	cmapDeptIcon.image = staticAssetPrefix + "/res/img/24/deptstores.png";
	icons['Department Stores'] = cmapDeptIcon;
	icons8bit['Department Stores'] = 'deptstores.png';
	
	var cmapElecIcon = new GIcon(cmapApparelIcon);
	cmapElecIcon.image = staticAssetPrefix + "/res/img/24/electronics.png";
	icons['Electronics'] = cmapElecIcon;
	icons8bit['Electronics'] = 'electronics.png';
	
	var cmapFinanceIcon = new GIcon(cmapApparelIcon);
	cmapFinanceIcon.image = staticAssetPrefix + "/res/img/24/finance.png";
	icons['Finance'] = cmapFinanceIcon;
	icons8bit['Finance'] = 'finance.png';
	
	var cmapFlowersIcon = new GIcon(cmapApparelIcon);
	cmapFlowersIcon.image = staticAssetPrefix + "/res/img/24/flowers.png";
	icons['Flowers & Gifts'] = cmapFlowersIcon;
	icons8bit['Flowers & Gifts'] = 'flowers.png';
		
	var cmapGasIcon = new GIcon(cmapApparelIcon);
	cmapGasIcon.image = staticAssetPrefix + "/res/img/24/gas.png";
	icons['Gas stations'] = cmapGasIcon;
	icons8bit['Gas stations'] = 'gas.png';
	
	var cmapGiftCertIcon = new GIcon(cmapApparelIcon);
	cmapGiftCertIcon.image = staticAssetPrefix + "/res/img/24/giftcerts.png";
	icons['Gift Certificates'] = cmapGiftCertIcon;
	icons8bit['Gift Certificates'] = 'giftcerts.png';
	
	var cmapGroceryIcon = new GIcon(cmapApparelIcon);
	cmapGroceryIcon.image = staticAssetPrefix + "/res/img/24/grocery.png";
	icons['Grocery'] = cmapGroceryIcon;
	icons8bit['Grocery'] = 'grocery.png';
	
	var cmapHealthIcon = new GIcon(cmapApparelIcon);
	cmapHealthIcon.image = staticAssetPrefix + "/res/img/24/health.png";
	icons['Health & Beauty'] = cmapHealthIcon;
	icons8bit['Health & Beauty'] = 'health.png';
	
	var cmapHomeIcon = new GIcon(cmapApparelIcon);
	cmapHomeIcon.image = staticAssetPrefix + "/res/img/24/home.png";
	icons['Home & Garden'] = cmapHomeIcon;
	icons8bit['Home & Garden'] = 'home.png';
	
	var cmapJewelIcon = new GIcon(cmapApparelIcon);
	cmapJewelIcon.image = staticAssetPrefix + "/res/img/24/jewelry.png";
	icons['Jewelry & Watches'] = cmapJewelIcon;
	icons8bit['Jewelry & Watches'] = 'jewelry.png';
	
	var cmapMusicIcon = new GIcon(cmapApparelIcon);
	cmapMusicIcon.image = staticAssetPrefix + "/res/img/24/music.png";
	icons['Music, DVDs & Video'] = cmapMusicIcon;
	icons8bit['Music, DVDs & Video'] = 'music.png';
	
	var cmapOfficeIcon = new GIcon(cmapApparelIcon);
	cmapOfficeIcon.image = staticAssetPrefix + "/res/img/24/office.png";
	icons['Office Supplies'] = cmapOfficeIcon;
	icons8bit['Office Supplies'] = 'office.png';
	
	var cmapIcon = new GIcon(cmapApparelIcon);
	cmapIcon.image = staticAssetPrefix + "/res/img/24/other.png";
	icons['Other'] = cmapIcon;
	icons8bit['Other'] = 'other.png';
	
	var cmapPetsIcon = new GIcon(cmapApparelIcon);
	cmapPetsIcon.image = staticAssetPrefix + "/res/img/24/pet.png";
	icons['Pet Supplies'] = cmapPetsIcon;
	icons8bit['Pet Supplies'] = 'pet.png';
	
	var cmapRestaurantsIcon = new GIcon(cmapApparelIcon);
	cmapRestaurantsIcon.image = staticAssetPrefix + "/res/img/24/food.png";
	icons['Restaurants'] = cmapRestaurantsIcon;
	icons8bit['Restaurants'] = 'food.png';
	
	var cmapSportsIcon = new GIcon(cmapApparelIcon);
	cmapSportsIcon.image = staticAssetPrefix + "/res/img/24/sports.png";
	icons['Sports & Recreation'] = cmapSportsIcon;
	icons8bit['Sports & Recreation'] = 'sports.png';
	
	var cmapAutoIcon = new GIcon(cmapApparelIcon);
	cmapAutoIcon.image = staticAssetPrefix + "/res/img/24/toolsauto.png";
	icons['Tools & Automotive'] = cmapAutoIcon;
	icons8bit['Tools & Automotive'] = 'toolsauto.png';
	
	var cmapTravelIcon = new GIcon(cmapApparelIcon);
	cmapTravelIcon.image = staticAssetPrefix + "/res/img/24/travel.png";
	icons['Travel & Luggage'] = cmapTravelIcon;
	icons8bit['Travel & Luggage'] = 'travel.png';
	
	var markers = [];
	var mgr;
	var mcOptions = {maxZoom: 14};
	
	G_NORMAL_MAP.getMinimumResolution = function () { return 12 };
	G_NORMAL_MAP.getMaximumResolution = function () { return 16 };
	G_PHYSICAL_MAP.getMinimumResolution = function () { return 12 };
	G_PHYSICAL_MAP.getMaximumResolution = function () { return 16 };
	G_SATELLITE_MAP.getMinimumResolution = function () { return 12 };
	G_SATELLITE_MAP.getMaximumResolution = function () { return 16 };
	G_HYBRID_MAP.getMinimumResolution = function () { return 12 };
	G_HYBRID_MAP.getMaximumResolution = function () { return 16 };
}

var filterState = 0; // 0 = none, 1 = type
var filters;

var ANALYTICS_MAP = 'Map';
var ANALYTICS_FILTER_CATEGORY = 'Category Filter';
var ANALYTICS_COUPON = 'Coupon';
var IFRAME_STR = ' (iframe)';

// This gets called after all of the map initialization stuff in the DOM ready function below.
function setupMap(latLong, zoomLevel) {
	if (typeof(zoomLevel) != 'undefined') {
		map.setCenter(latLong, 17 - zoomLevel);
	} else {
		map.setCenter(latLong, 14);
	}
    mgr = new MarkerClusterer(map, [], mcOptions);
    GEvent.addListener(map, "moveend", populate);
    //GEvent.addListener(map, "dragend", populate);
    //GEvent.addListener(map, "zoomend", populate);
    
    // analytics events
    GEvent.addListener(map, "dragend", function() { _gaq.push(['_trackEvent', ANALYTICS_MAP, 'Drag map']); });
    GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {  _gaq.push(['_trackEvent', ANALYTICS_MAP, 'Zoom level change', 'Zoom', newLevel]); });
    GEvent.addListener(map, "maptypechanged", function() {  _gaq.push(['_trackEvent', ANALYTICS_MAP, 'Map type change', map.getCurrentMapType().getName()]); });
    
    populate();
}

function getUrlFromMap() {
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var url = "/offers/" + northEast.lat() + "/" + northEast.lng() + "/" + southWest.lat() + "/" + southWest.lng() +"/";
    if (!isMainPage && ((typeof(filters) == 'undefined' || filters == '') || filters.indexOf('category') < 0)) {
    	url += '?all=1';
    } else if (typeof(filters) != 'undefined' && filters != '') {
    	url += '?' + filters;
    }
    return url;
}


function addMarker(offer, offerNumber){
    var point = new GLatLng(offer.latitude,
                            offer.longitude);
    var infoWinPoint = new GLatLng(offer.latitude,
                                   offer.longitude);
    var myIcon = icons[offer.category];
    var opts = {maxWidth:250, pixelOffset:new GSize(0,-16)};
    var marker = new GMarker(point, myIcon);
    
    GEvent.addListener(marker, "click", function(doScroll) {
    		var offerHtml = $(offer.html);
    		var storeNameElement = $('<strong class="storename">' + offerHtml.find('a.storename').text() + '</strong><br/>');
    		offerHtml.find('a.storename').replaceWith(storeNameElement);
            map.openInfoWindowHtml(infoWinPoint, $('<div></div>').append(offerHtml).html(), opts);
            if (doScroll != 0) { 
            	var activeOffer = $('div#offer' + offerNumber);
            	$('div#sBarResults').scrollTo(activeOffer);
            	$(".offer").removeClass("selected");
            	activeOffer.addClass("selected");
            	_gaq.push(['_trackEvent', ANALYTICS_COUPON, 'Bubble triggered from map', offer.category]);
            } else {
            	_gaq.push(['_trackEvent', ANALYTICS_COUPON, 'Bubble triggered from listing', offer.category]);
            }
        });
    GEvent.addListener(marker, "infowindowclose", function() {
    	_gaq.push(['_trackEvent', ANALYTICS_COUPON, 'Bubble closed', offer.category]);
    });
    return marker;
}


function populate() {
	if (map.getInfoWindow().isHidden()) { // check to see if bubble is open so that the auto-pan doesn't refresh the map
		var populateStarted = new Date().getTime();
	    GDownloadUrl(getUrlFromMap(), function(data) {
	    	markers = [];
	        $("#sBarResults").empty();
	        mgr.clearMarkers();
	        $('span.count').remove();
	        var response = eval( '(' + data + ')' );
	        offers = response['offers'];
	        if (offers.length) {
	        	$("#sBarResults p.alert").remove();
	        	
	        	var restaurantsChecked = $('input#filter-fo').attr('checked');
	        	var giftChecked = $('input#filter-gi').attr('checked');
	            for(var i=0; i<offers.length; i++) {
	            	if (filterState == 1 && offers[i].has_gift_certificate) { // handle restaurants with both coupons and certs
		            	if (restaurantsChecked && !giftChecked) {
		            		var newHtml = $(offers[i].html);
		            		newHtml.find('.rc').css('display', 'none');
		            		offers[i].html = $('<div></div>').append(newHtml).html();
		            		offers[i].category = 'Restaurants';
		            	} else if (giftChecked && !restaurantsChecked) {
		            		var newHtml = $(offers[i].html);
		            		newHtml.find('li:not(.rc)').css('display', 'none');
		            		offers[i].html = $('<div></div>').append(newHtml).html();
		            		offers[i].category = 'Gift Certificates';
		            	}
	            	}
	            	
	            	// generate the markers and icons for sidebar
	            	markers.push(addMarker(offers[i], i));
	            	var myHtml = []
	            	myHtml.push('<div class="offer pod cfx" id="offer');
	            	myHtml.push(i.toString());
	            	myHtml.push('"><div class="icon"><a href="#" class="marker-icon" id="marker');
	            	myHtml.push(i.toString());
	            	myHtml.push('"><img src="' + staticAssetPrefix + '/res/img/8/');
	            	myHtml.push(icons8bit[offers[i].category]);
	            	myHtml.push('" alt="');
	            	myHtml.push(offers[i].category);
	            	myHtml.push('" border="0" height="25" width="30" /></a></div><div>');
	            	myHtml.push(offers[i].html);
	            	myHtml.push('</div></div>');
	                $("#sBarResults").append(myHtml.join(''));
	            }
	        } else {
	        	$("#sBarResults").append($('<p class="msg alert">Sorry, there are no offers in this area matching your selections.</p>'));
	        }
	        
	        showCounts(response['c_counts'], 'filter');
	        
	        if (typeof(lat) && typeof(lng) && typeof(centerName) != 'undefined') { // add the center marker if present
	        	var latLong = new GLatLng(lat, lng);
	            var eventMarker = new GMarker(latLong, {maxWidth:200});
	            GEvent.addListener(eventMarker, "click", function() {
	            	var centerHtml = '<strong>' + centerName + '</strong><br />';
	            	if (typeof(centerAddr1) != 'undefined') {
	            		centerHtml += centerAddr1 + '<br />'
	            	}
	            	if (typeof(centerAddr2) != 'undefined') {
	            		centerHtml += centerAddr2 + '<br />'
	            	}
	                map.openInfoWindowHtml(latLong, centerHtml);
	            });
	            markers.push(eventMarker);	
	        }
	        mgr.addMarkers(markers);
	        $('#sBarResults').scrollTop(0);
	
	        _gaq.push(['_trackEvent', ANALYTICS_MAP, 'Map populated', 'At zoom level ' + map.getZoom(), new Date().getTime() - populateStarted]);
	    });
    }
}

function triggerPopup(id) {
	GEvent.trigger(markers[id], "click", 0);
	if (map.getZoom() <= 13) {
		map.setCenter(markers[id].getLatLng(), 15);
	}
	return false;
}

function showCounts(countDict, filterType) {
	for (var item in countDict) {
    	var checkbox = $('input#' + filterType + '-' + item);
    	var label = checkbox.parent('label');
    	label.append('<span class="count">&nbsp;(' + countDict[item] + ')</span>');
    	if (countDict[item] == 0) {
    		//checkbox.attr('disabled', 'disabled');
    		label.css('color', '#ccc');
    	} else {
    		//checkbox.attr('disabled', '');
    		label.css('color', '#000');
    	}
    }
}

function setLatCookie() { $.cookie("lat",map.getCenter().lat(),{expires:100, path: '/'}); }
function setLongCookie() { $.cookie("lg",map.getCenter().lng(),{expires:100, path: '/'}); }
function setZoomCookie() { googleZoom = map.getZoom(); $.cookie("zmlevel",17-googleZoom,{expires:100, path: '/'}); }
function setFilterTypeCookie() { $.cookie("ftype",filterState,{expires:100, path: '/'}); }
function setFilterStateCookie() {
	if (filterState == 1) {
		$.cookie("fstate",$('#filter-form').serialize(),{expires:100, path: '/'});
	} else {
		$.cookie("fstate",'',{expires:100, path: '/'});
	}
}

function getLatCookie() {
    var userLat = $.cookie("lat");
    if(userLat){
        try {
            currentLat = parseFloat(userLat);
            return currentLat;
        } catch (e) {
            currentLat = '';
            setLatCookie();
            return currentLat;
        }
    }
}
function getLongCookie() {
    var userLng = $.cookie("lg");
    if(userLng){
        try {
            currentLng = parseFloat(userLng);
            return currentLng;
        } catch (e) {
            currentLng = '';
            setLngCookie();
            return currentLng;
        }
    }
}
function getZoomCookie() {
    var userZm = $.cookie("zmlevel");
    if(userZm){
        try {
            currentZm = parseFloat(userZm);
            return currentZm;
        } catch (e) {
            currentZm = '';
            setZoomCookie();
            return currentZm;
        }
    }
}
function getFilterTypeCookie() { return $.cookie("ftype"); }
function getFilterStateCookie() { return $.cookie("fstate"); }

function setStateCookie(state) { $.cookie("state", state, {expires:100, path: '/'}); }
function setCityCookie(city) { $.cookie("city", city, {expires:100, path: '/'}); }
function getStateCookie() { return $.cookie("state"); }
function getCityCookie() { return $.cookie("city"); }

function centerMapOnUserLocation() {
	GDownloadUrl('/my-location/', function(data) {
		var geodata = eval( '(' + data + ')' );
        var latLong = new GLatLng(geodata['Latitude'], geodata['Longitude']);
        setupMap(latLong);
	});
}

function checkForStateAndCityCookies() {
	var state = getStateCookie();
	var city = getCityCookie();
	if (state == null && city == null) {
		GDownloadUrl('/my-location/', function(data) {
			var geodata = eval( '(' + data + ')' );
			if ('State' in geodata && 'City' in geodata) {
				buildCategoryLinks(geodata['State'], geodata['City']);
				setStateCookie(geodata['State']);
				setCityCookie(geodata['City']);
			}
		});
	} else {
		buildCategoryLinks(state, city);
	}
}

function buildCategoryLinks(state, city) {
	$('a.mainCatLink').each(function() {
		var href = $(this).attr('href');
		var hrefSplit = href.split('/');
		hrefSplit[1] = state;
		hrefSplit[2] = city;
		$(this).attr('href', hrefSplit.join('/'));
	});
}

// 
// Bottom Ad Space
// 
var btmAdCookie = $.cookie("CMap_btmAdSpace");
var alertCookie = $.cookie("CMap_emailAlert");

/*
if (($("#btmAd iframe").length > 0) || ($("#btmAd #google_ads_div_cc_728x90_footer").length > 0) || ($("#btmAd #google_ads_div_cc_728x90_footer_ad_container").length > 0)) {
  var btmAdLoaded = true;
} else {
  var btmAdLoaded = false;
}
*/

var btmAdLoaded = true;

function showBtmAd() {
  $("#btmAd").animate({
    height: "100px"
  },
  1000);
  $("body").css("padding-bottom", "100px");
}
function closeBtmAd() {
  $("#btmAd").animate({
    height: "0"
  },
  500);
  $("body").css("padding-bottom", "0");
}
$("#btmAdClose").live('click', function() {
  $.cookie("CMap_btmAdSpace", "Closed", { expires: 1 });
  closeBtmAd();
  return false;
});
$(function() {
  if ((btmAdLoaded == true) && !btmAdCookie && !alertCookie) {
    setTimeout("showBtmAd()", 2000);
  }
});




$(function() {
	// Initialize Google Map. If this is the main page (as opposed to the iframe) use the default map UI.
	// If it's the iframe, customize the controls and add the CouponMap logo.
	if ($('#map').size() > 0) {
		map = new GMap2(document.getElementById('map'));
	    if (typeof(isMainPage) != 'undefined' && isMainPage){
	    	checkForStateAndCityCookies(); // we want to swap out the category links on the main page with the user's location info
	    	if ($.browser.msie && parseFloat($.browser.version) < 7) DD_belatedPNG.fix('div.filter-container');
	    	//map.setUIToDefault();
	    	var theUI = map.getDefaultUI();
	    	theUI.controls.overviewmapcontrol = true;
	    	map.setUI(theUI);
	    } else if (typeof(isListingPage) != 'undefined' && isListingPage) {
	    	map.setUIToDefault();
	    } else { //ui options for iframed widget
	    	var theUI = map.getDefaultUI();
	    	theUI.controls.hierarchicalmaptypecontrol = false;
	    	theUI.controls.maptypecontrol = false;
	    	theUI.controls.menumaptypecontrol = false;
	    	theUI.controls.scalecontrol = false;
	    	theUI.controls.largemapcontrol3d = false;
	    	theUI.controls.smallzoomcontrol3d = true;
	    	map.setUI(theUI);
	    	
	    	function EmbeddedCouponMapLogo() {};
	    	EmbeddedCouponMapLogo.prototype = new GControl();
	    	EmbeddedCouponMapLogo.prototype.initialize = function(map) {
	    		var container = document.createElement("div");
	    		container.appendChild($('<a href="http://www.couponmap.com" target="_blank"><img src="' + staticAssetPrefix + '/res/img/CouponMap_embed.png" class="png" alt="CouponMap" border="0" width="150" height="60" /></a>')[0]);
	    		map.getContainer().appendChild(container);
	    		return container;
	    	}
	    	EmbeddedCouponMapLogo.prototype.getDefaultPosition = function() {
	    		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 0));
	    	}
	    	function GetCouponMapControl() {};
	    	GetCouponMapControl.prototype = new GControl();
	    	GetCouponMapControl.prototype.initialize = function(map) {
	    		var container = document.createElement("div");
	    		container.appendChild($('<a href="http://www.couponmap.com/widget/" target="_blank" style="padding: 2px 3px; background: #fff; opacity: 0.8; filter:alpha(opacity=50); color: #00f;">Like CouponMap? Get it for your site.</a>')[0]);
	    		map.getContainer().appendChild(container);
	    		return container;
	    	}
	    	GetCouponMapControl.prototype.getDefaultPosition = function() {
	    		return new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(3, 19));
	    	}
	    	map.addControl(new EmbeddedCouponMapLogo());
	    	map.addControl(new GetCouponMapControl());
	    	if ($.browser.msie && parseFloat($.browser.version) < 7) DD_belatedPNG.fix('img.png');
	    }
    
	    // More initialization.
	    if (typeof(isMainPage) != 'undefined' && isMainPage) {		    
		    // If URL-specified category is present, set filters accordingly. If not, and the filter type and state cookies are present, preset the filters with those.
		    if (typeof(urlCategory) != 'undefined') {
		    	$('#filter-form input[type=checkbox]').attr('checked', '');
		    	$('input#filter-' + urlCategory).attr('checked', 'checked');
		    	filters = $('#filter-form').serialize();
		    } else if (getFilterTypeCookie() != null && getFilterStateCookie() != null) {
		    	filters = getFilterStateCookie();
		    	var filterStateObj = $.deparam.querystring(filters);
		    	if (getFilterTypeCookie() == '1') {
		    		var chosenFilters = filterStateObj['category'];
		    		if (typeof(chosenFilters) != 'undefined') {
		    			filterState = 1;
			    		$('a#filter-link-type').css('font-weight', 'bold');
		    			$('#filter-form input[type=checkbox]').attr('checked', '');
		    			if (typeof(chosenFilters) == 'string') {
		    				$('input#filter-' + chosenFilters).attr('checked', 'checked');
		    			} else {
				    		for (var i = 0; i < chosenFilters.length; i++) {
				            	$('input#filter-' + chosenFilters[i]).attr('checked', 'checked');
				        	}
		    			}
		    		}
		    	} else {
		    		$('#filter-form input[type=checkbox]').attr('checked', 'checked');
			    	filters = $('#filter-form').serialize();
		    	}
		    } else {
		    	filters = $('#filter-form').serialize();
		    }

		    // This presets the map location. Order of precedence is: search query, query string location (from iframe), location from cookie, IP location.
		    if (typeof(searchQuery) != 'undefined') {
		    	var geocoder = new GClientGeocoder();
	            geocoder.getLocations(searchQuery,
	                               function(point) {
	                                   if (!point || point.Status.code == 602) {
	                                       alert('Sorry, the location "' + searchQuery + '" was not found.');
	                                       centerMapOnUserLocation();
	                                   } else {
	                                       var new_center = point.Placemark[0].Point;
	                                       var new_center_glat = new GLatLng(new_center.coordinates[1], new_center.coordinates[0]);
	                                       setupMap(new_center_glat);
	                                   }
	                               });
		    } else if (typeof(lat) != 'undefined' && typeof(lng) != 'undefined' && typeof(centerName) != 'undefined') {
		    	// passed in query params take precedence over cookie values
		        var latLong = new GLatLng(lat, lng);
		        setupMap(latLong);	    	
		    } else if (typeof(getLatCookie()) != 'undefined' && typeof(getLongCookie()) != 'undefined' && typeof(getZoomCookie()) != 'undefined') {
		    	// return user to where they were when they last left page
		        var latLong = new GLatLng(getLatCookie(), getLongCookie());
		        setupMap(latLong, parseInt(getZoomCookie()));
		    } else {
		    	centerMapOnUserLocation();
	    	}
	    } else if (typeof(isListingPage) != 'undefined' && isListingPage) {
	    	// This part runs if we're on a city/zip listing page
	    	var points = [];
	    	var mapPoints = [];
	    	var latitudes = [];
	    	var longitudes = [];
	    	var grubbs = new Grubbs();

	    	$('.offers .offer').each(function() {
	    		var thisLatitude = parseFloat($(this).attr('latitude'));
	    		var thisLongitude = parseFloat($(this).attr('longitude'));
	    		points.push(new GLatLng(thisLatitude, thisLongitude));
	    		latitudes.push(thisLatitude);
	    		longitudes.push(thisLongitude);
	    	});
	    	
	    	hasOutliers = true;
	    	while (hasOutliers && latitudes.length > 6) {
		    	var latitudeOutlier = grubbs.findOutlier(latitudes, grubbs.T_980);
		    	var longitudeOutlier = grubbs.findOutlier(longitudes, grubbs.T_980);
		    	if (latitudeOutlier > -1 || longitudeOutlier > -1) {
		    		if (latitudeOutlier == longitudeOutlier) { // neither is -1
		    			latitudes.splice(latitudeOutlier, 1);
		    			longitudes.splice(latitudeOutlier, 1);
		    		} else {
		    			if (latitudeOutlier > -1) {
			    			latitudes.splice(latitudeOutlier, 1);
			    			longitudes.splice(latitudeOutlier, 1);
		    			}
		    			if (longitudeOutlier > -1) {
			    			latitudes.splice(longitudeOutlier, 1);
			    			longitudes.splice(longitudeOutlier, 1);
		    			}
		    		}	
		    	} else {
		    		hasOutliers = false;
		    	}
	    	}
	    	
	    	for (var i = 0; i < latitudes.length; i++) {
	    		mapPoints.push(new GLatLng(latitudes[i], longitudes[i]));
	    	}
	    	
	    	var mapPolygon = new GPolygon(mapPoints);
	    	var pointsPolygon = new GPolygon(points);
	    	map.setCenter(mapPolygon.getBounds().getCenter());
	    	
	    	var minZoom = map.getBoundsZoomLevel(pointsPolygon.getBounds());
	    	G_NORMAL_MAP.getMinimumResolution = function () { return minZoom - 1 };
	    	G_PHYSICAL_MAP.getMinimumResolution = function () { return minZoom - 1 };
	    	G_SATELLITE_MAP.getMinimumResolution = function () { return minZoom - 1 };
	    	G_HYBRID_MAP.getMinimumResolution = function () { return minZoom - 1 };
	    	
	    	var currentZoom = map.getBoundsZoomLevel(mapPolygon.getBounds());
	    	map.setZoom(currentZoom);
	    	
	    	var opts = {maxWidth:250, pixelOffset:new GSize(0,-30)};
	    	for (var i = 0; i < points.length; i++) {
	            var letter = String.fromCharCode("A".charCodeAt(0) + i);
	            var letteredIcon = new GIcon(baseIcon);
	            letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
	            markerOptions = { icon:letteredIcon };
	    		var marker = new GMarker(points[i], markerOptions);
	    		marker.bubbleHtml = '<div>' + $('#offer' + (i + 1)).html() + '<br/><br/></div>';
	    		GEvent.addListener(marker, "click", function() {
	                map.openInfoWindowHtml(this.getLatLng(), this.bubbleHtml, opts);
	    		});
	    		map.addOverlay(marker);
	    	}
	    } else { // for the iframed widget
	    	filters = $.param.querystring();
	    	ANALYTICS_MAP += IFRAME_STR;
	    	ANALYTICS_FILTER_CATEGORY += IFRAME_STR;
	    	ANALYTICS_COUPON += IFRAME_STR;
	        
	    	var latLong;
	    	if (lat != '' && lng != '') {
	    		latLong = new GLatLng(lat, lng);
	    		setupMap(latLong);
	    	} else {
			    GDownloadUrl('/my-location/', function(data) {
		    		var geodata = eval( '(' + data + ')' );
			        latLong = new GLatLng(geodata['Latitude'], geodata['Longitude']);
			        setupMap(latLong);
			    });
	    	}
	    }
	}
    
    // Set up events on the filters. The filter links will trigger the changeState event. The "fromCloseBox"
	// parameter tells us if the filter was closed with the X box in the corner, which we track with GA.
	// Select and deselect all events are triggered by the select/deselect all links (obviously.)
	$('.filter-container-outer').bind('changeState', function(e, fromCloseBox) {
		var filterType = ANALYTICS_FILTER_CATEGORY;
		if ($(this).is(':visible')) { 
			$(this).hide();
			if (fromCloseBox) {
				_gaq.push(['_trackEvent', filterType, 'Filter closed via close box']);
			} else {
				_gaq.push(['_trackEvent', filterType, 'Filter closed via filter link']);
			}
		} else {
			$('.filter-container-outer').hide();
			$(this).show();
			_gaq.push(['_trackEvent', filterType, 'Filter opened']);
		}
	}).bind('selectAll', function(e) {
    	var filterType = ANALYTICS_FILTER_CATEGORY;
    	$(this).find('input[type=checkbox]').attr('checked', true);
    	_gaq.push(['_trackEvent', filterType, 'Select all']);
	}).bind('deselectAll', function(e) {
    	var filterType = ANALYTICS_FILTER_CATEGORY;
    	$(this).find('input[type=checkbox]').attr('checked', false);
    	_gaq.push(['_trackEvent', filterType, 'Deselect all']);
	});
		
	// Attach the filter change event to the filter links and to the filters' close boxes.
	$('a#filter-link-type').click(function() { $('#filter-container-type').trigger('changeState', false); return false; });
	$('a#closeType').click(function() { $('#filter-container-type').trigger('changeState', true); return false; });
	
	// Attach the select and deselect all links to the filters' select/deselect all events.
	$('.select-all').click(function() {
		$(this).parents('.filter-container-outer').trigger('selectAll');
		return false;
	});
    $('.deselect-all').click(function() {
    	$(this).parents('.filter-container-outer').trigger('deselectAll');
		return false;
    });
    
    $('#filter-form').submit(function(e){
    	e.preventDefault();
    	filters = $(this).serialize();
    	if ($(this).attr('id') == 'filter-form') {
    		filterState = 1;
    		$('a#filter-link-type').css('font-weight', 'bold');
    		_gaq.push(['_trackEvent', ANALYTICS_FILTER_CATEGORY, 'Apply filters']);
    	}
    	$('.filter-container-outer').hide();
    	populate();
    });
    
    // Tell Analytics when a filter is checked or unchecked
    $('#filter-form input.filter-checkbox').change(function() {
    	var filterCategory = ANALYTICS_FILTER_CATEGORY;
    	var filterText = $(this).parent('label').text().split('(')[0];
        if ($(this).attr('checked')) {
        	_gaq.push(['_trackEvent', filterCategory, 'Filter checked', filterText]);
        } else {
        	_gaq.push(['_trackEvent', filterCategory, 'Filter unchecked', filterText]);
        }
	});
    
    if ($.browser.msie) {
        $('#filter-form input.filter-checkbox').live('click', function() { this.blur(); this.focus(); });
    }
    
    $("#mapSearch").submit(function() {
    	if ($('#couponMap').size() > 0) {
            var geocoder = new GClientGeocoder();
            var address = $("#mapSearchInput").val();
            geocoder.getLocations(address,
                               function(point) {
                                   if (!point || point.Status.code == 602) {
                                       alert('Sorry, the location "' + address + '" was not found.');
                                   } else {
                                       var state = point.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
                                       var new_center = point.Placemark[0].Point;
                                       var new_center_glat = new GLatLng(new_center.coordinates[1], new_center.coordinates[0]);
                                       map.setCenter(new_center_glat, 14);
                                       populate();
                                   }
                               });
            _gaq.push(['_trackPageview', "/search?q="+address]);
            return false;
    	}
    });
        
    // popup marker when store icon is clicked
    $('#sBarResults div.offer').live('click', function(e) {
    	$(".offer").removeClass("selected");
    	$(this).addClass("selected");
    	if (!$(e.target).is('a')) {
    		triggerPopup(parseInt($(this).attr('id').replace('offer', '')));
    	}
    });
    
    $('a.grocery-coupons').live('click', function() {
		var WindowObjectReference;
		var strWindowFeatures='width=605,height=690,menubar=no,toolbar=no,location=no,resizable=no,scrollbars=no,status=no';
		WindowObjectReference=window.open('/grocery/','grocerycoupons',strWindowFeatures);
		return false;
    });
    
    $('div.infowindow-scroll li a').live('click', function() {
    	var clickUrl = '/' + $(this).attr('category') + '/';
    	if ($(this).attr('category') == '') { 
    		clickUrl = '/None/';
    	}
    	var storeName = $(this).parents('div.infowindow-scroll').prevAll('.storename').text();
    	clickUrl += storeName;
    	if ($(this).parents('#sBarResults').size() == 1) {
    		clickUrl += '/from-listing/';
    	} else {
    		clickUrl += '/from-map/';
    	}
    	clickUrl += $(this).text();
    	_gaq.push(['_trackPageview', clickUrl]);
    });
        
    // save the current filter/map settings before exit
    if (typeof(isMainPage) != 'undefined' && isMainPage) {
	    $(window).unload(function() {
	    	setLatCookie();
	    	setLongCookie();
	    	setZoomCookie();
	    	setFilterTypeCookie();
	    	setFilterStateCookie();
	    });
    }
});