/**
 * @classDescription The PortalMaps variable is the main class object for jMaps
 */
var PortalMaps;

if (!PortalMaps) PortalMaps = {};

/**
 * The main object that holds the maps
 */
PortalMaps.MapObjects = {};

/**
 * Creates a new map on the passed element with the defined options.  Creates a global object that contains the map.
 * @method
 * @namespace PortalMaps.MapObjects
 * @id PortalMaps.MapObjects.Set
 * @alias PortalMaps.MapObjects.Set
 * @param {jQuery} element The element that contains the map.
 * @param {Object} options An object that contains the options.
 * @return {Object} The object that contains the map.
 */
PortalMaps.MapObjects.Set = function ( element, options ) {
	var mapName = jQuery(element).attr('id');
	var thisMap = new google.maps.Map2(element);
	PortalMaps.MapObjects[mapName] = thisMap;
	PortalMaps.MapObjects[mapName].Options = options;
	PortalMaps.MapObjects[mapName].markers = {};
	PortalMaps.MapObjects[mapName].icons = {};
	return PortalMaps.MapObjects[mapName];
};

/**
 * Adds additional objects and functions to an existing MapObject
 * @method
 * @namespace PortalMaps.MapObjects
 * @id PortalMaps.MapObjects.Append
 * @alias PortalMaps.MapObjects.Append
 * @param {jQuery} element The element that contains the map
 * @param {Object} description The name of the object to create
 * @param {Object} appending The object or function to append
 */
PortalMaps.MapObjects.Append = function ( element, description, appending ) {
	var mapName = jQuery(element).attr('id');
	PortalMaps.MapObjects[mapName][description] = appending;
};

/**
 * Returns the current map object for the passed element
 * @method
 * @namespace PortalMaps.MapObjects
 * @id PortalMaps.MapObjects.Get
 * @alias PortalMaps.MapObjects.Get
 * @param {jQuery} element The element that contains the map.
 * @return {Object} PortalMaps The PortalMaps object that contains the map.
 */
PortalMaps.MapObjects.Get = function ( element ) {
	return PortalMaps.MapObjects[jQuery(element).attr('id')];
};

/**
 * The main function to initialise the map
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.Initialise
 * @alias PortalMaps.Initialise
 * @param {jQuery} element The element to initialise the map on.
 * @param {Object} options The object that contains the options.
 * @param {Object} callback The callback function to pass out after initialising the map.
 * @return {Function} callback The callback option with the map object and options.
 */
PortalMaps.Initialise = function ( element, options, callback ) {
 /**
	 * Default options for Initialise
	 * @method
	 * @namespace PortalMaps.Initialise
	 * @id PortalMaps.Initialise.defaults
	 * @alias PortalMaps.Initialise.defaults
	 * @param {String} language The locale language for the map
	 * @param {String} mapType The type of map to create.  Options are 'map' (default), 'sat' and 'hybrid'.
	 * @param {Object} mapCenter An array that contains the Lat/Lng coordinates of the map center.
	 * @param {Number} mapZoom The initial zoom level of the map.
	 * @param {String} mapControl The option for the map control.  The options are 'small' (default), 'large' or 'none'
	 * @param {Boolean} mapEnableType Defines if the buttons for map type are shown.  Default false.
	 * @param {Boolean} mapEnableOverview Defines if the map overview is shown.  Default false.
	 * @param {Boolean} mapEnableDragging Defines if the map is draggable or not.  Default true.
	 * @param {Boolean} mapEnableInfoWindows Defines if info windows are shown on the map or not.  Default true.
	 * @param {Boolean} mapEnableDoubleClickZoom Defines if double clicking zooms the map.  Default false.
	 * @param {Boolean} mapEnableSmoothZoom Defines if smooth scrolling is enabled.  Default false.
	 * @param {Boolean} mapEnableGoogleBar Defines if the google map search tool is enabled.  Default false.
	 * @param {Boolean} mapEnableScaleControl Defines if the scale bar is shown.  Default false.
	 * @param {Boolean} mapShowjMapsIcon Defines if the jMaps icon is shown.  Default true.
	 * @param {Boolean} debugMode Defines if the map object created is returned to the Firebug console.  Default false.
	 * @return {Object} The options for SearchAddress
	 */
	function defaults() {
		return {
			// Initial type of map to display
			'language': 'en',
			// Options: 1 - view, 2 - admin
			'mapMode': 1,
			// Options: "map", "sat", "hybrid"
			'mapType': 'hybrid',
			// Initial map center
			'mapCenter': [51.917168,19.138184],
			// Initial zoom level
			'mapZoom': 6,
			// Initial map control size
			// Options: "large", "small", "none"
			'mapControl': 'small',
			// Initialise type of map control
			'mapEnableType': false,
			// Initialise small map overview
			'mapEnableOverview': false,
			// Enable map dragging when left button held down
			'mapEnableDragging': true,
			// Enable map info windows
			'mapEnableInfoWindows': true,
			// Enable double click zooming
			'mapEnableDoubleClickZoom': false,
			// Enable zooming with scroll wheel
			'mapEnableScrollZoom': true,
			// Enable smooth zoom
			'mapEnableSmoothZoom': true,
			// Enable Google Bar
			'mapEnableGoogleBar': false,
			// Enables scale bar
			'mapEnableScaleControl': false,
			//Debug Mode
			'debugMode': false
		};
	};
	options = jQuery.extend(defaults(), options);

	if (google.maps.BrowserIsCompatible()) {

	PortalMaps.getLocations(element, {'link':window.location.href,'mode':'params'}, function(response) {
		if (response.params) {
			var initials = {
				'mapMode': parseInt(response.params.mode),
				'mapControl': response.params.type,
				'mapCenter':[response.params.latitude,response.params.longitude],
				'mapZoom': response.params.zoom
			};

			options = jQuery.extend(options, initials);
		}

		var icon_modules = [
			'2',	//PET
			'3',	//USER
			'4',	//SHELTER
			'8'		//VET
		];

		var thisMap = PortalMaps.MapObjects.Set(element, options);
		var mapType = PortalMaps.GetMapType(options.mapType);
		thisMap.setCenter(new google.maps.LatLng(options.mapCenter[0], options.mapCenter[1]), parseInt(options.mapZoom,10), mapType);

		jQuery.each(icon_modules, function(intIndex, IconID) {
   		thisMap.icons[IconID] = new google.maps.Icon( {
				'image': "/gfx/g_ico"+IconID+".png",
				'shadow': "/gfx/g_icosh.png",
				'iconSize': new google.maps.Size(32, 32),
				'shadowSize': new google.maps.Size(46, 34),
				'iconAnchor': new google.maps.Point(16, 32),
				'infoWindowAnchor': new google.maps.Point(16, 16),
				'transparent': "/gfx/g_icotrn.png"
			});
		});

		// Attach a controller to the map view
		// Will attach a large or small.  If any other value passed (i.e. "none") it is ignored
		switch (options.mapControl) {
			case "mini":
				break;
			case "small":
				thisMap.addControl(new google.maps.SmallMapControl());
				break;
			case "large":
				thisMap.addControl(new google.maps.LargeMapControl());
				break;
		};
		// Type of map Control (Map,Sat,Hyb)
		if (options.mapEnableType)
			thisMap.addControl(new google.maps.MapTypeControl()); // Off by default
		// Show the small overview map
		if (options.mapEnableOverview)
			thisMap.addControl(new google.maps.OverviewMapControl());// Off by default
		// GMap2 Functions (in order of the docs for clarity)
		// Enable a mouse-dragable map
		if (!options.mapEnableDragging)
			thisMap.disableDragging(); // On by default
		// Enable Info Windows
		if (!options.mapEnableInfoWindows)
			thisMap.disableInfoWindow(); // On by default
		// Enable double click zoom on the map
		if (options.mapMode==1)
			thisMap.enableDoubleClickZoom(); // On by default
		else
			thisMap.disableDoubleClickZoom();
		// Enable scrollwheel on the map
		if (options.mapEnableScrollZoom)
			thisMap.enableScrollWheelZoom(); //Off by default
		// Enable smooth zooming
		if (options.mapEnableSmoothZoom)
			thisMap.enableContinuousZoom(); // Off by default
		// Enable Google Bar
		if (options.mapEnableGoogleBar)
			thisMap.enableGoogleBar(); //Off by default
		// Enables Scale bar
		if (options.mapEnableScaleControl)
			thisMap.addControl(new google.maps.ScaleControl());

		if (options.mapMode==2)
			google.maps.Event.addListener(thisMap, "dblclick", onDblClick);

		if (options.debugMode)
			console.log(PortalMaps);

		if (typeof callback == 'function')
			return callback(thisMap, element, options);

	});

	function onDblClick(overlay, position) {
		//if (typeof callback == 'function') return callback(thisMap.Directions, options);
		PortalMaps.AddLocation(element,{position: position});
		//alert(position.lat()+'|'+position.lng());
	}

	} else {
		jQuery(element).text('Your browser does not support Google Maps.');
		return false;
	}
	return;
};

/**
 * A function to move a map to a passed position
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.MoveTo
 * @alias PortalMaps.MoveTo
 * @param {jQuery} element The element to initialise the map on.
 * @param {Object} options The object that contains the options.
 * @param {Object} callback The callback function to pass out after initialising the map.
 * @return {Function} callback The callback option with the map object and options or true.
 */
PortalMaps.MoveTo = function ( element, options, callback ) {
	/**
 	 * Default options for MoveTo
   * @method
   * @namespace PortalMaps
   * @id PortalMaps.MoveTo
   * @alias PortalMaps.MoveTo
   * @param {String} centerMethod The element to initialise the map on.
   * @param {String} mapType The type of map to create.  Options are 'map' (default), 'sat' and 'hybrid'.
   * @param {Object} mapCenter An array that contains the Lat/Lng coordinates of the map center.
   * @param {Number} mapZoom The initial zoom level of the map.
   * @return {Function} callback The callback option with the point object and options or true.
   */
	function defaults() {
		return {
			'centerMethod': 'normal',
			'mapType': null,
			'mapCenter': [],
			'mapZoom': null
		};
	};
	options = jQuery.extend(defaults(), options);

	var thisMap = PortalMaps.MapObjects.Get(element);

	if (options.mapType)
		var mapType = PortalMaps.GetMapType(options.mapType);
	var point = new google.maps.LatLng(options.mapCenter[0], options.mapCenter[1]);
	switch (options.centerMethod) {
		case 'normal':
			thisMap.setCenter(point, parseInt(options.mapZoom,10), mapType);
		break;
		case 'pan':
			thisMap.panTo(point);
		break;
	}
	if (typeof callback == 'function') return callback(point, options);
};

PortalMaps.ZoomAndCenter = function ( element, options, callback ) {

	function defaults() {
		return {
			'centerMethod': 'normal',
			'mapType': null,
			'mapCenter': [],
			'mapZoom': null
		};
	};
	var thisMap = PortalMaps.MapObjects.Get(element);

	options = jQuery.extend(defaults(), options);
	if (options.mapType) {
		var mapType = PortalMaps.GetMapType(options.mapType);
	}

	$markers_count = 0;
	jQuery.each(thisMap.markers, function( ){
		$markers_count++;
	});
	if ($markers_count > 0) {

		var bounds = new google.maps.LatLngBounds();
		jQuery.each(thisMap.markers, function( intIndex, marker ){
			bounds.extend(marker.getPoint());
 		});
		//var zoom = Math.max(1, PortalMaps.getBoundsZoomLevel(element, bounds) - 1);
		var zoom = Math.max(1, PortalMaps.getBoundsZoomLevel(element, bounds)-1);
		var point = bounds.getCenter();

		switch (options.centerMethod) {
			case 'normal':
				thisMap.setCenter(point, parseInt(zoom,10), mapType);
			break;
			case 'pan':
				thisMap.panTo(point);
			break;
		}
	}
	if (typeof callback == 'function') return callback(point, options);
};

PortalMaps.ZoomToFit = function ( element, options, callback ) {

	//options = jQuery.extend(defaults(), options);

	var thisMap = PortalMaps.MapObjects.Get(element);

	if (options.mapType) {
		var mapType = PortalMaps.GetMapType(options.mapType);
	}

	$markers_count = 0;
	jQuery.each(thisMap.markers, function( ){
		$markers_count++;
	});
	if ($markers_count > 0) {

		var bounds_map = PortalMaps.getBounds(element);
		var zoom_map = PortalMaps.getBoundsZoomLevel(element, bounds_map);

		var bounds = new google.maps.LatLngBounds();
		jQuery.each(thisMap.markers, function( intIndex, marker ){
			bounds.extend(marker.getPoint());
 		});
		//var zoom = Math.max(1, PortalMaps.getBoundsZoomLevel(element, bounds) - 1);
		var zoom = Math.max(1, PortalMaps.getBoundsZoomLevel(element, bounds));
		var point = bounds.getCenter();

		switch (options.centerMethod) {
			case 'normal':
				thisMap.setCenter(point, parseInt(zoom,10), mapType);
			break;
			case 'pan':
				thisMap.panTo(point);
			break;
		}
	}
	if (typeof callback == 'function') return callback(point, options);
};

/**
 * Save your current position on the map
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.SavePosition
 * @alias PortalMaps.SavePosition
 * @param {jQuery} element The element to initialise the map on.
 * @param {Object} options The object that contains the options.
 * @param {Object} callback The callback function to pass out after initialising the map.
 * @return {Function} callback The callback option with the map object and options or true.
 */
PortalMaps.SavePosition = function( element, options, callback ) {
	var thisMap = PortalMaps.MapObjects.Get(element);
	thisMap.savePosition();
	if (typeof callback == 'function') return callback(thisMap);
};

/**
 * Goto a previously saved position
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.GotoSavedPosition
 * @alias PortalMaps.GotoSavedPosition
 * @param {jQuery} element The element to initialise the map on.
 * @param {Object} options The object that contains the options.
 * @param {Function} callback The callback function to pass out after initialising the map.
 * @return {Function} callback The callback option with the map object and options or true.
 */
PortalMaps.GotoSavedPosition = function ( element, options, callback) {
	var thisMap = PortalMaps.MapObjects.Get(element);
	thisMap.returnToSavedPosition();
	if (typeof callback == 'function') return callback(thisMap);
};

/**
 * Create a keyboard handler to handle keyboard navigation
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.CreateKeyboardHandler
 * @alias PortalMaps.CreateKeyboardHandler
 * @param {jQuery} element The element to initialise the map on.
 * @param {Object} options The object that contains the options.
 * @param {Object} callback The callback function to pass out after initialising the map.
 * @return {Function} callback The callback option with the keyboard handler.
 */
PortalMaps.CreateKeyboardHandler = function( element, options, callback ) {
	var thisMap = PortalMaps.MapObjects.Get(element);
	var keyboardHandler = new google.maps.KeyboardHandler(thisMap);
	if (typeof callback == 'function') return callback(keyboardHandler);
};

/**
 * The SearchAddress function takes a map, options and callback function.  The options can contain either an address string, to which a point is returned - or reverse geocoding a GLatLng, where an address is returned
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.SearchAddress
 * @param {jQuery} element The jQuery object containing the map element.
 * @param {Object} options An object of options
 * @param {Function} callback The callback function that returns the result
 * @return {Function} Returns a passed callback function or true if no callback specified
 */
PortalMaps.SearchAddress = function( element, options, callback) {
	/**
	 * Default options for SearchAddress
	 * @method
	 * @namespace PortalMaps.SearchAddress
	 * @id PortalMaps.SearchAddress.defaults
	 * @alias PortalMaps.SearchAddress.defaults
	 * @param {String} query The Address or GLatLng to query in the geocoder
	 * @param {String} returnType The type of value you want to return from Google.  This is mapped to the function names available, the options are 'getLatLng' which returns coordinates, and 'getLocations' which returns points.
	 * @param {GGeoCache} cache The GGeoCache to store the results in if required
	 * @param {String} countryCode The country code to localise results
	 * @return {Object} The options for SearchAddress
	 */
	function defaults() {
		return {
			// Address to search for
			'query': null,
			// Return Type
			'returnType': 'getLocations',//'returnType': 'getLatLng',
			// Optional Cache to store Geocode Data (not implemented yet)
			'cache': undefined,
			// Country code for localisation (not implemented yet)
			'countryCode': 'uk'
		};
	};
	var thisMap = PortalMaps.MapObjects.Get(element);
	options = jQuery.extend(defaults(), options);

	// Check to see if the Geocoder already exists in the object
	// or create a temporary locally scoped one.
	if (typeof thisMap.Geocoder === 'undefined') {
		if (typeof options.cache === 'undefined') {
		 	var geoCoder = new google.maps.ClientGeocoder();
		} else {
			var geoCoder = new google.maps.ClientGeocoder(cache);
		}
		PortalMaps.MapObjects.Append(element, 'Geocoder', geoCoder);
		// We need to get the map object again, now we have attached the geocoder
		thisMap = PortalMaps.MapObjects.Get(element);
	}
	thisMap.Geocoder[options.returnType](options.query, function(result){
		if (typeof callback === 'function') {
			return callback(element, result, options);
		}
	});
	return;
};

/**
 * The SearchDirections function allows you to search for directions between two or more points and return it to a map and a directions panel
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.SearchDirections
 * @param {jQuery} element The jQuery object containing the map element.
 * @param {Object} options An object of options
 * @param {Function} callback The callback function that returns the result
 * @return {Function} Returns a passed callback function or true if no callback specified
 */
PortalMaps.SearchDirections = function( element, options, callback) {
	/**
	 * Default options for SearchDirections
	 * @method
	 * @namespace PortalMaps.SearchDirections
	 * @id PortalMaps.SearchDirections.defaults
	 * @alias PortalMaps.SearchDirections.defaults
	 * @param {String} query The directions query to parse.  Must contain one 'from:' and one 'to:' query, but can contain multiple 'to:' queries.
	 * @param {String} panel The ID of the panel that the directions will be sent to.
	 * @param {String} local The local for the directions.
	 * @param {String} travelMode Allows you to specify the travel mode, either 'driving' or 'walking'.  Driving is the default.
	 * @param {Boolean} avoidHighways Allows you to avoid Highways/Motorway's on trips.  Please note this may not always be possible depending on the route.
	 * @param {Boolean} getPolyline Decides if the returned result will draw a polyline on the map on the journey.  Default is True.
	 * @param {Boolean} getSteps Decides if the textual directions are returned to the directions panel.
	 * @param {Boolean} preserveViewport Decides if the map will zoom and center in on the directions results.
	 * @param {Boolean} clearLastSearch Clears the last direction search if you do not want to have multiple points.
	 * @return {Object} The options for SearchDirections
	 */
	function defaults() {
		return {
			// From address
			'query': null,
			// Optional panel to show text directions
			'panel': null,
			//The locale to use for the directions result.
			'locale': 'en_GB',
			//The mode of travel, such as driving (default) or walking
			'travelMode': 'driving',
			// Option to avoid highways
			'avoidHighways': false,
			// Get polyline
			'getPolyline': true,
			// Get directions
			'getSteps': true,
			// Preserve Viewport
			'preserveViewport' : false,
			// clear last search
			'clearLastSearch' : false
		};
	};
	var thisMap = PortalMaps.MapObjects.Get(element);
	options = jQuery.extend(defaults(), options);

	var queryOptions = {
		'locale': options.locale,
		'travelMode': options.travelMode,
		'avoidHighways': options.avoidHighways,
		'getPolyline': options.getPolyline,
		'getSteps': options.getSteps,
		'preserveViewport' : options.preserveViewport
	};

	var panel = $(options.panel).get(0);

	if (typeof thisMap.Directions === 'undefined') {
  	PortalMaps.MapObjects.Append(element, 'Directions', new google.maps.Directions(thisMap, panel));
  }

	google.maps.Event.addListener(thisMap.Directions, "load", onLoad);
  google.maps.Event.addListener(thisMap.Directions, "error", onError);

	if (options.clearLastSearch) {
		thisMap.Directions.clear();
	}

	thisMap.Directions.load(options.query, queryOptions);

	function onLoad() {
		if (typeof callback == 'function') return callback(thisMap.Directions, options);
	}

	function onError() {
		if (typeof callback == 'function') return callback(thisMap.Directions, options);
	}

	return;
};

/**
 * This function allows you to add markers to the map with several options
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.AddMarker
 * @alias PortalMaps.AddMarker
 * @param {jQuery} element The element to initialise the map on.
 * @param {Object} options The object that contains the options.
 * @param {Function} callback The callback function to pass out after initialising the map.
 * @return {Function} callback The callback option with the marker object and options.
 */
PortalMaps.AddMarker = function ( element, options, callback ) {
	/**
	 * Default options for AddGroundOverlay
	 * @method
	 * @namespace PortalMaps.AddGroundOverlay
	 * @id PortalMaps.AddGroundOverlay.defaults
	 * @alias PortalMaps.AddGroundOverlay.defaults
	 * @param {Object} pointLatLng The Lat/Lng coordinates of the marker.
	 * @param {String} pointHTML The HTML to appear in the markers info window.
	 * @param {String} pointOpenHTMLEvent The javascript event type to open the marker info window.  Default is 'click'.
	 * @param {Boolean} pointIsDraggable Defines if the point is draggable by the end user.  Default false.
	 * @param {Boolean} pointIsRemovable Defines if the point can be removed by the user.  Default false.
	 * @param {Boolean} pointRemoveEvent The event type to remove a marker.  Default 'dblclick'.
	 * @param {Number} pointMinZoom The minimum zoom level to display the marker if using a marker manager.
	 * @param {Number} pointMaxZoom The maximum zoom level to display the marker if using a marker manager.
	 * @param {GIcon} pointIcon A GIcon to display instead of the standard marker graphic.
	 * @param {Boolean} centerMap Automatically center the map on the new marker.  Default false.
	 * @param {String} centerMoveMethod The method in which to move to the marker.  Options are 'normal' (default) and 'pan'
	 * @return {Object} The options for AddGroundOverlay
	 */
	function defaults() {
		var values = {
			'pointID': 0,
			'pointModule': undefined,
			'pointItem': undefined,
			'pointLatLng': undefined,
			'pointHTML': undefined,
			'pointOpenHTMLEvent': 'click',
			'pointIsDraggable': false,
			'pointIsRemovable': false,
			'pointRemoveEvent': 'dblclick',
			'pointMinZoom': 4,
			'pointMaxZoom': 17,
			'pointIcon': undefined,
			'centerMap': false,
			'centerMoveMethod':'normal'
		};
		return values;
	};
	var thisMap = PortalMaps.MapObjects.Get(element);
	options = jQuery.extend({}, defaults(), options);

	var markerOptions = {}

	if (typeof options.pointIcon == 'object')
		jQuery.extend(markerOptions, {'icon': options.pointIcon});
	else if (typeof thisMap.icons[options.pointIcon] == 'object')
		jQuery.extend(markerOptions, {'icon': thisMap.icons[options.pointIcon]});

	if (options.pointIsDraggable)
		jQuery.extend(markerOptions, {'draggable': options.pointIsDraggable});

	if (options.centerMap) {
		switch (options.centerMoveMethod) {
			case 'normal':
				thisMap.setCenter(new google.maps.LatLng(options.pointLatLng[0],options.pointLatLng[1]));
			break;
			case 'pan':
				thisMap.panTo(new google.maps.LatLng(options.pointLatLng[0],options.pointLatLng[1]));
			break;
		}
	}

	// Create marker, optional parameter to make it draggable
	var marker = new google.maps.Marker(new google.maps.LatLng(options.pointLatLng[0],options.pointLatLng[1]), markerOptions);

	if (options.pointID)
		marker.location_id = options.pointID;

	// If it has HTML to pass in, add an event listner for a click
	if(options.pointHTML)
		google.maps.Event.addListener(marker, options.pointOpenHTMLEvent, function(){
			marker.openInfoWindowHtml(options.pointHTML, {maxContent: options.pointMaxContent, maxTitle: options.pointMaxTitle});
		});
	// If it is removable, add dblclick event
	if(options.pointIsRemovable) {
		google.maps.Event.addListener(marker, options.pointRemoveEvent, function(){
			thisMap.removeOverlay(marker);
		});
	}

	if (options.pointIsDraggable) {
		google.maps.Event.addListener(marker, 'dragend', function() {
			PortalMaps.UpdateMarker(element, marker);
		});
		google.maps.Event.addListener(marker, 'dragstart', function() {
			marker.closeInfoWindow();
		});
	}

	PortalMaps.RemoveMarkerFromMap( element, marker );
	// If the marker manager exists, add it
	if(thisMap.MarkerManager) {
		thisMap.MarkerManager.addMarker(marker, options.pointMinZoom, options.pointMaxZoom);
	} else {
		// Direct rendering to map
		thisMap.addOverlay(marker);
	}
	thisMap.markers[marker.location_id] = marker;

	if (typeof callback == 'function') return callback(marker, options);
	return;
};

PortalMaps.UpdateMarker = function ( element, marker, callback ) {

	var thisMap = PortalMaps.MapObjects.Get(element);
	var point = marker.getPoint();
	var inputs = [];

	inputs.push('mode=move');
	//inputs.push('post_id=' + this.post_id);
	inputs.push('location_id=' + marker.location_id);
	inputs.push('latitude=' + point.lat());
	inputs.push('longitude=' + point.lng());

	jQuery.ajax({
		element: element,
		dataType: 'json',
		data: inputs.join('&'),
		//url: window.location,
		//timeout: 5000,
		async: 'false',
		type: 'post',
		error: function() {
			//console.log("Failed to submit");
			alert("BÅ‚Ä…d aktualizowania lokalizacji!");
		},
		success: function(marker) {
			PortalMaps.AddMarker(this.element,{
				'pointID':marker.location_id,
				'pointLatLng':[marker.latitude,marker.longitude],
				'pointHTML':marker.description,
				'pointIcon':marker.module,
				'pointIsDraggable': true,
				'pointIsRemovable': true
			});
			PortalMaps.ZoomAndCenter(this.element,{});
			//if (typeof callback === 'function') return callback(response);
		}
	});

	//thisMap.removeOverlay(marker);
	if (typeof callback === 'function') return callback(marker);
	return;
};

PortalMaps.RemoveMarkerFromMap = function ( element, marker ) {
	var thisMap = PortalMaps.MapObjects.Get(element);

	if (!PortalMaps.MarkerExists( element, marker.location_id ))
		return;

	thisMap.removeOverlay(thisMap.markers[marker.location_id]);
	delete thisMap.markers[marker.location_id];
};

PortalMaps.MarkerExists = function ( element, location_id) {
	var thisMap = PortalMaps.MapObjects.Get(element);
	//var location_ids = jQuery.map(thisMap.markers, function(n, i){
  //    return (n);
  //  });
  //return location_ids.indexOf(location_id) >= 0;
  return thisMap.markers[location_id]!=undefined;
};

/**
 * This function allows you to remove markers from the map
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.RemoveMarker
 * @alias PortalMaps.RemoveMarker
 * @param {jQuery} element The element to initialise the map on.
 * @param {GMarker} options The marker to be removed
 * @param {Function} callback The callback function to pass out after initialising the map.
 * @return {Function} callback The callback option with the marker object.
 */
PortalMaps.RemoveMarker = function ( element, marker, callback ) {
	var thisMap = PortalMaps.MapObjects.Get(element);
	thisMap.removeOverlay(marker);
	if (typeof callback === 'function') return callback(marker);
	return;
};

PortalMaps.FindLocation = function ( element, options, callback ) {

	var thisMap = PortalMaps.MapObjects.Get(element);

	PortalMaps.SearchAddress( element, options, function(element, locations, options) {
		$status = PortalMaps.SearchCode(locations.Status.code);
		if (!$status.success) {
			alert($status.message);
			return;
		}

		var placemark = locations.Placemark[0];

		PortalMaps.MoveTo(element,{
			'mapCenter': [placemark.Point.coordinates[1],placemark.Point.coordinates[0]],
			'mapZoom': 16
		});
	});
	//if (typeof callback === 'function') return callback(marker);
};

PortalMaps.AddLocation = function ( element, options, callback ) {

	alert(options.position.lat()+'|'+options.position.lng());
	
	var items = {};
	$('#mapform :input').each( function(i, el) {
		items[$(el).attr('name')] = $(el).attr('value');
	});
	//{'query':items.query,'user':items.user,'module':items.module,'item':items.item} );

	function defaults() {
		var values = {
		'query': items.query,
		'user': items.user,
		'module': items.module,
		'item': items.item
		};
		return values;
	};
	var thisMap = PortalMaps.MapObjects.Get(element);
	options = jQuery.extend({}, defaults(), options);

	var inputs = [];
	inputs.push('mode=add');
	inputs.push('user=' + options.user);
	inputs.push('module=' + options.module);
	inputs.push('item=' + options.item);
	//inputs.push('post_id=' + this.post_id);
	//inputs.push('location_id=' + marker.location_id);
	inputs.push('latitude=' + options.position.lat());
	inputs.push('longitude=' + options.position.lng());
	//inputs.push('description=' + escape(placemark.address));

	jQuery.ajax({
		element: element,
		dataType: 'json',
		data: inputs.join('&'),
		//url: window.location,
		//timeout: 5000,
		async: 'false',
		type: 'post',
		error: function() {
			//console.log("Failed to submit");
			alert("B³¹d zapisywania lokalizacji!");
		},
		success: function(marker, element) {
			PortalMaps.AddMarker(this.element,{
				'pointID':marker.location_id,
				'pointLatLng':[marker.latitude,marker.longitude],
				'pointHTML':marker.description,
				'pointIcon':marker.module,
				'pointIsDraggable': true,
				'pointIsRemovable': true
			});
			PortalMaps.ZoomAndCenter(this.element,{});
			//if (typeof callback === 'function') return callback(response);
		}
	});
	//if (typeof callback === 'function') return callback(marker);
	return;
};

/**
 * A helper method that allows you to pass the status code of a search and get back a friendly oject
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.SearchCode
 * @param {Number} code The status code of the query
 * @return {Object} Returns a friendly object that contains the 'code', a 'success' boolean and a helpful 'message'.
 */
PortalMaps.SearchCode = function ( code ) {
	switch (code) {
		case G_GEO_SUCCESS:
			return {'code':G_GEO_SUCCESS,'success':true,'message':'Sukces'};
		case G_GEO_UNKNOWN_ADDRESS:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'Nie znaleziono odpowiadajÄ…cej lokacji geograficznej dla podanego adresu. MoÅ¼e byÄ‡ to spowodowanie podaniem zbyt nowego lub nieprawidÅ‚owego adresu.'};
			break;
		case G_GEO_SERVER_ERROR:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'Zapytanie nie mogÅ‚o byÄ‡ przetworzone, dokÅ‚adny powÃ³d bÅ‚Ä™du nie jest znany.'};
			break;
		case G_GEO_MISSING_QUERY:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'Pole zapytania byÅ‚o puste. Musisz podaÄ‡ lokalizacjÄ™ do wyszukania.'};
			break;
		case G_GEO_BAD_KEY:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'NieprawidÅ‚owy klucz aplikacji.'};
			break;
		case G_GEO_BAD_REQUEST:
			return {'code' : G_GEO_UNKNOWN_ADDRESS, 'success' : false, 'message' : 'Zapytanie o trasÄ™ nie mogÅ‚o byÄ‡ przetworzone.'};
			break;
		default:
			return {'code': null, 'success': false,	'message': 'WystÄ…piÅ‚ nieznany bÅ‚Ä…d.' };
			break;
	};
}

/**
 * An internal function to get the google maptype constant
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.GetMapType
 * @alias PortalMaps.GetMapType
 * @param {String} mapType The string of the map type.
 * @return {String} mapType The Google constant for a maptype.
 */
PortalMaps.GetMapType = function ( mapType ) {
	// Lets set our map type based on the options
	switch(mapType) {
		case 'map':	// Normal Map
			mapType = G_NORMAL_MAP;
		break;
		case 'sat':	// Satallite Imagery
			mapType = G_SATELLITE_MAP;
		break;
		case 'hybrid':	//Hybrid Map
			mapType = G_HYBRID_MAP;
		break;
	};
	return mapType;
};

/**
 * A helper function to create a google GIcon
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.createIcon
 * @alias PortalMaps.createIcon
 * @param {Object} options The options to create the icon
 * @return {GIcon} A GIcon object
 */
PortalMaps.createIcon = function (options) {
	/**
	 * Default options for createIcon
	 * @method
	 * @namespace PortalMaps.createIcon
	 * @id PortalMaps.createIcon.defaults
	 * @alias PortalMaps.createIcon.defaults
	 * @param {String} iconImage The foreground image URL of the icon.
	 * @param {String} iconShadow The shadow image URL of the icon.
	 * @param {GSize} iconSize The pixel size of the foreground image of the icon.
	 * @param {GSize} iconShadowSize The pixel size of the shadow image.
	 * @param {GPoint} iconAnchor The pixel coordinate relative to the top left corner of the icon image at which this icon is anchored to the map.
	 * @param {GPoint} iconInfoWindowAnchor The pixel coordinate relative to the top left corner of the icon image at which the info window is anchored to this icon.
	 * @param {String} iconPrintImage The URL of the foreground icon image used for printed maps. It must be the same size as the main icon image given by image.
	 * @param {String} iconMozPrintImage The URL of the foreground icon image used for printed maps in Firefox/Mozilla. It must be the same size as the main icon image given by image.
	 * @param {String} iconPrintShadow The URL of the shadow image used for printed maps. It should be a GIF image since most browsers cannot print PNG images.
	 * @param {String} iconTransparent The URL of a virtually transparent version of the foreground icon image used to capture click events in Internet Explorer. This image should be a 24-bit PNG version of the main icon image with 1% opacity, but the same shape and size as the main icon.
	 * @return {Object} The options for createIcon
	 */
	function defaults() {
		return {
			'iconImage': undefined,
			'iconShadow': undefined,
			'iconSize': undefined,
			'iconShadowSize': undefined,
			'iconAnchor': undefined,
			'iconInfoWindowAnchor': undefined,
			'iconPrintImage': undefined,
			'iconMozPrintImage': undefined,
			'iconPrintShadow': undefined,
			'iconTransparent': undefined
		};
	};

	options = jQuery.extend(defaults(), options);
	var icon = new google.maps.Icon(G_DEFAULT_ICON);

	if(options.iconImage)
		icon.image = options.iconImage;
	if(options.iconShadow)
		icon.shadow = options.iconShadow;
	if(options.iconSize)
		icon.iconSize = options.iconSize;
	if(options.iconShadowSize)
		icon.shadowSize = options.iconShadowSize;
	if(options.iconAnchor)
		icon.iconAnchor = options.iconAnchor;
	if(options.iconInfoWindowAnchor)
		icon.infoWindowAnchor = options.iconInfoWindowAnchor;
	return icon;
};

/**
 * A helper function to get the map center as a GLatLng
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.getCenter
 * @alias PortalMaps.getCenter
 * @param {jQuery} element The element that contains the map.
 * @return {GLatLng} A object containing the center of the map
 */
PortalMaps.getCenter = function ( element ) {
	options = jQuery.extend(defaults(), options);	var thisMap = PortalMaps.MapObjects.Get(element);
	var thisMap = PortalMaps.MapObjects.Get(element);
	return thisMap.getCenter();
};

/**
 * A helper function to get the bounds of the map
 * @method
 * @namespace PortalMaps
 * @id PortalMaps.getBounds
 * @alias PortalMaps.getBounds
 * @param {jQuery} element The element that contains the map.
 * @return {GSize} The bounds of the map
 */
PortalMaps.getBounds = function (element){
	var thisMap = PortalMaps.MapObjects.Get(element);
	return thisMap.getBounds();
};

PortalMaps.getBoundsZoomLevel = function (element, bounds){
	var thisMap = PortalMaps.MapObjects.Get(element);
	return thisMap.getBoundsZoomLevel(bounds);
};

PortalMaps.getLocations = function (element, options, callback) {

	function defaults() {
		return {
			'mode': 'read'
		};
	};
	options = jQuery.extend(defaults(), options);
	var thisMap = PortalMaps.MapObjects.Get(element);

	var inputs = [];

	inputs.push('mode='+options.mode);

	$.ajax({
		dataType: 'json',
		data: inputs.join('&'),
		url: options.url,
		//timeout: 5000,
		async: 'false',
		type: 'post',
		error: function() {
			//console.log("Failed to submit");
			alert("BÅ‚Ä…d Å‚adowania lokalizacji!");
		},
		success: function(response) {
			if (typeof callback === 'function') return callback(response);
		}
	});
};

var PortalMaps;

if (!PortalMaps) PortalMaps = {};

(function($){
	$.fn.pmap = function(method, options, callback) {
		return this.each(function(){
			if (method == 'init' && typeof options == 'undefined') {
				new PortalMaps.Initialise(this, {}, null);
			} else if (method == 'init' && typeof options == 'object') {
				new PortalMaps.Initialise(this, options, callback);
			} else if (method == 'init' && typeof options == 'function') {
				new PortalMaps.Initialise(this, {}, options);
			} else if (typeof method == 'object' || method == null) {
				new PortalMaps.Initialise(this, method, options);
			} else {
				try {
					new PortalMaps[method](this, options, callback);
				} catch(err) {
					throw Error('PortalMaps Function Does Not Exist');
				}
			}
		});
	}
})(jQuery);
