/*
    popup.js
    Version 2.0
    April 18, 2007
    Eric Salczynski - http://www.wehaventthetime.com
    Inspired by Lightbox v2 - http://www.huddletogether.com/projects/lightbox2
    
    Create popup windows using absolutely positioned div elements
    who's content is built into your existing markup.
    
    * Requires prototype.js, scriptaculous.js, and effects.js
    * Download them from http://script.aculo.us
*/

// create and define new class Popup
var Popup = Class.create();
Popup.prototype = {

    // defaults
    width: 740,
    height: 540,
    delay: 1000,
    
    // initialize useful class variables
    pageSize: null,
    el: null,
    
    // array to hold ids of all popup boxes
    popupBoxes: new Array(),

    // optional options for boxes
    /*  parameters:
                    event: onclick | onmouseover
                    position: center | center-float | fixed | float | cursor
                    right | left & top | bottom: <int>    (only w/ fixed or float)
                    width, height: <int>    (only w/ center, center-float, or cursor)
                    delay: <int>    (milliseconds - only w/ onmouseover)
                    effect: true | false    (use fade effect or not - recommend setting this to false with delay < 500)
    */
    options: $H({
                    bugReportBox: $H({ event: 'onclick', position: 'center-float', width: 340, height: 380, effect: true })
                }),
    
    // adds 'onclick' event listener to all anchors with a rel attribute matching 'popup'
    initialize: function() {
        if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');

		// loop through all anchor tags
		for (var i = 0; i < anchors.length; i++) {
			var anchor = anchors[i];
			var relAttribute = String(anchor.getAttribute('rel'));
			
			// use the string.search() method to catch 'popup' references in the rel attribute
			if (anchor.getAttribute('href') && relAttribute.toLowerCase().search('popup_') != -1) {
				
				// split the rel attribute on '_' to get the id of the element to "popup" and put the id in the variable popupBoxes
				var relArray = relAttribute.split('_')
				var el = this.options[relArray[1]]
			    this.popupBoxes.push(relArray[1])
			    
			    if(el && el.event == 'onmouseover') {
                    delay = el.delay != null ? el.delay : this.delay
                    anchor.onmouseover = function() {
                        timeout = setTimeout("myPopup.start('"+relArray[1]+"')", delay);
                        if(el.position == 'cursor') { this.onmousemove = myPopup.cursorPosition }
                    }
                    anchor.onmouseout = function () {
                        clearTimeout(timeout);
                        this.onmousemove = null;
                        myPopup.end(relArray[1]);
                    }
                    anchor.onclick = function() { return false; }
                } else
    				anchor.onclick = function() { myPopup.start(relArray[1]); return false; }
			}
		}
    },
    
    // opens the popup window as an absolutely positioned div element
    start: function(id) {
        var objBody = document.getElementsByTagName('body').item(0)
        var popup = $(id)
        this.el = this.options[id]
        
        // check to see if popup is already open
        if (popup.style.display != "none") { return; }
        
        // loop through all items in popupBoxes to close any open popups if alwaysHide == true
        if(this.el && this.el.alwaysHide) {
            for (var i = 0; i < this.popupBoxes.length; i++) {
                div = $(this.popupBoxes[i])
                if (div.style.display != "none") { myPopup.end(div) }
            }
        }
        
        // create temporary placeholder div
        var tempDiv = document.createElement("div")
        tempDiv.setAttribute("id", "temp")
        tempDiv.style.display = "none"
        objBody.appendChild(tempDiv)
        
        // get the parent div element of the popup
        var parent = popup.parentNode

        // replace temp div with content div
        var replacedDiv = objBody.replaceChild(popup, tempDiv)
        
        // put the replaced div element where the content div was
        parent.appendChild(replacedDiv)
        
        // create a close link to hide the popup if event == onclick
        if(this.el == null || this.el.event != 'onmouseover') {
            var closer = document.createElement("div")
            closer.setAttribute("id", "closer")
            closer.style.position = "absolute"
            closer.style.top = "15px"
            closer.style.right = "15px"
            closer.style.textAlign = "right"
            
            var closerLink = document.createElement("a")
            closerLink.setAttribute("href", "#close")
            closerLink.onclick = function () { myPopup.end(popup); return false; }
    
            var txtClose = document.createTextNode("Close [x]")
            
            closerLink.appendChild(txtClose)
            closer.appendChild(closerLink)
            popup.appendChild(closer)
        }
        
        // figure position of popup based on screen size/scroll or mouse position
        this.setPosition(popup)
        
        // use the Appear effect to show the popup for not IE browsers
        if (navigator.appName == "Microsoft Internet Explorer" || (this.el != null && !this.el.effect))
            popup.style.display = "block"
        else
            new Effect.Appear(popup.id, { duration: 0.5 })
    },
    
    // closes an open popup
    end: function(id) {
        var objBody = document.getElementsByTagName("body").item(0)
        var popup = $(id)
        var tempDiv = $("temp")
        var closer = (this.el == null || this.el.event == 'onclick') ? $("closer") : null
        
        // remove popup from view with the Fade effect, then replace temp div with content div
        // to return it to the normal document flow
        if (navigator.appName == "Microsoft Internet Explorer" || (this.el != null && !this.el.effect)) {
            popup.style.display = "none"
            if(closer) { popup.removeChild(closer) }
            if(tempDiv) { tempDiv.parentNode.replaceChild(popup, tempDiv) }
        }
        else {
            new Effect.Fade(popup.id, {
                duration: 0.5,
                afterFinish: function() {
                    if(closer) { popup.removeChild(closer) }
                    if(tempDiv) { tempDiv.parentNode.replaceChild(popup, tempDiv) }
                }
            })
        }
    },
    
    setPosition: function(popup) {
        if(this.el) {
            switch(this.el.position) {
                case "cursor":
                    break;
                case "float":
                    var prevResize = (window.onresize) ? window.onresize : function() {}
                    var prevScroll = (window.onscroll) ? window.onscroll : function() {}
                    window.onresize = function() { prevResize(); myPopup.updatePosition(popup) }
                    window.onscroll = function() { prevScroll(); myPopup.updatePosition(popup) }
                case "fixed":
                    this.updatePosition(popup)
                    break;
                case "center-float":
                    var prevResize = (window.onresize) ? window.onresize : function() {}
                    var prevScroll = (window.onscroll) ? window.onscroll : function() {}
                    window.onresize = function() { prevResize(); myPopup.centerPosition(popup) }
                    window.onscroll = function() { prevScroll(); myPopup.centerPosition(popup) }
                default:
                    this.centerPosition(popup)
                    break;
            }
        } else
            this.centerPosition(popup)
    },
    
    // used for the 'fixed' and 'float' positions
    updatePosition: function(popup) {
        this.pageSize = getPageSize()
        
        if(this.el.right != null)
            popup.style.right = (this.el.right - this.pageSize[0]) + "px"     // right
        else
            popup.style.left = (this.pageSize[0] + this.el.left) + "px"       // left
            
        if(this.el.top != null)
            popup.style.top = (this.pageSize[1] + this.el.top) + "px"         // top
        else
            popup.style.bottom = (this.el.bottom - this.pageSize[1]) + "px"   // bottom
    },
    
    // used for the 'center' and 'center-float' positions
    centerPosition: function(popup) {
        this.pageSize = getPageSize()
        
        if(this.el && this.el.height != null && this.el.width != null) {
            height = this.el.height
            width = this.el.width
        } else {
            height = this.height
            width = this.width
        }
            
        popup.style.top = (this.pageSize[1] + (this.pageSize[3] - height) / 2) + "px"
        popup.style.left = (this.pageSize[0] + (this.pageSize[2] - width) / 2) + "px"
    },
    
    // used for the 'cursor' position
    cursorPosition: function(e) {
        var relArray = this.readAttribute('rel').split('_')
        var target = $(relArray[1])
        var el = myPopup.options[relArray[1]]
        var pageSize = getPageSize()
        var posX = 0;
        var posY = 0;
        
        if (!e) var e = window.event;
        
        if (e.pageX || e.pageY) {
        	posX = e.pageX;
        	posY = e.pageY;
        }
        else if (e.clientX || e.clientY) {
            posX = e.clientX + document.body.scrollLeft
            	+ document.documentElement.scrollLeft;
            posY = e.clientY + document.body.scrollTop
            	+ document.documentElement.scrollTop;
        }
        
        // make adjustments for elements that might appear outside of the viewing area
        if(posX - el.width < 0)
            posX = posX
        else if(posX + el.width > pageSize[2])
            posX -= el.width

        if(posY - el.height < 0)
            posY = posY
        else if(posY + el.height > pageSize[3])
            posY -= el.height

        // update style positioning
        target.style.top = posY + "px"
        target.style.left = posX + "px"
        
        // ABSOLUTELY NECESSARY - removing these lines will result in strobing of the popup
        target.style.zIndex = 0     // set the popup to have a lower z-index than the anchor
        this.style.zIndex = 1
    }
}

/* 
    getPageSize()
        Inspired by lightbox.js
        Core code from - quirksmode.org
        Returns array with x/y page scroll values and window width/height.
*/
function getPageSize(){
	
	// scroll values
	var xScroll, yScroll;
    if (self.pageYOffset) {
        xScroll = self.pageXOffset;
        yScroll = self.pageYOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {      // Explorer 6 Strict
        xScroll = document.documentElement.scrollLeft;
        yScroll = document.documentElement.scrollTop;
    } else if (document.body) { // all other Explorers
        xScroll = document.body.scrollLeft;
        yScroll = document.body.scrollTop;
    }

	// window values
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	

	arrayPageSize = new Array(xScroll,yScroll,windowWidth,windowHeight)
	return arrayPageSize;
}

// initialization function to create new Popup object
function initPopup() { myPopup = new Popup(); }