var browserType = (navigator.userAgent.toLowerCase().indexOf('msie') == -1)?'ff':'ie';
var globalPopupCounter = 0; // holds the amount of popups in one page
var globalPopupZindexCounter = 105; //takes care that the current popup is always on top


/**
 * Document Viewed Width
 */
document.visibleWidth  = function() {
	if(typeof document.body.clientWidth != 'undefined'){
		return document.body.clientWidth;
	}	else	{
		return window.innerWidth;
	}
};

/**
 * Document Viewed Height
 */
document.visibleHeight  = function() {
	if(typeof document.body.clientHeight != 'undefined'){
		return document.body.clientHeight;
	}	else	{
		return window.innerHeight;
	}
};

/**
 * Window Viewed Width
 */
window.visibleWidth  = function() {
	if(typeof top.document.body.clientWidth != 'undefined'){
		return top.document.body.clientWidth;
	}	else	{
		return top.window.innerWidth;
	}
};

/**
 * Window Viewed Height
 */
window.visibleHeight  = function() {
	if(typeof top.document.body.clientHeight != 'undefined'){
		return top.document.body.clientHeight;
	}	else	{
		return top.window.innerHeight;
	}
};

/**
 *	Scroll Top position of the current Frame
 */
document.scrollTop = function() {
	if(typeof document.body.scrollTop != 'undefined'){
		return document.body.scrollTop;
	}	else	{
		return window.pageYOffset;
	}
}

/**
 *	Scroll Left position of the current Frame
 */
document.scrollLeft = function() {

	if(typeof document.body.scrollLeft != 'undefined'){
		return document.body.scrollLeft;
	}	else	{
		return window.pageXOffset;
	}
}

/**
 * Findes the Absoulte position of the element, in the current Frame
 * @param {Object} obj
 * @return {Array} [left(x),top(y)]
 */
function findPos(obj) {
	var posLeft = posTop = 0;
	if (obj.offsetParent) {
		posLeft = obj.offsetLeft
		posTop = obj.offsetTop
		while (obj = obj.offsetParent) {
			posLeft += obj.offsetLeft
			posTop += obj.offsetTop
		}
	}
	return [posLeft,posTop];
}

var popup;

function initPopup(options,css,func){
	var onLoad = window.onload;
	window.onload = function (){
		if(typeof onLoad == 'function'){
			onLoad();
		}
		 popup = new popupClass(options,css);
		if(typeof func == 'function'){
			func();
		}
	}
}



/**
 * Creates a seperate Popup, can be called multipe at one page
 * @param {String} options Defines the Type of the Popup, possibilitys:
 * 				   'greyout' =>	Greyout background of the page behind the popup
 * 				   'disablePage' => Puts as transperent Layer over the content behind the PopUp
 * 				   'moveable' => Displays Title Line
 * 				   'closeable' => Adds an X to the Titleline (moveable required)
 * 				   'closeOnLeave [ = Integer]' => Closes PopUp if cursor leaves the popup [optional = detay in ms until close]
 * @param {Sting} border [Optional] CSS code of the popup:
 */
function popupClass(options, css){
	// init variables
	var thisObj = this;


	/**
	 * Initialize the popup
	 * Internal use only
	 * @param {Object} options
	 * @param {Object} borderCss
	 */
	this.init = function(options, css){
		this.no = globalPopupCounter;
		globalPopupCounter ++;

		// get options
		this.greyout = /greyout/i.test(options);
		this.disablePage = /disablePage/i.test(options);
		this.moveable = /move/i.test(options);
		this.closeable = /closeable/i.test(options);
		this.closeOnLeave = /closeOnLeave/i.test(options);
		if(this.closeOnLeave){
			this.closeOnLeaveTimeout = options.replace(/(.*)(closeOnLeave)(={0,1})([0-9]*)(.*)/i,'$4');
		}



		//init container
		var doc = document;
		var body = doc.getElementsByTagName('body')[0];
		this.container = doc.createElement('div');
		this.container.id = 'popupContainer'+this.no;
		this.container.style.cssText += css;
		this.container.className = 'popupContainer';
		this.container.name = 'popupContainer';
		this.container.onmouseout = this.mouseOut;
		this.container.onmousemove = this.mouseOut;
		body.appendChild(this.container);

		this.container.style.width = '300px';
		this.container.style.height = '200px';
		//init select box blocker
		if( typeof doc.getElementById('popupBlockIeFrame') != 'element')
		{
			this.blockIeFrame = doc.createElement('iframe');
			this.blockIeFrame.id = 'popupBlockIeFrame';
			this.blockIeFrame.className = 'popupBlockIeFrame';
			this.blockIeFrame.src = 'about:blank';
			body.appendChild(this.blockIeFrame);
		}
		else{
			this.blockIeFrame = doc.getElementById('popupBlockIeFrame');
		}

		if( typeof doc.getElementById('popupGrey') != 'element')
		{
			this.grey = doc.createElement('div');
			this.grey.id = 'popupGrey';
			this.grey.className = 'popupGrey';
			body.appendChild(this.grey);
		}
		else{
			this.grey = doc.getElementById('popupGrey');
		}

		if( this.moveable || this.minimizeable || this.closeable){
			this.titleLine = doc.createElement('div');
			this.titleLine.id = 'popupTitleLine';
			this.titleLine.className = 'popupTitleLine';
			this.titleLine.onmousedown = this.movementInit;
			this.container.appendChild(this.titleLine);
		}

		if(this.closeable){
			this.buttonClose = doc.createElement('div');
			this.buttonClose.id = 'popupCloseButton';
			this.buttonClose.className = 'popupCloseButton';
			this.buttonClose.onmousedown = null;
			this.buttonClose.onclick = this.hide;
			this.buttonClose.style.left = (parseInt(this.container.style.width) -15)+'px';
			this.container.appendChild(this.buttonClose);
		}

	};

	/**
	 * Shows the popup with the defined content, is no content overgiven the old content will not be replaced.
	 * If <content> has a value all data at the Popup are replaced.
	 * @param {Object} content Content Node
	 */
	this.show = function (content){

		// init
		var scrollTopTmp  = thisObj.scrollTopTmp =  document.scrollTop();
		var scrollLeftTmp = thisObj.scrollLeftTmp = document.scrollLeft();

		//if there no position put the dialog in the middle of the screen
		if(typeof thisObj.top == 'undefined' || isNaN(thisObj.top)){
				thisObj.top =  document.visibleHeight() / 2 - parseInt(thisObj.container.style.height) / 2;
		}
		if(typeof thisObj.left == 'undefined' || isNaN(thisObj.left)){
				thisObj.left =  document.visibleWidth() / 2 - parseInt(thisObj.container.style.width) / 2;
		}
		//move the dialog
		thisObj.container.style.left = (thisObj.left + scrollLeftTmp)+'px';
		thisObj.container.style.top = (thisObj.top + scrollTopTmp)+'px';
		//blocke alles mit iframe
		var frameStyle = thisObj.blockIeFrame.style;
		if(thisObj.greyout || thisObj.disablePage){
			document.getElementsByTagName('body')[0].style.overflow = 'hidden';
			frameStyle.width  = document.visibleWidth()+'px';
			frameStyle.height = document.visibleHeight()+'px';
			frameStyle.left = scrollLeftTmp+'px';
			frameStyle.top = scrollTopTmp+'px';
			if(thisObj.interval == null ||typeof thisObj.interval == undefined){
				thisObj.interval = window.setInterval(this.scrollReset,100);
		  	}
		} else	{//block frame only behind the dialog
			frameStyle.width  = thisObj.container.style.width;
			frameStyle.height = thisObj.container.style.height;
			frameStyle.left = thisObj.container.style.left;
			frameStyle.top = thisObj.container.style.top;
		}
		
		if(browserType == 'ie'){
			frameStyle.display = 'block';
		}

		if(thisObj.greyout){
			thisObj.grey.style.display = 'block';
			thisObj.grey.style.width  = thisObj.blockIeFrame.style.width;
			thisObj.grey.style.height = thisObj.blockIeFrame.style.height;
			thisObj.grey.style.left = thisObj.blockIeFrame.style.left;
			thisObj.grey.style.top = thisObj.blockIeFrame.style.top;
		}
		var delCounter = 0;

		if(typeof content != 'undefined' && content != null){
			for(var c = 0; c < thisObj.container.childNodes.length; c++)
			{
				if(! /popup/i.test(thisObj.container.childNodes[0].className)){
					thisObj.container.removeChild(thisObj.container.childNodes[0]);
				}
			}
			thisObj.container.appendChild(content);
		}
		thisObj.container.style.zIndex = ++globalPopupZindexCounter;

		thisObj.container.style.display  = 'block';
		window.scrollTo(scrollLeftTmp,scrollTopTmp);
	};

	this.addContent = function(content){
		thisObj.container.appendChild(content);

	}

	/**
	 * Hides the Popup
	 */
	this.hide = function (){
		thisObj.grey.style.display = 'none';
		thisObj.blockIeFrame.style.display = 'none';
		thisObj.container.style.display = 'none';
		document.getElementsByTagName('body')[0].style.overflow = '';
		window.clearInterval(thisObj.interval);
		thisObj.interval = null;
	};

	/**
	 * Reposition the  popup (Unit is Pixel), no values means center the popup
	 * Coordinates depend on the current view
	 * @param {Integer} x
	 * @param {Integer} y
	 */
	this.move= function (x,y){

	  	thisObj.container.style.borderWidth.replace(/([0-9]*)(px )([0-9]*)(px )([0-9]*)(px )([0-9]*)(px)/gi,'$1$3$5$7');
	  	var borderTop = parseInt(RegExp.$1) + parseInt(RegExp.$5) || 0;
		var borderLeft = parseInt(RegExp.$3) + parseInt(RegExp.$7) || 0;

		thisObj.left = parseInt(x);
		if(typeof x == 'undefined'){
		  thisObj.left = (document.visibleWidth() - borderLeft - parseInt(thisObj.container.style.width)) / 2;
		}

		if(thisObj.left < 0){
			thisObj.left = 0;
		}

		thisObj.top  = parseInt(y);
		if(typeof y == 'undefined'){
			thisObj.top = (document.visibleHeight() - borderTop - parseInt(thisObj.container.style.height)) / 2;
		}
		if(thisObj.top < 0){
			thisObj.top = 0;
		}

		if(thisObj.left + parseInt(thisObj.container.style.width) > document.visibleWidth() - borderLeft){
			thisObj.left = document.visibleWidth() - borderLeft - parseInt(thisObj.container.style.width);
		}

		if(thisObj.top + parseInt(thisObj.container.style.height) > document.visibleHeight() - borderTop){
			thisObj.top = document.visibleHeight() - borderTop - parseInt(thisObj.container.style.height);
		}
		thisObj.container.style.left = (thisObj.left + document.scrollLeft())+'px';
		thisObj.container.style.top = (thisObj.top + document.scrollTop())+'px';
		if(!thisObj.greyout && !thisObj.disablePage){
			thisObj.blockIeFrame.style.left = thisObj.container.style.left;
			thisObj.blockIeFrame.style.top = thisObj.container.style.top;
		}
	};

	/**
	 * Moves Popup absolute, not relative to the current view
	 * @param {Object} x
	 * @param {Object} y
	 */
	this.moveAbsolute = function (x,y){
		thisObj.left = parseInt(x) - document.scrollLeft();
		thisObj.top  = parseInt(y) - document.scrollTop();

		thisObj.container.style.left = parseInt(x)+'px';
		thisObj.container.style.top = parseInt(y)+'px';
		if(!thisObj.greyout && !thisObj.disablePage){
			thisObj.blockIeFrame.style.left = thisObj.container.style.left;
			thisObj.blockIeFrame.style.top = thisObj.container.style.top;
		}
	};

	/**
	 * Resize the popup (Unit px)
	 * @param {String} width
	 * @param {String} height
	 */
	this.resize=function (width, height){
		thisObj.container.style.width = parseInt(width)+'px';
		thisObj.container.style.height = parseInt(height)+'px';
		if(thisObj.buttonClose){
			thisObj.buttonClose.style.left = (parseInt(thisObj.container.style.width) -14)+'px';
	    }
	};


	/**
	 * Puts current Content of the popup to the body.
	 * All Elements will be set style.display = 'none';
	 */
	this.putContentToBody=function (){
		for(var c = 0; c < thisObj.container.childNodes.length; c++)
		{
			if(! /popup/i.test(thisObj.container.childNodes[0].className)){
				thisObj.container.childNodes[0].style.display = 'none';
				thisObj.container.parentNode.appendChild(thisObj.container.childNodes[0]);
			}
		}
	};


	/**
	 * Handles Mouse out Event
	 * Internal use only
	 * @param {Object} event
	 */
	this.mouseOut = function(e){
		if(thisObj.closeOnLeave){
			e = (!e?window.event:e);
			var cursorLeft = e.clientX+document.scrollLeft() ;
			var cursorTop = e.clientY+document.scrollTop() ;
			if( 	parseInt(thisObj.container.style.left) < cursorLeft
				&&  (parseInt(thisObj.container.style.left) + parseInt(thisObj.container.style.width)) > cursorLeft
				&&	parseInt(thisObj.container.style.top) < cursorTop
				&&  (parseInt(thisObj.container.style.top) +parseInt(thisObj.container.style.height)) > cursorTop
			  ){
				if(thisObj.closeOnLeaveTimeout > 0)
					window.clearTimeout(thisObj.timeout);
			} else {
				if(thisObj.closeOnLeaveTimeout > 0)
					thisObj.timeout = window.setTimeout(thisObj.hide,thisObj.closeOnLeaveTimeout);
			}
		}
	}


	/**
	 * Handles Drag and Drop at the titlebar
	 * Internal use only
	 * @param {Object} event
	 */
	this.movementInit = function(e){
		e = (!e?window.event:e);
		//get iframe in front of the popup / resize to fullscreen
		var body = top.document.getElementsByTagName('body')[0];
		var glassFrame = thisObj.glassBlockFrame = top.document.createElement('iframe');
		glassFrame.id = 'glassBlockFrame';
		glassFrame.className = 'popupBlockIeFrame';
		body.appendChild(glassFrame);
		glassFrame.style.zIndex = '9999';
		glassFrame.style.display = 'block';

		//display glass
		thisObj.glass = top.document.createElement('div');
		thisObj.glass.className = 'popupMovmentGlass';
		body.appendChild(thisObj.glass);
		thisObj.glass.onmousemove = thisObj.movementHandle;
		thisObj.glass.onmouseup = thisObj.movementFinish;
		//calculate offset
		var offset = findPos(top.document.getElementById('mainFrame'));
		var elementOffset = findPos(this);
		thisObj.offsetX = offset[0] + ((e.clientX - elementOffset[0])+document.scrollLeft());
		thisObj.offsetY = offset[1] + ((e.clientY - elementOffset[1])+document.scrollTop());

		//disable select
		body.onselectstart= function(){return false};
	};

	/**
	 * Handles movement while Drag and drop
	 * Internal Use only
	 * @param {Object} event
	 */
	this.movementHandle = function(e){
		e = (!e?top.window.event:e);
		thisObj.move(e.clientX - thisObj.offsetX,e.clientY - thisObj.offsetY );
	};

	/**
	 * Handles drag and drop finish
	 * Internal use only
	 */
	this.movementFinish = function(){
		thisObj.glassBlockFrame.parentNode.removeChild(thisObj.glassBlockFrame);
		thisObj.glass.parentNode.removeChild(thisObj.glass);
		top.document.getElementsByTagName('body')[0].onselectstart= null;
	};

	/**
	 * Interval function for Firefox repaints
	 * Internal use only
	 */
	this.scrollReset = function(){
	if(thisObj.scrollLeftTmp != document.scrollLeft() ||thisObj.scrollTopTmp != document.scrollLeft())
		window.scrollTo(thisObj.scrollLeftTmp,thisObj.scrollTopTmp);
	}

	this.destroy = function(){
		thisObj.container.parentNode.removeChild(thisObj.container);
		if(document.getElementsByName('popupContainer').length == 1){
			thisObj.grey.parentNode.removeChild(thisObj.grey);
			thisObj.blockIeFrame.parentNode.removeChild(thisObj.blockIeFrame);
		}
		thisObj = null;
		return null;
	}

	//call consturctor
	this.init(options,css);
}



