/**
 *	Usage
 *	new W.Popup({id: 'slides', callback: obj.method.bind(obj)});
 * 	new W.Popup({width: 800, height: 600, classname: 'iframe', iframe: 'index.html'});
 *
 *	Note: if adding your own classname, make sure the class has position: absolute
 *
 * @requires W
 * @requires W.Dom
 * @requires W.Request
 */
W.Popup = function(param)
{
	this.init(param);
};



W.Popup.prototype = {
	
	classname		: '',
	width			: 0,
	height			: 0,
	top				: '50%',
	left			: '50%',
	iframe			: null,
	scrolling		: null,			// scrolling for popup window, or iframe
	id				: 'popup_win',
	xhr				: null,
	method			: 'GET',
	callback		: null,			// reference to exit callback function when exiting popup
	dim				: true,			// enable or disable dimming of the main page
	popup			: null,			// reference to popup window
	src				: '',			// content for innerHTML of popup window
	confirm_xhr		: null,			// for confirmation windows - xhr if action is confirmed
	hideFlash		: false,
	deleteOnExit	: true,
	
	

	init : function(param)
	{
	
		if (param) {
			this.classname		= param.classname || this.classname;
			this.width			= parseInt(param.width) || 0;
			this.height			= parseInt(param.height) || 0;
			this.iframe			= param.iframe;
			this.scrolling		= param.scrolling? 'yes' : 'no';
			this.id				= param.id || 'popup_win';
			this.xhr			= param.xhr;
			this.method			= param.method || this.method;
			this.callback		= param.callback;
			this.src			= param.src;
			if (param.dim !== undefined) { this.dim = param.dim; }
			if (param.deleteOnExit !== undefined) { this.deleteOnExit = param.deleteOnExit; }
		}
		
		if (navigator.userAgent.toLowerCase().indexOf('safari') != -1) { this.hideFlashFromSafari(); }

		this.overlay();
		this.window();
		this.populate();
	},
	
	
	
	confirm : function(message, xhr)
	{
		var obj			= this;
		var id			= this.id;
		
		var header	= '<div class="header"><div class="left"><div class="right"><div class="content"><a id="' + id + '_close" href="javascript:void(0)">Cancel</a></div></div></div></div>'
		var main	= '<div class="main"><div class="left"><div class="content"><p>' + message + '</p><p>This action cannot be undone.</p><p style="text-align: right"><a href="javascript:void(0)" id="confirm_action">confirm</a></div></div></div></div>';
		var footer	= '<div class="footer"><div class="left"><div class="right"></div></div></div>';
		
		this.src			= header + main + footer;
		this.width			= 300;
		this.height			= 200;
		this.classname		= 'popup_confirm';
		this.confirm_xhr	= xhr;
		
		this.window();
		this.populate();
		this.center();
		W.$(id + '_close').onclick 		= function() { obj.exit(); };
		W.$('confirm_action').onclick	= function() { obj.confirm_action(); };
	},
	
	
	
	confirm_action : function()
	{
		var obj	= this;
		
		new W.Request(this.method, this.confirm_xhr).call(obj.receive_confirm.bind(obj));
	},
	
	
	
	receive_confirm : function(req)
	{
		if (req.responseText == '') { return; }
		var result	= eval('(' + req.responseText + ')');
		
		if (result.status == 'ok') {
			if (result.redirect == 'location.href') {
				if (window.location.href.indexOf('#') != -1) {
					window.location.reload();						// reloads pages the have anchors, ie investments.php#notes
				} else {
					window.location.href = window.location.href;	// prevents an alert if form was submitted
				}
			} else {
				window.location = result.redirect;
			}
		}
	},
	
	
	
	hideFlashFromSafari : function()
	{
		var embeds = document.getElementsByTagName('embed');
		
		for (var i = embeds.length; --i >= 0; ) {
			embeds[i].style.visibility		= 'hidden';
		}
	},
	
	
	
	showFlash : function()
	{
		var embeds	= document.getElementsByTagName('embed');
		
		for (var i = embeds.length; --i >= 0; ) {
			embeds[i].style.visibility		= 'visible';
		}
		
		
		var objects	= document.getElementsByTagName('object');
		
		for (i = objects.length; --i >= 0; ) {
			objects[i].style.visibility		= 'visible';
		}
	},
	
	
	
	overlay : function()
	{
		var obj					= this;
		
		var win					= W.Dom.getContentSize();
		
		if (!W.$('overlay')) {
			var div					= document.createElement('div');
			div.style.position		= 'absolute';
			div.style.left			= 0;
			div.style.top			= 0;
			div.style.height		= win.y + 'px';
			div.style.width			= win.x + 'px';
			div.id					= 'overlay';
			div.onclick				= function() { obj.exit(); };
			
			document.getElementsByTagName('body')[0].insertBefore(div, null);
		} else {
			W.$('overlay').style.display = 'block';
		}
	},



	window : function()
	{
		var div;
		
		if (!W.$(this.id)) {
			div		= document.createElement('div');
			div.id	= this.id;
			
	
			if (this.classname) {
				div.className			= this.classname;
			} else {
				div.style.position		= 'absolute';
				//div.style.display		= 'none';
			}
			
		} else {
			this.popup = div = W.$(this.id);
			if (this.classname) { div.className = this.classname; }
			div.style.display = 'block';
		}
		

		//***** insert the popup *****//
		div.style.visibility	= 'hidden';
		div	= document.getElementsByTagName('body')[0].insertBefore(div, null);
		
		
		this.popup				= div;
	},
	
	
	
	center : function()
	{
		div = this.popup;
		var scroll				= W.Dom.getScroll();
		
		
		//***** set the height and width *****//
		if (this.height) {
			div.style.height	= this.height + 'px';
		} else {
			// check if height is set in the style sheet
			if (!isNaN(this.height = parseInt(W.Dom.getStyle(div, 'height'), 10))) { div.style.height = this.height + 'px'; } else { this.height = div.offsetHeight; }
		}
		
		if (this.width) {
			div.style.width	= this.width + 'px';
		} else {
			// check if width is set in the style sheet
			if (!isNaN(this.width = parseInt(W.Dom.getStyle(div, 'width'), 10))) { div.style.width = this.width + 'px'; } else { this.width = 0; }
		}
		
		//***** set the top and left *****//
		if (this.top == '50%') {
			div.style.marginTop = -(parseInt(this.height / 2, 10)) + scroll.y + 'px';
		} else {
			var top;
		
			if ((top = parseInt(W.Dom.getStyle(div, 'top'), 10)) !== 0 && !isNaN(top)) { this.top = top + 'px'; }
		}
		
		
		if (this.left == '50%') {
			div.style.marginLeft = -(parseInt(this.width / 2, 10)) + scroll.x + 'px';
		} else {
			var left;
		
			if ((left = parseInt(W.Dom.getStyle(div, 'left'), 10)) !== 0 && !isNaN(top)) { this.left = left + 'px'; }
		}
		
		
		div.style.top			= this.top;
		div.style.left			= this.left;
		div.style.visibility	= 'visible';
		
	},
	
	
	
	cancel : function()
	{
		this.callback	= null;
		this.exit();
	},
	
	
	
	submit : function(param)
	{
		if (this.callback) { this.callback(param); }
		
		this.exit();
	},



	exit : function()
	{
		if (navigator.userAgent.toLowerCase().indexOf('safari') != -1) { this.showFlash(); }
		
		if (this.callback) { this.callback(); }
		
		if (this.deleteOnExit) {
			if (this.iframe) { this.popup.getElementsByTagName('iframe')[0].parentNode.removeChild(this.popup.getElementsByTagName('iframe')[0]); }
			document.getElementsByTagName('body')[0].removeChild(W.$(this.id));
			document.getElementsByTagName('body')[0].removeChild(W.$('overlay'));
		} else {
			W.$('overlay').style.display = 'none';
			W.$(this.id).style.display = 'none';
		}
	},



	populate : function()
	{
		var obj	= this;
		
		if (this.iframe && !document.getElementById(this.id + '_iframe')) { 
			//this.popup.innerHTML	= '<iframe allowtransparency="1" id="' + this.id + '_iframe" name="' + this.id + '_iframe" width="' + this.width + '" height="' + this.height + '" src="' + this.iframe + '" frameborder="0" scrolling="' + this.scrolling + '" onload="parent.frames[\'' + this.id + '_iframe\'].document.body.className=\'' + this.classname + '\'"></iframe>'; 
			//if (document.all) {
				// needed for ie to render iframe with transparency
			//	this.popup.innerHTML	= '<iframe allowtransparency="1" id="' + this.id + '_iframe" name="' + this.id + '_iframe" width="' + this.width + '" height="' + this.height + '" src="' + this.iframe + '" frameborder="0" scrolling="' + this.scrolling + '"></iframe>'; 
			//} else {
				// needed for Firefox to be able to get reference to iframe using name attribute
				var iframe			= document.createElement('iframe');
				iframe.name			= this.id + '_iframe';
				iframe.id			= iframe.name;
				iframe.width		= this.width;
				iframe.height		= this.height;
				iframe.frameBorder	= 0;
				iframe.className	= this.classname;
				iframe.scrolling	= this.scrolling;
				iframe.src			= this.iframe;
				//iframe.allowtransparency	= "true";		// doesn't work
			
				this.popup.appendChild(iframe);
				this.center();
			//}
			
			
			// create phantom iframe for blocking select lists
			/*
			var content_iframe				= W.$(this.id + '_iframe');
			var phantom_iframe				= document.createElement('iframe');
			phantom_iframe.name				= this.id + '_phantom_iframe';
			phantom_iframe.width			= content_iframe.offsetWidth + 'px';
			phantom_iframe.height			= content_iframe.offsetHeight + 'px';
			phantom_iframe.frameBorder		= 0;
			phantom_iframe.style.position	= 'absolute';
			phantom_iframe.style.top		= 0;
			phantom_iframe.style.left		= 0;
			phantom_iframe.style.zIndex		= content_iframe.style.zIndex - 1;
			
			this.popup.appendChild(phantom_iframe);
			*/
		}
		
		if (this.iframe) {
			if (iframe.attachEvent) {		// WinIE
				iframe.attachEvent('onload', function() {
					if (iframe.contentWindow.document.getElementById('popup_close')) iframe.contentWindow.document.getElementById('popup_close').onclick = function() { obj.exit(); };
					if (iframe.contentWindow.document.getElementById('cancel')) iframe.contentWindow.document.getElementById('cancel').onclick = function() { obj.exit(); };
				});
			} else {						// Firefox, Safari
				iframe.onload = function() {
					if (iframe.contentDocument.getElementById('popup_close')) iframe.contentDocument.getElementById('popup_close').onclick = function() { obj.exit(); };
					if (iframe.contentDocument.getElementById('cancel')) iframe.contentDocument.getElementById('cancel').onclick = function() { obj.exit(); };
				};
			}
			this.center();
		}
				
		if (this.src) { this.popup.innerHTML = this.src; }
		
		if (this.xhr) { new W.Request(this.method, this.xhr).call(obj.receive.bind(obj)); }
		
		if (this.content_id) { this.popup.appendChild(W.$(this.content_id)); }
	},
	
	
	
	receive : function(req)
	{
		var content				= req.responseText;
		this.popup.innerHTML	= content;
		
		var pattern = /<script[^>]*>(.*?)<\/script>/gi;
		var result;
				
		while((result = pattern.exec(content.replace(/\n/g, ""))) !== null) {
			eval(result[1]);
		}
		
		var close;
		var obj	= this;
		if ((close = W.$('popup_close')) !== null) { close.onclick = function() {obj.exit(); return false; }; }
		
		this.center();
	}
};

