var default_map = '';
var counties	= null;
var fotoTO		= null;
var fadingOut	= false;
var fadingIn	= false;

$(document).ready( function() {
	var img_path	= $('#img_path').html();
	var map_path	= img_path + $('#map_path').html();
	var face_path	= img_path + $('#face_path').html();
	var preloads	= $('#preloads').html().split(',');
	counties		= treatJSON( $('#counties').html() );
	default_map	= $('#Sverige').attr( 'src' );

	$('#foto').hide();

	// Ladda in bilder...
	$.preload( preloads, {
		base: img_path,
    threshold: 26,
    enforceCache: true
	});

	$('.map_county, .link_county').hover( function() {
		var letter	= $(this).attr('letter');
		var county	= $(this).attr('id');

		$('.link_county').removeClass( 'hover' );

		if ( this.nodeName == 'A' ) {
			county	= makeMachineReadable( $(this).html() );
		    $(this).addClass( 'hover' );
		} else {
			$('#link_county_' + letter).addClass( 'hover' );
		}

		$('#Sverige').attr( 'src', map_path + county + '.png' );

		if ( counties['county_' + letter].contact ) {
			clearTimeout( fotoTO );
		    fotoTO	= null;
			    $('#foto').stop( true, false );
		    fadingOut = false;
		    $('#foto').css( 'opacity', 1 );

			var contact_image	= face_path + counties['county_' + letter].contact.image;

			$('#contact_name').html( counties['county_' + letter].contact.name );
		    $('#contact_img').attr( 'src', contact_image );

		    fadingIn = true;
			$('#foto').fadeIn( 'normal', function( ) { fadingIn = false; } );
		} else {
			if (!fadingOut) {
		        fadingOut = true;
		        $('#foto').fadeOut( 'fast', function() {
		            clearTimeout( fotoTO );
		            fotoTO	= null;
		            if (fadingOut) {
		                fadingOut = false;
		                $('#foto').hide();
		            }
		          } );
				} else {
					clearTimeout( fotoTO );
		        fotoTO = null;
		    }
		}
	}, function() {
		var letter	= $(this).attr('letter');
		$('#link_county_' + letter).removeClass( 'hover' );

		$('#Sverige').attr( 'src', default_map );

		if (!fadingOut) {
				$('#foto').stop( true, false );
			fotoTO = setTimeout( function() {
		                            fadingOut = true;
		    						$('#foto').fadeOut( 'normal', function() {
		                                clearTimeout( fotoTO );
		    							fotoTO	= null;
		                                if (fadingOut) {
		                                	fadingOut = false;
												$('#foto').stop( true, true );
		        							$('#foto').hide();
		                                }
		                                if (fadingIn) {
											$('#foto').fadeIn( 'normal', function( ) { fadingIn = false; } );
		                                }
									} ); }, 500 );
		} else {
			clearTimeout( fotoTO );
		    fotoTO		= null;
		}
	} );
} );
