var localSearch			= new GlocalSearch();
var map					= false;
var geocoder			= false;
var gdir				= false;
var selectedStore		= false;
var resultLat			= false;
var resultLng			= false;
var search_button		= false;
var address_input		= false;
var default_address		= false;
var my_store			= false;
var vip					= false;
var thoroughgoods		= false;
var body				= false;

var reasons				= [];
var current				= new Array();
var defaultlat			= eval('53.796206');
var defaultlng			= eval('-1.566738');
var defaultzoom			= eval('6');

var icon				= new GIcon();
icon.image				= "/images/store-icon.png";
icon.iconSize			= new GSize(16, 16);
icon.iconAnchor 		= new GPoint(16, 13);							
icon.infoWindowAnchor	= new GPoint(16, 4);

var tgicon				= new GIcon();
tgicon.image			= "/images/tgstore-icon.gif";
tgicon.iconSize			= new GSize(16, 16);
tgicon.iconAnchor 		= new GPoint(16, 13);							
tgicon.infoWindowAnchor	= new GPoint(16, 4);

var postcode_not_found_message = "Unable to pinpoint, please enter full postcode.";
var invalid_postcode_message = "Postcode appears to be incomplete, please enter full postcode.";
var address_not_found_message = "Sorry, we were unable to find that address.";

// LOAD FUNCTIONS
window.addEvent('domready', function() {
	
	// SETUP THE CONFIG TO DISPLAY THE RIGHT THINGS ETC.
	body 			= $(document.body);
	store_locator 	= $('storelocator');
	address_input 	= $('addressInput');
	
	if(body.get('id') == 'vip'){
		vip = true;
	}
	if(address_input.get('rel') == 'thoroughgoods'){
		thoroughgoods = true;
	}
	
	load();
	if(store_locator && address_input) {				
		default_address = address_input.get('value');
		store_locator.addEvent('submit', function(e) {
			e.preventDefault();
			initFromPostcode(searchLocations);
		});
	} else { return false; }	
	
	// If we have a postcode in the input - run the search.				
	if(default_address && default_address.clean() !== '') { return initFromPostcode(searchLocations); }
	
});


// Button event function
function initFromPostcode(callbackFunction) {
	add = address_input.get('value');
	//if(!$chk(add)) { alert(postcode_not_found_message); return false; }
	//if(add.length < 6) { alert(invalid_postcode_message); return false; }
	
	map.clearOverlays();
	
	localSearch.setSearchCompleteCallback(null, function() {
		if (localSearch.results[0]) {    
			resultLat = localSearch.results[0].lat;
			resultLng = localSearch.results[0].lng;
			my_point = new GLatLng(resultLat,resultLng);
			var my_marker = new GMarker(my_point);
			
			map.addOverlay(my_marker);
			//map.setCenter(my_point, defaultzoom);
			
			// Callback is passed in from click event - searchLocations()
			return callbackFunction();
		} else { alert(address_not_found_message); return false; }
	});  
	return localSearch.execute(add + ", UK");
}



// Check compatability - add map controls.
function load() {
	if (!GBrowserIsCompatible()) { return false; }

	geocoder = new GClientGeocoder();
	
	map = new GMap2(document.getElementById('map'));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());

	reasons[G_GEO_SUCCESS]            = "Success";
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
	
	var default_point = new GLatLng(defaultlat, defaultlng);		
	map.setCenter(default_point, defaultzoom);
}

// main work horse.
searchLocations = function() {
	if(my_point) {
	 	current[0] = resultLat;
	 	current[1] = resultLng;
    	searchLocationsNear(resultLat, resultLng, default_address);
	}
	return false;
}

// Wrapper for google function.
function showDirections(to) { 
	map.clearOverlays();
  		
	gdir = new GDirections(map, $("sidebar"));
	$("sidebar").set('html', '<a href="javascript:void(0);" onclick="return searchLocations()">&laquo;Back to stores</a><hr/>');        
	setDirections(current[0]+","+current[1], to, "en_GB");
}

// Wrapper for google function.
function setDirections(fromAddress, toAddress, locale) {
	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": locale });
}

// Get radial locations based on the current map point.
function searchLocationsNear(lat, lng, title){
	myaddress = new GLatLng(lat,lng);
	var radius = $('radiusSelect').value;
	var searchUrl = './index:locateStoresJson?lat=' + lat + '&lng=' + lng + '&radius=' + radius;
    GDownloadUrl(searchUrl, function(data){
		if(!data || data.clean() == ''){
			return false;
		}
		var my_markers = JSON.decode(data);
		if(!my_markers || my_markers.length < 1){
			return false;
		}
		var mlen = my_markers.markers.length;
        
        if(mlen){
			var count = 0;
			map.clearOverlays();
			var bounds = new GLatLngBounds();
			var sidebar = $('sidebar');
			sidebar.set('html', '');
			if(mlen == 1){
				sidebar.set('html', 'Sorry, no stores were found.');
				if(defaultlat && defaultlng && defaultzoom){
					map.setCenter(new GLatLng(defaultlat, defaultlng), defaultzoom);
				}
				return;
			}else{
				var mi=0;
				for(mi=0;mi<mlen;mi++){
					
					var mmarker = my_markers.markers[mi].marker;
					var title = mmarker.title;	
					
					var bargain = title.contains('Bargain');
					var address = mmarker.address;
					var telephone = mmarker.telephone;
					var description = mmarker.description;
					var distance = (parseFloat(mmarker.distance)) ? parseFloat(mmarker.distance) : 0;
					var point = new GLatLng(parseFloat(mmarker.lat), parseFloat(mmarker.lng));
					if(typeof distance == 'undefined' || !distance || distance == 0) {
						distance = 0.0;
					}
					var storeIcon = icon;
					
					if(bargain == false) {
						storeIcon = tgicon;
					}
					
					if(title == 'Your Location'){
						var marker = createMarker(point, title, address, storeIcon);
						map.addOverlay(marker);
						bounds.extend(point);
						var sidebarEntry = createSidebarEntry(marker, title, address, description, distance);
						sidebar.appendChild(sidebarEntry);
					}else{
						if(bargain != thoroughgoods) {
							count++;
							var marker = createMarker(point, title, address, storeIcon);
							map.addOverlay(marker);
							bounds.extend(point);
							var sidebarEntry = createSidebarEntry(marker, title, address, description, distance);
							sidebar.appendChild(sidebarEntry);
						}
					}
	
				}
				map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
			}
			if(count == 0){
				sidebar.set('html', 'Sorry, no stores were found.');
				if(defaultlat && defaultlng && defaultzoom){
					map.setCenter(new GLatLng(defaultlat, defaultlng), defaultzoom);
				}
			}
			
		}
	});
}

// GOOGLE POPUP INFORMATION
function createMarker(new_point, title, address, storeIcon) {
	if(title == 'Your Location'){
		var marker = new GMarker(new_point);
		var html = '<h5>' + title + '</h5>';
	}else{
		var marker = new GMarker(new_point, storeIcon);
		var html = '<h5>' + title + '</h5><p>' + address + '</p>';
	}
	
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

// SELECT STORES
function selectStore(marker, div) {
	if(selectedStore){ selectedStore.setAttribute('id', ''); }
	selectedStore = div;
	div.setAttribute('id', 'selectedStore');
	var fav = div.getAttribute('rel');
	if(fav != 'Your Location'){
		document.getElementById('my_store').setAttribute('value', fav);
	}
}

// HTML INFORMATION
function createSidebarEntry(marker, title, address, description, distance) {

	var div = document.createElement('div');
	div.setAttribute('class', 'store');
	div.setAttribute('className', 'store');
	div.setAttribute('rel', title);
	
	var html = '';
	
	var coor = marker.getLatLng();
	var lat = coor.y;
	var lng = coor.x;
	
	if(vip){	
		if(title != 'Your Location') {
			html += '<div class="dist"><strong>' + distance.toFixed(1) + '</strong> miles</div> <div class="storetitle">' + title + '</div>';
			//html += "<br/><a href=\"javascript:showDirections('"+lat+","+lng+"')\">Directions &raquo;</a>";
		} else {
			html += '<div class="dist"><strong>0</strong> miles</div> <div class="storetitle">' + title + '</div>';
		}
	}else{
		if(title != 'Your Location') {
			html += '<strong>' + title + '</strong> (' + distance.toFixed(1) + ' miles)<br/>' + description;
			html += "&nbsp;&#124;&nbsp;<a href=\"javascript:showDirections('"+lat+","+lng+"')\">Directions</a>";    
			html += "<br/>";
		} else {
			html += '<strong>' + title + '</strong>';
			html += "<br/>";
		}
	}
	
	div.innerHTML = html;
	if(vip){
		GEvent.addDomListener(marker, 'click', function() {
			selectStore(marker, div);
		});		
	}

	GEvent.addDomListener(div, 'click', function() {
		GEvent.trigger(marker, 'click');
	});
	
	GEvent.addDomListener(div, 'mouseover', function() {
		div.setAttribute('class', 'store hover');
		div.setAttribute('className', 'store hover');
	});
	
	GEvent.addDomListener(div, 'mouseout', function() {
		div.setAttribute('class', 'store');
		div.setAttribute('className', 'store');
	});
	
	return div;
}

// TO HTML
function toHtml(str) {
	str = str.replace(/&lt;/gi, '<');
	str = str.replace(/&gt;/gi, '>');
	str = str.replace(/&quot;/gi, '"');
	str = str.replace(/&#39;/gi, '\'');
	str = str.replace(/&amp;/gi, '&');    	
	return str;
}
