/* Create NetR namespace */
if(typeof NetR == "undefined"){ var NetR = {}; }

/**
* @requires jQuery
* Finds all links with the supplied combination of attribute and value
* and sets their target attribute to '_blank' to open a new window.
* An image can be used instead of plain text.
*/
NetR.JSTarget = function () {
	var options = {
		att: 'class', // The attribute to look for
		val: 'new-window', // The value that triggers a new window
		widthPrefix: 'w', // Prefixes for width and height (e.g. w400 h400)
		heightPrefix: 'h',
		warning: 'Nytt fönster', // Text that is appended to the link
		image: null, // The URL for an image that is used instead of plain text
		imageLinkClass: 'nw-image', // Class added to links that contain images
		hiddenClass: 'structural' // Class added to the image
	};
	/**
	* Initialization
	*/
	function init(opts) {
		// If options were supplied, apply them to the option Object.
		for (var key in opts) {
			if (options.hasOwnProperty(key)) {
				options[key] = opts[key];
			}
		}
		var oWarning, oImage;
		var reAtt = new RegExp("(^|\\s)" + options.val + "(\\s|$)");
		var reWidth = new RegExp("(^|\\s)" + options.widthPrefix + "([0-9]+)(\\s|$)");
		var reHeight = new RegExp("(^|\\s)" + options.heightPrefix + "([0-9]+)(\\s|$)");
		$('a').each(function () {
			var sAttVal;
			if (options.att == 'class') {
				sAttVal = this.className;
			} else {
				sAttVal = this.getAttribute(options.att);
			}
			if (reAtt.test(sAttVal)) {
				if (options.image) {
					oImage = document.createElement('img');
					oImage.src = options.image;
					oImage.setAttribute('alt', options.warning);
					oImage.className = options.hiddenClass;
					this.appendChild(oImage);
					$(this).addClass(options.imageLinkClass);
					this.setAttribute('title', options.warning);
				} else {
					oWarning = document.createElement("em");
					oWarning.appendChild(document.createTextNode(' (' + options.warning + ')'));
					this.appendChild(oWarning);
				}
				// If width and height values exist, open a sized window
				if (reWidth.test(sAttVal) && reHeight.test(sAttVal)) {
					$(this).click(function (e) {
						e.preventDefault();
						var sOptions = 'left=20,top=20,screenX=20,screenY=20,menubar=yes,toolbar=no,location=yes,resizable=yes,scrollbars=yes,status=yes,width=' + reWidth.exec(sAttVal)[2] + ',height=' + reHeight.exec(sAttVal)[2];
						window.open(this.href, '_blank', sOptions);
					});
				}
				else
				{
					this.target = '_blank';
				}
			}
		});
		oWarning = null;
		oImage = null;
	}
	return {
		init: init
	};
}();

$(document).ready(function () {
	NetR.JSTarget.init();

	$("a[href$='pdf']").click(function () {
		pageTracker._trackPageview(this.pathname);
	});

	var share = $('#share ul');
	var emailbox;

	share.find('.email-page a').click(function (e) {
		e.preventDefault();

		if (!emailbox) {

			var el = $(this);
			var selector = ('#' + el.attr('hash')).replace('##', '#');
			emailbox = $('<div class="email-page-form">');

			// IE seems to escape the hash part and send it along to the server.
			// This might cause an error, so we have to take the hash part away before requesting
			$.get(el.attr('href').replace(/#.+$/, ''), function (data) {
				var form = (selector == '#' ? $(data) : $(selector, data));
				if (form.length) {
					emailbox.hide();
					$('#footer').before(emailbox);
					emailbox.append(form);
					emailbox.slideDown();
					form.submit(function (e) {
						e.preventDefault();
						// Post/get with ajax
						$[form.attr('method') || 'post'](form.attr('action'), form.serialize(), function (data) {
							var content = selector == '#' ? data : $(selector, data);
							if (content.length) {
								// Set new dialog content
								emailbox.html(content);
							} else {
								emailbox.html('<p>Ett fel har tyvärr uppstått. Var vänlig försök igen.</p>');
							}
						});
					});
				}
			});
		} else {
			emailbox.slideToggle();
		}

	});

	var favouritesLink = $('<li><a href="' + document.URL + '" class="service-add-favourite" title="Spara den här sidan som ett bokmärke"><img src="/i/share-services/favourites.png" alt="Spara den här sidan som ett bokmärke" /></a></li>');
	share.append(favouritesLink);

	try {
		if (window.sidebar && window.sidebar.addPanel) {
			// Firefox
			favouritesLink.click(function (e) {
				e.preventDefault();
				window.sidebar.addPanel(document.title, document.URL, "");
			});
		} else if (document.all) {
			// Internet Explorer
			favouritesLink.click(function (e) {
				e.preventDefault();
				window.external.AddFavorite(document.URL, document.title);
			});
		} else if ($.browser.opera) {
			// Opera
			favouritesLink.find('a').attr({
				'rel': 'sidebar',
				'title': document.title
			});
		} else {
			// Other browsers get nothing :(
			favouritesLink.remove();
		}
	} catch (e) {
		// To prevent non working link, remove it if something breaks
		favouritesLink.remove();
	}

	// Print button
	share.append($('<li>').append($('<a>', {
		href: '#',
		className: 'print-page',
		html: '<img src="/i/share-services/print.png" alt="Skriv ut" />',
		title: 'Skriv ut',
		click: function (e) {
			e.preventDefault();
			window.print();
		}
	})));

	// Refine search box vertical position
	if ($("#search-header").length) {
		var contentTop = Math.round($("#content").offset().top);
		var sHeaderTop = Math.round($("#search-header").offset().top);
		var contSec = $("#content-secondary");

		contSec.css("position", "relative").css("top", sHeaderTop - contentTop + "px");

		$("#content").css("min-height", $(".refine-search").outerHeight() + (sHeaderTop - contentTop));
	}

	NetR.SiteSeeker.init();
	NetR.SiteSeeker.AutoComplete($('input[id^="searchtext"]'));
});
