if(!"console" in window){window.console={log:function(){}}}

// misc formatting
jQuery(function($) {
	$('form input[type=text]').focus(function() {
		if ($(this).attr('defaultValue') == $(this).val()) {
			$(this).val('');
		}
	});

	$('p:has(a.more)').addClass('hasMore');
	
	$('img[align=right]').addClass('alignright');
	$('img[align=left]').addClass('alignleft');

	$('ul').find('> li:last').addClass('last');

	$('#content hr').wrap('<div class="hr"></div>');

	var hostName = window.location.hostname;
	$('a').each(function(i, a) {
		var href = $(a).attr('href')
		if (href && (href.indexOf(hostName) < 0) && (href.indexOf('http') == 0) && !$(a).attr('target')) {
			$(a).attr('target', '_blank')
		}
	});
	
	//image rollovers
	$('img[hover]').each(function(i,img) {
		var hover = new Image();
		hover.src = $(img).attr('hover');
		var orig_src = $(img).attr('src');
		$(img).hover(function() {
			$(img).attr('src', hover.src);
		}, function() {
			$(img).attr('src', orig_src);
		});
	});
	if (typeof isIE7 != 'undefined') {
		$('#subnav ul li:not(.last)').append('<span class="s"> &nbsp; / &nbsp;</span>')
	}
	
});

// drop down menu handlers
jQuery(function($) {
	var dropdown = '.info:not(.pinned)';
	$('#mainnav > li').hover(
		function() { //over
			
			$(this).addClass('over').find(dropdown).show().closest('ul').find('.info.pinned').hide();
		},
		function() { //out
			$(this).removeClass('over').find(dropdown).hide().closest('ul').find('.info.pinned').show();
		}
	).addClass('initialized');
	$('#alt > li > a').click(function() {
		$(this).closest('li').toggleClass('over').closest('ul').find(dropdown).toggle()
		return false;
	});
});

// expandable sections
jQuery(function($) {
	var more = $('<li class="show-more">...See More</li>');
	more.click(function() {
		$(this).hide('fast').siblings().slideDown('fast');
		
	});
	$('#sidebar .expandable').each(function(i, obj) {
		$(obj).click(function() {
			$(this).toggleClass('opened')
			$(this).next('ul').slideToggle()
			if ($(this).hasClass('opened')) {
				$(this).find('span.status').text('(-)')
			} else {
				$(this).find('span.status').text('(+)')
			}
			return false;
		});
		var list = $(obj).next('ul');
		if ($(obj).hasClass('opened') || (list.find('li.selected, li.current-cat, li.current-menu-item').length > 0)) {
			$(obj).append(' <span class="status">(-)</span>')
			$(obj).addClass('opened')
		} else {
			$(obj).append(' <span class="status">(+)</span>')
			list.hide();
		}
		var listAll = $(obj).hasClass('list-all');
		if (!listAll) {
			var elems = list.find('> li')
			if (elems.length > 10 && elems.filter(':not(.current-cat').length <= 0) {
				elems.eq(8).nextAll().hide();
				list.append(more);
			}
		}
		
	});
	
	$('dl.expandable dt').click(function() {
		$(this).next('dd').slideToggle();
		return false;
	});
});

// banner images 
jQuery(function($) {
	var banner = $('#banner');
	var current = null;
	var currentPos = 0;
	var initialized = false;
	var timer = null;
	var movedOpacity = 0.99;
	banner.data('initialized', false);
	
	$(bannerImages).each(function(i, src) {
		var img = new Image();
		$(img).appendTo(banner).load(function () {
			startBanner(i);
		}).error(function () {
		    
		}).attr('src', BASE + src);
		
	});

	var timer = setTimeout(function() {
		//startBanner(0);
	}, 2000);
	$(window).resize(setBannerPosition);
	
	$('#banner-next').click(function() {
		if (currentPos < (bannerImages.length-1) ) {
			showBanner(currentPos + 1)
		} else {
			showBanner(0);
		}
		return false;
	});
	$('#banner-prev').click(function() {
		if (currentPos > 0) {
			showBanner(currentPos - 1)
		} else {
			showBanner(bannerImages.length-1)
		}
		return false;
	});
	$('#banner,#header').bind('touchstart', function(e) {
	}).bind('touchend', function() {
		if (timer) clearTimeout(timer);
		timer = setTimeout(nextBanner, 50);
		return false;
	});
	
	function nextBanner() {
		if (currentPos > 0) {
			showBanner(currentPos - 1)
		} else {
			showBanner(bannerImages.length-1)
		}
	}
	function startBanner(i) {
		if (!banner.data('initialized')) {
			banner.data('initialized', true);
			clearTimeout(timer);
			timer = null
			showBanner(i)
			setBannerPosition();
		} else {
		}
	}
	function setBannerPosition() {
		if (!current) return;
		
		var b = current.width();
		var w = $(window).width();
		var offset = 0;
		if (w < 940) w = 940;
		if (w < b) {
			offset = (b - w) / -2
		}
		banner.find('img').css({marginLeft:offset})
	}
	function showBanner(i) {
		current = banner.find('img').eq(i);
		currentPos = i;
		current.addClass('selected').show().siblings('img').hide().removeClass('selected');
	}
	
	
});
// ad carousel
jQuery(function($) {
	$('.rotate').each(function(i, ads) {
		var current = -1;
		var timer = null;
		var controls = $('<div class="controls"></div>');
		var len = $(ads).find('> *').length;
		var mTimer = null;
		var timeout = 5000;
		
		
		$(ads).bind('touchmove', function() {
			if (mTimer) clearTimeout(mTimer);
			
			mTimer = setTimeout(gotoNext, 50);
			
			return false;
		}).find('> *').addClass('ad').each(function(j, ad) {
			var btn = $('<span>'+(j+1)+'</span>');
			btn.click(function() {
				if (timer) {
					clearTimeout(timer);
					timer = null;
				}
				gotoAd(j);
			});
			controls.append(btn);
		}).end().wrapInner('<div class="imgs"></div>').append(controls);
		
		gotoAd(0);
		timer = setTimeout(gotoNext, timeout);
		
		function gotoAd(i) {
			controls.find('span').eq(i).addClass('selected').siblings().removeClass('selected');

			if (current < 0) {
				$(ads).find('.imgs').find('> .ad').eq(i).show().siblings().hide();
			} else {
				$(ads).find('.imgs').find('> .ad').eq(i).fadeIn().siblings().fadeOut()
			}
			current = i;
			
		}
		
		function gotoNext() {
			if (mTimer) clearTimeout(mTimer);
			mTimer = null;
			if (timer) clearTimeout(timer);
			timer = null;
			
		
			if (current >= (len-1)) {
				current = 0;
			} else {
				current = current + 1;
			}
			gotoAd(current)
			timer = setTimeout(gotoNext, timeout);
		}
		

	});
	
});


// initialize videos
jQuery(function($) {
	$('.embed').each(function(i, obj) {
		var url = $(obj).attr('href');
		var maxHeight = $(obj).attr('maxHeight')
		if (!maxHeight) maxHeight = null;
		if (url) {
			$(obj).oembed(url, {
				embedMethod:'fill',
				maxWidth:$(obj).width(),
				maxHeight:maxHeight,
				vimeo:{title:0,byline:0,portrait:0}
			});
		}
		//else $(obj).html('<p class="error">Error, no object found</p>');
	});
});

/*
 * Load Vimeo thumbnails
 */
jQuery(function($) {
	$('.vimeo-thumb[rel]').each(function(i, obj) {
		var video_id = $(obj).attr('rel')
		if ($(obj).hasClass('initialized')) return;
		var w = $(obj).width();
		
		$.getJSON('http://vimeo.com/api/v2/video/'+video_id+'.json?callback=?', function(response) {
			var data = response[0];
			//var r = data.width / data.height;
			var r = 1.33;
			var h = w / r;
			var offset = 0;
			
			var divHeight = $(obj).height()
			
			if (h > divHeight) {
				offset = (h - divHeight) / -2;
				
			}
			
			
			
			var img = document.createElement('img')
			$(img).attr({
				width:w,
				height:w / r,
				src:data.thumbnail_medium
			}).css({marginTop:offset});
			$(obj).append(img).addClass('initialized')
		});
/*		
		vimeo_video_info(video_id, {}, function(data) {
			var img = document.createElement('img')
			$(img).attr({
				width:100,
				height:75,
				src:data[0].thumbnail_small
			});
			$(obj).append(img).addClass('initialized')
		}, {video_id:video_id})
		*/
	});
});

/*
function vimeo_video_info(id, params, callback, extra) {

	var endpoint = 'http://vimeo.com/api/v2/video/'+id+'.json';
	//params = jQuery.extend(params, {});
	
	jQuery.getJSON(endpoint + '?' + jQuery.param(params) + '&callback=?', function(data) {
		callback(data)
	})
}
*/


jQuery(function($) {
	$.ajax({
		type: "GET",
		url: BASE + '/js/flickr.js',
		dataType: "script", 
		cache: true
	}); 
});

// status updates
jQuery(function($) {
	// twitter
	function getTweets(screen_name) {
		var dfd = $.Deferred();
		$.getJSON('http://twitter.com/statuses/user_timeline.json?callback=?', {screen_name:screen_name}, function(data) {
			dfd.resolve(data);
		});
		return dfd.promise();
	}
	var twitterContent = $('#twitter-updates .content');
	if (twitterContent.length > 0) {
		twitterContent.html('Loading...');
	
		$.when(getTweets('T4GOnline')).then(function(tweets) {
			$('#twitter-updates .content').html('');
			var tweet = tweets[0]
			var retweet = 'RT @'+tweet.user.screen_name+': '+tweet.text;
			var update = $('<p>'+linkify(tweet.text)+'</p><p class="meta"><small><a class="date" href="http://twitter.com/'+tweet.user.screen_name+'/status/'+tweet.id_str+'">'+prettyDate(tweet.created_at)+'</a> &nbsp; <a href="http://twitter.com/intent/retweet?tweet_id='+tweet.id_str+'" target="_blank">Retweet</a></small></p>').appendTo(twitterContent);
			
		});
	}
	
	// facebook
	function getFacebook(page) {
		var dfd = $.Deferred();
		$.getJSON('https://graph.facebook.com/'+page+'/feed?callback=?', {
			access_token:'275042205849695|77-N-U1ZSjt3PpXGuk-7oCCStNo'
		}, function(response) {
			dfd.resolve(response['data']);
		});
		return dfd.promise();
	}
	
	var facebookContent = $('#facebook-updates .content');
	if (facebookContent.length > 0) {
	facebookContent.html('Loading...');
		$.when(getFacebook('TogetherfortheGospel')).then(function(statuses) {
			$('#facebook-updates .content').html('');
			if (!statuses) return;
			var status = statuses[0];
			var id = status['id'].replace(/.*_/, '');
			var more = '';
			if (status['link'] && status['caption']) {
				var verb = 'More';
				if (status['type'] == 'video') {
					verb = 'View';
				} else if (status['type'] == 'music') {
					verb = 'Listen';
				} 
				more = '&nbsp; <a href="'+status['link']+'" target="_blank">'+verb+'</a>';
			}
			
			var html = '<p class="status '+status['type']+'">';
			html += status['message'];
			if (status['picture']) {
				//html += '<a href="http://www.facebook.com/TogetherfortheGospel/posts/'+id+'" class="picture"><img src="'+status['picture']+'"  /></a>'
			}
			
			html += '</p>';
			var update = $(html+'<p class="meta"><small><a class="date" href="http://www.facebook.com/TogetherfortheGospel/posts/'+id+'">'+prettyDate(status['created_time'])+'</a> '+more+'</small></p>').appendTo(facebookContent);
			
		});
	
	}
	
});




// print preview
jQuery(function($) {
	var links = $('link[rel=stylesheet]');
	var print = links.filter('link[media=print]')
	var screen = links.filter('link[media=screen]')
	$('a.print').click(function() {
		create_preview();
		return false;
	});
	function create_preview() {
		$(print).each(function(i, stylesheet) {
			$(stylesheet).attr('media', 'all')
		});
		$(screen).each(function(i, stylesheet) {
			$(stylesheet).attr('disabled', 'disabled')
		});
		var done = $('<input type="button" value="Done" />');
		done.click(function() {
			close_preview();
		});
		var preview = $('<form id="print-preview" style="margin: 0 0 2em 0; padding:0.75em; border-bottom:1px solid #555;background:#ccc;"><strong>Print Preview</strong> &nbsp; &nbsp; <input type="button" value="Print this Page" onclick="window.print()" /> &nbsp; &nbsp; <style media="print">#print-preview { display:none} </style></form>');
		preview.append(done).prependTo('body');
		
		setTimeout(function() { window.print(); }, 1000);
		
	}
	
	function close_preview() {
		$(print).each(function(i, stylesheet) {
			$(stylesheet).attr('media', 'print')
		});
		$(screen).each(function(i, stylesheet) {
			$(stylesheet).attr('disabled', false)
		});
		$('#print-preview').remove();
	}
});


/*
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettyDate(time){
	var date = new Date((time || "").replace(/-/g,"/").replace(/TZ?/g," ")),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ) {
		return time;
	}
			
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 31 && Math.ceil( day_diff / 7 ) + " weeks ago";
}


/*
 * linkify - v0.3 - 6/27/2009
 * http://benalman.com/code/test/js-linkify/
 * 
 * Copyright (c) 2009 "Cowboy" Ben Alman
 * Licensed under the MIT license
 * http://benalman.com/about/license/
 * 
 * Some regexps adapted from http://userscripts.org/scripts/review/7122
 */

window.linkify=(function(){var k="[a-z\\d.-]+://",h="(?:(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])\\.){3}(?:[0-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])",c="(?:(?:[^\\s!@#$%^&*()_=+[\\]{}\\\\|;:'\",.<>/?]+)\\.)+",n="(?:ac|ad|aero|ae|af|ag|ai|al|am|an|ao|aq|arpa|ar|asia|as|at|au|aw|ax|az|ba|bb|bd|be|bf|bg|bh|biz|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|cat|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|coop|com|co|cr|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|info|int|in|io|iq|ir|is|it|je|jm|jobs|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|me|mg|mh|mil|mk|ml|mm|mn|mobi|mo|mp|mq|mr|ms|mt|museum|mu|mv|mw|mx|my|mz|name|na|nc|net|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pro|pr|ps|pt|pw|py|qa|re|ro|rs|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tel|tf|tg|th|tj|tk|tl|tm|tn|to|tp|travel|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|xn--0zwm56d|xn--11b5bs3a9aj6g|xn--80akhbyknj4f|xn--9t4b11yi5a|xn--deba0ad|xn--g6w251d|xn--hgbk6aj7f53bba|xn--hlcj6aya9esc7a|xn--jxalpdlp|xn--kgbechtv|xn--zckzah|ye|yt|yu|za|zm|zw)",f="(?:"+c+n+"|"+h+")",o="(?:[;/][^#?<>\\s]*)?",e="(?:\\?[^#<>\\s]*)?(?:#[^<>\\s]*)?",d="\\b"+k+"[^<>\\s]+",a="\\b"+f+o+e+"(?!\\w)",m="mailto:",j="(?:"+m+")?[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@"+f+e+"(?!\\w)",l=new RegExp("(?:"+d+"|"+a+"|"+j+")","ig"),g=new RegExp("^"+k,"i"),b={"'":"`",">":"<",")":"(","]":"[","}":"{","B;":"B+","b?:":"b?9"},i={callback:function(q,p){return p?'<a href="'+p+'" title="'+p+'">'+q+"</a>":q},punct_regexp:/(?:[!?.,:;'"]|(?:&|&amp;)(?:lt|gt|quot|apos|raquo|laquo|rsaquo|lsaquo);)$/};return function(u,z){z=z||{};var w,v,A,p,x="",t=[],s,E,C,y,q,D,B,r;for(v in i){if(z[v]===undefined){z[v]=i[v]}}while(w=l.exec(u)){A=w[0];E=l.lastIndex;C=E-A.length;if(/[\/:]/.test(u.charAt(C-1))){continue}do{y=A;r=A.substr(-1);B=b[r];if(B){q=A.match(new RegExp("\\"+B+"(?!$)","g"));D=A.match(new RegExp("\\"+r,"g"));if((q?q.length:0)<(D?D.length:0)){A=A.substr(0,A.length-1);E--}}if(z.punct_regexp){A=A.replace(z.punct_regexp,function(F){E-=F.length;return""})}}while(A.length&&A!==y);p=A;if(!g.test(p)){p=(p.indexOf("@")!==-1?(!p.indexOf(m)?"":m):!p.indexOf("irc.")?"irc://":!p.indexOf("ftp.")?"ftp://":"http://")+p}if(s!=C){t.push([u.slice(s,C)]);s=E}t.push([A,p])}t.push([u.substr(s)]);for(v=0;v<t.length;v++){x+=z.callback.apply(window,t[v])}return x||u}})();

