$(function() {
	// Reject unsupported browsers
	/* Supported browsers:
		FF 2, 3, 3.5+
		IE 6, 7, 8+
		Chrome 4, 5, 6+
		Safari 3, 4, 5+
	*/
	$.reject({
		display: ['firefox', 'chrome', 'msie', 'safari'],
		browserInfo: {
			firefox: {
				text: 'Firefox'
			},
			chrome: {
				text: 'Google Chrome'
			},
			msie: {
				text: 'Internet Explorer'
			},
			safari: {
				text: 'Apple Safari'
			}
		},
		imagePath: '/wordpress/wp-content/themes/stockdale/images/browsers/',
		reject: {
			msie: false, msie5: true, msie6: false, msie7: false, msie8: false, // MSIE Flags
			firefox: false, firefox1: true, firefox2: false, firefox3: false, // Firefox Flags
			konqueror: true,
			chrome: false, chrome1: true, chrome2: true, chrome3: true, chrome4: true, chrome5: false, chrome6: false,// Chrome Flags (Global, 1-4) 
			safari: false, safari2: true, safari3: false, safari4: false, safari5: false, // Safari Flags (Global, 1-4) 
			opera: true,
			unknown: true // Unknown covers everything else 
		},
		closeCookie: false, 	// Only show once per session
		cookieSettings: {
			expires: 0		// Expires after current session
		}
	});
	
	// If IE6 run pngFix
	$("body").pngFix();
	$("body").css("visibility", "visible");
});
	
Site = {
	Map: {
		/* Attributes */
		map: null,
		infoWindow: null,
		polygons: [],
		
		/* Options */
		showRandom: true,
		
		/* Functions */
		init: function() {
			var map = new google.maps.Map(document.getElementById("map"), {
				center: new google.maps.LatLng(38, -95), // USA
				mapTypeControl: false,
				mapTypeId: google.maps.MapTypeId.ROADMAP,
				scrollwheel: false,
				zoom: 5
			});
			var bounds = null;
			// Set up zoom limits
			google.maps.event.addListener(map, 'zoom_changed', function() {
	              if (map.getZoom() < 5) map.setZoom(5);
				  if (map.getZoom() > 6) map.setZoom(6);
			}); 
			/* TODO Set the lat long limit
			google.maps.event.addListener(map, 'bounds_changed', function() { 
				var northEast = map.getBounds().getNorthEast();
				var southWest = map.getBounds().getSouthWest();
				var west = southWest.lng();
				var east = northEast.lng();
				var north = northEast.lat();
				var south = southWest.lat();
				// If this is the first rebounding, let's cache the current bounds
				if (!bounds) {
					bounds = {
						west: west,
						east: east,
						north: north,
						south: south
					};
				} else {
					// If out of bounds in any direction
					var rebound = {
						west: bounds.west,
						east: bounds.east,
						north: bounds.north,
						south: bounds.south
					};
					if (west < bounds.west - 20) {
						rebound.west = bounds.west - 20;
						rebound.east = bounds.east - 20;
					}
					if (east > bounds.east + 15)
						rebound.east = bounds.east + 15;
					if (north > bounds.north + 10)
						rebound.north = bounds.north + 10;
					map.fitBounds(new google.maps.LatLngBounds(
									new google.maps.LatLng(rebound.south, rebound.west), 
									new google.maps.LatLng(rebound.north, rebound.east))
					);
				}
			});
			*/
			this.infoWindow = new google.maps.InfoWindow();
			this.map = map;
			
			// Place each person
			var personElement = '.person';
			$(personElement).each(function() {
				var person = {};
				try {
					var content = $(this).children('.content')[0];
					var latlong = $(this).children('.latlong')[0];		
					var radius = parseInt($($(this).children('.radius')[0]).text());
				} catch (exception) {
					throw Exception("Could not get person");
				}
				if (content)
					person.content = $(content).html();
				else throw Exception("Could not get content for person");
				if (latlong) {
					try {
						latlong = $(latlong).text().split(',');
						person.latitude = parseInt(latlong[0]);
						person.longitude = parseInt(latlong[1]);
					} catch (exception) {
						throw Exception("Could not get latitude and longitude but found latlong key");
					}
				} else throw Exception("Could not get latlong or address");
				
				if (radius >= 0)
					person.radius = radius;
				else person.radius = 100;
				
				// Place the person on the map
				Site.Map.place(person);
				
			});
			
			// Wait until all the people are placed
			var interval = setInterval(function() {
				// Once they are all placed
				if (Site.Map.polygons.length == $(personElement).size()) {
					// Stop checking
					clearInterval(interval);
					// If showRandom is set, show a random person
					if (Site.Map.showRandom)
						Site.Map.randomInfo();
				}
			}, 100);
		},
		place: function(person) {
			// Check person object for necessary attributes
			if (!person || !person.latitude || !person.longitude || !person.radius) return;
			if (!person.numPoints) person.numPoints = 80;
			// Calculate all the points of the circle and draw them
			function calculate() {
				var d2r = Math.PI / 180;
				var circleLatLngs = new Array();
				// Convert statute miles into degrees latitude
				var circleLat = person.radius * 0.014483;
				var circleLng = circleLat / Math.cos(person.latitude * d2r);
				// Create polygon points (extra point to close polygon)
				for (var i = 0; i < person.numPoints + 1; i++) {
					// Convert degrees to radians
					var theta = Math.PI * (i / (person.numPoints / 2));
					var vertexLat = person.latitude + (circleLat * Math.sin(theta));
					var vertexLng = person.longitude + (circleLng * Math.cos(theta));
					var vertextLatLng = new google.maps.LatLng(vertexLat, vertexLng);
					circleLatLngs.push(vertextLatLng);
				}
				
				// Create a new polygon
				var polygon = new google.maps.Polygon({
					paths: circleLatLngs,
					strokeColor: "#880000",
					strokeOpacity: 0.8,
					strokeWeight: 3,
					fillColor: "#880000",
					fillOpacity: 0.35
				});
							
				// Place it on the map
				polygon.setMap(Site.Map.map);
				
				// Add a listener for the click event
				google.maps.event.addListener(polygon, 'click', function(event) { Site.Map.showInfo(person, event); });
				
				// Place the polygon into the list
				Site.Map.polygons.push(polygon);
				
			}
			// For some reason IE seems to need a delay.
			var delay = 0;
			if ($.browser.msie) delay = 2500;
			setTimeout(calculate, delay);
		},
		showInfo: function(person, event) {
			// Replace our Info Window's content and position
			this.infoWindow.setContent(person.content);
			this.infoWindow.setPosition(event.latLng);
			this.infoWindow.open(this.map);
		},
		randomInfo: function() {
			// Choose a random person and display them
			var person = Site.Map.polygons[Math.floor(Math.random() * Site.Map.polygons.length)];
			// Try to get a latitude and longitude
			var latLong = person.latLngs;
			try {
				if ($.isFunction(latLong.getAt))
					latLong = latLong.getAt(0);
				else throw "Could not get first latLong";
				if ($.isFunction(latLong.getAt))
					latLong = latLong.getAt(0);
				else throw "Could not get second latLong";
			} catch (exception) {
				// Could not get latlong for item
				return;
			}
			google.maps.event.trigger(person, 'click', { latLng: latLong });
		}
	},
	
	CompanyDirectory: {
		showRandom: false,
		init: function() {
			var id = 0;
			$('.listbox .collapsible .anchor').click(function() {
				var children = $(this).parent().children('.children:visible');
				if ($(children).length > 0) {
					$.cookie($(this).attr('anchor_id') + '', 'up', { expires: 7, path: '/' });
					$(this).text('—' + $(this).text().substring(1));
					$(this).css('margin-left', '0');
					children.slideUp();
				} else {
					$.cookie($(this).attr('anchor_id') + '', 'down', { expires: 7, path: '/' });
					$(this).text('+' + $(this).text().substring(1));
					$(this).css('margin-left', '6px');
					$(this).parent().children('.children:hidden').slideDown();	
				}
			});
			$('.listbox .collapsible .anchor').each(function() {
				$(this).parent().children('.children').hide();
				$(this).css('cursor', 'pointer');
				$(this).attr('anchor_id', id);
				var direction = $.cookie(id + '');
				if (direction == 'down') {
					var contents = $(this).text();
					$(this).text('+' + contents.substring(1));
					$(this).css('margin-left', '6px');
					$(this).parent().children('.children:hidden').css('display', 'block');
				} else if (direction != 'up') {
					$(this).click();
				}
				id++;
			});
			if (this.showRandom) {
				if (window.location.href == 'http://www.stockdaleco.com/connect/directory/') {
						// Select a random person and display them
						var person = Math.floor(Math.random() * $('.listbox .collapsible .children a').size());
						window.location.href = $('.listbox .collapsible .children a')[person];
				}
			}
		}
	}
}
