(function ($) {
	
	$.fn.autoClick = function(text) {
		$(this).click(function() {
			if ($(this).val() == text) {
				$(this).val('');
			}
		});
		
		$(this).blur(function() {
			if ($(this).val() == '') {
				$(this).val(text);
			}
		});
		
		return this;
	}
	
	function loadMap() {
		var geocoder = new google.maps.Geocoder();
		var latlng = new google.maps.LatLng(44.9799654, -93.2638361);
		
		var options = {
            zoom: 10,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };
					
		var map = new google.maps.Map(document.getElementById("map"), options);
		
		var addresses = new Array();
		var addressCount = 0;
		
		// Add markers
		$('address').each(function() {
			addressCount++;
			var address = $(this).html();
			address = address.replace(/<br>/ig, ",");
			geocoder.geocode({ address: address }, function (results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
					var address = results[0].geometry.location;
					addressCount--;
					addresses.push(address);
				
					if (addressCount == 0) {
						fitMap(map, addresses);
			
						for (var i=0; i < addresses.length; i++) {
							var marker = new google.maps.Marker({ position: addresses[i] });
							marker.setMap(map);
						}
					}
				}
			});
		});
	}
	
	function fitMap(map, points) {
	   var bounds = new google.maps.LatLngBounds();
	   for (var i = 0; i < points.length; i++) {
		  bounds.extend(points[i]);
	   }
	   
	   map.fitBounds(bounds);
	   var zoom = map.getZoom();
	   if (zoom > 14) zoom = 14;
	   
	   map.setZoom(zoom);
	   map.setCenter(bounds.getCenter());
	}
	
	function loadMapAll() {
		var addressSet = new Array();
		
		var latlng = new google.maps.LatLng(44.9799654, -93.2638361);
		
		var options = {
            zoom: 8,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
          };
					
		var map = new google.maps.Map(document.getElementById("map-all"), options);
					
		// Get all addresses
		$('#directory-content ul ul li[class!=hidden] address').each(function() {
			var c = $(this).html();
							
			if (typeof(addressSet[c]) == 'undefined') {
				addressSet[c] = new Array();
			}
			
			addressSet[c].push($(this).parent().find('a:first'));
		});
		
		// Add to map
		for (var coordinates in addressSet) {
			var coordinatesSplit = coordinates.split(",");				
			var point = new google.maps.LatLng(coordinatesSplit[0], coordinatesSplit[1]);
			var marker = new google.maps.Marker({ position: point, map: map });
			
			attachEvent(map, marker, addressSet);
		}
		
		$('.directory > img').hide();

	}
	
	function attachEvent(map, marker, addressSet) {
		var markerPos = marker.getPosition();
		var location = markerPos.lat().toFixed(7) + "," + markerPos.lng().toFixed(7);
		
		var html = "";
			
		var addresses = addressSet[location];
		for (var address in addresses) {
			var link = addresses[address];
			html += "<a href=\"" + link.attr("href") + "\">" + link.text() + "</a>, ";
		}
		
		html = "<p>" + html.substr(0, html.length - 2) + "</p>";
			
		var infowindow = new google.maps.InfoWindow({
			content: html,
			position: markerPos
		});
			
		google.maps.event.addListener(marker, "click", function() {
			infowindow.open(map);
		});
	}
	
	function testFilters() {
		if ($('.directory-header').length > 0) {
			$('#directory-content ul ul li').removeClass("hidden");
			
			var selectedStatus = $('.directory-header select[name=status]').val();
			
			switch (selectedStatus) {
				case "private_and_public":
					break;
				case "privately_held":
					$('#directory-content ul ul li:has(a.public)').addClass("hidden");
					break;
				case "publicly_held":
					$('#directory-content ul ul li:has(a.private)').addClass("hidden");
					break;
			}
			
			if ($('#type_startup').attr('checked')) {
				$('#directory-content ul ul li:has(a:not(.startup))').addClass("hidden");
			}
			
			$('#directory-content li').each(function() {
				if ($(this).find('li.hidden').length == $(this).find('li').length) {
					$(this).find('span').addClass('empty');
				}
				else {
					$(this).find('span').removeClass('empty');
				}
			});
			
			var selectedDisplay = $('.directory-header select[name=display]').val();
			
			switch (selectedDisplay) {
				case "list":
					$('#map-all').hide();
					$('#directory-content ul').show();
					$('.directory > img').hide();
					break;
				case "map":
					$('#directory-content ul').hide();
					$('#map-all').show();
					loadMapAll();
					break;
				default:
					$('.directory > img').hide();
					break;
			}
		}
	}
	
  /* Auto complete */
  $(document).ready(function () {
	$('#company_search').autoClick('Search by company name or keyword');
	$('#person_search').autoClick('Search by person name');
	$('#capital_search').autoClick('Search by organization name or keyword');
	$('#group_search').autoClick('Search by group name or keyword');
	
	$('.search-box').keydown(function() {
		$('.filter li').removeClass('active');
	});
  
	$('input#company_search').autocomplete('/directory/company-list', { 
		containerID: "directory-content", 
		formatItem: function(data, i, total) {
			var cssClass = "";
			if (data[2] == 1) {
				cssClass = "private";
			}
			else if (data[2] == 2) {
				cssClass = "public";
			}
			
			if (data[3] == 1) {
				cssClass += " startup";
			}
			
			return '<a href="/directory/companies/' + data[1] + '" class="' + cssClass + '">' + data[0] + '</a>' + data[4];
		},
		minChars: 1,
		scroll: false,
		max: 10000,
		width: 898,
		preAutoComplete: function() { $('.directory img').show(); },
		postAutoComplete: testFilters
	});
	
	$('input#group_search').autocomplete('/directory/group-list', { 
		containerID: "directory-content", 
		formatItem: function(data, i, total) {			
			return '<a href="/directory/groups/' + data[1] + '">' + data[0] + '</a>' + data[2];
		},
		minChars: 1,
		scroll: false,
		max: 10000,
		width: 898,
		preAutoComplete: function() { $('.directory img').show(); },
		postAutoComplete: testFilters
	});
	
	$('input#capital_search').autocomplete('/directory/capital-list', { 
		containerID: "directory-content", 
		formatItem: function(data, i, total) {			
			return '<a href="/directory/capital/' + data[1] + '">' + data[0] + '</a>' + data[2];
		},
		minChars: 1,
		scroll: false,
		max: 10000,
		width: 898,
		preAutoComplete: function() { $('.directory img').show(); },
		postAutoComplete: testFilters
	});
	
	$('input#person_search').autocomplete('/directory/people-list', { 
		containerID: "directory-content", 
		formatItem: function(data, i, total) {
			return '<a href="/directory/people/' + data[2] + '">' + data[1] + ' ' + data[0] + '</a>';
		},
		minChars: 1,
		scroll: false,
		max: 10000,
		width: 898,
		preAutoComplete: function() { $('.directory img').show(); },
		postAutoComplete: testFilters,
		hasNumbers: false
	});
  });
	
  /* AJAX request */
  $(document).ready(function () {		
	$('.filter a').click(function() {
		var link = $(this);
		$('.directory img').show();
		$.get(link.attr('href'), function(data) {
			$('#directory-content').html(data);
			testFilters();
			$('.filter li').removeClass('active');
			link.parent().addClass('active');
		});
		return false;
	});
	
	if ($('.filter li.active').length > 0) {
		$('.directory img').show();
		var link = $('.filter li.active a').attr('href');
		$.get(link, function(data) {
			$('#directory-content').html(data);
			testFilters();
		});
	}
	
  });
	
  /* Filters */
  $(document).ready(function () {
	//testFilters();
	$('#type_startup').click(function() {
		$('.directory img').show();
		testFilters();
	});
	$('.directory-header select[name=status]').change(function() {
		$('.directory img').show();
		testFilters();
	});
	$('.directory-header select[name=display]').change(function() {
		$('.directory img').show();
		testFilters();
	});
  });
	
  /* Google Maps */
  $(document).ready(function () {
	if ($('#map').length > 0) {
		loadMap();
	}	
  });
	
  /* Links opening in new window */
  $(document).ready(function () {
	$('a[rel=external]').click(function(){
		window.open(this.href);
		return false;
	});
  });
  
  /* Message hide */
  $(document).ready(function () {
	$('a.hide').click(function(){
		$(this).parent('.message').fadeOut('slow');
		var exDate = new Date();
		exDate.setDate(exDate.getDate() + 365);
		document.cookie = "techdotmn_" + $(this).attr('href') + "=" + "hide;expires=" + exDate.toGMTString();
		return false;
	});
  });
  
  $(document).ready(function() {
	$('#mc_mv_EMAIL').autoClick('Enter your Email Address');
  });
  
  $(document).ready(function() {
	$('.contact textarea').click(function() {
		$('textarea').css('height', '80px');
		$('.contact .hidden').show();
	});
	
	$('.contact textarea').autoClick('Type your message');
  });
  
  $(document).ready(function() {
	var logoImage = $('.detail .logo img');
	if (logoImage.length > 0) {
		var logoHeight = logoImage.height();
		var containerHeight = logoImage.parent().height();
		
		if (logoHeight < containerHeight) {
			var margin = (containerHeight - logoHeight) / 2;
			logoImage.css('marginTop', margin);
		}
		
		logoImage.css('display', 'block');
	}
  });
  
})(jQuery);