if( ! window['chattarati'] ) {
	window['chattarati'] = {};
	var chattarati = window['chattarati'];
}

(function($){

	function log( item ) {
		if( typeof window['console'] != 'undefined' && typeof console.log == 'function' ) {
			console.log( item );
		}
	}
	
	protos = {
		'a':	$('<a />'),
		'img':	$('<img />'),
		'li':	$('<li />'),
		'span':	$('<span />')
	};
	
	$(document).ready(function() {
		chattarati.isMobile = $('body').is('.mobile');
		chattarati.login();
		if( !chattarati.isMobile ) {
//			chattarati.nav();
			chattarati.equalHeights();
//			chattarati.tools();
			chattarati.selectors();
			chattarati.slideshow();
			chattarati.audio();
			chattarati.lightbox();
		}
		chattarati.ajaxComments();
		chattarati.tweet();
	});
	
	$(window).load(function() {
		if( !chattarati.isMobile ){
			chattarati.equalHeights();
		}
	});
	
	chattarati.nav = function() {
		var startTimeout, endTimeout = null;
		var hovered, clicked = false;
		var navLinks = $('#nav a');
		var subNavs = $('#sub-nav li[rel]');
		var currentSubNav = subNavs.filter(':visible');
		subNavs.css({'z-index': 2});
		currentSubNav.css({'z-index': 1});
		navLinks.hover(function() {
			var link = $(this);
			if( ! clicked ) {
				subNavs.filter(function() { return $(this).is(':hidden') && $(this).attr('rel') == link.attr('rel'); }).fadeIn(500);
				link.addClass('hover');
			}
		}, function() {
			var link = $(this);
			link.removeClass('hover');
			setTimeout(function(){
				if( ! hovered && ! clicked ) {
					subNavs.filter(function() { return $(this).is(':visible') && $(this).attr('rel') == link.attr('rel') && $(this).attr('rel') != currentSubNav.attr('rel'); }).fadeOut(500);
				}
			},100);
			setTimeout(function(){
				if( ! hovered && ! clicked ) {
					subNavs.filter(function() { return $(this).is(':visible') && $(this).attr('rel') == link.attr('rel') && $(this).attr('rel') != currentSubNav.attr('rel'); }).fadeOut(500);
				}
			},2000);
		});
		subNavs.hover(function() {
			hovered = true;
			navLinks.filter('[rel=' + $(this).attr('rel') + ']').addClass('hover');
		}, function() {
			hovered = false;
			navLinks.filter('[rel=' + $(this).attr('rel') + ']').removeClass('hover');
			var link = navLinks.filter('[rel=' + $(this).attr('rel') + ']');
			setTimeout(function(){
				if( ! hovered && ! clicked ) {
					subNavs.filter(function() { return $(this).is(':visible') && $(this).attr('rel') == link.attr('rel') && $(this).attr('rel') != currentSubNav.attr('rel'); }).fadeOut(500);
				}
			},100);
			setTimeout(function(){
				if( ! hovered && ! clicked ) {
					subNavs.filter(function() { return $(this).is(':visible') && $(this).attr('rel') == link.attr('rel') && $(this).attr('rel') != currentSubNav.attr('rel'); }).fadeOut(500);
				}
			},2000);
		});
		navLinks.add(subNavs.find('a')).click(function() {
			clicked = true;
		});
	}
	
	chattarati.equalHeights = function() {
		if(jQuery.browser.msie && jQuery.browser.version < 7) { return; }
		var sections = $('section:has(.articles), section:has(article):not(.top-story), .metablog #main section');
		if( $('body').is('.metablog') ) {
			var sections = $('.metablog #main section:first-child,.metablog #main section:nth-child(3n+1)');
			sections.each(function() {
				var height = 0;
				$(this).add($(this).next('section')).add($(this).next('section').next('section')).each(function() {
					height = $(this).height() > height ? $(this).height() : height;
				}).each(function() {
					var more = $(this).children('footer:has(a.more)');
					more.css({'padding-top': ( ( height - $(this).height() ) + parseInt( more.css('padding-top'), 10) ) + 'px'});
				});
			});
		} else {
			sections.each(function() {
				var section = $(this);
				var articles = section.find('article:first-child,article:nth-child(3n+1)');
				articles.each(function() {
					var height = 0;
					var theseArticles = $(this).add($(this).next('article')).add($(this).next('article').next('article'));
					theseArticles.each(function() {
						height = $(this).height() > height ? $(this).height() : height;
					}).each(function() {
						var more = $(this).children('footer:has(a.more)');
						more.css({'padding-top': ( ( height - $(this).height() ) + parseInt( more.css('padding-top'), 10) ) + 'px'});
					});
				});
			});
		}
		var authors = $('.author');
		var height = 0;
		authors.each(function() {
			height = $(this).height() > height ? $(this).height() : height;
		}).each(function() {
			$(this).height(height);
		});
		$('.two-up section:nth-child(odd)').each(function() {
			if( $(this).height() < $(this).next('section').height() ) {
				$(this).height( $(this).next('section').height() );
			} else {
				$(this).next('section').height( $(this).height() );
			}
		});
	}
	
	chattarati.tools = function() {
		var tools = $('ul.tools');
		var share = tools.find('a.share');
		var shareChoices = share.siblings('ul');
		tools.width(tools.width());
		shareChoices.hide();
		share.click(function(c) {
			c.preventDefault();
			shareChoices.slideToggle(500);
		});
	}
	
	chattarati.weather = function() {
		if( ! $('body').is('#home') ) { return; }
		$.ajax({
			url: 'http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20location%3D37415&format=json&callback=?',
			type: 'GET',
			dataType: 'json',
			success: function(data, textStatus) {
				var conditions = data.query.results.channel.item.condition;
				var li = protos.li.clone();
				li.addClass('weather');
				li.append(protos.span.clone().addClass('title').text('Current Weather:')).append(protos.span.clone().addClass('image').append(protos.img.clone().attr({'src': 'http://l.yimg.com/a/i/us/we/52/' + conditions.code + '.gif', 'alt': conditions.text, 'title': conditions.text }))).append(protos.span.clone().addClass('conditions').html(conditions.temp + '&deg; and ' + conditions.text)).append(protos.span.clone().addClass('powered-by').append(protos.a.clone().attr({'href':'http://weather.yahoo.com'}).text('Powered by Yahoo!')));
				li.prependTo($('#sub-nav li[rel=home] ul'));
			}
		});
		
	}
	
	chattarati.selectors = function() {
		$('#main section article:first-child, #main section article:nth-child(3n+1), .metablog #main section:first-child, .metablog #main section:nth-child(3n+1), #main .articles article:first-child, #main .articles article:nth-child(3n+1)').addClass('first-of-row');
	}
	
	chattarati.login = function() {
		if( ! $('body').is('#login') ) { return; }
		var actions = {
			'login': $('label[for=id_action_0]'),
			'register': $('label[for=id_action_1]')
		}
		$('form#login').addClass('scripted');
		var submit = $('form#login button span');
		var email = $('form#login li.email');
		if( actions.register.find('input').is(':checked') ) {
			actions.register.addClass('on');
			submit.text('Register');
		} else {
			email.hide();
			actions.login.addClass('on');
			submit.text('Log In');
		}
		actions.login.click(function() {
			actions.login.addClass('on');
			email.hide();
			actions.register.removeClass('on');
			submit.text('Log In');
		});
		actions.register.click(function() {
			actions.login.removeClass('on');
			email.show();
			actions.register.addClass('on');
			submit.text('Register');
		});
	}
	
	chattarati.slideshow = function() {
		var photos = $('article .photos .figure');
		if( photos.size() < 2 ) { return; }
		var container = photos.parent('.photos');
		container.addClass('scripted');
		var highest = 0;
		photos.each(function() {
			highest = $(this).height() > highest ? $(this).height() : highest;
		});
		container.height(highest);
		photos.hide().eq(0).show();
		setInterval(function(){
			var current = photos.filter(':visible');
			var to = current.next('.figure').size() ? current.next('.figure') : photos.eq(0);
			current.fadeOut(1000);
			to.fadeIn(1000);
		}, 6000);
	}
	
	chattarati.audio = function() {
		var playlists = $('.audio .playlist');
		var standaloneAudios = $('.singles audio');
		var div = $('<div />');
		AudioPlayer.setup('http://media.chattarati.com/media/player.swf', {
			'width': '100%',
			'transparentpagebg': 'yes',
			'leftbg': '000000',
			'lefticon': 'ffffff',
			'rightbg': '000000',
			'rightbghover': '333333',
			'righticon': 'ffffff',
			'bg': '000000',
			'voltrack': '000000',
			'volslider': 'ffffff',
			'loader': '666666',
			'text': 'ffffff',
			'track': '000000',
			'border': '000000',
			'tracker': '333333',
			'skip': 'ffffff',
			'animation': 'no'
		});
		standaloneAudios.each(function(index) {
			var audio = $(this);
			audio.siblings('.name').remove();
			audio.attr({'id': 'audio-' + index}).prependTo(audio.parent());
			AudioPlayer.embed('audio-' + index, {
				'soundFile': audio.attr('src'),
				'titles': audio.attr('title')
			});
		});
		playlists.each(function(index) {
			var playlist = $(this);
			var audios = playlist.find('audio');
			var files = ''
			var titles = ''
			audios.each(function() {
				files += $(this).attr('src') + ',';
				titles += $(this).attr('title') + ',';
			});
			files = files.replace(/,$/, '');
			titles = titles.replace(/,$/, '');
			playlist.attr({'id': 'playlist-' + index});
			AudioPlayer.embed('playlist-' + index, {
				'soundFile': files,
				'titles': titles
			})
		});
	}
	
	chattarati.ajaxComments = function() {
		var comments = $('#comments');
		var form = comments.find('form');
		var loading = $('<p class="loading">Your comment is being submitted.</p>');
		var error = $('<p class="error">There was an error submitting your comment.</p>');
		var required = $('<ul class="errorlist"><li>Comment is a required field.</li></ul>');
		var commentField = form.find('textarea[name=comment]');
		form.submit(function(s) {
			s.preventDefault();
			if( commentField.val() ) {
				$.ajax({
					'beforeSend': function() {
						error.remove();
						required.remove();
						form.before(loading);
						form.find(':input').attr({'disabled': 'disabled'});
					},
					'cache': false,
					'complete': function() {
						loading.remove();
						form.find(':input').removeAttr('disabled');
						commentField.val('');
					},
					'data': form.serialize(),
					'error': function() {
						form.before(error);
					},
					'success': function(data) {
						error.remove();
						if($(data).find('#comments ol.comment-list').size()) {
							comments.find('ol.comment-list').replaceWith($(data).find('#comments ol.comment-list'));
							window.location.hash = comments.find('ol.comment-list li:last-child').attr('id');
						}
						try {
							onlocation.live.updater.comments();
						} catch(e) {}
					},
					'type': 'POST',
					'url': form.attr('action')
				});
			} else {
				form.prepend(required);
			}
		});
	}
	
	chattarati.tweet = function() {
		var link = $('.tools a.twitter');
		if( ! link.size() ) { return; }
		if( link.attr('href').indexOf('twitter.com') > -1 ) { // this user doesn't have twitter linked up with us
			// do nothing
		} else {
			link.click(function(c) {
				c.preventDefault();
				try {
					$.ajax({
						'beforeSend': function() {
							link.addClass('loading');
						},
						'cache': false,
						'complete': function() {
							link.removeClass('loading');
						},
						'data': link.attr('href').split('?')[1] + '&next=' + window.location,
						'success': function(data) {
							if($(data).find('ul.messages').size()) {
								$('#bd').prepend($(data).find('ul.messages'));
							}
						},
						'type': 'POST',
						'url': link.attr('href').split('?')[0]
					});
				} catch(e) { window.location = link.attr('href'); }
			});
		}
	}
	
	chattarati.lightbox = function() {
		var links = $('a[rel^=lightbox]');
		var overlay = $('<div id="overlay" style="display: none"></div>');
		var container = $('<div id="lightbox" style="display: none"></div>');
		var close = $('<a href="#close" class="close">&times; Close</a>');
		var target = $('<div class="target"></div>');
		var prev = $('<a href="#prev" class="prev">&laquo; Previous</a>');
		var next = $('<a href="#next" class="next">Next &raquo;</a>');
		var title = $('<label />');

		chattarati.lightbox.links = links;
		chattarati.lightbox.overlay = overlay;
		chattarati.lightbox.container = container;
		chattarati.lightbox.close = close;
		chattarati.lightbox.target = target;
		chattarati.lightbox.prev = prev;
		chattarati.lightbox.next = next;
		chattarati.lightbox.title = title;

		$('body').append(overlay).append(container);
		container.append(close).append(target).append(prev).append(next).append(title);
		container.show().css({'top': Math.round((($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - container.outerHeight()) / 2) + 'px', 'left': Math.round(($(window).width() - container.outerWidth()) / 2) + 'px', 'margin-top': 0, 'margin-left': 0}).hide();
		close.click(function(c) {
			c.preventDefault();
			overlay.add(container).fadeOut('normal');
		});

		prev.add(next).click(function(c) {
			c.preventDefault();
			var current = parseInt(links.filter('.selected').attr('lb-position'),10);
			var to = $(this).is('.prev') ? links.eq(current - 1) : links.eq(current + 1);
			if(!to.size()) {
				to = $(this).is('.prev') ? links.eq(links.size() - 1) : links.eq(0);
			}
			if(to.size()) {
				to.click();
			}
		});

		links.each(function(index) {
			var link = $(this);
			link.click(function(c) {
				c.preventDefault();
				open(link.attr('href'),link.siblings('.subject').text());
				links.filter('.selected').removeClass('selected');
				link.addClass('selected');
			});
			link.attr({'lb-position': index});
		});

		var open = function(url, titleText) {
			if(container.is(':visible')) {
				target.children().add(title).fadeOut('normal', function() {
					target.children().remove();
					loadImage(url, titleText);
				});
			} else {
				target.children().remove();
				title.hide();
				overlay.add(container).fadeIn('normal',function(){
					loadImage(url, titleText);
				});
			}
		}

		var loadImage = function(url, titleText) {
			if(container.is('.loading')) { return; }
			container.addClass('loading');

			var img = new Image();
			img.onload = function() {
				img.style.display = 'none';

				var maxWidth = ($(window).width() - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'), 10)) - 100;
				var maxHeight = (($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'), 10)) - 100;

				if(img.width > maxWidth || img.height > maxHeight) { // One of these is larger than the window
					var ratio = img.width / img.height;
					if(img.height >= maxHeight) {
						img.height = maxHeight;
						img.width = maxHeight * ratio;
					} else {
						img.width = maxWidth;
						img.height = maxWidth * ratio;
					}
				}

				title.text( titleText );

				container.animate({'width': img.width,'height': img.height, 'top': Math.round((($(window).height() > window.innerHeight ? window.innerHeight : $(window).height()) - img.height - parseInt(container.css('padding-top'),10) - parseInt(container.css('padding-bottom'),10)) / 2) + 'px', 'left': Math.round(($(window).width() - img.width - parseInt(container.css('padding-left'),10) - parseInt(container.css('padding-right'),10)) / 2) + 'px'},'normal', function(){
					target.append(img);
					$(img).add(title).fadeIn('normal', function() {
						container.removeClass('loading');
					});
				})
			}
			img.src = url;
		}
	}
	
})(jQuery);