/* It's not really cool to add className to the <html>-element, 
   but it's needed to avoid flickering in IE when hiding content. */
document.documentElement.className = "js";

/* Extensions to document */
document.getLayout = function () {
	var _layout,
	    regex = /layout-\d+/i;
	function getLayout() {
		var result;
		if (!_layout) {
			result = regex.exec($('body').attr('class'));
			_layout = result ? result[0] : null;
		}
		return _layout;
	}
	return getLayout;
}();

document.hasLayout = function (layout) {
	return document.getLayout() === layout;
};

document.getPageType = function () {
	var _pagetype;
	function getPageType() {
		_pagetype = _pagetype || $('body').attr('id');
		return _pagetype;
	}
	return getPageType;
}();

document.isAdjustPage = function() {
    return document.isPageType('adjust');
};

document.isPageType = function (type) {
	return document.getPageType() === type;
};

document.isStartPage = function () {
	return document.isPageType('startPage');
};

document.initAdjustEvents = function() {
    $("#adjust input[name='ColorCombination']").click(function() {
        $('body').removeClasses('color-combination');
        $('body').addClass($("input[name='ColorCombination']:checked").val());
        document.setHtmlClass('color-combination');
    });
    $("#adjust input[name='FontFamily']").click(function() {
        $('body').removeClasses('font-family');
        $('body').addClass($("input[name='FontFamily']:checked").val());
    });
    $("#adjust input[name='FontSize']").click(function() {
        $('body').removeClasses('font-size');
        $('body').addClass($("input[name='FontSize']:checked").val());
    });
    $("#adjust input[name='LineHeight']").click(function() {
        $('body').removeClasses('line-height');
        $('body').addClass($("input[name='LineHeight']:checked").val());
    });
    $("#adjust input[name='WordSpacing']").click(function() {
        $('body').removeClasses('word-spacing');
        $('body').addClass($("input[name='WordSpacing']:checked").val());
    });
};
/*
document.setHtmlClass = function(classNamePrefix) {
    $('html').removeClasses(classNamePrefix);
    var body = $('body');
    $(body.attr('class').split(' ')).each(function() {
        if (this.indexOf(classNamePrefix) === 0)
            $('html').addClass(this);
    });
}
*/

/**
 * Article functions
 * @requires jQuery
 * Add article functions, e.g., 'Print' or 'Tell a friend'.
 */
document.articleFunctions = function() {
	var ul;
	function getUl() {
		if (!ul) {
			var funcs = $('#article-functions');
			if (funcs.length) {
				ul = $('ul', funcs);
				if (!ul.length) {
					ul = $('<ul></ul>').insertAfter($('h2', funcs));
				}
			}
		}
		return ul;
	}
	/**
 	 * Add an item
	 * @param  options  Object  An object with options
	 */
	function addItem(options) {
		var li, a;
		options = jQuery.extend({
			// Link html
			text: '',
			// Link (or li) class
			className: '',
			// Link (or li) id
			id: '',
			// Callback to execute on click
			callback: null,
			// An element to append the link to, bypassing the regular ul
			insertInto: null
		}, options || {});
		
		if (getUl() || options.insertInto) {
			// Create link
			a = $('<a href="#"></a>');
			a.html(options.text);
			a.click(options.callback);
			if (!options.insertInto) {
				// If no insertInto-element is specified,
				// append the link to an li and add it to the ul
				li = $('<li>');
				// Add class and id to the li
				li.attr({
					'class': options.className,
					'id': options.id
				});
				a.appendTo(li);
				li.appendTo(ul);
			} else {
				// Add class and id to the link
				a.attr({
					'class': options.className,
					'id': options.id
				});
				a.appendTo($(options.insertInto));
			}
			return a;
		}
	}
	return {
		addItem: addItem
	};
}();

(function($) {
    $.fn.extend({

        // Add a class to every odd child element. Useful for e.g. zebra tables
        addClassToOddChildren: function(className, tag) {
            var selector = (tag || '*') + ':odd';
            var className = className || 'alt';
            this.children(selector).addClass(className);
        },

        // Add corners to boxes (divs).
        addCorners: function(options) {
            options = $.extend({
                topRight: 'tr',
                bottomRight: 'br',
                bottomLeft: 'bl',
                topLeft: 'tl',
                rightEdge: 're',
                bottomEdge: 'be',
                leftEdge: 'le'
            }, options || {});
            return this.each(function() {
                var $this = $(this), pos = $this.css('position');
                if (pos == 'static' || pos == 'auto' || pos === '') {
                    $this.css('position', 'relative');
                }

                // Ugly, but needed, IE6 detection
                if ($.browser.msie && parseInt($.browser.version, 10) == 6) {
                    // For IE6 to get the correct containing element
                    $this.css('zoom', 1);
                    // IE6's rounding may position corners out of place, so we need the width and height to be odd
                    if ($this.innerWidth() % 2) {
                        // Width is even, set new odd width
                        $this.width($this.width() - 1);
                    }
                    if ($this.innerHeight() % 2) {
                        // Height is even, set new odd height
                        $this.height($this.height() + 1);
                    }
                }

                // Create container
                $(window).load(function() {
                    var container = $('<div class="corners"></div>');
                    var thisHeight = parseInt($this.height());
                    var mh = $this.find('.m-h');
                    var mhHeight = parseInt(mh.height());
                    mh.height(mhHeight);
                    mhHeight = isNaN(mhHeight) ? 0 : mhHeight;
                    $this.append(container);
                    if (options.topRight) {
                        container.append('<div class="' + options.topRight + '"></div>');
                    }
                    if (options.bottomLeft) {
                        container.append('<div class="' + options.bottomLeft + '"></div>');
                    }
                    if (options.topLeft) {
                        container.append('<div class="' + options.topLeft + '"></div>');
                    }
                    if (options.rightEdge) {
                        container.append('<div class="' + options.rightEdge + '" style="height:' + (thisHeight - mhHeight - 7) + 'px;top:' + mhHeight + 'px;"></div>');
                    }
                    if (options.bottomEdge) {
                        container.append('<div class="' + options.bottomEdge + '"></div>');
                    }
                    if (options.leftEdge) {
                        container.append('<div class="' + options.leftEdge + '" style="height:' + (thisHeight - mhHeight - 7) + 'px;top:' + mhHeight + 'px;"></div>');
                    }
                    if (options.bottomRight) {
                        container.append('<div class="' + options.bottomRight + '"></div>');
                    }
                });
            });
        },

        // Add corners to tables.
        addTableCorners: function() {
            this.each(function() {
                $(this).find('tr:first th:first, tr:first td:first').prepend('<div class="corners"><div class="top-left"></div></div>');
                $(this).find('tr:first th:last, tr:first td:last').prepend('<div class="corners"><div class="top-right"></div></div>');
                $(this).find('tr:last th:first, tr:last td:first').append('<div class="corners"><div class="bottom-left"></div></div>');
                $(this).find('tr:last th:last, tr:last td:last').append('<div class="corners"><div class="bottom-right"></div></div>');
            });
        },

        // Get an elements associated label(s)
        getLabel: function() {
            var label,
			    id = this.attr('id');
            if (id) {
                label = $('label[for=' + id + ']');
            }
            return label;
        },

        makeZebraTable: function() {
            if (this.children('tr:first').find('th').length > 0)
                this.children('tr:not(:first):odd').addClass('odd');
            else
                this.children('tr:odd').addClass('odd');
        },

        populateValue: function(options) {
            options = $.extend({
                // Whether to hide the input's associated label
                hideLabel: true,
                // Class to add to hide the label
                hiddenLabelClass: 'structural',
                // Whether to use the label text as value
                useLabelText: false,
                // Whether to use the input's title text as value
                useTitleText: true,
                // A value to use instead of title or label text
                value: null
            }, options);
            this.each(function() {
                var valueText,
				    node = $(this),
				    label = node.getLabel();
                // Make sure it's an input with type=text we're working with
                if (node.attr('type') === 'text') {
                    valueText = options.value;
                    if (!valueText) {
                        if (options.useLabelText) {
                            if (label) {
                                // If value is not explicitly set, and we want to
                                // use the label text and a label exist, let's use that. 
                                valueText = label.text();
                            }
                        } else if (options.useTitleText) {
                            // If no value is explicitly set, and we want to use the
                            // title of the input, let's try that.
                            valueText = node.attr('title');
                        }
                    }
                    if (valueText) {
                        // Set value
                        node.val(valueText);
                        node.focus(function() {
                            if (node.val() === valueText) {
                                node.val('');
                                // Make input caret visible in IE
                                node.select();
                            }
                        });
                        node.blur(function() {
                            if (node.val() === '') {
                                node.val(valueText);
                            }
                        });
                        if (label && options.hideLabel) {
                            // Hide label
                            label.addClass(options.hiddenLabelClass);
                        }
                    }
                }
            });
            return this;
        },

        removeClasses: function(classNamePrefix) {
            var element = this;
            $(this.attr('class').split(' ')).each(function() {
                if (this.indexOf(classNamePrefix) === 0)
                    element.removeClass(this);
            });
        },

        // Add target to links.
        addTargetBlank: function() {
            this.each(function() {
                $(this).attr('target', '_blank');

                var title = $(this).attr('title');
                if (title)
                    title = title + '\r\n';
                title = title + targetBlankTitle;
                $(this).attr('title', title);

                $(this).append('<span class="target-inner">&nbsp;</span>');
                //$(this).append(' aaaaa aaaaa aaaaa aaaaa aaaaa<span class="target-inner"> </span>');
                
                
                // Funkar i Firefox
                //$(this).html('<span class="target-inner">' + $(this).html() + ' aaaa aaaa aaaa aaaa aaaa aaaa</span>');
                
                
                //$(this).html('<span class="target-inner">aaaa aaaa aaaa aaaa aaaa aaaa aaaa</span>');
            });
        }
    });
})(jQuery);

jQuery(function() {
    var tell, printLink, friendLink, hideClass;










    $('a.target-_blank').addTargetBlank();













    $('.make-corners').addCorners();
    $('.welcome-box').addCorners();
    $('#intro').addCorners();
    $('.m-shortcuts').addCorners();
    $('.m-calendar').addCorners();
    $('.m-institutions .m-c-inner').addCorners();
    $('.m-freetext').addCorners();
    $('.m-healthservice').addCorners();

    $('table:not(.calendar)').addTableCorners();

    $('.find input').populateValue();

    $('table.zebra tbody').each(function() {
        $(this).makeZebraTable();
    });

    if (!document.isStartPage()) {
        printLink = document.articleFunctions.addItem({
            text: '<span>' + printLabel + '</span>',
            className: 'print',
            callback: function(e) {
                e.preventDefault();
                window.print();
            }
        });
        tell = $('#' + tellAFriendFormID);
        if (tell.size()) {
            if (window.location.hash == '#' + tellAFriendFormID) {
                tell.show();
                tell.isHidden = false;
            } else {
                tell.hide();
                tell.isHidden = true;
            }
            friendLink = document.articleFunctions.addItem({
                text: '<span>' + tellAFriendLabel + '</span>',
                className: 'tell-a-friend',
                callback: function(e) {
                    e.preventDefault();
                    if (tell.isHidden) {
                        tell.animate({
                            height: 'show',
                            opacity: 'show'
                        }, 'slow', function() {
                            var targetOffset = tell.offset().top;
                            $('html,body').animate({
                                scrollTop: targetOffset
                            }, 1000, function() {
                                window.location.hash = '#' + tellAFriendFormID;
                            });
                            tell.isHidden = false;
                        });
                    } else {
                        tell.animate({
                            height: "hide",
                            opacity: "hide"
                        }, 'slow', function() {
                            tell.isHidden = true;
                        });
                    }
                }
            });
        }
    }

    if (document.isAdjustPage()) {
        document.initAdjustEvents();
    }

    //document.setHtmlClass('color-combination');

    $(".search").submit(
        function() {
            var searchInput = $(this).find("#searchtext, #searchtext2");

            if (searchInput.length === 1 && searchInput.val() === searchInput.attr("title"))
                searchInput.val("");
        }
    )
});