var hr = hr || {};

hr.heroic_cities = {
    'juarez': {
        'lng': -106.425624, 'lat': 31.7311292
    },
    'newyork': {
        'lng': -74.0059731, 'lat': 40.7143528

    },
    'detroit': {
        'lng': -83.0457538, 'lat': 42.331427
    },
    'boston': {
        'lng': -71.0597732, 'lat': 42.3584308
    },
    'philly': {
        'lng': -75.163789, 'lat': 39.952335
    },
    'stlouis': {
        'lng': -90.224967, 'lat': 38.646991
    },
    'kazakhstan': {
        'lng': 76.9, 'lat': 43.25 // centered on almaty, for now?
    }
};

hr.heroic_cities['juarez']['boundaryVerticies'] =  [
	new OpenLayers.LonLat(-106.588088,31.779217),
	new OpenLayers.LonLat(-106.534188,31.777685),
	new OpenLayers.LonLat(-106.522773,31.766448),
	new OpenLayers.LonLat(-106.519339,31.766156),
	new OpenLayers.LonLat(-106.51479,31.756378),
	new OpenLayers.LonLat(-106.511357,31.755648),
	new OpenLayers.LonLat(-106.494277,31.743168),
	new OpenLayers.LonLat(-106.475652,31.746379),
	new OpenLayers.LonLat(-106.457713,31.759297),
	new OpenLayers.LonLat(-106.432994,31.748204),
	new OpenLayers.LonLat(-106.385444,31.72616),
	new OpenLayers.LonLat(-106.377204,31.706959),
	new OpenLayers.LonLat(-106.35463,31.691551),
	new OpenLayers.LonLat(-106.337035,31.655103),
	new OpenLayers.LonLat(-106.307853,31.613597),
	new OpenLayers.LonLat(-106.286395,31.587301),
	new OpenLayers.LonLat(-106.341891,31.58609),
	new OpenLayers.LonLat(-106.40506,31.581942),
	new OpenLayers.LonLat(-106.482595,31.605644),
    new OpenLayers.LonLat(-106.588088,31.779217)
];

hr.addMarker = function(ll, popupClass, popupContentHTML, closeBox, overflow) {
    var stacked = 0;
    for(var i=0; i<hr.markers.markers.length; i++) {
        var m = hr.markers.markers[i];
        if(ll.equals(m.lonlat)) {
            stacked++;
        }
    }
    var feature = new OpenLayers.Feature(hr.markers, ll); 
    feature.closeBox = closeBox;
    feature.popupClass = popupClass;
    feature.data.popupContentHTML = popupContentHTML;
    feature.data.overflow = (overflow) ? "auto" : "hidden";
	
    var size = new OpenLayers.Size(hr.ICONSZ,hr.ICONSZ);

    var xo = 0;
    var yo = 0;
    if(stacked) {
//        xo = parseInt((Math.random() > .5 ? 1 : -1) * Math.random() * ((stacked * stacked * 10) % 200));
//        yo = parseInt((Math.random() > .5 ? 1 : -1) * Math.random() * ((stacked * stacked * 10) % 200));
    }
    var offset = new OpenLayers.Pixel(xo,yo);
    feature.data.icon = new OpenLayers.Icon(hr.BUBBLE_IMG,size,offset);
    marker = feature.createMarker();
    marker._feature = feature;
    var markerClick = function (evt) {
        if (this.popup == null) {
            this.popup = this.createPopup(this.closeBox);
            hr.map.addPopup(this.popup);
            this.popup.show();
        } else {
            this.popup.toggle();
        }
        $(evt.srcElement).attr('src', hr.HIGHLIGHT_BUBBLE_IMG);
        currentPopup = this.popup;
        OpenLayers.Event.stop(evt);
    };
    marker.events.register("mousedown", feature, markerClick);
    hr.markers.addMarker(marker);
    return marker;
}

hr.shrink_marker = function(marker) {
    $(marker.icon.imageDiv).children("img").attr('src', hr.BUBBLE_IMG);
    $(marker.icon.imageDiv).children("img").animate({
	    height: hr.ICONSZ+"px",
	    width: hr.ICONSZ+"px"
	  }, 500 );
}

hr.grow_marker = function(marker) {
    $(marker.icon.imageDiv).children("img").attr('src', hr.HIGHLIGHT_BUBBLE_IMG);
    $(marker.icon.imageDiv).children("img").animate({
	    height: hr.BIGICONSZ+"px",
	    width: hr.BIGICONSZ+"px"
	  }, 500 );
}

hr.bounce_around = function() {
    var map = hr.map;
    var ridx;
    do {
        ridx = parseInt(Math.random()*hr.markers.markers.length) % hr.markers.markers.length;
    } while(hr.markers.markers[ridx] === hr._last_highlighted_marker);
    var marker = hr.markers.markers[ridx];
    var report = marker._feature.data.report;


	$("#highlightcontents").fadeOut(0, function() {
        var rhtm = '<h2>'+$('<div/>').text(report.title).html()+'</h2>';
        rhtm += $('<div/>').text(report.incident).html();
        $("#highlightcontents").html(rhtm);
		map.panTo(marker.lonlat);

        if(hr._last_highlighted_marker)
            hr.shrink_marker(hr._last_highlighted_marker);
        
        hr._last_highlighted_marker = marker;

        hr.grow_marker(marker);
		$("#highlightcontents").fadeIn(500);
	});

}

hr.hasBoundaryPolygon = function(){
	return hr.heroic_cities[hr.current_city]['boundaryVerticies']!=null;
}

hr.withinBoundaryPolygon = function(lonLat) {
    if (!hr.hasBoundaryPolygon()) {
		return true;
	}
    var p = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
	var isContained = hr.heroic_cities[hr.current_city]['boundaryFeature'].geometry.containsPoint(p);
	return isContained;
}

hr.init = function(){
    hr.map = new OpenLayers.Map(hr.map_el, { 
        maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),
        numZoomLevels: 19,
        maxResolution: 156543.0399,
        units: 'm',
        controls: [],
        projection: new OpenLayers.Projection("EPSG:900913"),
        displayProjection: new OpenLayers.Projection("EPSG:4326")
    });
    //hr.map.addControl(new OpenLayers.Control.PanZoomBar());
    var navctrl = new OpenLayers.Control.Navigation();
    hr.map.addControl(navctrl);
    //navctrl.disableZoomWheel();
    hr.map.addControl(new OpenLayers.Control.KeyboardDefaults());

    //var layerTah = new OpenLayers.Layer.OSM.Osmarender("Tiles@Home");
    var glayer = new OpenLayers.Layer.CloudMade("CloudMade", {
        key: '3bb82639a274433fb30120279ea08c76',
        styleId: 4993,
        sphericalMercator:true,
        wrapDateLine: true			
    });
    hr.map.addLayers([glayer]);

    hr.markers = new OpenLayers.Layer.Markers("Markers");
    hr.map.addLayer(hr.markers);
    hr.map.setCenter(
        new OpenLayers.LonLat(
            hr.heroic_cities[hr.current_city].lng, 
            hr.heroic_cities[hr.current_city].lat
        ).transform(
            new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")
        ), 
        13
    );

    AutoSizeFramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {'autoSize': true});
    var popupClass = AutoSizeFramedCloud;
        
	if ( hr.hasBoundaryPolygon() ) {
		// draw the boundary polygon
		var vectorLayer = new OpenLayers.Layer.Vector("Vector Layer");
		if (hr.DRAW_BOUNDARY_POLYGON) {
			hr.map.addLayer(vectorLayer);
		}
		var points = [];
		for (var p = 0; p < hr.heroic_cities[hr.current_city]['boundaryVerticies'].length; p++) {
			var newLonLat = hr.heroic_cities[hr.current_city]['boundaryVerticies'][p].transform(
			     new OpenLayers.Projection("EPSG:4326"), hr.map.getProjectionObject());
			//hr.addMarker(newLonLat, popupClass, 'Anchor', true, true);
			points.push(new OpenLayers.Geometry.Point(newLonLat.lon, newLonLat.lat));
		}
		
		var linearRing = new OpenLayers.Geometry.LinearRing(points);
		var polygonStyle = {
			strokeColor: "#000000",
			strokeOpacity: 0.5,
			strokeWidth: 2,
			fillColor: "#000000",
			fillOpacity: 0.2
		};
		var polygon = new OpenLayers.Geometry.Polygon([linearRing]);
		var polygonFeature = new OpenLayers.Feature.Vector(polygon,null, polygonStyle);
		hr.heroic_cities[hr.current_city]['boundaryFeature'] = polygonFeature;
		vectorLayer.addFeatures([polygonFeature]);
	}
		
    if(hr.reportlist) {
		var contained = 0;
		var outside = 0;
        var stacked = 0;
        for(var i=0; i<hr.reportlist.length; i++) {
            var report = hr.reportlist[i];
            if(report.lat && report.lng) {	

                var lonLat = new OpenLayers.LonLat(report.lng, report.lat).transform(new OpenLayers.Projection("EPSG:4326"), hr.map.getProjectionObject());
                                        
			    if (hr.hasBoundaryPolygon()) {
					// HACK: randomly distribute stacked markers inside the bounds
					var duplicatePositions = 0;
					for (var j = 0; j < hr.reportlist.length; j++) {
						var r = hr.reportlist[j];
						if (r.lat == report.lat && r.lng == report.lng) {
							duplicatePositions++;
						}
					}
					if (duplicatePositions > 0) {
						stacked++;
						var attempts = 0;
						var withinBound = false;
						do {
							
							// DOUBLE HACK: this math is highly tuned to the Juarez site
							var addinLon = Math.random() * duplicatePositions * 10 + 2000*Math.random();
							addinLon = addinLon - (duplicatePositions*10 + 2000)/2;
                            var addinLat = Math.random() * duplicatePositions * 10 + 2000*Math.random();
							addinLat = addinLat - (duplicatePositions*10 + 2000)/2;
							                            
							var randomLonLat = lonLat.add(addinLon, addinLat);
							lonLat = randomLonLat;
							attempts++;
						}
						while (!hr.withinBoundaryPolygon(lonLat) && (attempts < 5));
					}
					if (hr.withinBoundaryPolygon(lonLat)) {
						contained++;
					}
					else {
						outside++;
			    		// TRIPLE HACK: force any markers still outside the bounds to be stacked at the map center
				        lonLat = new OpenLayers.LonLat(hr.heroic_cities[hr.current_city].lng,
			                hr.heroic_cities[hr.current_city].lat).transform(
			                    new OpenLayers.Projection("EPSG:4326"), new OpenLayers.Projection("EPSG:900913")
				           ); 
					}
				}

                var incident = report.incident;
                var imgstr = '';
                if(report.image) {
                    imgstr = '<div style="height:200px; background: #fff url("/assets/uploads/'+hr.current_city+'/'+report.image+
                        '") top left no-repeat;" class="previewimage"></div>';
                } 
                var m = hr.addMarker(lonLat, popupClass, '<h4 style="margin-bottom:5px;"><a href="report/'+report.id+'">'+
                    report.title+'</a></h4>'+incident+imgstr, true, true
                );
                m._feature.data.report = report;
            }
        }
		//alert("contained="+contained+" , outside="+outside+" , stacked="+stacked);
    }
    if(hr.do_rand_reports) {
        setInterval(hr.bounce_around, hr.BOUNCE_INTERVAL*1000);
        hr.bounce_around();
    }
};

hr.DRAW_BOUNDARY_POLYGON = false;
hr.ICONSZ = 20;
hr.BIGICONSZ = 35;
hr.BOUNCE_INTERVAL = 10; // in seconds
hr.HIGHLIGHT_BUBBLE_IMG = 'assets/images/otherbubble-blue.png';
hr.BUBBLE_IMG = 'assets/images/otherbubble.png';

$(document).ready(function() {
    hr.init();
});

