var map;
var geocoder;
var marker;
var url;
var title;
var notes;
var mapClickListener;
var markerClickListener;
var lat;
var lng;
var clientip;
var $j = jQuery.noConflict();
var baseURL;
var urlhash;
var expandTxt;
var expanded = false;
var whereMarker = '<a href="javascript:centerMarker()">Hey, where\'s the marker!?</a>';
var mapTypes = ['', 'place', 'event', 'meeting'];
var showStart = false;
var showcaseURL;

function init() {
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
        map = new GMap2(document.getElementById("map_canvas"));
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
        map.setUIToDefault();
	}
	
	//initialize the modal
	$j('#modalWindow').jqm();
	
	//reset all variables
	reset();
	
	//load the showcase
	$j("#showcase").load(showcaseURL).show("slow");
	
	if (showStart)
		info('Create your own map in 3 easy steps', 'getstarted1');
}

function reset() {
	hideMarker();
		
	url = null;
	title = null;
	notes = null;
	
	//clear the location
	if (document.getElementById('where') != null)
		document.getElementById('where').value = '';
	
	urlhash = baseURL;

	//add a listener for move events
	GEvent.addListener(map, "moveend", function() {
		showWhereMarker();
	});

	//add a click listener for the map
	if (map != null && mapClickListener == null) {
	    mapClickListener = GEvent.addListener(map, "click", function(overlay,latlng) {
			if (marker == null)
				addMarker(latlng);
		}
		);
	}
}
function unloader() {
	//unload the Google map
	GUnload();
}
function showLocation(location) {
	var locationText = '<p>A location can be:</p>'
		+ '<ul>'
		+ '<li>a place name</li>'
		+ '<li>a street level address</li>'
		+ '<li>a zip code</li>'
		+ '</ul>'
		+ '<p>Examples of places include:</p>'
		+ '<ul>'
		+ '<li>The Statue of Liberty</li>'
		+ '<li>Harrods, UK</li>'
		+ '<li>1 Infinite Loop Cupertino, CA 95014</li>'
		+ '</ul>'
		+ '<p>Remember that it\'s best to add the country to your location if your map is outside the US.</p>'
		+ '<p><strong>Give your location again or click on the map to add your marker</strong></p>';


	if (location == null || location.length == 0) {
		var msg = 'You need to give a valid location first!'
			+ locationText;
		
		showModal('Oops!', msg);
		return false;
	}

	//remove any existing marker
	hideMarker();
	
	//show the new marker
	geocoder.getLatLng(location,
		function(point) {
			if (!point) {
				var msg = 'Sorry, your location, <strong>' + location + '</strong> could not be found.'
				+ locationText;
				
				showModal('Oops!', msg);				
			} else {
				map.setCenter(point, 13);
				addMarker(point);
			}
		}
	);		
}
function addMarker(latlng) {
	marker = new GMarker(latlng, {draggable: true});

	//add a click listener for the map
	markerClickListener = GEvent.addListener(marker, "click", function() {
			showInfo();
		}
	);

	map.addOverlay(marker);
	//closeInfo();
	showInfo();
}
function hideMarker() {
	if (marker == null)
		return;
	
	map.removeOverlay(marker);
	marker = null;
}
function centerMarker() {
	if (marker == null) {
		var msg = 'There is no marker on your map yet!'
			+ '<p><strong>Give a location or click on the map to add your marker</strong></p>'
		showModal('Oops!', msg);
	}
	else {
		map.panTo(marker.getLatLng());
	}
}
function showInfo() {
	if (marker == null)
		return;
	var msg1 = '<div class="infobox text">Drag this marker to your desired location <br /> '
		 + 'or <a href="javascript:hideMarker()">remove it from your map</a>'
	;
	
	marker.openInfoWindow(msg1);
	
	//set the values again
	if (document.getElementById('urlfield') != null)
		document.getElementById('urlfield').value = url;
	if (document.getElementById('titlefield') != null)
		document.getElementById('titlefield').value = title;
	if (document.getElementById('notesfield') != null)
		document.getElementById('notesfield').value = notes;
}
function selectTab(tab) {
	map.getInfoWindow().selectTab(tab);
}
function closeInfo() {
	marker.closeInfoWindow();
}
function saveMap() {
	if (marker == null) {
		var msg = 'Your map cannot be saved until you have added a marker to it.'
			+ '<p>You can do this by:</p>'
			+ '<ul>'
			+ '<li>giving a map location to automatically create a marker</li>'
			+ '<li>clicking on the map to manually create a marker</li>'
			+ '</ul>'
			+ '<p><strong>Give a location or click on the map to add your marker</strong></p>';
		;
		
		showModal('Oops!', msg);
	}
	else {
		showSaveModal('Just before we save your map...');
	}
}
function doSaveMap() {
	//save the map/marker
	document.getElementById('savemap').style.display = 'none';
	document.getElementById('mapmsg').innerHTML='Please wait while your map is saved...';
	document.getElementById('mapmsg').style.display = 'block';
	
	//close the marker info window
	closeInfo();
	
	//remove the map listener(s)
	GEvent.removeListener(mapClickListener);
	mapClickListener = null;
	GEvent.removeListener(markerClickListener);
	markerClickListener = null;
	
	//disable dragging
	marker.disableDragging();
	
	//get the location and other details
	var where = document.getElementById('where').value;
	var latlng = marker.getLatLng();
	var title = document.getElementById('savetitle').value;
	var url = document.getElementById('saveurl').value;
	var notes = document.getElementById('savenotes').value;
	var maptype = 1;
	
	//get the map type
	if (document.getElementById('type2').checked)
		maptype = 2;
	else if (document.getElementById('type3').checked)
		maptype = 3;
	
	//set up the params
	var params = {
		'q' : where,
		'u' : url,
		'n' : title,
		'i' : notes,
		'lat' : latlng.lat(),
		'lng' : latlng.lng(),
		'm' : mapTypes[maptype],
		't' : 'json'
	};
	
	//make the call to create the map
	$j.post("api/make", params, function callback(data) {
		urlhash = urlhash + data.map.hash;
			
		//redirect to the new page
		window.location = urlhash;
	}
	, 'json');
}
function doCloseSave() {
	$j('#modalWindow').jqmHide();
}
function newMap() {
	reset();
	
	document.getElementById('location').style.display = 'block';
	document.getElementById('savemap').style.display = 'block';
	document.getElementById('mapdetails').style.display = 'none';
	document.getElementById('newmap').style.display = 'none';
	
	document.getElementById("where").focus();
}
function setModalWidth(width) {
	if (typeof width == "undefined") {
		if ($j('.jqmWindow').width() != 400) {
			$j('.jqmWindow').width(400);
			$j('.jqmWindow').css('margin-left', -300);
		}
	}
	else {
		$j('.jqmWindow').width(width);
		$j('.jqmWindow').css('margin-left', -400);
	}	
}
function showModal(title, message, width) {
	setModalWidth(width);
	document.getElementById('jqmTitle').innerHTML = title;
	if (typeof message != "undefined" || message != null)
		document.getElementById('jqmContent').innerHTML = message;
	document.getElementById('modalWarning').style.display = 'block'; 
	document.getElementById('modalSave').style.display = 'none'; 
	$j('#modalWindow').jqmShow();	
}
function hideModal() {
	$j('#modalWindow').jqmHide();
}
function showSaveModal(title) {
	setModalWidth();
	document.getElementById('modalWarning').style.display = 'none'; 
	document.getElementById('modalSave').style.display = 'block'; 
	document.getElementById('jqmTitle').innerHTML = title;
	$j('#modalWindow').jqmShow({overlay:0, modal:true});	
}
function showWhereMarker() {
	var bounds = map.getBounds();
	if (marker == null || bounds.containsLatLng(marker.getLatLng()))
		document.getElementById('wheremarker').innerHTML = '&nbsp;';
	else
		document.getElementById('wheremarker').innerHTML = whereMarker;	
}
function expand() {
	if (expanded) {
		//collapse the map
		document.getElementById('rightcontent').style.display = 'block';
		document.getElementById('leftcontent').style.width = '540px';
		document.getElementById('mapcontainer').style.width = '500px';
		document.getElementById('map_canvas').style.width = '500px';
		document.getElementById('map_canvas').style.height = '320px';
		document.getElementById('expand').innerHTML = expandTxt[0];
		map.checkResize();
		showWhereMarker();
	}
	else {
		var viewportwidth = $j(window).width() - 20;
		var viewportheight = $j(window).height() - 180;		
				
		//expand the map
		document.getElementById('rightcontent').style.display = 'none';
		document.getElementById('leftcontent').style.width = viewportwidth + 'px';
		document.getElementById('mapcontainer').style.width = (viewportwidth - 20) + 'px';
		document.getElementById('map_canvas').style.width = (viewportwidth - 20) + 'px';
		document.getElementById('map_canvas').style.height = viewportheight + 'px';
		document.getElementById('expand').innerHTML = expandTxt[1];
		map.checkResize();
	}
		
	expanded = !expanded;
}
function info(title, what, isOpen) {
	if (isOpen == null)
		isOpen = false;
	
	$j('#jqmContent').load(baseURL + 'modal/' + what);
	showModal(title, null, 600);
}