// called by the flex app
function mouseOverCommunity(id) {
	if(id !== null){
		$("li[id=_" + id + "]").addClass("selected");
	}
}

// called by the flex app
function mouseOutCommunity(id) {
	if(id !== null){
		$("li[id=_" + id + "]").removeClass("selected");
	}
}

// Create our own, customv Plaats.nl Javascript object
$.plaats = {

	// The location URI
	locationUri: null,

	// The duplicate town names
	duplicateTowns: new Array(),

	currentPOIZipcode: null,

	init: function() {
		// TODO: only initialize shadowbox when necessary

		// Initialize the shadowbox
		if(typeof Shadowbox != 'undefined') {
			var shadowboxOptions = {
				overlayOpacity: 0.1,
				loadingImage: '/images/loading.gif',
				text: {
					cancel:  'Annuleren',
					loading: 'Bezig met laden',
					close:   'Sluiten',
					next:    'Volgende',
					prev:    'Vorige'
				}
			};

			Shadowbox.init(shadowboxOptions);
		}

		// Set-up the auto-completers
		$("#default, #countrySearchLocation").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, onItemSelect: function(selectedItem) {
			// Relocate to the selected community or town
			window.location = $.plaats.formatForUri('/' + selectedItem.extra + '/');
		}});
		$("#where").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, extraParams: { t: 'town' }, onItemSelect: function(selectedItem) {
			$("#where").val(selectedItem.extra);
		}});
		$("#register #registerTown").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, extraParams: { t: 'town' }, onItemSelect: function(selectedItem) {
			$("#register #registerTown").val(selectedItem.extra);
		}});

		$("#userTown").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, extraParams: { t: 'town' }, onItemSelect: function(selectedItem) {
			$("#userTown").val(selectedItem.extra);
		}});

		$("#photoSearch #searchLocation").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, mustMatch: 1, ignoreInitialValue: 1, onItemSelect: function(selectedItem) {
			$("#photoSearch #searchLocation").val(selectedItem.extra.toString());
		}});

		$("#photoSearch #searchPhotographer").autocomplete("/fotografen/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, mustMatch: 1, ignoreInitialValue: 1, onItemSelect: function(selectedItem) {
			$('#photoSearch #searchPhotographer').val(selectedItem.extra);
		}});


		$("#townname").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, extraParams: { t: 'town' }, onItemSelect: function(selectedItem) {
			var formattedName = $.plaats.formatForMap($.plaats.formatForUri(selectedItem.extra.toString()));
			$("#townname").val(formattedName);
			$.plaatsMaps.geocode(formattedName);
		}});

		// handle the community/province mouse over/out
		$("li.communityItem, li.provinceitem").hover(
			function () {
				// get the community id
				var itemData = $(this).attr('id').split('_');

				if(itemData.length == 2){
					var id = itemData[1];

					// call the ajax flex bridge
					var flexApp = FABridge.mapBridge.root();
					flexApp.showHoverOverlay(id);
				}

			},
			function () {
				// get the community id
				var itemData = $(this).attr('id').split('_');

				if(itemData.length == 2){
					var id = itemData[1];

					// call the ajax flex bridge
					var flexApp = FABridge.mapBridge.root();
					flexApp.showNormalOverlay(id);
				}
			}
		);


		// Redraw map if overview type changes
		$('#mapType').change( function()
		{
			// call the ajax flex bridge
			var flexApp = FABridge.mapBridge.root();
			flexApp.setOverviewType($(this).val());
			
			if($(this).val() == 'population') {
				$("#mapDescription").html('Klik op de provincies om naar een gemeente overzicht te gaan. Hoe donkerder de kleur, hoe meer inwoners.');
			} else {
				$("#mapDescription").html('Klik op de provincies om naar een gemeente overzicht te gaan. Hoe donkerder de kleur, hoe meer inwoners per vierkante kilometer');
			}
		});

		// Set-up the auto-completers
		$("#default, #countrySearchLocation").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, onItemSelect: function(selectedItem) {
			// Relocate to the selected community or town
			window.location = $.plaats.formatForUri('/' + selectedItem.extra + '/');
		}});
		$("#where").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, extraParams: { t: 'town' }, onItemSelect: function(selectedItem) {
			$("#where").val(selectedItem.extra);
		}});
		$("#register #registerTown").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, extraParams: { t: 'town' }, onItemSelect: function(selectedItem) {
			$("#register #registerTown").val(selectedItem.extra);
		}});

		$("#userTown").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, extraParams: { t: 'town' }, onItemSelect: function(selectedItem) {
			$("#userTown").val(selectedItem.extra);
		}});


		$("#townname").autocomplete("/locatie/auto-aanvullen/",	{	minChars: 1, maxItemsToShow: 10, matchSubset: 0, extraParams: { t: 'town' }, onItemSelect: function(selectedItem) {
			var formattedName = $.plaats.formatForMap($.plaats.formatForUri(selectedItem.extra.toString()));
			$("#townname").val(formattedName);
			$.plaatsMapsJS.geocode(formattedName +  ', Nederland');
		}});


		// Handle a click on dino link
		$('a.reportToggle').bind('click', function() {
			var display = $(this).parents('div').next('div.reportWrapper:first').css("display");
			$('div.reportWrapper').hide('slow');

			if(display == "none") {
				$(this).parents('div').next('div.reportWrapper').show('fast');
			}

			return false;
		});

		$('ul#marktplaatsCategories a.marktplaatsCategory').bind('click', function (e) {

			$(this).toggleClass('open');
			$(this).toggleClass('close');

			if ($(this).hasClass('open')) {
				$(this).children('span').css('font-weight', 'bold');
			} else {
				$(this).children('span').css('font-weight', 'normal');
			}
            $(this).parent().find('ul.subcategory').toggle();
        	return false;
        });
        
        $('form#marktplaats select#searchLocation').bind('click', function(e) {
            $('form#marktplaats').attr('action', '/' + $(this).val() + '/kaart/marktplaats/')
        });

		// Handle a click on dino link
		$('a.iconDino').bind('click', function() {
			$('#reportWrapper').toggle('slow');

			return false;
		});

		// Handle a click on a tag
		$('#tags a.tag').bind('click', function() {
			$('#searchFreetext').val($(this).html());
			$('#photoSearch').submit();

			return false;
		});

		// Handle a keypress on the tag
		$('#photoinfo #tag, #photoinfo #address').bind('keypress', function(e) {
			if (e.which == 13) {
				$(this).next('input.button').click();
				return false;
			}

			return true;
		});

		// Handle a keypress
		$('#photoinfo #title, #photoinfo #townname, #photoinfo #shotdate').bind('keypress', function(e) {
			if (e.which == 13) {
				return false;
			}

			return true;
		});

		$('#photoinfo #addTag').bind('click', function() {
			var tag = $('#tag').val();
			var tags = $.plaats.parseTags(tag);

			$('#tag').val('');
			var tagcount = tags.length;
			for(var i = 0; i < tagcount; ++i) {
				var newTag = $.trim(tags[i]);
				newTag = newTag.replace(/\'/g,'');
				if(newTag !== '' && !$('#tags' + newTag).val()) {
					$('#tags').append('<li onclick="$(this).remove();"><span class="icon iconRemove">' + newTag + '</span><input id="tags' + newTag + '" type="hidden" name="photo[tags][]" value="' + newTag + '"/></li>');
				}
			}
		});

		// Handle a new file selection
		$('#photo #filename').bind('change', function() {
			$('#original').imgAreaSelect({hide: true});
			$('#images').slideUp(1000);
			$('#loading').show(1000, function() {
				$('#photo').submit();
			});
		});

		// Handle a click on a rotate button
		$('#photoinfo #rotateRight').bind('click', function() {
			return $.plaats.rotateImage(90);
		});

		// Handle a click on a rotate button
		$('#photoinfo #rotateLeft').bind('click', function() {
			return $.plaats.rotateImage(-90);
		});

		// Handle a click on the address search
		$('#photoinfo #searchAddress').bind('click', function() {
			var address = $('#address').val() + ', ' + $('#townname').val() + ', Nederland';
			$.plaatsMapsJS.geocode(address);
		});

		// Create a datepicker for the links end date field
		$.datepicker.setDefaults($.datepicker.regional['nl']);
		$('#searchShotDateStart, #searchShotDateStop, #searchUploadedDateStart, #searchUploadedDateStop, #shotdate').datepicker();

		// Handle navigation links in the results form, which uses post values
		$('div.searchResultsPhotos div.navigation a').bind('click', function() {
			var photoSearchForm = $('form#photoSearch');
			photoSearchForm.attr('action', $(this).attr('href'));
			photoSearchForm.submit();
			return false;
		});

		// Handle clicks on tags in the tag cloud
		$('div#searchTags ul.tags a').bind('click', function() {
			var photoSearch = $('form#photoSearch');

			// Clear all current values
			photoSearch.find('input[type="text"]').each(function(index) {
				$(this).val('');
			});

			photoSearch.attr('action', '/' + $.plaats.locationUri + '/fotos/zoeken/');
			photoSearch.find('input#searchFreetext').val($(this).html());
			photoSearch.submit();
			return false;
		});

		// Handle a submit of the photo search form
		$('#photoSearch #searchSubmit').bind('click', function() {
			var searchLocation = $.trim($('#photoSearch #searchLocation').val());
			var photoSearchForm = $('form#photoSearch');
			if (searchLocation === '') {
				photoSearchForm.attr('action', '/' + $.plaats.locationUri + '/fotos/zoeken/');
			}
			else {
				photoSearchForm.attr('action', '/' + searchLocation + '/fotos/zoeken/');
			}
		});

		$('#vote #voteRating').bind('change', function() {
			if(this.value !== '-') {
				$('#vote').submit();
			}
		});

		// Empty the searchform on click (only if it has the standard value)
		$('#default').bind('click', function() {
			if($('#default').val() === "Vul je zoekterm in"){
				$('#default').val("");
			}
		});

		// Reset the searchform on blur (only if it's empty)
		$('#default').bind('blur', function() {
			if($('#default').val() === ""){
				$('#default').val("Vul een plaats, gemeente, postcode of netnummer in");
			}
		});

		// Catch the clicks on searchtype radiobuttons and display 2 inputfields
		// when searching for companies or persons
		$("#plaats-rsearch").find("input[name=searchtype]").bind("click" ,function() {
			// Get the searchtype
			var searchType = $(this).val();
			$.plaats.switchSearchBox(searchType);
		});

		// Catch the clicks on the searchtabs and display the correct form
		$('div#phonebook ul.tabbedMenu li').bind('click', function() {
			if ($(this).hasClass('active')){
				return false;
			}

			$.plaats.switchTab();
			return false;
		});

		// Catch the submit of the phonebookSearch form
		$('#phonebookSearch').bind('submit', function() {
			// Determine search type
			var searchType = $('#phonebook ul.tabbedMenu li[class*=active] a').html();
			
			if ($('#radioCompany:checked').val() === 'bedrijven') {
				searchType = 'bedrijven';
			} else {
				searchType = 'personen';
			}
			
			if (searchType == null) {
				searchType = $(this).find('#searchType').val();
			}

			var internalSearch = $(this).hasClass('internal');

			searchType = searchType.toLowerCase();
			var trackerSearchType = (searchType == 'bedrijven') ? 'GG' : 'DTG';

			// Get parameters
			var action = $(this).attr('action');
			var what = $(this).find("#searchWhat").val();
			var where = $(this).find("#searchWhere").val();

			what = $.trim(what.replace(/[\/']/g, ''));
			where = $.trim(where.replace(/[\/']/g, ''));
			var testWhat = what.replace(/\-+/g, '');
			var testWhere = where.replace(/\-+/g, '');

			// Check input
			if (what === '' || testWhat === '') {
				alert('U dient een zoekopdracht in te vullen.');
				$("#searchWhat").focus();
				return false;
			}
			if (where === '' || testWhere === '') {
					where = 'Nederland';
					testWhere = 'Nederland';					
			//	alert('U dient een plaatsnaam in te vullen.');
			//	$("#searchWhere").focus();
			//	return false;
			}

			if (internalSearch) {
				var selectedDuplicateTowns = $.plaats.duplicateTowns[where.toLowerCase()];

				// Check if the town is actually a duplicate
				if (selectedDuplicateTowns !== undefined) {
					var selectedDuplicateTownsCount = selectedDuplicateTowns.length;

					var optionsHtml = '<option value="">Kies een plaats...</option>';

					for (var i = 0; i < selectedDuplicateTownsCount; ++i) {
						optionsHtml += '<option value="' + selectedDuplicateTowns[i].formattedname + '"';
						optionsHtml += '>' + selectedDuplicateTowns[i].name + ' (gem. ' + selectedDuplicateTowns[i].communityname + ') (' + selectedDuplicateTowns[i].provinceshort + ')</option>';
					}

					var searchWhereDuplicate = $('#searchWhereDuplicate');
					searchWhereDuplicate.html(optionsHtml);

					// Hide the where item and show the select box
					$('#searchWhere').hide();
					searchWhereDuplicate.show();

					return false;
				}

				// Translate the searchtype
				var translatedType = (searchType === 'bedrijven') ? 'company' : 'person';

				// Log the search request
				$.ajax({url: '/' + $.plaats.locationUri + '/telefoonboek/log/', type: 'POST', data: {'logsearch[location]': where, 'logsearch[type]': translatedType, 'logsearch[query]': what}});

				var url = "/" + $.plaats.locationUri + "/telefoonboek/" + searchType + "/" + what + "/";
				// Don't add the where to the uri if it's the same
				url += ($.plaats.locationUri.toLowerCase() !== where.toLowerCase()) ? where : "";
				url += "/";

				// Show the search results page
				window.location = $.plaats.formatForUri(url);
			}
			else {
				// Track external pageview
				pageTracker._trackPageview('/extern/' + trackerSearchType + '/zoekbox/' + where + '/' + what + '/');

				// Open window to GoudenGids
				$.plaats.openWindow(action + searchType + '/' + what + '/' + where + "/");
			}
			return false;
		});

		// Handle a duplicate town selection
		$('#searchWhereDuplicate').bind('change', function() {
			var where = $(this).val();
			var searchWhere = $("#searchWhere");

			// Check if nothing was selected, if not allow the user to select the input
			if (where === '') {
				searchWhere.show();
				searchWHere.focus();
				return false;
			}

			what = $('#searchWhat').val();
			var testWhat = what.replace(/\-+/g, '');

			// Check input
			if (what === '' || testWhat === '') {
				alert('U dient een zoekopdracht in te vullen.');
				$("#searchWhat").focus();
				return false;
			}

			// Determine search type
			var searchType = $('div#phonebook ul.tabbedMenu li[class*=active] a').html();
			if (searchType === null) {
				searchType = $('div#phonebook ul.tabbedMenu li[class*=active] a span').html();
			}

			searchType = searchType.toLowerCase();

			// Translate the searchtype
			var translatedType = (searchType == 'bedrijven') ? 'company' : 'person';

			// Log the search request
			$.ajax({url: '/nijmegen/telefoonboek/log/', type: 'POST', data: {'logsearch[location]': where, 'logsearch[type]': searchType, 'logsearch[query]': what}});

			// Show the search results page
			window.location = $.plaats.formatForUri("/" + where + "/telefoonboek/" + searchType + "/" + what + "/");
			return false;
		});

		// Handle searches in the search form
		$("#countrySearch").bind("submit", function() {
			var query = $(this).find("#countrySearchLocation").val();
			query = query.replace(/\//g, '');
			query = $.trim(query);
			var test = query.replace(/\-+/g, '');

			// Check input
			//if (query === '' || test === '') {
			//	alert('U dient een plaats of gemeente in te vullen.');
			//	$("#countrySearchLocation").focus();
			//	return false;
			//}

			// Show the search results page
			window.location = $.plaats.formatForUri("/zoekresultaat/" + query + '/');

			return false;
		});

		// Handle searches in the search form
		$("#plaats-rsearch").bind("submit", function() {

			// Get the search type and the query
			var searchType = $(this).find("input[name=searchtype]").val();

			if (searchType === 'location') {
				var query = $(this).find("#default").val();
				query = query.replace(/\//g, '');
				query = $.trim(query);
				var test = query.replace(/\-+/g, '');

				// Check input
				if (query === '' || test === '') {
					alert('U dient een plaats, gemeente, postcode of netnummer in te vullen.');
					$("#default").focus();
					return false;
				}

				// Show the search results page
				window.location = $.plaats.formatForUri("/zoekresultaat/" + query + '/');
			}
			else if (searchType === 'google') {
				var query = $(this).find("#default").val();
				query = query.replace(/\//g, '');
				query = $.trim(query);
				var test = query.replace(/\-+/g, '');

				// Check input
				if (query === '' || test === '') {
					alert('U dient een zoekopdracht in te vullen.');
					$("#default").focus();
					return false;
				}

				// Show the search results page
				window.location = '/zoekresultaat/google/?&cx=015561717511650375913:uqayhmuzq14&cof=FORID:11&q='+query;
			}
			else if (searchType === 'company' || searchType === 'person') {
				var what = $(this).find("#what").val();
				var where = $(this).find("#where").val();
				what = $.trim(what.replace(/[\/']/g, ''));
				where = $.trim(where.replace(/[\/']/g, ''));
				what = $.trim(what);
				where = $.trim(where);
				var testWhat = what.replace(/\-+/g, '');
				var testWhere = where.replace(/\-+/g, '');

				// Check input
				if (what === '' || testWhat === '') {
					alert('U dient een zoekopdracht in te vullen.');
					$("#what").focus();
					return false;
				}
				if (where === '' || testWhere === '') {
					where = 'Nederland';
					testWhere = 'Nederland';					
				//	alert('U dient een plaatsnaam in te vullen.');
				//	$("#where").focus();
				//	return false;
				}

				var translatedType = (searchType == 'company') ? 'bedrijven' : 'personen';

				// Log the search request
				$.ajax({url: '/nijmegen/telefoonboek/log/', type: 'POST', data: {'logsearch[location]': where, 'logsearch[type]': searchType, 'logsearch[query]': what}});

				// Show the search results page
				window.location = $.plaats.formatForUri("/" + where + "/telefoonboek/" + translatedType + "/" + what + "/");
			}

			return false;
		});

		// Handle the adding of a link
		$('#addLink').bind('submit', function() {
			var srcFrame = $('#srcFrame').val();
			var url = $('#infoUrl').val();
			var description = $('#infoDescription').val();

			// Add the image in the parent
			parent.richtexteditorAddLink(srcFrame, url, description);

			// Close the pop-up
			parent.Shadowbox.close();

			return false;
		});

		// Handle the adding of a title
		$('#addTitle').bind('submit', function() {
			var srcFrame = $('#srcFrame').val();
			var title = $('#infoTitle').val();

			// Add the image in the parent
			parent.richtexteditorAddTitle(srcFrame, title);

			// Close the pop-up
			parent.Shadowbox.close();
			return false;
		});

		// Handle the adding of a link
		$('#editReturn').bind('click', function() {

			// Close the pop-up
			parent.Shadowbox.close();
			return false;
		});

		$('#infoTitle, #infoDescription').focus();

		// Handle the click on a link with rel=external
		$('a.external').bind('click', function() {
			window.open($(this).attr('href'));

			return false;
		});

		// Handle refresh of captcha image
		$('#refreshCaptcha').bind('click', function() {
			$.get('/index/captcha', function(data) {
				$('img.captcha').replaceWith(data);
			});

			return false;
		});

		// Handle refresh of captcha image
		$('#refreshCaptcha2').bind('click', function() {
			$.get('/index/captcha', function(data) {
				$('img.captcha').replaceWith(data);
			});

			return false;
		});

		$('#selectOtherLocation').bind('click', function() {
			$('#register').submit();
		});

		/**
		* Delete the item with id 'delete_{$id}'
		*/
		$("a.deleteLink").bind('click', function() {
			if (confirm("Weet je zeker dat je dit item wilt verwijderen?")) {
				var data = $(this).attr('id').split('_');
				var url  = $(this).attr('href');

				if(data.length == 2){
					var content = $(this).parent();
					var id = data[1];

					$.plaats.deleteItem(id, content, url);
				}
			}
			return false;
		});

		/*
		* Make the reactie editable
		*/
		$(".editableReactie").each(function(){
			var id = $(this).attr("id");

			var urlInfo = id.split('_');

			if (urlInfo.length != 2){
				return false;
			}

			var url = '/' + urlInfo[0] + '/fotos/commentaarbewerken/' + urlInfo[1];
			var currentValue = $(this).html();

			$(this).editable(url, {
				type   : 'textarea',
				submit : "Opslaan",
				callback : function(value, settings) {
					if(value !== "error"){
						$(this).html(value);
					} else {
						$(this).html(currentValue);
					}
				}
			});

		});

		$('.editReactie').bind('click', function() {

			var id = $(this).attr("id");
			$('p[id='+id+']').click();

			return false;
		});

		$('#profilePage a.removePhoto').bind('click', function() {
			var removeUrl = $(this).attr('href');
			var lastSlashIndex = removeUrl.lastIndexOf('/');
			var photoId = removeUrl.substr(lastSlashIndex + 1);

			$('#photoRemoveForm #removePhotoId').val(photoId);
		});

		$('a.removePhoto').bind('click', function() {
			if (confirm('Weet je zeker dat je deze foto wilt verwijderen?')) {
				var photoRemoveForm = $('#photoRemoveForm');

				$.ajax({
					url: photoRemoveForm.attr('action'),
					type: 'POST',
					dataType: 'json',
					data: photoRemoveForm.serialize(),
					success: function(jsonData) {
						window.location = jsonData.url;
					}
				});
			}

			return false;
		});

		/**
		* Delete the reactie
		*/
		$("a.deleteReactie").bind('click', function() {
			if (confirm("Weet je zeker dat je deze reactie wilt verwijderen?")) {
				var data = $(this).attr('id').split('_');
				var url  = $(this).attr('href');

				if(data.length == 2){
					var content = $(this).parent().parent();
					var id = data[1];
					$.plaats.deleteItem(id, content, url);
				}
			}
			return false;
		});

		if ($.browser.msie) {
			$('#logo a').bind('mouseover', function() {
				$(this).css('cursor', 'pointer');
			});
		}
	},

	deleteItem: function(id, content, url) {
		$.get(url,{id: id}, function(data) {
			if(data === "success") {
				// remove the line
				content.hide("slow");
			}
		});
	},

	/**
	* Change the layout of the searchbox in the page header
	*/
	switchSearchBox: function(searchType) {

		// Get the searchform legend
		var legend = $("#plaats-rsearch").find("legend");

		// Check the correct radiobutton
		$("#searchtype_" + searchType).attr("checked","checked");

		if (searchType === 'company' || searchType === 'person') {
			var legendText = (searchType === 'company') ? 'Wat' : 'Wie';
			legend.html("<span class=\"what\">" + legendText + "</span><span class=\"where\">Waar</span>");

			$("#default").hide();
			$("#what").show().val($("#default").val()).focus();
			$("#where").show();
		}
		else {
			var legendText = (searchType === 'google') ? 'zoekopdracht' : 'plaats, gemeente, postcode of netnummer';
			legend.html("Vul een " + legendText + " in");

			$("#what").hide().val("");
			$("#where").hide().val("");
			$("#default").show().focus();
		}
	},


	/**
	* Format a string for use in the uri
	*/
	formatForUri: function(str) {
		return str.toLowerCase().replace(/( +|-+)/g, '-').replace(/\'/g, '').replace(/\(/g, '').replace(/\)/g, '');
	},

	/**
	* Format a string for use in the uri
	*/
	formatForMap: function(str) {
		return str.toLowerCase().replace(/-gem.-/g, ', ').replace(/\'/g, '');
	},

	/**
	* Move to a specified URL
	*/
	moveToUrl: function(url) {
		window.location = $.plaats.formatForUri(url);
	},


	/**
	*
	*/
	switchTab: function() {
		// Set the active tab
		$('div#phonebook ul.tabbedMenu li').each(function() {
			$(this).toggleClass('active');
		});

		// Change the form class
		var phonebookForm = $('#phonebookSearch');
		phonebookForm
		.toggleClass('companies')
		.toggleClass('people');

		// Set legend text
		var legend = phonebookForm.find('legend');
		if (legend.html() == 'Bedrijf zoeken') {
			legend.html('Persoon zoeken');
		}
		else {
			legend.html('Bedrijf zoeken');
		}

		// Set search label text
		var searchWhat = phonebookForm.find('label[for=searchWhat]');
		if (searchWhat.html() == 'Wat') {
			searchWhat.html('Wie');
		}
		else {
			searchWhat.html('Wat');
		}

		phonebookForm.find('a').toggle();

		// Show the correct searches
		$('#topsearchPerson,#topsearchCompany').toggle();
	},


	/*
	* Opens popup window
	*/
	openWindow: function(url) {
		gidsWindow = window.open(url, 'gids', 'height=625, width=1010, resizable=yes, scrollbars=yes');
		gidsWindow.focus();
		return gidsWindow;
	},


	/**
	* Disable all links in preview screen
	*/
	disableLinks: function() {
		$('a, input[type=submit], a.external').bind('click', function() {
			return false;
		});
	},

	/**
	* Parse a string for tags
	*/
	parseTags: function(tagStr) {
		var tags = new Array();

		var startIndex = -1;
		var stopIndex = -1;

		do {
			// Find the start index of a double-quote delimited tag
			startIndex = tagStr.indexOf('"', 0);

			if (startIndex !== -1) {
				// Find the stop index of a double-quote delimited tag
				stopIndex = tagStr.indexOf('"', startIndex + 1);

				if (stopIndex !== -1) {
					// Get the tags (without the surrounding double quotes
					tags[tags.length] = tagStr.substr(startIndex + 1, stopIndex - startIndex - 1);

					// Remove the found tag from the tag string to prevent
					// us from processing it more than once
					tagStr = tagStr.substr(0, startIndex) + tagStr.substr(stopIndex + 1);
				}
			}
		} while (startIndex !== -1 && stopIndex !== -1);

		var subtags = tagStr.split(',');
		var subtagsCount = subtags.length;

		// Loop through the comma-splitted tag string
		for (var i = 0; i < subtagsCount; ++i) {
			var subtag = $.trim(subtags[i]);

			// Only add the tag when there is actually a tag :)
			if (subtag !== '') {
				tags[tags.length] = subtag;
			}
		}

		return tags;
	},

	/**
	* Rotate the image
	*/
	rotateImage: function(deg) {
		var p_deg = $('#imageRotation').val();
		p_deg = (parseInt(deg) + parseInt(p_deg));
		if(p_deg > 270) {
			p_deg = 0;
		}
		if(p_deg < 0) {
			p_deg = 270;
		}
		var browserCheck = (document.all) ? 1 : 0;
		if( browserCheck > 0 )
		{
			switch(p_deg) {
				case 0 :
				$('#original')[0].style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';
				break;
				case 90 :
				$('#original')[0].style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=1)';
				break;
				case 180 :
				$('#original')[0].style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=2)';
				break;
				case 270 :
				case -90 :
				$('#original')[0].style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=3)';
				break;
				default :
				$('#original')[0].style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(rotation=0)';
				break;
			}
			var height = $('#original')[0].height;
			var width = $('#original')[0].width;
			var max = 0;
			if(height < width) {
				max = height;
			}
			else {
				max = width;
			}
			$('#imageRotation').val(p_deg);
			$('#original').imgAreaSelect({ x1: 0, y1: 0, x2: max, y2: max, minHeight: 105, aspectRatio: '1:1', resizable: false, onSelectEnd: $.plaats.updateImage});
			return false;
		}
	},

	updateImage: function (img, selection)
	{
		p_deg = $('#imageRotation').val();
		var browserCheck = (document.all) ? 1 : 0;
		if( browserCheck > 0 )
		{
			switch(parseInt(p_deg)) {
				case 0 :
				case 180 :
				$('#imageWidth').val(img.width);
				$('#imageHeight').val(img.height);
				break;
				case 90 :
				case 270 :
				case -90 :
				$('#imageWidth').val(img.height);
				$('#imageHeight').val(img.width);
				break;
			}
		}
		$('#x1').val(selection.x1);
		$('#y1').val(selection.y1);
		$('#x2').val(selection.x2);
		$('#y2').val(selection.y2);
		$('#w').val(selection.width);
		$('#h').val(selection.height);
	}


};


/**
* Add an image to the rich text editor
*/
function richtexteditorAddImage(frameId, url, thumbUrl, description)
{
	// Add the image
	$('#' + frameId).richTextAddImage(url, thumbUrl, description);
}


/**
* Add an image to the rich text editor
*/
function richtexteditorAddLink(frameId, url, description)
{
	// Add the image
	$('#' + frameId).richTextAddLink(url, description);
}


/**
* Add a title to the rich text editor
*/
function richtexteditorAddTitle(frameId, title)
{
	// Add the image
	$('#' + frameId).richTextAddTitle(title);
}

/*
* Remove a tag
*/
function removeTag(id)
{
	$(id).remove();
}

/*
* Hide the selection box and show loading image
*/
function uploadFile()
{
	$('#original').imgAreaSelect({hide: true});
	$('#images').slideUp(1000);
	$('#loading').show(1000, function() {
		$('#photo').submit();
	});
}

function toggleSearchType(option)
{
	var type = option.value;
	document.getElementById('searchType').value = type;
	if(type=='bedrijven')
	{
		document.getElementById('GGLogoTop').style.display = 'block';
		document.getElementById('DTGLogoTop').style.display = 'none';
	} else {
		document.getElementById('GGLogoTop').style.display = 'none';
		document.getElementById('DTGLogoTop').style.display = 'block';
	}
}

// Initialize the Plaats object, which handles all Plaats.nl initialization
$(document).ready(function() {
	$.plaats.init();
});