$(window).load(function() {

	function initializeMap(){
		
		$('#map').fadeOut(300, function(){
			$('#map').empty().css({
				width: '625px',
				height: '279px',
				backgroundImage: 'url(map/images/mapa.jpg)',
				position: 'relative'
			});
			$('#map').fadeIn();
			loadBullets('coast', false);
		});
	}

	function addZoomable(id, width, height, top, left){
		$('<img class="zoomable" src="map/images/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', 'map/images/' + id + '.png')
				   .fadeIn('slow')
				   .animate({
						width: '625px',
						height: '279px',
						top: '0px',
						left: '0px'
					}, 300, '', function(){
					
					    /*alert(id);*/
					    
						$('#map').css({backgroundImage: 'url(map/images/' + id + '.png)'}).empty();
						loadBullets(id, true);
					});
		});
	}
	
	function loadBullets(id, back){
		$('#map').load('map/images/' + id + '?count=25', {}, function(){
			//add back button
			if(back){
				$('<a id="mapback" href="javascript:void(0)"><span>Volver  &gt;</span></a>')
					.appendTo(this)
					.click(function(){initializeMap()});
			}
			else{	
                    addZoomable('rcalabrano',21, 21,102,183); //lareina
                    addZoomable('rcalabrano',21,21,69,200);   //lascondes                     
                    addZoomable('rcalabrano',21,21,217,87);  //sanbernardo
                    addZoomable('rcalabrano', 21,21,162,41);   //maipu
                    addZoomable('laflorida',21,21,166,160);   //laflorida              
                    addZoomable('puentealto',21,21,214,164);    //puentealto
                    addZoomable('nunoa',21,21,109,148);  //nunoa
                    addZoomable('recoleta',21,21,69,125);  //recoleta                      
                    addZoomable('penaflor',21,21,202,17);     //penaflor
			}
			//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();

});
