var Popover = function(url, options) {
	this.url = url;
	this.options = options;
	// Detect IE6 or below for png stuff
	if (document.all && !window.opera && !window.XMLHttpRequest) {
		this.ie6 = true;
	}
};

// Think of this as a static method
Popover.preLoad = function() {
	// All the images we use
	var imgPaths = [
	'tl.png',
	'tr.png',
	'bl.png',
	'br.png',
	't.png',
	'b.png',
	'l.png',
	'r.png',
	'header_l.gif',
	'header_bg.gif',
	'header_r.gif',
	'header_close.gif',
	'/Images/loading.gif'
	];

	
	var iml = imgPaths.length;
	
	img = [];
	for (var i=0;i < iml;i++) {
		// Load up each image
		var timg = new Image();
		img.push(timg);
		timg.src = 'http://static.websimages.com' + ((imgPaths[i] != '/Images/loading.gif') ? '/Images/Base/PopoverR/' : '') + imgPaths[i];
	}
};

Popover.prototype = {
	ie6: false,
	showing: false,
	
	// Used to get around IE6 and below png problems
	filteredImage: function(url) {
		if (this.ie6) {
			return '<img src="http://static.websimages.com/Images/trans.gif" style="height: 18px;width: 18px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'http://static.websimages.com' + url + '\', sizingMethod=\'crop\');">';
		} else {
			return '<img src="http://static.websimages.com' + url + '">';
		}
	},
	
	filteredBg: function(url, repeat) {
		if (this.ie6) {
			return 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'http://static.websimages.com' + url + '\', sizingMethod=\'scale\');';
		} else {
			return 'background: url(\'http://static.websimages.com'+url+'\') '+repeat+';';
		}
	},
	// Fade in Code
	setOpacity: function(obj, opacity) {
		if (opacity === 0){
			if(obj.style.visibility != "hidden") obj.style.visibility = "hidden";
		} else {
			if(obj.style.visibility != "visible") obj.style.visibility = "visible";
		}
		if (window.ActiveXObject) obj.style.filter = "alpha(opacity=" + opacity*100 + ")";
		obj.style.opacity = opacity;
	},
	
	sin: function(pos){return ((-Math.cos(pos*Math.PI)/2) + 0.5);},
	
	
	fadeIn: function(el, duration, toValue, doneFunc) {
		var fn = this;
		
		var d = new Date();
		var start = d.getTime();
		var end = start + duration;
		var max = toValue;

		var opac = 0.0;
		
		var fade = setInterval(function() {
			var d = new Date();
			var pos = d.getTime();

			var opac = fn.sin((pos-start)/duration)*max;
			if (opac > max) {
				opac = max;
			}

			if (pos > end) {
				// Done
				opac = max;
				clearInterval(fade);
				if (doneFunc) {
					doneFunc();
				}
			}
			fn.setOpacity(el, (opac/100.0));
		}, 20);
	},
	// End of fade code
	
	
	show: function() {
		if (this.showing) return;
		this.showing = true;

		// Options stuff
		var url = this.url;
		var options = this.options;
		
		// Defaults
		var height = options.height || 400;
		var width = options.width || 500;
		var heading = options.heading || '';
		var showLoading = options.showLoading || false;
	

		var pullUp = 40;
		// Get the middleish of the screen
		var topPos = Math.max(((document.documentElement.scrollTop || document.body.scrollTop)+(Math.round((window.innerHeight || document.documentElement.clientHeight)/2))-Math.round(height/2)-pullUp),10);
		
		this.popOverFrame = document.createElement('div');
		this.popOverFrame.style.cssText = 'visibility: hidden;position: absolute;z-index:110;height: '+height+'px;width: '+width+'px;top: '+topPos+'px;left: 50%;margin-left: -'+(Math.round(width/2))+'px;';
		
		var frameTable = '\
		<table border="0" cellpadding="0" cellspacing="0" height="'+height+'" width="'+width+'" style="border-collapse: collapse;line-height:0;">\
			<tr>\
				<td style="height:18px;width: 18px;">'+this.filteredImage('/Images/Base/PopoverR/tl.png')+'</td>\
				<td style="height:18px;' + this.filteredBg('/Images/Base/PopoverR/t.png', 'repeat-x top left')+'"><img src="http://static.websimages.com/Images/trans.gif"></td>\
				<td style="height:18px;width: 18px;">'+this.filteredImage('/Images/Base/PopoverR/tr.png')+'</td>\
			</tr>\
			<tr>\
				<td style="width:18px;' + this.filteredBg('/Images/Base/PopoverR/l.png', 'repeat-y top left')+'"><img src="http://static.websimages.com/Images/trans.gif"></td>\
				<td style="height: '+(height-18-18)+'px;background-color: #fff;"></td>\
				<td style="width:18px;' + this.filteredBg('/Images/Base/PopoverR/r.png', 'repeat-y top right')+'"><img src="http://static.websimages.com/Images/trans.gif"></td>\
			</tr>\
			<tr>\
				<td style="height:18px;width: 18px;">'+this.filteredImage('/Images/Base/PopoverR/bl.png')+'</td>\
				<td style="height:18px;' + this.filteredBg('/Images/Base/PopoverR/b.png', 'repeat-x bottom left')+'><img src="http://static.websimages.com/Images/trans.gif"></td>\
				<td style="height:18px;width: 18px;">'+this.filteredImage('/Images/Base/PopoverR/br.png')+'</td>\
			</tr>\
		</table>';
		
		/*
        ==== THIS IS NO LONGER USED, KILL IT BECAUSE NEWER BROWSERS HAVE ODD ISSUES ANYWAY KTHXBAI -- RYAN ====
        if (showLoading) {
			var topLoadingPos = Math.max(((document.documentElement.scrollTop || document.body.scrollTop)+(Math.round((window.innerHeight || document.documentElement.clientHeight)/2))-25-pullUp),10);
			this.loader = document.createElement('div');
			this.loader.style.cssText = 'top: '+topLoadingPos+'px;left: 50%;width: 230px;height: 50;margin-left: -115px;text-align: center;position: absolute;z-index:114;border: 1px solid #ccc;background: #fff;';
			this.loader.innerHTML += '<h1 style="margin-bottom: 0;">Loading...</h1><img src="http://static.websimages.com/Images/loading.gif">';
			document.body.appendChild(this.loader);
		}*/
		
		this.popOverFrame.innerHTML += frameTable;
		
		this.popOver = document.createElement('div');
		// Position within the frame
		width -= 20;
		height -= 16;
		topPos += 9;
		
		if (heading) {
			height -= 33;
			var headerHTML = '\
				<div>\
					<table border="0" id="popoverHeader" cellpadding="0" cellspacing="0" width="100%" style="border-collapse: collapse;">\
						<tr>\
							<td style="width: 8px;"><img src="http://static.websimages.com/Images/Base/PopoverR/header_l.gif"></td>\
							<td vertical-align="top" style="font-size: 15pt;font-family: Arial;color: #fff;font-weight: bold;text-align: left;background: url(\'http://static.websimages.com/Images/Base/PopoverR/header_bg.gif\') repeat-x top left;">'+heading+'</td>';
							if (options.helpButton && (typeof options.helpButton === "string" || typeof options.helpButton === "function")) {
                                headerHTML += '<td style="width: 8px;"><a href="#"><img id="popoverHelpButton" style="border: 0;" src="http://static.websimages.com/Images/Base/PopoverR/header_help.gif"></a></td>';
							}

							headerHTML += '<td style="width: 8px;">';

							if (options.closeButton && (options.closeButton == true || typeof options.closeButton == "function")) {
								headerHTML += '<a href="#"><img id="popoverCloseButton" style="border: 0;" src="http://static.websimages.com/Images/Base/PopoverR/header_close.gif"></a>';
							} else {
								headerHTML += '<img src="http://static.websimages.com/Images/Base/PopoverR/header_r.gif">';
							}
							headerHTML += '</td>\
						</tr>\
					</table>\
				</div>\
			';
			this.popOver.innerHTML += headerHTML;
		}
		
		this.popOver.style.cssText = 'visibility: hidden;position: absolute;z-index:111;height: '+height+'px;width: '+width+'px;top: '+topPos+'px;left: 50%;margin-left: -'+(Math.round(width/2)-1)+'px;';

// added a name attribute so the iframe can be referenced via 'top.popoverIframe'		
		this.popOver.innerHTML += '<iframe id="popoverIframe" name="popoverIframe" frameborder="0" style="height: 100%;width: 100%;" allowtransparency="true" scrolling="no" src="'+url+'"></iframe>';
		
		
		document.body.appendChild(this.popOverFrame);
		document.body.appendChild(this.popOver);

		// Assign the close function
		if (heading) {
			var $G = function(el) {return document.getElementById(el);};

			if (options.closeButton) {
				var closeBtn = $G('popoverCloseButton');
				closeBtn.onmousedown = this.stopBubble;
				closeBtn.onmouseup = this.stopBubble;
				if (options.closeButton === true) {
					// create closure with 'this'
					var fn = this;
					closeBtn.onclick = function() {
						fn.hide();
						return false;
					};
				} else if (typeof options.closeButton == "function") {
					closeBtn.onclick = options.closeButton;
				}
			}
			if (options.helpButton) {
		        var helpBtn = $G('popoverHelpButton');
		        helpBtn.onmousedown = this.stopBubble;
		        helpBtn.onmouseup = this.stopBubble;
			    if (typeof options.helpButton === "function") {
			        helpBtn.onclick = options.helpBtn;
			    } else if (typeof options.helpButton === "string") {
			        helpBtn.parentNode.href = options.helpButton;
			        helpBtn.parentNode.target = '_blank';
			    }
			}
			this.header = $G('popoverHeader');
			this.iframe = $G('popoverIframe');
			
			if (this.options.dragable !== false) {
				this.header.style.cursor = 'default';

				var fn = this;
				this.header.onmousedown= function(event) {
					event = event || window.event;
//					document.body.style.margin = '0';
					
					fn.moving = true;
					fn.hasMoved = false;
					fn.mouseStart = {x: event.pageX || event.clientX, y: event.pageY || event.clientY};


					fn.popOverStart = fn.getPosition(fn.popOver);
					fn.popOverFrameStart = fn.getPosition(fn.popOverFrame);


					fn.popOver.style.marginLeft = 0;
					fn.popOver.style.left = fn.popOverStart.x + 'px';

					fn.popOverFrame.style.marginLeft = 0;
					fn.popOverFrame.style.left = fn.popOverFrameStart.x + 'px';

					fn.iframePos = fn.getPosition(fn.popOverFrame);

					fn.slint = document.createElement('div');

					fn.slint.style.cssText = 'left: '+fn.iframePos.x+'px;top: '+fn.iframePos.y+'px;height: '+(fn.options.height)+'px;width: '+(fn.options.width)+'px;z-index:120;background-color: #cccccc;position: absolute;opacity: 0.01; filter: alpha(opacity=01);';

					document.body.appendChild(fn.slint);


					fn.newMouse = fn.mouseStart;

					
					document.onmousemove = function(event) {
						if (fn.hasMoved === false) {
							fn.hasMoved = true;
							if (document.selection) document.selection.clear();
							//if (document.selection) document.selection.empty();
							//else if (window.getSelection) window.getSelection().removeAllRanges();
						}

						
    						
						event = event || window.event;
						fn.newMouse = {x: event.pageX || event.clientX, y: event.pageY || event.clientY};
						//console.log('mousemove' + fn.newMouse.x);

					}


					fn.popOverMoveInterval = setInterval(function() {
						
					
						function setLeftTop(el, left, top, minx, miny) {
							el.style.top = ((top > miny) ? top : miny) + 'px';
							el.style.left = ((left > minx) ? left : minx) + 'px';
							//el.style.top = top + 'px';
							//el.style.left = left + 'px';
						}
					
						if (fn.moving === true) {
							var xOffset = (fn.newMouse.x - fn.mouseStart.x);
							var yOffset = (fn.newMouse.y - fn.mouseStart.y);
							
							setLeftTop(fn.popOverFrame, (fn.popOverFrameStart.x + xOffset), (fn.popOverFrameStart.y + yOffset), 0, 0);
							setLeftTop(fn.popOver, (fn.popOverStart.x + xOffset), (fn.popOverStart.y + yOffset), (fn.popOverStart.x - fn.popOverFrameStart.x), (fn.popOverStart.y - fn.popOverFrameStart.y));
							setLeftTop(fn.slint, (fn.iframePos.x + xOffset), (fn.iframePos.y + yOffset), 0, 0);
						}
					}, 10);
					
					
					document.onmouseup = function(evt) {
						document.onmousemove = null;
						document.onmouseup = null;
						clearInterval(fn.popOverMoveInterval);
						document.body.removeChild(fn.slint);
						fn.moving = false;
					}
				
					return false;
				};
			}
		}
		
		
		
		var fn = this;
		this.showShutter(function() {
			setTimeout(function() {
				fn.popOverFrame.style.visibility = 'visible';
				fn.popOver.style.visibility = 'visible';
			}, 100);
		});
	},
	
	getScrollWidth: function(){
		if (document.all) return Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth);
		if (window.khtml) return document.body.scrollWidth;
		return document.documentElement.scrollWidth;
	},
		
	hideLoading: function() {
		if (this.loader !== undefined) {
			this.loader.parentNode.removeChild(this.loader);
			this.loader = undefined;
		}
	},

	getPosition: function(el){
		var left = 0, top = 0;
		do {
			left += el.offsetLeft || 0;
			top += el.offsetTop || 0;
			el = el.offsetParent;
		} while (el);
		return {'x': left, 'y': top};
	},
	
	hide: function(noClose) {
		if (!this.showing) return;
		if (noClose) {
			this.popOver.style.display = this.popOverFrame.style.display = this.shutter.style.display = 'none';
			return;
		}
		this.hideLoading();
	
		this.popOver.parentNode.removeChild(this.popOver);
		this.popOverFrame.parentNode.removeChild(this.popOverFrame);
		
		this.hideShutter();
		this.showing = false;
		if (this.options.onClose) this.options.onClose();
	},
	
	changeElements: function(elementName, attribute, value, condition) {
		var elements = document.getElementsByTagName(elementName);
		for (var i=0;i < elements.length;i++) {
			if (condition === undefined || condition(elements[i])) {
				elements[i].style[attribute] = value;
			}
		}
	},


	showShutter: function(doneFunc) {
		if (self.shutter && self.shutter.working) {
			self.hideShutter();
		}
		
		if (this.ie6 == true) {
			this.changeElements('select', 'display', 'none');
		}

		/* Make sure all the ads don't go over top of the uploader */
		this.changeElements('object', 'visibility', 'hidden');
	    this.changeElements('object', 'zIndex', 0);
		this.changeElements('embed', 'visibility', 'hidden');
		this.changeElements('embed', 'zIndex', 0);
		
		// Added this because nothing else seems to work
		//this.changeElements('object', 'zIndex', 0, function(el) {el.innerHTML = '';return false;});
		//this.changeElements('embed', 'zIndex', 0, function(el) {el.innerHTML = '';return false;});

		this.shutter = document.createElement('div');
		this.shutter.id = 'shutter';
		this.shutter.style.cssText = 'background-color:#000000; position: absolute;height: 100%;width: 100%;top: 0px;left: 0px; z-index:80;';
		//#858585 filter: alpha(opacity=0); opacity: 0.0;
		
		// Set shutter to the biggest page height we can find
		this.shutter.style.height = (Math.max((window.innerHeight || 0), document.body.clientHeight, document.documentElement.clientHeight, document.body.scrollHeight))+'px';
		document.body.appendChild(this.shutter);
		
		//var fadeTo = (this.options.hideShutter && this.options.hideShutter === true) ? 1.0 : 70.0;
		//this.fadeIn(this.shutter, this.options.fadeInTime || 100.0, fadeTo, doneFunc);
		this.setOpacity(this.shutter,0.7);
		doneFunc();
	},
	
	hideShutter: function() {
		if (this.ie6 == true) {
			document.getElementById('shutter').style.display = 'none';
			this.changeElements('select', 'display', 'inline');
		}

		/* Show the ads again */
		this.changeElements('object', 'visibility', 'visible', function(el) {return (el.style.visibility == 'hidden');});
		this.changeElements('embed', 'visibility', 'visible', function(el) {return (el.style.visibility == 'hidden');});

		
		this.shutter.parentNode.removeChild(this.shutter);
	},
	
	
	stopBubble: function(e) {
		if (!e) var e = window.event;
		e.cancelBubble = true;
		if (e.stopPropagation) e.stopPropagation();
	}

}



