var map = null;  
if( internal )
	var key = 'ABQIAAAAbX2UTiyMZJLgAmUFW32hMBSHlWb-REJiVlYA0DBbI2lk7gMSTRQqLPQ3sn44gDXeFaW1nptzxXVI7A';
else
	var key = 'ABQIAAAAQpm8MKqHY_YsEZOfmqnKBRRsKUYpPcuSqLJZX8u4u-wDltXcyxSh_pcR_v1ARn8s-QExBxvoZlf6JA';
var bounds = null;
var currentMarker = null;
var mapDiv = null;
var containerDiv = null;
var clickedX = 0;
var clickedY = 0;
var isLoaded = false;
	

/**
 * Called after script is asynchronously loaded in.
 * Creates the GMap2, GMarker objects and performs actions according to 
 * what the user did to trigger the map load (search, zoom, click etc).
 */
function loadMap() {
  if (GBrowserIsCompatible()) {
  	mapDiv = document.getElementById('map');
    mapDiv.style.background = '#fff';
    mapDiv.style.cursor = '';
    map = new GMap2(mapDiv, {logoPassive: true});
    
    bounds = new GLatLngBounds();
    for (var i = 0; i < businesses.length; i++) {
      bounds.extend(new GLatLng(businesses[i].lat, businesses[i].lng));
    }

	// Set up the copyright information
	// Each image used should indicate its copyright permissions
	var myCopyright = new GCopyrightCollection("© ");
	myCopyright.addCopyright(new GCopyright('Holiday Extras',
	  new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)),
	  0,'©2009 Holiday Extras'));
	
	// Create the tile layer overlay and 
	// implement the three abstract methods                 
	/*var tilelayer = new GTileLayer(myCopyright);
	tilelayer.getTileUrl = function() { return "/images/gmaps/tint.png"; };
	tilelayer.isPng = function() { return true;};
	tilelayer.getOpacity = function() { return 0.3; }
	
	var myTileLayer = new GTileLayerOverlay(tilelayer);*/

    var latSpan = bounds.toSpan().lat();
    map.setCenter(bounds.getCenter(), 12);
    if( height > 200 )
		map.addControl( new GLargeMapControl3D());
    else
		map.addControl( new GSmallZoomControl3D());
	map.addControl( new GMapTypeControl());
	//map.addOverlay(myTileLayer);

    var newBounds = map.getBounds();
    var newLatSpan = newBounds.toSpan().lat();
    if (latSpan/newLatSpan > .90) { map.zoomOut(); }

    for (var i = 0; i < businesses.length; i++) {
      var marker = createMarker(i);
      var latlng = marker.getLatLng();
      var pixel = map.fromLatLngToDivPixel(latlng);
      if (Math.abs(pixel.x - clickedX) < 12 && Math.abs(pixel.y - clickedY) < 20) {
      }
      map.addOverlay(marker);
    }
    isLoaded = true;
  }
}

/**
 * Zooms to the viewport that fits all the markers.
 */
function zoomToAll() {
  map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

/**
 * Creates a marker for the given business.
 * @param {Number} ind
 * @return {GMarker}
 */
function createMarker(ind) {
  var business = businesses[ind];
  if( typeof(business.code) != 'undefined' && business.code.length == 5) {
	var icon = new GIcon();
	icon.image = 'http://www.holidayextras.co.uk/images/googlemaps/icons/airport.png';
	var w = 21;
	var h = 34;
	icon.iconSize = new GSize( w, h );
	icon.iconAnchor = new GPoint( 2, 32 );
	icon.infoWindowAnchor = new GPoint( parseInt( w / 2 ), parseInt( h / 2 ));
	var marker = new GMarker(new GLatLng(business.lat, business.lng), icon);
  } else
  	var marker = new GMarker(new GLatLng(business.lat, business.lng));
  GEvent.addListener(marker, 'click', function() {
  	address = business.address;
  	while (address.indexOf(',') != -1 )
  		address = address.replace(',','<br />');
  	/*address += '<br /><hr /><br /><form action="#" method="post" onsubmit="hxGetDirections( \''+business.code+'\', \''+business.code+'-lat\', \'route\', true, \''+business.code+'-name\' ); $(\'#'+business.code+'-button\').click(); return false;"><input type="hidden" id="'+business.code+'-lat" value="'+business.lat+','+business.lng+'" /><input type="hidden" id="'+business.code+'-name" value="'+business.name+'" /><input type="text" id="'+business.code+'" name="addr" value="" /> <input class="thickbox" alt="#TB_inline?height=400&width=450&inlineId=routable" type="button" value="Get Directions" id="'+business.code+'-button" style="display:inline;" title="" onclick="hxGetDirections( \''+business.code+'\', \''+business.code+'-lat\', \'route\', true, \''+business.code+'-name\' );" /></form>';*/
    marker.html = ['<h2 style="margin-bottom:2px">', business.name, '</h2>', 
                 address].join('');
    currentMarker = marker;
    marker.openInfoWindowHtml(marker.html);
  });
  return marker;
}

/**
 * Formats business info into a URL-friendly version for maps url.
 * @param {Object} business
 * @return {String}
 */
function formatAddressForMaps(business) {
  var address = business.address;
  return escape(address.replace(' ', '+'));
}

/**
 * Convenience function for creating an element and assigning an id to it.
 * @param {String} elementType
 * @param {String} id
 * @return {Element} 
 */
function _cel(elementType, id) {
  var element = document.createElement(elementType);
  element.id = id;
  return element;
}

/**
 * Loads in the Maps API script. This is called after some sort of user interaction.
 * The script loads asynchronously and calls loadMap once it's in.
 */
function loadScript() {
  if (!isLoaded) {
	$.getScript('http://www.holidayextras.co.uk/javascript/thickbox2008.js', function(){
		tb_init('a.thickbox, area.thickbox, input.thickbox');
		imgLoader = new Image();
		imgLoader.src = tb_pathToImage;
	});
	mapDiv = document.getElementById('map');
    var div = document.createElement('div');
    div.className = 'message';
    mapDiv.appendChild(div);
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://maps.google.com/maps?file=api&width='+width+'&height='+height+'&v=2.x' + 
                 '&async=2&callback=loadMap&key='+key;
    document.body.appendChild(script);
    var lscript = document.createElement('script');
    lscript.type = 'text/javascript';
    lscript.src = 'http://www.google.com/uds/api?file=uds.js&async=2&v=1.0&key='+key;
    document.body.appendChild(lscript);
  }
}

/**
 * Get directions function
 */
var oGdirections = false;
var oGlocalSearch = false;
function hxGetDirections( address, target, dirArea, bDirectionsTo, nameEl ) {
	if( !isLoaded || $('#TB_ajaxContent').length < 1 ) {
		if( isLoaded ) {
			if( $('#getDirections').length > 0 ) {
				var t = $('#getDirections')[0].title || $('#getDirections')[0].name || '';
				var a = $('#getDirections')[0].href || $('#getDirections')[0].alt;
				var g = $('#getDirections')[0].rel || '';
			} else {
				if( typeof(nameEl) == 'undefined' ) {
					if( typeof(businesses[1]['name']) != 'undefined' )
						names = 'Destination';
					else
						names = businesses[0]['name'];
				} else
					names = document.getElementById(nameEl).value;
				var t = names;
				var a = '#TB_inline?height=400&width=450&inlineId=routable';
				var g = '';
			}
	  		tb_show(t,a,g);
		} else
			loadScript(); 
		setTimeout("hxGetDirections( '"+address+"', '"+target+"', '"+dirArea+"', "+bDirectionsTo+", '"+nameEl+"' )",3000);
	} else {
		var route = document.createElement('div');
		route.id = 'route';
		document.getElementById('gmap').appendChild(route);
		address = document.getElementById(address).value;
		if( typeof(nameEl) == 'undefined' || nameEl == "undefined" ) {
			if( businesses.length > 1 )
				nameEl = 'Destination';
			else
				nameEl = businesses[0]['name'];
		} else
			nameEL = document.getElementById(nameEl).value;
		target = document.getElementById(target).value;
		dirArea = document.getElementById('route');
		$('#getDirections').attr('title', 'Directions from: '+address+' to: '+nameEl );
		var bDirectionsTo = ( bDirectionsTo == null ) ? true : bDirectionsTo;
	  if ( !oGdirections ) {
		oGdirections = new GDirections( map, dirArea );
	  } else {
		loadMap();
		oGdirections = new GDirections( map, dirArea );
	  }
	  oGdirections.clear();
	  $(dirArea).html( "" );
	  if ( !oGlocalSearch ) {
		oGlocalSearch = new GlocalSearch();
	  }
	  oGlocalSearch.setSearchCompleteCallback( null, function() {
		if ( oGlocalSearch.results.length > 0 ) {
			var source = oGlocalSearch.results[0].lat + ',' + oGlocalSearch.results[0].lng;
		} else {
			alert( "We couldn't understand this location. Try adding a city, county, or postal code." );
		}
		if ( bDirectionsTo ) {
			var routeString = 'from: ' + source + ' to: ' + target;
		} else {
			var routeString = 'from: ' + target + ' to: ' + source;
		}
		oGdirections.load( routeString, {getPolyline: true}, {getSteps: true} );
		$('#route').appendTo( $('#TB_ajaxContent') );
	  } );
	  oGlocalSearch.execute( address + ', UK' );
  }
}

/**
 * Sets up the gadget by setting CSS and click events.
 */
function loadMapGadget() {
  containerDiv = document.getElementById('container');
  mapDiv = document.getElementById('map');
  mapDiv.style.cursor = 'pointer';

  var urlString = ['http://maps.google.com/staticmap?markers='];
  var markerString = [];
  for (var i = 0; i < businesses.length; i++) {
    markerString.push(businesses[i].lat + ',' + businesses[i].lng + ',red');
  }
  urlString.push(markerString.join('|'));
  urlString.push('&size='+width+'x'+height+'');
  urlString.push('&zoom=12');
  urlString.push('&key='+key);
  mapDiv.innerHTML = '<img onclick="loadScript(); $(this).remove();" src="'+urlString.join('')+'" />';
}
$(function(){
	loadMapGadget();
});

