jQuery.fn.extend({
	
	toggleText: function(check, replace){
		var new_text = (this.text() === check) ? replace : check;
		this.text(new_text);
		return this;
	}
	
});


var Photorific = {

	/*-------------------------------------------------------
	*	Some repeatedly used variables/functions
	-------------------------------------------------------*/
	
	agent: navigator.userAgent.toLowerCase(),
	
	is_iphone: false,
	
	loader_gif: '',
	
	theme_width: 920,
	
	set: function(item, value){
		this[item] = value;
	},
	
	/*-------------------------------------------------------
	*	Theme setup functions (always called on page load)
	-------------------------------------------------------*/
	
	init: function(){
		var is_iphone = (this.agent.match(/iphone|ipod/)) ? true : false;
		this.set("is_iphone", is_iphone);
		
		var theme_width = (is_iphone) ? 300 : 920;
		this.set("theme_width", theme_width);
	},
	
	/*-------------------------------------------------------
	*	Index & Permalink Page Controllers
	-------------------------------------------------------*/

	index: function(){
	
		// Set up the theme for iPhone users
		if(this.is_iphone) this.setup.iPhone(true);
		
		// Fix windows video embeds
		if(this.agent.match(/windows/)) this.fix.windowsVideo();
		
		this.setup.postTags();
		this.setup.videoPosts();
	},
	
	permalink: function(){
		
		// What kind of single post-type are we dealing with?
		var id = $('#permalink').children('div').attr("id");
	
		// Do some stuff based on that post-type
		switch(id)
		{
			case "text": case "link": case "quote": case "chat":
				this.setup.notes(id);
				this.misc.notesHashCheck();
				break;
			
			case "photo":
				this.post.photo();
				if(this.is_iphone) this.setup.iPhone(false);
				this.setup.notes(id);
				break;
			
			case "audio":
				$('#notes-container').show();
				break;
			
			default:
				$('#notes-container').show();
				break;
		}
		
		// Conditionally change the avatar size of all notes
		if( ! this.is_iphone) this.setup.notesAvatars();
	},
	
	/* Prep some collections */
	fix: {},
	misc: {},
	post: {},
	setup: {}
};

/*-------------------------------------------------------
*	Fix
*
*	A collection of functions for tweaking theme
*	elements to work better for us
-------------------------------------------------------*/

Photorific.fix = {
	
	/*	Following - remove margins from orphaned followers */
	following: function(){	
		if($("#following"))
		{
			var per_row = 13,
				count = $("#following a").size(),
				rows = Math.round(count / per_row);
				
			for (i = 1; i <= rows; i++)
			{
				var person = $("#following").find("a img:eq(" + (i * per_row) - 1 + ")");
				person.addClass("orphan");
			}
		}
		else if($("#members"))
		{
			$("#members").find("p:odd").each(function(){
				$(this).addClass("orphan");
			});
		}			
	},
	
	/*	Windows Video - identify windows embeds w/ a class */
	windowsVideo: function(){
		$("div.post.video").each(function(){	
			var id = (Photorific.agent.match(/safari/)) ? "safari" : "mozilla";
			$(this).attr("id", "win_" + id);
		});	
	},
	
	test: function(){ alert(Photorific.theme_width); }
}

/*-------------------------------------------------------
*	Misc
*
*	Miscelaneuos functions
-------------------------------------------------------*/

Photorific.misc = {
	
	/*	Notes Hash Check - send a click on a "#notes" hash in the url */
	
	notesHashCheck: function(){
		if(location.hash.match(/#notes/)) $("a#notes-button").click();
	},
	
	/*	Display Photo - determine how to display photo posts
	-------------------------------------------------------*/
	displayPhoto: function(img, info_div){
		var img_width = img.width(),
			img_height = img.height(),
			div_height = info_div.height(),
			div_max_height = img_height / 1.75;
			
		if(div_height > img_height)
		{
			var body = info_div.html();
			info_div.remove();
			$("p.photo").after('<div class="body">' + body + '</div>');
			this.notesHashCheck();
			return;
		}
		else
		{
			if($.browser.msie)
			{
				info_div.css({
					"width": img_width - 16,
					"max-height": div_max_height
				});
			}
			else
			{
				info_div.css({
					"width": img_width - 20,
					"max-height": div_max_height
				});
			}
		}
		
		if(img_width != Photorific.theme_width)
		{
			var offset = img.offset();
			info_div.css({
				"left": offset.left
			});
		}
		
		this.notesHashCheck();
	}
};

/*-------------------------------------------------------
*	Post
*
*	Various post functions
-------------------------------------------------------*/

Photorific.post = {
	

	/*	Photo
	*	
	*	Hides the photo before loading to prevent 
	*	complications between resizing the photo and 
	*	displaying the notes.
	-------------------------------------------------------*/
	
	photo: function(){
		var div = $('#photo p.photo'),
			img = $('#photo p.photo img'),	
			info_div = $('#photo .photo_info');
			loader = Photorific.loader_gif,
			notes_label = $('p#notes-label');
	
		if(Photorific.is_iphone)
		{
			var body = info_div.html();
			info_div.remove();
			div.after('<div class="iphone_photo_body">' + body + '</div>');	
			return;
		}
		
		// Safari bug fix for displaying the photo
		if(img.height() > 0 && Photorific.agent.match(/safari/i))
		{
			Photorific.misc.displayPhoto(img, info_div);
			return;
		}
		
		img.hide();
		notes_label.hide();
		
		if( ! $.isEmptyObject(Photorific.loader_gif))
		{
			$("<img/>", {
				"id": "img_loader",
				"alt": "Loading...",
				"src": loader
			}).prependTo(div);
		}
		
		img.load(function()
		{
			$("img#img_loader").remove();
			img.fadeIn(500);
			notes_label.fadeIn(500);
			Photorific.misc.displayPhoto(img, info_div);
		});
	}
	
};

/*-------------------------------------------------------
*	Setup
*
*	A collection of functions for attatching events
*	and setting up theme elements
-------------------------------------------------------*/

Photorific.setup = {

	/*	iPhone - setup the theme for use on an iPhone/iPod */
	
	iPhone: function(is_index){
		// Toggle footer opacity
		$("div#footer").click(function(){
			if( ! $(this).hasClass("iphone_clicked"))
			{
				$(this).addClass("iphone_clicked");
			}
		});
			
		if(is_index)
		{
			$("div.post").each(function(){
				$(this).append('<p class="show_more"><a href="#more" class="show_more">More</a></p>');
			});
		}
	},

	/*	Notes - setup an onclick event for fading in notes */
	
	notes: function(id)
	{
		var post = $('#permalink #' + id),
			box = $('#notes-container'),
			button = $('a#notes-button');
			
		button.click(function(e){
			if (box.is(':visible'))
			{
				box.fadeOut(500, function()
				{
					post.fadeIn(500);
				});
			}
			else
			{
				post.fadeOut(500, function()
				{
					box.fadeIn(500);
				});
			}
			
			$(this).toggleClass('open');
			
			e.preventDefault();
		});
	},
	
	/*	Notes Avatars - change the post notes avatar size */
	
	notesAvatars: function(){
		var avatar = $('#notes-container').find('img.avatar');
		avatar.each(function(){
			var source = $(this).attr("src");
			var file_type = source.match(/(png|jpe?g|gif)$/);
			var big = source.replace("16." + file_type[0], "30." + file_type[0]);
			$(this).attr("src", big).addClass('big');
		});
	},
	
	/*	Post Tags - ready the post tag button & align boxes */
	
	postTags:  function(){
		var box = $("div.tags");
		
		if(Photorific.agent.match(/msie/))
		{
			box.each(function(){ $(this).remove(); });
			return;
		}
		
		box.each(function(){
			var p = $(this).find("p.tags"),
				tags = p.find("a"),
				a = $(this).find("a.tags"),
				top = (parseFloat(p.height()) + 13) * -1;
			
			p.css({"top" : top});
			
			if(this.is_iphone) p.css({"margin-top" : top * (tags.length + 2)});
			
			a.click(function(){
				p.toggle();
			});
		});
	},
	
	/*	Video Posts - toggle the post content box for video posts */
	
	videoPosts: function(){
		$("a.info").each(function(){
			$(this).click(function(){
					var a = $(this),
						box = a.parent().parent(), // div#info
						parent = a.parent().parent().parent(), // Whew...!
						content = parent.find("div.post_content"),
						top = (parseFloat(box.css("top")) == 175) ? "0px" : "175px",
						bottom = (parseFloat(box.css("bottom")) == 0) ? "-175px" : "0px";
						
					if( ! Photorific.agent.match(/msie/))
					{
						a.toggleText("Show", "Hide");
					}
		
					content.toggle();
					box.css({"top" : top, "bottom" : bottom });
			});
		});
	}
};


/*-------------------------------------------------------
*	Recent Tweets
-------------------------------------------------------*/

function recent_tweets(data)
{
	var box = $("div#twitter"),
		tweet = data[0],
		text = tweet.text,
		twitter = "http://twitter.com/",
		replies = (text.match(/@(\w)+/g)) ? text.match(/@(\w)+/g) : "",
		tags = (text.match(/#(\w)+/g)) ? text.match(/#(\w)+/g) : "";
	
	if(replies != "")
	{
		for (i = 0; i < replies.length; i++)
		{
			var username = replies[i].replace("@", "");
			text = text.replace(replies[i], '<a href="' + twitter + username + '">' + replies[i] + '</a>');
		}
	}
	
	if(tags != "")
	{
		for (i = 0; i < tags.length; i++)
		{
			var tag = tags[i].replace("#", "");
			text = text.replace(tags[i], '<a href="' + twitter + "#search?q=%23" + tag + '">' + tags[i] + '</a>');
		}
	}
	
	var date = tweet.created_at.toLowerCase()
	date = date.split(" ", 3);
	
	text += ' <a href="' + twitter + tweet.user.screen_name + '/status/' + tweet.id + '">#</a> <span id="tweet_info">';
	
	if(data[0].in_reply_to_status_id)
	{
		var reply_name = tweet.in_reply_to_screen_name;
		var reply_id = tweet.in_reply_to_status_id;
		text += ' <a href="'+ twitter + reply_name + '/status/' + reply_id + '">in reply</a> to <a href="' + twitter + reply_name + '">' + reply_name + '</a>';
	}
	
	text += '</span>';
	
	box.append("<p>" + text + "</p>");
}

/*-------------------------------------------------------
*	Flickr
-------------------------------------------------------*/

function flickr(id){
	
	var url = 'http://api.flickr.com/services/feeds/photos_public.gne?id=' + id + '&format=json&jsoncallback=?';
	
	num_photos = (Photorific.is_iphone) ? 3 : 8;
	
	$.getJSON(url , function(data) {
	
		var box = $("#flickr");
		var user_home = data.items[0].link.replace(/[0-9]+\//, "");
		var user_name = user_home.replace("http://www.flickr.com/photos/", "").replace("/", "");
		box.prepend("<p class='photos'></p>");
		
		
		var header = '<h3>Flickr <br /><a class="username" href="' + user_home +'">' + user_name + '</a></h3>';
		box.prepend(header);
		
		$.each(data.items, function(i,item) {
		
			var mImg = item.media.m;
			var sImg = (item.media.m).replace("_m.jpg", "_s.jpg");
			var link = item.link;
			
			$("<img/>")
				.attr("src", sImg)
				.attr("id", "thumb")
				.appendTo("#flickr p.photos")
				.wrap('<a href="' + link + 'sizes/l/" title="' + item.title + '"></a>');

			if (i >= num_photos) return false;
		});
		
		$("#flickr img:last").addClass("last");

	});
}

/*-------------------------------------------------------
*	New Video
-------------------------------------------------------*/

function new_video(player, color, width, perma)
{
	// Fix ridiculous "object" syntax errors
	player = player.replace(/><\/(param|embed)>/g, "/>");

	/*	Add wmode = opaque
	-------------------------------------------------------*/
	if(	! player.match(/name="wmode"/))
		player = player.replace(/<param/, '<param name="wmode" value="opaque" /><param');
	
	if( ! player.match(/wmode="(transparent|opaque)"/))
		player = player.replace(/\/><\/object>/, 'wmode="opaque" /></object>');
		
	player = player.replace('wmode="transparent"', 'wmode="opaque"');
	player = player.replace('name="wmode" value="transparent"', 'name="wmode" value="opaque"');
	
	/*  Embed Options (via matthewbuchanan.name)
	-------------------------------------------------------*/
	
	var obj_class = "other";
	
	/* Vimeo */
	
	if(player.match(/vimeo\.com/i))
	{
		color = color.replace("#", "");
			
		var vimeoOld = /show_title=[01]&amp;show_byline=[01]&amp;show_portrait=[01]&amp;color=([a-fA-F0-9]){1,6}/g,
			vimeoNew = "show_title=0&amp;show_byline=1&amp;show_portrait=1&amp;color=" + color;
		
		if(perma === false) player = set_ratio(player, width);
		
		player = player.replace(vimeoOld, vimeoNew);
		obj_class = "vimeo";
	}
	
	/* YouTube */
	
	if(player.match(/youtube\.com/i))
	{
		var youtubeOld = /rel=0/g,
			youtubeNew = "rel=0&amp;hd=1&amp;color1=0xFFFFFF&amp;color2=0xFFFFFF";
			
		player = player.replace(youtubeOld, youtubeNew);
		obj_class = "youtube";
	}
	
	/* Hulu */
	
	if(player.match(/hulu\.com/i) && perma === false)
	{
		player = set_ratio(player, 500);
		obj_class = "hulu";
	}
	
	player = player.replace(/^<object/, '<object class="' + obj_class + '"');
	
	// -------------------------------------------------
	
	if(perma === true) player = set_ratio(player, Photorific.theme_width);
	
	document.write(player);
}

/*-------------------------------------------------------
*	New Audio
-------------------------------------------------------*/

function new_audio(player, color, id, perma)
{
	// Fix ridiculous "object" syntax errors
	player = player.replace(/><\/(param|embed)>/g, "/>");
	
	color = color.replace("#", "");
	
	if(color == "000000")
	{
		player = player.replace("&color=FFFFFF", "");
		player = player.replace("audio_player.swf", "audio_player_black.swf");
	}
	else
	{
		player = player.replace("color=FFFFFF", "color=" + color);
	}
	
	// -------------------------------------------------
	
	if(perma === true)
	{
		var width = ($("div.audio_extra").length === 0) ? Photorific.theme_width : 545;
		$("div.player").width(width);
		player = set_ratio(player, width);
	}
	
	var box = $("span#" + id);
	box.html(player);
	box.parent().addClass("replaced");
}

/*-------------------------------------------------------
*	Set Ratio
-------------------------------------------------------*/

function set_ratio(player, target_width)
{
	// Match the current height and width
	var h_matches = player.match(/(?:height=")([0-9]+)(?:")/);
	var w_matches = player.match(/(?:width=")([0-9]+)(?:")/);
	
	var height = parseFloat(h_matches[1]);
	var width = parseFloat(w_matches[1]);
	
	// Get the ratio and set a new target height
	var ratio = height / width;
	var target_height = Math.round(target_width * ratio);
	
	// Set the player code with the new height and width
	player = player.replace(/width="[0-9]+"/g, 'width="' + target_width + '"');
	player = player.replace(/height="[0-9]+"/g, 'height="' + target_height + '"');
	
	return player;
}
