var lat;
var lng;
var delayed;

function initialize() {
	$('#map_canvas').fadeOut(300, function() {
		latLng = new google.maps.LatLng(lat, lng);
		options = {
			zoom: 12,
			center: latLng,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		};
		map = new google.maps.Map(document.getElementById('map_canvas'), options);
		marker = new google.maps.Marker({
			position: latLng,
			map: map
		});
		$(this).fadeIn(300);
	});
}

var interval;
var open_fly_out;

$(document).ready(function(){
	$('#form_map').submit(function() {
		var post_code = $('#post_code').val();
		if (post_code != '') {
			$.getJSON('/offices/gg/' + post_code, function(data) {
				lat = data.results[0].geometry.location.lat;
				lng = data.results[0].geometry.location.lng;
				initialize();
				$.getScript('http://maps.google.com/maps/api/js?sensor=false&callback=initialize');
			});
		}
		return false;
	});
	$('#nav').navFlyOut();
	$('.validate').validate();
	$('.accordion').accordion({
		autoHeight:false,
		change: function(event, ui) {
			if ($('#map_canvas').length) {
				title = $(ui.newHeader).children('a').attr('title');
				marker = findMarkerByTitle(title);
				createInfoWindowForMarker(marker, true);
			}
		},
		create: function(event, ui) {
			if ($('#map_canvas').length) {
				openInfoWindowOnDelay();
			}
		}
	});
	$('#banners').fader(5000);
	$('.text_size').click(function() {
		
		jQuery.ajax({
			dataType: 'html', 
			url: '/css/text_size/' + $(this).attr('id'),
			success: function(data, textStatus, jqXHR) {
			$('#font_rule').html(data);
		}});
		return false;
	});
});

$.fn.navFlyOut = function(){
	return this.each(function(){
		var nav = $(this), timeout;
		var fadeInFunction = function(li) {
			$(li).children('.fly_out_nav').fadeIn('fast')
				.parent().addClass('on')
				.siblings().removeClass('on')
				.children('.fly_out_nav').fadeOut('fast');
		};
		var fadeOutFunction = function(li) {
			var link = $(li).children('a');
			timeout = setTimeout(function() {
				link.parent().removeClass('on');
				link.next('.fly_out_nav').fadeOut('fast');
			},100);
		};
		nav.children('li')
			.bind('mouseenter', function(){fadeInFunction(this);})
			.bind('mouseleave', function(){fadeOutFunction(this);});
		nav.children('li').children('a')
			.bind('focus', function(){fadeInFunction($(this).parent());});
	});
}
