var e2LayerObj, e2CloseLayerViewer, e2RemoveLayerViewer;
var e2ViewerVars = new E2InitViewerVars();

function e2OpenLayerViewer(url, width, height, scroll) {
    e2LayerObj = new E2LayerViewerObj(url, width, height, scroll);
    e2CloseLayerViewer = e2LayerObj.CloseAll;
    e2RemoveLayerViewer = e2LayerObj.RemoveAll;
}

function E2InitViewerVars() {
    this.SemiTransPNG = 'images/transPngDark.png';
    this.TransGIF = 'images/1dot_transparent.gif';
    this.LoadingGIF = 'images/bigrotation2.gif';
    this.LinkColor = '#FFFFFF';
    this.defaultW = 600;
    this.defaultH = 435;
 
    var e2PreLoadImg = new Array();
    e2PreLoadImg[0] = new Image();
    e2PreLoadImg[1] = new Image();
    e2PreLoadImg[2] = new Image();
    e2PreLoadImg[0].src = this.SemiTransPNG;
    e2PreLoadImg[1].src = this.TransGIF;
    e2PreLoadImg[2].src = this.LoadingGIF;    
}

function E2LayerViewerObj(url, width, height, scroll) {
    var titleH = 16;        // Final height of title/close bar on top.
    if (scroll === 0) {
        var scrollBar = 0;     // Elimnate allowance for right scroll bar.
    } else {
        var scrollBar = 20;     // Allowance for right scroll bar.
    }
    var framePad = 0;       // Padding between viewer edge and content. 
    var coverW = 120;       // Starting width of viewer window before animation.
    var coverH = 32;        // Starting height of viewer window before animation.

    var ieVer = GetIEVersion();
    var stndCompat = (document.compatMode && document.compatMode !== "BackCompat") ? true : false;
    var ieBody = (document.compatMode && document.compatMode !== "BackCompat") ? document.documentElement : document.body;
    var objW = (typeof width === 'undefined') ? e2ViewerVars.defaultW : width;;
    var objH = (typeof height === 'undefined') ? e2ViewerVars.defaultH : height;

    var targetL, targetT, targetW, targetH, adjustedH;
    var oHolder, oScreen, oClose, oContent, oCover, oFrame;

    var animateDir = 1;
    var reloadOnClose = false;
    var that = this;
    var animateTimer;
	var AV = null;
	
    this.PositionAll = function() {
	    var stylePos = (ieVer === -1 || (ieVer >= 7 && stndCompat)) ? 'fixed' : 'absolute';
        var viewW = (ieVer !== -1) ? ieBody.clientWidth : window.innerWidth;
        var viewH = (ieVer !== -1) ? ieBody.clientHeight : window.innerHeight;
        var scrollL = (ieVer !== -1) ? ieBody.scrollLeft : document.body.scrollLeft;
        var scrollT = (ieVer !== -1) ? ieBody.scrollTop : document.body.scrollTop;
	    var tmpLeft = (stylePos === 'fixed') ? 0 : scrollL;
	    var tmpTop = (stylePos === 'fixed') ? 0 : scrollT;
    	
	    targetW = objW + scrollBar + framePad;
	    targetH = objH + ((framePad + 1) * 2);
	    targetL = parseInt(tmpLeft + (viewW - targetW)/2);
	    targetT = parseInt(tmpTop + (viewH - targetH )/2 + (titleH/2));
	    adjustedH = height;
	    if(targetT - titleH < tmpTop) {
		    targetT = tmpTop + titleH;
		    targetH = viewH - titleH;
		    adjustedH = targetH - (framePad * 2);
	    } 
    	
	    oHolder = document.getElementById('e2ViewerHolder');
	    if(!oHolder) {
		    MakeContainers();
		    oHolder = document.getElementById('e2ViewerHolder');
	        oScreen = document.getElementById('e2ViewerScreen');
	        oClose = document.getElementById('e2ViewerClose');
	        oContent = document.getElementById('e2ViewerContent');
	        oCover = document.getElementById('e2ViewerCover');
		    SetStyles();
	    }
    	
	    oScreen.style.width = viewW + 'px';
	    oScreen.style.height = viewH + 'px';
	    oScreen.style.left = tmpLeft + 'px';
	    oScreen.style.top = tmpTop + 'px';
    		
	    if(oHolder.style.display === 'none') {
		    if(stylePos !== 'absolute') {
			    oScreen.style.position = stylePos;
			    oClose.style.position = stylePos;
			    oContent.style.position = stylePos;
			    oCover.style.position = stylePos;
		    }
    		
		    var startL = parseInt(tmpLeft + targetL + (targetW - coverW)/2) - framePad;
		    var startT = parseInt(tmpTop + targetT + (targetH - coverH)/2) - framePad;
		    oCover.style.left = startL + 'px';
		    oCover.style.top = startT + 'px';
    		
		    //animateTimer = setInterval(GrowDiv, 10);
		    //animateTimer = setInterval(GrowDivEven, 10);
			animateTimer = setInterval(GrowDivVertical, 10);
    	} else {
		    oContent.style.left = targetL + 'px';
		    oContent.style.top = targetT + 'px';
		    oContent.style.height = targetH + 'px';
		    oClose.style.left = targetL + 'px';
		    oClose.style.top = (targetT - titleH) + 'px';
		    oFrame.height = adjustedH;
	    }
    }

    function MakeContainers() {
	    var e2ViewerHolder = document.createElement("div");
	    e2ViewerHolder.id = 'e2ViewerHolder';
	    e2ViewerHolder.style.display = 'none';
    	
	    var centerDivW = coverW + (framePad * 2);
	    var centerDivH = coverH + (framePad * 2);
    	
	    var html = '';
	    // Div for full screen semi-transparent layer.
	    html += '<div id="e2ViewerScreen" style="position: absolute; left: 0px; top: 0px; z-index: 100;">&nbsp;</div>';
    	
	    // Div for the close button bar.
	    html += '<div id="e2ViewerClose" style="position: absolute; left: ' + targetL + 'px; top: ' + targetT + 'px; width: ' + targetW + 'px; height: ' + titleH + 'px; text-align: right; margin: 0px; padding: 1px; vertical-align: middle; display: none; z-index: 101;">';
	    html += '<a href="#" onclick="e2CloseLayerViewer(); return false;" style="text-decoration: none;"><span style="font-family: Arial, Helvetica, sans-serif; font-size: 11px; font-weight: bold; vertical-align: middle; text-decoration: none; color: ' + e2ViewerVars.LinkColor + ';">Close [X]</span></a>';
	    html += '</div>';
    	
	    // Div for the content iframe.
	    html += '<div id="e2ViewerContent" style="position: absolute; left: ' + targetL + 'px; top: ' + targetT + 'px; padding: 0px; margin: 0px; border: solid 1px #333333; width: ' + targetW + 'px; height: ' + targetH + 'px; overflow: hidden; text-align: center; vertical-align: middle; z-index: 102; display: none;">&nbsp;</div>';	
    	
	    // Div the animates and covers the iframe until its content is loaded.
	    html += '<div id="e2ViewerCover" style="position: absolute; top: 0px; left: 0px; padding: 0px; margin: 0px; width: ' + centerDivW + 'px; height: ' + centerDivH + 'px;  border: solid 1px #000000; background-color: #EEEEEE; overflow: hidden; text-align: center; z-index: 103;">';
		    //html += '<div style="position: relative; width: auto; height: ' + centerDivH + 'px; top: 50%; margin-top: ' + (centerDivH/(-2)) + 'px; padding: ' + framePad + 'px;">';
            html += '<div style="padding: 10px;">';
		    html += '<a href="#" onclick="e2RemoveLayerViewer(); return false;" style="text-decoration: none;">';
		    html += '<img src="' + e2ViewerVars.LoadingGIF + '" width="32" height="32" border="0" style="vertical-align: middle;" alt="Loading" />&nbsp;&nbsp;';
		    html += '<span style="vertical-align: middle; font-family: Arial, Helvetica, sans-serif; font-size: 11px; font-weight: bold; vertical-align: middle; text-decoration: none; color: #666666;">Cancel</span>';
		    html += '</a>';
		    html += '</div>';
	    html += '</div>';
    	
	    e2ViewerHolder.innerHTML = html;
	    document.getElementsByTagName('body')[0].appendChild(e2ViewerHolder);
    }

    function SetStyles() {
	    if(ieVer < 6) {
		    oScreen.style.background = 'url(' + e2ViewerVars.SemiTransPNG + ') repeat';
	    } else {
		    oScreen.style.background ='url(' + e2ViewerVars.TransGIF + ') repeat';
		    oScreen.style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + e2ViewerVars.SemiTransPNG + '",sizingMethod="scale")';
	    }
    	
    }
	
	function AnimateVals(obj) {
		this.width = parseInt(obj.style.width.replace(/px/,''));
		this.height = parseInt(obj.style.height.replace(/px/,''));
		this.left = parseInt(obj.style.left.replace(/px/,''));
		this.top = parseInt(obj.style.top.replace(/px/,''));
		this.animateDir = 1;
		this.done = false;
	}
    
    function GrowDiv() {
        var increment;
	    var overShoot = 0;

	    if(oCover) {
		    var width = parseInt(oCover.style.width.replace(/px/,''));
		    var height = parseInt(oCover.style.height.replace(/px/,''));
		    var left = parseInt(oCover.style.left.replace(/px/,''));
		    var top = parseInt(oCover.style.top.replace(/px/,''));
    			
		    var tarW = targetW;
		    var tarH = targetH;
		    var tarL = targetL;
		    var tarT = targetT;
    		
		    if(animateDir !== -1) {
			    tarW += overShoot;
			    tarH += overShoot;
			    tarL -= overShoot/2;
			    tarT -= overShoot/2;
			    increment = 26; // Make sure it is an even number.
		    } else {
			    increment = 2;
		    }
    		
		    if(animateDir === -1 && width > tarW && width - increment <= tarW) {
			    oCover.style.width = tarW + 'px';
			    oCover.style.left = tarL + 'px';
			    oCover.style.height = tarH + 'px';    
			    oCover.style.top = tarT + 'px';
		    } else if(animateDir === -1 && width > tarW) {
			    oCover.style.width = (width - increment) + 'px';
			    oCover.style.left = parseInt(left + increment/2) + 'px';
			    oCover.style.height = (height - increment) + 'px';
			    oCover.style.top = parseInt(top + increment/2) + 'px';
		    } else if(width < tarW && width + increment >= tarW) {
			    oCover.style.width = tarW + 'px';
			    oCover.style.left = tarL + 'px';
		    } else if (width < tarW) {
			    oCover.style.width = (width + increment) + 'px';
			    oCover.style.left = parseInt(left - increment/2) + 'px';
		    } else if(height < tarH && height + increment >= tarH) {
			    oCover.style.height = tarH + 'px';    
			    oCover.style.top = tarT + 'px';
			    animateDir = -1
		    } else if(height < tarH) {
			    oCover.style.height = (height + increment) + 'px';
			    oCover.style.top = parseInt(top - increment/2) + 'px';
		    } else {
			    clearInterval(animateTimer);
			    RenderIFrame();
		    }
	    } 
    }

    function GrowDivEven() {
		if(AV === null) {
			oHolder.style.display = '';
			AV = new AnimateVals(oCover);
		}
		var overShoot = 0;
		var incOver = 2;
		var incX = 20;
		var incY = parseInt((targetH - AV.height)/((targetW - AV.width)/incX));
		incY += (incY % 2 === 1) ? 1 : 0;
		
		if(AV.done) {
			clearInterval(animateTimer);
			AV = null;
			RenderIFrame();
		} else {
			if(AV.animateDir === -1 && AV.width > targetW && AV.width - incOver <= targetW) {
				AV.width = targetW;
				AV.left = targetL;
				AV.height = targetH;
				AV.top = targetT;
				AV.done = true;
			} else if(AV.animateDir === -1 && AV.width > targetW) {
				AV.width -= incOver;
				AV.left += incOver/2;
				AV.height -= incOver;
				AV.top += incOver/2;
			} else if(AV.animateDir !== -1 && AV.width < targetW + overShoot && AV.width + incX >= targetW + overShoot) {
				AV.width = targetW + overShoot;
				AV.left = targetL - overShoot/2;
				AV.height = targetH + overShoot;
				AV.top = targetT - overShoot/2;
				AV.animateDir = -1;
			} else {
				AV.width += incX;
				AV.left -= incX/2;
				AV.height += incY;
				AV.top -= incY/2;
			}
			oCover.style.width = AV.width + 'px';
			oCover.style.left = AV.left + 'px';
			oCover.style.height = AV.height + 'px';
			oCover.style.top = AV.top + 'px';
		}
    }
    
    function GrowDivVertical() {
		if(AV === null) {
			oCover.style.top = targetT + 'px';
			oHolder.style.display = '';
			AV = new AnimateVals(oCover);
		}
		var incX = 40;
		var incY = 20;
		
		if(AV.done) {
			clearInterval(animateTimer);
			AV = null;
			RenderIFrame();
		} else {
			if(AV.width < targetW && AV.width + incX >= targetW) {
				AV.width = targetW;
				AV.left = targetL;
				oCover.style.width = AV.width + 'px';
				oCover.style.left = AV.left + 'px';
			} else if(AV.width < targetW) {
				AV.width += incX;
				AV.left -= incX/2;
				oCover.style.width = AV.width + 'px';
				oCover.style.left = AV.left + 'px';
			} else if(AV.height < targetH && AV.height + incY >= targetH) {
				AV.height = targetH;
				AV.done = true;
				oCover.style.height = AV.height + 'px';
			} else {
				AV.height += incY;
				oCover.style.height = AV.height + 'px';
			}
		}
    }

    function RenderIFrame() {
        var ts = new Date();
	    var frameW = width + scrollBar;
	    var frameH = adjustedH;
	    var pad = framePad;
	    var showurl = url;
	    var html = '';

	    showurl += (showurl.indexOf('?') === -1) ? '?ts=' + escape(ts) : '&ts=' + escape(ts);

	    html += '<div style="background-color: #FFFFFF; margin: 0px; padding: ' + pad + 'px 0px ' + pad + 'px 0px; text-align: center;">';
	    if (scroll === 0) {
	        html += '<iframe id="e2ViewerFrame" name="e2ViewerFrame" src="' + e2ViewerVars.TransGIF + '" width="' + frameW + '" height="' + frameH + '" scrolling="no" frameborder="0" style="margin-left: auto; margin-right: auto;"></iframe>';
	    } else {
	        html += '<iframe id="e2ViewerFrame" name="e2ViewerFrame" src="' + e2ViewerVars.TransGIF + '" width="' + frameW + '" height="' + frameH + '" scrolling="auto" frameborder="0" style="margin-left: auto; margin-right: auto;"></iframe>';
	    }
	    html += '</div>';
    	
        oContent.innerHTML = html;
        oFrame = document.getElementById('e2ViewerFrame');

	    try {
		    AddEventSimple(oFrame,"load",that.iFrameLoaded);
		    AddEventSimple(window,"resize",that.PositionAll);
		    AddEventSimple(window,"scroll",that.PositionAll);
		    oFrame.src = showurl;
	    } catch(e) {
		    alert('Not supported in this browser. Content will open in a new window.');
		    that.RemoveAll();
		    WinBRopen(url, 'PreviewWindow', width + 30, height + 10);
	    }
    }
    
    this.iFrameLoaded = function() {
        RemoveEventSimple(oFrame,"load",that.iFrameLoaded);
	    oContent.style.display = '';
	    //oCover.style.background = '';
	    oCover.style.display = 'none';
	    animateTimer = setInterval(ShowCloseBar, 15);
    }

    function ShowCloseBar() {
	    var top = parseInt(oClose.style.top.replace(/px/,''));
	    oClose.style.display = '';	
    	
	    if(top > targetT - titleH) {
		    top--;
		    oClose.style.top = top + 'px';
	    } else {
	        clearInterval(animateTimer);
	    }
    }

    function GetIEVersion() {
	    var regex = new RegExp("msie\\s*([\\d.]+);","i");
	    var matches = regex.exec(navigator.userAgent);
	    if(matches !== null && matches.length === 2) return parseFloat(matches[1]);
	    return -1.0
    }

    this.CloseAll = function(reloadPage) {
        //reloadOnClose = (reloadPage) ? true : null;
        reloadOnClose = reloadPage;
        oCover.innerHTML = '&nbsp;';
        oCover.style.display = '';
        oCover.style.backgroundColor = '#FFFFFF';
        oCover.style.left = targetL + 'px';
        oCover.style.top = targetT + 'px';
	    oContent.style.display = 'none';
	    oClose.style.display = 'none';
		//AV = new AnimateVals(oCover);
	    animateTimer = setInterval(ShrinkDiv, 10);
    }
    
    this.RemoveAll = function() {
	    if(oHolder) {
			clearInterval(animateTimer);
		    RemoveEventSimple(window,"resize",that.PositionAll);
		    RemoveEventSimple(window,"scroll",that.PositionAll);
    		
	        var par = oHolder.parentNode;
	        par.removeChild(oHolder);
		    e2Layer = null;
		    if(reloadOnClose) { window.location.reload() };
        }
    }

    function ShrinkDivUp() {
		if(AV === null) { AV = new AnimateVals(oCover); }
		var incY = 20;
		
		if(AV.done) {
			clearInterval(animateTimer);
			AV = null;
			that.RemoveAll();
		} else {
			if(AV.height > 0 && AV.height - incY <= incY) {
				AV.height = 0;
				oCover.style.height = AV.height + 'px';
				AV.done = true;
			} else {
				AV.height -= incY;
				oCover.style.height = AV.height + 'px';
			}
		}
    }

    function ShrinkDiv() {
		if(AV === null) { AV = new AnimateVals(oCover); }
		var incX = 40;
		var incY = parseInt(AV.height/(AV.width/incX));
		
		if(AV.done) {
			clearInterval(animateTimer);
			AV = null;
			that.RemoveAll();
		} else {
			if(AV.width > 0 && AV.width - incX <= 0) {
				AV.width = 0;
				AV.left = parseInt(targetL + targetW/2);
				AV.height = 0;
				AV.top = parseInt(targetT + targetH/2);
				AV.done = true;
			} else {
				AV.width -= incX;
				AV.left += parseInt(incX/2);
				AV.height -= incY;
				AV.top += parseInt(incY/2);
			}
			oCover.style.width = AV.width + 'px';
			oCover.style.left = AV.left + 'px';
			oCover.style.height = AV.height + 'px';
			oCover.style.top = AV.top + 'px';
		}
    }

    function WinBRopen(theURL, Name, popW, popH) {
	    var winHorz = (screen.width-popW)/2;
	    var winVert = (screen.height-popH)/2;
	    var winProp = 'width='+popW+',height='+popH+',left='+winHorz+',top='+winVert+',scrollbars=yes,resizable=yes';
	    PreviewWin = window.open(theURL, Name, winProp);
	    if (parseInt(navigator.appVersion) >= 4 && PreviewWin) { PreviewWin.window.focus(); }
    }
    
    function AddEventSimple(obj,evt,fn) {
	    if (obj.addEventListener)
		    obj.addEventListener(evt,fn,false);
	    else if (obj.attachEvent)
		    obj.attachEvent('on'+evt,fn);
    }

    function RemoveEventSimple(obj,evt,fn) {
	    if (obj.removeEventListener)
		    obj.removeEventListener(evt,fn,false);
	    else if (obj.detachEvent)
		    obj.detachEvent('on'+evt,fn);
    }
    
    this.PositionAll();
}
