window.currentPopup = null;
Event.onDOMReady(initPopups);

function initPopups() {
	for (var i = 0, link = null; link = $$('a[rel="popup"]')[i]; i++) {
		if (link.href.split('#') && $(link.href.split('#')[1]) && window.location.href.split('#')[0] == link.href.split('#')[0]) {
			$(link.href.split('#')[1]).hide();

			link.onclick = function() {
				var title = this.title || 'Telenor Kundeservice';
				if (window.currentPopup != null && window.currentPopup.close) window.currentPopup.close();
				window.currentPopup = new Popup(this, null, 'confirm');
				window.currentPopup.render($(this.href.split('#')[1]), title);
				return false;
			};
		} else {
			link.onclick = function() {
				var title = this.title || 'Telenor Kundeservice';
				if (window.currentPopup != null && window.currentPopup.close) window.currentPopup.close();
				window.currentPopup = new IframePopup(this, null, 'iframe');

				if (this.href.indexOf('#') >= 0) {
					var url = (this.href.split('#')[0]);
					url = url.indexOf('?') >= 0 ? url + '&' : url + '?';
					url = url + 'layout=lightbox#' + (this.href.split('#')[1]);
					window.currentPopup.render(url, title);
				} else {
					var url = this.href.indexOf('?') >= 0 ? this.href + '&' : this.href + '?';
					window.currentPopup.render(url + 'layout=lightbox', title);
				}
				return false;
			};
		}
	}
}

function closeCallback(closeButton) {
	window.currentPopup = null;

	if (closeButton.className.indexOf('update') > 0)
		window.parent.location.href = window.parent.location.href;
}

var Popup = Class.create();
Popup.prototype = {
	overlayClass: null,
	overlay: null,
	useOverlay: true,
	useCloseButton: true,

	initialize: function(parent, id, classNames) {
		this.window = Element.extend(HTMLDOMUtil.createElement('div', 'popup'));
		this.body = $(document.getElementsByTagName('body')[0]);

		if (parent == null)
			this.parent = this.body;
		else
			this.parent = $(parent);

		if (classNames != null) this.window.addClassName(classNames);
		if (id != null) this.window.id = id;
	},

	render: function(content, title) {
		if (title != null) this.window.appendChild(HTMLDOMUtil.createElement('div', 'title', null, null));

		if (content instanceof String) {
			this.window.innerHTML = content;
		} else {
			var c = $(content.cloneNode(true));
			c.id = c.id + '_popup';
			c.removeClassName('section');
			c.show();

			if (this.window.id == null || this.window.id == '') this.window.id = c.id + '_frame';
			this.window.appendChild(c);
		}

		this.body.appendChild(this.window);
		var pos = HTMLUtil.getScrollTop();
		this.window.style.top = (pos + 50) + 'px';

		if (this.useOverlay) this.createOverlay();
		if (this.useCloseButton) this.addCloseButton();

		var confirm = document.getElementsByClassName('confirm', this.window);
		var cancel = document.getElementsByClassName('cancel', this.window);

		for (var i = 0, element = null; (element = confirm[i]); i++)
			window.currentPopup.registerConfirmButton(element);

		for (var i = 0, element = null; element = cancel[i]; i++)
			window.currentPopup.registerCancelButton(element);
	},

	getWindowPosition: function() {
		var offset = Position.cumulativeOffset(this.parent);
		var dim = this.window.getDimensions();
		var pageSize = HTMLUtil.getPageSize();
		var left = offset[0];
		var top = offset[1];

		if ((pageSize.windowWidth - left) < dim.width)
			left = (left - dim.width) >= 0 ? left - dim.width : (pageSize.windowWidth - dim.width);

		if ((pageSize.windowHeight - top) < dim.height)
			top = (top - dim.height) >= 0 ? top - dim.height : (pageSize.windowHeight - dim.height);

		return { left: left, top: top };
	},

	setOverlayClass: function(className) {
		this.overlayClass = className;
	},

	setUseOverlay: function(use) {
		this.useOverlay = use;
	},

	createOverlay: function() {
		this.overlay = HTMLDOMUtil.createElement('div', this.overlayClass, 'overlay');
		var pageDimensions = $(document.documentElement).getDimensions();
		this.overlay.popup = this;
		this.overlay.ondblclick = function() { this.popup.close(); };
		this.toggleSelects();

		this.body.appendChild(this.overlay);

		var version = 0;
		
		if (navigator.appVersion.indexOf("MSIE")!=-1) {
			var temp = navigator.appVersion.split("MSIE");
			version = parseFloat(temp[1]);
		}

		if (version >= 5.5)
			return;

		// TODO:This function should probably be simplified as this is no longer needed for FF or Opera at least
		//this.overlay.style.height = pageDimensions.height + 'px';
	},

	addCloseButton: function(text) {
		var closeImg = HTMLDOMUtil.createElement('img', null, null, null, 
			['src', '/design/images/lightbox/close.gif', 'alt', 'Lukk', 'title', 'Lukk']);
		var closeLink = HTMLDOMUtil.createElement('a', 'close', null, closeImg, ['href', '', 'popup', this]);
		this.registerButton(closeLink, false);
		this.window.insertBefore(closeLink, this.window.firstChild);
	},

	close: function(closeButton) {
		if (this.overlay != null) $(this.overlay).remove();
		$(this.window).remove();

		if (window.closeCallback)
			closeCallback(closeButton);
	},

	toggleSelects: function() {
		var elements = document.getElementsByTagName('select');

		for (var i = 0, element = null; element = $(elements[i]); i++)
			if (element.hasClassName('hidden'))
				element.removeClass('hidden');
			else
				element.addClass('hidden');
	},

	registerButton: function(button, returnValue) {
		button = $(button);
		button.popup = this;

		button.onclick = function(e) {
			var val = this.popup.buttonClick(returnValue);
			if (val) this.popup.close(this);

			return false;
		};
	},

	registerCancelButton: function(button) {
		this.registerButton(button, false);
	},

	registerConfirmButton: function(button) {
		this.registerButton(button, true);
	},

	buttonClick: function(val) {
		return true;
	}
};

var IframePopup = Class.create();
IframePopup.prototype = Object.extend(new Popup(), {
	renderPopup: Popup.prototype.render,
	content: null,

	render: function(url, title) {
		var iframe = HTMLDOMUtil.createElement('iframe', null, 'externalResourceWindow');
		iframe.src = url;
		iframe.frameBorder = '0';
		iframe.scrolling = 'no';
		iframe.title = title;
		var dim = URL.getParameter('dim', url);

		if (dim != null) {
			dim = [parseInt(dim.split('x')[0], 10), parseInt(dim.split('x')[1], 10)];

			if (dim[0].toString() != 'NaN') {
				this.window.style.width = dim[0] + 'px';
				this.window.style.marginLeft = Math.round(-dim[0]/2) + 'px';
				iframe.style.width = dim[0] + 'px';
			}

			if (dim[1].toString() != 'NaN' && dim[1] > 26) {
				this.window.style.height = dim[1] + 'px';
				iframe.style.height = (dim[1] - 35) + 'px';
			}
			this.renderPopup(iframe, title);
		} else {
			//render then scale
			this.renderPopup(iframe, title);
			// Wait to not crash IE and Opera TODO make a better solution for this, body:onload in iframe?
			setTimeout(this.fitToContent, 1000);
		}
	},
	
	fitToContent: function() {
		// find the height of the internal page
		var rw = document.getElementById('externalResourceWindow_popup');

		if (!rw || !rw.contentWindow || !rw.contentWindow.document) return;
		var the_height = rw.contentWindow.document.body.offsetHeight;
		
		if (the_height < 10) {
		// TODO dont think this is correct
			setTimeout(this.fitToContent, 1000);
		} else {
			if (self.innerHeight) {	// all except Explorer
				// add space for absolute positioned buttons at the bottom
				the_height = the_height + 44;
			}
			
			// change the height of the container
			document.getElementById('externalResourceWindow_popup_frame').style.height = (the_height + 35) + 'px';
		
			// change the height of the iframe
			document.getElementById('externalResourceWindow_popup').style.height =  the_height + 'px';
		}
		return true;
	}
});
