var totalWords = 1500;

 // google map directions
    var map;
    var gdir;
    var geocoder = null;
    var addressMarker;

    function initializeGMap(from,address) {
      if (GBrowserIsCompatible()) {      
        map = new GMap2(document.getElementById("map_canvas"));
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        setDirections(from, address);
      }
    }
    
    function setDirections(fromAddress, toAddress) {
      gdir.load("from: " + fromAddress + " to: " + toAddress,
                { "locale": "en_GB" });
    }

    function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
	   		directionsError();
	   		$('#directions-wrapper').remove();
	   } else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
	     	directionsError();
	     	$('#directions-wrapper').remove();
	   } else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
	   		directionsError();
	   		$('#directions-wrapper').remove();
	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   } else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
	     	directionsError();
	     	$('#directions-wrapper').remove();
	   } else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
	     	directionsError();
	     	$('#directions-wrapper').remove();
	   } else {
	   	   directionsError();
	   	   $('#directions-wrapper').remove();
	   	   
	  }
	   
	}
	
	function directionsError() {
		$('#fromAddress').val('Enter Post Code').css({color:'#BF0D1D'});
		setTimeout(function() {$('#fromAddress').css({color:'#aaaaaa'});},3000)
	}
	
	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	  

			$('#directions-wrapper').css({visibility:'visible',position:'relative','margin-top':'-100px'});
			doOverlay("body");
			$('#directions-wrapper').fadeIn(500,function() {
				$("#close-overlay").unbind('click');
				
				$("#vtoverlay, #close-overlay").click(function() {
					$("#directions-wrapper").fadeOut(500,function(){
						$('#vtoverlay').remove();
						$(this).remove();
						$(window).unbind('resize.overlay')
					});
					return false;
				});
			}).center();

	  
	}
   
    // end of google map directions
    
    
    
    
    
    function loadGoogleMap(address) {
      if (GBrowserIsCompatible()) {
        //var map = new GMap2(document.getElementById("map"));

        //map.setCenter(new GLatLng(37.4419, -122.1419), 13);
        showAddress(address);
      }
    }

    function showAddress(address) {
     var geocoder = new GClientGeocoder();
      geocoder.getLatLng(
        address,
        function(point) {
          var map = new GMap2(document.getElementById("map"));
          if (!point) {
            //alert(address + " not found");
          } else {
            map.setCenter(point, 13);
            var marker = new GMarker(point);
            map.addOverlay(marker);
            marker.openInfoWindowHtml(address);
          }
        }
      );
    }



	function doOverlay(element) {
	 $(window).unbind('resize.overlay');
	 $(element).prepend('<div style="height:'+$(document).height()+'px;width:100%;position:absolute;z-index:10;" id="vtoverlay"></div>');
	 if($('#vtoverlay').length > 0) {
	 	$(window).bind('resize.overlay',function() {
	 	$('#vtoverlay').remove();
			doOverlay(element);
	 	});
	 }
	}
	


$(document).ready(function(){

	$('#directions-container button[type="submit"]').click(function() {
		$(this).parents('#directions-container').removeClass('error');
		var html = '<div id="directions-wrapper" style="visibility:hidden;position:absolute"><a id="close-overlay" href="#">Close X</a><a id="print-directions" href="#">Print Directions</a><div id="map_canvas" style="float:left; width: 400px; height: 600px; margin: 16px 0px 0px 0px;"></div><div id="directions" style="float:right; width: 290px"></div></div>';
		$('body').prepend(html)
		
		var toAddress = "WR1 2PL";
		var fromAddress = $('#fromAddress').val();
		initializeGMap(fromAddress,toAddress);

		$("#print-directions").click(function(ev){
			window.open('/print.html');
			ev.preventDefault();
			return false;
		})
		
		return false;
	});
	
	

	$(".sitemap-content-noscript").removeClass("sitemap-content-noscript").addClass("sitemap-content");

	$("a.sitemap").click(function(){
		if( $(this).hasClass("open")){
			$(this).removeClass("open");
			$(".sitemap-content").fadeOut();
			$(".buttonswitch").toggle();
		} else {
			$(this).addClass("open");
			$(".sitemap-content").fadeIn();
			$(".buttonswitch").toggle();
		}
	});
	$('<span></span>').appendTo('.sub-navigation a');
	
	$("#ctmessage").each(function() { processWords(); });
	$("#ctmessage").keypress(function() { processWords(); });
	$("#ctmessage").blur(function() { processWords(); });
	
	
	$('a').click(function(){
		if( $(this).attr("rel") == "external" ) {
        	window.open(this.href);
        	return false;
        }
    });
		
	// This removes the default input value and replaces it if eu doesnt enter anything
	
	$('input[type="text"]').focus(function() {
    		    if (this.value == this.defaultValue){ 
    		    	this.value = '';
				}
				if(this.value != this.defaultValue){
	    			this.select();
	    		}
    		});
    		$('input[type="text"]').blur(function() {
    			
    		    if ($.trim(this.value) == ''){
			    	this.value = (this.defaultValue ? this.defaultValue : '');
				}
    		});
	
	
});

function processWords() {
	if ($("#ctmessage").val().length > totalWords) $("#ctmessage").val( 
$("#ctmessage").val().substring(0,totalWords) 
);
	$("#wordCount").html(totalWords - $("#ctmessage").val().length);
}

