var currentStreetviewPanorama;
var currentLatitude = 51.828053;
var currentLongitude = 4.794867;
var sliedrecht = new google.maps.LatLng(currentLatitude, currentLongitude);
var currentZoom = 0;
var currentHeading = 180; //rotation
var currentPitch = 0;
var currentAddress;
var currentTimer;
var currentMapZoom = 14;
var currentMapTypeID;
var usersLocation;
//route
var directionDisplay;
var directionsService;
var infowindow;
var markerLatLngs = new google.maps.LatLngBounds();
var markersToAdd = new Array
var cityZoomlevel = false;

var mapStyles = {
	'addvision': [
  {
    featureType: "all",
    elementType: "all",
    stylers: [
      { saturation: -74 },
      { hue: "#006eff" },
      { lightness: 37 }
    ]
  },{
    featureType: "road",
    elementType: "all",
    stylers: [
      { hue: "#ffaa00" },
      { saturation: -100 },
      { lightness: -6 }
    ]
  },{
    featureType: "water",
    elementType: "all",
    stylers: [
      { saturation: -9 },
      { lightness: -26 },
      { hue: "#00b2ff" }
    ]
  },{
    featureType: "all",
    elementType: "labels",
    stylers: [
      { visibility: "off" }
    ]
  },{
    featureType: "road",
    elementType: "all",
    stylers: [
      { visibility: "on" }
    ]
  }
]
};
var styledMapOptions = { name: "Skin" };
var theMapType = new google.maps.StyledMapType(mapStyles["addvision"], styledMapOptions);

$.createMap = function(canvas, latitude, longitude, zoom, mapTypeID)
{
	var options = {
		center: new google.maps.LatLng(latitude, longitude),
		zoom: zoom,
		mapTypeId: mapTypeID,
		streetViewControl: false,
		mapTypeControl: false
	}
	var map = new google.maps.Map(document.getElementById(canvas), options);

	infowindow = $.createInfoWindow();

	map.markers = new Array();

	map.mapTypes.set("skin", theMapType);
	map.setMapTypeId("skin");


	return map;
}

$.createStreetViewPanorama = function(canvas, latitude, longitude, zoom, heading, pitch)
{
	var panoramaOptions = {
	  position: new google.maps.LatLng(latitude, longitude),
	  pov: {
		heading: heading,
		pitch: pitch,
		zoom: zoom
	  }
	};
	var streetviewPanorama = new google.maps.StreetViewPanorama(document.getElementById(canvas),panoramaOptions);
	return streetviewPanorama;
}

$.createMarkerMapAndStreetView = function(latitude, longitude, mapToCreate, streetViewToCreate, title, infoWindowContent) {
	$.createMarker(latitude, longitude, mapToCreate, title, infoWindowContent);
	$.createMarker(latitude, longitude, streetViewToCreate, title, infoWindowContent);
}

$.createInfoWindow = function()
{
	infowindow = new google.maps.InfoWindow({

	});
	return infowindow;
}

$.createMarkerImage = function(image, width, height, originX, originY, anchorX, anchorY) {
	var image = new google.maps.MarkerImage(image,
		// This marker is 20 pixels wide by 32 pixels tall.
		new google.maps.Size(width, height),
		// The origin for this image is 0,0.
		new google.maps.Point(originX,originY),
		// The anchor for this image is the base of the flagpole at 0,32.
		new google.maps.Point(anchorX, anchorY)
	);
	return image;
}

$.createMarker = function(latitude, longitude, whereToCreate, title, infoWindowContent, add)
{
	if (latitude != '') {
		if (add == 1) {
			markerLatLngs.extend(new google.maps.LatLng(latitude, longitude));
			icon = $.createMarkerImage('/grafix/pin_googleMaps.png', 30, 52, 0, 0, 0, 30);
			iconShadow = $.createMarkerImage('/grafix/pin_googleMaps_shadow.png', 38, 42, 0, 0, -16, 16)
			flat = false;
		} else {
			if (add == 2) {
				markerLatLngs.extend(new google.maps.LatLng(latitude, longitude));
			}
			icon = $.createMarkerImage('/grafix/pin_googleMaps2.png', 12, 12, 0, 0, 0, 0);
			iconShadow = $.createMarkerImage('/grafix/pin_googleMaps2_shadow.png', 40, 41, 0, 0, -16, 16)
			flat = true;
		}

		var options = {
			clickable: true,
			cursor: 'pointer',
			draggable: false,
			flat: flat,
			icon: icon,
			map: whereToCreate,
			position: new google.maps.LatLng(latitude, longitude),
			shadow: iconShadow,
			//shape: MarkerShape,
			title: title,
			visible: true,
			zIndex: 1
		}
		var marker = new google.maps.Marker(options);
		whereToCreate.markers[whereToCreate.markers.length] = marker;

		if (infoWindowContent != false) {
			google.maps.event.addListener(marker, 'click', function() {
				infowindow.setContent(urldecode(infoWindowContent));
				infowindow.open(whereToCreate,marker);
			});

		}



		return whereToCreate.markers.length-1;
	}
}

$.rotateStreetviewPanorama = function(panorama, zoom, heading, pitch)
{
	heading += 5;
  	panorama.setPov({zoom: zoom, heading:heading, pitch: pitch});
  	currentHeading = heading;
}

$.stopRotateStreetviewPanorama = function(timer)
{
	clearInterval(timer);
}

$.determineUsersPosition = function()
{
	// Try W3C Geolocation (Preferred)
	if(navigator.geolocation) {
    	browserSupportFlag = true;
    	navigator.geolocation.getCurrentPosition(function(position) {
      		usersLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      		currentMap.setCenter(usersLocation);
    	}, function() {
   			$.handleNoGeolocation(browserSupportFlag);
    	});
  		// Try Google Gears Geolocation
  	} else if (google.gears) {
    	browserSupportFlag = true;
    	var geo = google.gears.factory.create('beta.geolocation');
    	geo.getCurrentPosition(function(position) {
      	usersLocation = new google.maps.LatLng(position.latitude,position.longitude);
      	currentMap.setCenter(usersLocation);
    }, function() {
      	$.handleNoGeoLocation(browserSupportFlag);
    });
  	// Browser doesn't support Geolocation
  	} else {
    	browserSupportFlag = false;
    	$.handleNoGeolocation(browserSupportFlag);
  	}
}

$.handleNoGeolocation = function (errorFlag){
    if (errorFlag == true) {
      	usersLocation = sliedrecht;
    } else {
      	usersLocation = sliedrecht;
    }
    currentMap.setCenter(usersLocation);
}

google.maps.Map.prototype.clearMarkers = function() {
    for(var i=0; i < this.markers.length; i++){
        this.markers[i].setMap(null);
    }
    this.markers = new Array();
};

$.calculateRoute = function () {
	var request = {
		origin: $('#start').val(),
		destination: new google.maps.LatLng(currentLatitude, currentLongitude),
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};

	directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			directionsDisplay.setDirections(response);
		}
	});
	return false;
}

$.initMap = function(latitude, longitude, zoom, center)
{
	currentMap = $.createMap('map', latitude, longitude, zoom, google.maps.MapTypeId.ROADMAP);

	for (i = 0; i < markersToAdd.length; i++) {
		$.createMarker(markersToAdd[i].latitude, markersToAdd[i].longitude, currentMap, markersToAdd[i].title, markersToAdd[i].infoWindowContent, markersToAdd[i].add);
	}
	if (center != undefined) {
		currentMap.setCenter(center);
	} else {
		currentMap.setCenter(markerLatLngs.getCenter());
	}
    if (cityZoomlevel != false) {
        currentMap.setZoom(cityZoomlevel);
	} else if (zoom != undefined) {
		currentMap.setZoom(zoom);
    } else {
        currentMap.fitBounds(markerLatLngs);
    }
}

function urldecode (str) {
    // Decodes URL-encoded string
    //
    // version: 1009.2513
    // discuss at: http://phpjs.org/functions/urldecode    // +   original by: Philip Peterson
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      input by: AJ
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // +      input by: travc
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Lars Fischer
    // +      input by: Ratheous    // +   improved by: Orlando
    // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +      bugfixed by: Rob
    // +      input by: e-mike
    // +   improved by: Brett Zamir (http://brett-zamir.me)    // %        note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
    // %        note 2: Please be aware that this function expects to decode from UTF-8 encoded strings, as found on
    // %        note 2: pages served as UTF-8
    // *     example 1: urldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin van Zonneveld!'    // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
        return decodeURIComponent((str+'').replace(/\+/g, '%20'));
}


