google.load('search', '1');
google.load('maps', '2');
var map;
var spotSearch;
var AddedResults = [];
var CurrentResults = [];
var currentPosition;
var added = 0;
var manMarker;
var geocoder;
var redDotIcon = null;
var blkDotIcon = null;
var manIcon = null;
var start = [
		{what:"Starbucks",where:"San Francisco"},
		{what:"Hostels",where:"Amsterdam"},
		{what:"Groceries",where:"Seattle"},
		{what:"Bar",where:"Berlin"},
		{what:"Pizza",where:"Chicago"},
		{what:"Books",where:"London"},
		{what:"Apartments",where:"Paris"},
		{what:"Burgers",where:"New York"}
	];

// Set up the map and the local searcher.
function OnLoad() {
	manIcon = new google.maps.Icon();
	manIcon.image = "man.png";
	manIcon.iconSize = new google.maps.Size(50, 50);
	manIcon.iconAnchor = new google.maps.Point(16, 50);
	manIcon.infoWindowAnchor = new google.maps.Point(14, 5);	  

	redDotIcon = MapIconMaker.createFlatIcon({width: 22, height: 22, primaryColor: "#ee0000"});
	blkDotIcon = MapIconMaker.createFlatIcon({width: 30, height: 30, primaryColor: "#000000"});
	
	document.getElementById('mapset').style.height = (document.body.offsetHeight-120) +'px';
	document.getElementById('map').style.height = (document.body.offsetHeight-120) +'px';
	
	// Initialize the map
	map = new google.maps.Map2(document.getElementById("map"));
	map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(5,35)));
	map.addControl(new GMapTypeControl());
	map.addMapType(G_PHYSICAL_MAP);
//	map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 14);
	map.checkResize();
	var keybrd = new GKeyboardHandler(map);
	geocoder = new GClientGeocoder();

	var i = Math.floor(Math.random()*8);
	if(google.loader.ClientLocation && google.loader.ClientLocation.address.city && google.loader.ClientLocation.address.region)
		document.getElementById("where").value = google.loader.ClientLocation.address.city + ", " +google.loader.ClientLocation.address.region;
	else 
	document.getElementById("where").value = start[i].where;
	document.getElementById("what").value = start[i].what;	
	
	// Initialize the local searcher
	spotSearch = new google.search.LocalSearch();
	spotSearch.setSearchCompleteCallback(null, OnLocalSearch);

	// First time add mashman and search
	geocoder.getLatLng(document.getElementById("where").value,function(point) {
		map.setCenter(point, 14);
		NewSearchPoint(point);
		addMashman(point);
		manMarker.openInfoWindowHtml('<div align="center">Drag Me <br>or <br>Click anywhere on the map</div>');		
//			var opts = {text : "Hello! I'm a PopupMarker."};
//			var marker1 = new PopupMarker(point, opts);
//			map.addOverlay(marker1);
	});
	
	// new search when position changed
	GEvent.addListener(map, 'click', function(overlay, point) {
		if(!overlay){
			document.getElementById("where").value = "(My Position)";
			document.getElementById("where").style.color = "#cccccc";
			currentPosition = point;
			map.removeOverlay(manMarker);
			addMashman(point);
			NewSearchPoint(point);
		}
	});
	
	var GAdsOptions = {maxAdsOnMap:10, minZoomLevel:2, channel:"8885509004"};
	var GAds = new GAdsManager(map,"ca-pub-2773616400896769", GAdsOptions);
	GAds.enable();
//	setTimeout("showAds();",2000);
	
//	GEvent.addListener(map, "moveend", showLat49Ads);
}

function numSpots (num) {
	if (num == '8') spotSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);
	else spotSearch.setResultSetSize(google.search.Search.SMALL_RESULTSET);
	go();
}

function addMashman (latlng) {
		manMarker = new GMarker(latlng, {icon:manIcon, draggable: true, bouncy: true, title: "Drag Me!"});				
		map.addOverlay(manMarker);
		GEvent.addListener(manMarker, "dragend", function(){
			manMarker.closeInfoWindow();
			document.getElementById("where").value = "(My Position)";
			document.getElementById("where").style.color = "#cccccc";
			currentPosition = manMarker.getPoint();
			NewSearchPoint(currentPosition);
		});
		GEvent.addListener(manMarker, "click", function(){
			var position = manMarker.getPoint();
			geocoder.getLocations(position, function(addresses) {
			  if(addresses.Status.code != 200) {
				manMarker.openInfoWindowHtml("<center><b>I have no idea where I am </b><br>My position is " + position.toUrlValue());
			  }
			  else {
				address = addresses.Placemark[0];
				var html = address.address;
				manMarker.openInfoWindowHtml("<center><b>I'm at</b><br>"+html,{maxWidth:200});
			  }
			});					
		});			
}

function go() {
	if(document.getElementById("where").value != "(My Position)") {
		currentPosition = document.getElementById("where").value;
	}
	var geocoder = new GClientGeocoder();
	geocoder.getLatLng(currentPosition,function(point) {
		manMarker.setPoint(point);
		map.setCenter(point);
		NewSearchPoint(point);
	});
//	showAds();
	return false;
}	

function NewSearchPoint(latlng) {	
	spotSearch.setCenterPoint(latlng);
	spotSearch.execute(document.getElementById("what").value);
	return false;
}

// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() {
	if (!spotSearch.results) return;
	document.getElementById("resultPanel").innerHTML = "";
	for (var i = 0; i < CurrentResults.length; i++) {
		if (!CurrentResults[i].added()) {
			map.removeOverlay(CurrentResults[i].marker());
		}	
	}
	CurrentResults = [];
	for (var i = 0; i < spotSearch.results.length; i++) {
		CurrentResults.push(new LocalResult(spotSearch.results[i],i+1));
	}
	var attribution = spotSearch.getAttribution();
	if (attribution) {
		document.getElementById("resultPanel").appendChild(attribution);
	}	
}

// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result,label) {
	this.result_ = result;
	this.resultNode_ = this.resultHtml(0);
	document.getElementById("resultPanel").appendChild(this.resultNode_);
	switch(label)
	{
		case 1:
		redDotIcon = MapIconMaker.createFlatIcon({width: 28, height: 28, primaryColor: "#ee0000",label: "1", labelColor:"#000000", labelSize:12});
		break;
		case 2:
		redDotIcon = MapIconMaker.createFlatIcon({width: 28, height: 28, primaryColor: "#ee0000",label: "2", labelColor:"#000000", labelSize:12});
		break;
		case 3:
		redDotIcon = MapIconMaker.createFlatIcon({width: 28, height: 28, primaryColor: "#ee0000",label: "3", labelColor:"#000000", labelSize:12});
		break;
		case 4:
		redDotIcon = MapIconMaker.createFlatIcon({width: 28, height: 28, primaryColor: "#ee0000",label: "4", labelColor:"#000000", labelSize:12});
		break;
		case 5:
		redDotIcon = MapIconMaker.createFlatIcon({width: 28, height: 28, primaryColor: "#ee0000",label: "5", labelColor:"#000000", labelSize:12});
		break;
		case 6:
		redDotIcon = MapIconMaker.createFlatIcon({width: 28, height: 28, primaryColor: "#ee0000",label: "6", labelColor:"#000000", labelSize:12});
		break;
		case 7:
		redDotIcon = MapIconMaker.createFlatIcon({width: 28, height: 28, primaryColor: "#ee0000",label: "7", labelColor:"#000000", labelSize:12});
		break;
		case 8:
		redDotIcon = MapIconMaker.createFlatIcon({width: 28, height: 28, primaryColor: "#ee0000",label: "8", labelColor:"#000000", labelSize:12});
		break;		
	}
	map.addOverlay(this.marker(redDotIcon));
}

// Returns the map marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function(opt_icon) {
	if (this.marker_) return this.marker_;
	var marker = new google.maps.Marker(new google.maps.LatLng(parseFloat(this.result_.lat), parseFloat(this.result_.lng)), {icon:opt_icon, title:this.result_.titleNoFormatting});
	var infoHtml;
	infoHtml = this.added() ? this.infoHtml(1) : this.infoHtml(0);	
	GEvent.bind(marker, "click", this, function() {
		marker.openInfoWindow(infoHtml,{maxWidth:200});
	});
	this.marker_ = marker;
	return marker;
};

// "Saves" this result if it has not already been saved
LocalResult.prototype.add = function() {
	if (!this.added()) {
		this.added_ = true;

		// Remove the old marker and add the new marker
		map.removeOverlay(this.marker());
		this.marker_ = null;
		map.addOverlay(this.marker(blkDotIcon));

		// Add our result to the saved set
		document.getElementById("addedPanel").appendChild(this.resultHtml(1));
		var hr = document.createElement("hr");
		hr.size = '1';
		hr.className = 'spacer';
		document.getElementById("addedPanel").appendChild(hr);
		document.getElementById("PanelB").style.visibility = "visible";

		// Remove the old search result from the search well
		this.resultNode_.parentNode.removeChild(this.resultNode_);
	}	
};

// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.resultHtml = function(added) {
	var container = document.createElement("div");
	container.className = "results";
	var infoHtml = this.infoHtml(added);
      GEvent.bindDom(container, "mouseover", this, function() {
        this.marker_.openInfoWindow(infoHtml,{maxWidth:200});
		container.className = "mouseover";
      });	
      GEvent.bindDom(container, "mouseout", this, function() {
		this.marker_.closeInfoWindow();  
		container.className = "results";
      });	  
	container.appendChild(this.result_.html.cloneNode(true));
	if(added == 0) {  
	  var addDiv = document.createElement("div");
      addDiv.className = "select";
      addDiv.innerHTML = "Add this spot";
      GEvent.bindDom(addDiv, "click", this, function() {
        map.closeInfoWindow();
		this.add();
		AddedResults.push(this);	
      });
      container.appendChild(addDiv);  
	}  
	return container;
};

LocalResult.prototype.infoHtml = function(added) {
	var container = document.createElement("div");
	container.className = "results";  
	container.appendChild(this.result_.html.cloneNode(true));
      var addDiv = document.createElement("div");
      addDiv.className = "select";
      addDiv.innerHTML = "Add this Spot";
      GEvent.bindDom(addDiv, "click", this, function() {
        map.closeInfoWindow();
		this.add();
        AddedResults.push(this);
      });
      if(added == 0) container.appendChild(addDiv);	
	return container;
};

// Returns true if this result is currently "saved"
LocalResult.prototype.added = function() {
	return this.added_;
};

function clearSearch() {
	for (var i = 0; i < CurrentResults.length; i++) {
		if (!CurrentResults[i].added()) {
			map.removeOverlay(CurrentResults[i].marker());
		}	
	}
	document.getElementById("resultPanel").innerHTML = '';
}

function clearAdded() {
	map.clearOverlays();
	document.getElementById("addedPanel").innerHTML = '';
	document.getElementById("PanelB").style.visibility = "hidden";
	addMashman(map.getCenter());
	go();
}

function maximize (thisId) {
	document.getElementById(thisId).innerHTML = '<a href="javascript:void(0);" onclick="minimize(\''+thisId+'\')"><img src="tree_expand.GIF" border="0"></a>';
	document.getElementById("resultPanel").style.height = "0px";	
}

function minimize (thisId) {
	document.getElementById(thisId).innerHTML = '<a href="javascript:void(0);" onclick="maximize(\''+thisId+'\')"><img src="tree_collapse.GIF" border="0"></a>';	
	document.getElementById("resultPanel").style.height = "";
}

function showAds() {
	document.getElementById('adsPanel').style.visibility = 'visible';
}

var markersArray;

function addPushPin(adLoc) {
	var adIcon = new google.maps.Icon();
	adIcon.image = adLoc.pinurl;
	adIcon.iconSize = new google.maps.Size(36,32);
	adIcon.iconAnchor = new google.maps.Point(18, 32);
	adIcon.infoWindowAnchor = new google.maps.Point(18, 5);
	var title = adLoc.title;
	var address = adLoc.address;
	var adMarker = new google.maps.Marker(new google.maps.LatLng(adLoc.lat, adLoc.lon), {title:title, icon:adIcon});
	GEvent.bind(adMarker, "click", this, function() {
		adMarker.openInfoWindow("<div><b>"+title+"</b><br>"+address+"</div>",{maxWidth:200});
	});	
	map.addOverlay(adMarker);
	markersArray.push(adMarker);	
}

function showPushPin(adLocations) {
	markersArray = new Array();
	for(var i=0; i<adLocations.length;i++) {
		addPushPin(adLocations[i]);
	}
}

function hidePushPin() {
	for (var i = 0; i < markersArray.length; i++) {
		map.removeOverlay(markersArray[i]);
	}
}	   
	   
function showLat49Ads(){
	Lat49.initAds(574);
	var center = map.getCenter();
	var lat = center.lat();
	var lng = center.lng();
	var zoomlevel = Lat49.Tile.convertGMap2Zoom(map.getZoom());
	Lat49.updateAdByLatLonWithExtents("lat49ads", lat, lng, zoomlevel);
}

function showPopup() {
	document.getElementById('popup').style.left = ((document.body.offsetWidth-340)/2) +'px';
	document.getElementById('popup').style.visibility = 'visible';
	dim(1);
}

function dim(yes) {
	if (yes == 1) {
		document.getElementById('canvas').style.opacity = '0.10';
	}
	else {
		document.getElementById('canvas').style.opacity = '1';
	}
}

function httpPost (url,params) {
	var http;
	
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
		try {
			http = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
			   http = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	
	http.open("POST", url, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	document.getElementById("pop").innerHTML = "Sending Email...<br>";
	http.onreadystatechange = function() {//Call a function when the state changes.
		if(http.readyState == 4 && http.status == 200) {
			document.getElementById("pop").innerHTML += http.responseText + "<br>";
		}
	}
	http.send(params);
//	document.getElementById("pop").innerHTML += "Email Sent";
}

function sendEmail() {
  var postparam = "address=" + encodeURI( document.getElementById("address").value ) +
				"&message=" + encodeURI( document.getElementById("message").value ) +
				"&data=" + encodeURI( document.getElementById("data").value );
  httpPost("send-email",postparam);
}

function popPrint() {
		var popup = window.open ("","","height=500,width=350,top=150,left=200,status=no,scrollbars=yes");
		var print = popup.document.createElement('div');
		print.id = 'printCanvas';
		print.style.font = '10pt Arial';
		print.className = "results";
		print.style.width = '100%';
		print.style.height = '100%';
		popup.document.body.appendChild(print);
		popup.document.getElementById("printCanvas").innerHTML = 'MashSpots.com<hr size="1">';
		popup.document.getElementById("printCanvas").innerHTML += '<input type="button" value="Print" onclick="window.print()"><hr size="1">';
		popup.document.getElementById("printCanvas").innerHTML += document.getElementById("addedPanel").innerHTML;
}

function popEmail() {
		showPopup();
		var data = document.getElementById("addedPanel").innerHTML;
		document.getElementById("pop").innerHTML = '<form><b>Email:</b><br><input id="address" name="address" type="text" size="30" style="width:95%"/><br><b>Message:</b><br><textarea id="message" name="message" cols="30" rows="3" style="width:95%"></textarea><br><input id="data" name="data" type="hidden" value="'+escape(data)+'"><br><input type="button" onclick="sendEmail()" value="Send"/></form>The list below will be attached:<hr size="1">';
		document.getElementById("pop").innerHTML += data;
}

google.setOnLoadCallback(OnLoad, true);
