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

var map;
var mapHandler;
var searchLocChanged = false;

function MainMapHandler() {
	var icons = new Object();
	var markers = [];
	var mgr;
	var mcOptions = {maxZoom: 13};
	var geolocationInactionTimeout;
	var infowindow;
	
	this.filterType = 0; // 0 = none, 1 = type, corresponds to the ftype cookie

	this.initialize = function() {
		this.setupFilters();
		setupCategoryIcons();
		this.presetLocation();
		
		infowindow = new google.maps.InfoWindow({maxWidth: 250, pixelOffset: new google.maps.Size(0, -16)});
		//google.maps.event.addListener(infowindow, "closeclick", function() { gaq.push(['_trackEvent', ANALYTICS_COUPON, 'Bubble closed', offer.category])});
		google.maps.event.addListener(infowindow, "closeclick", function() { _gaq.push(['_trackEvent', ANALYTICS_COUPON, 'Bubble closed'])});
		
	    // 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', '')));
	    	}
	    });
	}

	this.initializeWidget = function() {
		setupCategoryIcons();
		this.presetLocationForWidget();

		infowindow = new google.maps.InfoWindow({maxWidth: 250, pixelOffset: new google.maps.Size(0, -16)});
		//google.maps.event.addListener(infowindow, "closeclick", function() { gaq.push(['_trackEvent', ANALYTICS_COUPON, 'Bubble closed', offer.category])});
		google.maps.event.addListener(infowindow, "closeclick", function() { _gaq.push(['_trackEvent', ANALYTICS_COUPON, 'Bubble closed'])});
		
		function EmbeddedCouponMapLogo(controlDiv, map) {
    		var container = document.createElement("div");
    		container.appendChild($('<a href="http://www.couponmap.com" target="_blank"><img src="' + staticAssetPrefix + '/img/CouponMap_embed.png" class="png" alt="CouponMap" border="0" width="150" height="60" /></a>')[0]);
    		controlDiv.appendChild(container);
		}

    	function GetCouponMapForYourSite(controlDiv, 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;font-size: 11px;line-height: 1.3;">Like CouponMap? Get it for your site.</a>')[0]);
    		controlDiv.appendChild(container);
		}
    	
    	var logoControlDiv = document.createElement('DIV');
    	var logoControl = new EmbeddedCouponMapLogo(logoControlDiv, map);
    	var call2ActionControlDiv = document.createElement('DIV');
    	var call2ActionControl = new GetCouponMapForYourSite(call2ActionControlDiv, map);

    	logoControlDiv.index = 1;
    	call2ActionControlDiv.index = 1;
    	map.controls[google.maps.ControlPosition.TOP_RIGHT].push(logoControlDiv);
    	map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(call2ActionControlDiv);
	}
	
	this.setupFilters = function() {
		// 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');
	    	this.filterState = $('#filter-form').serialize();
	    } else if (getFilterTypeCookie() != null && getFilterStateCookie() != null) {
	    	this.filterState = getFilterStateCookie();
	    	var filterStateObj = $.deparam.querystring(this.filterState);
	    	if (getFilterTypeCookie() == '1') {
    			this.filterType = 1;
	    		$('a#filter-link-type').css('font-weight', 'bold');

	    		var version = filterStateObj['v'];
	    		
	    		if (typeof(version) != 'undefined' && version == 3) {
	    			$('#filter-form input[type=checkbox]').attr('checked', 'checked');
	    			for (var item in filterStateObj) {
	    				if (item != 'v' && filterStateObj[item] == 'false') {
	    					$('input#filter-' + item).attr('checked', '');
	    				}
	    			}
	    			this.filterState = $('#filter-form').serialize();
	    		} else {
	    			$('#filter-form input[type=checkbox]').attr('checked', 'checked');
			    	this.filterState = $('#filter-form').serialize();
	    		}
	    	} else {
	    		$('#filter-form input[type=checkbox]').attr('checked', 'checked');
		    	this.filterState = $('#filter-form').serialize();
	    	}
	    } else {
	    	this.filterState = $('#filter-form').serialize();
	    }
	}
	
	function setupCategoryIcons() {
		var catList = ['Clothing & Shoes',
	                   'unused',
	                   'unused',
	                   'Computers & Phones',
	                   'unused',
	                   'Retail',
	                   'unused',
	                   'unused',
	                   'unused',
	                   'unused',
	                   'Restaurants',
	                   'Gas Stations',
	                   'unused',
	                   'Grocery',
	                   'Health & Beauty',
	                   'Home & Garden',
	                   'unused',
	                   'unused',
	                   'unused',
	                   'Other',
	                   'Pets',
	                   'Sports & Entertainment',
	                   'Tools & Automotive',
	                   'Travel',
	                   'Services'];
	    
	    var spriteVar = 0;
	    var spriteLoc = staticAssetPrefix + "/img/24/catsprite.png";
	    icons['shadow'] = new google.maps.MarkerImage(staticAssetPrefix + "/img/cmap_shad.png", new google.maps.Size(40, 25), new google.maps.Point(0, 0), new google.maps.Point(12, 25));
	    for (var i in catList) {
	    	icons[catList[i]] = new google.maps.MarkerImage(spriteLoc, new google.maps.Size(30, 25), new google.maps.Point(0, spriteVar), new google.maps.Point(12, 25));
	    	spriteVar += 50;
	    }
	}
	
	this.presetLocation = function() {
		// 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 google.maps.Geocoder();
            geocoder.geocode({'address': searchQuery}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
                    mapHandler.setupMap({center: results[0].geometry.location});
			     } else {
			        alert('Sorry, the location "' + address + '" was not found.');
			        centerMapOnUserLocation();
			     }
			});
	    } else if (typeof(lat) != 'undefined' && typeof(lng) != 'undefined') {
	    	// passed in query params take precedence over cookie values
	        var latlng = new google.maps.LatLng(lat, lng);
	        this.setupMap({center: latlng});	    	
	    } else if (typeof(getLatCookie()) != 'undefined' && typeof(getLongCookie()) != 'undefined' && typeof(getZoomCookie()) != 'undefined') {
	    	// return user to where they were when they last left page
	        var latlng = new google.maps.LatLng(getLatCookie(), getLongCookie());
	        this.setupMap({center: latlng, zoomLevel: parseInt(getZoomCookie())});
	    } else {
	    	centerMapOnUserLocation();
    	}
	}
	
	this.presetLocationForWidget = function() {
		if (lat != '' && lng != '') {
			this.setupMap({center: new google.maps.LatLng(lat, lng), additionalOptions: {overviewMapControl: false, streetViewControl: false}});
		} else {
		    $.get('/my-location/', function(data) {
		        mapHandler.setupMap({center: new google.maps.LatLng(data['latitude'], data['longitude']), additionalOptions: {overviewMapControl: false, streetViewControl: false}});
		    }, 'json');
		}
	}

	function centerMapOnUserLocation() {
		if (navigator.geolocation) {
			geolocationInactionTimeout = setTimeout(centerMapOnUserLocationFallback, 6000);
			navigator.geolocation.getCurrentPosition(handleGeolocationQuery, centerMapOnUserLocationFallback);
		} else {
			centerMapOnUserLocationFallback();
		}
	}

	function handleGeolocationQuery(position) {
		clearTimeout(geolocationInactionTimeout);
		_gaq.push(['_trackEvent', 'Geolocation', 'HTML5 Geolocation Success']);
		var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
	    mapHandler.setupMap({center: latlng});
	}

	function centerMapOnUserLocationFallback(err) {
		clearTimeout(geolocationInactionTimeout);
		if (typeof(err) != 'undefined') {
			if (err.code == 1) {
				_gaq.push(['_trackEvent', 'Geolocation', 'HTML5 Geolocation Failure (User Denied)']);
			} else if (err.code == 2) {
				_gaq.push(['_trackEvent', 'Geolocation', 'HTML5 Geolocation Failure (Location Not Found)']);
			} else {
				_gaq.push(['_trackEvent', 'Geolocation', 'HTML5 Geolocation Failure']);
			}
		} else {
			_gaq.push(['_trackEvent', 'Geolocation', 'HTML5 Geolocation Failure']);
		}
		$.get('/my-location/', function(data) {
	        var latlng = new google.maps.LatLng(data['latitude'], data['longitude']);
	        mapHandler.setupMap({center: latlng});
		}, 'json');
	}

	this.setupMap = function(options) {
	    var myOptions = {
	      center: options.center,
	      mapTypeId: google.maps.MapTypeId.ROADMAP,
	      minZoom: 12,
	      maxZoom: 16,
	      zoom: 14,
	      mapTypeControl: false,
	      overviewMapControl: true
	    };

	    if (typeof(options.zoomLevel) != 'undefined') {
	    	myOptions.zoom = 17 - options.zoomLevel;
		}

	    if (typeof(options.additionalOptions) != 'undefined') {
	    	for (var i in options.additionalOptions) {
	    		myOptions[i] = options.additionalOptions[i];
	    	}
		}

	    map = new google.maps.Map(document.getElementById("map"), myOptions);
	    mgr = new MarkerClusterer(map, [], mcOptions);
	    
	    var thiz = this;
	    var zoomChangeIsOccuring = false;
	    var initializationEvent = google.maps.event.addListener(map, 'tilesloaded', function() { thiz.populate(); google.maps.event.removeListener(initializationEvent); });
	    google.maps.event.addListener(map, 'dragend', function() { thiz.populate(); });
	    google.maps.event.addListener(map, 'zoom_changed', function() { zoomChangeIsOccuring = true; infowindow.close(); });
	    google.maps.event.addListener(map, 'idle', function() { if (zoomChangeIsOccuring) { thiz.populate(); zoomChangeIsOccuring = false; } });
	    
	    // analytics events
	    google.maps.event.addListener(map, "dragend", function() { _gaq.push(['_trackEvent', ANALYTICS_MAP, 'Drag map']); });
	    google.maps.event.addListener(map, "zoom_changed", function(oldLevel, newLevel) {  _gaq.push(['_trackEvent', ANALYTICS_MAP, 'Zoom level change', 'Zoom', newLevel]); });
	    google.maps.event.addListener(map, "maptypeid_changed", function() {  _gaq.push(['_trackEvent', ANALYTICS_MAP, 'Map type change', map.getCurrentMapType().getName()]); });
	}

	this.populate = function() {
		var populateStarted = new Date().getTime();
	    $.get(this.getUrlFromMap(), function(data) {
	    	markers = [];
	        $("#sBarResults").empty();
	        mgr.clearMarkers();
	        $('span.count').remove();
	        var response = data;
	        offers = response['offers'];
	        if (offers.length) {
	        	$("#sBarResults p.alert").remove();
	        	
	        	var storeIds = [];
	        	
	            for (var i = 0; i < offers.length; i++) {
	            	// generate the markers and icons for sidebar
	            	markers.push(addMarker(offers[i], i));
	            	var myHtml = []
	            	myHtml.push('<div class="offer pod cfx');
	            	
	            	if (offers[i].is_selfservice) {
	            		myHtml.push(' ss');
	            	}
	            	
	            	myHtml.push('" id="offer');
	            	myHtml.push(i.toString());
	            	myHtml.push('"><div class="icon"><a href="#" class="marker-icon category-sprite category-sprite-');
	            	myHtml.push(offers[i].category.toLowerCase().replace(/[^a-z]/g, ''));		
	            	myHtml.push('" id="marker');
	            	myHtml.push(i.toString());
	            	myHtml.push('"></a></div><div>');
	            	myHtml.push(offers[i].html);
	            	myHtml.push('</div></div>');
	                $("#sBarResults").append(myHtml.join(''));
	                
	                storeIds.push(offers[i].id);
	            }
	            
	            trackImpressions(storeIds);
	        } 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 google.maps.LatLng(lat, lng);
	    		var centerMarker = new google.maps.Marker({position: latLong});
	    		var centerHtml = '<strong>' + centerName + '</strong><br />';
            	if (typeof(centerAddr1) != 'undefined') {
            		centerHtml += centerAddr1 + '<br />'
            	}
            	if (typeof(centerAddr2) != 'undefined') {
            		centerHtml += centerAddr2 + '<br />'
            	}
	    		google.maps.event.addListener(centerMarker, "click", function() {
	    			infowindow.setContent(centerHtml);
	    		    infowindow.open(map, centerMarker);
	    		});
	            markers.push(centerMarker);	
	        }
	        mgr.addMarkers(markers);
	        $('#sBarResults').scrollTop(0);

	        _gaq.push(['_trackEvent', ANALYTICS_MAP, 'Map populated', 'At zoom level ' + map.getZoom(), new Date().getTime() - populateStarted]);
	        for (var i = 0; i < response['zips'].length; i++) {
	        	_gaq.push(['_trackEvent', ANALYTICS_MAP, 'Zip populated', response['zips'][i]]);
	        }
	    }, 'json');
	}
	
	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');
	    	}
	    }
	}

	this.getUrlFromMap = function() {
	    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(this.filterState) == 'undefined' || this.filterState == '') || this.filterState.indexOf('category') < 0)) {
	    	url += '?all=1';
	    } else
	    if (typeof(this.filterState) != 'undefined' && this.filterState != '') {
	    	url += '?' + this.filterState;
	    }
	    return url;
	}
	
	function addMarker(offer, offerNumber){
		var point = new google.maps.LatLng(offer.latitude, offer.longitude);
	    var myIcon = icons[offer.category];
	    var marker = new google.maps.Marker({position: point, icon: myIcon, shadow: icons['shadow']});

	    google.maps.event.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);
	    		infowindow.setContent($('<div></div>').append(offerHtml).html());
	    		infowindow.setPosition(point);
	            infowindow.open(map);

	            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]);
	            }
	        });
	    
	    return marker;
	}
	
	function triggerPopup(id) {
		if (map.getZoom() <= 13) {
			map.setCenter(markers[id].getPosition());
			map.setZoom(15);
		}
		google.maps.event.trigger(markers[id], 'click');
		return false;
	}
}

function ListingPageMapHandler() {
	var infowindow;
	var lettermarkers = [];
	
	this.initialize = function() {
    	infowindow = new google.maps.InfoWindow({maxWidth: 250});
    	setupLetterMarkers();
    	this.populate();
	}
	
	this.populate = function() {
		var grubbs = new Grubbs();
		var offerPoints = [];
		var latitudes = [];
		var longitudes = [];

		$('.offers .offer').each(function() {
    		var thisLatitude = parseFloat($(this).attr('latitude'));
    		var thisLongitude = parseFloat($(this).attr('longitude'));
    		offerPoints.push(new google.maps.LatLng(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;
	    	}
    	}

    	var bounds = new google.maps.LatLngBounds();
    	var i;
    	for (var i = 0; i < latitudes.length; i++) {
    		bounds.extend(new google.maps.LatLng(latitudes[i], longitudes[i]));
    	}

    	var mapOptions = {center: bounds.getCenter(), mapTypeId: google.maps.MapTypeId.ROADMAP, minZoom: 10, maxZoom: 17, mapTypeControl: false, streetViewControl: false};
    	map = new google.maps.Map(document.getElementById("map"), mapOptions);
    	map.fitBounds(bounds);

    	for (var i = 0; i < offerPoints.length; i++) {
            var letter = String.fromCharCode("A".charCodeAt(0) + i);
    		infoWindowHtml = '<div>' + $('#offer' + (i + 1)).html() + '<br/><br/></div>';
    		addMarker(offerPoints[i], letter, infoWindowHtml);
    	}
	}
	
	function setupLetterMarkers() {
		var spriteVarX = 0;
	    var spriteVarY = 0;
	    var spriteLoc = staticAssetPrefix + "/img/24/lettermarkers.png";
	    lettermarkers['shadow'] = new google.maps.MarkerImage("http://www.google.com/mapfiles/shadow50.png", new google.maps.Size(37, 34), null, new google.maps.Point(10, 34));
	    for (var i = 65; i < 91; i++) {
	    	if (i == 89) {
	    		spriteVarX = 70;
	    		spriteVarY = 0;
	    	}
	    	lettermarkers[String.fromCharCode(i)] = new google.maps.MarkerImage(spriteLoc, new google.maps.Size(20, 34), new google.maps.Point(spriteVarX, spriteVarY), new google.maps.Point(10, 34));
	    	spriteVarY += 84;
	    }
	}

	function addMarker(location, letter, infoWindowHtml) {
		var marker = new google.maps.Marker({position: location, icon: lettermarkers[letter], shadow: lettermarkers['shadow'], map: map});
		google.maps.event.addListener(marker, "click", function() {
			infowindow.setContent(infoWindowHtml);
		    infowindow.open(map, marker);
		});
	}
}

function trackImpressions(storeIds) {
	if (typeof(storeIds) != 'string') {
		storeIds = JSON.stringify(storeIds);
	}
	$.post('/i/t/', {'s': storeIds});
}

function trackOnlineImpressions(offerIds) {
	if (typeof(offerIds) != 'string') {
		offerIds = JSON.stringify(offerIds);
	}
	$.post('/i/to/', {'o': offerIds});
}

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", mapHandler.filterType, {expires:100, path: '/'}); }
function setFilterStateCookie() {
	if (mapHandler.filterType == 1) {
		var filterCookie = [];
		$('#filter-form .filter-checkbox').each(function() { filterCookie.push($(this).val() + "=" + $(this).is(':checked')); });
		filterCookie.push('v=3');
		$.cookie("fstate", filterCookie.join('&'), {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 checkForStateAndCityCookies() {
	if (getStateCookie() == null && getCityCookie() == null) {
		$.get('/my-location/', function(data) {
			if ('state' in data && 'cityName' in data) {
				buildCategoryLinks(data['state'], data['cityName']);
				setStateCookie(data['state']);
				setCityCookie(data['cityName']);
			}
		}, 'json');
	}
}

function alphanumericWithDashes(value) {
    value = $.trim(value.replace(/[^\w\s-]/g, ""));
    value = value.replace(/[-\s]+/g, "-");
    return value.toLowerCase();
}

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

function geocodeThenSearch() {
	var loc = $('#cpnMapSearchLoc').val();
	var geocoder = new google.maps.Geocoder();
	geocoder.geocode({'address': loc}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			var viewport = results[0].geometry.viewport;
			var viewportNE = viewport.getNorthEast();
			var viewportSW = viewport.getSouthWest();
			$('#cpnMapSearchViewportNELat').val(viewportNE.lat());
			$('#cpnMapSearchViewportNELng').val(viewportNE.lng());
			$('#cpnMapSearchViewportSWLat').val(viewportSW.lat());
			$('#cpnMapSearchViewportSWLng').val(viewportSW.lng());	
		}
		$('#searchForm').unbind('submit');
		$('#searchForm').submit();
	});
}

// 
// 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").not('#body-iframe').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() {
	$.ajaxSetup({
	    jsonp: null,
	    jsonpCallback: null
	});

	if ($.browser.msie && parseFloat($.browser.version) < 7 && typeof(DD_belatedPNG) != 'undefined') DD_belatedPNG.fix('button');

	if ($('#map').size() > 0) {
	    if (typeof(isMainPage) != 'undefined' && isMainPage) {
	    	checkForStateAndCityCookies(); // we want to swap out the category links on the main page with the user's location info
	    	mapHandler = new MainMapHandler();
	    	mapHandler.initialize();
	    	
	        // save the current filter/map settings before exit
	    	$(window).unload(function() {
		    	setLatCookie();
		    	setLongCookie();
		    	setZoomCookie();
		    	setFilterTypeCookie();
		    	setFilterStateCookie();
		    });
	    } else if (typeof(isListingPage) != 'undefined' && isListingPage) {
	    	mapHandler = new ListingPageMapHandler();
	    	mapHandler.initialize();
	    } else {
	    	if ($.browser.msie && parseFloat($.browser.version) < 7) DD_belatedPNG.fix('img.png');

	    	ANALYTICS_MAP += IFRAME_STR;
	    	ANALYTICS_FILTER_CATEGORY += IFRAME_STR;
	    	ANALYTICS_COUPON += IFRAME_STR;
	    	
	    	mapHandler = new MainMapHandler();
	    	mapHandler.filterState = $.param.querystring();
	    	mapHandler.initializeWidget();
	    	
	    	$('a.storename').live('click', function() {
	    		$(this).attr('target', '_blank');
	    	});
	    }
	}
    
    // 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();
    	mapHandler.filterState = $(this).serialize();
    	if ($(this).attr('id') == 'filter-form') {
    		mapHandler.filterType = 1;
    		$('a#filter-link-type').css('font-weight', 'bold');
    		_gaq.push(['_trackEvent', ANALYTICS_FILTER_CATEGORY, 'Apply filters']);
    	}
    	$('.filter-container-outer').hide();
    	mapHandler.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 google.maps.Geocoder();
            var address = $("#mapSearchInput").val();
            
            geocoder.geocode({'address': address}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					map.setCenter(results[0].geometry.location);
					map.setZoom(14);
			     } else {
			        alert('Sorry, the location "' + address + '" was not found.');
			     }
			});

            _gaq.push(['_trackPageview', "/search?q="+address]);
            return false;
    	}
    });
    
    $('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]);
    });
    
    try {
    	$(".fb").fancybox();
    } catch (e) {}

    $('#cpnMapSearchLoc').keypress(function() {
    	searchLocChanged = true;
    	$('#cpnMapSearchViewportNELat').val('');
		$('#cpnMapSearchViewportNELng').val('');
		$('#cpnMapSearchViewportSWLat').val('');
		$('#cpnMapSearchViewportSWLng').val('');
		$(this).unbind('keypress');
    });
    
    $('#searchForm').submit(function(e) {
    	var loc = $('#cpnMapSearchLoc').val();
    	if (searchLocChanged || loc == '') {
	    	e.preventDefault();
	    	if (loc == '') {
	    		var cityCookie = getCityCookie();
	    		var stateCookie = getStateCookie();
	    		if (cityCookie != null && stateCookie != null && cityCookie != '' && stateCookie != '') {
	    			loc = cityCookie + ', ' + stateCookie;
	    			$('#cpnMapSearchLoc').val(loc);
	    			geocodeThenSearch();
	    		} else {
	    			$.get('/my-location/', function(data) {
	    				if ('state' in data && 'cityName' in data) {
	    					setStateCookie(data['state']);
	    					setCityCookie(data['cityName']);
	    					loc = data['cityName'] + ', ' + data['state'];
	    	    			$('#cpnMapSearchLoc').val(loc);
	    	    			geocodeThenSearch();
	    				}
	    			}, 'json');
	    		}
	    	} else {
	    		geocodeThenSearch();
	    	}
    	} else {
    		return true;
    	}
    });
    
    $('#cat-tree').treeview({
		animated: "fast",
		prerendered: true
	});
});
