$(window).load(function() {

	function initializeMap(){
		$('#searchlocations').hide();
		$('#map').fadeOut(500, function(){
			$('#map').empty().css({
				width: '490px',
				height: '441px',
				backgroundImage: 'url(img/map/carteGuadeloupe.png)',
				position: 'relative'
			});
			$('#map').fadeIn();
			loadBullets('coast', false);
		});
	}

	function addZoomable(id, width, height, top, left){
		$('<img class="zoomable" src="img/map/blank.gif" id="' + id + '" />').css({
			border: 'none',
			position: 'absolute',
			width: width + 'px',
			height: height + 'px',
			top: top + 'px',
			left: left + 'px',
			cursor: 'pointer'
		}).appendTo('#map').click(function() {
			$(this).siblings().fadeOut();
			$(this).hide()
				   .attr('src', 'img/map/' + id + '_base.jpg')
				   .fadeIn('slow')
				   .animate({
						width: '577px',
						height: '418px',
						top: '0px',
						left: '0px'
					}, 1000, '', function(){
						$('#map').css({backgroundImage: 'url(img/map/' + id + '_base.jpg)'}).empty();
						loadBullets(id, true);
					});
		});
	}
	
	function loadBullets(id, back){
		$('#map').load('section/' + id + '?count=25', {}, function(){
			//add back button
			if(back){
				$('<a id="mapback" href="javascript:void(0)"><span>return to NC Coast &gt;</span></a>')
					.appendTo(this)
					.click(function(){initializeMap()});
			}
			else{
				addZoomable('manteo', 138, 102, 37, 400);
				addZoomable('triangle', 107, 73, 68, 56);
				addZoomable('morehead', 43, 32, 269, 354);
				addZoomable('wilmington', 44, 32, 348, 212);
			}
			//place bullets
			$(this).children('a.bullet').each(function(){
				var coords = $(this).attr('rel').split('-');
				$(this).css({left: coords[0] + 'px', top: coords[1] + 'px'})
					   .hide()
					   .fadeIn()
					   .click(function(){showPopup($(this).attr('id'));});
			});
		});
	}
	
	function showPopup(id){
		$('#map div.popup').fadeOut(); 
		var boxid = '#' + id + '-box';
		$(boxid).fadeIn();
		$('a.close').click(function(){
			$(this).parent().fadeOut();
		});
	}

	
	//initialize map
	initializeMap();
	

});
