/*
    Modified from Slimbox code to load content into a lightbox overlay via AJAX.
    Finds all <a> tags where href has '/videos/player' in it and binds them to this class.
*/

function detectMacFF() {
    var userAgent = navigator.userAgent.toLowerCase();
    if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
        return true;
    }
}

var Htmlbox = new Class({
    
    initialize: function(options){
        
        this.linkRegex = /http:\/\/(www\.)?epitaph\.(cubancouncil\.)?(com|dev)\/videos\/player/, // Regex to test for in hrefs
        
        // Set options
		this.options = Object.extend({
			resizeDuration: 400,
			resizeTransition: Fx.Transitions.sineInOut,
			initialWidth: 728,
			initialHeight: 353,
			displayWidth : 728, 
			displayHeight: 353,
            offsetTop: 150 // Offset from flash nav
		}, options || {});
		
		// Set video player links
		this.anchors = [];
		$each(document.links, function(el){
			if (el.href && el.href.test(this.linkRegex, "i")){
				$(el).addEvent('click', function(event) {
				    this.click(event, el);
				}.bind(this));
				this.anchors.push(el);
			}
		}, this);
		
		this.nowOpen = false;
		
		this.eventPosition = this.position.bind(this);
		
		// Build view box
		this.overlay = new Element('div').setProperty('id', 'lbOverlay').setStyles({visibility: "hidden", top: "0"}).injectInside(document.body);
		this.center = new Element('div').setProperty('id', 'lbCenter').setStyles({width: this.options.initialWidth+'px', height: this.options.initialHeight+'px', marginLeft: '-'+(this.options.initialWidth/2)+'px', display: 'none'}).injectInside(document.body);
		this.canvas = new Element('div').setProperty('id', 'lbCanvas').injectInside(this.center);
		
		// Bottom
        this.bottomContainer = new Element('div').setProperty('id', 'lbBottomContainer').setStyle('display', 'none').injectInside(document.body);
        this.bottom = new Element('div').setProperty('id', 'lbBottom').injectInside(this.bottomContainer);
        
        // Close link
        closeLink = new Element('a').setProperties({ id: "lbCloseLink", href: "#" });
        closeLink.addClass("close");
        closeLink.setHTML("<span>Close</span>");
        closeLink.onclick = this.close.bind(this);
        closeLink.injectInside(this.bottom);
        
        this.overlay.onclick = this.close.bind(this);
		new Element('div').setStyle('clear', 'both').injectInside(this.bottom);

	},
	
	click: function(event, link){
	    
	    event = new Event(event).stop();
		
		if (link.rel.length == 8) return this.show(link.href, link.title, link.rev);

		var j, itemNumber, items = [];
		this.anchors.each(function(el){
			if (el.rel == link.rel){
				for (j = 0; j < items.length; j++) if(items[j][0] == el.href && items[j][2] == el.rev) break;
				if (j == items.length){
					items.push([el.href, el.title, el.rev]);
					if (el.href == link.href && el.rev == link.rev) itemNumber = j;
				}
			}
		}, this);
		return this.open(items, itemNumber);
	},

	show: function(url, title, rev){
		return this.open([[url, title, rev]], 0);
	},
	
	open: function(items, itemNumber){
		this.items = items;
		
		if (!this.nowOpen) {
		    this.position();
    		this.setup(true);
    		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
    		var st = document.body.scrollTop  || document.documentElement.scrollTop;
    		this.top = st + (wh / 15) + this.options.offsetTop;
    		this.center.setStyles({top: this.top+'px', display: ''});
        
            this.overlay.style.visibility = 'visible';
    		this.center.style.visibility = 'visible';
		
    		if (detectMacFF()) {
                //osx ff css opacity + flash causes problems
                this.overlay.style.backgroundColor = "transparent";
                this.overlay.style.backgroundImage= "url(/_img/generic/opaque.png)";
                this.overlay.style.backgroundRepeat="repeat";
            } else {
                this.overlay.style.backgroundColor = "#333";
                this.overlay.style.MozOpacity = .8;
                this.overlay.style.opacity = .8;
                this.overlay.style.filter = "alpha(opacity=80)";
            }
        }
        
		return this.changeItem(itemNumber);
	},
	
	position: function(){
		//IE6 - XML prolog problem.
		var ww = (window.getWidth() == 0) ? window.getScrollWidth()-22 : window.getWidth();
		var wh = (window.getHeight() == 0) ? window.getScrollHeight() : window.getHeight();
        var st = document.body.scrollTop  || document.documentElement.scrollTop;
        this.overlay.setStyles({top: st+'px', height: wh+'px', width: ww+'px'});
	},
	
	setup: function(open){
	    this.nowOpen = open;
		var elements = $A(document.getElementsByTagName('object'));
		elements.extend(document.getElementsByTagName(window.ie ? 'select' : 'embed'));
		elements.extend(document.getElementsByTagName('iframe'));
		elements.each(function(el){
			if (open) el.lbBackupStyle = el.style.visibility;
			el.style.visibility = open ? 'hidden' : el.lbBackupStyle;
		});
		
		this.center.style.display = open ? 'block' : 'none';
		this.overlay.style.visibility = open ? 'visible' : 'hidden';
        this.overlay.style.display = open ? 'inline' : 'none';
        
        if (open) {
            window.addEvent('scroll', this.eventPosition);
            window.addEvent('resize', this.eventPosition);
        }else{
            window.removeEvent('scroll', this.eventPosition);
            window.removeEvent('resize', this.eventPosition);
        }
	},
	
	changeItem: function(itemNumber){
		if ((itemNumber < 0) || (itemNumber >= this.items.length)) return false;
		this.activeItem = itemNumber;

		this.center.className = 'lbLoading';
		
		this.bottomContainer.style.display = 'none';

		this.removeCurrentItem();
		
		// check item type
		var url = this.items[this.activeItem][0];
		var rev = this.items[this.activeItem][2];
		
		this.displayItem = new Object();
		this.displayItem.w =  this.matchOrDefault(rev, new RegExp("width=(\\d+)", "i"), this.options.displayWidth);
		this.displayItem.h = this.matchOrDefault(rev, new RegExp("height=(\\d+)", "i"), this.options.displayHeight);
		this.displayItem.url = url
		
		this.display();

		return false;
	},
	
	display: function() {
	    this.center.className = '';

		// Create HTML element
		this.p_width = this.displayItem.w;
		this.p_height = this.displayItem.h;
		
		this.iframeId = "lbFrame_"+new Date().getTime(); // Safari would not update iframe content that has static id.
		var displayDiv = new Element('div').setProperties({id: this.iframeId, width: this.p_width, height: this.p_height, style: "padding: 10px;"});
		var loading = new Element('div').setProperty("id","lbLoadingIndicator");
		var loadingImg = new Element('img').setProperties({src: '/_img/generic/loading.gif', alt: 'Loading', width: '24', height: '24'});
	    
	    loadingImg.injectInside(loading);
	    loading.injectInside(displayDiv);
	    displayDiv.injectInside(this.canvas);
		
		this.canvas.style.width = this.bottom.style.width = this.p_width+'px';
        this.canvas.style.height = this.bottom.style.height = this.p_height+'px';
        this.bottomContainer.setStyles({top: (this.top + this.center.clientHeight)+'px', height: 'auto', marginLeft: this.center.style.marginLeft, width:this.center.style.width, display: ''});
        this.bottom.style.width = "auto";
        this.bottom.style.height = this.bottomContainer.style.height;
        
		this.displayRequest = new Ajax(this.displayItem.url, {
		    update: displayDiv,
		    evalScripts: true, // Execute javascript in loaded content
		    onComplete: function() {
                if ($('lbLoadingIndicator')) $('lbLoadingIndicator').remove();
                $each(displayDiv.getElements('a'), function(el){ // Get lightbox links from within display
        			if (el.href && el.href.test(this.linkRegex, "i")){
        				el.addEvent('click', function(event) {
        				    this.click(event, el);
        				}.bind(this));
        				this.anchors.push(el);
        			}
        		}, this);
		    }.bind(this)
		}).request();
	},

	close: function(){
	    this.displayRequest.cancel(); // Stop current ajax call
        this.removeCurrentItem(); // discard content
        this.center.style.display = this.bottomContainer.style.display = 'none';
        this.overlay.style.visiblity = 'hidden';
        this.setup(false);
		return false;
	},

	removeCurrentItem: function(){
		if (this.displayItem){
		    var removeItem = $(this.iframeId);
		    removeItem.innerHTML = ''; // Gets rid of continued flash streaming in IE
            removeItem.remove();
			this.displayItem = null;
		}		
	},

	matchOrDefault: function(str, re, val){
		var hasQuery = str.match(re);
		return hasQuery ? hasQuery[1] : val;
	}
	
});

window.addEvent('domready', function() {
    var hBox = new Htmlbox();
});