var IS_IPHONE = ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) ? true : false;
function delegate(that, thatMethod) {
	return function() { return thatMethod.call(that); }
}
(function() {

	if (foo == undefined)
		var foo = {};

	function getDimensions(el, width) {
		if (el.style.display != 'none')
			return width ? el.offsetWidth : el.offsetHeight;
		// reset css properties to get accurate reading
		var old = el.resetCSS({display: '', visibility: 'hidden', position: 'absolute'});
		var dim = (width ? el.clientWidth : el.clientHeight) ;
		el.restoreCSS(old);
		return dim;
	}

	function extend() {
		function ext(dest, src) {
			for(var p in src) dest[p] = src[p];
		}
		if(arguments.length == 2)
			ext(arguments[0], arguments[1])
		else {
			var l = arguments.length, src = arguments[l-1], i = l-1;
			while(i--) { ext(arguments[i], src); }
		}
	}
	
	extend(String.prototype, {
		trim: function() {
			var re = new RegExp(/\s+?/);
		    return this.replace(re, '');
		}
	});

	extend(HTMLElement.prototype, {
	 	resetCSS: function(ext) {
			var old = {};
			for (var p in ext) {
				old[p] = this.style[p];
				this.style[p] = ext[p];
			}
			return old;
		},
		restoreCSS: function(ext) {
			for (var p in ext)
				this.style[p] = ext[p]
		},
		getFullHeight: function() { return getDimensions(this, false); },
		getFullWidth: function() { return getDimensions(this, true); },
		hasClass: function(className) {
	        var re = new RegExp('(?:^|\\s+)'+className+'(?:\\s+|$)');
	        return re.test(this.className);
		},
		removeClass: function(className) {
	        var re = new RegExp('(?:^|\\s+)'+className+'(?:\\s+|$)');
	        this.className = this.className.replace(re, ' ');
			this.className.trim();
		},
		addClass: function(className) {
	        if(!this.hasClass(className))
	            this.className += ' ' + className.trim();	
		},
		css: function() {
			if (arguments.length == 2 && typeof arguments[0] == 'string')
				this.style[arguments[0]] = arguments[1];
			else if (arguments.length == 1) {
				if (typeof arguments[0] == 'object')
					extend(this.style, arguments[0]);
				else if (typeof arguments[0] == 'string')
					return (this.style[arguments[0]] != undefined ? this.style[arguments[0]] : null);
			}
		}
	});
	
	extend((foo.Cookie = {}), {
		create: function(name,value,days) {
			if (days) {
				var date = new Date();
				date.setTime(date.getTime()+(days*24*60*60*1000));
				var expires = "; expires="+date.toGMTString();
			}
			else var expires = "";
			document.cookie = name+"="+value+expires+"; path=/";
		},
		read: function(name) {
			var nameEQ = name + "=";
			var ca = document.cookie.split(';');
			for(var i=0;i < ca.length;i++) {
				var c = ca[i];
				while (c.charAt(0)==' ') c = c.substring(1,c.length);
				if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
			}
			return null;
		},
		erase: function(name) {
			this.create(name,"",-1);
		}
	});

	// utility functions
	extend((foo.Utils = {}), {
		extend: extend,
		hideURLBar: function(offset) {
			if (window.pageYOffset < 2)
				setTimeout('window.scrollTo(0, '+(offset!=undefined?offset:1)+')', 200);
		},
		domQuery: function (query, context) {
			if (!context) context = document;
			return context.querySelector(query)
		},
		domQueryAll: function(query, context) {
			if (!context) context = document;
			return context.querySelectorAll(query)
		}
	});
	
	window.Cookie = foo.Cookie;
	window.Utils = foo.Utils;
	window.$ = foo.Utils.domQuery; 		// watch out if you have a lib like jquery as these two lines
	window.$$ = foo.Utils.domQueryAll;	// will clobber the $, $$
	window.delegate = function(obj,origFunc) {
		var scope = obj;
		var func = origFunc;
		var f = function() {
			return func.apply(scope, arguments);
		};

		return f;
	}
})();


/*** 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 ***/

function main() {
	if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) 
		IS_IPHONE = true;

	if (IS_IPHONE) {
		var f =function() {
			switch(window.orientation) {
				case 0:
		    		document.body.setAttribute("orient", 'portrait');
					break;
				case 90:
				case -90:
					document.body.setAttribute("orient", 'landscape');
			}
			setTimeout('window.scrollTo(0, 1)', 200);
		};
		
		addEventListener('orientationchange', f, false);
		f();
	}

	setupToggleButtons();
	//setupDetailsBox();
	//setupSearchBox();
	setupStreamBox();
	
	window.menus = {};
	window.menus.niches = new PopupMenu('#nichesMenu', false);	
	
}
addEventListener('load', main, false);

function hideURLbar() {
	if (window.pageYOffset < 2)
		setTimeout('window.scrollTo(0, 1)', 200);
}

function submitJoinForm() {
	alert('do somethin');
}

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

/*** SETUP SEARCH BOX ***/
function setupSearchBox() {
	var searchBox = document.getElementById('searchBox');
	if (!searchBox) return;
	var cancelButton = document.getElementById('searchCancelButton');
	var submitButton = document.getElementById('searchSubmitButton');
	var searchForm = document.querySelector('#searchBox form[name=searchBoxForm]');

	// setup cancel button inside the search box
	cancelButton.addEventListener('click', function() {
		searchResetPageOffset();
		searchBox.css('display', 'none');
	},
	false);
	
	submitButton.addEventListener('click', searchDoSubmit, false);
	setupSearchCloseButton();

	function searchDoSubmit(e) {
		searchResetPageOffset();
		searchBox.css('display', 'none');
		searchForm.submit();
	}
}
function searchBoxShow() {
	var searchBox = document.getElementById('searchBox');
	var searchInput = document.querySelector('#searchBox .searchInput');

	searchBox.lastYOffset = window.pageYOffset;
	searchBox.css({'display': 'block', 'color': '#999', 'top': document.getElementById('masthead').getFullHeight() + 'px'});
	searchInput.focus();
	window.scrollTo(0, 1);
}
function searchResetPageOffset() {
	var searchBox = document.getElementById('searchBox');
	window.scrollTo(0, searchBox.lastYOffset);
}

function setupSearchCloseButton() {
 	var close = document.querySelector(".textBoxClose");
	var input = document.querySelector(".searchInput");
	var icon = document.querySelector(".textBoxClose .closeIcon");
	var inputContainer = document.querySelector(".searchInputContainer");
	var emptyMsg = 'search...';
	var firstFocus = true;

	if (IS_IPHONE) {
		inputContainer.removeClass('noClose');
		checkInput();
		close.onmousedown = function(e) { if (e) e.preventDefault(); };
		close.onclick = function(e) {
			input.value = '';
			input.focus();
			icon.css('display', 'none');
			if (e) e.preventDefault();
		};
	}
	if (input.value == '' && firstFocus) {
		input.value = emptyMsg;
		input.css('color', '#999');
	}

	input.onfocus = function() {
		if (firstFocus && input.value == emptyMsg) {
			input.value = '';
			input.css('color', '#000');
			firstFocus = false;
		}
	}
	input.onkeyup = function() { checkInput(); };

	function checkInput() {
		if (input.css('color') == "#999") input.css('color', '#000');

		if (IS_IPHONE) {
			if (input.value == '') {
				if (icon.css('display') != 'none')
					icon.css('display', 'none');
			}
			else {
				if (icon.css('display') == 'none')
					icon.css('display', 'block');
			}
		}
	}
}

/*****************************************************************************
 * STREAMBOX (VIDEO SETTINGS)                                                *
 *****************************************************************************/
function streamBoxShow(msg) {
	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();
				Cookie.create('cookieViewSpeed', this.getAttribute('rel'), 365);
				streamBoxSet(this.getAttribute('rel'));
				setTimeout('streamBoxHideUnderlay()', 100);
				
				// redirect code
				var newViewSpeed = 'viewSpeed=' + this.getAttribute('rel');
				var oldUrl = window.location.href;				
			    var viewSpeed = getQuerystring('viewSpeed');
				var viewSpeed = 'viewSpeed=' + viewSpeed;
				var newUrl = oldUrl.replace(viewSpeed,newViewSpeed);
				window.location=newUrl;	
				
			}
		}
		else {
			el.addEventListener('click', function() {
				Cookie.create('cookieViewSpeed', this.getAttribute('rel'), 365);
				streamBoxSet(this.getAttribute('rel'));
				setTimeout('streamBoxHideUnderlay()', 100);
				
				// redirect code
				var newViewSpeed = 'viewSpeed=' + this.getAttribute('rel');
				var oldUrl = window.location.href;
				var viewSpeed = getQuerystring('viewSpeed');
				var viewSpeed = 'viewSpeed=' + viewSpeed;
				var newUrl = oldUrl.replace(viewSpeed,newViewSpeed);
				window.location.href=newUrl;
				
			}, false);
		}
	}

	// if the cookie is not set for streaming bitrate ask for it
	if (Cookie.read('cookieViewSpeed') != null)
		streamBoxSet(Cookie.read('cookieViewSpeed'));
	else if (streamBox.hasClass('initSetting'))
		streamBoxShow();
}
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 selectSite(link) {
   if (link == '') return;
   document.location = link;
}

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];
}

// Frame Buster
if (top.frames.length!=0){ top.location=self.document.location;}