var flyoutSpeed = 444;
var rotatorSpeed = 333;
var rotatorTimeout = 6666;
var fadeOutSpeed = 'slow';
var fadeInSpeed = 'fast';
var socialAnimationSpeed = 'slow';
var newsItemHeight = 81; //Height of each individual news item in scrolling list (including padding)
var maxNewsItems = 3; //Maximum number of news items to show at any one time in scrolling list
var maxRssItems = 8;
var latestNewsHeadingHeight = 45; //Height of the Latest News heading at the top of scrolling list
var newsListScrollSpeed = 345;
var downloadScrollHeight = 34;
var maxDownloads = 5;
var vidThumbItemWidth = 152;
var maxVidItems = 4;
var maxLogoHeight = 60;
var baseUrl = $("base:first").attr('href');
var reviewScrollAmount=150;
var reviewScrollSpeed=300;
var otherAppsScrollSpeed=300;

//Set default Cufon font
Cufon.set('fontFamily', 'Museo');
//Cufonize
Cufon.replace('h1');
Cufon.replace('.museo');
Cufon.replace('#rotator h2');
Cufon.replace('#rotator p');
Cufon.replace('.main-content h2');
Cufon.replace('.products-main h2');
Cufon.replace('#mem-page-content h2');
Cufon.replace('.product-wrap h3');
Cufon.replace('#rotator h4');
Cufon.replace('.signup-form-wrap h4');
Cufon.replace('.signup-holder h5');
Cufon.replace('.signup-inner h5');
Cufon.replace('.current-apps');
Cufon.replace('#wpcr_button_1');
Cufon.replace('body.page-template-support-php h3');

//Preload any rollovers or dynamically loaded images
var logoutBox = new Image(); logoutBox.src = 'http://www.fingertapps.com/wp-content/themes/fingertapps/images/logout-box.png';

$(document).ready(function() {

	/* recaptcha styling */
	var val=$('input[name=recaptcha_challenge_field]').val();
	$('#recaptcha_widget_div').html($('#recaptcha_image').html()+'<input type="hidden" name="recaptcha_challenge_field" value="'+val+'" /><span style="display:block;width:70px;height:41px; float:right;background:url(/wp-content/themes/fingertapps/images/recaptcha-logo.jpg) no-repeat 0 0;margin-top:10px;"></span><span style="float:left;padding-top:10px;">Type the two words:</span><br /><input style="float:left;width:150px;" name="recaptcha_response_field" id="recaptcha_response_field" type="text" autocorrect="off" autocapitalize="off" autocomplete="off" /><div class="clear"></div>').find('img').css({'width':'240px','height':'45px'});

/*----------Navigation------------*/
//Duplicate navigation text to enable color swapping on cufon rollovers
	$('#nav ul li a').each(function(){
		var navText = $(this).children('.nav-text').html();
		$(this).children('.roll').html(navText);
	});
//Nav text must be Cufonized AFTER they have been duplicated (above) to ensure rollovers are visible
	Cufon.replace('#nav .menu li a');
//Force custom link in footer to open in new tab (for 'Legal')
	$('#footer .menu li.menu-item-type-custom a').attr('target','_blank');
/*-------Home Signup Form---------*/
//Show signup form flyout box when download button is clicked
	$('.beta-download .button-wrap').click(function(){
		$(this).siblings('.flyout-box').show(flyoutSpeed);
	});
//Hide signup form flyout when close button is clicked
	$('.close-box').click(function(){
		$(this).parents('.flyout-box').hide(flyoutSpeed);
	});
//Show signup form when download button is clicked
	$('.download-button.beta-download.home-sign-up-now').click(function(e){
		e.preventDefault();
		$('#home-signup-wrap').fadeIn(fadeInSpeed);
	});
//Enable hover for signup submit button
	$('#mc-embedded-subscribe').mouseenter(function(){
		$(this).addClass('over');
	}).mouseleave(function(){
		$(this).removeClass('over');
	});
//Fade out intro text on signup form so it can be replaced by validation if necessary
	$('#mc-embedded-subscribe').click(function(){
		$('.signup-inner h6').animate({'opacity':0}, 123);
		$('.products-signup-form h5').animate({'opacity':0}, 123);
		$('#mce-error-response').fadeOut(fadeOutSpeed);
		$('#mce-success-response').fadeOut(fadeOutSpeed);
	});
//Remove default text from signup input field
	$('.mc-field-group').mouseenter(function(){ enterSignupForm($(this), fadeOutSpeed);	});
	$('.mc-field-group .mce_inline_error').mouseenter(function(){ enterSignupForm($(this), fadeOutSpeed); });
	$('.mc-field-group').click(function(){ $(this).children('label').addClass('hidden'); });
//Close signup box when close button is clicked
	$('#mc_embed_close').click(function(){
		$('#home-signup-wrap').fadeOut(fadeOutSpeed);
		$('#mce-error-response').fadeOut(fadeOutSpeed);
		$('#mce-success-response').fadeOut(fadeOutSpeed);
		$('.signup-inner h6').animate({'opacity':1}, fadeOutSpeed);
	});
//Activate login box when login button is clicked
	$('.log-in-out').mouseenter(function(e){
		e.preventDefault();
		var loginBox = $('#login-box');
		var closeButton = $('#login-box .close-button');
		if(loginBox.hasClass('open')){
			//loginBox.hide(fadeOutSpeed).removeClass('open');
			//closeButton.css('display','none');
		}else{
			loginBox.addClass('open').show(fadeInSpeed, function(){
				$('.members-button span').css('visibility','hidden');
			});
			closeButton.css('display','block');
		}
	});
	$('.log-in-out').click(function(e){ e.preventDefault(); });
//Close log-in-out box when close button is clicked
	$('#login-box .close-button').click(function(e){
		e.preventDefault();
		$('#login-box').removeClass('open').hide('fast', function(){
			$('.members-button span').css('visibility','visible');
		})
	});
//Login
	$('.alw-btn-login').click(function(){ disableLoginAlerts(); });
	$('#login-pass-input').bind('keydown',function(e){
		if(e.which == 13){ disableLoginAlerts(); }
	});
//Rollover for login submit button
	$('.alw-btn-login').mouseenter(function(){$(this).addClass('roll');}).mouseleave(function(){$(this).removeClass('roll');});
//Remove error message from login box when focusing on input field
	$('#alw_loginForm table input').focus(function(){ $('.msg-login-error').fadeOut('fast'); });
//Remove error message and swap background of login box when forgotten password link is clicked
	/*$('.lost-password-link').click(function(){
		$('.msg-login-error').fadeOut('fast');
		$('#login-box').addClass('logout');
	});*/
/*--------Home Rotator-------------*/
//Activate homepage rotator if on homepgae
	if($('body').hasClass('home')){
		startRotator(rotatorSpeed, rotatorTimeout, $('.rp-main'));
	//Calculate width of rotator pager to centre align
		var rpWidth = $('.rp-main').width() + ($('.rp-edge').width() * 2);
		$('#r-pager').width(rpWidth);
	}


/*-------Home page news/social/feature area------*/
	// Add rollover to news list item
	$('.news-items li').mouseenter(function(){ $(this).addClass('over'); }).mouseleave(function(){ $(this).removeClass('over'); });
		
	// Load Facebook/Twitter feeds
	if ($("#home-social")) {
		// cache elements and data
		var $template = $("#social-post"),
			$tw_list = $("#twitter-social-items"),
			$fb_list = $("#facebook-social-items");
		// wait on window load for performance
		$(window).load(function(){
			$.ajax({
				url: baseUrl+"/json/?feed=tw",
				dataType: "json",
				success: function(tw_data){
					var tweets = [];
					for (var x=0; x<tw_data.length && x<3; x++) {
						var dt=twitter_time_convert(tw_data[x].created_at);
						tweets.push({ "link":'http://twitter.com/#!/Fingertapps/status/'+tw_data[x].id_str, "time":dt, "text":tw_data[x].text, "user":"@"+tw_data[x].user.name });
					}
					for(i in tweets) {
						$tw_list.append('<li><div class="social-content clearfix"><span class="social-blurb">'+tweets[i].text+'</span><span class="social-date">'+$.timeago(tweets[i].time)+': <a href="'+tweets[i].link+'" target="_blank">'+tweets[i].user+'</a></span></div></li>');
					}
				}
			});
			$.ajax({
				url: baseUrl+"/json/?feed=fbf",
				dataType: "json",
				success: function(fbf_data){
					if(fbf_data==null)return;
					var posts = []; 
					for(var x=0; x<fbf_data.entries.length && x<3; x++) {
						if (fbf_data.entries[x].title.replace(/[^A-Za-z0-9]/,"")) {
							posts.push({ "link": fbf_data.entries[x].alternate, "time":fbf_data.entries[x].published, "text":fbf_data.entries[x].title, "user":fbf_data.entries[x].author.name });
						}
					}
					for(var i in posts) {
						$fb_list.append('<li><div class="social-content clearfix"><span class="social-blurb">'+posts[i].text+'</span><span class="social-date">'+$.timeago(posts[i].time)+': <a href="'+posts[i].link+'" target="_blank">'+posts[i].user+'</a></span></div></li>');
					}
				}
			});
		});
	
		// Toggle Facebook and Twitter
		$("#home-social h3").click(function(){
			if($("#home-social h3.facebook").hasClass('active')){ // now activate twitter
				$("#home-social h3.facebook,#home-social div.social-inner.facebook").removeClass('active').addClass('inactive').not('h3').slideUp(socialAnimationSpeed);
				$("#home-social h3.twitter,#home-social div.social-inner.twitter").removeClass('inactive').addClass('active').not('h3').slideDown(socialAnimationSpeed);
			}else{ // otherwise activate facebook
				$("#home-social h3.twitter,#home-social div.social-inner.twitter").removeClass('active').addClass('inactive').not('h3').slideUp(socialAnimationSpeed);
				$("#home-social h3.facebook,#home-social div.social-inner.facebook").removeClass('inactive').addClass('active').not('h3').slideDown(socialAnimationSpeed);
			}
		}).first().click(); // (twitter is default)
	}
	
	function setup_medialinks() {
		// set up youtube video links
		$("a.youtube_link").unbind('click').click(function(e){
			e.preventDefault();
			vimeo_embed = $("<iframe/>",{
				"src":"http://www.youtube.com/embed/"+$(this).attr("href")+"?autoplay=1&amp;rel=0&amp;modestbranding=1&amp;showinfo=0",
				"width":"100%", "height":"100%", "frameborder":"0", "webkitAllowFullScreen":"webkitAllowFullScreen", "allowFullScreen":"allowFullScreen"
			});
			modal_window(vimeo_embed,560,315);
		});
	}
	setup_medialinks();
	
	//-----------Review scrolling--------
	var maxh=$('#product-reviews').css('max-height');
	var scrh=$('#product-reviews').prop('scrollHeight');
	if (scrh < maxh || $('#review-scroll-down').hasClass('disabled')) { // not enough items, just disable scrolling
		$('#review-scroll-down').addClass('disabled');
		$('#review-scroll-down,#review-scroll-up').click(function(e){e.preventDefault();}); // disable the links
		$('#product-reviews').css('max-height', 'none');
	} else { // enable scrolling
		$('#review-scroll-down').click(function(e){
			e.preventDefault();
			scrollReviews(reviewScrollAmount);
		});
		$('#review-scroll-up').click(function(e){
			e.preventDefault();
			scrollReviews(reviewScrollAmount * -1);
		});
	}
	
	//-----------"Other apps you might like" scrolling--------
	$("#product-other-like div.scroll a").click(function(e){
		e.preventDefault();
		var li='#product-other-like div.prod',sc='#product-other-scroll';
		var oa_max_scr=$(li).length * $(li).first().outerWidth();
		var oa_scrl=$(sc).scrollLeft();
		var scra=$(li).first().outerWidth();
		if($(this).hasClass('left'))scra*=-1;
		if(oa_scrl+scra*2>=oa_max_scr){
			$(sc).animate({scrollLeft:0}, otherAppsScrollSpeed);
		}else if(oa_scrl+scra<0){
			$(sc).animate({scrollLeft:oa_max_scr+scra*2}, otherAppsScrollSpeed);
		}else{
			$(sc).animate({scrollLeft:$(sc).scrollLeft()+scra}, otherAppsScrollSpeed);
		}
	});
	
	//-----------Features/System requirements tabs--------
	$('#product-feat-req ul.tabs li a').click(function(e){
		e.preventDefault();
		var li=$(this).parents('li:first');
		$('#product-feat-req ul.tabs li a.active').removeClass('active');
		$(this).addClass('active');
		Cufon.refresh('.museo');
		$('#feat-req-active').html($(li).children('div.content').html());
	}).first().click();
	
	jQuery("a#wpcr_button_1").unbind('click');
	$("a#wpcr_button_1").unbind('click').click(function(e){
		e.preventDefault();
		if ($('#wpcr_respond_2').hasClass('hidden')) {
			$("#wpcr_respond_2").slideDown(300);
			$('#wpcr_respond_2').removeClass('hidden');
			$("#wpcr_button_1").html('Click to hide form');
			$("#wpcr_table_2").find("input:text:visible:first").focus();
			if($('#product-reviews li').length==0)$('#review-scroll').slideDown(300);
		} else {
			$("#wpcr_respond_2").slideUp(300);
			$('#wpcr_respond_2').addClass('hidden');
			$("#wpcr_button_1").html('Click to show form');
			if($('#product-reviews li').length==0)$('#review-scroll').slideUp(300);
		}
		Cufon.replace('#wpcr_button_1');
	});
	wpcr_showform=function(){return;}

	
	//-----------Button hovering--------
	$('.btn-medium').hover(function(){
		$(this).addClass('over');
		Cufon.replace(this);
	}).mouseleave(function(){
		$(this).removeClass('over');
		Cufon.replace(this);
	});
	
	//-----------Slideshow scrolling + clicking--------
	if($("#prod-slide-select").length>0) {
		var ss_scrl=0;
		$("#prod-slide-select div.scroll a").click(function(e){
			e.preventDefault();
			var li='#product-slide-cont div.slide',sc='#product-slide-scroll';
			var oa_max_scr=$(li).length * $(li).first().outerWidth();
			var oa_scrl=ss_scrl;
			var scra=$(li).first().outerWidth();
			if($(this).hasClass('left'))scra*=-1;
			if(oa_scrl+scra*4>=oa_max_scr){
				ss_scrl=0;
			}else if(oa_scrl+scra<0){
				ss_scrl=oa_max_scr+scra*4;
			}else{
				ss_scrl+=scra;
			}
			$(sc).stop().animate({scrollLeft:ss_scrl}, otherAppsScrollSpeed);
		});
		$("#product-slide-cont div.slide a").click(function(e){
			e.preventDefault();
			var v=$(this).attr('data-video');
			if(v) {
				$("#prod-slide-active").html('<a href="'+v+'" class="youtube_link"><span class="play-button"></span><img src="'+$(this).attr('href')+'" alt="'+$(this).attr('alt')+'" /></a>');
				setup_medialinks();
			} else {
				$("#prod-slide-active").html('<img src="'+$(this).attr('href')+'" alt="'+$(this).attr('alt')+'" />');
			}
			$('#product-slide-cont div.slide a.active').removeClass('active');
			$("#prod-slide-caption").html($(this).attr('data-caption'));
			$(this).addClass('active');
		}).first().click();
	}
	
	// buy product
	$('a#product-buy').click(function(e){
		e.preventDefault();
		$('#prod-paypal_code form').submit();
	});
	
	$('ul#news h3 a,ul#news .permalink').hover(function(){
		$(this).parents('li').addClass('over');
		Cufon.refresh();
	}).mouseleave(function(){
		$(this).parents('li').removeClass('over');
		Cufon.refresh();
	});
	
/*-----------------Members area--------------------*/
//Only run this code if on the members page
	if($('body').hasClass('page-template-members-php')){
	//Insert user logo into header and vertically align
		var userLogo = $('.user-logo-holder').html();
		var logoHeight = $('.user-logo-holder img').height();
		if(logoHeight < maxLogoHeight){
			var topPos = parseInt((maxLogoHeight - logoHeight) / 1.5);
		}
		$('.m-logo').html(userLogo);
		$('.m-logo img').css('top',topPos);
	//Add class on alternating rows for news list items
		$('#news-items li:odd').addClass('even');
	//Add rollover to news list item
		$('#news-items li').mouseenter(function(){ $(this).addClass('over'); }).mouseleave(function(){ $(this).removeClass('over'); });
	//Open fingerbox when news link is clicked
		$('#mem-news .news-link').click(function(e){
			e.preventDefault();
		//Get article content
			var articleContent = $(this).siblings('.hidden-article').html();
		//Add article content to popup box
			$('.fingerbox .article-holder').html(articleContent);
		//Position and show popup box
			var thisParentPos = $(this).parent('li').position();
			var thisParentTop = parseInt(thisParentPos.top + latestNewsHeadingHeight);
			var newsListTop = parseInt($('#news-items').css('top'));
			$('.fingerbox-wrap').css('top',thisParentTop + newsListTop).css('opacity',0).css('display','block').animate({'opacity':1},'fast');
		});
	//Close fingerbox when close button is clicked
		$('.fingerbox .close-button').click(function(e){
			e.preventDefault();
			var thisFingerbox = $(this).parents('.fingerbox-wrap');
			thisFingerbox.hide('fast');
		});
	//Count number of news items so we know whether to disable scrolling
		var listCounter = 0;
		$('#news-items').children('li').each(function(){ listCounter++; });
	//Disable scrolling and resize news list if there are not enough items
		if(listCounter <= maxNewsItems){
			$('#mem-news-controls .scroll-down').addClass('disabled');
			$('#mem-news .inner').animate({'height':listCounter * newsItemHeight}, 'slow');
		}else{
			$('#mem-news .inner').height(newsItemHeight * maxNewsItems);
		}
	//Enable scrolling for news items
		$('#mem-news-controls .scroll').click(function(e){
			e.preventDefault();
		//Close popup box if it's open
			$('.fingerbox-wrap').hide('fast');
			var theButton = $(this);
		//Activate scrolling function if clicked button is not disabled
			if(!theButton.hasClass('disabled')){
				var newsList = $('#news-items');
				scrollNewsList(newsList, theButton, newsItemHeight, newsListScrollSpeed, maxNewsItems, listCounter);
			}
		});
	//-----------RSS stuff---------------
	//Add classes to rss list items
		$('.rss-list li:odd').addClass('even');
	//Count number of RSS items and wrap content in div
		var rssCounter = 0;
		$('.rss-list').children('li').each(function(){
			rssCounter++;
			var rssContent = $(this).html();
		//Replace any break tags
			/*rssContent = rssContent.replace('<br>',' - ');
			rssContent = rssContent.replace('<br />',' - ');*/
			var newRssContent = '<div class="rss-content clearfix"><span class="news-button"></span>'+rssContent+'</div>';
			$(this).html(newRssContent);
		});
	//Set height of RSS holding div
		$('#rss-news .inner').height(newsItemHeight * maxRssItems);
	//Enable rollover
		$('.rss-list li').mouseenter(function(){ $(this).addClass('over'); }).mouseleave(function(){ $(this).removeClass('over'); });
	//Enable scrolling for rss items
		$('#rss-news-controls .scroll').click(function(e){
			e.preventDefault();
		//Close popup box if it's open
			$('.fingerbox-wrap').hide('fast');
			var theButton = $(this);
		//Activate scrolling function if clicked button is not disabled
			if(!theButton.hasClass('disabled')){
				var rssList = $('.rss-list');
				scrollNewsList(rssList, theButton, newsItemHeight, newsListScrollSpeed, maxRssItems, rssCounter);
			}
		});
	//Count number of video thumbs so we know whether to disable scrolling
		var vidListCounter = 0;
		$('.thumb-list').children('li').each(function(){ vidListCounter++; });
	//Set width of list
		var vidListWidth = vidListCounter * vidThumbItemWidth;
		$('.thumb-list').width(vidListWidth);
	//Enable scrolling for video items
		$('#mem-vid-buttons .scroll').click(function(e){
			e.preventDefault();
			var theButton = $(this);
			if(!theButton.hasClass('active')){
				theButton.addClass('active');
			//Activate scrolling function if clicked button is not disabled
				if(!theButton.hasClass('disabled')){
					scrollVidThumbList(theButton, vidThumbItemWidth, newsListScrollSpeed, maxVidItems, vidListCounter);
				}
			}else{
				return false;	
			}
		//Remove active class after half a second or so
			setTimeout('$("#mem-vid-buttons .scroll").removeClass("active")', 500);
		});
	//When user clicks on a thumb in the Latest Videos section
		$('ul.thumb-list li a.thumb-link').click(function(e){
			e.preventDefault();
		//Capture hidden content from clicked thumb
			var hiddenContent = $(this).siblings('.hidden-content');
			var newContent = hiddenContent.children('.h-content').html();
			var newTitle = hiddenContent.children('.h-title').html();
			var newDate = hiddenContent.children('.h-date').html();
		//Hide current video content in main area
			$('#mem-vid-main-inner').fadeOut('fast');
			$('#mem-vid-info span').fadeOut('fast');
		//Replace with new content
			$('#mem-vid-main-inner').html(newContent);
			$('.m-title').html(newTitle);
			$('.m-date').html(newDate);
		//Show new video content
			$('#mem-vid-main-inner').fadeIn('fast');
			$('#mem-vid-info span').fadeIn('fast');
		});
	//Enable scrolling for downloads
		$('.d-scroller .scroll').click(function(e){
			e.preventDefault();
			var theButton = $(this);
			if(!theButton.hasClass('active')){
				theButton.addClass('active');
			//Activate scrolling function if clicked button is not disabled
				if(!theButton.hasClass('disabled')){
					scrollDownloadList(theButton, downloadScrollHeight, newsListScrollSpeed, maxDownloads, vidListCounter);
				}
			}else{
				return false;	
			}
		//Remove active class after half a second or so
			setTimeout('$(".d-scroller .scroll").removeClass("active")', 500);
		});
	//Replace href of download item with hidden link
		$('ul.download-list li .pdf-link').each(function(){
			if($(this).html() != ''){
				var pdfLink = $(this).children('a').attr('href');
				$(this).siblings('a').attr('href', pdfLink);
			}else{
				$(this).siblings('a').attr('href', 'javascript:alert("Sorry, there is no file attached to this link")');
			}
		});
	//Enable tabbing for downloads
		$('.d-tit-link').click(function(e){
			e.preventDefault();
			if(!$(this).parent('li').hasClass('active')){
			//Hide the old list and show the new
				var clickedList = $(this).siblings('.d-list-wrap').children('ul.download-list');
				var oldList = $('ul#download-tabs li.active .d-list-wrap ul.download-list');
				oldList.hide('fast');
				clickedList.show('fast');
			//Remove all active classes from tab list
				$('ul#download-tabs li').removeClass('active');
			//Apply active class to clicked tab
				$(this).parent('li').addClass('active');
			}
		});
		setVidTopValue();
	} //end if($('body').hasClass('page-template-members-php')){
/*--------------------------------*/
//Add clearfix to navigation menus
	$('#menu-main').addClass('clearfix');
}); //end $(document).ready(function() {

//Enable cycle plugin to transition in correct direction when prev or next buttons are clicked
$.fn.cycle.transitions.scrollHorz = function($cont, $slides, opts) {
	$cont.css('overflow','hidden').width();
	opts.before.push(function(curr, next, opts, fwd) {
		//fwd = !fwd;  //  <--  add this line!!
		$.fn.cycle.commonReset(curr,next,opts);
		opts.cssBefore.left = fwd ? (next.cycleW-1) : (1-next.cycleW);
		opts.animOut.left = fwd ? -curr.cycleW : curr.cycleW;
	});
	opts.cssFirst = { left: 0 };
	opts.cssBefore= { top: 0 };
	opts.animIn   = { left: 0 };
	opts.animOut  = { top: 0 };
};

function disableLoginAlerts(){
//Hide validation message if it's there already
	$('.msg-login-error').hide('fast');
//Disable alerts to stop stupid ajax login plugin from popping up a pointless box with invalid content
	window.alert = function() {
		$('.msg-login-error').show('fast');
	}	
}
function setVidTopValue(){
	var vidHeight = $('#mem-vid-main-inner').height();
	var maxHeight = $('#mem-video').height();
	var topValue = ((maxHeight - vidHeight) / 2) - 27;
	$('#mem-vid-main-inner').css('top', topValue);
}

function scrollDownloadList(sButton, downloadScrollHeight, newsListScrollSpeed, maxDownloads, listCounter){
	//var dList = $('.download-list');
	var dList = sButton.parents('.d-scroller').siblings('.d-list-wrap').children('.download-list');
//Get current position of list relative to parent
	var thePos = dList.position();
	var listPos = thePos.top;
//Determine whether there is an overflow
	var dAreaHeight = downloadScrollHeight * 5;
	var dTotalHeight = dList.height();
	var dOverflow = dTotalHeight - dAreaHeight;
//Determine whether to scroll up or down and when to stop
	if(sButton.hasClass('scroll-down')){
	//Move list if there are more items below
		if((listPos - dAreaHeight) > (dTotalHeight * -1)){
			var newTopPos = listPos - dAreaHeight;
			dList.animate({'top':newTopPos}, newsListScrollSpeed);
		}else{
			sButton.addClass('disabled');
		}
	}else{
	//Move list if it's not at the top
		var newTopPos = listPos + dAreaHeight;
		if(listPos != 0){
			dList.animate({'top':newTopPos}, newsListScrollSpeed);
		}else{
			sButton.addClass('disabled');
		}
	}
//Remove disable class from other button
	sButton.siblings('.scroll').removeClass('disabled');
}

function scrollVidThumbList(sButton, vidThumbItemWidth, newsListScrollSpeed, maxVidItems, listCounter){
	var thumbList = $('.thumb-list');
//Get width of list
	var vidListWidth = thumbList.width();
//Get current position of list relative to parent
	var thePos = thumbList.position();
	var listPos = thePos.left;
//Calculate the amount of overflow
	var theOffset = vidThumbItemWidth * -(listCounter - maxVidItems);
//Determine whether to scroll up or down and when to stop
	if(sButton.hasClass('scroll-right')){
	//Move list if there are more items below
		var newListPos = listPos - vidThumbItemWidth;
		newListPos = parseInt(newListPos);
		if(listPos > theOffset){
			thumbList.animate({'left':newListPos}, newsListScrollSpeed);
		}else{
			sButton.addClass('disabled');
		}
	}else{
	//Move list if it's not at the beginning
		var newListPos = listPos + vidThumbItemWidth;
		newListPos = parseInt(newListPos);
		if(listPos != 0){
			thumbList.animate({'left':newListPos}, newsListScrollSpeed);
		}else{
			sButton.addClass('disabled');
		}
	}
//Remove disable class from other button
	sButton.siblings('.scroll').removeClass('disabled');
}


function scrollNewsList(newsList, sButton, newsItemHeight, newsListScrollSpeed, maxNewsItems, listCounter){
	sButton.addClass('disabled');
//Get current position of list relative to parent
	var thePos = newsList.position();
	var listPos = thePos.top;
//Calculate the amount of overflow
	var theOffset = newsItemHeight * -(listCounter - maxNewsItems);
	var ua = navigator.userAgent;
    var MSIEOffset = ua.indexOf("MSIE 8");
    if (MSIEOffset == -1) {
        var isIE8 = 'no';
    } else {
        var isIE8 = 'yes';
    }
//Determine whether to scroll up or down and when to stop
	if(sButton.hasClass('scroll-down')){
	//Move list if there are more items below
		var newListPos = listPos - newsItemHeight;
	//Fix some really weird stuff happening in IE8
		if((navigator.appName == 'Microsoft Internet Explorer') && (isIE8 == 'yes')){
			if(newListPos < -243){ newListPos = newListPos - 1; }
		}
		if(listPos > theOffset + (newsItemHeight/2)){
			newsList.animate({'top':newListPos}, newsListScrollSpeed, function(){
				sButton.removeClass('disabled');
			});
		}else{
			sButton.addClass('disabled');
		}
	}else{
	//Move list if it's not at the top
		var newListPos = listPos + newsItemHeight;
	//Fix some really weird stuff happening in IE8
		if((navigator.appName == 'Microsoft Internet Explorer') && (isIE8 == 'yes')){
			if(newListPos < -243){ newListPos = newListPos - 1; }
		}
		if((listPos != 0) && (listPos < 0)){
			newsList.animate({'top':newListPos}, newsListScrollSpeed, function(){
				sButton.removeClass('disabled');
			});
		}else{
			sButton.addClass('disabled');
		}
	}
//Remove disable class from other button
	sButton.siblings('.scroll').removeClass('disabled');
}
	
function startRotator(rotatorSpeed, rotatorTimeout, rpMain){
//Replace title/alt attributes of images in rotator with main text
	$('.r-panel').each(function(){
		var imageText = $(this).children('.r-text').children('h3').html();
		if(imageText == ''){ imageText = 'Sweet apps for all';}
		$(this).children('.r-images').children('img').attr('title', imageText);
		$(this).children('.r-images').children('img').attr('alt', imageText);
	});
	$('#rotator').cycle({
		fx: 'scrollHorz',
		speed: rotatorSpeed,
		pager: rpMain,
		activePagerClass: 'active',
		prev: '.r-prev',
		next: '.r-next',
		prevNextEvent: 'click.cycle',
		pagerEvent: 'click.cycle',
		timeout: rotatorTimeout,
		after: function(){
			$('div.r-panel').each(function(){
				if($(this).css('display')=='block'){
					$('.signup-holder').html($(this).find('div.r-static-text').html());
					return;
				}
			});
		}
	});	
}
function fadeOutContent(theContent, fadeOutSpeed){
	theContent.fadeOut(fadeOutSpeed, function(){ theContent.addClass('hidden'); });
}
function enterSignupForm(theForm, fadeOutSpeed){
	var thisLabel = theForm.children('label');
	var thisInput = theForm.children('input');
	fadeOutContent(thisLabel, fadeOutSpeed);
	thisInput.focus();
}
function scrollReviews(amount){
	var scrh=$('#product-reviews').prop('scrollHeight');
	var cscr=$('#product-reviews').prop('scrollTop');
	if (amount >= 0) { // going down
		$('#review-scroll-up').removeClass('disabled');
		if(cscr+amount>=scrh-cscr){
			$("#product-reviews").animate({ scrollTop: scrh }, reviewScrollSpeed);
			$('#review-scroll-down').addClass('disabled');
		} else {
			$("#product-reviews").animate({ scrollTop: cscr+amount }, reviewScrollSpeed);
			$('#review-scroll-down').removeClass('disabled');
		}
	} else { // going up
		$('#review-scroll-down').removeClass('disabled');
		if(cscr+amount<=0){
			$("#product-reviews").animate({ scrollTop: 0 }, reviewScrollSpeed);
			$('#review-scroll-up').addClass('disabled');
		} else {
			$("#product-reviews").animate({ scrollTop: cscr+amount }, reviewScrollSpeed);
			$('#review-scroll-up').removeClass('disabled');
		}
	}
}

var modal_window = function() {
	var modal_overlay = $("<div/>",{"class":"modal_overlay"}),
		modal_outer = $("<div/>",{"class":"modal_outer"}),
		modal_inner = $("<div/>",{"class":"modal_inner"}),
		modal_close = $("<div/>",{"class":"modal_close"})/*.text("Close")*/,
		close = function(){
			modal_overlay
				.animate({"opacity":0},fadeOutSpeed,function(){
					modal_overlay.css({"display":"","filter":"","-ms-filter":""});
				});
			modal_outer
				.animate({"opacity":0},fadeOutSpeed,function(){
					modal_outer.css({"display":"","filter":"","-ms-filter":""});
					modal_inner.empty();
				});
		};
	modal_inner.appendTo(modal_outer);
	modal_close.appendTo(modal_outer);
	$(document).ready(function(){
		modal_overlay.appendTo(document.body);
		modal_outer.appendTo(document.body);
	});
	modal_overlay.click(close);
	modal_close.click(close)
	return function (md_obj,md_width,md_height) {
		modal_overlay
			.css({"opacity":0, "display":"block"})
			.animate({"opacity":0.9},fadeInSpeed);
		modal_outer
			.width(md_width)
			.height(md_height)
			.css({"opacity":0, "display":"block"})
			.animate({"opacity":1},fadeInSpeed,function(){
				modal_outer.css({"filter":"","-ms-filter":""});
				modal_inner.append(md_obj);
			});
	};
}();

function twitter_time_convert(tw_time){ // returns iso 8601: 2011-10-31T22:37:18+00:00
	var m=new Array('','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
	tw_time=tw_time.match(/([A-z]{3}) ([A-z]{3}) ([0-9]+) ([0-9]+):([0-9]+):([0-9]+) \+([0-9]{2})([0-9]{2}) ([0-9]{4})/);
	for(var i in m){if(m[i]==tw_time[2]){tw_time[2]=i;}}
	for(var i=2;i<8;i++){var n=parseInt(tw_time[i]);if(n<10){tw_time[i]='0'+n;}}
	var fb_time = tw_time[9]+'-'+tw_time[2]+'-'+tw_time[3]+'T'+tw_time[4]+':'+tw_time[5]+':'+tw_time[6]+'+'+tw_time[7]+':'+tw_time[8];
	return fb_time;
}

