﻿var menuIsClicked = false;

// form plugin
(function($) {
	var methods = {
		init : function( options ) {
			var defaults = {
				starIcon : '/gfx/template/required.png',
				starIconOffset : '5px -8px',
				url : '/inc/modules/forms/oForm_submit.asp'
			};
			var settings = $.extend({}, defaults, options);			
			
			return this.each(function() {
				// init
				$(this).bind('submit', methods.submit).data('url',settings.url);
				jQuery.each($("input",$(this)), function() {
					var obj = $(this);
					var type = (obj.hasClass('text')) ? 'text' : false;
					if(type) {
						var defaultVal = (obj.attr('rel')!="") ? obj.attr('rel') : '';
						var currVal = obj.val();
						if(currVal.length==0||defaultVal==currVal) obj.addClass('empty');
						var required = (obj.hasClass('required')) ? true : false;
						if(defaultVal||required) {
							var typeOfRequired = (required) ? 
																(obj.hasClass('email')) ? 'email' : 
																									(obj.hasClass('phone')) ? 'phone' : 'text'
															: '';	
							obj
							.val(defaultVal)
							.bind('focus',methods.focus)
							.bind('blur',methods.blur)
							.data('defaults',{
								defaultVal : defaultVal,
								required : typeOfRequired,
								starIcon : settings.starIcon,
								starIconOffset : settings.starIconOffset
								});
						}
						if(required) methods.addStar(obj);
					}
				});
			});			
		},
		destroy : function( ) {
			return this.each(function(){
			})
			
		},		
		focus : function(e) { 
			if($(this).val()==$(this).data('defaults').defaultVal) $(this).val('').removeClass('empty');
		},
		blur : function(e) {
			if($(this).val()=='') $(this).val($(this).data('defaults').defaultVal).addClass('empty');
			if($(this).data('defaults').required!='') {
				var val = $(this).val();
				switch($(this).data('defaults').required) 
				{
					case 'text':
						if($(this).val()!=""&&$(this).val()!=$(this).data('defaults').defaultVal) {
							methods.removeStar($(this));
						} else {
							methods.addStar($(this));
						}
					break;
					case 'phone':
					break;
					case 'email':
						if(!methods.validateEmail(val)) {
							methods.addStar($(this));
						} else {
							methods.removeStar($(this));
						}
					break;
				}
			}
		},
		validateEmail : function(str) {
			var re = new RegExp(/[a-z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,12}/ig);
			return (str.match(re)) ? true : false;
		},
		addStar : function(obj) {
			if($("img.oStar[rel=" + $(obj).attr('id') + "]").size()==0) {
				var star = $("<img />");
				// star.addClass('star').attr('rel',$(obj).attr('id')).attr('src',$(obj).data('defaults').starIcon)
				// .css({
					// 'top' : $(obj).position().top + 'px',
					// 'left' : $(obj).data('defaults').starIconOffsetLeft + 'px'
				// });
				// $(obj).parents('fieldset:first').append(star);

				star.addClass('oStar').attr('rel',$(obj).attr('id')).attr('src',$(obj).data('defaults').starIcon)
				.position({
					'my' : 'left top',
					'at' : 'right middle',
					'of' : $(obj),
					'offset' : $(obj).data('defaults').starIconOffset
				});
				$("body").append(star);				
				
			}
		},
		removeStar : function(obj) {
			$("img.oStar[rel=" + $(obj).attr('id') + "]").remove();
		},
		trueWidth : function(obj) {
			
			return Math.ceil(
				$(obj).width()+
				parseInt($(obj).css('paddingLeft').replace('px',''))+
				parseInt($(obj).css('paddingRight').replace('px',''))
			);
		},
		submit : function(e) {
			e.preventDefault();
			var post_url = $(this).data('url');
			obj = $(this);
			
			// remove submit 
			$("input[type=submit]").replaceWith("<h3>Vent venligst...</h3>");
			
			var qs = $(this).serialize();
			$.ajax({
				type: "POST",
				url: post_url,
				data: qs,
				success: function(msg) { methods.success(msg,obj); }
			});					
			
		},
		success : function(msg,obj) {
			if(msg.substring(0,1)=="0") {
				// error
				msg = msg.substring(2);
				msg = msg.replace(/_lbr_/ig,"\n -");
				alert(msg);
			} else {
				msg = msg.substring(2);
				$("fieldset",$(obj)).html(msg);
			}
			
		}
	};
	
	$.fn.oForm = function(method) {
	
		if ( methods[method] ) {
			return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
		} else if ( typeof method === 'object' || ! method ) {
			return methods.init.apply( this, arguments );
		} else {
			$.error( 'Method ' +  method + ' does not exist on jQuery.oForm' );
		}    
		
	}
})(jQuery);

// // form plugin


// checkbox plugin
(function($) {
	$.fn.oCheck = function(options) {
		
		var defaults = {
			change : function() {},
			wrapperAttrs : {
				id : '_oCheckWrapper'
			}
		};
		var settings = $.extend({}, defaults, options);
		
		return this.each(function() {
			obj = $(this);
			var wrapper = $("<div />").attr('id',obj.attr('id')+'_oCheckWrapper').addClass('oCheck');
			var label = $("label[for=" + obj.attr('id') + "]");
			label.addClass('oCheck');
			if(obj.attr('checked')) wrapper.addClass('checked');
			wrapper.click(function() {
				if($(this).hasClass('checked')) {					
					$("input:checkbox",$(this)).removeAttr('checked');
					$(this).removeClass('checked');
				} else {
					$("input:checkbox",$(this)).attr('checked','checked');
					$(this).addClass('checked');
				}
				settings.change.call(this);
			});
			label.click(function() {
				wrapper = $("div#" + $(this).attr('for') + settings.wrapperAttrs.id + "]");
				if(wrapper.hasClass('checked')) {					
					$("input:checkbox",wrapper).removeAttr('checked');
					wrapper.removeClass('checked');
				} else {
					$("input:checkbox",wrapper).attr('checked','checked');
					wrapper.addClass('checked');
				}
				settings.change.call(this);
			});

			obj.wrap(wrapper);
			
			
		});
	}
})(jQuery);

// // checkbox plugin

$(function() {
	// boligagent pop
	if($("#createAgent").size()==1) {
		
		$("#createAgent").colorbox({
			href: function() {
				var vejnavn = $("#vejnavn").val();
				var kontantpris_fra = $("#kontantpris_fra").attr('rel');
				var kontantpris_til = $("#kontantpris_til").attr('rel');
				var antalrum_fra = $("#antalrum_fra").attr('rel');
				var antalrum_til = $("#antalrum_til").attr('rel');
				var boligareal_fra = $("#boligareal_fra").attr('rel');
				var boligareal_til = $("#boligareal_til").attr('rel');					
				var grundareal_fra = $("#grundareal_fra").attr('rel');
				var grundareal_til = $("#grundareal_til").attr('rel');	
				var zip_from = $("#zip_from").val();
				zip_from = (isNaN(zip_from)) ? '' : htmlSecure(zip_from);
				var zip_to = $("#zip_to").val();
				zip_to = (isNaN(zip_to)) ? '' : htmlSecure(zip_to);
				var boligtype = "";
				jQuery.each($("input[type=checkbox][class*=boligtype]:checked"), function() {
					boligtype = boligtype + "," + $(this).val();
				});
				if(boligtype!="") boligtype = boligtype.substring(1);
				var bynavn = "";
				jQuery.each($("select#city option:selected"), function() {
					bynavn = bynavn + "," + $(this).html();
				});
				if(bynavn!="") bynavn = bynavn.substring(1);
				var post_url = "" +
				"vejnavn=" + htmlSecure(vejnavn) + 
				"&kontantpris_fra=" + htmlSecure(kontantpris_fra) +
				"&kontantpris_til=" + htmlSecure(kontantpris_til) +
				"&antalrum_fra=" + htmlSecure(antalrum_fra) +
				"&antalrum_til=" + htmlSecure(antalrum_til) +
				"&boligareal_fra=" + htmlSecure(boligareal_fra) +
				"&boligareal_til=" + htmlSecure(boligareal_til) +
				"&grundareal_fra=" + htmlSecure(grundareal_fra) +
				"&grundareal_til=" + htmlSecure(grundareal_til) +
				"&boligtype=" + htmlSecure(boligtype) +
				"&bynavn=" + htmlSecure(bynavn) + 
				"&zip_from=" + zip_from + 
				"&zip_to=" + zip_to;		
				return "/inc/boligfiler/boligagent.asp?" + post_url;
			},
			iframe: true,
			initialWidth: 600,
			initialHeight: 400,
			width: '600px',
			height: '400px',
			opacity: 0.7,
			transition: 'none'
		});		

	}	

	// salgsvurdering pop-up
	if($(".gratis-salgsvurdering").size()==1) {
		if(ignorePop) {
			$(".gratis-salgsvurdering").colorbox({
				iframe: true,
				initialWidth: 600,
				initialHeight: 430,
				width: '600px',
				height: '430px',
				opacity: 0.7,
				transition: 'none',
				onClosed: function() {
					$.ajax({ type: "POST",url: "/inc/boligfiler/ajax.asp",data: "cmd=stopPoppin"});					
				}
			});		
		} else {
			$(".gratis-salgsvurdering").colorbox({
				iframe: true,
				initialWidth: 600,
				initialHeight: 430,
				width: '600px',
				height: '430px',
				opacity: 0.7,
				open: true,
				transition: 'none',
				onClosed: function() {
					$.ajax({ type: "POST",url: "/inc/boligfiler/ajax.asp",data: "cmd=stopPoppin"});					
				}
			});
		}
	}
	// if panorama
	if(location.hash.indexOf('panorama')>0) {
		$("ul.pop li[rel=panorama]").addClass('active');
		$(".image_controls").hide();
		$("div#shadow div.active").hide().removeClass('active');
		$("div#shadow div#panorama").show().addClass('active');
	}
	setTimeout("$('#logo3').fadeOut(3000,function() { $('#logo').fadeIn(3000); });",2000);
	
	$("form.oForm").oForm();
	$("input.oCheck[type=checkbox]").oCheck({
		change: function() {  
			clearTimeout(search_timer);
			search_timer = setTimeout("search_cases_numbers()",search_timeOut);
		}
	});
	
	$("a.external").bind("click", function() {
		
		window.open($(this).attr('href'));
		return false;
		
	});
	
	$("table#bottommenu td, ol#leftMenu li").bind("click", function() {
		if(menuIsClicked==false) {
			menuIsClicked = true;
			var linkObj = $(this).find("a");
			if($(linkObj).attr('href')) {
				if($(linkObj).attr('href').length>0) {
					if($(linkObj).hasClass('external')) {
						window.open($(linkObj).attr('href'));
					} else {
						document.location.href = $(linkObj).attr('href');
					}
				}
			}
		}	
	});
	
	// front begin
	if($("body").attr('id')=='front') {
		// wait 5 seconds before starting front slide show, so the images can load from esoft
		setTimeout("startFrontShow()",5000);
	}
	// front end
	
	// sag begin
	if($("body").attr('id')=='sag') {
		

		$("ul.casebuttons li").disableSelection();
		// init toggle view button
		$("a.toggle_image_view").click(function(e) {
			e.preventDefault();
			toggleView($(this));
		});
		// init navigational direction
		directional_nav($("ul#caseimages li"));
		
		if($("div#shadow div#images ul.images li").size()>1) {
			// init image changers
			$('#caseimages')
			.anythingSlider({
				width          : 950,
				height         : 666,
				hashTags	   : false,
				startStopped   : true,
				buildNavigation : false,
				buildArrows : false
			});

			$("#case_images_left").click(function(e) {
				e.preventDefault();
				$('#caseimages').data('AnythingSlider').goBack(); 
			});

			$("#case_images_right").click(function(e) {
				e.preventDefault();
				$('#caseimages').data('AnythingSlider').goForward(); 
			});	
		}
		
		if($("div#shadow div#plantegninger ul.images li").size()>1) {
			$('#planimages')
			.anythingSlider({
				width          : 950,
				height         : 425,
				hashTags	   : false,
				startStopped   : true,
				buildNavigation : false,
				buildArrows : false
			});

			$("#plan_images_left").click(function(e) {
				e.preventDefault();
				$('#planimages').data('AnythingSlider').goBack(); 
			});

			$("#plan_images_right").click(function(e) {
				e.preventDefault();
				$('#planimages').data('AnythingSlider').goForward(); 
			});			
		}

		
		// init case buttons
		$("ul.casebuttons li").click(function(e) {
			location.hash = "";
			$("img.oStar").remove();
			$("ul.pop li.active").removeClass('active');
			$("ul.casebuttons li.active").removeClass('active');
			$(this).addClass('active');
			if($(this).hasClass('pop')) {
				// find and show pop - or hide it
				var $pop = $("#pop_" + $(this).attr('rel'));
				// place it
				$pop.css({
					'left' : ($(this).position().left)+'px',
					'top' : ($(this).offset().top-$pop.height()-30) + 'px',
					'height' : 'auto'
				});
				// $pop.position({
					// my : 'left bottom',
					// at : 'left top',
					// of : $(this),
					// offset : '0 0'
				// });
				if($pop.css('display')=='block') {
					$pop.hide();
				} else {
					$pop.show();
				}
			} else {
				if($("div#images").hasClass('expanded')) toggleView();
				// not a pop menu - take rel and show corresponding div with same id as rel
				
				// hide all pops
				$("ul.pop").hide();
				var attrRel = $(this).attr('rel');

				switch(attrRel) {
					case "boliginfo":
						if($("div#shadow div#" + $(this).attr('rel')).hasClass('active')) {
							$("div.info",$("div#shadow div#" + $(this).attr('rel'))).toggle();
						} else {
							$("div#shadow div.active").hide().removeClass('active');
							$("div.info",$("div#shadow div#" + $(this).attr('rel'))).show();
							$("div#shadow div#" + $(this).attr('rel')).show().addClass('active');				
						}
						break;
					case "kort":
						$("div#shadow div.active").hide().removeClass('active');
						$("div#shadow div#" + $(this).attr('rel')).show().addClass('active');				
						if(!geocoder) initializeMap();
						break;						
					case "dokumenter":
						$("div#shadow div.active").hide().removeClass('active');
						$("div#shadow div#" + $(this).attr('rel')).show().addClass('active');				
						break;				
					case "lignende":
						$("div#shadow div.active").hide().removeClass('active');
						$("div#shadow div#" + $(this).attr('rel')).show().addClass('active');				
						break;				
					case "fremvisning":
						if($("div#shadow div#" + attrRel).hasClass('active')) {
							$("div.info",$("div#shadow div#" + attrRel)).toggle();
							$("div#shadow div#" + attrRel).removeClass('active');
							$("div.ajax",$("div#shadow div#" + attrRel)).remove();
						} else {
							$("div.info",$("div#shadow div#" + attrRel)).show();
							$("div#shadow div.active").hide().removeClass('active');
							var targetDiv = $("div#shadow div#" + attrRel);
							targetDiv.show().addClass('active');
							$.ajax({
								type: "POST",
								url: "/inc/boligfiler/ajax.asp",
								data: "cmd=" + attrRel + "&sagsnr=" + $sagsnr,
								success: function(msg){	
									$("div.ajax",targetDiv).remove();
									var div = $("<div />");
									targetDiv.append(div);
									div.css({
										'width' : '320px',
										'position' : 'absolute',
										'top' : '0',
										'left' : '0',
										'zIndex' : '10'
									}).addClass('ajax');
									div.html(msg);
									$("form.oForm",div).oForm();
									
								}	
							});	
						}
						break;		
					case "givbud":
						if($("div#shadow div#" + attrRel).hasClass('active')) {
							$("div.info",$("div#shadow div#" + attrRel)).toggle();
							$("div#shadow div#" + attrRel).removeClass('active');
							$("div.ajax",$("div#shadow div#" + attrRel)).remove();
						} else {
							$("div.info",$("div#shadow div#" + attrRel)).show();
							$("div#shadow div.active").hide().removeClass('active');
							var targetDiv = $("div#shadow div#" + attrRel);
							targetDiv.show().addClass('active');
							$.ajax({
								type: "POST",
								url: "/inc/boligfiler/ajax.asp",
								data: "cmd=" + attrRel + "&sagsnr=" + $sagsnr,
								success: function(msg){	
									$("div.ajax",targetDiv).remove();
									var div = $("<div />");
									targetDiv.append(div);
									div.css({
										'width' : '320px',
										'position' : 'absolute',
										'top' : '0',
										'left' : '0',
										'zIndex' : '10'
									}).addClass('ajax');
									div.html(msg);
									$("form.oForm",div).oForm();
									
								}	
							});			
						}
						break;
					case "vurdering":
						if($("div#shadow div#" + attrRel).hasClass('active')) {
							$("div.info",$("div#shadow div#" + attrRel)).toggle();
							$("div#shadow div#" + attrRel).removeClass('active');
							$("div.ajax",$("div#shadow div#" + attrRel)).remove();
						} else {
							$("div.info",$("div#shadow div#" + attrRel)).show();					
							$("div#shadow div.active").hide().removeClass('active');
							var targetDiv = $("div#shadow div#" + attrRel);
							targetDiv.show().addClass('active');
							$.ajax({
								type: "POST",
								url: "/inc/boligfiler/ajax.asp",
								data: "cmd=" + attrRel,
								success: function(msg){	
									$("div.ajax",targetDiv).remove();
									var div = $("<div />");
									targetDiv.append(div);
									div.css({
										'width' : '320px',
										'position' : 'absolute',
										'top' : '0',
										'left' : '0',
										'zIndex' : '10'
									}).addClass('ajax');
									div.html(msg);
									$("form.oForm",div).oForm();
									
								}	
							});	
						}							
						break;						
					case "maegler":
						if($("div#shadow div#" + $(this).attr('rel')).hasClass('active')) {
							$("div.info",$("div#shadow div#" + $(this).attr('rel'))).toggle();
						} else {					
							$("div#shadow div.active").hide().removeClass('active');
							$("div#shadow div#" + $(this).attr('rel')).show().addClass('active');				
						}
						break;
						
				}
				// hide image controls
				$(".image_controls").hide();
			}
		});

		$("ul.pop li").click(function(e) {
			if($("div#images").hasClass('expanded')) toggleView();
			$("li.active",$(this).parent('ul')).removeClass('active');
			$(this).addClass('active');
			$(this).parent('ul').hide();
			switch($(this).attr('rel')) {
				case "panorama":
					$(".image_controls").hide();
					$("div#shadow div.active").hide().removeClass('active');
					$("div#shadow div#" + $(this).attr('rel')).show().addClass('active');
					location.hash = "panorama";
					break;			
				case "plantegninger":
					$(".image_controls").hide();
					$("div#shadow div.active").hide().removeClass('active');
					$("div#shadow div#" + $(this).attr('rel')).show().addClass('active');
					if($("div#shadow div#" + $(this).attr('rel') + " ul.images li").size()<=1) { 
						$("#plan_image_controls").hide();
					} else {
						$("#plan_image_controls").show();
					}
					break;
				case "images":
					$(".image_controls").hide();
					$("div#shadow div.active").hide().removeClass('active');
					$("div#shadow div#" + $(this).attr('rel')).show().addClass('active');				
					if($("div#shadow div#" + $(this).attr('rel') + " ul.images li").size()<=1) { 
						$("#case_image_controls").hide();
					} else {
						$("#case_image_controls").show();
					}
					break;	
			}
		});		
		refreshLignende();
		if($("div#shadow div.active ul.images li").size()>1) $("#case_image_controls").show();
		
	}
	
	// sag end
	
	// search begin
	if($("body").attr('id')=='search') {
		$("#resultsOrderBtn").val('Sorter efter: ' + $("ul#pop_sorter li.active").html()).attr('rel',$("ul#pop_sorter li.active").attr('rel'));
		$("#resultsOrderBtn").click(function(e) {
			e.stopPropagation();
			$("ul.pop li.active").removeClass('active');
			// find and show pop - or hide it
			var $pop = $("#pop_sorter");
			// place it
			
			$pop.css({
				'left' : ($(this).position().left)+5+'px',
				'top' : ($(this).position().top+$(this).height()+15)+'px',
				'height' : ($pop.height()+15) + 'px',
				'zIndex' : '9999999'
			});
			if($pop.css('display')=='block') {
				$pop.hide();
				$("body").unbind('click.pop');
			} else {
				$pop.show();
				$("body").bind('click.pop',function() { $pop.hide(); });
			}
		});
		$("ul#pop_sorter li").click(function(e) {
			e.stopPropagation();
			$("li.active",$(this).parent('ul')).removeClass('active');
			$(this).addClass('active');
			$(this).parent('ul').hide();
			var orderBy = $(this).attr('rel');
			$("#resultsOrderBtn").val('Sorter efter: ' + $(this).html()).attr('rel',orderBy);
			clearTimeout(search_timer);
			search_timer = setTimeout("search_cases_newOrder()",search_timeOut);			
		});			
		// init search submit 
		$("#showResultsBtn").click(function() {
			search_cases();
		});
		$("#showMoreResultsBtn").click(function() {
			$rr1 = $rr2+1;
			$rr2 = $rr2+more_results_number;
			search_cases();			
		});
		// init sliders
		$( "#slider_price" ).slider({
			range: true,
			min: 0,
			max: 10000000,
			step: 25000,
			values: [ $("#kontantpris_fra").attr('rel'), $("#kontantpris_til").attr('rel') ],
			slide: function( event, ui ) {
				$( "#kontantpris_fra" ).html(formatCurrency(ui.values[0],"")+" kr").attr('rel',ui.values[0]);
				$( "#kontantpris_til" ).html(formatCurrency(ui.values[1],"")+" kr").attr('rel',ui.values[1]);
				clearTimeout(search_timer);
			},
			change: function(event,ui) {
				clearTimeout(search_timer);
				search_timer = setTimeout("search_cases_numbers()",search_timeOut);
			}
		});
		$( "#kontantpris_fra" ).html(formatCurrency($( "#slider_price" ).slider( "values",0 ),"")+" kr").attr('rel',$( "#slider_price" ).slider( "values",0 ));
		$( "#kontantpris_til" ).html(formatCurrency($( "#slider_price" ).slider( "values",1 ),"")+" kr").attr('rel',$( "#slider_price" ).slider( "values",1 ));

		$( "#slider_rooms" ).slider({
			range: true,
			min: 0,
			max: 20,
			step: 1,
			values: [ $( "#antalrum_fra" ).attr('rel'), $( "#antalrum_til" ).attr('rel') ],
			slide: function( event, ui ) {
				$( "#antalrum_fra" ).html(ui.values[0]).attr('rel',ui.values[0]);
				$( "#antalrum_til" ).html(ui.values[1]).attr('rel',ui.values[1]);
				clearTimeout(search_timer);
			},
			change: function(event,ui) {
				clearTimeout(search_timer);
				search_timer = setTimeout("search_cases_numbers()",search_timeOut);
			}
		});
		$( "#antalrum_fra" ).html($( "#slider_rooms" ).slider( "values",0 )).attr('rel',$( "#slider_rooms" ).slider( "values",0 ));
		$( "#antalrum_til" ).html($( "#slider_rooms" ).slider( "values",1 )).attr('rel',$( "#slider_rooms" ).slider( "values",1 ));

		$( "#slider_areal" ).slider({
			range: true,
			min: 0,
			max: 2000,
			step: 10,
			values: [ $( "#boligareal_fra" ).attr('rel'), $( "#boligareal_til" ).attr('rel') ],
			slide: function( event, ui ) {
				$( "#boligareal_fra" ).html(formatCurrency(ui.values[0],"")+" m<sup>2</sup>").attr('rel',ui.values[0]);
				$( "#boligareal_til" ).html(formatCurrency(ui.values[1],"")+" m<sup>2</sup>").attr('rel',ui.values[1]);
				clearTimeout(search_timer);
			},
			change: function(event,ui) {
				clearTimeout(search_timer);
				search_timer = setTimeout("search_cases_numbers()",search_timeOut);
			}
		});
		$( "#boligareal_fra" ).html(formatCurrency($( "#slider_areal" ).slider( "values",0 ),"")+" m<sup>2</sup>").attr('rel',$( "#slider_areal" ).slider( "values",0 ));
		$( "#boligareal_til" ).html(formatCurrency($( "#slider_areal" ).slider( "values",1 ),"")+" m<sup>2</sup>").attr('rel',$( "#slider_areal" ).slider( "values",1 ));

		$( "#slider_grundareal" ).slider({
			range: true,
			min: 0,
			max: 300000,
			step: 100,
			values: [ $( "#grundareal_fra" ).attr('rel'), $( "#grundareal_til" ).attr('rel') ],
			slide: function( event, ui ) {
				$( "#grundareal_fra" ).html(formatCurrency(ui.values[0],"")+" m<sup>2</sup>").attr('rel',ui.values[0]);
				$( "#grundareal_til" ).html(formatCurrency(ui.values[1],"")+" m<sup>2</sup>").attr('rel',ui.values[1]);
				clearTimeout(search_timer);
			},
			change: function(event,ui) {
				clearTimeout(search_timer);
				search_timer = setTimeout("search_cases_numbers()",search_timeOut);
			}
		});
		$( "#grundareal_fra" ).html(formatCurrency($( "#slider_grundareal" ).slider( "values",0 ),"")+" m<sup>2</sup>").attr('rel',$( "#slider_grundareal" ).slider( "values",0 ));
		$( "#grundareal_til" ).html(formatCurrency($( "#slider_grundareal" ).slider( "values",1 ),"")+" m<sup>2</sup>").attr('rel',$( "#slider_grundareal" ).slider( "values",1 ));
		
		// init sliders END		
		
		// init autocomplete
		$("#vejnavn").autocomplete({
			source: "/inc/boligfiler/search_vejnavn.asp",
			minLength: 2,
			close: function( event, ui ) {
				clearTimeout(search_timer);
				search_timer = setTimeout("search_cases_numbers()",search_timeOut);
			}
		});	
		// init autocomplete END
		
		// init city selector
		$("select#city").change(function() {
			clearTimeout(search_timer);
			search_timer = setTimeout("search_cases_numbers()",search_timeOut);
		});
		// init city selector END
		
		// init zip interval
		$("#zip_from, #zip_to").keyup(function() {
			clearTimeout(search_timer);
			search_timer = setTimeout("search_cases_numbers()",search_timeOut);		
		});
		// init zip END
		
		// init back to search buttons
		
		$("#backToSearch").click(function() {
			$("#maegler").val('');
			$rr1 = 1;
			$rr2 = more_results_number;
			$("#searchResults").css({ 'display' : 'none' });
			$("div#results_container ul.results").html('');
			$("div#shadow").show();
			$("#showResultsBtn,#createAgent,h1.searchResults").show();
			$.ajax({type: "POST",url: "/inc/boligfiler/ajax.asp",data: "cmd=clearSearch"});			
		});
		$("#backToSearch2").click(function() {
			$("#maegler").val('');
			$rr1 = 1;
			$rr2 = more_results_number;
			$.ajax({type: "POST",url: "/inc/boligfiler/ajax.asp",data: "cmd=clearSearch", success: function() { location.reload(); }});			
		});		
		
		// back to search END
		
		
		if($("#numberOfCases").val()!=""||($("#maegler").size()>0&&$("#maegler").val()!="")) {
			if($("#maegler").size()>0&&$("#maegler").val()!="") {
				search_cases_numbers();
				search_cases();			
				console.log("a");
			} else {
				if(parseInt($("#numberOfCases").val())>0) search_cases();
				console.log("b");
			}
		}
		
		// show results if searchQuery = 1
			// if(($("#searchQuery").val())==1) {
				// search_cases();
			// }
		// show results END
		
	}
	// search end
		
	$( "#r_form" ).dialog( "destroy" );

	var adresse = $( "#r_adresse" ),
		postnr = $( "#r_postnr" ),
		byen = $( "#r_byen" ),
		allFields = $( [] ).add( adresse ).add( postnr  ).add( byen ),
		tips = $( ".validateTips" );

	function updateTips( t ) {
		tips
			.text( t )
			.addClass( "ui-state-highlight" );
		setTimeout(function() {
			tips.removeClass( "ui-state-highlight", 1500 );
		}, 500 );
	}

	function checkLength( o, n, min, max ) {
		if ( o.val().length > max || o.val().length < min ) {
			o.addClass( "ui-state-error" );
			updateTips( n + " skal være mellem " +
				min + " og " + max + " tegn." );
			return false;
		} else {
			return true;
		}
	}

	$( "#r_form" ).dialog({
		autoOpen: false,
		height: 350,
		width: 350,
		modal: true,
		buttons: {
			"Hent rute": function() {
				var bValid = true;
				allFields.removeClass( "ui-state-error" );

				bValid = bValid && checkLength( adresse, "adresse", 8, 255 );
				bValid = bValid && checkLength( postnr, "postnummer", 4, 4 );
				bValid = bValid && checkLength( byen, "bynavn", 3, 40 );

				if ( bValid ) {
					// make Google call
					var addressLine = adresse.val() + ", " + postnr.val() + " " + byen.val();
					calcRoute(addressLine);
					$( this ).dialog( "close" );
				}
			},
			"Fortryd": function() {
				$( this ).dialog( "close" );
			}
		},
		close: function() {
			allFields.val( "" ).removeClass( "ui-state-error" );
		}
	});

});



var search_timer = "";
var search_timeOut = 500;
var more_results_number = 8;
var $rr1 = 1;
var $rr2 = more_results_number;
function search_cases() {
	// collect data
	var vejnavn = $("#vejnavn").val();
	var kontantpris_fra = $("#kontantpris_fra").attr('rel');
	var kontantpris_til = $("#kontantpris_til").attr('rel');
	var antalrum_fra = $("#antalrum_fra").attr('rel');
	var antalrum_til = $("#antalrum_til").attr('rel');
	var boligareal_fra = $("#boligareal_fra").attr('rel');
	var boligareal_til = $("#boligareal_til").attr('rel');					
	var grundareal_fra = $("#grundareal_fra").attr('rel');
	var grundareal_til = $("#grundareal_til").attr('rel');	
	var zip_from = $("#zip_from").val();
	zip_from = (isNaN(zip_from)) ? '' : htmlSecure(zip_from);
	var zip_to = $("#zip_to").val();
	zip_to = (isNaN(zip_to)) ? '' : htmlSecure(zip_to);
	var maegler = $("#maegler").val();
	// get boligtyper
	var boligtype = "";
	jQuery.each($("input[type=checkbox][class*=boligtype]:checked"), function() {
		boligtype = boligtype + "," + $(this).val();
	});
	if(boligtype!="") boligtype = boligtype.substring(1);

	var bynavn = "";
	jQuery.each($("select#city option:selected"), function() {
		bynavn = bynavn + "," + $(this).html();
	});
	if(bynavn!="") bynavn = bynavn.substring(1);
	
	var orderBy = $("#resultsOrderBtn").attr('rel');
	var post_url = "" +
	"&vejnavn=" + htmlSecure(vejnavn) + 
	"&kontantpris_fra=" + htmlSecure(kontantpris_fra) +
	"&kontantpris_til=" + htmlSecure(kontantpris_til) +
	"&antalrum_fra=" + htmlSecure(antalrum_fra) +
	"&antalrum_til=" + htmlSecure(antalrum_til) +
	"&boligareal_fra=" + htmlSecure(boligareal_fra) +
	"&boligareal_til=" + htmlSecure(boligareal_til) +
	"&grundareal_fra=" + htmlSecure(grundareal_fra) +
	"&grundareal_til=" + htmlSecure(grundareal_til) +
	"&maegler=" + htmlSecure(maegler) +
	"&boligtype=" + htmlSecure(boligtype) +
	"&bynavn=" + htmlSecure(bynavn) + 
	"&zip_from=" + zip_from + 
	"&zip_to=" + zip_to +
	"&orderBy=" + htmlSecure(orderBy) +
	"&rr1=" + $rr1 + "&rr2=" + $rr2;
	
	var isSessionSearch = ($("#numberOfCases").val()!="") ? 1 : 0;
	if(isSessionSearch==1) post_url += "&sessionSearch=1";
	$("#bigload").show();
	// real search
	$("#showResultsBtn,#createAgent,h1.searchResults").hide();
	$("div#shadow").hide();
	var $resultUl = $("div#results_container ul.results");

	$("li.small_result",$resultUl).unbind('click');
	var zIndexCounter = ($("li.small_result:last",$resultUl).size()>0) ? $("li.small_result:last",$resultUl).css('z-index') : 999999;
	$.getJSON('/inc/boligfiler/ajax.asp', "cmd=search" + post_url,function(data) {
		$.each(data, function(i,item){
			var $li = "" +
			"<li style='z-index:" + (zIndexCounter-i) + ";' rel='" + item.id_bolig + "' class='small_result'>" +
				"<div class='result_container'>" +
					"<div class='images'><ul><li>"
					if(item.billede!="") $li += "<img src='" + item.billede + "' alt='' />"
					$li += "</li></ul></div>" +
					"<div class='small'>" +
						"<p>" + item.vejnavn + " " + item.vejnr + ", " + item.bynavn + "</p>" +
						"<p>" + item.antalrum + " værelses på " + item.boligareal + " m<sup>2</sup> til " + formatCurrency(item.kontantpris,"") + ",-</p>" +
					"</div>" +
				"</div>" +
			"</li>";
			$resultUl.append($li);
		});			
		$("li.small_result",$resultUl).bind('click',function() { 
			toggle_small_result($(this),$(this).attr('rel'));
		});
		$("#backToSearch2").hide();
		$("#searchResults div.button").show();
		$("#searchResults").css('display','block');
		if(!isNaN($("#nuOfResults").html())) $("#showMoreResultsBtn").css('display',(parseInt($("#nuOfResults").html())<=$rr2) ? 'none' : 'block');
		$("#bigload").hide();

	});			

}


function search_cases_newOrder() {
	// collect data
	var orderBy = $("#resultsOrderBtn").attr('rel');
	var post_url = "&rr1=1&rr2=" + $rr2 + "&sessionSearch=1&orderBy=" + htmlSecure(orderBy);
	console.log("rr1: " + $rr1);
	console.log("rr2: " + $rr2);
	var $resultUl = $("div#results_container ul.results");
	$("li.small_result",$resultUl).unbind('click').remove();
	var zIndexCounter = ($("li.small_result:last",$resultUl).size()>0) ? $("li.small_result:last",$resultUl).css('z-index') : 999999;
	$.getJSON('/inc/boligfiler/ajax.asp', "cmd=search" + post_url,function(data) {
		console.log(data);
		$.each(data, function(i,item){
			var $li = "" +
			"<li style='z-index:" + (zIndexCounter-i) + ";' rel='" + item.id_bolig + "' class='small_result'>" +
				"<div class='result_container'>" +
					"<div class='images'><ul><li>"
					if(item.billede!="") $li += "<img src='" + item.billede + "' alt='' />"
					$li += "</li></ul></div>" +
					"<div class='small'>" +
						"<p>" + item.vejnavn + " " + item.vejnr + ", " + item.bynavn + "</p>" +
						"<p>" + item.antalrum + " værelses på " + item.boligareal + " m<sup>2</sup> til " + formatCurrency(item.kontantpris,"") + ",-</p>" +
					"</div>" +
				"</div>" +
			"</li>";
			$resultUl.append($li);
		});			
		$("li.small_result",$resultUl).bind('click',function() { 
			toggle_small_result($(this),$(this).attr('rel'));
		});		
	});			

}



function search_cases_numbers() {
	$("#createAgent").show();
	// show loader
	$("#nuOfResults").html("<img src='/gfx/template/ajaxloader.gif' border='0' />");
	// collect data
	var vejnavn = $("#vejnavn").val();
	var kontantpris_fra = $("#kontantpris_fra").attr('rel');
	var kontantpris_til = $("#kontantpris_til").attr('rel');
	var antalrum_fra = $("#antalrum_fra").attr('rel');
	var antalrum_til = $("#antalrum_til").attr('rel');
	var boligareal_fra = $("#boligareal_fra").attr('rel');
	var boligareal_til = $("#boligareal_til").attr('rel');					
	var grundareal_fra = $("#grundareal_fra").attr('rel');
	var grundareal_til = $("#grundareal_til").attr('rel');	
	var zip_from = $("#zip_from").val();
	zip_from = (isNaN(zip_from)) ? '' : htmlSecure(zip_from);
	var zip_to = $("#zip_to").val();
	zip_to = (isNaN(zip_to)) ? '' : htmlSecure(zip_to);
	var maegler = $("#maegler").val();
	// get boligtyper
	var boligtype = "";
	jQuery.each($("input[type=checkbox][class*=boligtype]:checked"), function() {
		boligtype = boligtype + "," + $(this).val();
	});
	if(boligtype!="") boligtype = boligtype.substring(1);

	var bynavn = "";
	jQuery.each($("select#city option:selected"), function() {
		bynavn = bynavn + "," + $(this).html();
	});
	if(bynavn!="") bynavn = bynavn.substring(1);
	
	var orderBy = $("#resultsOrderBtn").attr('rel');
	var post_url = "" +
	"&vejnavn=" + htmlSecure(vejnavn) + 
	"&kontantpris_fra=" + htmlSecure(kontantpris_fra) +
	"&kontantpris_til=" + htmlSecure(kontantpris_til) +
	"&antalrum_fra=" + htmlSecure(antalrum_fra) +
	"&antalrum_til=" + htmlSecure(antalrum_til) +
	"&boligareal_fra=" + htmlSecure(boligareal_fra) +
	"&boligareal_til=" + htmlSecure(boligareal_til) +
	"&grundareal_fra=" + htmlSecure(grundareal_fra) +
	"&grundareal_til=" + htmlSecure(grundareal_til) +
	"&maegler=" + htmlSecure(maegler) +
	"&boligtype=" + htmlSecure(boligtype) +
	"&bynavn=" + htmlSecure(bynavn) + 
	"&zip_from=" + zip_from + 
	"&zip_to=" + zip_to +
	"&orderBy=" + htmlSecure(orderBy);

	$("h1.searchResults").show();
	// display number of results
	$.ajax({
		type: "POST",
		url: "/inc/boligfiler/ajax.asp",
		data: "cmd=searchNumbers" + post_url,
		success: function(msg){	
			var label_bolig = (msg==1) ? "bolig" : "boliger";
			$("#nuOfResults").html(msg);
			$("#label_bolig").html(label_bolig);
		}	
	});
}

function startFrontShow() {
// init slide settings
	nu_of_slides = $("div.slide").size();
	// init slide controls
	$(".imgcontrols div.active").click(function() { clearTimeout(slide_timer); });
	$(".imgcontrols div[class!=active]")
	.css('opacity',0.5)
	.hover(
		function() { $(this).css('opacity',0.7); },
		function() { $(this).css('opacity',0.5); }
	).click(function() {
		clearTimeout(slide_timer);
		$("div.progressbar").remove();
		var $current_slide = $(this).parents('div.slide:first');
		var $this_nr = $(this).html();
		var $new_slide = $("div.slide[rel=slide_" + $this_nr + "]");
		$current_slide.removeClass('current');
		$new_slide.addClass('current');
		
		$("#cases").animate({
			'left' : '-' + $new_slide.position().left + 'px'
		},slide_animation_duration,'easeOutCubic');

	});
	$("div.progressbar:eq(0)").animate({ 'width' : '0px' },slide_interval);
	slide_timer = setTimeout("nextSlide()",slide_interval);
}
function toggle_small_result(obj,id_bolig) {
	var container = $("div.result_container",obj);
	var small_info = $("div.small",container);
	if($("div.large_info",container).size()>0) {
		// collapse
		container.animate({ height : '147px'},{ duration : 300, complete: function() {
				$("div.large_info",container).remove();
				small_info.css('display','block').animate({ bottom : '0px' },{ duration: 200 });
		} });
		$("div.images ul",obj).oSlideShow('destroy');
		$("#nextBtn,#prevBtn").remove();
	} else {
		// if there's other cases open, close them
		if($("ul.results li div.result_container div.large_info").size()>0) {
			$("#nextBtn,#prevBtn").remove();
			jQuery.each($("ul.results li div.result_container div.large_info"), function() {
				var tmpCont = $(this).parents('div.result_container');
				$("div.images ul",tmpCont).oSlideShow('destroy');
				tmpCont.animate({ height : '147px'},{ duration : 300, complete: function() {
						$("div.large_info",$(this)).remove();
						$("div.small",tmpCont).css('display','block').animate({ bottom : '0px' },{ duration: 200 });
				} });		
			});
		}
		// expand
		$("div.images ul li:first",obj).css('opacity',0.4);
		$.ajax({
			type: "POST",
			url: "/inc/boligfiler/ajax.asp",
			data: "cmd=small_result&id_bolig=" + id_bolig,
			success: function(msg){		
				var large_info = $("<div />");
				large_info.addClass('large_info').html(msg).appendTo(container);
				small_info.animate({ bottom : '-50px' },{ duration: 200, complete: function() { 
						$(this).css({ display : 'none' }); 
						container.animate({ height : Math.ceil(container.height()+large_info.height()+30) + 'px'},{ duration : 400 });						

						// get pictures and position image nav buttons
						if($("div.images ul li",obj).size()==1) {
							$.ajax({
								type: "POST",
								url: "/inc/boligfiler/ajax.asp",
								data: "cmd=small_result_images&id_bolig=" + id_bolig,
								success: function(msg){
									// add small results image nav buttons
									var nextBtn = $("<img />");
									nextBtn.attr({src : '/gfx/template/nextBtn.png', id : 'nextBtn' }).appendTo(obj);
									var prevBtn = $("<img />");
									prevBtn.attr({src : '/gfx/template/prevBtn.png', id : 'prevBtn' }).appendTo(obj);
									$("div.images ul li",obj).remove();
									$("div.images ul",obj).append(msg).oSlideShow({
										width: '221px',
										height: '147px'	
									});
									$("div.images ul li:first",obj).fadeTo('slow',1);
									
								}
							});
						} else {
							// add small results image nav buttons
							var nextBtn = $("<img />");
							nextBtn.attr({src : '/gfx/template/nextBtn.png', id : 'nextBtn' }).appendTo(obj);
							var prevBtn = $("<img />");
							prevBtn.attr({src : '/gfx/template/prevBtn.png', id : 'prevBtn' }).appendTo(obj);
							$("div.images ul",obj).oSlideShow({
								width: '221px',
								height: '147px'	
							});
							$("div.images ul li:first",obj).fadeTo('slow',1);
						}

					} 
				});
			}	
		});	
	
	}
}
function toggleView(obj) {
	var container = $(obj).parents('div.page');
	if(container.height()==425) {
		container.addClass('expanded');
		// expand
		// unbind dir nav
		$("ul.images li",container).unbind('mousemove');
		// reset images
		$("ul.images li img",container).css('top','0');
		// find tallest image
		var tallestImg = 0;
		jQuery.each($("ul.images li img",container),function() {
			if($(this).height()>tallestImg) tallestImg = $(this).height();
		});
		//expand container
		container.animate({ 'height' : tallestImg + 'px'},500);
		$("#shadow").animate({ 'height' : tallestImg + 'px'},500);
		container.parent('div.page').animate({ 'height' : tallestImg + 'px'},500);
		if($(window).height()<925) $("div.wrapper").css('paddingBottom', (tallestImg-465)+'px');
	} else {
		container.removeClass('expanded');
		// collapse
		//expand container
		container.animate({ 'height' : '425px'},500);
		$("#shadow").animate({ 'height' : '425px'},500);
		container.parent('div.page').animate({ 'height' : '425px'},500);		
		
		// bind nav dir
		if(container.parent('div').attr('id')=='images') {
			directional_nav($("ul.images li"),container);
			if($(window).height()<925) $("div.wrapper").css('paddingBottom','0px');
		}
	}
}
function directional_nav(obj) {
	$(obj).mousemove(function(e) {
		var $offTop = $("#shadow").offset().top;
		var $realY = Math.floor(e.clientY-$offTop);
		var $img = $("img",this);
		var $imgHeight = $img.height();
		var $rmx = $imgHeight/425;
		var $imgPos = ($img.position().top<0) ? (-$img.position().top) : $img.position().top;
		var $imgDiff = $imgPos-$realY;
		$imgDiff = ($imgDiff<0) ? (-$imgDiff) : $imgDiff;
		$img.css('top','-' + Math.floor(($rmx*$realY)-$realY) + 'px');
	});
}

var img_change_speed = 1000;
var current_slide = "";
var slide_timer = "";
var slide_interval = 5000;
var slide_animation_duration = 2000;
var nu_of_slides = 0;

function nextSlide() {
	$("div.progressbar").css('width','200px');
	var $current_slide = $("div.slide.current");
	var $curr_slide_nr = parseInt($current_slide.attr('rel').replace("slide_",""));
	if($curr_slide_nr>=nu_of_slides) $curr_slide_nr = 0;
	var $new_slide = $("div.slide[rel=slide_" + ($curr_slide_nr+1) + "]");
	$current_slide.removeClass('current');
	$new_slide.addClass('current');	
	$("#cases").animate({
		'left' : '-' + $new_slide.position().left + 'px'
	},{
		duration: slide_animation_duration,
		easing: 'easeOutCubic', 
		complete: function() {
			slide_timer = setTimeout("nextSlide()",slide_interval);
			$("div.progressbar",$new_slide).animate({ 'width' : '0px' },slide_interval);
		}
	});
}


var customImgArr = "";
var curr_customImg = 0;
var customImg_time = 2500;
var customImg_delay = 2000;

function customImgFolder(cmd) {
	switch(cmd) {
		case "init":
			customImgArr = $("#customImg img").length-1;
			curr_customImg = customImgArr;
			$("#customImg img").css('display','block');
			setTimeout("customImgFolder('')",customImg_delay);
		break;
		case "":
			var tmp = curr_customImg;
			curr_customImg = (curr_customImg==0) ? curr_customImg = customImgArr : curr_customImg = curr_customImg-1;
			$("#customImg img").css('zIndex','0');
			$($("#customImg img").get(tmp)).css('zIndex','1');
			$($("#customImg img").get(curr_customImg)).css({ 'opacity' : 0, 'zIndex' : '2', 'display' : 'block' })
			.animate({ 'opacity' : 1 }, {duration : customImg_time, complete: function() {
				setTimeout("customImgFolder('')",customImg_delay);
			}});
			
			
		break;
	}
}

function htmlSecure(str_tmp) {
	var tmp = str_tmp;
	if(tmp!=""&&tmp.length>0) {
		tmp = tmp.replace(/>/g,"&gt;");
		tmp = tmp.replace(/</g,"&lt;");
		tmp = tmp.replace(/[\r\n]+/g, " ");
		tmp = encodeURIComponent(tmp);
	}
	return tmp;
}

function validEmail(str) {
	var re = new RegExp(/[a-z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-z]{2,12}/ig);
	return (str.match(re)) ? true : false;
}



var geocoder;
var map;
var directionDisplay;
var directionsService;
var stepDisplay;
var markerArray = [];

function HomeControl(controlDiv, map) {
 
	// Set CSS styles for the DIV containing the control
	// Setting padding to 5 px will offset the control
	// from the edge of the map
	controlDiv.style.padding = '5px';

	// Set CSS for the control border
	var controlUI = document.createElement('DIV');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.borderStyle = 'solid';
	controlUI.style.borderWidth = '2px';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = 'Få rutevejledning';
	controlDiv.appendChild(controlUI);

	// Set CSS for the control interior
	var controlText = document.createElement('DIV');
	controlText.style.fontFamily = 'Arial,sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.color = '#000000';
	controlText.style.border = '1px solid #000000';
	controlText.style.paddingLeft = '4px';
	controlText.style.paddingRight = '4px';
	controlText.innerHTML = '<b>Rutevejledning</b>';
	controlUI.appendChild(controlText);

	google.maps.event.addDomListener(controlUI, 'click', function() {
		$( "#r_form" ).dialog( "open" );

	});
 
}

function initializeMap() {
	directionsService = new google.maps.DirectionsService();
	
	geocoder = new google.maps.Geocoder();
	var address_or_geo = "";
	geocoder.geocode( { 'address': $case_address}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK && ($case_longitude==""&&$case_latitude=="")) {

			var myOptions = {
				zoom: 15,
				center: results[0].geometry.location,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			}
			map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);	
			var marker = new google.maps.Marker({
				map: map, 
				icon: '/gfx/template/map-marker.png',
				position: results[0].geometry.location
			});			
			
		  var homeControlDiv = document.createElement('DIV');
		  var homeControl = new HomeControl(homeControlDiv, map);
		 
		  homeControlDiv.index = 1;
		  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);		

			// Create a renderer for directions and bind it to the map.
			var rendererOptions = {
			  map: map
			}
			directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)

			// Instantiate an info window to hold step text.
			stepDisplay = new google.maps.InfoWindow();		  
			
		} else {
			
			var latlng = new google.maps.LatLng($case_longitude, $case_latitude);			
			var myOptions = {
				zoom: 15,
				center: latlng,
				mapTypeId: google.maps.MapTypeId.ROADMAP
			}
			map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
			var marker = new google.maps.Marker({
				map: map, 
				icon: '/gfx/template/map-marker.png',
				position: latlng
			});					
			
			  var homeControlDiv = document.createElement('DIV');
			  var homeControl = new HomeControl(homeControlDiv, map);
			 
			  homeControlDiv.index = 1;
			  map.controls[google.maps.ControlPosition.TOP_RIGHT].push(homeControlDiv);				

			// Create a renderer for directions and bind it to the map.
			var rendererOptions = {
			  map: map
			}
			directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions)

			// Instantiate an info window to hold step text.
			stepDisplay = new google.maps.InfoWindow();		  

			  
		}
	});	
}

function calcRoute(address) {
  
    // First, remove any existing markers from the map.
    for (i = 0; i < markerArray.length; i++) {
      markerArray[i].setMap(null);
    }
 
    // Now, clear the array itself.
    markerArray = [];
 
    var request = {
        origin: address,
        destination: $case_address,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
 
    // Route the directions and pass the response to a
    // function to create markers for each step.
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        var warnings = document.getElementById("warnings_panel");
	    warnings.innerHTML = "<b>" + response.routes[0].warnings + "</b>";
        directionsDisplay.setDirections(response);
        showSteps(response);
      }
    });
  }
 
  function showSteps(directionResult) {
    // For each step, place a marker, and add the text to the marker's
    // info window. Also attach the marker to an array so we
    // can keep track of it and remove it when calculating new
    // routes.
    var myRoute = directionResult.routes[0].legs[0];
 
    for (var i = 0; i < myRoute.steps.length; i++) {
      var marker = new google.maps.Marker({
        position: myRoute.steps[i].start_point, 
        map: map
      });
      attachInstructionText(marker, myRoute.steps[i].instructions);
      markerArray[i] = marker;
    }
  }
 
  function attachInstructionText(marker, text) {
    google.maps.event.addListener(marker, 'click', function() {
      // Open an info window when the marker is clicked on,
      // containing the text of the step.
      stepDisplay.setContent(text);
      stepDisplay.open(map, marker);
    });
  }





function refreshLignende() {
	var post_url = "cmd=lignende&postnr=" + htmlSecure(lignende_postnr) + "&kontantpris=" + htmlSecure(lignende_kontantpris) + "&maegler=" + htmlSecure(lignende_maegler);
	//window.open("/inc/boligfiler/ajax.asp?cmd=lignende&postnr=" + htmlSecure(lignende_postnr) + "&kontantpris=" + htmlSecure(lignende_kontantpris) + "&maegler=" + htmlSecure(lignende_maegler));
	$.ajax({
		type: "POST",
		url: "/inc/boligfiler/ajax.asp",
		data: post_url,
		success: function(msg){	
			$("table#lignende_boliger tbody tr").remove();
			$("table#lignende_boliger tbody").append(msg);
		}	
	});
}




function formatCurrency(num,currSign) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+'.'+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + currSign + num);
}


