/**
* Javascript to process 
*
* @package CafeWorkr 
* @subpackage Javascript 
* @author Andrew Woods <andrew@mastodonlabs.com>
*
*/  

$(document).ready(function(){

	$(':input.required').siblings('label').addClass('required');

	$('#search_form').submit(function(e){
		e.preventDefault();
			
		var path = $(this).attr('action');
		var query = $('#query').val();
		
		var regex = /\s+/g; // multiple spaces, globally
		var replacement = ' '; // a single space
		query =  query.replace(regex, replacement, 'g');

		var href = path + '/' + myescape(query);
		  
		location.href = href;
	});

	/*  */
	$('#venue_add_edit').submit(function(event){
		myform = $(this);
		returnValue = false;
		
		validation_url = "http://" + location.host + "/venue/validate/ajax";

		formData = $(":input.required").serialize();
		formData += '&add-edit-submit-button=ajax-submit';

		$.ajax({
			type: 'POST',
			async: false, 
			url: validation_url, 
			data: formData, 
			dataType: 'json',
			/* don't use in production 				
			error: function(xhr, textStatus, errorThrown){
				alert('textStatus=' + textStatus + ', errorThrown=' + errorThrown);					
			},
			*/
			success: function(info, textStatus){
				if (info['no_errors'])
				{
					returnValue = true;		
				}
				else
				{
					event.preventDefault();
					data = "The following errors occurred\n";
					for (i in info)
					{
						data += ' * ' + i + '=' + info[i] + "\n";
					}
			        alert(data);						
			
				}
			}
		});
		test_text = (returnValue) ? 'yes' : 'no';
		
		return returnValue;
		
	});
	

	$('#data_index').submit(function(event){
		event.preventDefault();
		
		var data = {'state': '', 'batch-limit': '' };
		data.state = $('state').val();
		data.batch_size = $('batch-size').val();
		
		$.ajax({
		  	type: 'POST',
			async: false,
		  	url: $(this).attr('action'),
		  	data: $(":input.required").serialize(),
		  	success: function(response){
				alert(response);
			},
			dataType: 'text/plain'
		});
		/* */
		
	});

	$('#point_radius').submit(function(event){
		event.preventDefault();
		
		var data = {'origin': '', 'distance': '' };
		data.origin = $('#origin').val();
		data.distance = $('#distance').val();
		
		$.ajax({
		  	type: 'POST',
		  	url: $(this).attr('action'),
		  	data: data,
		  	success: function(response){
				alert(response);
			},
			dataType: 'text/plain'
		});
		/* */
		
	});

	var google_map = $("#google_map");

	if ( $('#google_map').hasClass('empty') )
	{
		console.log('start');	
		if (navigator.geolocation)
		{
			console.log('geolocation is supported');	
			navigator.geolocation.getCurrentPosition(
			
				function(position){
					// success
					latitude  = position.coords.latitude;
					longitude = position.coords.longitude;
					console.log('current position: SUCCESS: ' + latitude 
					+ ', ' +longitude);	

					data = new Object();
					data['latitude']  = latitude;
					data['longitude'] = longitude;
					process( data );
					$('#google_map').removeClass('empty').show();
				},
				function( error ){
					// error handling
					// ERROR: code=2 
					// PERMISSION_DENIED=1 
					// POSITION_UNAVAILABLE=2 
					// TIMEOUT=3

					if (error['code'] == error['PERMISSION_DENIED'] ){
						message = 'Cannot access user location. no permission.';
						console.log('position: ERROR: ' + message );	
					}

					if (error['code'] == error['POSITION_UNAVAILABLE'] ){
						message = 'Their position is unavailable.';
						// 47.6127878,-122.3328662
						data = new Object();
						data['latitude']  = 47.6127878;
						data['longitude'] = -122.3328662;
						process( data );
						return;
					}
					if (error['code'] == error['TIMEOUT'] ){
						message = 'sorry. it took too long.';
						console.log('position: ERROR: ' + message );	
					}
					
				},
				{
					// options
					enableHighAccuracy: true
				}
			);
		}
		else
		{
			alert('GeoLocation Not Available');
		}
		
	}

});

function parseObject( data ){

	result = '';
	for ( i in data ){
		result += i + '=' + data[i]+ "\n";	
	}
	return result;
}

var map = ''; 	
function process( position )
{
	console.log('process position');
	var ajax_url = '';
	var markersArray = [];
	var infoWindow = null;

	//  Users Location Detected
	coords = position['latitude'] + "," + position['longitude'] ;

	ajax_url = "/search/" + escape(coords) + "/ajax";
	console.log('ajax url=' + ajax_url);
	
	$.ajax({
	  url: ajax_url ,
	  dataType: 'json',
	  success: function( result, textStatus, jqXHR ){

		if ( result == null )
		{
			console.log('No Results');
			alert('No Results');
			return;
		}

		// dont show more than 10 results
		resultMax = ( 15 < result.data.length ) ? 15 : result.data.length ;

		renderGoogleMap(position, result.data, resultMax);

		resultHtml = '<ul class="venue-listing">';
		for (i=0; i < resultMax; i++)
		{
			var infoHtml = '';
			resultItem = result.data[i];
			
			itemMapUrl = myescape(resultItem.address 
			+ ' ' + resultItem.city + ' ' +  resultItem.state 
			+ ' ' + resultItem.postal);

			resultHtml += '<li class="vcard box clearfix">'
			+ '<div class="grid_5">'
			+ '<a href="/venue/id/' + resultItem.id + '">'
			+ '<h2 class="fn org">' + resultItem.name + '</h2></a>'
			+ '<div class="adr">';
			

			if ( resultItem.neighborhood )
			{		
				resultHtml += '<span class="neighborhood">'
				+ '<a href="/venue/all/' + resultItem.state + '/' 
				+ resultItem.city + '/' + resultItem.neighborhood 
				+ '" title="search ' + resultItem.neighborhood 
				+ ' for other cafes">' + resultItem.neighborhood + '</a>'
				+ '</span><br>';

			}
			
			if (resultItem.address){
				resultHtml += '<span class="street-address">' 
				+ resultItem.address + '</span><br />';
			} else {
				resultHtml += '<br />';
			}

			if (resultItem.city){
				resultHtml += '<span class="locality">' 
				+ resultItem.city + '</span> ';
			}

			if (resultItem.state){
				resultHtml += '<span class="region">' 
				+ resultItem.state + '</span> ';
			}

			if (resultItem.postal){
				resultHtml += '<span class="postal-code">' 
				+ resultItem.postal + '</span><br>';
			}
			resultHtml += '</div>'
			+ '</div>'
			+ '<div class="grid_6">'
			+ '<div>';
			
			resultHtml += 'Phone: <span class="tel">';
			if (resultItem.phone){
				resultHtml += resultItem.phone; 
			}
			resultHtml += '</span><br>';

			resultHtml += 'website: '; 
			if (resultItem.website){
				resultHtml += '<a class="url" rel="external" href="' 
				+ resultItem.website + '">' + resultItem.website + '</a>'
			}
			resultHtml += '</div>'
			+ '<br>'
			+ '<a href="/venue/id/' + resultItem.id + '">Details</a> '
			+ '<a class="contact" rel="external" href="http://maps.google.com/maps?q=' 
			+ itemMapUrl + '&amp;ie=UTF8&amp;z=16">Map It!</a><br> '
			+ '</div>'
			+ '</li>' ;

		}
		
		resultHtml += "</ul>";
		$('#results').html(resultHtml);


		$('google_map').removeClass('empty');
	  },
	  error: function( jqXHR, textStatus, errorThrown ){
		
		output = "";
		output += "Status=" + textStatus + "\n";
		output += "Error=" + errorThrown + "\n";

		alert("ERROR:" + jqXHR.status + " / " + jqXHR.statusText 
		+ " / textStatus=" + textStatus 
		+ " / errorthrown=" + errorThrown );
	  }
	});

	return;
}

function renderGoogleMap(position, data, max){

	dataMarker = new Array();
	var userLocation = new google.maps.LatLng(
		position['latitude'], position['longitude']
	);

	var mapOptions = {
		zoom: 15
		, center: userLocation 
		, mapTypeId: google.maps.MapTypeId.ROADMAP
	};

	if (typeof map_id == "undefined"){ 
		map = new google.maps.Map(document.getElementById("google_map"), 
		mapOptions);
	} else {
		map = new google.maps.Map(document.getElementById(map_id), 
		mapOptions);
	}
	var userIcon = '/img/icons/blue-pin.png';
	var userMarker = new google.maps.Marker({
		position: userLocation
		, visible: true
		, icon: userIcon 
		, title:"You are here!"
	});
	userMarker.setMap(map);

	for (i=0; i < max; i++){
		var infoHtml = '';
		if (typeof data == "undefined"){
			break;	
		}
		resultItem = data[i];

		infoHtml += '<a href="/venue/id/' + resultItem.id + '">'
		+  resultItem.name + '</a><br />'

		if (resultItem.neighborhood){
			infoHtml += '<span class="neighborhood">'
			+ resultItem.neighborhood 
			+ '</span><br>';
		}

		if (resultItem.address){
			infoHtml += resultItem.address + '<br>';
		}

		if (resultItem.city){
			infoHtml += resultItem.city + ' ';
		}

		if (resultItem.state){
			infoHtml +=  resultItem.state + ' ';
		}

		if (resultItem.postal){
			infoHtml += resultItem.postal + ' ';
		}
		
		infoHtml += '<br />';

		if (resultItem.phone){
			infoHtml += 'Phone: '; 
			if (resultItem.phone != 'null'){
				infoHtml += '/' + resultItem.phone + '/';
			}
			infoHtml += '<br />';
		}

		if (resultItem.website){
			infoHtml += 'website: <a class="url" rel="external" href="' 
			+ resultItem.website + '">' + resultItem.website + '</a>';
		}

		var cafeLocation = new google.maps.LatLng(
			resultItem.lat, resultItem.lng
		);

		var marker = new google.maps.Marker({
			position: cafeLocation
			, visible: true
			, title: resultItem.name
		});

		dataMarker[i] = marker;

		infoWindow = new google.maps.InfoWindow();
		infoWindow.setContent(infoHtml);

		google.maps.event.addListener(marker, 'click',
			handleMarkerClick(marker, infoWindow)
		); 

		marker.setMap(map);
	}
	
}

// In the global namespace
function handleMarkerClick(marker, infoWindow) {

	return function() {
		infoWindow.open(map, marker);
	};
} 



/**
 * Function : dump()
 * Arguments: The data - array,hash(associative array),object
 *    The level - OPTIONAL
 * Returns  : The textual representation of the array.
 * This function was inspired by the print_r function of PHP.
 * This will accept some data as the argument and return a
 * text that will be a more readable version of the
 * array/hash/object that is given.
 * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
 */
function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

function myescape(str){
	
	/* change all spaces into + */
	str = str.replace(/\s+/g, '+');
	
	return escape(str);
}



