//<![CDATA[
var mapviewer;
var labeled = false;
var map;
var mapSize = 'normal';
var zoomControl;
var typeControl;
var point;
var marker;
var gdir;

//
var TOSIcon = new GIcon(G_DEFAULT_ICON);
TOSIcon.image = "http://www.timeoutsingapore.com/images/map_icon.png";
TOSIcon.iconSize = new GSize(23, 26);
TOSIcon.iconAnchor = new GPoint(12,26);
TOSIcon.shadow = '';

function loadMap() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("mapviewer"));
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		map.disableScrollWheelZoom(); 
		zoomControl = new GSmallMapControl();
		map.addControl(zoomControl);
		if (locationLAT != '' && locationLON != '') {
			point = new GLatLng(locationLAT, locationLON);
			map.setCenter(point, 15);
			marker = new GMarker(point, {icon: TOSIcon, title: VenueName});
			map.addOverlay(marker);
			gdir = new GDirections(map, document.getElementById("googleDir"));
      	  	GEvent.addListener(gdir, "error", handleErrors);
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
		}
	}
}

function navMap(lat, lon) {
	map.removeOverlay(marker);
	point = new GLatLng(lat, lon);
	map.setCenter(point, 15);
	marker = new GMarker(point);
	map.addOverlay(marker);
	document.location.hash = 'mapa';
}

function switchMapSize() {
	var mapDiv = MM_findObj("mapviewer");
	var mapCtrl = MM_findObj("mapControls");
	var lnkLbl = MM_findObj("lnkLabel");
	if (mapSize == 'normal') {
		zoomControl = new GLargeMapControl();
		typeControl = new GMapTypeControl();
		map.addControl(zoomControl);
		map.addControl(typeControl);
		map.enableScrollWheelZoom(); 
		mapDiv.style.height = '600px';
		mapDiv.style.width = '650px';
		mapCtrl.style.width = '650px';
		lnkLbl.innerHTML = 'Smaller view';
		setTimeout('resetView()', 10);
		mapSize = 'extended';
	} else {
		map.removeControl(zoomControl);
		map.removeControl(typeControl);
		map.disableScrollWheelZoom(); 
		zoomControl = null;
		typeControl = null;
		mapDiv.style.height = '300px';
		mapDiv.style.width = '100%';
		mapCtrl.style.width = '100%';
		lnkLbl.innerHTML = 'Larger view';
		setTimeout('resetView()', 10);
		map.setMapType(G_NORMAL_MAP);
		mapSize = 'normal';
	}
}

function resetView() {
	map.checkResize(); 
	map.setCenter(point, 15);
}

function showRoute(theForm) {
	from = theForm.fromAddress.value;
	var to = '';
	to = point.y.toString() + ', ' + point.x.toString();
	gdir.load("from: " + from + " to: " + to,
                { "locale": 'pt_BR' });
}

function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
		alert("Não foi possível localizar o endereço digitado. Verifique o endereço e tente novamente.\nError code: " + gdir.getStatus().code);
		document.form2.fromAddress.focus();
	} else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
		alert("Ocorreu um erro desconhecido ao processar o endereço solicitado.\n Error code: " + gdir.getStatus().code);
		document.form2.fromAddress.focus();
	} else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
		alert("Você não digitou nenhum endereço. Tente novamente.\n Error code: " + gdir.getStatus().code);
		document.form2.fromAddress.focus();
	} else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
		alert("Ocorreu um problema ao processar o endereço.\n Error code: " + gdir.getStatus().code);
		document.form2.fromAddress.focus();
	}else if (gdir.getStatus().code == G_GEO_BAD_REQUEST){
		alert("Ocorreu um problema ao processar o endereço.\n Error code: " + gdir.getStatus().code);
		document.form2.fromAddress.focus();
	} else {
		alert("Ocorreu um erro desconhecido.\n Error code: " + gdir.getStatus().code);
	}
}
function onGDirectionsLoad(){ 
	el = MM_findObj('googleDir');
	el.style.display='block';
}
		   
		   
/*
var mapviewer, searcher, search, markers;
var labeled = false;
var rfs = ['client_id', 'name', 'street', 'town', 'pc', 'lat', 'lon'];

function onLoad() { 
	//Add the map
	mapviewer = new MultimapViewer( document.getElementById( 'mapviewer' ) );
	mapviewer.addEventHandler( 'endSearchRequest', endSearch );
	if (addressID > 0 && addressID != null) {
		var ml = new MMLocation(new MMSearch(new MMSearchFilter('client_id','eq',addressID)));
		mapviewer.goToPosition(ml);
	} else {
		if (locationLAT != 0 && locationLON != 0) {
			var pos = new MMLatLon;
			pos.lat = locationLAT;
			pos.lon = locationLON;
			var mapLocation = new MMLocation(pos);
		} else {
			var mapLocation = new MMLocation(new MMAddress({ qs : locationSTR + ', SINGAPORE' }));
		}
		mapviewer.addEventHandler( 'endPan', mapHasPanned );
		mapviewer.addWidget( new MMSmallPanZoomWidget() );
		mapviewer.goToPosition(mapLocation, 17);
	}
}

function onContextMenu( type, target, menu, pos, step ) {
	items = [ { label : 'Get Position', onclick : function() { addMarker(pos) }, className : 'MMaddmarker' } ];
	menu.addItemsJSON( items );
}

function addMarker(pos) {
	var icon = new MMIcon( 'http://www.timeoutsingapore.com/images/map_icon.png' );
	icon.iconSize = new MMDimensions( 23, 26 );
	icon.iconAnchor = new MMPoint( 12, 13 );
	var marker = mapviewer.createMarker( pos, {'label': VenueName, 'icon' : icon} );
	var addr = '<h1>' + VenueName + '</h1>';
	addr = addr + '<h6>';
	addr = addr + locationSTR + '<br />';
	if (buildingSTR != '') {
		addr = addr + buildingSTR + '<br />';
	}
	addr = addr + 'Singapore<br />';
	addr = addr + postalSTR + '<br />';
	addr = addr + '</h6>'
	
	var srv = '<h1>' + VenueName + '</h1>';
	srv = srv + '<h6>';
	srv = srv + locationSTR;
	if (busInfo != '') {
		srv = srv + '<br />Bus Lines: ' + busInfo;
	}
	if (stInfo != '') {
		srv = srv + '<br />Nearby Stations: ' + stInfo;
	}
	if (busInfo == '' && stInfo == '') {
		srv = srv + '<br />No bus lines or stations nearby';
	}
	srv = srv + '</h6>'
	
	var cts = '<h1>' + VenueName + '</h1>';
	cts = cts + '<h6>';
	cts = cts + locationSTR;
	if (phoneSTR != '') {
		cts = cts + '<br />Phone: ' + phoneSTR;
	}
	if (siteSTR != '') {
		cts = cts + '<br /><a href="' + siteSTR + '" target="_blank">visit website &raquo;</a>';
	}
	cts = cts + '</h6>'
	var tabs = [
		new MMInfoBoxTab( 'Location', addr ),
		new MMInfoBoxTab( 'Services', srv ),
		//new MMInfoBoxTab( 'Photo', "<img src=\"http://ww1.timeoutsingapore.com/contentFiles/image/venues/butterfactory200.JPG\" />" ),
		new MMInfoBoxTab( 'Contacts', cts ) 
	];
	marker.setInfoBoxContent(tabs);
	
	//searchNearby(pos);
	
	labeled = true;
}

function createMarker(location, display_name, num) {
    var marker = mapviewer.createMarker(location, {'text' : num});
    marker.setInfoBoxContent('<p>' + display_name + '<' + '/p>');
    return marker;
}

function searchNearby(pos) {
	searcher = MMFactory.createSearchRequester( resultsLoaded );
	search = new MMSearch();
	search.return_fields = rfs;
	
	search.count = 10;
	
	search.point = pos;
	search.max_distance = 1;

	search.distance_units = 'km';
	
	searcher.search( search );
}

function resultsLoaded ( ) {
	markers = new Array(); 
    // If an error code has been produced, display the explanation:
    if ( searcher.error_code ) {
        var err =  '';
        if ( searcher.error_explanation ) {
            err =  searcher.error_explanation;
        } else {
            err =  'Your request failed. Error code: ' + searcher.error_code;
        }
        alert( err );
        return;
    } 

    var results_returned = 1;
    var el = document.createElement ( 'ol' );
    el.id = 'recordList';
    var  start_index_value = 1;      
     
    // Loop through each record set:
    for ( count=0; count < searcher.record_sets.length; count++ ) {
        
        // If an error was returned for the record set, display details and return:
        if ( searcher.record_sets[count].error ) {
            var err =  '';
            if ( searcher.record_sets[count].error.error_explanation ) {
                err =  searcher.record_sets[count].error.error_explanation;
            } else {
                err =  'Your request failed. Error code: ' + searcher.record_sets[count].error.error_code;
            }
            alert( err );
            return;  
        } 
        // If not, check to see if individual records have been returned:
        if ( searcher.record_sets[count].records ) {
            // Loop through each record in the record set, and add it to the list below the map,
            //  and populate the infobox text:           
            for (var record_count = 0, rl = searcher.record_sets[count].records.length; record_count < rl; record_count++ ) {
                var record = searcher.record_sets[count].records[record_count];                  
                var anchor = handleRecord(record, start_index_value + record_count);
                var li = document.createElement('li');
                li.appendChild(anchor);
                el.appendChild ( li );
            }
            
        } else {
            // No records have been returned. If a record count has been returned, display it,
            // otherwise display a message noting that no records were returned by the search:        
            var total = searcher.record_sets[count].totalRecordCount; 
            el = document.createElement ('p');
            if ( total  > 0) {
                el.appendChild ( document.createTextNode( 'Total results found: ' + total ) );
            } else {
                el.appendChild ( document.createTextNode( 'No results returned' ) ); 
            }  
            results_returned = 0;
        }
        
    }
    
    //container.appendChild(el);                    
    if ( results_returned == 1 ) {
        mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) ); 
     }  
        
}

function handleRecord ( record, num ) {
    // Create marker text for the infobox for this record:    
    var markerText = '<h1>Result #' + num + '<' + '/h1>'; 
    markerText += '<p>';  
    for ( i = 0, j=0; i < rfs.length; i++ ) {
        if ( record[rfs[i]] ) {
            if ( j > 0) markerText += ', ';
            markerText += record[rfs[i]];
            j++;
        }
    }
    markerText += '<' + '/p>';    
    if ( record.distance ) {
        markerText += '<p>Distance: ' + record.distance.km + ' km, ' + record.distance.miles + ' mi<' + '/p>'
    }
    if ( record.point ) {
        var marker = createMarker( record.point, markerText, num);
        markers.push(marker);
    } 
    // Show the name in our records list. When the name is clicked, open
    //  our info box:    
    var anchor = document.createElement ( 'a' );
    anchor.href = '#';
    anchor.record_id = record.id;
    anchor.appendChild(document.createTextNode(record.name));
    anchor.onclick = function () { openInfoBox ( 'click', marker ); return false; };
    return anchor;

}

function mapHasPanned( eventType, eventTarget, arg1, arg2, arg3 ) {
	if (arg3 == 'goToPosition' && labeled == false) {
	   	var pos = mapviewer.getCurrentPosition(); 
    	addMarker(pos);
	}
    return true;
}

function endSearch( type, target, results, error_code ) {
	if( error_code ) {
		mapviewer.addEventHandler( 'endPan', mapHasPanned );
		if (locationLAT != 0 && locationLON != 0) {
			var pos = new MMLatLon;
			pos.lat = locationLAT;
			pos.lon = locationLON;
			var mapLocation = new MMLocation(pos);
		} else {
			var mapLocation = new MMLocation(new MMAddress({ qs : locationSTR + ', SINGAPORE' }));
		} 
		mapviewer.goToPosition(mapLocation, 17);
	} else {
		var pos = new MMLatLon;
		pos.lat = results[0].records[0].point.lat;
		pos.lon = results[0].records[0].point.lon;
		
		var mapLocation = new MMLocation(pos);
		mapviewer.goToPosition(mapLocation, 17);
		mapviewer.addWidget( new MMSmallPanZoomWidget() );
		
		addMarker(pos);
	}
}*/
//]]> 