function initPage(){
	clearFormFields({
		clearInputs: true,
		clearTextareas: true,
		passwordFieldText: true,
		addClassFocus: "focus",
		filterClass: "default"
	});
}
function clearFormFields(o){
	if (o.clearInputs == null) o.clearInputs = true;
	if (o.clearTextareas == null) o.clearTextareas = true;
	if (o.passwordFieldText == null) o.passwordFieldText = false;
	if (o.addClassFocus == null) o.addClassFocus = false;
	if (!o.filter) o.filter = "default";	
	function inputsSwap(el, el2) {
		if(el) el.style.display = "none";
		if(el2) el2.style.display = "inline";
	}
}

function initScript() {
	addClass({
		tagName:'div',
		tagClass:'div-class',
		classAdd:'div-add-class'
	})
	
	addClass({
		tagName:'a',
		tagClass:'link-open',
		classAdd:'block-close',
		addToParent:true
	})
}

function addClass (_options) {
	var _tagName = _options.tagName;
	var _tagClass = _options.tagClass;
	var _classAdd = _options.classAdd;
	var _addToParent = false || _options.addToParent;
	var _el = document.getElementsByTagName(_tagName);
	if (_el) {
		for (var i=0; i < _el.length; i++) {
			if (_el[i].className.indexOf(_tagClass) != -1) {
				_el[i].onclick = function() {
					if (_addToParent) {
						if (this.parentNode.className.indexOf(_classAdd) == -1) {
							this.parentNode.className += ' '+_classAdd;
						} else {
							this.parentNode.className = this.parentNode.className.replace(_classAdd,'');
						}
					} else {
						if (this.className.indexOf(_classAdd) == -1) {
							this.className += ' '+_classAdd;
						} else {
							this.className = this.className.replace(_classAdd,'');
						}
					}
					return false;
				}
			}
		}
	}
}
if (window.addEventListener)
	window.addEventListener("load", initPage, false);
else if (window.attachEvent)
	window.attachEvent("onload", initPage);
if (window.addEventListener)
	window.addEventListener("load", initScript, false);
else if (window.attachEvent)
	window.attachEvent("onload", initScript);
	
	
/* TMH: 15042011: The functions below, printRoute and printRouteLoad is made by Esben from folia */
 var printRoute = function () {
    var height = screen.availHeight - (screen.availHeight / 100) * 10;
    var borderSize = (window.outerWidth - window.innerWidth) / 2 || 5;
    var offsetLeft = (window.screen.width / 2) - (330 + borderSize);
    var offsetTop = ((screen.availHeight / 100) * 10) / 2;
    var printWindow = window.open('/html/print.html', 'printRoute', 'status=0, toolbar=0, menubar=0, location=0, directories=0, scrollbars=1, width=670, height=' + height + ', left=' + offsetLeft + ', top=' + offsetTop);
}

var printRouteLoad = function (sender) {
    var directions, directionsLength, start, startFlag, viaPoint, viaFlag, viaFlagNumber, end, endFlag, polyline, printMapCanvas, printMap, printMapSrc, i;
    
	directions = directionsDisplay.getDirections();
    start = directions.routes[0].legs[0].start_location.toUrlValue();
	viaPoint = null;
	end = null;
	directionsLength = directions.routes[0].legs.length;
	
	startFlag = "http://118.dk/skattejagt/routeflags/flag_route_start_map.png";
	viaFlag = "http://118.dk/skattejagt/routeflags/flag_route_via_map";
	endFlag = "http://118.dk/skattejagt/routeflags/flag_route_end_map.png";
	
	polyline = directions.routes[0].overview_polyline.points.toString();
	
	printMapCanvas = sender.document.getElementById('mapCanvas');
	printMap = printMapCanvas.appendChild(sender.document.createElement('img'));
	printMapSrc = "http://maps.google.com/maps/api/staticmap?sensor=false&size=640x640&center=" + map.getCenter().toUrlValue() + "&zoom=" + map.getZoom() + "&markers=icon:" + startFlag + "|" + start;		
	
	if(directionsLength > 1){		
		for(i = 0; i < directionsLength; i += 1){
			viaPoint = directions.routes[0].legs[i].end_location.toUrlValue();						
			
			if(i === (directionsLength - 1)){
				printMapSrc += "&markers=icon:" + endFlag + "|" + viaPoint;																
			}else{
				printMapSrc += "&markers=icon:" + viaFlag;
				if(directionsLength > 2){					
					viaFlagNumber = i + 1;
					printMapSrc += "_" + viaFlagNumber + ".png";					
				}else{
					printMapSrc += ".png";
				}
				printMapSrc += "|" + viaPoint;
			}
		}
		printMapSrc += "&path=weight:5|color:blue|enc:" + polyline;
	}else{
		end = directions.routes[0].legs[0].end_location.toUrlValue();
		printMapSrc += "&markers=icon:" + endFlag + "|" + end + '&path=weight:5|color:blue|enc:' + polyline;
	}    
    
    printMap.src = printMapSrc;

    var printDirectionsPanel = sender.document.getElementById('directionsPanel');
    var directionsPanel = document.getElementById('directionsPanel');
    printDirectionsPanel.innerHTML = directionsString(directionsPanel);     
}

var directionsString = function(from){
	var $from = $(from);		
	var htmlToInsert = "<div>";
	var $uls = $from.find("ul");
	
	
	htmlToInsert += "<h2>" + $from.find("h2").text() + "</h2>";	
	htmlToInsert += "<span>" + $from.find("span.tid:first").text() + "</span><br />";	
	htmlToInsert += "<span>" + $from.find("span.afstand:first").text() + "</span><br />";	
	htmlToInsert += "<table>";
	htmlToInsert += "<tr><td valign='top' align='right' colspan='3'><em>km  </em></td></tr>";
	
	var countLis = $uls.size();
	
	$.each($uls, function(index, value){
		var that = $(this);
		var $lis = that.find("li");
		var tidIndex;
		
		if(countLis > 1){
			tidIndex = index + 1;
		}else{
			tidIndex = index;
		}		
		
		htmlToInsert += "<tr>";
		htmlToInsert += "<td valign='top' colspan='3'>"
		htmlToInsert += "<span>" + $from.find("span.from:eq("+ index +")").html() + "</span><br />";
		htmlToInsert += "<span>" + $from.find("span.to:eq("+ index +")").html() + "</span><br />";	
		htmlToInsert += "<span>" + $from.find("span.tid:eq("+ tidIndex +")").html() + "</span><br />";	
		htmlToInsert += "</td>";
		htmlToInsert += "</tr>";
		
		
		
		$.each($lis, function(index, value){
			var $this = $(value);
			var $step = $this.children("span");
			var $desc = $this.children("a");
			var $dist = $this.children("em");
			
			htmlToInsert += "<tr>";
			htmlToInsert += "<td valign='top'>" + $step.text() + "</td>";
			htmlToInsert += "<td valign='top' style='padding-right: 20px'>" + $desc.text() + "</td>";
			htmlToInsert += "<td valign='top' align='right'>" + $dist.text() + "</td>";
			htmlToInsert += "</tr>";
		});
		htmlToInsert += "<tr>";
		htmlToInsert += "<td valign='top' colspan='3'>"
		htmlToInsert += "<br />";		
		htmlToInsert += "</td>";
		htmlToInsert += "</tr>";
	});		
	
	htmlToInsert += "</table>";	
	htmlToInsert += "</div>";
	
	
	/*
	var $from = $(from);		
	var htmlToInsert = "<div>";
	var $lis = $from.find("li");
	
	htmlToInsert += "<h2>" + $from.find("h2").text() + "</h2>";	
	htmlToInsert += "<span>" + $from.find("span.from").html() + "</span><br />";
	htmlToInsert += "<span>" + $from.find("span.to").html() + "</span><br />";
	htmlToInsert += "<span>" + $from.find("span.afstand").text() + "</span>";
	htmlToInsert += "<br />";
	htmlToInsert += "<span>" + $from.find("span.tid").text() + "</span>";	
	htmlToInsert += "<table>";
	htmlToInsert += "<tr><td valign='top' align='right' colspan='3'><em>km  </em></td></tr>";
	
	$.each($lis, function(index, value){
		var $this = $(value);
		var $step = $this.children("span");
		var $desc = $this.children("a");
		var $dist = $this.children("em");
		
		htmlToInsert += "<tr>";
		htmlToInsert += "<td valign='top'>" + $step.text() + "</td>";
		htmlToInsert += "<td valign='top' style='padding-right: 20px'>" + $desc.text() + "</td>";
		htmlToInsert += "<td valign='top' align='right'>" + $dist.text() + "</td>";
		htmlToInsert += "</tr>";
	});		
	
	htmlToInsert += "</table>";	
	htmlToInsert += "</div>";
	
	*/
		
	return htmlToInsert;			
};

// TMH: 13-05-2011: Init ruteplan from left content
function initRoutePlan(indikator){				
	click();
	showMapGlobal();
	if(indikator === 1){		
		$("#routePlanLink").trigger("click");
	}else if(indikator === 2){
		$("#searchNearby").trigger("click");
	}					
}

function showMapGlobal(){					
	$("#imageGallery").find("img.active").removeClass("active").addClass("inactive");
	$(".map_canvas").removeClass("hiddenMap");
};

// TMH: 16-05-2011: Image gallery funktion, used on enhanced listings
var imageGallery = function(imgList, imgListThumbs){	
	var mapHidden = true,
	$activeImg = $(imgList).find(".active");
		
	mapHidden = $("#map_canvas").hasClass("hiddenMap");	
				
	// Function used to change the highlighted image.
	var changeGalleryImage = function(imgClicked){
		if(!mapHidden){			
			$(".map_canvas").addClass("hiddenMap");
			mapHidden = true;
		}
		$activeImg = $(imgList).find(".active");		
		var imgThumbIndex = $(imgClicked).parent().index();				
		var $imgToShow = $(imgList).find("li:eq(" + imgThumbIndex + ")");				
					
		// Hide the current active image		
		if($activeImg[0]){			
			$activeImg.removeClass("active").addClass("inactive");						
		}
		// Show the new active image
		$imgToShow.children().removeClass("inactive").addClass("active");											
	};
	
	// Function used, to show map funktion
	var showMap = function(){			
		mapHidden = false;
		$(imgList).find("img").removeClass("active").addClass("inactive");
		$(".map_canvas").removeClass("hiddenMap");		
	};
	
	// Bind changeGalleryImage funktion to image thumbs		
	$(imgListThumbs).delegate("a.imageThumb", "click", function(e){
		e.preventDefault();
		changeGalleryImage(this);
	});	
	
	// Bind showMap funktion to map thumb
	$(imgListThumbs).delegate("a.mapThumb", "click", function(e){
		e.preventDefault();
		showMap();
	});	
};

// TMH: 29-08-2011: Initiate public transport box
function initPublicTransportation(map){
	var container = new folia.ui.box({ width: "90px", height: "auto", collapsible: true });	            	            
		    			
    pubblicTransportOptions = {	                
        title: "Trafik info",
        className: "PublicTransport",
        publicTransportIds: [folia.maps.PublicTransportIds.BUS, folia.maps.PublicTransportIds.TRAIN, folia.maps.PublicTransportIds.METRO, folia.maps.PublicTransportIds.S_TRAIN],
        map: map
    };
    
    var pubblicTransport = new folia.maps.PublicTransportControl(pubblicTransportOptions);	            
    container.appendChild(pubblicTransport.getElement());
    map.controls[google.maps.ControlPosition.RIGHT].push(container);
};

function setInitialFocus() {
    foundIt = false;
    for (var f =0; f < document.forms.length;f++) {
        var field = document.forms[f];
        for (var i = 0; i < field.length; i++) {
            e = field.elements[i]
            if (!foundIt && ((e.type == "text") || (e.type == "password") || (e.type == "textarea")) && !e.disabled && !e.readOnly ) {
                e.focus();
                foundIt = true;
            }
        }
    }
}

function showHouseNumber() {
    houseNum = document.forms.advancedSearchForm.whereHouseNumber.value
    var re = /([^- ]+)(-[^- ]*)?( [^- ]+)?/
    var match = re.exec(houseNum)
    document.forms.houseNumberForm.whereHouseMin.value = "";
    document.forms.houseNumberForm.whereHouseMax.value = "";
    document.forms.houseNumberForm.whereHouseParity[0].checked = false;
    document.forms.houseNumberForm.whereHouseParity[1].checked = false;
    document.forms.houseNumberForm.whereHouseParity.value = null;
    
    if (match==null) {
        document.forms.houseNumberForm.whereHouseMin.value = houseNum;
    } else {
        document.forms.houseNumberForm.whereHouseMin.value = match[1];
        if (match[2]!=null) {
            document.forms.houseNumberForm.whereHouseMax.value = match[2].substring(1);
        }
        if (match[3]!=null && match[3]==" lige") {
            document.forms.houseNumberForm.whereHouseParity[0].checked = true;
            document.forms.houseNumberForm.whereHouseParity.value = "lige";
        }
        if (match[3]!=null && match[3]==" ulige") {
            document.forms.houseNumberForm.whereHouseParity[1].checked = true;
            document.forms.houseNumberForm.whereHouseParity.value = "ulige";
        }
    }
    document.getElementById('popup4').style.display='block';
}

function hideHouseNumber() {
    document.getElementById('popup4').style.display='none';
}

function updateHouseNumber() {
    var from = document.forms.houseNumberForm.whereHouseMin.value;
    var upTo = document.forms.houseNumberForm.whereHouseMax.value;
    var parity = null;
    if (document.forms.houseNumberForm.whereHouseParity[0].checked) {
        parity = "lige";
    }
    if (document.forms.houseNumberForm.whereHouseParity[1].checked) {
        parity = "ulige";
    }
    if (from.trim()!="" || upTo.trim()!="" || parity != null) {
        document.forms.advancedSearchForm.whereHouseNumber.value = from+(from || upTo ? '-' : '')+upTo+(parity ? ' '+parity : '');
    }
    hideHouseNumber();
}

function showAndet() {
    document.forms.andetForm.medier.value = document.forms.advancedSearchForm.whatOther.value;
    document.getElementById('popup3').style.display='block';
    $("popup3").modal();
}

function hideAndet() {
    document.getElementById('popup3').style.display='none';
}

function updateAndet() {
    document.forms.advancedSearchForm.whatOther.value = document.forms.andetForm.medier.value;
    hideAndet();
}

function urlEncode(s) {
    return encodeURIComponent( s ).replace( /\%20/g, '+' ).replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' ).replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /\~/g, '%7E' );
}

function urlDecode(s) {
    return decodeURIComponent( s.replace( /\+/g, '%20' ).replace( /\%21/g, '!' ).replace( /\%27/g, "'" ).replace( /\%28/g, '(' ).replace( /\%29/g, ')' ).replace( /\%2A/g, '*' ).replace( /\%7E/g, '~' ) );
}          

function getWhere() {
    var n = document.getElementById('ql-hvor');
    if ( n && n.innerHTML.trim() != "" ) {
      return n.innerHTML;
    }

    n = document.getElementById('hvor');

    if ( n && n.value.trim() != "" ) {
      return n.value;
    }

    return "";
}

function getWhat() {
    var n = document.getElementById('ql-hvor'); 
    if ( n ) {
      return "";
    }
    n = document.getElementById('hvem');
    if ( n && n.value.trim() != "" ) {
      return n.value;
    }
    return "";
}

function showHideDebugInfo() {
    var d = document.getElementById('debug_info'); 
    if ( d ) {
        if ( d.style.display != 'block' ) {
            d.style.display = 'block';
        } else {
            d.style.display = 'none';
        }
    }
}

var clearSearchFields = (function(){
	var advancedSearchForm;
	
	this.clear = function(){
		advancedSearchForm = $("#advancedSearchForm");
		var inputFields = advancedSearchForm.find('input[type="text"]');
		inputFields.attr("value", "");
	};
	return this;
}());

//*************************************************
// Search Result listing functions
//*************************************************
function showDropDown(node) {
	var e = document.getElementById('popup7_drop_menu'); 
	if ( e ) {
		if ( e.style.display != 'block' ) {
			var s = jQuery(node);
			var d = jQuery(document);
			var offset = s.offset();
			var left = offset.left - 8;
			var top = offset.top + 8;
			e.style.left = left + 'px';
			e.style.top = top + 'px';
			e.style.display = 'block';
		}
	}
}

function hideDropDown() {
	var e = document.getElementById('popup7_drop_menu'); 
	if ( e && e.style.display == 'block' ) {
		e.style.display = 'none';
	}
}

function showHideDropDown(node) {
	var e = document.getElementById('popup7_drop_menu'); 
	if ( e ) {
		if ( e.style.display == 'block' ) {
			hideDropDown()
		} else {
			showDropDown(node)
		}
	}
}

function hidePopup() {
	hideDropDown()
	var popup = $('#popup9');
	if ( popup ) popup.hide();
	hideSpinner()
	var popup7 = $('#popup7_drop_menu');
	if ( popup7 ) popup7.hide();
	infowindowopen = false;
}

function hideSpinner() {
	var spinner = $('#spinner');
	if ( spinner ) spinner.hide();
}

function showStreetView(lat,lng){
	hideDropDown()
	var position = new google.maps.LatLng(lat,lng);
	panorama = map.getStreetView();
	panorama.setPosition(position);
 	panorama.setVisible(true);
}

function toggleRoutePlanDirection() {
	var di = document.route_plan_form.direction;
	var whereValue = document.route_plan_form.whereValue.value;

	if ( di.value == 'til' ) {
		$('#route_plan_direction').html(
			'<strong class="heading">Ruteplan: <span>fra her</span></strong>' +
			'<a href="#" class="link-right" onclick="toggleRoutePlanDirection();return false;">til her</a>'
		);
		di.value = 'fra';
		document.getElementById("routeStartWhere").value = whereValue;
		document.getElementById("routeStartWhere").name = "routeStart.where";
		document.getElementById("routeEndWhere").value = "";
		document.getElementById("routeEndWhere").name = "";
		document.getElementById('route_plan_input').name = "routeEnd.where";
		document.getElementById("route_plan_form_label").value = "Til:";
		document.getElementById("route_plan_form_label").innerHTML = "Til:";
		
	} else {
		$('#route_plan_direction').html(
			'<strong class="heading">Ruteplan: <span>til her</span></strong>' +
			'<a href="#" class="link-right" onclick="toggleRoutePlanDirection();return false;">fra her</a>'
		);
		di.value = 'til';
		document.getElementById("routeStartWhere").value = "";
		document.getElementById("routeStartWhere").name = "";
		document.getElementById("routeEndWhere").value = whereValue;
		document.getElementById("routeEndWhere").name = "routeEnd.where";
		document.getElementById('route_plan_input').name = "routeStart.where";
		document.getElementById("route_plan_form_label").value = "Fra:";
		document.getElementById("route_plan_form_label").innerHTML = "Fra:";
	}
	
	document.getElementById('route_plan_input').focus();
}

var tooltip = function(){
	var id = 'tt';
	var top = 3;
	var left = 3;
	var maxw = 270;
	var speed = 10;
	var timer = 20;
	var endalpha = 95;
	var alpha = 0;
	var tt,t,c,b,h;
	var ie = document.all ? true : false;	
	return{
		show:function(v,w){
			
			if(tt == null){				
				tt = document.createElement('div');
				tt.setAttribute('id',id);
				t = document.createElement('div');
				t.setAttribute('id',id + 'top');
				c = document.createElement('div');
				c.setAttribute('id',id + 'cont');
				b = document.createElement('div');
				b.setAttribute('id',id + 'bot');
				tt.appendChild(t);
				tt.appendChild(c);
				tt.appendChild(b);
				document.body.appendChild(tt);
				tt.style.opacity = 0;
				tt.style.filter = 'alpha(opacity=0)';
				document.onmousemove = this.pos;
			}
			tt.style.display = 'block';
			c.innerHTML = v;
			tt.style.width = w ? w + 'px' : 'auto';
			if(!w && ie){
				t.style.display = 'none';
				b.style.display = 'none';
				tt.style.width = tt.offsetWidth;
				t.style.display = 'block';
				b.style.display = 'block';
			}
			if(tt.offsetWidth > maxw){tt.style.width = maxw + 'px'}
			h = parseInt(tt.offsetHeight) + top;
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(1)},timer);
		},
		pos:function(e){
			var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
			var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
			tt.style.top = (u - h) + 'px';
			tt.style.left = (l + left) + 'px';
		},
		fade:function(d){
			var a = alpha;
			if((a != endalpha && d == 1) || (a != 0 && d == -1)){
				var i = speed;
				if(endalpha - a < speed && d == 1){
					i = endalpha - a;
				}else if(alpha < speed && d == -1){
					i = a;
				}
				alpha = a + (i * d);
				tt.style.opacity = alpha * .01;
				tt.style.filter = 'alpha(opacity=' + alpha + ')';
			}else{
				clearInterval(tt.timer);
				if(d == -1){tt.style.display = 'none'}
			}
		},
		hide:function(){
			clearInterval(tt.timer);
			tt.timer = setInterval(function(){tooltip.fade(-1)},timer);
		}
	};
}();

