/*
 * FORUMADVOKATER
 * Main JS file
 * By Wemind
 */

function dlog(str){
	try {
		if(window.console && window.console.log){
			console.log(str)
		}
	} catch(e){}
}

$(document).ready(function(){
	// Layout vars
	window._topHeight      = $("#top")[0].offsetHeight
	window._footerHeight   = $("#footer")[0].offsetHeight - 28
	window._bodyHeight     = $("#body")[0].offsetHeight
	window._primaryOffset  = $("#primary")[0].offsetTop
	window._adminBarHeight = 0
	if($("#adminbar").length > 0){
		window._adminBarHeight = $("#adminbar")[0].offsetHeight
	}
	if(_primaryOffset <= 0){ // IE
		window._primaryOffset  = document.getElementById("body").offsetTop
	}

	// Page vars
	window._kontakt       = $("body").hasClass("kontakt")
	if(typeof window._front == "undefined"){
		window._front     = false
	}

	// Search area
	window._searchDefault = $("#searchdefault").length > 0 ? $("#searchdefault").text() : "Dit søgeord..."
	$("#search input.q").val(_searchDefault)
	$("#search input.q").focus(function(){
		if(this.value == _searchDefault){
			this.value = ""
		}
	})
	$("#search input.q").blur(function(){
		if(this.value == ""){
			this.value = _searchDefault
		}
	})
	$("#top #search span.languages").click(function(evt){
		evt.preventDefault();
	})
	var langHover = false
	$("#top #search span.languages").hover(function(){
		langHover = true
		$("#top #search span.languages select").show()
	}, function(){
		langHover = false
		window.setTimeout(function(){ if(!langHover){ $("#top #search span.languages select").hide() } }, 1000)
	})
	$("#top #search span.languages select").change(function(){
		window.location.href = window.location.protocol + "//" + window.location.host + "/" + ($(this).val() == "da" ? "" : $(this).val())
	})

	// Layout
	if($("#primary").height() < $("#body").height()){
		var x = $.browser.msie ? 42 : 40
		$("#primary").css("min-height", ($("#body").height()-x) + "px")
	}
	if($("#tertiary").height() > $("#body").height()){
		$("#primary").css("min-height", $("#tertiary").height() + "px")
	}
	function fmaresizer(){
		if(!window._front){
			var ph = _primaryOffset + _bodyHeight + _adminBarHeight + _footerHeight
			if($(window).height() > ph){ // || $("#primary").css("min-height") != "none"
				//dlog($("#primary").css("min-height"))
				//dlog($(document).height() + " - (" + _primaryOffset + " + " + _adminBarHeight + " + " + _footerHeight + " - 32) = " + ($(document).height() - (_primaryOffset + _adminBarHeight + _footerHeight) - 32) + "px")
				$("#primary").css("min-height",($(document).height() - (_primaryOffset + _adminBarHeight + _footerHeight) - 32) + "px")
			}
		}
	}
	$(window).bind("resize", fmaresizer)
	$(window).trigger("resize")

	// Om os page
	// if($(".view-personer").length > 0 && !window.location.href.match(/\?/)){
		// $(".view-personer .view-content, .view-personer .item-list").hide() // Hide by default if no args
		// $("#primary").css("min-height","")
		// $("#primary").css("min-height",($(document).height() - (_primaryOffset + _adminBarHeight + _footerHeight) - 32) + "px")
	// }

	// Kontakt page
	if(_kontakt && google && "maps" in google){
		var ll            = new google.maps.LatLng(55.6457, 12.0764)//(55.646308, 12.077579)
		window.kontaktMap = new google.maps.Map($(".kontaktmap")[0], {
			zoom: 14,
			center: ll,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			mapTypeControl: true,
			mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
			scaleControl: true,
			navigationControl: true,
			navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
			scrollwheel: false // This would otherwise break scrolling on the page
		})
		window.kontaktMak = new google.maps.Marker({
		    position: ll,
		    map: kontaktMap,
		    title: ""
		})
	}
})


if(_front){
	$(document).ready(function(){
		window._frontTopHeight = $("#front-top")[0].offsetHeight

		/**
			FLEXIBACKGROUND BY MICHAEL BESTER AT KIMILI.COM. Modified by Wemind.
			http://kimili.com/journal/flexible-scalable-background-image
		*/
		/**
			Declare and define variables
		*/
		var $window = $(window),
			$body = $("body"),
			imageID = "expando",
			tallClass = 'tall',
			wideClass = 'wide',
			$bgImage, $wrapper, img, url, imgAR;

		/**
			Are we dealing with ie6?
		*/
		var ie6 = ($.browser.msie && parseInt($.browser.version, 10) <= 6);

		function flexi_resize() {
			var win = {
				height : $window.height(),
				width : $window.width()
			};

			// The current aspect ratio of the window
			var winAR = win.width / win.height;

			// Determine if we need to show the image and whether it needs to stretch tall or wide
			if (win.width < bgImageSize.width && win.height < bgImageSize.height) {
				$body
					.removeClass(wideClass)
					.removeClass(tallClass);
			} else if ((win.w < bgImageSize.width && win.height >= bgImageSize.height) || (winAR < imgAR)) {
				$body
					.removeClass(wideClass)
					.addClass(tallClass);
				// Center the image
				$bgImage.css('left', Math.min(((win.width - bgImageSize.width) / 2), 0));
			} else if (win.width >= bgImageSize.width) {
				$body
					.addClass(wideClass)
					.removeClass(tallClass);
				$bgImage.css('left', 0);
			}

			// Need to fix the height of the wrapper for IE6
			if (ie6) {
				$wrapper.css('height', win.height);
				$bgImage.css("display", "none") // Nevermind ...
			}

			// Forumadvokater exclusive stuff ------------------------------
			// THE X FACTOR
			var x, hp, ih
			//x = (0.1*$("#"+imageID)[0].offsetHeight)
			ih = $("#"+imageID)[0].offsetHeight
			x  = (0.1*ih)
			hp = (ih-win.height)/ih
			x  = (hp/3)*ih
			$wrapper.css("margin-top", "-" + x + "px")
			$wrapper.css("height", win.height + x + "px")
			//$wrapper.css("height", $(document).height() + x + "px")

			// THE FRONT GAP
			var frontTop = $("#front-top")
			var upper    = _topHeight    + 50 + _frontTopHeight + _adminBarHeight
			var lower    = _footerHeight + 50 + _bodyHeight
			var delta    = win.height - (upper + lower)
			if(delta < 100){
				frontTop.css("margin-bottom", "100px")
			} else {
				frontTop.css("margin-bottom", delta + "px")
			}
		}

		function flexi_init(){
			if(ie6){ return }
			if(typeof window.bgImageSize == "undefined"){ return }
			// No need for any of this if the screen isn't bigger than the background image
			if (screen.availWidth <= bgImageSize.width && screen.availHeight <= bgImageSize.height){
				return;
			}

			// Parse out the URL of the background image and drop out if we don't have one
			url = $body.css('background-image').replace(/^url\(("|')?|("|')?\);?$/g, '') || false;
			if (!url || url === "none" || url === "") {
				return;
			}

			// Get the aspect ratio of the image
			imgAR = bgImageSize.width / bgImageSize.height;

			// Create a new image element
			$bgImage = $('<img />')
						.attr('src', url)
						.attr('id', imageID);

			// Create a wrapper and append the image to it.
			// The wrapper ensures we don't get scrollbars.
			$wrapper = $('<div id="expando-wrap"></div>')
							.css({
								'overflow' : 'hidden',
								'width' : '100%',
								'height' : '100%',
								'z-index' : '-2'
							})
							.append($bgImage)
							.appendTo($body);

			// IE6 Doesn't do position: fixed, so let's fake it out.
			// We'll apply a class which gets used in the CSS to emulate position: fixed
			// Otherwise, we'll simply used position: fixed.
			/**/if (ie6) {
				$wrapper.addClass('ie6fixed');
			} else {
				$wrapper.css({
					'position' : 'fixed',
					'top' : 0,
					'left' : 0
				});
			}/*
			$wrapper.css({
				"position": "absolute",
				"top":      0,
				"left":     0
			})*/

			// Set up a resize listener to add/remove classes from the body
			$window.bind('resize', flexi_resize);

			// Set it up by triggering a resize
			$window.trigger('resize')
			window.setTimeout(function(){ $(window).trigger("resize") }, 500)
		}
		flexi_init()
	})
}


jQuery.expr[':'].Contains = function(a, i, m) {
  return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0;
};

$(function(){
  $("div.filterable-lists").each(function(){
    $(this).prepend(" \
<p> \
  <label for='stikord_filter'>Filter: </label> \
  <input class='filter text' type='text' /> \
</p>");
  });

  $("input.filter").bind("change keyup", function(){
    var q = $(this).attr("value");
    var div = $(this).parents("div.filterable-lists");
    if (q == "") {
      $("li, h2", div).show();
    } else {
      $("li, h2", div).hide();
      $("a:Contains("+q+")", div).parents("li").show();
    }
  });
});


