// FM Contest Map Init
// Version: V2.3.2
// Updated: March 16 2011
// By: Jshaw 
	// bugs
	// disapearing media bubbles
	// channel filters to media on the map
	//March 16
	//Added text availability for viewing on map

function initMap(lat,lng,zoom,controller,type,markers) {

	var map = initGMap(lat,lng,zoom,controller,type);

	// We need to keep track of all the markers we add to the map to ensure we don't add duplicates in the mediaUpdater function
	if (markers) {

		try {
			var updateTimer = null;

			// Only update media 2 seconds after a map movement has ended and cancel any other media updates that may be pending.
			GEvent.addListener ( map, 'moveend', function () {
				if ( updateTimer != null )
				clearTimeout ( updateTimer );
				setTimeout ( mediaUpdater, 1000 );
			} );

			mediaUpdater(false,true);

		} catch (ex) { console.log('error: '+ex); }
	}
}

function mediaUpdater(users,media) {

	var picSize = 13;
	var channel = $('mapChannel').value;
	
	// if no user or media was passed
	if (!users && !media) {
		// if this page has the ability to show and hide users and media
		if ($('cb_users') && $('cb_media')) {
			if ($('cb_users').checked) {
				var users = true;
			} else {
				var users = false;
			}
			if ($('cb_media').checked) {
				var media = true;
			} else {
				var media = false;
			}
		} else {
			var users = true;
			var media = true;
		}
	} else {
		var users = users;
		var media = media;
	}
	
	var showPhotos = true;
	var showVideos = true;
	var showAudio = true;
	var showText = true;	
	
	if ($('cb_photos')) {
		if ($('cb_photos').checked == true) {
			showPhotos = true;
		} else {
			showPhotos = false;
		}
	} else {
		showPhotos = true;
	}
	
	if ($('cb_videos')) {
		if ($('cb_videos').checked == true) {
			showVideos = true;
		} else {
			showVideos = false;
		}
	} else {
		showVideos = true;
	}
	
	if ($('cb_audio')) {
		if ($('cb_audio').checked == true) {
			showAudio = true;
		} else {
			showAudio = false;
		}
	} else {
		showAudio = true;
	}
	
	if ($('cb_text')) {
		if ($('cb_text').checked == true) {
			showText = true;
		} else {
			showText = false;
		}
	} else {
		showText = true;
	}
	
	var mapMarkers = new Hash ();

	if ($('mapModeration') != null) {
		moderation = $('mapModeration').value
	} else {
		moderation = 1;
	}

	var paramsMedia = {
		'vhost' : selectedVHost,
		'filters' : {
	        'geoBoundaries' : [
	            map.getBounds().getNorthEast().lat(),
	            map.getBounds().getNorthEast().lng(),
	            map.getBounds().getSouthWest().lat(),
	            map.getBounds().getSouthWest().lng()
	        ],
	        'channel':channel,
	        'includeChildren':1,
	        'moderationStatus': moderation
        },
		'fields' : ['title','geo_latitude','geo_longitude','thumbUrl','filetype','hits']
	}

	var paramsUser = {
		'vhost' : selectedVHost,
		'northEast' : [map.getBounds().getNorthEast().lat(),map.getBounds().getNorthEast().lng()],
		'southWest' : [map.getBounds().getSouthWest().lat(),map.getBounds().getSouthWest().lng()]
	}
	
	if(users == false || media == false || showPhotos == false || showVideos == false || showAudio == false || showText == false) {
		map.clearOverlays();
	}
	
	if (media == true) {
	
		jsonRequest('media.getFiles',paramsMedia,function(result) {

		result = result.data;

			for(var i=0; i<result.length; i++) {
				
				if ((result[i].filetype == 1 && showPhotos) || (result[i].filetype == 2 && showVideos) || (result[i].filetype == 3 && showAudio) || (result[i].filetype == 4 && showText)) {
				
					var item = result[i];
					
					if ( mapMarkers.get ( 'm' + i ) )
					continue;
	
					var latlng = new GLatLng(item.geo_latitude,item.geo_longitude);
					
					if(item.filetype == 4){
						var marker = new AvatarMarker(latlng,"/static/contest/images/text.gif",24);
					}else if(item.filetype == 3){
						var marker = new AvatarMarker(latlng,"http://assets.filemobile.com/371/contest/v2/images/audio_small.gif",24);
					}else{
						var marker = new AvatarMarker(latlng,item.thumbUrl+"/11",24);
					}
	
					marker.info = item;

					GEvent.addListener(marker,'click',function() {
												
						var mid = this.info.thumbUrl.substr(this.info.thumbUrl.lastIndexOf("/")+1,this.info.thumbUrl.length);
						var incImg = new Image();		
						var short = '<div class="stats">'+this.info.hits+' views</div>';
						
						var infoWindow = '<div class="mediainfo mapmarker">'+
						'<div class="title">'+
							'<a href="/entry/'+mid+'-'+this.info.title+'?offset=0">'+this.info.title+'</a>'+
						'</div>'+
						short+
						'<a href="/entry/'+mid+'-'+this.info.title+'?offset=0">';
												
						if(this.info.filetype == 4){
							infoWindow += '<img src="/static/contest/images/text.gif" alt="'+this.info.title+'" style="width:176px; height:132px;"/>';
						}else if(this.info.filetype == 3){
							infoWindow += '<img src="http://assets.filemobile.com/371/contest/v2/images/audio_large.gif" alt="'+this.info.title+'" style="width:176px; height:132px;"/>';
						}else{
							infoWindow += '<img src="'+this.info.thumbUrl+'/'+picSize+'" alt="'+this.info.title+'" style="width:176px; height:132px;"/>';
						}
						
						infoWindow += '</a><div class="clear"></div></div>';
						
						this.openInfoWindowHtml(infoWindow);
						
					});
	
					map.addOverlay(marker);
					mapMarkers.set ( 'm' + i, marker );
					
				}
			}
			
		},false,true);

	}

/*
	if (users == true) {

		jsonRequest('geo.getUsersFromArea',paramsUser,function(result) {

			for(var i=0; i<result.length; i++) {
			
				var item = result[i];			
				if ( mapMarkers.get ( 'u' + item.id ) )
				continue;

				item.avatarImg = '/static/1/images/global/male.gif';

				if ($('mapMaleAvatar') != null) {
					item.avatarImg = $('mapMaleAvatar').value;
				}

				if (item.gender == 'F') {
					if ($('mapFemaleAvatar') != null) {
						item.avatarImg = $('mapFemaleAvatar').value;
					} else {
						item.avatarImg = '/static/1/images/global/female.gif';
					}

				}
				
				item.avatarImg = 'http://www.gravatar.com/avatar/'+item.gravatarid+'?s=16&d='+item.avatarImg;	
				
				if (item.external_id.length > 0) {
					if (item.external_id[0].external_id_provider == 'facebook') {
						item.avatarImg = 'http://facebook.com/pics/t_silhouette_logo.gif';
					}
				}

				if (item.avatarImg && parseInt(item.avatar) > 0) {
					item.avatarImg = 'http://fmdev.s3.amazonaws.com/storage/'+item.avatar+'/11';
				}
				
				var latlng = new GLatLng(item.geo_latitude,item.geo_longitude);
				var marker = new AvatarMarker(latlng,item.avatarImg,16)			
				
				item.avatarLarge = '<img src="'+item.avatarImg.replace('s=16','s=50')+'"/>';
								
				marker.userInfo = item;
						
				GEvent.addListener(marker,'click',function() {
					this.openInfoWindowHtml(
						'<div class="mapmarker mapuser" style="height:50px;">' +
							'<a href="/profile/' + this.userInfo.id + '" class="avatar left">' + 
								this.userInfo.avatarLarge + 
							'</a>'+
							'<div class="left">' +
								'<ul>'+
									'<li>'+
										'<a href="/profile/' + this.userInfo.id + '">' + this.userInfo.firstname.escapeHTML() + ' ' + this.userInfo.lastname.escapeHTML() + '</a>' +
									'</li>'+
									'<li>'+this.userInfo.city+'</li>'+
									'<li>'+this.userInfo.country+'</li>'+
								'</ul>'+
								''+ 
								
							'</div>'+
							'<div class="clear"></div>'+
						'</div>'
					);
				});
				
				map.addOverlay(marker);
				mapMarkers.set ( 'u' + item.id, marker );

			}

		},false,true);

	}
*/

}

function initGMap(latinc,lnginc,zoominc,controllerinc,typeinc) {

	var lat = latinc;
	var lng = lnginc;
	var zoom = zoominc;
	var controller = controllerinc;
	var type = typeinc;

    // Google maps initialization
	window.map = new GMap2(document.getElementById("map"));
    var map = window.map;

    var latlng = new GLatLng(lat, lng);

	if (!zoom) {
		zoom = 4;
	}

    // Zoom level 4 will allow the majority of North America to appear in the map by default
    map.setCenter(latlng, zoom);

	if (controller) {
		if ($('map').getHeight() < 260) {
		    var zoomer = new GSmallMapControl();	
		} else {
    		var zoomer = new GLargeMapControl3D();
    	}
    	map.addControl(zoomer);
	}
	
	if (type) {
    	var maptype = new GMapTypeControl(false);
    	map.addControl(maptype);
    }

    map.enableScrollWheelZoom();
    map.enableContinuousZoom();
    
    if ($('maploading')) {
    	$('maploading').remove();
    }
   
    return map;

}

function selectLocation(map,latlng, center) {
  if (center) map.setCenter(latlng, 10);
}

function searchAddress(searchString) {

   var geocoder = new GClientGeocoder();
   geocoder.getLatLng(searchString, function(point) { 

        if (point) {
            selectLocation(window.map, point, true);
        } else {
            Messenger.message(1,searchString + ' not found!');
        }

   });
   
}

// map init for registeration / behaves differently
// part of the validation for the map / user geo
function showmap(lat,lng,zoom,controller,type,markers){
		
	initMap(lat,lng,zoom,controller,type,markers);
	
	GEvent.addListener(map, "click", function(overlay, latlng) {
		markit(map,latlng);		
		if($$('li.mapLabel .error')){
			e = $$('.error');
			e.each (function(i){
				i.removeClassName('error');
				i.innerHTML = $('geo_lat').readAttribute('title')+" *";
			});
		}
	});		
		
	function markit(map,latlng){				
		map.clearOverlays();
		var marker = new GMarker(latlng);
		map.addOverlay(marker);
		$('geo_lat').value  = latlng.lat();
		$('geo_long').value = latlng.lng();				
	}			
}	
