//<![CDATA[
	/**
	 * Preloading images
	 */
	if (document.images){
		var images = new Array("gui/img/star_select.gif","gui/img/star_noselect.gif","gui/img/star2_select.gif", "gui/img/star2_halfselect.gif", "gui/img/star2_noselect.gif");
		for(i=0; i<images.length; i++){
   		var pic = new Image(10,10);
     		pic.src=images[i];  
		}
   }
	/**
	 * AJAX ACE
	 */
	var controller = new Controller();
	/**
	 * Methods for loading and initialising the map
	 */
	var map;
	var custommap;
	var geocoder;
	var dist;
	var position; // position of click
   var mapcorner;
	var domain = -1;
	function load(){
		createNavigation();
		resizeMap();
   	if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById("mapdiv"));
			map.addControl(new GLargeMapControl());
        	map.addControl(new GOverviewMapControl()); 
        	map.enableScrollWheelZoom();
        	geocoder = new GClientGeocoder();
			dist = new GDirections(map);
			var copyright = new GCopyright(1,  new GLatLngBounds(new GLatLng(40, 0), new GLatLng(60, 10)), 0, "©2007 Google");
			var copyrightCollection = new GCopyrightCollection('Chart');
			copyrightCollection.addCopyright(copyright);
			CustomGetTileUrl=function(a,b){
         	if(b==16 && a.x>=33618 && a.x<=33629 && a.y>=21970 && a.y<=21981){
				 domain = domain + 1;
				 return "http://maps"+((domain%4)+1)+".lagatie.be/"+b+"_"+a.x+"_"+a.y+".gif";
        		} else {
         	 return G_NORMAL_MAP.getTileLayers()[0].getTileUrl(a,b);
        		}
		   }
			var tilelayers = [new GTileLayer(copyrightCollection,0,17)];
      	tilelayers[0].getTileUrl = CustomGetTileUrl;
			tilelayers[0].getCopyright = function(a,b) {
          	return G_NORMAL_MAP.getTileLayers()[0].getCopyright(a,b);
      	}
			custommap = new GMapType(tilelayers, new GMercatorProjection(18), "Old OS");
      	map.addMapType(custommap);
			// check if startlocation is set
        	checkStartLocation();
     	}
 	}
	function checkStartLocation(){
        // does cookie exist?
        var re          = new RegExp('lagatie_start=(.*)');
        var state       = re.exec(document.cookie);
        if(state){
            // read startlocation
            var startlocation = unescape(state[1].split(';')[0]);
            centerToStart(startlocation);
        } else {
            // no cookie, ask startlocation
            askStartLocation();
        } 
    }
    function setStartLocation(startlocatie){
        if(startlocatie==="") startlocatie = "Leuven, Belgium";
        centerToStart(startlocatie);
		  saveStartLocation(startlocatie);
		  hideStartLocation();
    }
    function saveStartLocation(startlocatie){
	 	  var now = new Date();
        var exp = new Date();
        var x = Date.parse(now) + 365*24*60*60*1000; // 1 year from now
        exp.setTime(x);
        str = exp.toUTCString();
        re = '/(\d\d)\s(\w\w\w)\s\d\d(\d\d))/';
        var expires = str.replace(re,"$1-$2-$3");
        document.cookie = 'lagatie_start='+escape(startlocatie)+';path=/;expires='+expires;
    }
    function centerToStart(startlocatie){
        if (geocoder) {
            geocoder.getLatLng(startlocatie, function(point) {
                if (!point){
					 	  startLocationNotFound();
                }else{
                    map.setCenter(point, 16, custommap);
						  // recalculate mapcorner
        				  updateMapCorner();
						  // load datapoints
        				  loadData();
						  // add maplisteners
						  addMapListeners();
                }
            });
        }else{
            // wachten op geocoder
            centerToStart(startlocatie);
        }
   }
	function updateMapCorner(){
   	mapcorner=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
   }
	var clickCallback = function(point){hideAll();};
	var centering = null;
	function addMapListeners(){
		GEvent.addListener(map,"singlerightclick",function(point, src, overlay) {
      	exitEditMode();
      });   
		GEvent.addListener(map,"click",function(overlay,point) {
      	if(!overlay){
				clickCallback(point);
         }
      });
      GEvent.addListener(map, "moveend", function() {
			checkVisibility();
			// showtooltip when done moving
			if(centering!=null){
            showTooltip(centering);
				centering = null;
			}
      });
      GEvent.addListener(map, "move", function() {
			hideAll();
         updateMapCorner();
      });
      GEvent.addListener(map, "zoomend", function() {
			hideAll();
         updateMapCorner();
         // hide buildings on further zoom
         if(map.getZoom()<15){
             for(var i=0; i<buildings.length; i++){
                buildings[i].hide();
             }
         }else{
             for(var i=0; i<buildings.length; i++){
                buildings[i].show();
             }
         }
      });
	} 
	function resizer(){
		resizeMap();
		map.checkResize();
    	//GEvent.trigger(map, 'resize');
	}
	function resizeMap(){
		var height;
		if (self.innerWidth){
			height = self.innerHeight;
		}else if (document.documentElement && document.documentElement.clientWidth){
			height = document.documentElement.clientHeight;
		}else if (document.body){
			height = document.body.clientHeight;
		}
		document.getElementById("mapdiv").style.height = Math.abs(height-210)+"px";//(document.body.clientHeight-190)+"px";
	}
	/**
	 * Object for resolving UTF-8 decoding
	 */
	var Utf8 = {
   	decode : function (utftext) {
      	var string = "";
      	var i = 0;
      	var c = 0;
			var c1 = 0;
			var c2 = 0;
         while ( i < utftext.length ) {
            c = utftext.charCodeAt(i);
            if (c < 128) {
              	string += String.fromCharCode(c);
              	i++;
            }else if((c > 191) && (c < 224)) {
              	c2 = utftext.charCodeAt(i+1);
              	string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
              	i += 2;
            }else {
              	c2 = utftext.charCodeAt(i+1);
              	c3 = utftext.charCodeAt(i+2);
              	string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
              	i += 3;
            }
         }
      	return string;
   	}
   }
	/**
	 * Methods for creating and controlling the navigationmenu and content-loading
	 */
	var buttons = ["Inloggen", "Registreren", "Zoeken", "Routeplanner", "Toevoegen", "Wijzigen", "Vriendenlijst", "Legende", "Over"];
	var templates = ["login", "register", "search", "route", "add", "change", "buddylist", "legend", "about"];
	var callbacks = [null,null,new Function("writeTypes(document.getElementById('search_type'))"),new Function("enableOnLoggedInAndHome(document.getElementById('routebutton'))"),new Function("writeTypes(document.getElementById('add_type')); enableOnLoggedIn(document.getElementById('select_button'))"),writeChange, writeBuddies,writeLegend,getSiteData];
	var loaded = 0;
	function createNavigation(){
		document.getElementById("content").innerHTML = "<form><table class='content-table'><tr><td style='vertical-align: middle; text-align: center; color:#b3cbe8;'>loading</td></tr></table></form>";
		document.getElementById("content").colSpan = buttons.length;
		document.getElementById("separator").colSpan = buttons.length;
		var navigation =document.getElementById("navigation");
	   for(i=0;i<buttons.length;i++){
	      var middle = navigation.insertCell(i);
			middle.id = "but_"+i;
			middle.className = "button";
			middle.style.width = (100/buttons.length)+"%";
			middle.onmouseover = new Function("over("+i+")");
			middle.onmouseout = new Function("out("+i+")");
			middle.onclick = new Function("loadContent("+i+")");
			if(i==0) left="fleft";
			else left="left";
	      if(i==buttons.length-1) right="fright";
			else right="right";
	  		middle.innerHTML = '<table><tr><td class="'+left+'" id="but_'+i+'_l"></td><td class="middle" id="but_'+i+'_m">'+buttons[i]+'</td><td class="'+right+'" id="but_'+i+'_r"></td></tr></table>';
		}
		loadContent(0);
	}
	function over(id){
		overChange(document.getElementById("but_"+id+"_l"));
		overChange(document.getElementById("but_"+id+"_m"));
		overChange(document.getElementById("but_"+id+"_r"));
	}
	function out(id){
		if(loaded!=id){
			outChange(document.getElementById("but_"+id+"_l"));
			outChange(document.getElementById("but_"+id+"_m"));
			outChange(document.getElementById("but_"+id+"_r"));
		}
	}
	function overChange(obj){
		var cl = obj.className;
		var i = cl.indexOf("_hover");
		if(i==-1){
			obj.className = cl+"_hover";
		}
	}
	function outChange(obj){
		var cl = obj.className;
		var i = cl.indexOf("_hover");
		if(i!=-1){
			obj.className = cl.substring(0, i);
		}
	}
	/**
	 * Methods for loading content
	 */
	function loadContent(id){
		document.getElementById("content").innerHTML = "<form><table class='content-table'><tr><td style='vertical-align: middle; text-align: center; color:#b3cbe8;'>loading</td></tr></table></form>";
		prev = loaded;
		loaded = -1;
		out(prev);
		controller.loadContent.call(templates[id]);
      controller.loadContent.result = function(content) {
			if(content!=false){
      		document.getElementById("content").innerHTML = Utf8.decode(content);
				loaded = id;
				over(loaded);
				var callback = callbacks[id];
				if(callback!=undefined && callback!=null) callback();
			}else throwError("404");
   	};
	}
	/**
	 * Methods for login and checking
	 */
	var user = null;
	function User(userid, x, y, username, info, isAdmin){
		this.userid = userid;
		this.x = x;
		this.y = y;
		this.username = username;
		this.info = info;
		this.isAdmin = isAdmin;
		// if home is set, make home
		if(x!=0 || y!=0){
      	this.home = createHome(userid, x, y, username, info);
      }
		// if this person is an admin, show build mode option
		//if(isAdmin=="1" || isAdmin==1) showBuildMode();
		// functions
   	this.hasHome = function(){
      	return (this.home!=undefined && this.home!=null);
    	}
		this.isHome = function(home){
			return (this.home==home);
		}
	}
	function isLoggedIn(){
		return (user!=null);
	}
   function login(username, password){
        if(username==="" || password===""){
            notify("Gelieve een emailadres en paswoord in te geven.");
            return;
        }
        controller.login.call(username, password);
        controller.login.result = function(data) {
            if(data!=false){
					// make userobject
					user = new User(data[0], data[1], data[2], data[3], data[4], data[5]);
					loadPersonal();
					// load the buddies of this person
					loadBuddies();
					// load the personal stars
					updateStars();
				}else notify("Login is niet geslaagd, verkeerd paswoord?");
        };
    }
	 function checkLoggedIn(){
        controller.checklogin.call();
        controller.checklogin.result = function(data) {
            if(data!=false){
					user = new User(data[0], data[1], data[2], data[3], data[4], data[5]);
					loadPersonal();
					// load the buddies of this person
					loadBuddies();
					// load the personal stars
					updateStars();
				}
        };
    }
	 /**
	  * Methods for creating types and icons
	  */
    var types = [];
	 var types_ids = [];
    var buildingTypes = [];
	 var buildingTypes_ids = [];
	 function buildingTypeObj(id, naam, color){
        this.id = id;
        this.naam = naam;
        this.color = color;
    }
    function typeObj(id, naam, icon){
        this.id = id;
        this.naam = naam;
        this.icon = icon;
    }
    function createIcon(url){
        var icon = new GIcon();
        icon.image = "img/"+url;
        icon.iconSize = new GSize(10, 10);
        icon.iconAnchor = new GPoint(5, 5);
        icon.infoWindowAnchor = new GPoint(5, 1);
        return icon;
    }
    function createType(id, naam, url){
        var type = new typeObj(id, naam, createIcon(url));
        types[id] = type;
		  types_ids[types_ids.length] = id;
    }
    function createBuildingType(id, naam, color){
        var type = new buildingTypeObj(id, naam, color);
        buildingTypes[id] = type;
		  buildingTypes_ids[buildingTypes_ids.length] = id;
    }
	 /**
	  * Methods for adding different kinds of markers
	  */
    var locations = [];
	 var locations_ids = [];
    var buildings = [];
    var buddies = [];
	 var buddies_ids = [];
    function createMarker(id, x, y, naam, html, icon){
	 	  // create marker object
        var marker = new GMarker(new GLatLng(y, x),icon);
		  // add properties
        marker.naam = naam;
        marker.info = html;
        marker.id = id;
		  marker.visible = false;
		  // add listeners
        GEvent.addListener(marker,"mouseover", function() {
            showTooltip(marker);
        });        
        GEvent.addListener(marker,"mouseout", function() {
	    		hideTooltip();
        });
		  // add marker to map
        return marker;
    }
	 var selected;
	 function createLocation(id, original, x, y, naam, html, iconid, myscore, score, votes){
	 	  // create marker
        var marker = createMarker(id, x, y, naam, html, types[iconid].icon);
		  // add extra properties
        marker.type = iconid;
		  marker.score = score;
		  marker.myscore = myscore;
		  marker.votes = votes;
		  if(original==0){
		  		marker.original = id;
		  }else{
				marker.original = original;
		  }
		  // add extra listener
        GEvent.addListener(marker, "click", function() {
            showMarkerMenu(marker);
            selected = marker;
				checkSelected();
        });
		  // add to list of locations
        locations[id] = marker;
		  locations_ids[locations_ids.length] = id;
    }
    function createHome(id, x, y, nickname, info){
        var marker = createMarker(id, x, y, nickname, info, createIcon("home.gif"));
		  // immediatly add marker
		  map.addOverlay(marker);
		  return marker;
    }
    function createBuddy(id, x, y, nickname, info){
	 	  // create marker
        var marker = createMarker(id, x, y, nickname, info, createIcon("buddy.gif"));
		   // immediatly add marker
		  map.addOverlay(marker);
		  // add to list of buddies
        buddies[id] = marker;
		  buddies_ids[buddies_ids.length] = id;
    }
    function createBuilding(type, points){
        var line = new GPolyline(points, buildingTypes[type].color, 1,0.7);
        buildings.push(line);
        map.addOverlay(line); 
    }
	 /**
	  * Methods to load data
	  */
	  function loadData(){
        // get types
        controller.getTypes.call();
        controller.getTypes.result = function(results) {
            for(var i=0; i<results.length; i++){
					 // create type
                createType(results[i][0], Utf8.decode(results[i][1]), results[i][2]);
            }
            // read building types
            //getBuildingTypes();
				// buildings been disabled, to messy
				readData();
        };
    }
	 function getBuildingTypes(){
        // get buildingtypes
        controller.getBuildingTypes.call();
        controller.getBuildingTypes.result = function(results) {
            for(var i=0; i<results.length; i++){
                createBuildingType(results[i][0], Utf8.decode(results[i][1]), results[i][2]);
            }
				// read buildings
            readBuildings();
        };
    }
	 function readBuildings(){
        controller.readBuildings.call();
        controller.readBuildings.result = function(results) {
            var id = 0;
            var type = 0;
            var points = [];
            for(var i=0; i<results.length; i++){
                if(id!= 0 && results[i][0]!=id){
                    // starting new building, add previous building to map
                    points.push(points[0]);
                    createBuilding(type, points);
                    points = [];
                }
                points.push(new GLatLng(results[i][3], results[i][2]));
                type = results[i][1];
                id = results[i][0];
            }
            // add last point and draw last building
            // assuming no building of 1 point
            points.push(points[0]);
            createBuilding(type, points);
				// read the data
            readData();
        };
    }
    var alldata;
    var start;
	 var num = 3;
	 var time = 3;
	 function readData(){
	 	  // read all datapoints
        controller.readData.call();
        controller.readData.result = function(results) {
            //alldata = results;
   			//start = 0;
            //window.setTimeout(loadPart, time);
				for(var i=0; i<results.length; i++){
		  			createLocation(results[i][0], results[i][1], Number(results[i][4]), Number(results[i][5]), Utf8.decode(results[i][3]), "", results[i][2], 0, Number(results[i][6]), Number(results[i][7]));
        		}
				checkVisibility();
				// check login
            checkLoggedIn();
        };
    }
	 function updateStars(){
        controller.updateStars.call();
        controller.updateStars.result = function(results) {
	 			for(var i=0; i<results.length; i++){
						var marker = locations[Number(results[i][0])];
						if(marker!=undefined){
							marker.myscore = Number(results[i][1]);
						}
        		}
		  }
	 }
	/* function loadPart(){
        var stand = Math.min(start+num, alldata.length);
        for(var i=start; i<stand; i++){
		  		// if location has not been read, create
            if(locations[alldata[i][0]]===null || locations[alldata[i][0]]===undefined){
					createLocation(alldata[i][0], alldata[i][1], Number(alldata[i][4]), Number(alldata[i][5]), Utf8.decode(alldata[i][3]), "", alldata[i][2], Number(alldata[i][6]), Number(alldata[i][7]), Number(alldata[i][8]));
				}else if(isLoggedIn() && locations[alldata[i][0]].myscore!=Number(alldata[i][6])){ // just logged in, update personal stars
					locations[alldata[i][0]].myscore = Number(alldata[i][6]);
				}
        }
        start = stand;
        if(start!=alldata.length) window.setTimeout(loadPart, time);
    }*/
	 function checkVisibility(){
		  // run over all locations, check if visible or not
		  // note: original design did not even create reference, there was a problem when trying to center to a marker not yet loaded
		  var bounds = map.getBounds();
		  var minX = bounds.getSouthWest().lng();
		  var minY = bounds.getSouthWest().lat();
		  var maxX = bounds.getNorthEast().lng();
		  var maxY = bounds.getNorthEast().lat();
		  var width = maxX-minX;
		  var height = maxY-minY;
		  minX -= width;
		  maxX += width;
		  minY -= height;
		  maxY += height;
		  for(var i=0; i<locations_ids.length; i++){
		  		// check bounds of location and add to map
				var marker = locations[locations_ids[i]];
				if(marker!=null && !marker.visible){
					var x = marker.getPoint().x;
					var y = marker.getPoint().y;
            	if(x<maxX && x>minX && y<maxY && y>minY){
						map.addOverlay(marker);
						marker.visible = true;
					}
				}
        }
	 }
	 function loadBuddies(){
        controller.loadBuddies.call();
        controller.loadBuddies.result = function(results) {
            if(results.length==0 || results!=false){
            	for(var i=0; i<results.length; i++){
            	    createBuddy(results[i][0], results[i][1], results[i][2], results[i][3], results[i][4]);
            	}
				}else throwError("103");
        };
    }
	 /**
	  * Methods for calculating and drawing routes
	  */
	 function Route(id, start, end){
		  // set properties
        this.id = id;
        this.start = start;
        this.end = end;
		  GEvent.addListener(dist,"error", function() {
        	throwError("187/"+dist.getStatus().code);
        });
		  // listener
        GEvent.addListener(dist,"load", function() {
            // clear previous route
           // clearRoute();
            // draw polygon on map
            var distance = (dist.getDistance().meters/1000)+" km";
       		var duration = dist.getDuration().html;
		 		showRouteInfo(distance, duration);
        })
		  // add functions
        this.show = function(){
		  		// calculate route, load is called afterwards
            dist.loadFromWaypoints([this.start,this.end], {getPolyline:true});
        };
    }
	 function clearRoute(){
		 dist.clear();
		 hideRouteInfo();
	 };
	 /**
	  * Methods for panning and centering map
	  */
	 function toHereMarker(marker, drawroute){
        centering = marker;
		  toHerePoint(marker.getPoint(), drawroute);
    }
	 function toHerePoint(point, drawroute){
        if(drawroute && isLoggedIn() && user.hasHome()){
        		var route = new Route(1, user.home.getPoint(), point);
        		route.show();
		  }else{
		  		map.panTo(point, custommap);
		  }
    }
	 /**
	  * Functionality
	  */
	 function register(email, password, username){
        if(email==="" || password==="" ||  username===""){
            notify("Gelieve een emailadres, paswoord en nickname in te geven.");
            return;
        }
        controller.register.call(email, password, username);
        controller.register.result = function(data) {
            if(data===false){
					throwError("102");
				}else if(success=="existing email"){
                notify("Dit emailadres bevindt zich reeds in het systeem.");
            }else{
                user = new User(data[0], 0, 0, data[1], "", false);
                loadPersonal();
            }
        };
    }
	 var routes = [];
	 function search(needle, type){
        if(type=="0" && (needle==="" || needle.length<2)){
            notify("Gelieve een zoekstring in te voeren van minimaal 2 tekens en/of een type te selecteren.");
            return;
        }
        controller.search.call(needle, type);
        controller.search.result = function(results) {
            newSearchResults();
            for(var i=0; i<results.length; i++){
                addRoute(results[i][0], locations[results[i][0]]);
                addSearchResult(results[i][0], results[i][1], Utf8.decode(results[i][2]), results[i][3]);
            }
				checkSearchResults();
        };
    }
	 function addRoute(id, end){
       if(user!= null && user.hasHome() && end!=null && end!=undefined){
            var route = new Route(id, user.home.getPoint(), end.getPoint());
            routes[id] = route;
        }
    }
	 function savePersonal(username, info){
        if(username===""){
            notify("Gelieve een username in te geven.");
            return;
        }
        controller.savePersonal.call(username, info);
        controller.savePersonal.result = function(data) {
            if(data!=false && user!=null){
                user.username = data[0];
                user.info = data[1];
            }else{
                throwError("106");
            }
        };
    }
    function remHomeMeth(){
        controller.remHome.call();
        controller.remHome.result = function(success) {
            if(success){
                map.removeOverlay(user.home);
                user.home=null;
					 checkHome();
            }else{
                throwError("108");
            }
        };
    }
	 function setHomeMeth(point){
        if(!isLoggedIn()) return;
        controller.addHome.call(point.x, point.y);
        controller.addHome.result = function(data) {
            if(data!=false){
                if(user.hasHome()) map.removeOverlay(user.home);
                user.home = createHome(data[0], data[1], data[2], data[3], data[4]);
					 checkHome();
            }else{
                throwError("107");
            }
        };
    }
	 function jumpTo(location, routeOn){
	 		if(location===""){
            notify("Gelieve een adres in te geven.");
            return;
        }
        geocoder.getLatLng(location, function(point) {
                if (!point) {
                	  notify("Het opgegeven adres werd niet teruggevonden.");
                } else {
                    toHerePoint(point, routeOn);
                }
            });
    }
	 var addPoint;
	 function addLocation(type, naam){
        if(type==0 || naam===""){
            notify("Gelieve een naam en type in te geven.");
            return;
        }
        controller.addLocation.call(addPoint.x, addPoint.y, type, naam);
        controller.addLocation.result = function(data) {
            if(data!=false){
                createLocation(data[0], data[0], data[1], data[2], data[3], "", data[4],0,0,0);
                resetAddLocation();
            }else{
                throwError("109");
            }
        };
    }
    function remLocationMeth(marker){
        controller.remLocation.call(marker.id);
        controller.remLocation.result = function(success) {
            if(success){
                locations[marker.id] = null;
                map.removeOverlay(marker);
                hideAll();
            }else{
                throwError("110");
            }
        };
    }
    function moveLocationMeth(marker, point){
        controller.moveLocation.call(marker.id, point.x, point.y);
        controller.moveLocation.result = function(data) {
            if(data!=false){
                createLocation(data[0], data[1], data[4], data[5], data[2], "", data[3], marker.myscore, marker.score, marker.votes);
                map.removeOverlay(marker);
                hideAll();
            }else{
                throwError("112");
            }
        };
    }
	 function changeLocationMeth(marker, type, naam){
        if(naam===""){
            notify("Gelieve een naam en type in te geven.");
            return;
        }
        controller.changeLocation.call(marker.id, naam, type);
        controller.changeLocation.result = function(data) {
            if(data!=false){
                createLocation(data[0], data[1], addPoint.x, addPoint.y, data[2], "", data[3], marker.myscore, marker.score, marker.votes);
                map.removeOverlay(marker);
                hideAll();
            }else{
                throwError("111");
            }
        };
    }
	 function addBuddy(email){
        if(email===""){
            notify("Gelieve een emailadres in te geven.");
            return;
        }
        controller.addBuddy.call(email);
        controller.addBuddy.result = function(data) {
            if(data==false){
                throwError("105");
            }else if(data=="unknown email"){
               notify("Dit email-adres bevindt zich niet in het systeem.");
            }else if(data=="already buddy"){
               notify("Dit email-adres is reeds een vriend van u.");
            }else{
                createBuddy(data[0], data[1], data[2], Utf8.decode(data[3]), Utf8.decode(data[4]));
                addBuddyToList(Utf8.decode(data[3]), data[0]);	 
            }
        };
    }
	 function submitScore(score, marker){
		// submit score and receive new average
		marker.myscore = score;
		controller.submitScore.call(marker.original, score);
      controller.submitScore.result = function(data) {
            if(data==false){
                throwError("155");
            }else{
					 updatestars(Number(data[0][0]), Number(data[0][1]));
					 marker.score = Number(data[0][0]);
					 marker.votes = Number(data[0][1]);
            }
      };
	 }
	 /**
	  * Methods to hande GUI operations
	  */
	 var tooltip;
	 var menu;
	 var markerMenu;
	 var cursor;
	 var selector;
	 function addMenus(){
	 	//tooltip = document.getElementById("tooltip");
      //menu = document.getElementById("menu");
      //cursor = document.getElementById("cursor");
      selector = document.getElementById("selector");
      //markermenu = document.getElementById("markermenu");
      //map.getContainer().appendChild(menu);
      //map.getContainer().appendChild(cursor);
      map.getContainer().appendChild(selector);
      //map.getContainer().appendChild(markermenu);
      //map.getContainer().appendChild(tooltip);
	 }
    function throwError(errorCode){
		notify("Er is een fout opgetreden, verwittig de webmaster. Gelieve de volgende foutcode mee te geven: "+errorCode+".");
	 }
	 function notify(message){
		var notifier = document.createElement('div');
  		notifier.id = 'notifier';
		notifier.className = 'notifier';
  		notifier.innerHTML = '<table><tr class="title"><td class="fleft"></td><td class="middle">Let op</td><td class="fright"></td></tr><tr class="message"><td colspan="3">'+message+'<br><br><input type="button" value="OK" onclick="hideMessage();"></td></tr></table><div>';
		document.body.appendChild(notifier);
	 }
	 function confirm(message, callback){
		var notifier = document.createElement('div');
  		notifier.id = 'notifier';
		notifier.className = 'notifier';
  		notifier.innerHTML = '<table><tr class="title"><td class="fleft"></td><td class="middle">Bent u zeker?</td><td class="fright"></td></tr><tr class="message"><td colspan="3">'+message+'<br><br><input type="button" value="Ja" id="confirm_button">&nbsp;<input type="button" value="Nee" onclick="hideMessage()"></td></tr></table><div>';
		document.body.appendChild(notifier);
		document.getElementById("confirm_button").onclick = callback;
	 }
	 function hideMessage(){
	 	document.body.removeChild(document.getElementById('notifier'));
	 }
	 function getPixel(latlong, ofx, ofy){
		var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(latlong,map.getZoom());
		return pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - mapcorner.x -ofx,- offset.y + mapcorner.y - ofy));
    }
	 function showTooltip(marker){
	 	hideTooltip();
	 	var tooltip = createTooltip(marker);
		map.getContainer().appendChild(tooltip);
		var anchor=marker.getIcon().iconAnchor;
		var width=marker.getIcon().iconSize.width;
		var pixel = getPixel(marker.getPoint(), anchor.x-width, anchor.y).apply(tooltip);
	 }
	 function hideTooltip(){
		if(document.getElementById('tooltip')!=undefined) map.getContainer().removeChild(document.getElementById('tooltip'));
	 }
	 function hideMarkerMenu(){
		if(document.getElementById('markermenu')!=undefined) map.getContainer().removeChild(document.getElementById('markermenu'));
		if(document.getElementById('selector')!=undefined) map.getContainer().removeChild(document.getElementById('selector'));
	 }
	 function hideAll(){
	 	hideTooltip();
		unselectMarker();
	 }
	 function unselectMarker(){
		hideMarkerMenu();
		selected = null;
		checkSelected();
	 }
	 function showMarkerMenu(marker){
	 	unselectMarker();
		var selector = createSelector();
		map.getContainer().appendChild(selector);
		getPixel(marker.getPoint(), 8,8).apply(selector);
		document.getElementById('tooltip').id = "markermenu";
		document.getElementById("mmenu").style.display = "";
		if(isLoggedIn()){
			document.getElementById("averagestars").style.display = "";
			document.getElementById("mystars").style.display = "";
		}
	 }
	 function createTooltip(marker){
	 	var tooltip = document.createElement('div');
  		tooltip.id = 'tooltip';
		tooltip.className = 'tooltip';
	 	var html = "<div class='border'>";
		if(marker.info===""){
      	html += "<div class='tekst'>"+marker.naam+"</div>";
     	}else{
        	html += "<div class='tekst'><a class='naam'>"+marker.naam+"</a><br><a class='info'>"+marker.info+"</a></div>";
     	}
		score = marker.score;
		myscore = marker.myscore;
		if(score!=undefined){
			// average score stars
			html += "<div class='stars1' id='averagestars'";
			if(score==0){
				html += " style='display:none;'";
			}
			html += ">";
			for(i=0; i<5; i++){
				html += "<img id='globalstar"+i+"' src='gui/img/star2_";
				if(i<Math.floor(score)){
  					html += "select";
				}else if(i<Math.round(score)){
  					html += "halfselect";
				}else{
					html += "noselect";
				}
				html += ".gif'>";
			}
			html += "<a class='numstars' id='numvotes'>"+marker.votes+"</a></div>";
			if(isLoggedIn()){
				// my score stars
				html += "<div class='stars2' id='mystars' style='display:none;'>";
				for(i=0; i<5; i++){
					html += "<img id='star"+i+"' src='gui/img/star_";
					if(i<myscore){
  						html += "select";
					}else{
						html += "noselect";
					}
					html += ".gif' onmouseover='starOver("+i+");' onmouseout = 'starOut();' onclick = 'submitScore("+(i+1)+", selected);'>";
				}
				html += "</div>";
			}
		}
		html += "</div><div class='buttons' style='display:none;' id='mmenu'><a href='javascript:toHereMarker(selected, true);'><img src='gui/img/route.gif' width='15' height='15'></a>&nbsp;&nbsp;";
		if(isLoggedIn()){
			html += "<a href='javascript:moveLocation();'><img src='gui/img/verplaatsen.gif' width='15' height='15'></a>&nbsp;&nbsp;<a href='javascript:changeLocation();'><img src='gui/img/wijzigen.gif' width='15' height='15'></a>&nbsp;&nbsp;<a href='javascript:remLocation();'><img src='gui/img/verwijderen.gif' width='15' height='15'></a>";
		}else{
			html += "<img src='gui/img/verplaatsen_dis.gif' width='15' height='15'>&nbsp;&nbsp;<img src='gui/img/wijzigen_dis.gif' width='15' height='15'>&nbsp;&nbsp;<img src='gui/img/verwijderen_dis.gif' width='15' height='15'>";
		}
		html += "</div>";
		tooltip.innerHTML = html;
		return tooltip;
	 }
	 function createSelector(){
	 	var selector = document.createElement('img');
  		selector.id = 'selector';
		selector.src = 'img/selector.gif';
		return selector;
	 }
	 function showRouteInfo(distance, duration){
			 // switch to routinfo tab
			var callback=function(){
				enableOnLoggedInAndHome(document.getElementById('routebutton'));
	 			document.getElementById("contenthelp").style.display = "none";
	 			document.getElementById("routeinformation").style.display = "";
	 			document.getElementById("route_afstand").value = distance;
	 			document.getElementById("route_duur").value = duration;
			}
			callbacks[3] = callback;
			if(loaded!=3){
				loadContent(3);
			}else{
	 			document.getElementById("contenthelp").style.display = "none";
	 			document.getElementById("routeinformation").style.display = "";
			}
	 }
	 function hideRouteInfo(){
	 	 // reset function back to orgininal
		 callbacks[3] = new Function("enableOnLoggedInAndHome(document.getElementById('routebutton'));");
	 	 document.getElementById("routeinformation").style.display = "none";
		 document.getElementById("contenthelp").style.display = "";
	 }
	 function loadPersonal(){
	 	document.getElementById("but_0_m").innerHTML = "Profiel";
		templates[0] = "profile";
		var callback = function(){
			document.getElementById('change_username').value = user.username;
			document.getElementById('change_info').value = user.info;
			checkHome();
		}
		callbacks[0] = callback;
		loadContent(0);
	 }
	 function writeTypes(select){
	 	for(var i=0; i<types_ids.length; i++){
			var type = types[types_ids[i]];
		 	select.options[select.options.length] = new Option(type.naam, type.id);
		}
	 }
	 function writeBuddies(){
		var select = document.getElementById("buddy_select");
		if(buddies_ids.length==0){
			if(isLoggedIn()){
				select.options[0] = new Option("Geen vrienden toegevoegd.");
			}else{
				select.options[0] = new Option("Hiervoor moet u inloggen.");
				document.getElementById("buddy_add_button").disabled = true;
				document.getElementById("buddyadd").disabled = true;
			}
       	select.disabled = true;
		}else{
	 		for(var i=0; i<buddies_ids.length; i++){
				var buddy = buddies[buddies_ids[i]];
			 	select.options[select.options.length] = new Option(buddy.naam, buddy.id);
			}
		}
	 }
	 function writeLegend(){
	 	var tbl = document.getElementById('legendtable');
		var half = Math.ceil(types_ids.length/4);
	 	for(var i=0; i<half; i++){
			var row = tbl.insertRow(tbl.rows.length);
			for(var j=i; j<types_ids.length; j+=half){
				var type = types[types_ids[j]];
  				var cellLeft = row.insertCell(row.cells.length);
  				cellLeft.innerHTML = "<img src='"+type.icon.image+"'>";
  				var cellRight = row.insertCell(row.cells.length);
  				cellRight.innerHTML = type.naam;
			}
		}
	 }
	 function writeChange(){
		if(loaded==5){
		if(selected!=null){
		  // show data
		  document.getElementById("selected").style.display = "";
		  document.getElementById("notselected").style.display = "none";
	 	  var point = selected.getPoint();
	 	  var lat = Math.floor(point.x) + "\u00B0" + Math.floor((point.x-Math.floor(point.x))*60)+ "'"+ Math.floor((((point.x-Math.floor(point.x))*60)-Math.floor((point.x-Math.floor(point.x))*60))*60)+"''";
		  var long = Math.floor(point.y) + "\u00B0" + Math.floor((point.y-Math.floor(point.y))*60)+ "'"+ Math.floor((((point.y-Math.floor(point.y))*60)-Math.floor((point.y-Math.floor(point.y))*60))*60)+"''";
		  document.getElementById("select_button").value = lat+" : "+long;
        var sel = document.getElementById("add_type");
		  var s = 0;
		  for(var i=0; i<types_ids.length; i++){
			  var type = types[types_ids[i]];
		 	  sel.options[sel.options.length] = new Option(type.naam, type.id);
			  if(type.id==selected.type){
			  	  s=i;
			  }
		  }
		  sel.selectedIndex = s;
		  document.getElementById("add_name").value = selected.naam;
		 }
		 }
	 }
	 function newSearchResults(){
	 	document.getElementById("contenthelp").style.display = "none";
	 	document.getElementById("searchresults").style.display = "";
		// clear searchresults
		var tbl = document.getElementById('searchresults_select');
		for(i=tbl.rows.length; i > 0; i--){
      	tbl.deleteRow(i-1); 
		}
	 }
	 function addSearchResult(id, type, naam, score){
		var tbl = document.getElementById('searchresults_select');
		var row = tbl.insertRow(tbl.rows.length);
		var cell0 = row.insertCell(row.cells.length);
		var type = types[type];
  		cell0.innerHTML = "<img src='"+type.icon.image+"' width='10' height='10'>";
		cell0.style.width = "15px";
  		var cell1 = row.insertCell(row.cells.length);
  		cell1.innerHTML = naam;
		cell1.onmouseover = new Function("this.parentNode.className='selectrow_hover';");
		cell1.onmouseout = new Function("this.parentNode.className='selectrow_normal';");
		cell1.onclick = new Function("toHereMarker(locations["+id+"], false);");
  		var cell2 = row.insertCell(row.cells.length);
		html = "";
		if(score!=0){
			for(i=0; i<5; i++){
				html += "<img src='gui/img/star2_";
				if(i<Math.floor(score)){
  					html += "select";
				}else if(i<Math.round(score)){
  					html += "halfselect";
				}else{
					html += "noselect";
				}
				html += ".gif'>";
			}
		}
  		cell2.innerHTML = html;
		cell2.style.width = "70px";
  		var cell3 = row.insertCell(row.cells.length);
  		cell3.innerHTML = "<a href='javascript:toHereMarker(locations["+id+"], true);'><img src='gui/img/route.gif' width='15' height='15'></a>";
		cell3.style.width = "15px";
	 }
	 function checkSearchResults(){
	 	var tbl = document.getElementById('searchresults_select');
		if(tbl.rows.length===0){
			var row = tbl.insertRow(tbl.rows.length);
			var cell0 = row.insertCell(row.cells.length);
			cell0.innerHTML = "Geen resultaten";
		}
	 }
	 function addBuddyToList(naam, id){
    	var buddylist = document.getElementById("buddy_select");
      buddylist.options[buddylist.options.length] = new Option(naam, id);
		document.getElementById("buddyadd").value="";			 
	 }
	 function askStartLocation(){
	 	var startlocation = document.createElement('div');
  		startlocation.id = 'startlocation_div';
		startlocation.className = 'welcome';
  		startlocation.innerHTML = '<table><tr class="title"><td class="fleft"></td><td class="middle">WorldWiki</td><td class="fright"></td></tr><tr class="message"><td colspan="3"><br><a class="quote">“</a>Diffused knowledge immortalizes itself<a class="quote">„</a><br><a style="float: right; font-style: italic; color: #628FC3;">- Sir James Mackintosh -</a><br><br><hr><br>Welkom op deze interactieve wiki. Hier kan <a style="font-weight: bold; color: #628FC3;">iedereen</a> helpen bouwen aan een wereldkaart vol met nuttige plaatsen. Voeg gerust plaatsen toe, nodig uw vrienden uit en gebruik deze kaart!<br><br><br>Waar wilt u beginnen?<br><br><form onsubmit="setStartLocation(document.getElementById(\'startlocation\').value); return false;"><input type="text" id="startlocation" value="Leuven" style="width:50%;">&nbsp;<input type="submit" value="Start" onclick=";" style="width:20%;"><br><font size="-2">(Deze plaats wordt onthouden op deze computer)</font></form></td></tr></table>';
		document.body.appendChild(startlocation);
	 }
	 function hideStartLocation(){
	 	document.body.removeChild(document.getElementById('startlocation_div'));
	 }
	 function startLocationNotFound(){
	 
	 }
	 function enterEditMode(){
	 	document.getElementById("mapdiv").className = "mapdiv_edit";
	 }
	 function exitEditMode(){
	 	clickCallback = function(point){hideAll();};
		document.getElementById("mapdiv").className = "mapdiv";
		if(document.getElementById("select_button")!= undefined) document.getElementById("select_button").disabled = false;
	 }
	 function setHome(){
	 	enterEditMode();
		clickCallback = function(point){
			setHomeMeth(point);
			exitEditMode();
		}
	 }
	 function remHome(){
	 	confirm("Bent u zeker dat u uw locatie wil verwijderen van de kaart?", function(){remHomeMeth(); hideMessage();});
	 }
	 function checkHome(){
	 	if(loaded == 0 && isLoggedIn()){ // logged in and profile is open
			if(user.hasHome()){
				document.getElementById("locationset").style.display = "";
				document.getElementById("locationnotset").style.display = "none";
			}else{
				document.getElementById("locationnotset").style.display = "";
				document.getElementById("locationset").style.display = "none";
			}
		}
	 }
	 function checkSelected(){
	 	if(loaded == 5){ // change is open
		 if(selected!=null && isLoggedIn()){
		   // reload data
			loadContent(5);
		 }else{
		  	document.getElementById("selected").style.display = "none";
		  	document.getElementById("notselected").style.display = "";
		 	if(!isLoggedIn()){
				document.getElementById("message").innerHTML = "Hiervoor moet u ingelogd zijn.";
		 	}else{
				document.getElementById("message").innerHTML = "Selecteer een locatie op de kaart.";
			}
		 }
		}
	 }
	 function enableOnLoggedIn(button){
	 	if(isLoggedIn()){
			button.disabled = false;
		}
	 }
	 function enableOnLoggedInAndHome(button){
	 	if(isLoggedIn() && user.hasHome()){
			button.disabled = false;
		}
	 }
	 function selectLocation(){
	 	enterEditMode();
		document.getElementById("select_button").disabled = true;
		clickCallback = function(point){
			exitEditMode();
			document.getElementById("select_button").disabled = false;
			addPoint = point;
			var lat = Math.floor(point.x) + "\u00B0" + Math.floor((point.x-Math.floor(point.x))*60)+ "'"+ Math.floor((((point.x-Math.floor(point.x))*60)-Math.floor((point.x-Math.floor(point.x))*60))*60)+"''";
			var long = Math.floor(point.y) + "\u00B0" + Math.floor((point.y-Math.floor(point.y))*60)+ "'"+ Math.floor((((point.y-Math.floor(point.y))*60)-Math.floor((point.y-Math.floor(point.y))*60))*60)+"''";
			document.getElementById("select_button").value = lat+" : "+long;
			document.getElementById("add_type").disabled = false;
			document.getElementById("add_button").disabled = false;
			document.getElementById("add_name").disabled = false;
		}
	 }
	 function resetAddLocation(){
	 		document.getElementById("select_button").value = "Selecteer op kaart";
			document.getElementById("add_type").disabled = true;
			document.getElementById("add_type").selectedIndex = 0;
			document.getElementById("add_button").disabled = true;
			document.getElementById("add_name").disabled = true;
			document.getElementById("add_name").value = "";
	 }
	 function getSiteData(){
        controller.getSiteData.call();
        controller.getSiteData.result = function(data) {
            if(data!=false){
                document.getElementById("numusers").innerHTML = data[0][0];
					 document.getElementById("numlocations").innerHTML = data[0][1];
            }else{
                throwError("181");
            }
        };
    }
	 function remLocation(){
	 	if(isLoggedIn()){
	 		hideMarkerMenu();
      	confirm("Bent u zeker dat u '"+Utf8.decode(selected.naam)+"' wil verwijderen?", function(){remLocationMeth(selected); hideMessage();});
		}
    }
    function moveLocation(){
	 	if(isLoggedIn()){
	 		hideMarkerMenu();
	 		enterEditMode();
			clickCallback = function(point){
				exitEditMode();
				moveLocationMeth(selected,point);
			}
		}
    }
	 function changeLocation(){
	 	if(isLoggedIn()){
	 		addPoint = selected.getPoint();
	 		loadContent(5);
		}
	 }
	// score system
	function starOver(id){
		for(i=0; i<5; i++){
			var star = document.getElementById("star"+i);
			if(i<=id){
				star.src = "gui/img/star_select.gif";
			}else{
				star.src = "gui/img/star_noselect.gif";
			}
		}
	}
	function starOut(){
		for(i=0; i<5; i++){
			var star = document.getElementById("star"+i);
			if(i<selected.myscore){
				star.src = "gui/img/star_select.gif";
			}else{
				star.src = "gui/img/star_noselect.gif";
			}
		}
	}
	function updatestars(score, votes){
		for(i=0; i<5; i++){
			var star = document.getElementById("globalstar"+i);
			if(i<Math.floor(score)){
  				star.src = "gui/img/star2_select.gif";
			}else if(i<Math.round(score)){
  				star.src = "gui/img/star2_halfselect.gif";
			}else{
				star.src = "gui/img/star2_noselect.gif";
			}
		}
		document.getElementById("numvotes").innerHTML = votes;
	}
//]]>
