ARCTICBAY_QUEST = function () {
	var map, labels, names, media, rankings, drawControls, popup;
	var hoverFeature = null;
	var selectedFeature = null;
	var previouslySelectedFeature = null;
	var slideshow_html = "";
	var html = "";
									
	var myStyleMap = new OpenLayers.StyleMap({
								"clicked": new OpenLayers.Style({
											fillColor: "#ffffff",
											strokeColor: "#ff2200",
											fillOpacity: 0.1,
											hoverFillColor: "white",
											hoverFillOpacity: 0.8,
											strokeOpacity: 1,
											strokeWidth: 3,
											strokeLinecap: "round", //[butt | round | square]
											strokeDashstyle: "solid", //[dot | dash | dashdot | longdash | longdashdot | solid]
											hoverStrokeColor: "red",
											hoverStrokeOpacity: 1,
											hoverStrokeWidth: 0.2,
											pointRadius: 8,
											hoverPointRadius: 1,
											hoverPointUnit: "%",
											pointerEvents: "visiblePainted",
											cursor: ""
										}),
								"default": new OpenLayers.Style({
											fillColor: "#f8e900",
											fillOpacity: 0.4,
											hoverFillColor: "white",
											hoverFillOpacity: 0.8,
											strokeColor: "#f8e900",
											strokeOpacity: 1,
											strokeWidth: 3,
											strokeLinecap: "round", //[butt | round | square]
											strokeDashstyle: "solid", //[dot | dash | dashdot | longdash | longdashdot | solid]
											hoverStrokeColor: "red",
											hoverStrokeOpacity: 1,
											hoverStrokeWidth: 0.2,
											pointRadius: 6,
											hoverPointRadius: 1,
											hoverPointUnit: "%",
											pointerEvents: "visiblePainted",
											cursor: ""
										}),
								"select": new OpenLayers.Style({
											fillColor: "#0000ff",
											fillOpacity: 0.4,
											hoverFillColor: "white",
											hoverFillOpacity: 0.8,
											strokeColor: "#0000ff",
											strokeOpacity: 1,
											strokeWidth: 1,
											strokeLinecap: "round", //[butt | round | square]
											strokeDashstyle: "solid", //[dot | dash | dashdot | longdash | longdashdot | solid]
											hoverStrokeColor: "red",
											hoverStrokeOpacity: 1,
											hoverStrokeWidth: 0.2,
											pointRadius: 6,
											hoverPointRadius: 1,
											hoverPointUnit: "%",
											pointerEvents: "visiblePainted",
											cursor: "pointer"
										})
								});
	
	var insertSound = function (surl) {
		if (surl) {
			$('#dhtmlsound').html('<embed src="quest_media/' + surl + '" id="hoversound" hidden="true" autostart="true" loop="false" />');
		} else {
			$('#dhtmlsound').empty();
		}
	};
	
	var feature_side_info = function (feature) {
		slideshow_html = "";
		html = "";
		html += "<p><strong>" + feature.attributes.name + "</strong></p>";
		html += "<ul>";
		html += "<li><strong>Position:</strong> "+  feature.attributes.lat + " lat, " +  feature.attributes['long'] + " lon</li>";
		html += "<li><strong>Description:</strong> "+  feature.attributes.description + "</li>";
		
		
		html += "</ul><br />\r<table><thead><tr>";
		if (feature.attributes.place_id === 1) {
			html += '<th scope="row">Departure Time</th><th scope="row">Name</th><th scope="row">Community</th></tr></thead>\r<tbody>';
			var r;
			for(r in rankings.features) {
				if (rankings.features[r].attributes.place_id === feature.attributes.place_id) {
					html += "<tr>";
					html += "<td>" + rankings.features[r].attributes.start_time + "</td>";
					html += "<td>" + rankings.features[r].attributes.name + "</td>";
					html += "<td>" + rankings.features[r].attributes.community + "</td>";
					html += "</tr>";
				}
			}
		} else if (feature.attributes.place_id === 9) {
			html += '<th scope="row">Total Time</th><th scope="row">Name</th><th scope="row">Community</th></tr></thead>\r<tbody>';
			for(r in rankings.features) {
				if (rankings.features[r].attributes.place_id === feature.attributes.place_id) {
					html += "<tr>";
					html += "<td>" + rankings.features[r].attributes.total_time + "</td>";
					html += "<td>" + rankings.features[r].attributes.name + "</td>";
					html += "<td>" + rankings.features[r].attributes.community + "</td>";
					html += "</tr>";
				}
			}
		} else {
			html += '<th scope="row">Place</th><th scope="row">Name</th><th scope="row">Community</th></tr></thead>\r<tbody>';
			for(r in rankings.features) {
				if (rankings.features[r].attributes.place_id === feature.attributes.place_id) {
					html += "<tr>";
					html += "<td>" + rankings.features[r].attributes.placed + "</td>";
					html += "<td>" + rankings.features[r].attributes.name + "</td>";
					html += "<td>" + rankings.features[r].attributes.community + "</td>";
					html += "</tr>";
				}
			}
		}
		

		
		html += "</tbody></table>";
		
		for(var m in media.features) {
			if (media.features[m].attributes.place_id === feature.attributes.place_id) {
				if (media.features[m].attributes.filetype === "image") {
					slideshow_html += '<div><p>' + (media.features[m].attributes.caption || "&nbsp;") + '</p><img src="quest_media/' + media.features[m].attributes.filename + '" alt="' + (media.features[m].attributes.caption || "") + '"/></div>';
				} else if (media.features[m].attributes.filetype === "movie") {
					slideshow_html += '<div><p>' + (media.features[m].attributes.caption || "&nbsp;") + '</p><OBJECT classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320"' +
        									'height="256" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="src" value="quest_media/' +
        									media.features[m].attributes.filename +
        									'">' +
        									'<param name="autoplay" value="false">' +
        									'<param name="controller" value="true">' +
       										'<param name="loop" value="false">' +
        									'<EMBED src="quest_media/' +
        										media.features[m].attributes.filename +
        										'" width="320" height="256" autoplay="false" ' +
        										'controller="true" loop="false" pluginspage="http://www.apple.com/quicktime/download/">' +
        									'</EMBED>' +
        								'</OBJECT></div>';
				} else if (media.features[m].attributes.filetype === "sound") {
					slideshow_html += '<div><p>' + (media.features[m].attributes.caption || "&nbsp;") + '</p><OBJECT classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="320"' +
        									'height="16" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="src" value="quest_media/' +
        									media.features[m].attributes.filename +
        									'">' +
        									'<param name="autoplay" value="false">' +
        									'<param name="controller" value="true">' +
       										'<param name="loop" value="false">' +
        									'<EMBED src="quest_media/' +
        										media.features[m].attributes.filename +
        										'" width="320" height="16" autoplay="false" ' +
        										'controller="true" loop="false" pluginspage="http://www.apple.com/quicktime/download/">' +
        									'</EMBED>' +
        								'</OBJECT></div>';

				}
			}
		}
		$('#slideshow').html(slideshow_html);
		if (slideshow_html !== "") {
			html += '<p id="media_icon"><span onClick="$(\'#mediaViewer\').jqmShow();"><img src="images/media_icon.png" alt="View Media" width="64" height="64"/></span><br/><a href="#" onClick="$(\'#mediaViewer\').jqmShow();">View Media</a></p>';
			if ($('#slideshow > *').length > 1) {
				$('#slideshow').cycle({
					prev:		'#prev',
					next:		'#next',
					timeout:	0,
					after:		function(curr, next, opts) {
						$('#count').html((opts.currSlide+1) + "/" + opts.slideCount);
					}
				});
			} else {
				$('#count').html("1/1");
			}
		}
		$('#quest_dynamic').html(html);
		$('#quest_intro').hide();
	};
	
	var onClick = function(evt) {
	
			selectedFeature = this;
			if (previouslySelectedFeature) {
				if (previouslySelectedFeature.style) {
					delete previouslySelectedFeature.style;
					previouslySelectedFeature.renderIntent = 'default';
				}
			}
			selectedFeature.style = {};
			selectedFeature.style = myStyleMap.styles.clicked.defaultStyle;
			names.redraw();
			feature_side_info(selectedFeature);
			previouslySelectedFeature = this;
	        OpenLayers.Event.stop(evt);
	        this.layer.events.unregister('mousedown', this, onClick);
	};
	
	var onPopupClose = function (evt) {
        //drawControls.select.unselect(hoverFeature);
    };

    function onFeatureSelect(feature) {
		var feature_popup_html = "<div>";
		hoverFeature = feature;
		//for(var i in feature.attributes) feature_popup_html += "<li><b>" + i + "</b>: "+  feature.attributes[i] + "</li>";
		feature_popup_html += hoverFeature.attributes.name + "<br/>\n";
		feature_popup_html += "</div>";
		var popup_lonlat = hoverFeature.geometry.getBounds().getCenterLonLat();
    	popup = new OpenLayers.Popup.Anchored("chicken"
    						,popup_lonlat
    						,null
    						,feature_popup_html
    						,{ size: new OpenLayers.Size(10,10)
            					,offset: new OpenLayers.Pixel(-5,-5)
    						}
    						,false
    						,onPopupClose);
		popup.autoSize = true;
		popup.panMapIfOutOfView = true;
		popup.setOpacity("80");
    	hoverFeature.popup = popup;
    	map.addPopup(popup);
		for (var m in media.features) {
			if (media.features.hasOwnProperty(m)) {
				if (media.features[m].attributes.place_id === hoverFeature.attributes.place_id && media.features[m].attributes.filetype === "hoversound") {
					insertSound(media.features[m].attributes.filename);
				}
			}
		}
		hoverFeature.layer.events.registerPriority('mousedown', hoverFeature, onClick);
    }

    var onFeatureUnselect = function (feature) {
    	insertSound();
    	if (feature !== hoverFeature) {
    		map.removePopup(hoverFeature.popup);
			hoverFeature.popup.destroy();
        	hoverFeature.popup = null;
			hoverFeature.layer.events.unregister('mousedown', hoverFeature, onClick);
    	}
		map.removePopup(feature.popup);
		feature.popup.destroy();
        feature.popup = null;
		feature.layer.events.unregister('mousedown', feature, onClick);
    };

	return {
		init: function () {
			map = new OpenLayers.Map('map', {
				projection: new OpenLayers.Projection("EPSG:900913"),
				displayProjection: new OpenLayers.Projection("EPSG:4326"),
				units: "m",
				maxResolution: 156543.0339,
				maxExtent: new OpenLayers.Bounds(-20037508.34, -20037508.34,
					20037508.34, 20037508.34)
				});
			
			labels = new OpenLayers.Layer.WMS("Camp Labels",
												"/geoserver/wms",
			                                   {layers: "arcticbay:quests",
            			                        styles: "quest_style",
            			                        transparent: true});
            labels.singleTile = true;
            
			OpenLayers.Strategy.Fixed.prototype.preload=true;	
			
			names = new OpenLayers.Layer.Vector("Camps", {
					strategies: [new OpenLayers.Strategy.Fixed()],
					protocol: new OpenLayers.Protocol.HTTP({
						url: "/geoserver/wfs",
						params: {
							typename: "arcticbay:quests",
							service: "WFS",
							version: "1.0.0",
							request: "GetFeature",
							srsName: "EPSG:900913",
							bbox: '-20037508.34,-20037508.34,20037508.34,20037508.34',
							outputformat: 'json'
						},
						format: new OpenLayers.Format.GeoJSON()
					}),
					styleMap: myStyleMap
			});
	
			media = new OpenLayers.Layer.Vector("Media", {
				strategies: [new OpenLayers.Strategy.Fixed()],
				protocol: new OpenLayers.Protocol.HTTP({
					url: "/geoserver/wfs",
					params: {
						typename: "arcticbay:quest_contributions",
						service: "WFS",
						version: "1.0.0",
						request: "GetFeature",
						srsName: "EPSG:900913",
						bbox: '-20037508.34,-20037508.34,20037508.34,20037508.34',
						outputformat: 'json'
					},
					format: new OpenLayers.Format.GeoJSON()
				}),
				displayInLayerSwitcher: false,
				visibility: false
			});
			
			rankings = new OpenLayers.Layer.Vector("Rankings", {
				strategies: [new OpenLayers.Strategy.Fixed()],
				protocol: new OpenLayers.Protocol.HTTP({
					url: "/geoserver/wfs",
					params: {
						typename: "arcticbay:quest_rankings",
						service: "WFS",
						version: "1.0.0",
						request: "GetFeature",
						srsName: "EPSG:900913",
						bbox: '-20037508.34,-20037508.34,20037508.34,20037508.34',
						outputformat: 'json'
					},
					format: new OpenLayers.Format.GeoJSON()
				}),
				displayInLayerSwitcher: false,
				visibility: false
			});
			
			var gsat = new OpenLayers.Layer.Google(
				"Google Satellite",
				{type: G_SATELLITE_MAP, 'sphericalMercator': true}
			);
			var gphy = new OpenLayers.Layer.Google(
				"Google Physical",
				{type: G_PHYSICAL_MAP, 'sphericalMercator': true}
			);
			var ghyb = new OpenLayers.Layer.Google(
				"Google Hybrid",
				{type: G_HYBRID_MAP, 'sphericalMercator': true}
			);

	
			map.addLayers([gsat, ghyb, gphy, names, media, rankings, labels]);
	
			map.addControl(new OpenLayers.Control.MousePosition());
			map.addControl(new OpenLayers.Control.LayerSwitcher());
			//map.addControl(new OpenLayers.Control.DragPan());
	
			//var ddBounds = new OpenLayers.Bounds(-108,65,-88,70);
			var ddBounds = new OpenLayers.Bounds(-86.0,69.0,-81.5,73.5);
	
			map.zoomToExtent(
				ddBounds.transform(map.displayProjection, map.getProjectionObject())
			);
			
			drawControls = {
				selectNames: new OpenLayers.Control.SelectFeature(
					names,
						{
							hover: true,
							onSelect: onFeatureSelect,
							onUnselect: onFeatureUnselect
						}
					),
				selectMedia: new OpenLayers.Control.SelectFeature(
					media,
						{
							hover: true,
							onSelect: onFeatureSelect,
							onUnselect: onFeatureUnselect
						}
					)
			};
				
			for (var key in drawControls) {
				if (drawControls.hasOwnProperty(key)) {
					map.addControl(drawControls[key]);
				}
			}
			
			drawControls.selectNames.activate();
			//drawControls.selectMedia.activate();
				
		}
	};
}();
