﻿SolnaStad.PopUpManager = (function() {
	var container, shade, PopUp;
	var popups = [];
	var hiddenPopUpClass = 'hidden-popup';
	var topZ = 100000;

	function paintItBlack() {
		///<summary>Cover the entire page with a black, semi-transparent background</summary>
		shade.css({
			position: 'absolute',
			width: $(window).width(),
			height: $('body').outerHeight() + 20
		});
		// If this is IE6, hide all selects on the page
		if ($.browser.msie && $.browser.version.match(/^6\./)) {
			$('select').hide();
			popups[popups.length - 1].contentDiv.find('select').show();
		}
	}

	function letTheSunshineIn() {
		///<summary>Removes black background set by paintItBlack</summary>
		shade.css({
			position: 'static',
			height: 'auto'
		});
		// If this is IE6, show all selects againg
		if ($.browser.msie && $.browser.version.match(/^6\./)) {
			$('select').show();
		}
	}

	function createContainer() {
		container = $('<div id="popups"></div>');
		shade = $('<div id="popup-shade"></div>');
		shade.click(function(e) {
			popups[popups.length - 1].hide();
		});
		$('body').append(container).append(shade);
		$('body').keypress(function(e) {
			if (e.keyCode === 27) {
				// Close top popup if esc is pressed
				popups[popups.length - 1].hide();
			}
		});
	}

	function addPopUp(options) {
		if (!container) {
			createContainer();
		}
		var popup = new PopUp(options);
		popups.push(popup);
		return popup;
	}

	function removePopUp(indexOrPopup) {
		var index, popup;
		if ((/^\d+$/).test(indexOrPopup)) {
			index = indexOrPopup;
			popup = popups[index];
		} else {
			popup = indexOrPopup;
			index = $.inArray(popup, popups);
		}
		if (popup && (index || index === 0)) {
			// Remove DOM elements
			popup.wrapper.remove();
			// Remove popup instance
			popups.splice(index, 1);
		}
	}

	function PopUp(options) {
		this.options = $.extend({}, this.options, options || {});
		this.hidden = true;
	}
	PopUp.prototype = {
		options: {
			// A modal popup blacks out the background
			modal: false,
			// Size of popup {width, height}
			dimensions: {},
			// Whether to add a close button
			closeButton: true,
			// Content to display. Can be text or DOM node
			content: null,
			// Url to get content from
			contentURL: null,
			// Classname to add to popup
			className: null
		},
		setContent: function(content) {
			var t = this,
			    div = this.contentDiv;
			if (div) {
				if (typeof content == 'string') {
					div.html(content);
				} else {
					div.empty();
					div.append(content);
				}
				div.find('a.cancel, a.close').click(function(e) {
					e.preventDefault();
					t.hide();
				});
			} else {
				this.options.content = content;
			}
		},

		toggle: function() {
			(this.hidden ? this.show() : this.hide());
		},

		show: function() {
			var t = this;
			function show() {
				if (t.options.modal) {
					// Black out the page if this is a modal popup
					paintItBlack();
				}
				t.wrapper.removeClass(hiddenPopUpClass);
				t.hidden = false;
			}
			// Overwrite the show method with the one defined above
			this.show = show;

			function createAndShow() {
				t.createElements();
				show();
			}

			// Create elements on first open
			if (this.options.contentURL) {
				$.get(this.options.contentURL, {}, function(data) {
					t.setContent(data);
					createAndShow();
				});
			} else {
				createAndShow();
			}
		},

		hide: function() {
			//this.fireEvent('onHide', this);
			this.wrapper.addClass(hiddenPopUpClass);
			this.hidden = true;
			if (this.options.modal) {
				// Remove black backdrop
				letTheSunshineIn();
			}
		},

		destroy: function() {
			removePopUp(this);
		},

		setPosition: function() {
			var self = this,
			    intervalID;
			// This function is executed at intervals to make sure the wrapper is created
			function set() {
				if (self.wrapper) {
					clearInterval(intervalID);
					self.wrapper.css({
						top: $(window).scrollTop() + 20,
						left: ($(window).width() / 2) - (self.wrapper.width() / 2),
						visibility: ''
					});
				}
			}
			intervalID = setInterval(set, 10);
		},

		placeOnTop: function() {
			topZ = topZ + 1;
			this.wrapper.css('z-index', topZ);
		},

		createElements: function() {
			var opt = this.options, self = this, closeButton;

			//this.fireEvent('onCreate', this);            
			this.wrapper = $('<div class="popup' + (opt.className ? ' ' + opt.className : '') + '"></div>');
			this.wrapper.css({
				'width': (/^\d+$/).test(opt.dimensions.width) ? parseInt(opt.dimensions.width, 10) + 'px' : '',
				'height': (/^\d+$/).test(opt.dimensions.height) ? parseInt(opt.dimensions.height, 10) + 'px' : '',
				'visibility': 'hidden'
			});
			this.contentDiv = $('<div class="content"></div>');

			container.append(this.wrapper.append(this.contentDiv));

			if (opt.content) {
				this.setContent(opt.content);
			}
			this.placeOnTop();
			this.setPosition();
			this.fireEvent('afterCreate', this);

		},
		fireEvent: function(event) {
			if (this.options[event] && typeof this.options[event] == 'function') {
				this.options[event].apply(this);
			}
		}
	};

	return {
		addPopUp: addPopUp
	};

})();