
var clipIdNumber = null;
var viewSpeed = null;
var button = null;
var startTimeOffset = 0;

function hideJoinBox() {
	if (o = document.getElementById('joinStd'))
		o.css('display', 'none');
	if (o = document.getElementById('joinSpiffy'))
		o.css('display', 'none');

	if (o = document.getElementById('joinUnderlay'))
		o.css('display', 'none');
}

function showJoinBox() {
	if (o = document.getElementById('joinStd')) {
		o.css('display', 'block');
		o.style.top = document.body.scrollTop  + 'px';
	}
	if (o = document.getElementById('joinSpiffy')) {
		o.css('display', 'block');
		o.style.top = document.body.scrollTop  + 'px';
	}
	if (o = document.getElementById('joinUnderlay'))
		o.css('display', 'block');
}

function quickShowImage(url) {
	if ($('#quickShowImageContainer'))
		quickShowClose();

	var div = document.createElement('div');
	var img = new Image();
	img.src = url;
	
	var load = $('#quickShowLoading');
	if (!load) {
		load = document.createElement('div');
		load.setAttribute('id', 'quickShowLoading');
		document.body.appendChild(load);
	}
	load.css({'top':window.pageYOffset + window.innerHeight / 2 + 'px', 'display':'block'});

	img.onload = function() {
		load.css('display', 'none');
		div.css({
			'position': 'absolute',
			'overflow:': 'hidden',
			'white-space': 'nowrap',
			'width': this.width + 'px',
			'height': this.height + 'px',
			'display': 'block'
		});
		div.addClass('quickShowIn');
		div.css({
			'left': '50%',
			'top': window.pageYOffset + window.innerHeight / 2 + 'px',
			'marginTop': '-' + this.height/2 + 'px',
			'marginLeft': '-' + this.width/2 + 'px'
		})

	}
	div.setAttribute('id', 'quickShowImageContainer');
	div.css('display', 'none');
	div.innerHTML = "<a class='closeButton' href='javascript:quickShowClose()'>close</a>";
	div.onclick = quickShowClose;
	div.appendChild(img);
	document.body.appendChild(div);
}

function quickShowClose() {
	var div = $('#quickShowImageContainer');
	if (div) document.body.removeChild(div);
}



/*** POPUP MENU CODE START ***/
function htmlCreateUnderlay(name) {
	var div = document.createElement('div');
	div.setAttribute('id', name);
	div.css('display', 'none');
	document.body.appendChild(div);
	return div;
}

/** popup menu only expects an optional closeButton class for closing the popup and menu items in 
    <li></li> or <li class="selected"></li> **/
function PopupMenu() {
	Utils.extend(this, {
		me: 'PopupMenu(): ',
		show: function() {
			this.disabled = false;

			if (!this.popup) throw new Error(this.me + 'Popup does not exist');
			var popupTop = 30;
			this.popup.css({'top': window.pageYOffset + popupTop + 'px' , 'display': 'block'});
			
			var popupH = window.pageYOffset + this.popup.getFullHeight() + (popupTop * 2);
			var pageH = document.body.clientHeight;
			this.underlay.css({'display': 'block', 'height': (popupH > pageH ? popupH : pageH) + 'px', 'top': '0'});
			if (window.pageYOffset < 2) window.scrollTo(0, 1);
			
			if (this.outsideHide) {
				if (IS_IPHONE) {
					var thisObj = this;
					this.underlay.ontouchstart = function(e) {
						e.preventDefault();
						thisObj.hide();
						return false;
					}
				}
				else {
					this.elistener = delegate(this, this.hide);
					this.underlay.addEventListener('click', this.elistener, false);	
				}
			}
		},
		hide: function() {
			this.underlay.css('display','none');
			this.popup.css('display', 'none');
			if (this.outsideHide) {
				if (IS_IPHONE)
					this.underlay.ontouchstart = null;
				else {
					if (this.elistener)
						this.underlay.removeEventListener('click', this.elistener, false);
				}
			}
		},
		getUnderlay: function() {
			var underlay = $('#wkPopupMenuUnderlay');
			if (!underlay) underlay = htmlCreateUnderlay('wkPopupMenuUnderlay');
			return underlay;
		},
		select: function(el) {
			if (el && !el.hasClass('stdButton')) el.addClass('selected');
			this.disabled = true;
			var thisObj = this;
			var href = el.href;
			setTimeout(function() {
				thisObj.hide();
				window.location = href;
			}, this.menuCloseDelay);
		},
		clearSelected: function() {
			var lis = $$('.menu a', this.popup), i = lis.length;
			while (i--) {
				var el = lis[i];
				if (el.hasClass('selected')) el.removeClass('selected');
			}
		},
		contructor: function(selector, outsideHide) {
			this.id = selector;
			this.menuCloseDelay = 300;
			this.outsideHide = (outsideHide != undefined ? outsideHide : true);
			this.disabled = false;
			this.popup = $(selector);
			this.underlay  = this.getUnderlay();
			
			if (!this.popup) throw new Error(this.me + 'Popup "' + selector + '" does not exist');3
			if (this.popup) {
				var close = $('.closeButton', this.popup)
				if (close) close.addEventListener('click', delegate(this, this.hide), false);
				
				var buttons = $$('.menu a', this.popup), l = buttons.length;
				for (var i=0; i<l; i++) {
					var el = buttons[i];
					var thisObj = this;
					el.addEventListener('click', function(e) {
						if (!thisObj.disabled && !this.hasClass('selected')) {
							thisObj.clearSelected();
							thisObj.select(this);
						}
						e.preventDefault();
						return false;
					}, false);
				}
			}
		}
	});
	
	this.contructor.apply(this, arguments);
}
/*** POPUP MENU CODE END ***/






/*****************************************************************************
 * STREAMBOX (VIDEO SETTINGS)                                                *
 *****************************************************************************/
function streamBoxShow(msg) {
	
	var videoBox = document.getElementById('videoPlayerPopup');
	videoBox.css({'display': 'none'});
	
	var streamBox = document.getElementById('streamBox');
	//var underlay  = document.getElementById('streamBoxUnderlay');
    if (!streamBox) return;
	if (streamBox.css('display') == 'none') {
		var h1 = document.height || document.body.offsetHeight;
		var h2 = (window.innerHeight + window.pageYOffset);
		//if (underlay) underlay.css({'display': 'block', 'height': (h1 > h2 ? h1 : h2) + 'px' });
		streamBox.css({'top': window.pageYOffset + (window.innerHeight/2 - streamBox.getFullHeight()/2) + 'px',	'display': 'block'});
		if (window.pageYOffset < 2) window.scrollTo(0, 1);
	}
	else
		streamBox.css('display', 'none');
}
function streamBoxHideUnderlay() {
	document.getElementById('streamBoxUnderlay').css('display','none');
	document.getElementById('streamBox').css('display', 'none');
}
function streamBoxSet(type) {
	var buttons = document.querySelectorAll('#streamBox .streamOptions a');
	for (var i=0; i<buttons.length; i++) {
		var el = buttons[i];
		if (el.getAttribute('rel') == type)
			el.addClass('selected');
		else {
			if (el.hasClass('selected'))
				el.removeClass('selected');
		}
	}
}	
function setupStreamBox() {
	
	var streamBox = document.getElementById('streamBox');
    if (!streamBox) return false;
    
	var underlay = htmlCreateUnderlay('streamBoxUnderlay');
	var imgs = new Array();

	if (IS_IPHONE) {
		underlay.ontouchstart = function(e) {
			e.preventDefault();
			streamBoxHideUnderlay();
		}
	}
	else
		underlay.addEventListener('click', streamBoxHideUnderlay, false);
		
	var buttons = document.querySelectorAll('#streamBox .streamOptions a');

	for (var i=0; i<buttons.length; i++) {
		var el = buttons[i];
		
		if (IS_IPHONE) {
			el.ontouchstart = function(e) {
				e.preventDefault();
				streamBoxSet(this.getAttribute('rel'));
			};
			el.ontouchend = function(e) {

				e.preventDefault();
				loadRedirect(this.getAttribute('rel'));
			};
		}
		else {
			el.addEventListener('click', function(e) {
				
				loadRedirect(this.getAttribute('rel'));
				
			}, false);
		}
	}

	// if the cookie is not set for streaming cookieViewSpeed ask for it
	if (Cookie.read('cookieViewSpeed') != null)
		streamBoxSet(Cookie.read('cookieViewSpeed'));
	else if (streamBox.hasClass('initSetting'))
		streamBoxShow();
}

function loadRedirect( rel ) {
	
	Cookie.create('cookieViewSpeed', rel, 365);
	streamBoxSet(rel);
	setTimeout('streamBoxHideUnderlay()', 100);
	
	// redirect code
	var newViewSpeed = 'viewSpeed=' + rel;
	var oldViewSpeed = 'viewSpeed=' + ( viewSpeed ? viewSpeed : getQuerystring('viewSpeed') );
	viewSpeed = rel;
	
	if ( !$("#FULLEPISODE") ) {
	
		var oldHref = window.location.href;
		newHref = oldHref.replace(oldViewSpeed,newViewSpeed);
		window.location.href = newHref;
		return;
	}
	
	$("#FULLEPISODE").href = $("#FULLEPISODE").href.replace(oldViewSpeed,newViewSpeed);
	$(".trailerButton").href = $(".trailerButton").href.replace(oldViewSpeed,newViewSpeed);
	
	for ( var i = 1; i<10; i++ ) {
		
		if ( !$("#BTN"+i) ) continue;
		var rawHref = $("#BTN"+i).href;
		$("#BTN"+i).href = rawHref.replace(oldViewSpeed,newViewSpeed);
	}
	
	// button, button, who'se got the button
	var a = ( clipIdNumber == 0 
			  ? $('#FULLEPISODE') 
			  : ( clipIdNumber == -1 
				  ? $('.trailerButton') 
				  : $('#BTN'+clipIdNumber) )
	);
	
	var e = document.createEvent('MouseEvents');
    
	var video;
	if ( document.getElementById('videoTrailerEmbed') ) {
		
		video = document.getElementById('videoTrailerEmbed');
		startTimeOffset = video.currentTime;
	}
   
	e.initMouseEvent( "click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null );
	a.dispatchEvent(e);
}

function getDetailsShow() {
	var defaultValue = 'hide';
	var sh = Cookie.read('showDetails');
	if (sh != null)
		return sh;
	Cookie.create('showDetails', defaultValue, 365);
	return defaultValue;
}
function setupDetailsBox() {
	var detailsButton = document.getElementById('hideDetailsButton');
	if (!detailsButton) return;
	var details = $('.episodeDetails');
	var showDetails = getDetailsShow('show');

	var reconcileDetails = function(show) {
		if (show == undefined)
			show = detailsButton.innerHTML == 'Show Details' ? show = 'show': 'hide';
		if (show == 'show') {
			detailsButton.innerHTML = 'Hide Details';
			details.css('display', 'block');
			Cookie.create('showDetails', 'show', 365);
		}
		else {
			detailsButton.innerHTML = 'Show Details';
			details.css('display', 'none');
			Cookie.create('showDetails', 'hide', 365);
		}
	}
	
	reconcileDetails(showDetails);
	detailsButton.addEventListener('click', function() {
		reconcileDetails();
	}, false);
}
function setupToggleButtons() {
	var buttons = $$('.toggleButton');
	var l = buttons.length;
	
	for (var i=0; i<l; i++) {
		var obj = buttons[i];
		obj.addEventListener('click', function() {
			if (this.hasClass('toggleButtonOn')) {
				this.removeClass('toggleButtonOn');
				this.addClass('toggleButtonOff');
			}
			else {
				this.removeClass('toggleButtonOff');
				this.addClass('toggleButtonOn');
			}
		}, false);
	}
}


function main() {
	setupStreamBox();
}

addEventListener('load', main, false);

function getQuerystring(key, default_)
{
  if (default_==null) default_="";
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

addEventListener('load', function() {
    if(document.getElementById('nichesMenu')) {
        window.niches = new PopupMenu('#nichesMenu', false);
    }
}, false);

function detectVideoSupport() {
    var detect = document.createElement('video') || false;
    this.html5 = detect && typeof detect.canPlayType !== "undefined";
    this.mp4 = this.html5 && (detect.canPlayType("video/mp4") === "maybe" || detect.canPlayType("video/mp4") === "probably");
    this.ogg = this.html5 && (detect.canPlayType("video/ogg") === "maybe" || detect.canPlayType("video/ogg") === "probably");
    return this;
};

function loadVideoPopup(videoUrl,dontCloseWhenDone,viewLimit,joinUrl,clipNum) {

	if ( clipNum != null )  clipIdNumber = clipNum;
	
    // this makes the assumption that the trailerViews cookie is a native
    // javascript array...and I'm certain that's not the case here
    var tviews = Cookie.read('trailerViews');
    if( tviews != null){
        var tviewArray = tviews.split(':');
        if(tviewArray.length > viewLimit){
            document.location = joinUrl;
            return false;
        }
    }
    	
	// handle non-supporting browsers
    // Both Opera and Firefox support OGG but lack MP4 support
    var videoSupport = detectVideoSupport();
    if((videoSupport.ogg && !videoSupport.mp4) || navigator.appName == "Microsoft Internet Explorer"){
        document.location = videoUrl;
        return false;
    }

   // if the url is in a members area and not a direct url this creates an authentication issue with airplay
    // in order to resolve this we do a syncronous ajax request to the server to obtain the actual video url
    if(videoUrl.search(/\.mp4/) == -1 && document.location.hostname.search(/members/) != -1) {
        videoUrl = document.location.protocol + '//' + document.location.hostname + videoUrl;
        var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
        xhr.open('GET',videoUrl,false);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.send();
        if(xhr.readyState==4 && xhr.status == 200){
            if(xhr.responseText) {
                videoUrl = xhr.responseText;    
            }
        }
    }

    // add the download link
    // comment this out as the donload link was removed per ticket 49414
    /*
    var downloadLink = $('#videoDownloadButton');
    if(downloadLink) {
        downloadLink.setAttribute('href', videoUrl);
        downloadLink.css({'display':'inline'});
    }
    */

    var underlay = $('#videoPlayerUnderlay');
    var popup = $('#videoPlayerPopup');
    var c = $('#videoPlayerContainer');
    var v = $('#videoTrailerEmbed');
    if (v && c) c.removeChild(v);
    if (underlay) underlay.css({'display':'block', 'height': document.body.clientHeight+'px', 'top':'0px'});
    if (c) {
        v = document.createElement('video');
        v.setAttribute('id', 'videoTrailerEmbed');
        v.setAttribute('controls', 'controls');
        v.setAttribute('x-webkit-airplay', 'allow');
        v.setAttribute('autoPlay', 'autoplay');
        v.setAttribute('src', videoUrl);
        
        c.appendChild(v);
        if (dontCloseWhenDone !== true)
            v.addEventListener('ended', closeVideoPopup, false);

        v.play();
        //v.addEventListener('loadedmetadata', loadVideoStart, false);
    }
    
    if (popup) popup.css({'display':'block', 'top':window.pageYOffset + 'px'});
    document.ontouchmove = function(e) { e.preventDefault(); return false; }
    $('body').addEventListener('orientationchange', videoPopupResetPosition, false);
    sizeVideo();
}

function loadVideoStart(event) {
	// iOS on iPad does not support setting currentTime
    //$('#videoTrailerEmbed').currentTime = 0; //( startTimeOffset >= 0 ? parseInt(startTimeOffset) : 0 );
}

function sizeVideo() {
    if (window.orientation != undefined) {
        if (window.orientation == 0) $('#videoPlayerContainer video').css({'width':'768px', 'height':'439px'});
        else $('#videoPlayerContainer video').css({'width':'1024px', 'height':'585px'});
    }
}
function videoPopupResetPosition(e) {
    var u = $('#videoPlayerUnderlay');
    var p = $('#videoPlayerPopup');
    if (u) u.css({'top':window.pageYOffset + 'px', height:window.innerHeight + 'px'});
    if (p) p.css('top', window.pageYOffset + 'px');
    sizeVideo();
}
function closeVideoPopup() {
	
	startTimeOffset = 0;
	
	var o = $('#streamBoxUnderlay');
	var y = $('#streamBox');
    var u = $('#videoPlayerUnderlay');
    var p = $('#videoPlayerPopup');
    var c = $('#videoPlayerContainer');
    var v = $('#videoTrailerEmbed');
    
    if (o) o.css('display', 'none');
    if (y) y.css('display', 'none');
    if (u) u.css('display', 'none');
    if (p) p.css('display', 'none');
    if (v && c) c.removeChild(v);

    document.ontouchmove = null;
    removeEventListener('orientationchange', videoPopupResetPosition, false);
}

function openNewWindow(url) {
    window.open(url);
}




