var PopoverWindow = new function() {
	// setting your media path is important
	// it is relative to the webpage from which the popup is launched
	// or you can set the full URL such as "http://example.com/popover/media"
	// no trailing slash on the path is required
	this.path = '';
	this.loadingURL = 'loading.html';
	this.ready = false;
	this.shown = false;
	this.autoURL = '';
	this.defaultCount = 0;
	this.defaults = {

		// settings
		width : 500,
		height : 400,
		icon : 'default',
		title : 'Serial Number Results',
		showOverlay : true,
		scrolling : true,
		showClose : true,
		fadeIn : true,
		fadeOut : true,
		drag : true,
		resize : true,
		
		// theme
		titleFont : 'sans-serif',
		titleColor : 'black',
		titleSize : '8pt',
		windowColor : '#c0c0c0',
		overlayColor : 'black',
		overlayOpacity : 0.7,
		pageBorder : true,
		pageBorderSize : 1,
		pageBorderColor : '#888',
		pageBorderStyle : 'solid',
		windowPadding : 5
		
	};
	this.options = null;
	
	this.setPath = function(path) {
		this.path = path;
		this.loadingURL = path + '/loading.html';
	};
	
	this.init = function() {
		var pid = 'popover';
		PopoverWindow.insert(pid);
		
		if (id(pid+'_main')) {
			this.elm = this.elements('popover');
			
			style.opacity(this.elm.overlay,0);
			
			var me = this;
			dom.addEvent(this.elm.overlay,'mousedown',function() {
				me.hide();
			});
			dom.addEvent(this.elm.close,'mousedown',function() {
				me.hide();
			});
			dom.addEvent(this.elm.close,'mouseover',function() {
				me.closeOver();
			});
			dom.addEvent(this.elm.close,'mouseout',function() {
				me.closeOut();
			});
			dom.addEvent(this.elm.title,'mousedown',function(e) {
				me.dragStart(e);
			});
			dom.addEvent(this.elm.resize,'mousedown',function(e) {
				me.resizeStart(e);
			});
			dom.addEvent(document,'mouseup',function(e) {
				me.dragEnd(e);
				me.resizeEnd(e);
			});
			
			style.opacity(this.elm.cover,0);
			dom.addEvent(document,'mousemove',function(e) {  //this.elm.cover
				me.dragMove(e);
				me.resizeMove(e);
			});
			
			//window.onscroll = this.reset;
			//window.onresize = this.resize;
			
			PopoverWindow.ready = true;
			if (this.autoURL) this.show(this.autoURL);
		}
		//else alert(overlay+"PopoverWindow Error: DIV#popover_main element not found");
	};
	
	this.insert = function(pid,generator) {
		if (!generator) {
			var overlay = document.createElement('div');
			overlay.id = pid+'_overlay';
			overlay.className = 'popover_overlay';
			document.body.appendChild(overlay);
			
			var mousecover = document.createElement('div');
			mousecover.id = pid+'_mousecover';
			mousecover.className = 'popover_mousecover';
			document.body.appendChild(mousecover);
		}
		
		var main = document.createElement('div');
		main.id = pid+'_main';
		main.className = 'popover_main';
		
		if (generator) main.style.position = 'relative';
		else main.style.position = (jaxscript.client.supports('fixed'))? 'fixed':'absolute';
		
		main.innerHTML = '<div id="'+id+'_titlebar" class="popover_titlebar">\
			<span id="'+pid+'_tab" class="popover_tab">\
				<span id="'+pid+'_tabwrap" class="popover_tabwrap">\
					<a id="'+pid+'_title" class="popover_title" href="javascript://" title="Click to move Window"></a>\
					<a id="'+pid+'_close" class="popover_close" href="javascript://" title="Close Window">&nbsp;&nbsp;&nbsp;&nbsp;</a>\
				</span>\
			</span>\
		</div>\
		<a id="'+pid+'_resize" class="popover_resize" href="javascript://"></a>\
		<div id="'+pid+'_content" class="popover_content">'+
			(generator? 
			'<div id="'+pid+'_iframe" class="popover_iframe"></div>'
			:
			'<iframe id="'+pid+'_iframe" class="popover_iframe" src="'+this.loadingURL+'" frameborder="0"></iframe>'
			)+
		'</div>';
		
		if (generator) id('popover_generator').appendChild(main);
		else document.body.appendChild(main);
	};
	
	this.defaultLoad = function() {
		this.defaultCount++;
		if (this.defaultCount>1) {
			this.hide();
		}
	};
	
	this.closeOver = function() {
		this.elm.close.style.backgroundImage = 'url('+this.path+'/images/close.png)';
	};
	this.closeOut = function() {
		this.elm.close.style.backgroundImage = 'url('+this.path+'/images/closegrey.png)';
	};
	
	this.setTheme = function(theme) {
		this.theme = theme;
	};
	
	this.setOptions = function(options) {
		if (!options) options = this.defaults;
		for (var i in this.defaults) {
			if (typeof options[i]=='undefined') {
				options[i] = this.defaults[i];
			}
			else {
				if (parseInt(options[i])==options[i]) options[i] = parseInt(options[i]);
			}
		}
		this.options = options;
		return options;
	};
	
	// colorSync is an optional feature to synchronize the background of the popup page
	// this is not necessary if you explicitly set the background color in the CSS of your popover page.
	// to the color assigned in the PopupWindow options
	// to use this feature inclue the following code in your popup page html:
	/*
	
	<script language="javascript">
	if (parent.PopoverWindow) parent.this.colorSync(this);
	</script>
	
	*/
	this.colorSync = function(iframe) {
		if (this.options && this.options.pageColor) {
			var body;
			if (iframe.document) body = iframe.document.body;
			if (iframe.contentWindow) iframe.contentWindow.document.body;
			if (body) body.style.backgroundColor = this.options.pageColor;
		}
	};
	
	this.elements = function(pid) {
		return {
			main : id(pid+'_main'),
			content : id(pid+'_content'),
			iframe : id(pid+'_iframe'),
			overlay : id(pid+'_overlay'),
			close : id(pid+'_close'),
			title : id(pid+'_title'),
			resize : id(pid+'_resize'),
			tab : id(pid+'_tab'),
			cover : id(pid+'_mousecover')
		}
	}
	
	this.show = function(url, options, generator) {
		if (options) this.setOptions(options);
		var options = this.options;
		if (generator) echo('showing generator');
		if (!this.ready) {
			this.autoURL = url;
			return; // auto show on init?
		}
		var d = (generator)? this.elements('generator') : this.elm;
		
		if (!generator) {
			style.visible(d.overlay,false);
			if (options.overlayColor) d.overlay.style.backgroundColor = options.overlayColor;
		}
		
		if (options.showClose) {
			d.close.style.backgroundImage = 'url('+this.path+'/images/closegrey.png)';
			d.close.style.display = 'inline';
		}
		else {
			style.display(d.close,false);
		}
		
		d.tab.className = (options.roundedCorners)? 'popover_tab popover_roundtab':'popover_tab';
		d.content.className = (options.roundedCorners)? 'popover_content popover_roundcontent':'popover_content';
		
		d.iframe.scrolling = (options.scrolling)? 'auto':'no';
		
		// resizing
		var tabsize = dimensions(d.title);
		var mainwidth;
		var mainheight;
		
		if (generator) {
			options.width = 250;
			options.height = 200;
		}
		mainwidth = options.width+options.pageBorderSize*2+options.windowPadding*2+1;
		mainheight = options.height+tabsize.h+options.pageBorderSize*2+options.windowPadding*2;
		
		style.size(d.main,mainwidth,mainheight);
		style.size(d.iframe,options.width,options.height);
		
		var cw = parseInt(options.width)+parseInt(options.pageBorderSize)*2;
		d.content.style.width = cw+'px';
		
		var title_dim = dimensions(d.title);
		style.move(d.resize,options.width-15+parseInt(options.pageBorderSize)*2+parseInt(options.windowPadding)*2,options.height-15+title_dim.h+parseInt(options.pageBorderSize)*2+parseInt(options.windowPadding)*2);
		
		d.content.style.padding = parseInt(options.windowPadding)+'px';
		
		//if (options.pageMargin!=null) iframe.contentWindow.document.body.style.margin = options.pageMargin+'px';
		
		if (!!options.pageBorderSize) {
			d.iframe.style.border = options.pageBorderSize+'px '+options.pageBorderStyle+' '+options.pageBorderColor;
		}
		else d.iframe.style.border = '0';
		
		d.iframe.style.backgroundColor = options.pageColor;
			
		if (!generator) {
			this.resize(true);
			this.reset(true);
		}
		
		if (options.icon) {
			d.title.style.paddingLeft = '20px';
			d.title.style.background = 'url('+this.path+'/icons/'+options.icon+'.png) no-repeat center left';
		}
		else {
			d.title.style.paddingLeft = '0px';
			d.title.style.background = '';
		}
		d.title.style.color = options.titleColor;
		d.title.style.fontFamily = options.titleFont;
		d.title.style.fontSize = options.titleSize;
		d.title.innerHTML = options.title;
		
		d.content.style.backgroundColor = options.windowColor;
		d.tab.style.backgroundColor = options.windowColor;
		
		if (generator) {
			//d.main.style.position = "relative";
			style.visible(d.main,true);
		}
		else {
			d.iframe.src = url;

			style.visible(d.overlay,true);
			if (options.fadeIn) {
				fx.fade(d.overlay,options.overlayOpacity,function() {
					style.visible(d.main,true);
					this.shown = true;
				},0.1,20);
			}
			else {
				style.opacity(d.overlay,options.overlayOpacity);
				style.visible(d.overlay,true);
				style.visible(d.main,true);
				this.shown = true;
			}
		}
	};
	
	this.update = function(options) {
		id('generator_main').style.zIndex = 0;
		this.show(null,options,true);
	}
	
	this.hide = function() {
		if (this.options.fadeOut) {
			style.visible(this.elm.main,false);
			
			var pop = this;
			fx.fade(this.elm.overlay,0,function() {
				pop._hide();
			},0.1,20);
		}
		else this._hide();
	};
	this._hide = function() {
		style.visible(this.elm.main,false);
		style.visible(this.elm.overlay,false);
		style.size(this.elm.overlay,0,0);
		this.defaultCount = 0;
		this.elm.iframe.src = this.loadingURL;
		this.shown = false;
	};
	
	this.resize = function(override) {
		if (this.shown || override) {
			var win = dimensions('#window');
			var page = dimensions('#document');
			var w = Math.max(win.w,page.w);
			var h = Math.max(page.h,win.h)
			style.size(this.elm.overlay, w, h);
		}
	};
	
	this.reset = function(override) {
		if (this.shown || override) {
			var window_size = dimensions('#window');
			var page = dimensions('#document');
			
			var main_size = dimensions(this.elm.main);
			var content_size = dimensions(this.elm.content);
			
			var x=y=0;
			
			var offsetX = (jaxscript.client.supports('fixed'))? 0:page.x;
			var offsetY = (jaxscript.client.supports('fixed'))? 0:page.y;
			x = offsetX + window_size.w/2-main_size.w/2;
			y = offsetY + window_size.h/2-content_size.h/2 - 30;
			
			if (x<0) x = 0;
			if (y<0) y = 0;
			style.move(this.elm.main,x,y);
		}
	};
	
	this.dragStart = function(e) {
		if (this.options.drag) {
			var target = dom.eventTarget(e);
			this.mainXY = style.getXY(this.elm.main);
			this.startPos = dom.eventPosition(e);
			var d = dimensions(this.elm.overlay);
			this.isDragging = true;
			style.size(this.elm.cover, d.w, d.h);
			style.visible(this.elm.cover,true);
			
			return dom.cancelEvent(e);
		}
	};
	
	this.dragEnd = function(e) {
		var c = this.elm.cover;
		this.isDragging = false;
		style.size(c,0,0);
		style.visible(c,false);		
		//dom.releaseEvent(c,'mouseup',this,'dragEnd');
		//jax.event.release(c,'mousemove',this,'dragMove');
	};
	
	this.dragMove = function(e) {
		if (this.isDragging) {
			var currentPos = dom.eventPosition(e);
			var b = document.body;
			var dx = currentPos.x - this.startPos.x;
			var dy = currentPos.y - this.startPos.y;
			var x = this.mainXY.x + dx; // - this.docDim.x;
			var y = this.mainXY.y + dy; // - this.docDim.y;
			if (x<3) x=3;
			if (y<6) y=6;
			style.move(this.elm.main,x,y);
		}
	};
	
	this.resizeStart = function(e) {
		if (this.options.resize) {
			var target = dom.eventTarget(e);
			this.mainDim = dimensions(this.elm.main);
			this.startPos = dom.eventPosition(e);
			echo('startPos = '+inspect(this.startPos));
			
			this.minWidth = Math.max(dimensions(this.elm.tab).w+20,80);
			
			var d = dimensions(this.elm.overlay);
			
			this.isResizing = true;
			
			style.size(this.elm.cover, d.w, d.h);
			style.visible(this.elm.cover,true);
			this.elm.cover.style.cursor = 'resize';
			
			//jax.event.bind(this.elm.cover,'mouseup',this,'resizeEnd');
			//jax.event.bind(this.elm.cover,'mousemove',this,'resizeMove');
			return dom.cancelEvent(e);
		}
	};
	
	this.resizeEnd = function(e) {
		this.isResizing = false;
		style.size(this.elm.cover,0,0);
		style.visible(this.elm.cover,false);
		//jax.event.release(this.elm.cover,'mouseup',this,'resizeEnd');
		//jax.event.release(this.elm.cover,'mousemove',this,'resizeMove');
	};
	
	this.resizeMove = function(e) {
		if (!this.isResizing) return;
		var currentPos = dom.eventPosition(e);
		var dx = currentPos.x - this.startPos.x;
		var dy = currentPos.y - this.startPos.y;
		
		/*iframe.style.width = options.width+'px';
		iframe.style.height = options.height+'px';
		
		var cw = parseInt(options.width)+parseInt(options.pageBorderSize)*2;
		content.style.width = cw+'px';
		*/
		
		var options = this.options;
		
		var w = this.mainDim.w + dx;
		var h = this.mainDim.h + dy;
		if (w<this.minWidth) w = this.minWidth;
		if (h<50) h = 50;
		style.size(this.elm.main,w,h);
		
		this.elm.content.style.width = (w - options.windowPadding*2) +'px';
		
		var tabsize = dimensions(this.elm.title);
		var mainwidth = options.width+options.pageBorderSize*2+options.windowPadding*2+1;
		var mainheight = options.height+tabsize.h+options.pageBorderSize*2+options.windowPadding*2;
		
		var frame_w = w - options.pageBorderSize*2 - options.windowPadding*2;
		var frame_h = h - options.pageBorderSize*2 - options.windowPadding*2 - tabsize.h;
		
		this.elm.iframe.style.width = frame_w+'px';
		this.elm.iframe.style.height = frame_h+'px';
		
		var title_dim = tabsize;
		style.move(this.elm.resize,frame_w-14+parseInt(options.pageBorderSize)*2+parseInt(options.windowPadding)*2,frame_h-14+title_dim.h+parseInt(options.pageBorderSize)*2+parseInt(options.windowPadding)*2);
	
		this.elm.cover.style.cursor = 'resize';
	};
	
	this.maximize = function(e) {
		style.move(this.elm.main,3,6);
		var window_size = dimensions('#window');
		this.elm.iframe.style.width = window_size.w-40+'px';
		this.elm.iframe.style.height = window_size.h-60+'px';
	};

};

jaxscript.run(function() {
	PopoverWindow.init();
});

