
// Needs some functions from slicedice.js
var CMSMap = function(){
	
	var map;
	var mapContainer;
	var tooltip;
	var detailEl;	
	var mapConf;	
	var manager; 	// The markermanager
	var companyList ;
	var accommodationList ;
	
	
	function init( mapId, conf){
	
		MapUtils.loadAPI( function(){
			build( mapId, conf );		
		});
	}
	
	function build( mapId, conf ){

		if ( conf.lat == undefined || conf.lng == undefined || conf.zoom == undefined || !conf.lat || !conf.lng || !conf.zoom  ){
			return false;
		}
		mapConf = conf;

		// Create the map
		map = new GMap2( document.getElementById( mapId ) );
		detailEl = $('#map-details');
		detailEl.children('img.close').click( closeDetails ).css('cursor', 'pointer' );
		var center = new GLatLng( parseFloat(conf.lat), parseFloat(conf.lng) );
		map.setCenter( center, parseInt(conf.zoom) );

		map.setUIToDefault();
		map.enableContinuousZoom(); 
		map.setMapType(G_PHYSICAL_MAP);
		
		MapUtils.restrictViewAreaToTexel( map );
		tooltip = $('<div id="tooltip"></div>').appendTo( $('#' + mapId ) );

		MapUtils.setMarkerClickHandler( showDetails );
		// Create the MapManager
		manager = new MarkerManager(map);

		// Refresh when dragging or zooming out
		GEvent.addListener(map, 'dragend', refresh );
		GEvent.addListener(map, 'zoomend', function( oldLevel, newLevel){
			//if ( oldLevel > newLevel ){
				refresh();
			//}
		});
		
		mapContainer = $('#map-container');

		companyList = $('#map-companies');
		accommodationList = $('#map-accommodations');
		
		if ( mapConf.size == 'XXL'){
			initCollapsibleList();
			
		}
		companyList.find('input').click( handleInputClick );
		accommodationList.find('input').click( handleInputClick );
	
		refresh();

		return false;
	}
	
	function handleInputClick(){
		
		var input = $(this);
		var li = input.parent('li');
		
		if ( input.attr('checked') ){
			li.removeClass('disabled');
			li.find('ul input').attr('disabled', '' );
		}else{
			li.addClass('disabled');
			li.find('ul input').attr('disabled', 'disabled' );
		}
		
		refresh();
		
	}
	
	function getCompanyTypesString( size ){
		
		var size = size || '';
		
		var inputs;
		
		if ( size == 'XXL'){
			// We only want types ( not supertypes ) 
			inputs = $('li:not(.disabled) li input', companyList);
		}else{
			// Does't have supertypes, we can loop through all
			inputs = companyList.find('input')
		}
		
		// Create string representing the companytypes 
		var tmp = [];

		inputs.each( function(){
			var input = $(this);
			var id = input.attr('id');
			// We only want types that are checked
			if (  !input.attr('checked') ){
				return;
			}
			tmp.push('T', id.replace('type-', '')); 
		});

		return tmp.join('');

	}
	
	var lastBoundingBox = null;
	
	function refresh(){
		setLoading(true);
		
		var compTypes = getCompanyTypesString( mapConf.size );


		var tmp = [];
		// Also add accommodationTypes
		$('input', accommodationList ).each( function(){
			
			var input = $(this);
			var id = input.attr('id');

			if (  !input.attr('checked') ){
				return;
			}
			tmp.push('A', id.replace('accotype-', '')); 
		});
		var accoTypes = tmp.join('');
		
		
		// Get the visible area of the map
		var bounds = map.getBounds();
		var NE = bounds.getNorthEast();
		var SW = bounds.getSouthWest();
		var tags = '';
		if (mapConf.tags){
			tags = mapConf.tags.join('|');
		}

		var params = {
			lat1: NE.lat(),
			lng1: NE.lng(),
			lat2: SW.lat(),
			lng2: SW.lng(),
			types: compTypes,
			accoTypes: accoTypes,
			tags: tags
		};

		if ( lastBoundingBox && params.types == lastParams.types && params.q == lastParams.q && lastBoundingBox.containsBounds(bounds) ){
			// We already got all markers for this area
			setLoading(false);
			//return;
		}
		
		lastBoundingBox = bounds;
		lastParams = params;
	
		Ajax.doRequest( 'ag-map', params, handleRefresh );
		
	}

		
	function handleRefresh( resp ){

		// Create the markers we need to add
		var markers = MapUtils.createMarkers( resp.data.markers, {
			map:map,
			tooltip:tooltip
		} );
			
		
		manager.clearMarkers();
		// Add them at once
		manager.addMarkers( markers, 5);
		
		// Refresh MarkerManager to show the newly added markers 
		manager.refresh();


		if ( resp.data.limitReached ){
			showLimitNotification();
		}
		
		setLoading(false);
	}
	
	
	var notification = null;
	
	function showLimitNotification(){

		if ( notification ){ 
			return false;
		}
		notification = $('#limit-notification');	
		if (notification.text() == ''){
			return false;
		}
		
		setTimeout(  function(){
			notification.fadeIn(1000);
			setTimeout( function(){
				notification.fadeOut();
			}, 6000)

		}, 2000 );

	}
	
	// todo
	var detailOpen = false;
	
	function showDetails(marker, reqMarker ){

		detailEl.children('div.content:first').html(reqMarker.html);
		
		if (mapConf.size == 'XXL'){
			detailEl.fadeIn();
		}else{
			// Make the detail element come sliding out
			if (!detailOpen){

				var toTheLeft = detailEl.width();
				var left =  parseInt( detailEl.css('left').replace('px', '')) - toTheLeft  ;
				
				detailEl.css('visibility', 'visible').animate({ 
			        left: left +  'px'
			      }, 800 );		
			}
		}
		detailOpen = true;


	}

	function closeDetails(){
		
		if (mapConf.size == 'XXL'){
			detailEl.fadeOut(200);
		}else{
			var distance = parseInt( detailEl.css('left').replace('px', '')) +  detailEl.width();
			
			detailEl.animate({ 
		        left: distance + 'px'
		      }, 200 );		
		}
		
		detailOpen = false;
		return false;
	}
	
	function initCollapsibleList(){
		
		companyList.find('span.sublist-toggler').click( function(){
			toggleSublist( $(this).parent('li') );
		});

	}
	
	// li should be JQ obj
	function toggleSublist( li ){
		
		if ( li.hasClass('opened') ){
			li.removeClass('opened');
		}else{
			li.addClass('opened');
		}
	}

	var loadingIndicator = null;
	function setLoading( isLoading ){
	
		util.setLoading( isLoading );
		/*
		
		if ( !loadingIndicator ){
			loadingIndicator = $('<div class="loading"></div>').appendTo( mapContainer);
		}
		if(isLoading){
			// When map is doing something
			loadingIndicator.show();
		}else{
			//loadingIndicator.hide();
		}
		*/
	
		
	}
	
	return {
		init:init,
		map: function(){ 
			return map;
		}
	}
	
	
	
}();



