var map = null;
jQuery(document).ready(function($){
	map = new googleMaps('map');
	try { map.create();
	map.marker.clickHandler = function(){
		var _marker = this; 
		map.gMap.panTo(_marker.getPoint());
		setTimeout(function(){
			_marker.openExtInfoWindow(
				  map.gMap,
				  "custom_info_window_bubble",
				  "<div style=\"width:235px;\"><strong>"+_marker.title+"</strong><br />"+_marker.address+"<br />"+_marker.city+" - "+_marker.state+"</div>",
				  {beakOffset: 0}
				);
			}, 800);
	}
	} catch(e){ }
});
function toogleMarkers(checkbox)
{
	map.gMap.closeExtInfoWindow();
	if(checkbox.checked){
		show(map, checkbox.value);
	} else {
		hide(map, checkbox.value);
	}
}
function show(map, _icon) {
	for (var i=0; i < map.markers.length; i++) {
		if (map.markers[i].local_type == _icon) {
			map.markers[i].show();
		}
	}
}
function hide(map, _icon) {
	for (var i=0; i < map.markers.length; i++) {
		if (map.markers[i].local_type == _icon) {
			map.markers[i].hide();
		}
	}
	map.gMap.closeInfoWindow();
}
function addMarkers( _map, _title, _address, _city, _state, _lat, _lng, _icon){
	if (!window.GBrowserIsCompatible || !GBrowserIsCompatible())  {	return this; }
	var _marker = map.addMarker(_lat, _lng, _icon);
	_marker.title = _title;
	_marker.address = _address;
	_marker.city = _city;
	_marker.state = _state;
	_marker.local_type = _icon;
}
function googleMaps ( element_id ){
	var _this = this;
	this.fn = function( callback ){ if(callback != undefined && typeof(callback) == 'function') { callback(); } return this; };
	this.gMap = function( fn ) { return this; };
	this.geocoder = function ( fn ) { return this; };
	
	this.markers = [];
	this.gicons = [];
		
	this.defaults = {
		lat: -14.23500,
		lng: -51.92528,
		zoom: 3,
		notfound: 'Endereco nao encontrado'
	};
	
	this.progressBar = function (  ) {
		if(!window.ProgressbarControl) { console.log("ERROR: ProgressbarControl, not loaded!"); return this; }
		this.progressBar = new ProgressbarControl(this.gMap, {width:150, loadstring:'Loading...please wait'});
	};
	
	this.create = function ( callback ) {
		if (!window.GBrowserIsCompatible || !GBrowserIsCompatible())  {	console.log("ERROR: GoogleMaps, not loaded!"); return this; }
		try { 
			this.gMap = new GMap2( element_id );
			this.gMap.setCenter(new GLatLng( this.defaults.lat , this.defaults.lng ), this.defaults.zoom );
			this.geocoder = new GClientGeocoder();
			var customUI = this.gMap.getDefaultUI();
	        customUI.maptypes.hybrid = false;
	        this.gMap.setUI(customUI);
			this.fn( callback );
		} catch ( e ){ }
		return this;
	};
	
	this.addMarker = function ( lat, lng, icon) {
		if (!window.GBrowserIsCompatible || !GBrowserIsCompatible())  {	return this; }
		var _icon = (icon == undefined) ? this.Icon() : this.gicons[icon];
		markerOptions = { icon:_icon, draggable: true };
		point = new GLatLng( lat, lng );
		var marker =  new GMarker( point, markerOptions );
		if(this.marker.clickHandler != undefined && typeof(this.marker.clickHandler) == 'function') {
			GEvent.addListener(marker, 'click', this.marker.clickHandler);
		}
		this.gMap.addOverlay( marker );
		this.markers.push(marker);
		return marker;
	};
	
	this.marker = function( fn ){
		clickHandler = function( fn ){
		}
	};
	
	this.Icon = function (  ){
		if (!window.GBrowserIsCompatible || !GBrowserIsCompatible()) { return this; }
		var icon = new GIcon();
		icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
		icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		icon.iconSize = new GSize(12, 20);
		icon.shadowSize = new GSize(22, 20);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);
		return icon;
	};
	
	this.addIcon = function ( _id, _image, _shadow, _width, _height ){
		var icon = new GIcon();
		icon.image = _image;
		icon.shadow = _shadow;
		icon.iconSize = new GSize( _width, _height);
		icon.shadowSize = new GSize( (parseInt(_width) + 10), _height );
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);
		this.gicons[_id] = icon;
	}
	
	this.findLocale = function ( address, callback ) {
		this.geocoder.getLocations((remove_special_char(address) + ' - Brasil'), this.showLocation);
		this.fn ( callback );
		return this;
    };
	
	this.showLocation = function( response ) {
		if (!window.GBrowserIsCompatible || !GBrowserIsCompatible()) {	return this; }
		if (!response || response.Status.code != 200) {
			alert(_this.defaults.notfound);
		} else {
			place = response.Placemark[0];
			try { _this.gMap.closeExtInfoWindow(); _this.gMap.removeOverlay(_this.lastMarker); } catch (e) { };
			_this.lastMarker = _this.addMarker(place.Point.coordinates[1], place.Point.coordinates[0]);
			_this.marker.clickHandler = function(){};
			_this.gMap.setZoom(11);
			_this.gMap.panTo(point);
		}
		return _this;
    };

	this.lastMarker = function (){}

	this.randomize = function ( nMarkers, icon ) {
		if (!window.GBrowserIsCompatible || !GBrowserIsCompatible())  {	console.log("ERROR: GoogleMaps, not loaded!"); return this; }
		var icon = undefined;
		var bounds = this.gMap.getBounds();
		var southWest = bounds.getSouthWest();
		var northEast = bounds.getNorthEast();
		var lngSpan = northEast.lng() - southWest.lng();
		var latSpan = northEast.lat() - southWest.lat();
	
		this.marker.clickHandler = function(){ 
			var _marker = this; 
			_this.gMap.panTo(_marker.getPoint());
		}
	
		for(var x = 0; x < (nMarkers || 10 ); x++){
			this.addMarker(southWest.lat() + latSpan * Math.random(), southWest.lng() + lngSpan * Math.random(), icon);
		}
	};

	element_id = document.getElementById( element_id );
	if(element_id != undefined && element_id.tagName == 'DIV') {
		return this;
	} else {
		console.log("ERROR: GoogleMaps, DIV target not found!");
	}
}

function remove_special_char(word) {  
var before = 'áàãâäéèêëíìîïóòõôöúùûüçÁÀÃÂÄÉÈÊËÍÌÎÏÓÒÕÖÔÚÙÛÜÇ'; var after = 'aaaaaeeeeiiiiooooouuuucAAAAAEEEEIIIIOOOOOUUUUC'; var newWord='';
	for(i=0; i < word.length; i++) {  
		if ( before.search( word.substr( i,1 ) ) >= 0 ) {  
			newWord += after.substr( before.search( word.substr( i,1 ) ),1 );  
		} else {  
			newWord += word.substr(i,1);  
		}  
	}  
	return newWord;
}
