

/**
 * GMap2.showBounds() method
 * @ author Esa 2008
 * @ param bounds_ GLatLngBounds()
 * @ param opt_options Optional options object {top, right, bottom, left, instant, save}
 */
GMap2.prototype.showBounds = function(bounds_, opt_options){
  var opts = opt_options||{};
  opts.top = opt_options.top*1||0;
  opts.left = opt_options.left*1||0;
  opts.bottom = opt_options.bottom*1||0;
  opts.right = opt_options.right*1||0;
  opts.save = opt_options.save||true;
  opts.disableSetCenter = opt_options.disableSetCenter||false;
  var ty = this.getCurrentMapType();
  var port = this.getSize();
  if(!opts.disableSetCenter){
    var virtualPort = new GSize(port.width - opts.left - opts.right, 
                            port.height - opts.top - opts.bottom);
    this.setZoom(ty.getBoundsZoomLevel(bounds_, virtualPort));
    var xOffs = (opts.left - opts.right)/2;
    var yOffs = (opts.top - opts.bottom)/2;
    var bPxCenter = this.fromLatLngToDivPixel(bounds_.getCenter());
    var newCenter = this.fromDivPixelToLatLng(new GPoint(bPxCenter.x-xOffs, bPxCenter.y-yOffs));
    this.setCenter(newCenter);
    if(opts.save)this.savePosition();
  }
  var portBounds = new GLatLngBounds();
  portBounds.extend(this.fromContainerPixelToLatLng(new GPoint(opts.left, port.height-opts.bottom)));
  portBounds.extend(this.fromContainerPixelToLatLng(new GPoint(port.width-opts.right, opts.top)));
  return portBounds;
}


var ShippingTerminals = {

	// Shortcut for logging in Firebug Console
	log: function() {
		if( !console||!window.console) return;

		console.log(arguments);
	},

	getGeocodes: function(callback) {

		new Ajax('/applications/shipping-terminals/api/geocodes.php?t='+$time(),{
			'method':'get',
			'onComplete': function(txt) {
				callback(txt);
			}
		}).request();

	},

	setGeocodes: function( objGeocodes ) {
		ShippingTerminals.Geocodes = objGeocodes;
	},

	handleGeocodes: function(json) {

		// Set Geocodes Cache here if not already set
		if( $type(ShippingTerminals.Geocodes) != 'object' )
			ShippingTerminals.setGeocodes(Json.evaluate(json));
	},

	setTabs: function(_tabs_selector, _panes_selector, options) {
		ShippingTerminals.tabs_selector = _tabs_selector;
		ShippingTerminals.panes_selector = _panes_selector;

		tabs = $$(_tabs_selector);
		panes = $$(_panes_selector);


		startIndex = ( options['start'] && $type(options['start'])=='number' )? options['start'] : 0;
		tabs[startIndex].addClass('active');
		panes[startIndex].setStyle('display','block');

		tabs.each( function(t, ti) {
			t._tabIndex = ti;

			if( ti != startIndex ) {
				panes[ti].setStyle('display','none');
				t.removeClass('active');
			}

			t.addEvent('click', function(e) {
				new Event(e).stop();
				this.blur();

				ShippingTerminals.toggleTab(this);
			});
		});
	},

	toggleTab: function( tabRef ) {

		switch( $type(tabRef) ) {
			case 'element': tab=$(tabRef); break;
			case 'number':
				tab = $$(ShippingTerminals.tabs_selector);
				tab = tab[tabRef];
			break;
			default: tab=$(tabRef); break;
		};

		if( tab.hasClass('active') ) return;

		activeTab = $$(ShippingTerminals.tabs_selector+'.active');
		activeTab = activeTab[0];
		panes = $$(ShippingTerminals.panes_selector);
		activePane = panes[activeTab._tabIndex];

		// Deactivate Tab + Pane
		activeTab.removeClass('active');
		activePane.setStyle('display', 'none');

		// Activate Tab + Pane
		tab.addClass('active');
		activePane = panes[tab._tabIndex];
		activePane.setStyle('display','block');

	},

	fixContainerHeight: function(fcontainer_element) {
		container_element = $(fcontainer_element);

		maxHeight = 0;
		container_element.getChildren().each( function(el) {
			_h = el.getStyle('height').toInt();
			if( maxHeight < _h )
				maxHeight = _h;
		});

		container_element.setStyle('min-height',
								   maxHeight);
	},

	statesAccordion: function() {
		$$('table#terminalstatelisting td b').each( function(el) {
			el.setStyles({'cursor': 'pointer'});
		});

		new Accordion( 'table#terminalstatelisting td b',
					   'table#terminalstatelisting td div',
					   {alwaysHide:true,
						show:-1} );

		$$('table#terminalstatelisting td div a').each( function(link) {
			city_state = link.getProperty('rel').replace(/target\[|\]/g,"").split(",");
			link.city = city_state[0];
			link.state = city_state[1];
			link.location = link.city + ", " + link.state;

			link.addEvent('click', function(e) {
				new Event(e).stop();

				ShippingTerminals.toggleTab(1);

				state = this.state;
				statePoints = [];

				// 1) Get all Links referencing the this's state
				// 2) create GLatLng Objects Points for its related coordinates
				// 3) Add the Points to the state points collection
				selector = 'table#terminalstatelisting td div a[class$=state-'+this.state+']';

				$$(selector).each( function(stateLink) {
					if( !ShippingTerminals.Geocodes[stateLink.location] ) return;

					lat=ShippingTerminals.Geocodes[stateLink.location]['lat'];
					lng=ShippingTerminals.Geocodes[stateLink.location]['lng'];

					pt = new GLatLng(lat, lng);
					statePoints.push(pt);
				});

				cacheGeocodes = ShippingTerminals.Geocodes[this.location];

				targetAddress = new GLatLng(cacheGeocodes['lat'],cacheGeocodes['lng']);

				gmapHashObject = ShippingTerminals.googleMaps.get('addressSearch');
				geocoder = gmapHashObject.get('geocoder');
				geocoder = gmapHashObject.get('geocoder');

				geocoder.getLatLng(this.state, function(point) {
					if(point==null) { 
						ShippingTerminals.handleGMapsError( {
							'type':ShippingTerminals.googleMapsErrors.BAD_ADDRESS,
							'message':'Invalid State Specified'
						} );
					}
					else {
						ShippingTerminals.setGMapCenter(state, point, statePoints, 'addressSearch');
					}
				});



			});
		});
	},

	//
	// Google Maps controls
	//
	handleGMapsError: function(errorObj) {
		alert(errorObj.message);

		// Handle Map Errors Here
//		ShippingTerminals.log(errorObj.message);

		/*switch( errorObj.type ) {
			case ShippingTerminals.googleMapsErrors.BAD_ADDRESS:
				console.log( errorObj.message );
			break;
			default:
				console.log( errorObj.message );
			break;
		};*/
	},

	setGoogleMapsVariables: function( hash ) {
		initialVars = {'map':null, 'mapElement':null, 'markerMgr':null, 'geocoder':null};
		ShippingTerminals.googleMaps = new Hash({'stateListing':new Hash(initialVars),
												 'addressSearch':new Hash(initialVars)});

		ShippingTerminals.googleMapsErrors = {'BAD_ADDRESS':'Invalid Address'};
	},

	// Sets Google Map Data for the specified hashIndex,
	// using the provided canvasRef as the Map Canvas / Overlay
	setGmap: function( canvasRef, hashIndex ) {
		mapElement = $(canvasRef);
		map = new GMap2(mapElement);

		g = new GClientGeocoder();
		g.getLatLng( 'USA', function(point) {
			if( $defined(point) ) {
				// Initialize the map by centering it
				map.setCenter(point, 4);

//				var bounds = new GLatLngBounds();
//				bounds.extend(point);
//			    map.setZoom(map.getBoundsZoomLevel(bounds));
//			    map.setCenter(bounds.getCenter());

//			    map.setUIToDefault();
			}
			else {
				/* Bad Address */
				ShippingTerminals.handleGMapsError({'message':'Invalid Address'});
			}
		});

		hashObject = ShippingTerminals.googleMaps.get(hashIndex);
		hashObject.set('map', map);
		hashObject.set('mapElement', mapElement);
		hashObject.set('hash_markerMgr', new Hash());
		hashObject.set('geocoder', g);
		ShippingTerminals.googleMaps.set(hashIndex,hashObject);
	},


	setGMapCenter: function(state, statePoint, statePointsCollection, hashIndex) {

		hashObject = ShippingTerminals.googleMaps.get(hashIndex);
		map = hashObject.get('map');
		hash_markerMgr = hashObject.get('hash_markerMgr');
//		geocoder = hashObject.get('geocoder');

		// Senter the grid relative to the statePoint
		map.setCenter( statePoint );

		// Start Bounds logistics.
		bounds = new GLatLngBounds();
		markers = [];

		// Loop thru State Points Collection to accurately Determine the Bounds for the Grid
		for(p=0; p<statePointsCollection.length; p++) {
			bounds.extend( statePointsCollection[p] );

			mkr = new GMarker(statePointsCollection[p]);
			markers.push(mkr);
		}

		// Correct for Markers that will appear outside of the Map Viewport
		bounds = map.showBounds(bounds, {top:50,right:20, left:20, disableSetCenter:false});

		// Get the Zoom Level
		minZoomLevel = 7;
		zoomLevel = Math.min( minZoomLevel, map.getBoundsZoomLevel(bounds) );

		if( ShippingTerminals.googleMaps.hasKey('previousMarkerMgr') ) {
			ShippingTerminals.googleMaps.get('previousMarkerMgr').clearMarkers();
		}

		markerMgr = new MarkerManager(map, {maxZoom: zoomLevel, trackMarkers: true});
		markerMgr.addMarkers(markers, zoomLevel);
		markerMgr.refresh();

		map.setZoom( zoomLevel );
		map.setCenter( bounds.getCenter() );
		markerMgr.refresh();

		ShippingTerminals.googleMaps.set('previousMarkerMgr', markerMgr);

		hashObject.set('map', map);
//		hashObject.set('mapElement', mapElement);
		hashObject.set('hash_markerMgr', hash_markerMgr);
//		hashObject.set('geocoder', geocoder);
		ShippingTerminals.googleMaps.set(hashIndex,hashObject);
	},

	// Set Google Maps Data for statesListing Hash
	setStatesGMap: function(canvasRef) {
		ShippingTerminals.setGmap(canvasRef,'statesListing');
	},

	// Set Google Maps Data for addressSearch Hash
	setAddressSearchGMap: function(canvasRef) {
		ShippingTerminals.setGmap(canvasRef,'addressSearch');
	},

	// Google Map Dynamic Positioning/Displaying Control
	// 20090715: Intended only for statesListing Hash Object.
	hideGmap: function( hashIndex ) {
		hashObject = ShippingTerminals.googleMaps.get(hashIndex);
		mapElement = hashObject.get('mapElement');
		mapElement.getParent().setStyle('display','block');
	},

	positionGmap: function( hashIndex, coordinates ) {
		coordinates['display'] = 'block';
		hashObject = ShippingTerminals.googleMaps.get(hashIndex);
		mapElement = hashObject.get('mapElement');
		mapElement.getParent().setStyles(coordinates);
		ShippingTerminals.hideGmap.delay(10000);
	}
};


//window.addEvent('domready', function() { ShippingTerminals.accordion(); } );

window.addEvent('unload', function() { GUnload(); });
