/* maps.js
 * 
 * Contains all of the client-side functionality necessary to resolve address
 * post codes to geographical co-ordinates, and create Google Map applets to
 * display this information.
 *
 * The get_map function should be called onblur on the building and postcode
 * fields, and body onload.
 * 
 * The page must have a div element named <mapName>_map (optional to display
 * the Google Map), <mapName>_address (optional to display the resolved
 * address), and hidden form input elements named <mapName>_address_lat and
 * <mapName>_address_lng.
 */


/* Creates and applies the Google Map applet, centred of given co-ordinates,.
 * to the page.
 *
 * The function is called by the request_map function which retrieves the
 * co-ordinates, based on the user input post coode and building.
 * 
 * The following arguments are required:
 * 
 * lat - The latitude co-ordinate (WGS84 format)
 * lng - The longitude co-ordinate (WGS84 format)
 * mapName - The map to update. The page must have a div element named
 * <mapName>_map, and hidden form input elements named <mapName>_address_lat
 * and <mapName>_address_lng.
 */
function initialize(lat, lng, mapName) {

	// Check the browser is compatible with Google Maps.
	if (GBrowserIsCompatible()) {

		// Create the map and location objects.
		map    = new GMap2($(mapName + '_map'))
		center = new GLatLng(lat, lng)

		// Add the map controls.
		map.addControl(new GSmallMapControl())

		// Set the map centre point and zoom level.
		map.setCenter(center, zoom)

		// Add the marker for the venue's location.
		var home = new GMarker(center, {icon: homeIcon, draggable: true})

		/* Listener updates the latitude and longitude form fields if the
		 * marker is dragged.
		 */
		GEvent.addListener(home, "dragend", function() {
		  $(mapName + '_address_lat').value = home.getLatLng().lat()
		  $(mapName + '_address_lng').value = home.getLatLng().lng()
		});

		// Add the marker overlay to the map.
		map.addOverlay(home)

		// Change the map type to terrain type.
		map.setMapType(G_PHYSICAL_MAP)
	}
}


/* Checks whether the venue and/or management address fields are populated,
 * and if so calls the request_map function to get the full address and map.
 *
 * The function is called onblur for the building and post code fields, and
 * body onload.
 *
 * The following arguments are optional
 *
 * id - The page element ID which is calling the function. This determines
 * which address to retrieve and prevents it requesting both addresses each
 * time. If the value is null (body onload), both addresses are requested.
 */
function get_address(type) {

	// Check if the venue address has been changed.
	if ((type == null) || (type == 'venue')) {

		if ($('address_post_code').value != '') {

			request_addresses('address_post_code')

		} else {

			$('venue_map').style.display        = 'none';
			$('venue_address_lat').value        = '';
			$('venue_address_lng').value        = '';
			$('venue_address_confirm_id').value = '';
		}
	}

	// Check if the management address has been changed.
	if ((type == null) || (type == 'management')) {

		if ($('management_address_post_code').value != '') {

			request_addresses('management_address_post_code')

		} else {
			$('management_address_confirm_id').value = '';
		}
	}
}

function request_address(type) {

	id = $(type + '_address_id').value

	var opt = {

		// Use GET
		method: 'get',

		onLoading: function() {
			$(type + '_address_select').innerHTML = '<span style="margin: 10px 0 10px 140px;"><img src="../images/ajax-loader.gif" /> Searching for address...</span>'
		},
		// Handle successful response
		onSuccess: function(t) {

			var location = t.responseText.split(',')

		  	if (location[0] == 'error') {

				$(type + '_address_select').innerHTML = '<span class="errorBlock">Unable to retrieve address details. Please try again. If you are still having problems please call Customer Services on 020 7183 0110.</span>'

		  	} else {

		  		if (type == 'venue') {

		   			$(type + '_map').style.display  = 'block';
					  $(type + '_map_tips').innerHTML = '<strong>Tips</strong><p>Drag and drop the marker on the map to refine the positioning of your venue.</p>';
					  
					  new Effect.Highlight($('venue_map_tips'), { startcolor: '#ddffdd', endcolor: '#ffff99', restorecolor: '#ffff99' });
					  window.setTimeout(function() { new Effect.Highlight($('venue_map_tips'), { startcolor: '#ffff99', endcolor: '#ddffdd', restorecolor: '#ddffdd' }); }, 2500);
					  
					  $(type + '_address_lat').value = location[0];
			    	$(type + '_address_lng').value = location[1];

					  $('address_post_code').style.display = 'none';

					  initialize(location[0], location[1], type);
		    	} else {
					$(type + '_address_post_code').style.display = 'none';
				}

				$(type + '_address_post_code_entry').style.display = 'none';
				$(type + '_address_select').style.display          = 'none';
				$(type + '_address_confirm').style.display         = 'block';

				address = location[2] + '<br />'

				if (location[3].length > 0) { address += location[3] + '<br />' }
				if (location[4].length > 0) { address += location[4] + '<br />' }
				if (location[5].length > 0) { address += location[5] + '<br />' }
				if (location[6].length > 0) { address += location[6] + '<br />' }
				if (location[7].length > 0) { address += location[7] + '<br />' }
				if (location[8].length > 0) { address += location[8] + '<br />' }
				if (location[9].length > 0) { address += location[9] + '<br />' }

				address += '<a href="#' + type + '_post_code" onclick="change_address(\'' + type + '\')"><img src="/images/buttons/change_address.gif" width="113" height="20" alt="Change Address" /></a>'
        
        // added for previewPane
        if (type == 'venue') {
          var input = document.createElement('input');
          input.value = address;
          input.id = 'venue_address';

          updatePreview(input); // this function checks if the previewPane is set
          updatePreview('map');
        }
        // ---

				$(type + '_address_confirm').innerHTML = address

		    	$(type + '_address_confirm_id').value = location[10]
		  	}
		},
		// Handle 404
		on404: function(t) {
			//alert('Error 404: location "' + t.statusText + '" was not found.');
		},
		// Handle other errors
		onFailure: function(t) {
			//alert('Error ' + t.status + ' -- ' + t.statusText);
		}
	}

	new Ajax.Request('/venues/get_address?id=' + escape(id) + '&authenticity_token=' + escape(getValueByName('authenticity_token')), opt);
}


function change_address(type) {

	if (type == 'venue') {
		$('address_post_code').value = ''
		$('address_post_code').style.display = 'inline'
		$(type + '_map').style.display = 'none'
		$(type + '_address_lat').value = ''
		$(type + '_address_lng').value = ''
		$('address_post_code_validation_icon').innerHTML = ''
	} else {
		$(type + '_address_post_code').value = ''
		$(type + '_address_post_code').style.display = 'inline'
		$(type + '_address_post_code_validation_icon').innerHTML = ''
	}

	$(type + '_address_post_code_entry').style.display = 'block'
	$(type + '_address_select').style.display = 'none'
	$(type + '_address_confirm').style.display = 'none'
	$(type + '_address_confirm').innerHTML = ''
	$(type + '_address_confirm_id').value = ''
}

function request_addresses(id) {

	type = (id == 'address_post_code') ? 'venue' : 'management'
	postcode  = (id == 'address_post_code') ? $('address_post_code').value : $('management_address_post_code').value

	if (postcode.match(/^[A-PR-UWYZ][A-HK-Y0-9][A-HJKSTUW0-9]?[ABEHMNPRVWXY0-9]?\s*[0-9][ABD-HJLN-UW-Z]{2}$/i)) {

 		new Ajax.Request('/venues/get_addresses?type=' + escape(type) + '&post_code=' + escape(postcode) + '&authenticity_token=' + escape(getValueByName('authenticity_token')), {

			// Use GET
			method: 'get',

			onLoading: function() {

				$(type + '_address_select').style.display = 'inline';
				$(type + '_address_select').innerHTML = '<span style="margin: 10px 0 10px 140px;"><img src="../images/ajax-loader.gif" /> Searching for addresses...</span>'
			},
			// Handle successful response
			onSuccess: function(t) {

				var response = t.responseText;

				if (response == 'error') {
					$(type + '_address_select').innerHTML = '<span class="errorBlock">Post code not found. Please check and try again. If you are still having problems please call Customer Services on 020 7183 0110.</span>'
				} else {

					result = response.split(',')

					$(result[0] + '_address_select').style.display = 'inline'
					$(result[0] + '_address_select').innerHTML = result[2];

					if (result[1] == '1') {
						request_address(result[0])
					}
				}
			},
			// Handle 404
			on404: function(t) {
				//alert('Error 404: location "' + t.statusText + '" was not found.');
			},
			// Handle other errors
			onFailure: function(t) {
				//alert('Error ' + t.status + ' -- ' + t.statusText);
			}
		});

	} else {

	}
}


function check_addresses()
{
	if (($('venue_address_confirm_id').value == '') || ($('venue_address_lat').value == '') || ($('venue_address_lng').value == '') || ($('management_address_confirm_id').value == '')) {

		if ((($('address_post_code').value != '') && ($('venue_address_select').style.display == 'none')) || (($('management_address_post_code').value != '') && ($('management_address_select').style.display == 'none'))) {
		} else {
			alert('Please confirm the venue address and management contact address before continuing.')
		}

		return false
	} else {
		return true
	}
}