var IBD = {
	map: null,
	basePoint: null,
	mapEvents: {},
	geocoder: null,
	filters: {},
	projects: null,
	markers: {},
	allowedBounds: null,
	canAddProjects: false,
	stages: {'in voorbereiding':'/images/pin_planned.png', 'in uitvoering':'/images/pin_inprogress.png', 'afgerond':'/images/pin_finished.png'},
	initialize: function(elementId, lat, lng, zoom) {
		// initialize the map
		if (this.map === null) {
			this.basePoint = new google.maps.LatLng(lat, lng);
			this.createMap(elementId, this.basePoint, zoom);
		} else {
			this.markers = {};
			this.projects = {};
			this.map.clearOverlays();
		}
	
		// first get our project data
		this.filterAndLoad(this.placeProjects);
	},
	createMap: function(elementId, point, zoom) {
		if (!zoom) zoom = 8;
		/*var options = {
			zoom: zoom,
			center: new google.maps.LatLng(lat, lng),
			navigationControl:true,
			mapTypeControl: false,
			scaleControl: true,
			mapTypes: google.maps.G_PHYSICAL_MAP // TERRAIN, 
		};*/
		this.map = new google.maps.Map2(document.getElementById(elementId));
		//this.map.addMapType(G_PHYSICAL_MAP);
		//this.map.setMapType(G_PHYSICAL_MAP);
		this.map.setCenter(point, zoom);

		this.restrictBounds(50.74, 3.23, 53.59, 7.21);
		this.restrictZoom(7, 20);

		// add control overlays
		$("div.context").each(function(){
			var posVertical = 'top';
			var posHorizontal = 'right';
			if ($(this).css('right') === 'auto') {
				posHorizontal = 'left';
			}
			if ($(this).css('top') === 'auto') {
				posVertical = 'bottom';
			}
			
			IBD.map.addControl(new google.maps.__customControl($(this), posVertical, posHorizontal));
		});
		this.map.addControl(new google.maps.LargeMapControl3D());
		this.map.addControl(new google.maps.ScaleControl());
		
		// load forms for projects when requested. 
		this.addListener(IBD.map.getInfoWindow(), 'maximizeclick', 'createHtmlProjectForm');
		this.addListener(IBD.map.getInfoWindow(), 'maximizeend', 'realignMaximizedWindow');
		
		// hide those horrible shadows!
		this.map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.visibility="hidden"; 
		this.geocoder = new google.maps.ClientGeocoder();
		this.map.enableScrollWheelZoom();
		this.map.enableContinuousZoom();
		
	},
	// places the project pins on the map
	placeProjects: function() {
		// are the projects already loaded? 
		if (IBD.projects === null) {
			alert('projects not yet loaded');
			return false;
		}
	
		// empty the detail pane and prepare it
		$("#contextMain  #projectList").html('<option value="0">&gt; Selecteer project</option>');
		
		// place everything
		for (var key in IBD.projects) {
			var marker = IBD.placeMarker(IBD.projects[key]);
			IBD.updateProjectNodes('create', marker);
		}
		//$("#contextMain #projectList").show();
		//$("#contextMain #projectList li").hide();
		//$("#contextMain #projectList li").serial_fade({speed:40,fade:'in'});		
		IBD.setEditingMode();	
	},
	updateProjectInfo: function(marker) {
		var projectId = marker.projectOb.id;
		$.ajax({async: false, url: "/ajax/projects/find", data: {'projectId': projectId}, success: function(data){
			IBD.projects[projectId] = data.projects[projectId];
			marker.projectOb = data.projects[projectId];
		}, dataType: 'json'});
		if (marker.projectOb.name === '') marker.projectOb.name = 'naamloos';
		return marker.projectOb;
	},
	updateProjectNodes: function(type, marker) {
		var project = marker.projectOb;
		if (type === 'delete') {
			$('#projectList option[value=project'+project.id+']').remove();
			setTimeout(function(){
				IBD.map.removeOverlay(marker);
			}, 500);
		} else if (type === 'modify') {
			project = IBD.updateProjectInfo(marker);
			IBD.map.removeOverlay(marker);
			setTimeout(function(){
				$('#projectList option[value=project'+ project.id+']').text(project.name);
				IBD.placeMarker(project);
			}, 400);
		} else if (type === 'create') {
			var $projectLink = $('<option value="project'+ project.id +'">'+ project.name +"</option>").appendTo("#projectList");

			$('#projectList').bind('change', function(){
				// might have been better to attach markers to projects instead of the other way around. 
				// Then we could have called them more easily (having a project id). Anyway, this will do.. 
				// (but it attaches the event for every new option to the selectbox)
				if (this.options[this.selectedIndex].value === 'project'+ project.id) {
					var infoWindow = IBD.map.getInfoWindow();
					IBD.showBalloon(marker, function(){
						infoWindow.hide();
						IBD.keepControlsVisible();
						setTimeout(function (){
							infoWindow.show();
							infoWindow.maximize();
						}, 300);
					});
				}
			});
		}
		//return marker;
	},
	showProjectDetails: function(projectId) {
		function crossFade($container, classElement, classActive, fadeTime, back, $index, delay) {
			if (back === true) var direction = 'prev';
			else direction = 'next';
			var $cur = $container.find("." + classActive);
			var $next = $container.find("." + classActive)[direction]("." + classElement);
			if ($next.length !== 1) {
				if (back === true) var firstLast = 'last';
				else var firstLast = 'first';
				$next = $container.find("." + classElement + ":"+firstLast);
			}
			$cur.css('z-index', 1).removeClass(classActive);

			$next.addClass(classActive);
			if ($index) {
				var count = 0;
				var $prev = $next;
				while($prev.prev().length > 0) {
					$prev = $prev.prev();
					count++;
				}
				$index.text(++count);
			}

			$cur.stop().animate({'opacity': 0}, fadeTime);
			$next.stop().css('z-index', 2).animate({'opacity': 1}, fadeTime, null, function(){
				if (delay) {
					setTimeout(function(){
						crossFade($container, classElement, classActive, fadeTime, null, null, delay);
					}, delay);
				}
			});
		}
		
		
		var project = IBD.projects[projectId];
		$('#contextMain .infoText').hide();
		$('#contextMain .detailPane').show();

		// first process all images
		if (project.photos.length !== 0) {
			var $dProjectImages = $('<ul class="projectImage"></ul>');
			var i = 0;
			for (key in project.photos) {
				var $imgLink = $('<a></a>').attr({
					href: project.photoPath + project.photos[key].resizedMaxId + '/'+ project.photos[key].filename,
					rel: 'bigView'
				}).append($('<img />').attr({
					src: project.photoPath + project.photos[key].resizedThumbId + '/'+ project.photos[key].filename
				}));
				
				if (project.photos[key].isHighlight == 1) {
					var $imgHighlight = $imgLink;
					$imgLink = $imgLink.clone();
					with ({$curImgLnk: $imgLink}) {
						$imgHighlight.click(function(){
							$curImgLnk.click();
							return false;
						});
					};
					$dProjectImages.prepend($('<li class="projectPhoto"></li>').css('opacity', 0).append($imgLink));
				} else {
					$dProjectImages.append($('<li class="projectPhoto"></li>').css('opacity', 0).append($imgLink));
				}
				i++;
			}
			if (typeof $imgHighlight === 'undefined' && typeof $imgLink !== 'undefined') {
				var $imgHighlight = $imgLink.clone(); // set the last image as highlight
				$imgHighlight.click(function(){
					$imgLink.click();
					return false;
				});
				// prepend as first image in image gallery
				$dProjectImages.prepend($dProjectImages.find('.projectPhoto:last'));
			}
			
			// slimbox the images
			var slimboxOptions = {
				captionAnimationDuration: 1,
				resizeDuration: 1,
				imageFadeDuration: 1,
				initialWidth: 600,
				initialHeight: 400
			}
			$dProjectImages.find('a').slimbox(slimboxOptions);			
			
		} else {
			var $imgHighlight = $('<img />').attr({	src: '/images/default_img.jpg' });
		}
		
		if (project.manager != '') {
			project.leader = project.manager;
		} else {
			project.leader = project.owner.name;
		}
		
		// setting up the information tab
		
		var $tBudget = ''; var $pBudget = ''; var $pNote = ''; var $tLeader = ''; var $pLeader = ''; var $tDescription = ''; var $pDescription = ''; var $tPlanning = ''; var $pPlanning = '';
		
		var $projectName = $('<div class="projectName"></div>').text(project.name);
		var $dProjectImage = $('<div class="projectImage"></div>').append($imgHighlight).append($projectName);
		var $projectDetails = $('<div class="projectDetails"></div>');
		
		if (project.leader != '') {
			$tLeader = $('<h1>Projectleider</h1>');
			$pLeader = $('<p></p>').text(project.leader);
		}

		if (project.description != '') {
			$tDescription = $('<h1>Omschrijving</h1>');
			$pDescription = $('<p></p>').text(project.description);
		}

		if (project.budget != '') {
			$tBudget = $('<h1>(uitvoerings)krediet</h1>');
			$pBudget = $('<p></p>').html(project.budget);
		}

		if (project.note != '') {
			$pNote = $('<p></p>').html('<em>notitie:</em> ' + project.note);
		}
		
		if (project.dateTender != '' || project.dateStart != '' || project.dateDelivery != '') {
			$tPlanning = $('<h1>Planning</h1>');
			$pPlanning = $('<table cellspacing="0"></table>').append(
				'<tr><th>Aanbesteding:</th><td>'+ project.dateTender +'</td></tr>' +
				'<tr><th>Start werkzaamheden:</th><td>'+ project.dateStart +'</td></tr>' +
				'<tr><th>Oplevering:</th><td>'+ project.dateDelivery +'</td></tr>');
		}
		
		$('#contextMain .detailPane .tabs .projectInfo').html('')
			.append($dProjectImage)
			.append($projectDetails
				.append($tDescription).append($pDescription)
				.append($tLeader).append($pLeader)
				.append($tBudget).append($pBudget)
				.append($tPlanning).append($pPlanning)
				.append($pNote)
			);

		$('#contextMain .detailPane .tabs .projectInfo .projectImage').fadeIn(200, function(){
			$('#contextMain .detailPane .tabs .projectInfo .projectName').slideDown(200);
		});
		
		// documentation tab now
		var $documentationTab = $('#contextMain .detailPane .tabs .documentation');
		$documentationTab.html('');
		if (typeof $dProjectImages !== 'undefined') {
			var $tPhotos = $('<h1>Afbeeldingen</h1>');
			$dProjectImages.find('.projectPhoto:first').addClass('active').css('opacity', 1);
			var $currentPhoto = $('<span>1</span>');
			var $prevPhoto = $('<img style="cursor: pointer; margin-right: 10px" src="/images/arrow_left.png" alt="vorige foto" />').click(function(){
				crossFade($dProjectImages, 'projectPhoto', 'active', 500, true, $currentPhoto);	
			});
			var $nextPhoto = $('<img style="cursor: pointer; margin-left: 10px" src="/images/arrow_right.png" alt="volgende foto" />').click(function(){
				crossFade($dProjectImages, 'projectPhoto', 'active', 500, false, $currentPhoto);	
			});
		
			var $photoControls = $('<div class="photoControls"></div>')
				.append($prevPhoto)
				.append($currentPhoto)
				.append(' van ' + $dProjectImages.find('.projectPhoto').length)
				.append($nextPhoto);
				
			$documentationTab
				.append($tPhotos)
				.append($dProjectImages)
				.append($photoControls);
		}
		if (typeof project.documents != 'undefined') {
			var extensions = {
				'archive' : {'zip' : true,'rar' : true,'tar.gz' : true},
				'office' : {'doc' : true, 'docx' : true, 'xls' : true, 'ppt' : true},
				'pdf' : {'pdf' : true},
				'images' : {'png' : true, 'gif' : true, 'jpg' : true, 'jpeg' : true}
			};
			
			var $divDocs = $('<div id="documents"><h1>Documenten</h1></div>');
			var $dDocs = $('<ul class="projectImage"></ul>');
			var docsAvailable = false;
			for (key in project.documents) {
				var extension = '';
				var dot = project.documents[key].filename.lastIndexOf("."); 
				 if( dot != -1) {
					var documentIcon = '';
				 	extension = project.documents[key].filename.substr(dot+1,project.documents[key].filename.length); 
					if (typeof extensions.archive[extension] != 'undefined') {
						documentIcon = '/images/icons/page_white_compressed.png';
					} else if (typeof extensions.office[extension] != 'undefined') {
						documentIcon = '/images/icons/page_white_office.png';
					} else if (typeof extensions.pdf[extension] != 'undefined') {
						documentIcon = '/images/icons/page_white_acrobat.png';
					} else if (typeof extensions.images[extension] != 'undefined') {
						documentIcon = '/images/icons/foto.png';
					} else {
						documentIcon = '/images/icons/page_white.png';
					}
				}
				docsAvailable = true;
				var $docLink = $('<a></a>').attr({
					target: '_blank',
					href: project.filePath + project.documents[key].id + '/'+ project.documents[key].filename
				}).text(project.documents[key].filename);
				$dDocs.append($('<li></li>').append('<img src="'+ documentIcon +'" alt="document icoon" />').append($docLink));
			}
			if (docsAvailable) {
				$divDocs.append($dDocs);
				$documentationTab.append($divDocs);
			}
		}
	},
	restrictBounds: function(latSW, lngSW, latNE, lngNE) {
		var defaultSW = new google.maps.LatLng(latSW, lngSW); 
		var defaultNE = new google.maps.LatLng(latNE, lngNE); 

		IBD.allowedBounds = new google.maps.LatLngBounds(defaultSW,defaultNE);

		IBD.addListener(IBD.map, "infowindowclose", 'checkBounds');
		IBD.addListener(IBD.map, "dragend", 'checkBounds');
		IBD.addListener(IBD.map, "dblclick", 'checkBounds');
		IBD.addListener(IBD.map, "zoomend", 'checkBounds');
		
	},
	setFiltersAndSelections: function(enabled) {		
		// admin settings
		$('#extraControls #moveProjects').unbind().bind('click', function() {
			if (!enabled) { // this is purely to disable events while loading the new selection
				return false;
			}
			if ($(this).hasClass('active')) {
				$(this).removeClass('active');
			} else {
				$(this).addClass('active');
			}
			IBD.setEditingMode();
			return false;
		});
		
		$('#extraControls #placeProject').unbind().bind('click', function(){
			if ($(this).hasClass('active')) {
				$(this).removeClass('active');
				IBD.setEditingMode(false);
				$('#map div:first div:first').css('cursor', 'default');
			} else {
				$(this).addClass('active');
				IBD.setEditingMode(true);
				$('#map div:first div:first').css('cursor', 'crosshair');
			}			
			return false;
		});

		// filters
		$('#cbOwnedOnly, #filterControls select').not('#municipalitySelector').unbind().bind('change', function() {
			if (!enabled) return false;
			IBD.initialize();
		});	
		
		$('#filterControls #municipalitySelector').unbind().bind('change', function(){
			var options = '<option value="0">&gt; Alle afdelingen</option>';
			for (var department in municipalities[$(this).val()]) {
				options += '<option value="'+ department +'">'+ municipalities[$(this).val()][department]['title'] +'</option>';
			}
			$('#filterControls #departmentSelector').attr('disabled','').html(options);
			IBD.initialize();
		});
		
	},
	setEditingMode: function(adding, moving) {
		if (this.mapEvents['click']) {
			google.maps.Event.removeListener(this.mapEvents['click']);
		}
		
		if (adding) {
			this.mapEvents['click'] = this.addListener(this.map,'click', 'newProject');
		} else {
			$('#extraControls #placeProject').removeClass('active');
			$('#map div:first div:first').css('cursor', 'default');			
		}
		
		
		if (moving || $("#extraControls #moveProjects").hasClass('active')) {
			var enableDisable = 'enableDragging';
		} else {
			var enableDisable = 'disableDragging';
		}
		for (var key in this.markers) {
			if (this.markers[key].projectOb.userCanEdit === true) {
				this.markers[key][enableDisable]();
			} else {
				this.markers[key].disableDragging();
			}
		}
	},
	restrictZoom: function(minRes, maxRes) {
		// Get the list of map types
		var mt = IBD.map.getMapTypes();
		// Overwrite the getMinimumResolution() and getMaximumResolution() methods
		for (var i=0; i<mt.length; i++) {
			mt[i].getMinimumResolution = function() {return minRes;}
			mt[i].getMaximumResolution = function() {return maxRes;}
		}		
	},
	placeMarker: function(project) {
		if (project.name === '') {
			project.name = 'naamloos';
		}
		var type = project.status.value
		var lat = project.lat;
		var lng = project.lng;
		var position = new google.maps.LatLng(lat, lng);
		var icon = new google.maps.Icon(G_DEFAULT_ICON, this.stages[type]);
		icon.iconSize = new google.maps.Size(16,24);
		icon.shadow = '/images/pin_shadow.png';
		icon.shadowSize = new google.maps.Size(32,24);
		icon.iconAnchor = new google.maps.Point(0, 18);
		//icon.infoWindowAnchor = new google.maps.Point(6, 0);
		var marker = new google.maps.Marker(position, {
			icon: icon,
			draggable: true
		});
		this.map.addOverlay(marker);
		this.markers[project.id] = marker;

		this.addListener(marker, 'dragstart', 'storeOldLocation');
		this.addListener(marker, 'dragend', 'storeNewLocation');

		marker.projectOb = project;
		IBD.addListener(marker, 'mousedown', 'showBalloon');
		return marker;
		//}
	},
	addListener: function(item, e, action) {
		if (e === 'click' && item === IBD.map) {
			return google.maps.Event.addListener(item, 'click', IBD.newProject);
		} else {
			return google.maps.Event.addListener(item, e, function() {
				IBD[action](item);
			});
		}
	},
	moveTo: function(lat, lng) {
		var location = new google.maps.LatLng(lat, lng);
		this.map.setCenter(location);
	},
	keepControlsVisible: function() {
		if ($("#map").width() > 1100) {
			$("#map #lmc3d, #map #scalecontrol").each(function(){
				$(this).attr('style', $(this).attr('style') + ' visibility: visible !important');
			});
		}
		if ($("#map").width() > 960) {
			// when maximizing the infoWindow all controls are hidden, which we don't always want 
			$("#contextMain").each(function(){
				$(this).attr('style', $(this).attr('style') + ' visibility: visible !important');
			});
		}
	},
	newProject: function(overlay, latLng, overlayLatLng) {
		IBD.setEditingMode(false);
		var position = latLng;
		$.post('ajax/action/addproject?'+$.param(IBD.filters), {
			lat: position.lat(),
			lng: position.lng(),
			status: 3
		}, function(data){
			if (data !== 'add_error') {
				var project = data;
				IBD.projects[project.id] = data;
				var marker = IBD.placeMarker(project);
				IBD.updateProjectNodes('create', marker);
				IBD.addListener(marker, 'click', 'showBalloon');
				IBD.showBalloon(marker, function(){
					IBD.keepControlsVisible();
					var infoWindow = IBD.map.getInfoWindow();
					infoWindow.calledBy = marker;
					infoWindow.maximize();
				});
			} else {
				alert('kon nieuwe locatie niet opslaan.');
			}
		}, 'json');				
	},	
	loadLocations: function(filters, callback) {
		IBD.setFiltersAndSelections(false); // disable filter controls while loading. 
		$.get("/ajax/projects/find", filters, function(data){
			IBD.projects = data.projects;
			if (data.canAddProjects === true) {
				IBD.canAddProjects = true;
			} else {
				IBD.canAddProjects = false;
			}
		
			if (callback) {
				callback();
			}
			IBD.setFiltersAndSelections(true); // enable filter controls again	
			
		}, 'json');
	},
	filterAndLoad: function(callback) {
		if (!callback) var callback = false;
		this.filters.searchString = '';
		this.filters.municipality = $('#filterControls select[name=municipality]').val();
		this.filters.department = $('#filterControls select[name=department]:visible').val();
		this.filters.stages = '';

		this.filters.ownedOnly = $("#filterAdmin #cbOwnedOnly").attr('checked');

		if (this.filters.municipality != 0) {
			var municipalityName = $('#filterControls select[name=municipality] option[value='+ this.filters.municipality +']').text();
			this.geocoder.getLatLng(municipalityName + ', Netherlands', function(point) {
	        	if (point) {
					IBD.map.panTo(point);
				}
			});
		} else {
			//refocus on starting position
			IBD.map.panTo(this.basePoint);
		}
		this.loadLocations(this.filters, callback);
	},	
	zoom: function(item) {
		IBD.map.set_zoom(8);
	},
	alert: function(item) {
		alert('testing an action');
	},
	showBalloon: function(item, callback) {
		var options = {pixelOffset: new google.maps.Size(6, -18)};		
		var infoWindow = IBD.map.getInfoWindow();
		var project = item.projectOb;		
		var title = 'naamloos';
		var description = project.description || '--';
		if (typeof project !== 'undefined' && project !== '') {
			title = project.name;
		}
		$content = $('<div id="infoWindowSummary"><h1>'+ title +'</h1><p>'+ description.substr(0, 140) +'</p></div>');
		if (project.userCanEdit) {
			$("#projectForm").remove();
 			// gmaps moves this node instead of cloning it so we have to recreate it all the time.
			$("#infoWindowContents").append('<div id="projectForm"><div id="formMessage"></div><div id="formContents"></div></div>');
			
			if (callback) {
				options.onOpenFn = callback;
			}
			
			/*var $linkDelete = $('<a href="#">verwijderen</a>').click(function(){
				if (confirm('Weet u zeker dat u dit project ('+ project.name +') wilt verwijderen? ')) {
					$.post('ajax/action/modifyproject', {
						'action': 'action_delete', 
						'project': project.id,
						'owner': project.owner.id
					}, 	function(data){
							if (data == 1) {
								IBD.map.closeInfoWindow();
								IBD.updateProjectNodes('delete', item);
								alert('Het project is verwijderd');
							} else {
								alert('Project kon niet worden verwijderd.');
							}
					});
				} else return false;
			});*/
			//$linkDelete.appendTo($content);			

			var $linkEdit = $('<a style="display: block; margin-top: 10px; margin-left: 160px;" href="#">bewerken</a>').click(function(){
				IBD.keepControlsVisible();
				infoWindow.maximize();
				return false;
			});

			$linkEdit.appendTo($content);

			options.maxContent = $("#projectForm")[0];
			
		}
		/*var $linkDetails = $('<div class="right"><a href="#">meer informatie</a></div>').click(function(){
			IBD.showProjectDetails(project.id);
			return false;
		});
		$linkDetails.appendTo($content);*/
		
		IBD.map.openInfoWindow(item.getLatLng(), $content[0], options);
		IBD.showProjectDetails(project.id);
		IBD.map.getInfoWindow().calledBy = item;
		
	},
	storeNewLocation: function(item) {
		if (confirm('Wilt u de nieuwe locatie opslaan?')) {
			var position = item.getLatLng();
			$.post('ajax/action/modifyproject', {
				'action': 'storePosition',
				'project': item.projectOb.id,
				'owner': item.projectOb.owner.id,
				'lat': position.lat(),
				'lng': position.lng()
			}, function(data){
				if (data === 'modify_error') {
					alert('Kon nieuwe locatie niet opslaan.');
				}
			});
		} else {
			item.setLatLng(item.projectOb.oldPosition);
		}
	},
	storeOldLocation: function(item) {
		item.projectOb.oldPosition = item.getLatLng();
	},
	// If the map position is out of range, move it back
	checkBounds: function(item) {
		if (!IBD.map.getInfoWindow().isHidden()) {
			//infoWindow is opened, don't correct the view
			return false;
		}
		var map = IBD.map;
		// Perform the check and return if OK
		var currentBounds = map.getBounds();
		var cSpan = currentBounds.toSpan(); // width and height of the bounds
		
		//var aberration = 0.2; // this value is a good choice for germany (?!)
		
		var offsetX = cSpan.lng() / (100000); // we need a little border
		var offsetY = cSpan.lat() / (100000);
		var C = map.getCenter(); // current center coords
		var X = C.lng();
		var Y = C.lat();

		// now check if the current rectangle in the allowed area
		var checkSW = new google.maps.LatLng(C.lat()-offsetY,C.lng()-offsetX);
		var checkNE = new google.maps.LatLng(C.lat()+offsetY,C.lng()+offsetX);
		
		if (IBD.allowedBounds.containsLatLng(checkSW) &&
			IBD.allowedBounds.containsLatLng(checkNE)) {
			return; // nothing to do
		}

		var AmaxX = IBD.allowedBounds.getNorthEast().lng();
		var AmaxY = IBD.allowedBounds.getNorthEast().lat();
		var AminX = IBD.allowedBounds.getSouthWest().lng();
		var AminY = IBD.allowedBounds.getSouthWest().lat();

		if (X < (AminX+offsetX)) {X = AminX + offsetX;}
		if (X > (AmaxX-offsetX)) {X = AmaxX - offsetX;}
		if (Y < (AminY+offsetY)) {Y = AminY + offsetY;}
		if (Y > (AmaxY-offsetY)) {Y = AmaxY - offsetY;}

		map.panTo(new google.maps.LatLng(Y,X));
		return;
	}, 
	realignMaximizedWindow: function(infoWindow) {
		if ($('#map').width() < 1260 && $('#map').width() > 960) {
			IBD.map.panBy(new google.maps.Size(-135,0));
		}
	},
	createHtmlProjectForm: function(infoWindow) {
		function deleteFile(filename, fileType, projectId, fileId, $element) {
			if (!confirm('Weet u zeker dat u `'+ filename +'` wilt verwijderen?')) {
				return false;
			}
			
			$.post('ajax/action/modifyproject', {
				action: 'removeFile',
				fileType: fileType,
				project: projectId,
				fileId: fileId
			}, function(responseText){
				if (responseText === 'removeFile_error') {
					alert('kon het bestand niet verwijderen');
				} else {
					$element.remove();
				}
			});
			return false;
		}
		
		function highlightImage(projectId, imageId, $element) {
			$.post('ajax/action/modifyproject', {
				action: 'setHighlight',
				project: projectId,
				imageId: imageId
			}, function(responseText){
				if (responseText !== 'success') {
					alert('Kon de foto niet als highlight instellen');
				} else {
					var $parent = $element.parent();
					var $curHl = $element.parents('td:first').find('span.highlight');
					if ($curHl.length !== 0) {
						var $parentHl = $curHl.parent();
						$parentHl.prepend($element);
						$parent.prepend($curHl);
					} else {
						$element.remove();
						$parent.prepend('<span class="highlight"><img src="/images/icons/highlight_a.gif" alt="primaire afbeelding" /></span>');
					}
				}
			});
			return false;			
		}
		
		var item = infoWindow.calledBy;
		var project = item.projectOb;
		var projectForm = null;
		var parameters = null;
		if (project) {
		 	parameters = 'project='+project.id;
			var form = "/ajax/projects/formedit";
			$('#projectList option[value=project'+ project.id +']').attr('selected', 'selected');
		} else { // currently we never use this, project is already created when showing this form
		 	parameters = IBD.filters;
			var form = "/ajax/projects/formnew";
		}
		$("#formContents").load(form, parameters, function(responseText){
			if (responseText === 'logout_error') {
				// logged out, go to login screen
				window.location = '/beheer?prevLocation='+form+'&prevQs='+project.id;
				return false;
			}
			var $form = $('#formContents form:first');
			
			$form.find('div.filename a.delete').click(function(){
				deleteFile(
					$(this).parent().text(), 
					$(this).attr('rel'), 
					project.id, 
					$(this).parent().attr('id').split('file')[1],
					$(this).parent()
				);
				return false;
			});
			$form.find('div.filename a.setHighlight').click(function(){
				highlightImage(
					project.id, 
					$(this).parent().attr('id').split('file')[1],
					$(this)
				);
				return false;
			});
			
			$form.find('.uploadField').each(function(){
				var $fileUpload = $(this);
				if ($(this).hasClass('image')) {
					var fileType = 'image';
					var allowedExtensions = 'jpg|jpeg||png|gif';
				} else {
					var fileType = 'document';
					var allowedExtensions = 'doc|pdf|xls|ppt|odt|pages|zip|rar|gz|jpg|jpeg|png|gif';
				}
				new AjaxUpload(this, {
					action: 'ajax/action/modifyproject',
					name: this.name,
					// Additional data to send
					data: {
						fileType: fileType,
						project: project.id,
						action: 'upload'
					},
					// Submit file after selection
					autoSubmit: true,
					// The type of data that you're expecting back from the server.
					// Also set server response type to text/html, otherwise it will not work in IE6
					responseType: false,
					// Fired after the file is selected
					// @param file basename of uploaded file
					// @param extension of that file
					onChange: function(file, extension){},
					// Fired before the file is uploaded
					onSubmit: function(file, extension) {
						var regexp = new RegExp('^(' + allowedExtensions + ')$');
						if (!(extension && regexp.test(extension))){
							// extension is not allowed
							alert('Error: invalid file extension');
							// cancel upload
							return false;
						}
						$fileUpload.parent().after('<img class="spinner" src="/images/spinner.gif" />');
					},
					// Fired when file upload is completed
					// WARNING! DO NOT USE "FALSE" STRING AS A RESPONSE!
					onComplete: function(file, response) {
						if (/^\d+$/.test(response)) {
							var $file = $('<div class="filename">'+ file +'&nbsp;</div>');
							var $fileRemove = $('<a class="delete" href="#"><img src="/images/icons/trash.gif" alt="bestand verwijderen" /></a>');
							
							if (fileType === 'image') {
								var $setHighlight = $('<a class="setHighlight" href="#"><img src="/images/icons/highlight.gif" alt="instellen als primaire afbeelding" /></a>');
								$setHighlight.prependTo($file);
								$setHighlight.click(function(){
									highlightImage(
										project.id, 
										response,
										$(this)
									);
								});
							}
							
							$fileRemove.appendTo($file);
							$fileRemove.click(function(){
								deleteFile(
									file, 
									fileType, 
									project.id, 
									response, 
									$(this).parents('div.filename:first')
								);
								return false;
							});
							$fileUpload.parent().next('img.spinner').remove();
							
							$fileUpload.parent().after($file);
						} else if (response == 'size_exceeded') {
							alert('Bestand kon niet worden geüpload: bestanden mogen niet groter zijn dan 3MB voor afbeeldingen en 20MB voor documenten.');
							$fileUpload.parent().next('img.spinner').remove();
						}
					}
				});				
			});


			// set the hidden action field so we know if it's a delete or edit (submit buttons aren't submitted with jquery form..)
			$form.find(':submit').bind('click', function(){
				$form.find('input:hidden[name=action]').val($(this).attr('name'));
				if ($(this).attr('name') === 'action_delete') {
					if (!confirm('Weet u zeker dat u project \'' + project.name + '\' wilt verwijderen?')) {
						return false;
					}
				}
			});

			$form.bind('submit', function() {
	            $(this).ajaxSubmit({
					//dataType: 'json',
	                //target: '#formMessage',
					beforeSubmit: function(formData) {

						// update lat / lng info
						var position = item.getLatLng();
					    for (var i=0; i < formData.length; i++) { 
					        if (formData[i].name === 'lat') { 
								formData[i].value = position.lat();
					        } 
					        if (formData[i].name === 'lng') { 
								formData[i].value = position.lng();
					        }
					    }					
					},
					success: function(responseText) {
						if (responseText === 'delete_success') {
							//project got removed
							$("#projectForm").html('');
							IBD.map.getInfoWindow().restore();
							$('#infoWindowSummary').html('Project \''+ project.name +'\' is verwijderd.');
							IBD.updateProjectNodes('delete', item);
						} else if (responseText === 'modify_success') {
							// update the projectinfo inside the map
							IBD.map.getInfoWindow().restore();
							IBD.updateProjectNodes('modify', item);					
							IBD.showProjectDetails(project.id);
							$('#infoWindowSummary p').text('De wijzigingen voor \''+ item.projectOb.name +'\' zijn opgeslagen.');
						}
					}
				});
	            return false; // <-- important!
	        });
		});
	}
}
