jQuery(document).ready(function(){
	init();
	
	if(jQuery("#none")) {
		jQuery("#none").click(function(){
		 	 toggleControl(this);
		});
	}
	if(jQuery("#line")) {
		jQuery("#line").click(function(){
		 	 toggleControl(this);
		});
	}
	if(jQuery("#widescreen")) {
		jQuery("#widescreen").click(function(){
			wideScreen(this);
		});
	}

	if(jQuery("#clearsearch")) {
		jQuery("#clearsearch").click(function(){
			clearSearch('all');
		});
	} 
	if(jQuery("#clearThemesButton")) {
		jQuery("#clearThemesButton").click(function(){
			clearThemes();
		});
	} 
	
	if(jQuery("#userlocationsearch")) {
		jQuery("#userlocationsearch").click(function(){
			userLocationSearch();
		});
	}
	if(jQuery("#btnYouarehere")) {
		jQuery("#btnYouarehere").click(function(){
			toggleYouAreHere(this);
		});
	}
	if(jQuery("#arblegend")) {
		jQuery("#arblegend").click(function(){
			showArbLegend();
		});
	}
	if(jQuery("#btnTrees")) {
		jQuery("#btnTrees").click(function(){
			 btnTrees();
		});
	}
	if(jQuery("#parklegend")) {
		jQuery("#parklegend").click(function(){
			showParkingLegend();
		});
	}
	if(jQuery("#btnPark")) {
		jQuery("#btnPark").click(function(){
			btnPark();
		});
	}
	
	//the tabs  detailsTab && searchTab
	if(jQuery("#detailsTab")) {
		jQuery("#detailsTab").click(function(){
			toggleTabs('infoPanel', this);
		});
	}
	if(jQuery("#searchTab")) {
		jQuery("#searchTab").click(function(){
			toggleTabs('searchResults', this);
		});
	}
	
	//get all the li's w/ .togglegml and make them clickable w/ this fcn:  toggleGML(elem)
	jQuery(".togglegml").click(function(){
		toggleGML(this);
	});
});
/** Styling of OSM Layers **/

var test = 0;
function style_osm_feature(feature) {
	feature.style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
	if(feature.attributes.loctype == 7) {
		feature.style.strokeColor = "#"+locCategories[feature.attributes.loctype][2];
		feature.style.fillOpacity = 0;
		feature.style.strokeDashstyle = "solid";
		feature.style.strokeWidth = 0;
	}
	else if(feature.attributes.loctype != null && feature.attributes.loctype != 0  && locCategories[feature.attributes.loctype] != null)
	{
		if(locCategories[feature.attributes.loctype][1] == true) //highlight
		{
			if(locCategories[feature.attributes.loctype][4] == 1) //pointlayer
			{
				var shadowImg = sLocalBasePath+"resources/imx/marker_shadow.png";
				if(feature.attributes.loctype == 14){shadowImg = "";}
				feature = addMarker(feature, locCategories[feature.attributes.loctype][6], shadowImg,36);
			}
			else if(locCategories[feature.attributes.loctype][4] == 2) //linelayer
			{
				feature.style.strokeColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillOpacity = .4;
				feature.style.strokeWidth = 2;
			}
			else {
				feature.style.strokeColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillOpacity = .6;
				feature.style.strokeDashstyle = "solid";
			}
		}
		else 
		{		
			if(locCategories[feature.attributes.loctype][3] == true) //visable
			{
				feature.style = styleStandard;
			}
			else
			{
				feature.style = styleHidden;
			}
		}
	}
	else {
		feature.style = styleStandard;
	}
	
	aFeatures[aFeatures.length] = feature;
}

function on_feature_deselect(feature) {
	style_osm_feature(feature);
	redrawLayers();
} 


function on_feature_select(feature) {
	feature.style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
	if(feature.attributes.loctype == 7) {
				feature.style.strokeColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillOpacity = 0;
				feature.style.strokeDashstyle = "solid";
				feature.style.strokeWidth = 2;
	}
	else if(feature.attributes.loctype != null && feature.attributes.loctype != 0  && locCategories[feature.attributes.loctype] != null)
	{
		if(locCategories[feature.attributes.loctype][1] == true) //highlight
		{
			if(locCategories[feature.attributes.loctype][4] == 1) //pointlayer
			{
				var shadowImg = sLocalBasePath+"resources/imx/marker_shadow.png";
				if(feature.attributes.loctype == 14){shadowImg = "";}
				feature = addMarker(feature, locCategories[feature.attributes.loctype][5], shadowImg,36);
			}
			else if(locCategories[feature.attributes.loctype][4] == 2) //linelayer
			{
				feature.style.strokeColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillOpacity = .6;
				feature.style.strokeWidth = 1;
			}
			else {
				feature.style.strokeColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillColor = "#"+locCategories[feature.attributes.loctype][2];
				feature.style.fillOpacity = .6;
				feature.style.strokeDashstyle = "solid";
			}
		}
		else 
		{		
			if(locCategories[feature.attributes.loctype][3] == true) //visable
			{
				feature.style = styleHighlight;
			}
			else
			{
				feature.style = styleHidden;
			}
		}
	}
	else {
		feature.style = styleHighlight;
	}
	if(document.getElementById('tabs') != null) {
		toggleTabs('infoPanel');
	}
	redrawLayers();
    formatDetailAreaByFeature(feature);
}   


/** Styling of Content Window **/


function popup_formatDetailArea(feature)
{
    var name = "";
    var x = "";
    var y = "";
	
    if (feature.attributes['name'] != null) {name = feature.attributes['name'];}
    if (feature.attributes['x'] != null) {x = feature.attributes['x'];}
    if (feature.attributes['y'] != null) {y = feature.attributes['y'];}
	
	var eA = document.createElement('a');
	eA.href = sLocalBasePath + 'locationInfo.php?x='+x+'&y='+y;
	eA.title = name;
	eA.rel = 'mediabox[480 380]';
	Mediabox.click(eA);
	return '';
}
function formatDetailAreaByFeature(feature){
	formatDetailArea(feature.attributes['umid'],feature.attributes['loctype']);
}
function formatDetailArea(umid,loctype,resultDiv) {
	var text = 'not found';
	if(resultDiv == '' || resultDiv == null){resultDiv = 'infoPanel';}
	if(umid != null)
	{
		var strURL = sLocalBasePath+'admin/action.php';
		jQuery.post(strURL,{
			action: "formatLocationData",
			loctype: loctype,
			umid: umid
			}, 
			function(xml) {
				
				$(resultDiv).innerHTML = xml;
				
				tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
				imgLoader = new Image();// preload image
				imgLoader.src = tb_pathToImage;
			}
		);
	}
	else {
		$("infoPanel").innerHTML = text;
	}
    return true;
}
function formatDetailArea_from_gml(feature){
    var text = "";
    var img = "";
    var name = "";
    var type = "";
    var x = "";
    var y = "";
    var description = "";
    
    if (locCategories[feature.attributes['loctype']] != null) {type = locCategories[feature.attributes['loctype']][0];}
    if (feature.attributes['name'] != null) {name = feature.attributes['name'];}
    if (feature.attributes['descrip'] != null) {description = feature.attributes['descrip'];}
    if (feature.attributes['x'] != null) {x = feature.attributes['x'];}
    if (feature.attributes['y'] != null) {y = feature.attributes['y'];}
    
    if (feature.attributes['img'] != null) {img = feature.attributes['img'];}
    //else if(feature.attributes['layertype'] == 3) {img = sLocalBasePath+"resources/imx/map/busstop.jpg";}
    else {img = sLocalBasePath+"resources/imx/map/default.jpg";}
    
    text += "<div><h2>" + name + "</h2>";
    if(privLevel <= 1) {
        text += "<p>[<a href='"+sLocalBasePath+"/admin/locationInfo.php?x="+x+"&y="+y+"'  rel=\"mediabox[640 360]\" onclick='return Mediabox.click(this)'>edit</a>]</p>";
		//text += "<p><a onclick='return Mediabox.click(this)' href='http://www.youtube.com/watch?v=l9MdgSUpG5U' rel='mediabox[480 380]' title='www.youtube.com'>play YouTube »</a></p>";
    }
    if (type != "") {
        text += "<p><strong>Type</strong>: " + type + "</p>";
    }
    if (description != "") {
   		text += "<p><strong>Description</strong>: " + description + "</p>";
    }
    text += "</div><span><img src='" + img + "' alt='image of " + name + "' title='image of " + name + "'/></span>";
    
    return text;
}

/** add GML Layers **/

function addGMLlayer(layerName, gmlFile, map)
{
	layer = new OpenLayers.Layer.GML(layerName, gmlFile, 
	{
        format: OpenLayers.Format.GML, 
        formatOptions: {
			extractStyles: true, 
			extractAttributes: true
    	}
   	});
	layer.units = 'm';
	/*
	var welcomeMessage = $("infoPanel").innerHTML;
	layer.events.register("loadstart", null, function() { $("infoPanel").innerHTML = welcomeMessage; })
	layer.events.register("loadend", null, function() { $("infoPanel").innerHTML = welcomeMessage; })
    */
	layer.preFeatureInsert = style_osm_feature; 

	var sf = new OpenLayers.Control.SelectFeature(layer, {
		'onSelect': on_feature_select,
		'onUnselect': on_feature_deselect
		});
		
    if (typeof(sf.handlers) != "undefined") { // OL 2.7
        sf.handlers.feature.stopDown = false;
    } else if (typeof(sf.handler) != "undefined") { // OL < 2.7
        sf.handler.stopDown = false; 
        sf.handler.stopUp = false; 
    } 
    
	map.addControl(sf);
	sf.activate();
 	map.addLayer(layer);
	gmlLayer = layer;
	aLayers[aLayers.length] = layer;
	return map;
}

/** create controlshttp://10.10.18.201/OpenLayers-2.7/examples/measure.html **/
function addMapControls(map){

	//style the sketch fancy
	sketchSymbolizers = {
		"Point": {
		    pointRadius: 4,
		    graphicName: "square",
		    fillColor: "white",
		    fillOpacity: 1,
		    strokeWidth: 1,
		    strokeOpacity: 1,
		    strokeColor: "#333333"
		},
		"Line": {
		    strokeWidth: 3,
		    strokeOpacity: 1,
		    strokeColor: "#666666",
		    strokeDashstyle: "dash"
		},
		"Polygon": {
		    strokeWidth: 2,
		    strokeOpacity: 1,
		    strokeColor: "#f0f",
		    fillColor: "white",
		    fillOpacity: 0.3
		}
	};
	var style = new OpenLayers.Style();
	style.addRules([new OpenLayers.Rule({symbolizer: this.sketchSymbolizers})]);
	var styleMap = new OpenLayers.StyleMap({"default": style});
	
	var options = {
		handlerOptions: {
		    style: "default", // this forces default render intent
		    layerOptions: {styleMap: styleMap},
		    persist: true
		}
	};
	measureControls = {
		//polygon: new OpenLayers.Control.Measure(OpenLayers.Handler.Polygon, options),
		line: new OpenLayers.Control.Measure(OpenLayers.Handler.Path, options)
	};
	    
	var control;
	for (var key in measureControls) {
		control = measureControls[key];
		control.events.on({
			//"measurepartial": handleMeasurements,
			"measure": handleMeasurements
		});
		map.addControl(control);
	}

	var navigation = new OpenLayers.Control.Navigation({'zoomWheelEnabled': false});
	map.addControl(navigation);
	
	map.addControl(new OpenLayers.Control.PanZoomBar());
    map.addControl(new OpenLayers.Control.Permalink());
    map.addControl(new OpenLayers.Control.ScaleLine());            
	//map.addControl(new OpenLayers.Control.LayerSwitcher({'div':OpenLayers.Util.getElement('layerswitcher')}));
	//map.addControl(new OpenLayers.Control.MousePosition());

	return map;
}

function convertToFeet(distance, units)
{
	var feet = 0;
	var englishUnits = new Array();
	if(units == 'km') {
		feet = (distance*1000) * 3.2808;
	} else if(units == 'm') {
		feet = distance * 3.2808;
	}
	if(feet > 5280) { 
		englishUnits[0] = roundNumber(feet/5280,2);
		englishUnits[1] = 'miles';
		englishUnits[2] = roundNumber(feet/2.6,0);
		englishUnits[3] = 'steps';
	}
	else { 
		englishUnits[0] = roundNumber(feet, 2);
		englishUnits[1] = 'feet';
		englishUnits[2] = roundNumber(feet/2.6,0);
		englishUnits[3] = 'steps';
	}
	return englishUnits;
}

function roundNumber(num, dec) {
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}
var distanceInfo = "";
function handleMeasurements(event) {
    var geometry = event.geometry;
    var units = event.units;
    var order = event.order;
    var measure = event.measure;
    var cont_feet = document.getElementById('dist_feet');
    var cont_steps = document.getElementById('dist_steps');
    var out = "";
	var engUnits = convertToFeet(measure.toFixed(3), units);
	var distElem = document.getElementById('distData');
	if(distanceInfo == "") {
   		distanceInfo = distElem.innerHTML;
	}
	distElem.innerHTML =  distanceInfo + "<li><strong>" + engUnits[1] + "</strong>: "+engUnits[0]+"</li><li><strong>" + engUnits[3] + "</strong>: "+engUnits[2]+"</li>";  

}

function toggleToolIcon(element){
	document.getElementById('line').src = document.getElementById('line').src.replace('On.png','.png');
	document.getElementById('none').src = document.getElementById('none').src.replace('On.png','.png');
	
	element.src = element.src.replace('.png','On.png');
}

function toggleControl(element) {
	toggleToolIcon(element);
    for(key in measureControls) {
        var control = measureControls[key];
        if(element.id == key) {
			var distContent = "<h3 class='dist'>Distance</h3>"+
								"<ul class='toolbox' id='distData'>"+
								"<li class='info'>Click to draw the path you would like to measure, then <strong>double click</strong> to calculate the distance.</li>" +
								"</ul>";
			document.getElementById('infoPanel').innerHTML = distContent;
			if (document.getElementById('tabs') != null) {
				toggleTabs('infoPanel');
			}
            control.activate();
        } else {
            control.deactivate();
        }
    }
}
searchMarkerSize = new OpenLayers.Size(21,25);
highlightMarkerSize = new OpenLayers.Size(22,26);
hereMarkerSize = new OpenLayers.Size(20,20);
markerOffset = new OpenLayers.Pixel(-(searchMarkerSize.w/2), -(searchMarkerSize.h/2));
searchMarkerIcon = new OpenLayers.Icon(sLocalBasePath+'resources/imx/searchMarker2.png',searchMarkerSize,markerOffset);
highlightMarkerIcon = new OpenLayers.Icon(sLocalBasePath+'resources/imx/searchMarker2on.png',highlightMarkerSize,markerOffset);
markerHereIcon = new OpenLayers.Icon(sLocalBasePath+'resources/imx/hereMarkerBig.png',hereMarkerSize,markerOffset);

var arb;
function init() {
	
	map = new OpenLayers.Map($('map'),
    {   
		controls: [],
		maxResolution: 4.832,
        numZoomLevels: 5,
		projection: new OpenLayers.Projection("EPSG:32612"),
		units: "m",
		maxExtent: new OpenLayers.Bounds(272120,5193577,273356,5194814)
	});
	
	
   var base = new OpenLayers.Layer.TMS("Base","http://map.umt.edu/tilecache/tilecache.py/", {
					serviceVersion: "1.0.0", 
					layername: "utm3D",  
					type: "png?FORCE=1" 
				});
   arb = new OpenLayers.Layer.WMS("Trees", "http://map.umt.edu/tilecache/tilecache.py/",  {  
					transparent: 'true',
					layers: "utmArb"
				});
				
	arb.visibility = false;
	   park = new OpenLayers.Layer.WMS("Parking", "http://tssmaps.ito.umt.edu/tilecache/tilecache.py/",  {  
			transparent: 'true',
			layers: "utmPark"
		});
		
	   park.visibility = false;
	if(locId != '' && locId != -1) {
		var geoRssUri = sLocalBasePath+'service.php?action=lookup&term='+locId;
		current = new OpenLayers.Layer.GeoRSS('Location', geoRssUri, {icon: markerHereIcon});
		current.markerClick = function(evt) { OpenLayers.Event.stop(evt); }
		current.visibility = true;
	}
	map.addLayer(base);
	if(current != null) {
		map.addLayer(current);
	}
    map.setBaseLayer(base);
	//alert(addedOptions);
	map = addGMLlayer("gml", sLocalBasePath+"resources/gml/gml.php?themes="+addedOptions, map);
	//add custom map contols
	map = addMapControls(map);
		
	if (permalink == false) {
		var x = 272573;
		var y = 5193951;
		var zoom = 2;
    	map.setCenter(new OpenLayers.LonLat(x, y), zoom);
	}
}

function moveLayerToTop(layer)
{
	map.raiseLayer(layer, map.getNumLayers());
}

function showArbLegend(){
	
	toggleTabs('infoPanel');
	var content = "	<div class='arb_grid_sm'>" +
						"<h4 class='center'>Arboretum Legend</h4>" +
						"<ul>" +
						"	<li class='arbcol1'><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=ponderosa&TB_iframe=true&height=630&width=893' title=''>Ponderosa Pine</a></li>" +
						"	<li><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=cedar&TB_iframe=true&height=630&width=893' title=''>Cedar</li>" +
						"	<li class='arbcol1'><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=maple&TB_iframe=true&height=630&width=893' title=''>Maple</li>" +
						"	<li><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=aspen&TB_iframe=true&height=630&width=893' title=''>Aspen</li>" +
						"	<li class='arbcol1'><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=larch&TB_iframe=true&height=630&width=893' title=''>Larch</li>" +
						"	<li><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=fir&TB_iframe=true&height=630&width=893' title=''>Fir</li>" +
						"	<li class='arbcol1'><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=honeylocust&TB_iframe=true&height=630&width=893' title=''>Honey Locust</li>" +
						"	<li><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=othercon&TB_iframe=true&height=630&width=893' title=''>Other Coniferous</li>" +
						"	<li class='arbcol1'><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=spruce&TB_iframe=true&height=630&width=893' title=''>Spruce</li>" +
						"	<li><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=juniper&TB_iframe=true&height=630&width=893' title=''>Juniper</li>" +
						"	<li class='arbcol1'><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=apple&TB_iframe=true&height=630&width=893' title=''>Apple</li>" +
						"	<li><a class='thickbox' href='"+sLocalBasePath+"arboretum/arbdetails.php?active=otherdec&TB_iframe=true&height=630&width=893' title=''>Other Deciduous</li>" +
						"</ul>" +
					"</div>" +
					"<h4>More...</h4>" +
					"<ul>" +
					"	<li class='arbmore'><a class='thickbox external' href='"+sLocalBasePath+"arboretum/arbdetails.php?TB_iframe=true&height=630&width=893'>Take a campus tree tour</a></li>" +
					"</ul>";
	document.getElementById('infoPanel').innerHTML = content;
	
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
}
function showParkingLegend(){
	
	toggleTabs('infoPanel');
	var content =   "<p class='parkclick'>Click on parking lots for detailed lot information</p>" +
					"	<div class='park_grid_sm'>" +
						"<h4 class='center'>Parking Legend</h4>" +
						"<ul class=\"parking_legend\">" +
						"	<li>ADA Accessible Parking</li>" +
						"	<li>A & C Decal or Day Pass</li>" +
						"	<li>A & C Decal or Day Pass<br/><em>No Parking 2am - 5am</em></li>" +
						"	<li>Quick Stop, Special Permit or<br/>Service and Delivery</li>" +
						"	<li>Metered Parking<br/><em>No Parking 2am - 5am</em></li>" +
						"	<li>Reserved<br/><em>No Parking 2am - 5am</em></li>" +
						"</ul>" +
					"</div>";
	document.getElementById('infoPanel').innerHTML = content;
	
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
}
function btnTrees() { 
	if(document.getElementById('btnTrees').className == 'active') {
		document.getElementById('btnTrees').className = ''; 
		arb.visibility = false;
		map.removeLayer(arb);
	}
	else {
		document.getElementById('btnTrees').className = 'active';
		arb.visibility = true;
		map.addLayer(arb);
		layers = map.getLayersByName('gml');
		moveLayerToTop(layers[0])
		showArbLegend();
	}
 }
function btnPark() { 

	var li = document.createElement('li');
	li.id = "theme_7";
	if(document.getElementById('btnPark').className == 'active') {
		document.getElementById('btnPark').className = ''; 
		park.visibility = false;
		map.removeLayer(park);
		li.className = "active togglegml";
	}
	else {
		document.getElementById('btnPark').className = 'active';
		park.visibility = true;
		map.addLayer(park);
		layers = map.getLayersByName('gml');
		moveLayerToTop(layers[0])
		showParkingLegend();
		li.className = "inactive togglegml";
	}
	toggleGML(li);
 }
