var map = null;
var geocoder = null;
var disamb = null;
var mapControl = null;
var bounds = null;
var points = [];

var operators = [];
var sectors = [];
var free = null;

var currentPoint = null;
var currentPage = 0;

var filter;

var ths_loc_paths;

function initialize() {
	
	$(document.body).addEvent({
		'unload': GUnload
	});
	
	if (!GBrowserIsCompatible()) {
		window.alert("Google Maps can't play with your browser.");
		return;
	}
	
	$$('img', 'key').addEvents({
		'mouseenter': function(img) {
			$$('.filter h1').set('text', img.target.getProperty('title'));
					
		},
		'click': function(img) {
			// prepended each icon with an "i", to be removed here...
			icon = img.target.getProperty('id').substring(1);
			
			if(icon == "free") {		
				if(free) {
					free = null;
				} else {
					free = true;
					icon = icon + "-on";
				}
			} else {
				if (sectors.contains(icon)) {
					sectors.erase(icon);
				} else {
					sectors.include(icon);
					icon = icon + "-on";
				}
			}
			img.target.setProperty('src', '/images/icons/' + icon + '.png');
		}
	});

	$('key').addEvent('mouseleave', function() {
		$$('.filter h1').set('text','search filter');
	});
	
	
	$('updateFilter').addEvent('click', function() {
		cleanUp();
		initSearch();
	});

	$('go').addEvent('click', function() {
		cleanUp();
		initSearch();
	});
	
	$('address').addEvents({
		'click': function(el) { 
			// select all text...
			
		},
		'keydown': function(el) {
//			console.log(el);
			if(!el.target.value.length) {
				
				$('disambSelect').empty();
				$('disamb').addClass('hidden');
				
			} else if(el.code == '13') {
				cleanUp();
				initSearch();
			}
		}
	});
	
	$('disambSelect').addEvent('change', function(el) {
		// console.log(disamb.Placemark[$('disambSelect').value]);
		if($('disambSelect').value > 0) {
			fetchData(disamb.Placemark[$('disambSelect').value - 1]);
		}
	});
	
	$('clearSearch').addEvent('click', function(el){
		$('disambSelect').empty();
		$('disamb').addClass('hidden');
	});

	map = new GMap2($('map'));
	
	map.setCenter(new GLatLng(46.8,1.8), 0); 
	geocoder = new GClientGeocoder();

	mapControl = new GSmallMapControl();

	$('map').setStyle('height', getMapHeight());
	
	$('map').addEvents( {
		'mouseenter' :addControls,
		'mouseleave' :removeControls
	});

	window.onresize = resizeContainer;
	window.onscroll = scrollMap;

	loadingStatus(true);

	initSearch();

}

function initSearch() {

	if (geocoder) {
		// we should grab this from elsewhere...
		geocoder.setBaseCountryCode($('iso_id').value);

		// expand upon disambiguation to display options...
		geocoder.getLocations($('address').value, function(locations) {
			
			disamb = locations;
			
			if(disamb.Status.code == 602) {
				window.alert('No places found. Please try searching again.');
				return;
			}
			
			switch(disamb.Placemark.length) 
			{
			case 0:
				window.alert('No places found. Please try searching again.');
				return;
			case 1:
				fetchData(disamb.Placemark[0]);
				return;
			default:				
				$('disambSelect').empty();
				
				// show the locations
				$('disambCount').set('text', disamb.Placemark.length + ' places');
				$('disamb').removeClass('hidden');
				
				$('disambSelect').adopt(new Element('option',{'value': 0}));
				
				disamb.Placemark.each(function(item, index) {
					
					var option = new Element('option', {
										'value'	:index + 1,
										'text'	:item.address 
										});
					
					$('disambSelect').adopt(option);
					
				});
				
			}
			
		});

		// $('heading').set('text', disamb.Placemark[0].address);	
	}
}

function fetchData(placemark) {
	
	$$('#main .title h1').set('text', placemark.address.toLowerCase());
	
	if(placemark == currentPoint) {
		currentPage++;
	} else {
		currentPoint = placemark;
		currentPage = 1;
		$('results').empty();
		var myFx = new Fx.Scroll(window).toTop;
	}

//	console.log(point);

	var jSonRequest = new Request.JSON( {
		url :"/search",
		onSuccess : function(results) {
			displayResults(results);
		}
	}).get( {
		'lat' :placemark.Point.coordinates[1],
		'lon' :placemark.Point.coordinates[0],
//		'distance' :$('distance').value,
		'page' : currentPage,
		'sectors': sectors,
		'operators': operators,
		'free' : free
	});
	
}

// clean up guff for brand new search or filter...
function cleanUp() {
	disamb = null;
	$('disambSelect').empty();
	currentPage = 0;
	map.clearOverlays();
	$('results').empty();
}

// point is temporary since each location will contain a point...
function displayResults(results) {
	
	// console.log(results);
	// $('results').setProperty('start', results.firstIndice );
	$('results').setProperty('start', 1 );
		
	locations = results.locations.rummbles;

	bounds = new GLatLngBounds();
	points = new Array();

	ths_loc_paths = results.ths_loc_paths;
	
	locations.each(function(venue, index) {
		$('results').appendChild(handleRecord(venue));
	});
	
//	bounds.extend(points);
	
	// count locations or do bounding...
	/*
	for (i = 0; i < locations.length; i++) {

		points[i] = new GLatLng(locations[i].latitude, locations[i].longitude);

		bounds.extend(points[i]);

		var marker = new GMarker(points[i]);
		
		var h3Venue = new Element('h3').set('text', locations[i].name);
		
		// create list of operators
//		var ulOperators = new Element('ul', { 'class': 'mapOperators'});
//		locations[i].Operator.each(function(operator) {
//			ulOperators.grab(new Element('li').set('text', operator.company));
//		});
		
//		marker.bindInfoWindowHtml(new Element('div').adopt(h3Venue, ulOperators));
		
		marker.bindInfoWindowHtml(new Element('div').adopt(h3Venue));
		map.addOverlay(marker);
		
		$('results').appendChild(handleRecord(locations[i], marker));

	}
	*/
	
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());
	
	$$('.pagination').setStyle('display', results.lastPage > 1 ? 'block' : 'none');

	loadingStatus(false);
}

function handleRecord(venue) {
	
	// Handle single record from search result set
	var li_location = new Element('li', {
		'class' :'location',
		'events' : {
			'mouseenter' : function() {
		
				li_location.morph({
					'background-color':'#f2ebf7'
				});
				
//				ul_social.morph({
//					'background-color':'#fff'
//				});
				
				GEvent.trigger(marker, 'click');
				
				if(map.getZoom() < 14) {
					map.setZoom(14);
				}
			},
			'mouseleave' : function() {
				li_location.morph({
					'background-color':'#fff'
				});
				
//				ul_social.morph({
//					'background-color':'#f2ebf7'
//				});
			}
		}
	});

	/*
	var img_icon = new Element('img', {
		'src' :'/images/icons/map/' + location.Sector.ico_id + '.gif',
		'alt' :location.Sector.sector_real,
		'title' :location.Sector.sector_real,
		'class' :'icon'
	});
	*/
	
	var a_loc = new Element('a', {
		//	'href' :venue.loc_full_path
		// 'record_id': mm_record.id,
	}).set('text', venue.name);
	
	var derived_from = venue.derived_from.split(':');
	
	var loc_url = "";
	
	// build url according to data source
	switch(derived_from[0])
	{
		case 'THS':
			loc_url = ths_loc_paths[derived_from[1]] ? ths_loc_paths[derived_from[1]] : '/wireless_hotspot/' + derived_from[1];	
			break;
			
		case 'RUMMBLE':
			loc_url = '/rummblespot/' + derived_from[1];
			break;
		
		default:
			var rummble_id = venue.rummble_id.split(":");
			if(rummble_id[0] == 'RUMMBLE') {
				loc_url = '/rummblespot/' + rummble_id[1];
			}
			break;
	}
	
	a_loc.setProperty('href', loc_url);
	
//	if(ths_loc_paths[venue])
	
	var h2_loc = new Element('h2');
//	h2.adopt( [ img_icon, anchor ]);
	h2_loc.adopt( [ a_loc ]);
	
	li_location.adopt(h2_loc);
	
	// repeated below in marker...
	if($type(venue.address) == 'string') {
		li_location.adopt(new Element('p').set('text', venue.address));
	}

	var distance;
	if (venue.distance_from_search_location_metres) {
		distance = venue.distance_from_search_location_metres + ' metres';
	}

	var p_distance = new Element('p', {
		'class' :'distance'
	}).set('text', distance);

	/*
	if(location.number_of_reviews > 0) {
		
		var review_text = location.number_of_reviews == 0
		
	} else {
		
	} */
	
	var p_reviews = new Element('p', {
/*		'html':location.number_of_reviews > 0 ? location.number_of_reviews + ' review' + (location.number_of_reviews == 1 ? '' : 's') : 'write review', */
		'class':'reviews'
	}).adopt(new Element('a', {
		'html': venue.number_of_reviews > 0 ? venue.number_of_reviews + ' review' + (venue.number_of_reviews == 1 ? '' : 's') : 'write review',
		'href':'#'
	}));
	
	if(venue.rating == -1) {
		
		p_reviews.setStyle('top', '7px');
		
	} else {
		
		p_rating  = new Element('p', { 
			'class' : 'rating',
			'html' : venue.rating / 10,
			'styles' : {
				'background-position': '0 ' + (1 - (100 - venue.rating)) + 'px'
			}
		}); // .set('text', venue.rating );
		
//		var grad_vertical_position = 1 - (100 - venue.rating);
//		p_rating.setStyle('background-position', '0 ' + grad_vertical_position + 'px');
		
		li_location.adopt(p_rating);
		
	}
	
	
	/*
 
	var ul_social = new Element('ul', {
		'class' :'social'
	});

	var li_favourite = new Element('li', {
		'class' :'favicon'
	});
	var a_fav = new Element('a', {
		'href' :'#'
	});
	var img_fav = new Element('img', {
		'src' :'/images/icons/heart-off.gif'
	});

	a_fav.appendText('add to favourites');
	a_fav.adopt(img_fav);

	li_favourite.adopt(a_fav);

	li_favourite.addEvents( {
		'mouseenter' : function() {
			img_fav.setProperty('src', '/images/icons/heart-on.gif');
		},
		'mouseleave' : function() {
			img_fav.setProperty('src', '/images/icons/heart-off.gif');
		},
		'click' : function() {
			// json request to add location to favourites.
		// console.log(mm_record['client_id']);
	}
	});

	ul_social.adopt(li_favourite);

	li_reviews = new Element('li').set('text', '0 reviews | write');
	ul_social.adopt(li_reviews);

//	li_ratings = new Element('li').set('text', 'rating');
//	ul_social.adopt(li_ratings);

	var ul_operators = new Element('ul', {
		'class' :'operators'
	});
	
	*/

	if(venue.free == 1) {
	
		img_free = new Element('img', {
			'src': '/images/icons/free-focus.png',
			'width': '20px',
			'height': '20px',
			'class': 'free'
		});
		
		li_location.adopt(img_free);
		
	}
	
	li_location.adopt( [ p_reviews, p_distance]); //, ul_social, ul_operators ]);

	// add map marker
	point = new GLatLng(venue.latitude, venue.longitude);
	points.include(point);

	bounds.extend(point);

	var marker = new GMarker(point);
	
	var h3_venue = new Element('h3').set('text', venue.name);
	
	// create list of operators
//	var ulOperators = new Element('ul', { 'class': 'mapOperators'});
//	locations[i].Operator.each(function(operator) {
//		ulOperators.grab(new Element('li').set('text', operator.company));
//	});
	
//	marker.bindInfoWindowHtml(new Element('div').adopt(h3Venue, ulOperators));
		
	bubble_html = new Element('div').adopt( h3_venue );
	
	if($type(venue.address) == 'string') {
		bubble_html.adopt(new Element('p').set('text', venue.address));
	}
	
	if($type(venue.tags) == 'string') {
		bubble_html.adopt(new Element('p').set('text', venue.tags.replace(/,/g,", ")));
	}
	
	if(venue.photo_thumbnail) {
		
		bubble_html.adopt(new Element('img', {
			'src':venue.photo_thumbnail
		}));
		
	}
	
	marker.bindInfoWindowHtml(bubble_html);
	
	map.addOverlay(marker);
	
	// buildRummbleButtons();
	
	return li_location;

}


function addControls() {

	map.addControl(mapControl);

}

function removeControls() {

	map.removeControl(mapControl);

}

function getMapHeight() {

//	var map_height = window.innerHeight - 278;

	var map_height = window.innerHeight - 278;
	
	if (map_height < 250) {
		map_height = 250;
	}

	if (map_height > 512) {
		map_height = 512;
	}

	return map_height;
}

function loadingStatus(bool) {
	$$('#address, #iso_id, #address_select, #distance, #go').setStyle(
			'disabled', bool);
	
	$('loading').setStyle('display', bool ? 'inline' : 'none');
	
	if (bool) {
		var scroll = new Fx.Scroll(window);
		scroll.toTop();
	}
}

function resizeContainer() {
	// Resize container
	var mapFX = new Fx.Morph('map', {
		transition :Fx.Transitions.Sine.easeOut
	});

	mapFX.start( {
		'height' :getMapHeight()
	});

}

function scrollMap() {

	var scroll = window.getScroll().y - 256 + 28;
	
	if (scroll < 0) {
		scroll = 0;
	}
	
	max_scroll = window.getScrollSize().y - getMapHeight() - 240 - 350;

	// console.log(max_scroll);

	if (scroll > max_scroll) {
		scroll = max_scroll;
	}

	$('sponsors').morph( {
		'padding-top':scroll + 'px'
	});

}

window.addEvent('domready', function(ev) { 
	// console.log('the dom is ready'); 
	initialize(); 
});
