// default mapping global variables
var map, pos, marker;

var preloadedDestination;

// XXX remove this after the AJAX calls are programmed
user = company = index = total = 'test';

document.observe("dom:loaded", function(){

	// make content_sub the height of content_main if needed
	if (document.getElementById('content_sub')) {
		var subHeight = $('content_sub').getHeight();
		var mainHeight = $('content').getHeight();
		if (subHeight < mainHeight) {
			$('content_sub').setStyle({height:(mainHeight - parseInt($('content_sub').getStyle('paddingBottom')))+'px'});
		}
	}

	// mapping functions for the find-a-solicitor page
	if (document.getElementById("map") && GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		pos = new GLatLng(51.240426,-0.565796); // default to west Surrey
		marker = new GMarker(pos);

		map.setCenter(pos, 10);
		map.addOverlay(marker);
		map.addControl(new GLargeMapControl());
		map.enableScrollWheelZoom();
		
		if (preloadedDestination) {
		  highlightDestination(preloadedDestination);
		}

		if (document.getElementById('destination')) {
			destinations = $$('#destination a');
			loadDestinationDetails.call(destinations[0]);
			destinations.each(function(t){ t.observe('click', loadDestinationDetails) });
		}
	}
	// booking form functions
	/*if (document.getElementById('book')) {
		
		// hide empty table initially
		if($$('#attendees tr').length == 1) $('attendees').hide();
		
		// add attendees panel
		var addPanel = '<p id="addLinks" class="more"><a href="#">Add myself</a> <a href="#">Add another attendee</a></p>';
		$$('#book fieldset')[0].hide().insert({before:addPanel});
		var addLinks = $$('#addLinks a');
		addLinks[0].observe('click', addMyself);
		addLinks[1].observe('click', toggleBookingPanel);
		
		// remove users
		$$('#attendees input').each(function(t){t.observe('click', removeUser)});

		// add users
		$$('#book input.submit')[0].observe('click', addUser);
	}*/
	
	// only show helper labels when focusing a form element
	if($$('label>span')) {
		var spans = $$('label>span');
		spans.each(function(t){
			t.hide().up(0).next().observe('focus',showExplanation).observe('blur',hideExplanation);
		});
	}

});

function loadCoursePage(course_id, user_id){
	updateAttendees(course_id, user_id); 	
	if($('myself')){ 
		$('myself').onclick = function () {
			addAttendee(user_id, user_id, course_id, '','','');	
			$('myself').style.display='none';
			$('bookedMyself').style.display='inline';
		}
	}
	if($('add_another')){
		$('add_another').onclick = function () {
			$('addAttendee').style.display='block';
		}
	}
	$('addAttendee').style.display='none';
	if($('button_go_back')){
		$('button_go_back').onclick = function () {
			$('addAttendees').style.display = 'block';
			$('confirmAttendees').style.display = 'none';
		}
	}
}   

function loadFindPage(firm_id, lat, lng){
  if(firm_id) {
    getInfo(firm_id);
    var point = new GLatLng(lat, lng);
    preloadedDestination = point; // To be loaded later
  }
	if($('getDistances')){
		$('getDistances').onsubmit = function () {
			if($('postcode_first').value=='')
			usePointFromPostcode($('company_name').value, $('company_name').value, $('area').value);
			else
			usePointFromPostcode($('postcode_first').value, $('company_name').value, $('area').value);
			return false;
		}
	}

	
}

function usePointFromPostcode(postcode, company, area) {
	if(postcode==' '){
		alert("Please enter a postcode!");
	} else {
	var localSearch = new GlocalSearch();
	localSearch.setSearchCompleteCallback(null, 
		function() {
			if (localSearch.results[0])
			{
				var point =  new GLatLng(localSearch.results[0].lat,localSearch.results[0].lng);
				if (postcode != "" && postcode != company)
				window.location.href='map.php?ll='+point+'&pc='+postcode+"&area="+area;
				else
				window.location.href='map.php?company_name='+company+"&ps="+point+"&pc="+company+"&area="+area;
			} else {
				window.location.href='map.php?company_name='+company+"&ps="+point+"&pc="+company+"&area="+area;
			}
		});	
	 localSearch.execute(postcode + ", UK");
	}
}

function loadDestinationDetails(e) {
	if(e) { Event.stop(e) }
	var latLng = $(this).readAttribute('rel').split(',');
	pos = new GLatLng(latLng[0],latLng[1]);
	highlightDestination(pos);
	new Effect.Highlight(this.parentNode.parentNode, {startcolor: '#ffff99', restorecolor: 'true'});
}

function highlightDestination(pos) {
  if(pos.lat() == 0 && pos.lng() == 0) {
    $('map').style.display = 'none';
    $('map_unavailable').style.display = 'block';
  } else {
    $('map_unavailable').style.display = 'none';
    $('map').style.display = 'block';
  }
	marker.setLatLng(pos);
	marker.showMapBlowup();
	map.setZoom(13);
	map.panTo(pos);
}
                      
function addAttendee(member_id, created_by, course_id, name, company, email, is_member) {
	var url = '/cpd/action/addAttendee.php';
	var params = 'member_id=' + member_id + '&course_id=' + course_id + '&created_by=' + created_by + '&name=' + name + '&company=' + company + '&email=' + email + '&is_member=' + is_member;
	var ajax = new Ajax.Request(url, {
		method: 'get',
		parameters: params,
		onSuccess: function(transport) {
			updateAttendees(course_id, created_by)
		}
	});
	$('name').value='';
	$('company').value='';
	$('email').value='';
	$('is_member').checked=false;
}

function removeAttendee(id, course_id, created_by) {
	var url = '/cpd/action/removeAttendee.php';
	var params = 'id=' + id;
	var ajax = new Ajax.Request(url, {
		method: 'get',
		parameters: params,
		onSuccess: function(transport) {
			updateAttendees(course_id, created_by)
		}
	});
}

function removeMe(id, course_id, created_by) {
	var url = '/cpd/action/removeAttendee.php';
	var params = 'id=' + id;
	var ajax = new Ajax.Request(url, {
		method: 'get',
		parameters: params,
		onSuccess: function(transport) {
			updateAttendees(course_id, created_by)
		}
	});
	$('myself').style.display='block';
	$('bookedMyself').style.display='none';
}

function totalCost(course_id, created_by) {
	var url = '/cpd/action/totalCost.php';
	var params = '&course_id=' + course_id + '&created_by=' + created_by;
	var ajax = new Ajax.Updater({success: 'total_cost'},url,{method: 'get', parameters: params});
}

function updateAttendees(course_id, created_by) {
	var url = '/cpd/action/updateAttendees.php';
	var params = '&course_id=' + course_id + '&created_by=' + created_by;
	var ajax = new Ajax.Updater({success: 'attendeeList'},url,{method: 'get', parameters: params});
	totalCost(course_id, created_by);
}

function confirmAttendees(course_id, created_by) {
	var url = '/cpd/action/confirmAttendees.php';
	var params = '&course_id=' + course_id + '&created_by=' + created_by;
	var ajax = new Ajax.Updater({success: 'confirmAttendeeList'},url,{method: 'get', parameters: params});
	confirmTotalCost(course_id, created_by);
}
function confirmTotalCost(course_id, created_by) {
	var url = '/cpd/action/totalCost.php';
	var params = '&course_id=' + course_id + '&created_by=' + created_by;
	var ajax = new Ajax.Updater({success: 'confirm_total_cost'},url,{method: 'get', parameters: params});
}
function getInfo(id){
	var url = '/find/action/getInfo.php';
	var params = 'id=' + id;
	var ajax = new Ajax.Updater({success: 'details'},url,{method: 'get', parameters: params});
}

function showExplanation() {
	$(this).previous().down().show();
}

function hideExplanation() {
	$(this).previous().down().hide();
}