var streamBoxPreload = [
	"images/popup-top.png",
	"images/popup-middle.png",
	"images/popup-bottom.png",
	"images/popup-button.png",
	"images/popup-button-selected.png",
	"images/popup-check.png"
];
var searchBoxPreload = [
	"images/butn-bg-main-nav.png",
	"images/glass-gradient-overlay.png"
];
var IS_IPHONE = false;
var IV_NAV_OFFSET = 92;
var IV_IPHONE_NAV_OFFSET = 63;
var SCREEN_WIDTH = 320;
var SCREEN_HEIGHT = 480;

jQuery(document).ready(function() {
	if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) 
		IS_IPHONE = true;
	
	window.onorientationchange = function() {
		switch(window.orientation) {
			case 0:
	    		document.body.setAttribute("orient", 'portrait');
				break;
			case 90:
			case -90:
				document.body.setAttribute("orient", 'landscape');
		}
	}
	if (IS_IPHONE)
		window.onorientationchange();
		
	// if the homeMainNav exist we're on the home page
	if ($('.homeMainNav').length)
		setupHomeMainNav();
		
	// if the rating box exists on this page handle it
	if ($('#userRatingBox').length)
		setupRatingBox();
		
	// if the image viewer exists on this page handle it
	if ($('#imageViewer').length)
		setupImageViewer();
	
	// if a search button on the page exists set up search box
	if ($('.doSearchButton').length)
		setupSearchBox();
		
	// if a search box exists on the page setit up
	if ($('#streamBox').length)
		setupStreamBox();
		
	// if the class selectMembershipRadios exists we're on the signup page
	if ($('.selectMembershipRadio').length)
		setupSelectMembership();
	
//	if (IS_IPHONE)
		hideURLbar();
});

/*** RATING BOX STUFF ***/
function setupRatingBox() {
	for (var i=0; i<=4; i++) {
		$('#userRatingBox .stars').append(
			'<a rel="'+ (i+1) + '" class="emptyStar" href="javascript:void(0)" onclick="javascript:updateRating(this.rel)"></a>'
		);
	}

	$('#userRatingBox img').each(function() {
		var el = $(this)[0];
		el.ontouchstart = el.ontouchmove = el.ontouchend = function(e) { e.preventDefault(); }
	});

}

function updateRating(num) {
	setRatingBoxStars(num);
	if (window.ratingCallback !== undefined)
		window.ratingCallback(num);
}

function setRatingBoxStars(num) {
	$('#userRatingBox .stars a').each(function (i){
		if (i <= (num-1)) {
			if ($(this).hasClass('emptyStar'))
				$(this).removeClass('emptyStar');
			if (!$(this).hasClass('fullStar'))
				$(this).addClass('fullStar');
		}
		else {
			if ($(this).hasClass('fullStar'))
				$(this).removeClass('fullStar');
			if (!$(this).hasClass('emptyStar'))
				$(this).addClass('emptyStar');
		}
	});
}


/***  IMAGE VIEWER STUFF ***/
function setupImageViewer() {
	window.initImageViewer = true;
	if (IS_IPHONE) {
		addEventListener("load", function() {
			setTimeout('imageViewerHideURLbar(); window.initImageViewer = false', 0);
	    }, false);
	}
	
	$('body').css('background-color', $('#imageViewer').css('background-color'));
	$('#imageViewer .next').click(imageViewerNext);
	$('#imageViewer .prev').click(imageViewerPrev);

	$('#theImage').html('<img src="" />');
	$('#theImage img')[0].opacity = 0;
	$('#theImage img')[0].onload = function() { imageViewerHandleSizing(); };
	window.loadPrevImg = new Image();
	window.loadNextImg = new Image();
	
	window.loadImageViewer = function(images, start) {
		imageViewerArray = images;
		imageViewerCurrent = start;
		imageViewerLast = start;
		imageViewerLoadImage(window.imageViewerCurrent);
	}
	window.onOrientationChangePassthrough  = window.onorientationchange;
	window.onorientationchange = function() {
		imageViewerHandleSizing();
		if (window.onOrientationChangePassthrough !== undefined)
			window.onOrientationChangePassthrough();
	}
}

function imageViewerHideURLbar() {
	if (window.pageYOffset != IV_NAV_OFFSET)
		setTimeout('window.scrollTo(0, IV_NAV_OFFSET)', 100);
}

function imageViewerHandleSizing(doScroll) {
	imageViewerHideLoading();
	if (IS_IPHONE) {
		var imageOrient = ($('#theImage img').width() > $('#theImage img').height()) ? 'landscape' : 'portrait';
		
		// iphone in portrait mode
		if (window.orientation == 0) {
			switch (imageOrient) {
				case 'portrait':
					$('#theImage img').css({width: '100%', height: 'auto', marginTop: '0' });
					break;
				case 'landscape':
					$('#theImage img').css({width: '100%', height: 'auto'});
					$('#theImage img').css(
						'marginTop',
						Math.ceil(((SCREEN_HEIGHT-IV_IPHONE_NAV_OFFSET)/2) - ($('#theImage img').height()/2)) + 'px'
					);
			}
		}
		// iphone in landscape mode
		else {
			switch (imageOrient) {
				case 'portrait':
					$('#theImage img').css({width: 'auto', height: '290px', marginTop: '0', margin: '0 auto' });
					break;
				case 'landscape':
					$('#theImage img').css({width: '100%', height: 'auto', marginTop: '0' });
			}
		}

		if (!window.initImageViewer)
			imageViewerHideURLbar();
	}
}

function imageViewerShowLoading() {	$('#imageViewer .loading').css('display', 'block'); }
function imageViewerHideLoading() {	$('#imageViewer .loading').css('display', 'none'); }

function imageViewerLoadImage(num) {
	imageViewerShowLoading();
	if (window.scrollYoffset)
	if (num > 1)
		window.loadPrevImg.src = imageViewerArray[num-1];
   	if (num < imageViewerArray-2)
		window.loadNextImg.src = imageViewerArray[num+1]
	$('#theImage img').attr('src', window.imageViewerArray[num]);
}

function imageViewerNext() {
	if (imageViewerCurrent < imageViewerArray.length-1) {
		imageViewerCurrent++;
		imageViewerLoadImage(imageViewerCurrent);
	}
}

function imageViewerPrev() {
	if (imageViewerCurrent > 0) {
		imageViewerCurrent--;
		imageViewerLoadImage(imageViewerCurrent);
	}
}

/*** SETUP SEARCH BOX ***/
function setupSearchBox() {
	var imgs = new Array()
	for (var i=0, l=searchBoxPreload.length;i<l;i++) {
		imgs.push(new Image());
		imgs[i].src = searchBoxPreload[i];
	}

	// setup cancel button inside the search box
	$('#searchBox .searchCancelButton').click(function() {
		searchCleanupHandlers();
		$('#searchBox .searchInput').val('');
		$('#searchBox').css('display', 'none');
	});
	
	// hook the search functionality up
	$('#searchBox .searchInput').keypress(function(e) {
		if (e.which == 13) {
			$('#searchBox').css('display', 'none');
			$('#searchBox form[name=searchBoxForm]')[0].submit();
		}
	});
	
	// attach to the doSearchButton(s) on the page 
	$('.doSearchButton').click(function(){
		window.scrollTo(0, 51);
		$('#searchBox').css('display', 'block');
		var el = $('#searchBox .searchInput');
		el.css('color', '#999').val('search...').focus();
		el[0].cleanup = true;
		el.click(searchClearContent);
		el.keydown(searchClearContent);

	});
}

function searchClearContent() {
	searchCleanupHandlers();
	var el = $('#searchBox .searchInput');
	el.val('');
	el.css('color', '#000');
}
function searchCleanupHandlers() {
	var el = $('#searchBox .searchInput');
	if (el[0].cleanup) {
		el[0].cleanup = false;
		el.unbind('click', searchClearContent);
		el.unbind('keydown', searchClearContent);
	}
}

/*** HOME MAIN NAV ***/
function setupHomeMainNav() {
	$('.navSections div a').each(function() {
		this.url = this.href;
		$(this).attr('href', 'javascript:void(0)');
		$(this).click(function() {
			$('span', $(this).parent()).addClass('selected');
			setTimeout("window.location='"+this.url+"'", 100);
		});
	});
}

/*** STREAM BOX ***/
function setupStreamBox() {
	var underlayHTML = "<div style='display: none' id='streamBoxUnderlay'></div";
	var imgs = new Array()
	for (var i=0, l=streamBoxPreload.length;i<l;i++) {
		imgs.push(new Image());
		imgs[i].src = streamBoxPreload[i];
	}
	
	$('body').append(underlayHTML);
	if (IS_IPHONE) {
		$('#streamBoxUnderlay')[0].ontouchstart = function(e) {
			e.preventDefault();
			streamBoxHideUnderlay();
		}
	}
	else
		$('#streamBoxUnderlay').click(streamBoxHideUnderlay);
	
	$('#streamBox .streamOptions a').each(function(i) {
		if (IS_IPHONE) {
			this.ontouchstart = function(e) {
				e.preventDefault();
				streamBoxSet($(this).attr('rel'));
			}
			this.ontouchend = function(e) {
				e.preventDefault();
				//setCookie('bitrate', type, 365);
				streamBoxSet($(this).attr('rel'));
				setTimeout('streamBoxHideUnderlay()', 100);
			}
		}
		else {
			$(this).click(function() {
				//setCookie('bitrate', type, 365);
				streamBoxSet($(this).attr('rel'));
				setTimeout('streamBoxHideUnderlay()', 100);

			});
		}
	});
	
	$('.linkToStreaming').click(function() {
		if ($('#streamBox').css('display') == 'none') {
			$('#streamBoxUnderlay').css('display', 'block');
			$('#streamBoxUnderlay').css('height', '' + (window.innerHeight + window.pageYOffset) + 'px');
			$('#streamBox').css('top', window.pageYOffset + (window.innerHeight/2 - $('#streamBox').height()/2));
			$('#streamBox').css('display', 'block');
		}
		else
			$('#streamBox').css('display', 'none');
	});
}
function streamBoxHideUnderlay() {
	$('#streamBoxUnderlay').css('display', 'none');
	$('#streamBox').css('display', 'none');
}
function streamBoxSet(type) {
	$('#streamBox .streamOptions a').each(function() {
		if ($(this).attr('rel') == type)
			$(this).addClass('selected');
		else {
			if ($(this).hasClass('selected'))
				$(this).removeClass('selected');
		}
	});
}	

function setupSelectMembership() {
	transmogrifyRadioControls();
	$('.customRadioBox a').click(function() {
		var rel = $(this).attr('rel');
		$('input[rel='+rel+'].selectMembershipRadio ').attr('checked', true);
		$('.customRadioBox a').each(function(i) {
			if ($(this).attr('rel') == rel)
				$('span', this).addClass('checked');
			else {
				if ($('span', this).hasClass('checked'))
					$('span', this).removeClass('checked');
			}
		});
		
	});
}

function transmogrifyRadioControls() {
	var inject = '';

	inject = "<ul class='customRadioBox'>";
	$('.selectMembershipRadio').each(function(i) {
		$(this).css('display', 'none');
		$(this).attr('rel', i);
		inject += '<li><a href="javascript:void(0)");" rel="'+i+'">' +
			'<span' + ($(this).attr('checked')  ? ' class="checked"' : '') + '></span>' +
			$(this).attr('title') + '</a></li>';
	});
	inject += '</ul>';
	$('.selectMembershipRadio').parent().append(inject);
}

function hideURLbar() {
	/*
		homepage: scroll to the top of the page
		every other page except the image viewer: scroll underneath the masthead
		image viewer: scroll under the masthead and nav
	*/
	if ($('.homeMainNav').length || $('.support').length) {
		if (window.pageYOffset == 0)
			addEventListener("load", function() { setTimeout('window.scrollTo(0, 1)', 200); }, false);
		return;
	}
	else if ($('#imageViewer').length)
		return;

	if (window.pageYOffset == 0)
		addEventListener("load", function() { setTimeout('window.scrollTo(0, 51)', 200); }, false);
}
