
/////////////////////////////////
// Geotagging related functions
/////////////////////////////////


	var map;
	var geocoder;
	var localSearch;

	function handleGeotagValueChange( element ) {
	
	  // do what you want when a value change
	  hideAddGeotagLink();
	  showUpdateGeotagLink();
	
	}

	function chooseGeoTag(element) {
		initGeotagPanel(element.innerHTML);		
	}
	
	function initGeotagPanel(address) {
		load();
	  	showCancelGeotagLink();		
		newGeoTag = new Geotag();
		addressArray = address.split(",");	
		keyword = addressArray[0];

		doLocalSearch(keyword,keyword,newGeoTag);						
	}
	
	function doLocalSearch(keyword, address, geoTagObject) {
	  // Create a LocalSearch instance.
	  localSearch = new google.search.LocalSearch();

	  // Set the Local Search center point
	  localSearch.setCenterPoint("USA");

	  // Set searchComplete as the callback function when a search is complete. The
	  // localSearch object will have results in it.
	  localSearch.setSearchCompleteCallback(this, searchComplete, [keyword, geoTagObject]);

	  // Specify search quer(ies)
	  localSearch.execute(address); 

	  // Include the required Google branding. 
	  // Note that getBranding is called on google.search.Search
	  google.search.Search.getBranding('branding');		
	}


	function searchComplete(keyword, geoTagObject) {

	  // Check that we got results
		if($('geoTagPanel').style.display == 'none') {
			jQuery('#geoTagPanel').css('display','block');			
		}
		$('geotagEditTab').observe('click',showGeotagEdit);
		$('geotagListTab').observe('click',showGeotagList);
		// Observe changes of a form element
		$('streetAddress').observe('keydown',handleGeotagValueChange);
		$('city').observe('keydown',handleGeotagValueChange);
		$('state').observe('keydown',handleGeotagValueChange);
		$('zip').observe('keydown',handleGeotagValueChange);	
		$('country').observe('keydown',handleGeotagValueChange);		
		showGeotagList();
		
	  document.getElementById('geoTagList').innerHTML = '';
	  if (localSearch.results && localSearch.results.length > 0) {
		var latlngBounds = new google.maps.LatLngBounds();
	    for (var i = 0; i < localSearch.results.length; i++) {
			console.log(localSearch.results);
    		var locallatlng = new google.maps.LatLng(localSearch.results[i].lat, localSearch.results[i].lng);
			latlngBounds.extend(locallatlng);
    		var marker = new google.maps.Marker({
        		map: map, 
        		position: locallatlng
    		});

	      // Create HTML elements for search results
	      var p = document.createElement('li');
	      var a = document.createElement('a');
	      var b = document.createElement('b');
	      var c = document.createElement('c');
	      a.innerHTML = localSearch.results[i].title;
	      b.innerHTML = "<br>" + 
	        localSearch.results[i].streetAddress;
	      c.innerHTML = "<br>" + 
	        localSearch.results[i].city + "," +
	        localSearch.results[i].region;

	      // Append search results to the HTML nodes
	      p.appendChild(a);
	      p.appendChild(b);
	      p.appendChild(c);

	      jQuery("#geoTagList").append(p);
		  with({title: localSearch.results[i].titleNoFormatting, 
				streetAddress: localSearch.results[i].streetAddress,
				city: localSearch.results[i].city,
				region: localSearch.results[i].region,
				zip: "",
				country: localSearch.results[i].country,
				latitude: localSearch.results[i].lat,
				longitude: localSearch.results[i].lng,
				keyword: keyword,
				geoTagObject: geoTagObject})
		  {
			  jQuery(p).bind('click', function() { 
				var individualBounds = new google.maps.LatLngBounds(new google.maps.LatLng(latitude, longitude));
				map.setZoom(13);
				google.maps.event.trigger(map, 'resize');
				map.setCenter(individualBounds.getCenter());
				
				$('keyword').value = title;
				$('streetAddress').value = streetAddress;
				$('city').value = city;
				$('state').value = region;
				$('zip').value = zip;
				$('country').value = country;
				
				geoTagObject.setLatitude(latitude);
				geoTagObject.setLongitude(longitude);
				geoTagObject.setStreetAddress(streetAddress);
				geoTagObject.setCity(city);
				geoTagObject.setState(region);
				geoTagObject.setZip(zip);
				geoTagObject.setCountry(country);
				isSetLatLong(geoTagObject);
				showGeotagEdit(); //Switch so user can edit data
			  });
		  }
		
	    }
	    map.fitBounds(latlngBounds);
		google.maps.event.trigger(map, 'resize');
		map.setCenter(latlngBounds.getCenter());	
	
	      var p = document.createElement('li');
	      var a = document.createElement('a');
	      var b = document.createElement('b');
	      var c = document.createElement('c');
	      a.innerHTML = "<a href='#' onclick='showGeotagEdit();return false;'>Don't see the "+keyword+" you're looking for? Add some more details.</a>";
	      b.innerHTML = "<br>";
	      c.innerHTML = "<br>";

	      // Append search results to the HTML nodes
	      p.appendChild(a);
	      p.appendChild(b);
	      p.appendChild(c);

	      jQuery("#geoTagList").append(p);	
	  } else {
	      var p = document.createElement('li');
	      var a = document.createElement('a');
	      var b = document.createElement('b');
	      var c = document.createElement('c');
	      a.innerHTML = "<a href='#' onclick='showGeotagEdit();return false;'>We can't find any places called " + keyword + ".  Tell us about it now.</a>";
	      b.innerHTML = "<br>";
	      c.innerHTML = "<br>";

	      // Append search results to the HTML nodes
	      p.appendChild(a);
	      p.appendChild(b);
	      p.appendChild(c);

	      jQuery("#geoTagList").append(p);	

	  }
	
	
	
	}
	
	
	function clearGeotagEditForm() {
		$('keyword').value = "";
		$('streetAddress').value = "";
		$('city').value = "";
		$('state').value = "";
		$('zip').value = "";
		$('country').value = "";
	}
	

    function load() {

	    geocoder = new google.maps.Geocoder();
	    var latlng = new google.maps.LatLng(-34.397, 150.644);
	    var myOptions = {
	      zoom: 8,
	      center: latlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    }
	

	function updateMapFromForm() {
		address = $('keyword').value + ' ,' + $('streetAddress').value + ',' + $('city').value + ',' + $('state').value + ',' + $('zip').value + ',' + $('country').value;
		doLocalSearch(keyword, address, new Geotag());
	}	
	
    // addAddressToMap() is called when the geocoder returns an
    // answer.  It adds a marker to the map with an open info window
    // showing the nicely formatted version of the address and the country code.
    function addAddressToMap(keyword, results, status, geoTagObject) {

      if (status == google.maps.GeocoderStatus.OK) {
		console.log(results);

	  //	fillGeotagPanel(keyword, results.Placemark[0].AddressDetails, geoTagObject);	  

		numberOfPlaces = results.length;
		
		if(numberOfPlaces > 1) {
			showListOfPlaces(keyword, results);
		} else {
			showPlaceOnMap(results[0], geoTagObject);
		}

	  } else {
		hideAddGeotagLink();
		setGeotagMessage("Sorry, we were unable to geocode that address.  Please provide some additional information below or click on the map.");
		google.maps.event.trigger(map, 'resize');
        map.setCenter(new GLatLng(51, -150), 2);
        map.addControl(new GSmallMapControl());
		$('keyword').value = keyword;
		showGeotagEdit();
		if($('geoTagPanel').style.display == 'none') {
			jQuery('#geoTagPanel').css('display','block');
		}  
	  }

	}
	


	function showListOfPlaces(keyword, places) {
		htmlString = "";
		for(i = 0; i < places.length; i++) {
			listItemNumber = i%2;
			htmlString += "<li class='listItem_"+listItemNumber+"'>"+places[i].formatted_address+"</li>";
		}
		jQuery('#geoTagList').html(htmlString);		
		
	}

	function showGeotagList() {
		$('geoTagInput').style.display = "none";
		$('geoTagList').style.display = "block";
		
		$('geotagListTab').className = "active";
		$('geotagEditTab').className = "inactive";		
	}


	function showGeotagEdit() {
		$('geoTagList').style.display = "none";
		$('geoTagInput').style.display = "block";

		$('geotagEditTab').className = "active";		
		$('geotagListTab').className = "inactive";
	}

	function hideGeotagListTab() {
		$('geotagListTab').style.display = "none";
	}
	
	function showGeotagListTab() {
		$('geotagListTab').style.display = "block";
	}
		
	function isSetLatLong(geoTagObject) {
		if(geoTagObject.getLongitude() && geoTagObject.getLatitude()) {
			showAddGeotagLink();	
			hideUpdateGeotagLink();	
		} 
	}

	function showAddGeotagLink() {
		$('addGeotagLink').style.display = 'block';		
	}
	
	function hideAddGeotagLink() {
		$('addGeotagLink').style.display = 'none';
	}

	function showUpdateGeotagLink() {
		$('updateGeotagLink').style.display = 'block';
	}

	function showCancelGeotagLink() {
		$('cancelGeotagLink').style.display = 'block';
	}	
	
	function hideUpdateGeotagLink() {
		$('updateGeotagLink').style.display = 'none';
	}

	function hideCancelGeotagLink() {
		$('cancelGeotagLink').style.display = 'none';
	}

	function setGeotagMessage(message) {
		$('geotagMessage').innerHTML = message;
	}
	
	function array_to_get(theArray)
	{
		output = '';
		for(i=0;i<theArray.length;i++){
			glue = (i)?'&':'?';
			output += glue+'myArray['+i+']='+theArray[i];
		}
		return output;
	} 

	function addGeotag(thread,id) {
		//Update the currentGeotag with the latest information from the form.  This ensures what the user sees is what is set.
		updateCurrentGeotagFromForm();

		//Add this GeoTag to the array of GeoTags so we can use them during submit.  Use clone or else a reference will be created
		geoTagsArray[geoTagsArray.length] = currentGeoTag.clone();
		thread.getCommentById(id).addGeotag(currentGeoTag.clone());
		//Add This GeoTag to the Database via remote call 
		//<![CDATA[
			new Ajax.Request('/post/insertGeotag', {asynchronous:true, evalScripts:true, parameters:currentGeoTag.serialize(),onComplete:completeAddGeotag});
		//]]>		

	}
	
	function updateCurrentGeotagFromForm() {
		currentGeoTag.setKeyword($('keyword').value);
		currentGeoTag.setStreetAddress($('streetAddress').value);
		currentGeoTag.setCity($('city').value);
		currentGeoTag.setState($('state').value);
		currentGeoTag.setZip($('zip').value);
		currentGeoTag.setCountry($('country').value);
	}
	
	function updateCurrentGeotag(longitude, latitude, keyword, streetAddress, city, state, zip, country) {
		currentGeoTag.setLongitude(longitude);
		currentGeoTag.setLatitude(latitude);
		currentGeoTag.setKeyword(keyword);
		currentGeoTag.setStreetAddress(streetAddress);
		currentGeoTag.setCity(city);
		currentGeoTag.setState(state);
		currentGeoTag.setZip(zip);
		currentGeoTag.setCountry(country);		
	}
	
	function completeAddGeotag() {

		//Update the json that gets submitted with the post submit
		$('postGeotagArray').value = Object.toJSON(geoTagsArray);

		//Add to visual list of geoTags
		// $('currentGeoTagsList').innerHTML += "<li id='currentGeoTag_"+currentGeoTag.getKeyword()+"' style='display:none;'>"+currentGeoTag.getKeyword()+"</li>";
		// Effect.Appear('currentGeoTag_'+currentGeoTag.getKeyword());

		//If the list is not already visible then do so now
		//if($('currentGeoTags').style.display == 'none') {
		//	Effect.BlindDown('currentGeoTags');
		//}

		//Clear the input field and add focus
		//Hid GeoTagPanel
		Effect.BlindUp('geoTagPanel');
		hideAddGeotagLink();
		hideCancelGeotagLink();
		$('keyword').value = "";
		$('streetAddress').value = "";
		$('city').value = "";
		$('state').value = "";
		$('zip').value = "";								
		$('country').value = "";
		
	}
	
	function cancelGeotag() {
		Effect.BlindUp('geoTagPanel');
		hideUpdateGeotagLink();
		hideAddGeotagLink();
		hideCancelGeotagLink();				
	}

	function hideGeotagCheckMessage() {
		Effect.Fade($('geotagCheckMessage'));
	}