function cleanup(u, g)
{
	jQuery('.post .byLine .username a').each(function(){

		if(u==jQuery(this).html() || g=="true")
		{
			pid = jQuery(this).closest('div.post')[0].id.replace(/post/,'');
			path = window.location.href.replace(/:3000/, '').split('?')[0].split('.com')[1] + '/' + pid + '/edit';

			if(jQuery(this).parent().siblings('.cleanUp').find('a.edit').size()==0)
			{
				jQuery(this).parent().siblings('.cleanUp').append(' <a href="'+ path +'" class="edit">edit</a>');
			}
		}
	});
}

function created_post(u, g, id)
{
	THREDDED.post_listing.toggle_subscriber();
	cleanup(u, g);
	jQuery(id).effect('highlight', {}, 500);
	jQuery('fieldset.faded').removeClass('faded');
	jQuery('img.spinna').remove();
	jQuery('input').removeAttr('disabled');
	jQuery('fieldset textarea').val('').focus();
  jQuery('#attach p').remove();
	if(navigator.userAgent.indexOf('Safari') < 0){ window.history.go(-1); }
}

// == DEBUG SETUP ============================================================
if(window['debug'] === undefined) {
  window.debug = function(q,w,e,r){  
    try { if (typeof console != 'undefined') console.log.apply(console,arguments); } 
    catch(err){ if (typeof console != 'undefined')  console.log(q,w,e,r); }
  }
}

// ====================
// = OBJECT: THREDDED =
// ====================
window.THREDDED = {
	
	// common domready code that runs on all pages
	common:{
		
		// code effecting visual look of the page (reason why it fires first / inits)
		init:function()
		{
			// set the ie6 variable to true if they're using ie7
			jQuery.browser.ie7 = (jQuery.browser.msie && jQuery.browser.version == 7);
			jQuery.browser.ie6 = (jQuery.browser.msie && jQuery.browser.version < 7);
			
			// set all first and last li's to have appropriate classes
			jQuery('#sidebar > div:first-child, li:first-child').addClass('first');
			jQuery('#sidebar > div:last-child, li:last-child').addClass('last');
			
			// focus/blur bahavior for the invite form
			// available on any messageboard-related page (a widget)
			jQuery('#invitation_email').focus(function(){ if(this.value == 'Email'){this.value=""}}).blur(function(){ if(this.value == ''){this.value="Email"}});
			
			// search form behavior
			// available on any messageboard-related page (a widget)
			jQuery('#search input#q').focus(function(){
				if(this.value=='search...'){ this.value = ''; }
				else if(this.value==''){ this.value='search...'; }
			}).blur(function(){
				if(this.value==''){ this.value='search...'; }
			});
			
			// set all external links (in posts) to have an external class, and target="_blank"
			jQuery('#posts a[href^="http"]').addClass('external').attr('target','_blank');
		},
		
		//code that doesn't effect the look of the page (hence, "finalize")
		finalize: function()
		{		
			// console.log("Fired: THREDDED.common.finalize()");
		},
		
		// pngfix for legacy POS browsers
		// USE: THREDDED.common.pngfix('img.bigProdShot,a.thumb');
		pngfix: function(sel)
		{
			// ensure that conditional comments pull in the DD_belatedPNG js. Otherwise this will just return.
			if (typeof DD_belatedPNG == 'undefined'){
				return; 
			} else {
				// delay pngfix until window onload
				jQuery(window).load(function(){
					jQuery(sel).each(function(){
						DD_belatedPNG.fixPng(arguments[1]);
					});
				}); 
			}
		} // THREDDED.common.pngfix
		
	}, // end of THREDDED.common
	
	// ===========================================================================
	// = The following are for the pages. They're defined by the 'id' in <body>. =
	// = THREDDED.Util Looks to See What the Id is in <body> and then fires off       =
	// = the page-specific methods.                                              =
	// ===========================================================================
	
	topic_listing:{
		
		init: function()
		{
			//homepage specific PNGFIX ... same thing for the rest of the id's below, mgmt, news, etc	
			if (jQuery.browser.ie6){ /* THREDDED.common.pngfix('#'); */ }
			// console.log("Fired: THREDDED.home.init()");
		}	
		
	}, // end top_listing
	
	new_topic:{
		
		init: function()
		{
			jQuery.ajaxSetup({ 'beforeSend': function(xhr){xhr.setRequestHeader("Accept", "text/javascript")} });
			jQuery("#newPostForm #q").autocomplete('/users/search', {
				width: 260,
				multiple: true,
				selectFirst: false
			});
			jQuery('#markitup_new').markItUp(mySettings);
			jQuery('fieldset input:first').focus();
		}
		
	},
	
	search_results:{
		init: function()
		{
			// nothing here yet
		}
	},
	
	post_listing:{
		
		contents 	: jQuery('#posts .content'),
		save_links 	: null,
		
		init: function()
		{
			THREDDED.post_listing.add_private_user();
			THREDDED.post_listing.cleanup_for_user();
			THREDDED.post_listing.bind_quote_links();
			THREDDED.post_listing.bind_edit_links();
			THREDDED.post_listing.set_submit_spin();
			THREDDED.post_listing.resize_huge_images();
			THREDDED.post_listing.resize_huge_images_onResize();
			prettyPrint();
			THREDDED.post_listing.create_save_links();
			THREDDED.post_listing.setup_post_editor();
			THREDDED.post_listing.scroll_to_post();
			THREDDED.post_listing.bind_save_links();
		},

    add_private_user: function()
    {
      jQuery('#participants .add_user').click(function(){
        path = location.pathname
        path = path.replace('posts','add_user');
        form = '<form method="post" action="'+path+'"><input type="hidden" value="put" name="_method"><input type="text" name="username" id="username"></form>'
        jQuery(this).replaceWith(form);
        jQuery('#participants form input').focus();
        return false;
      });
    },
		
		cleanup_for_user: function()
		{
			if(jQuery('body.logged_in').length && jQuery('body.subject_starter').length || jQuery('body.site_administrator').length || jQuery('body.board_administrator').length || jQuery('body.g').length)
			{
				// -- set the hover class for editable titles
				$('h1 span:last').hover(
				  function(){ $(this).addClass('hover'); }, 
			      function(){ $(this).removeClass('hover'); }
			    );
				// -- make the field editable
				subject_url = window.location.href.split('/posts')[0];
				$('h1 span:last').editable(subject_url,{
					method    : "PUT", 
					style     : 'display: inline',
					tooltip   : 'Click to edit...'
				});
			}
			// -- clean stuff up
			login = jQuery('#nav .last > a').html().split('You are logged in as ')[1].toLowerCase();
			g = (jQuery('body.g').length > 0).toString();
			cleanup(login, g);
		},
		
		setup_post_editor: function()
		{
			jQuery('#markitup_reply').markItUp(mySettings);
		}, // end THREDDED.post_listing.setup_post_editor()
		
		bind_quote_links: function()
		{
			jQuery('.cleanUp a.quote').click(function(){
				jQuery.ajax({ 
					async:true, 
					url:this.href,
				   	success: function(msg)
						{ 
							eval('post='+msg);
							jQuery.scrollTo(jQuery('#replyPostForm'), 1500, {
								onAfter:function(){
									jQuery('#markitup_reply').val(post.content)
									jQuery('#markitup_reply').effect("highlight", {}, 1000);
								}
							});
						}
				});
				return false;
			});
		}, // end THREDDED.post_listing.bind_quote_links()
		
		bind_edit_links: function()
		{
			jQuery('.cleanUp a.edit').live('click', function(event){
				str = this.href.replace(/2\.com\:3000/, '')
				match_arr = str.match(/\d+/g)
				subject = match_arr[0];
				post = jQuery(this).closest('div.post')[0].id.replace(/post/,'');
				$.ajax({
				  url: "/topics/"+subject+"/posts/"+post+"/edit?e=y",
				  cache: false,
				  success: function(html){
				    html = jQuery(html).find('div.post_edit_form').html();
				    jQuery('#post'+post).html(html);
					jQuery('#post'+post+' textarea').markItUp(mySettings);
				  }
				});
				return false;
			});
		}, // end THREDDED.post_listing.bind_edit_links()
		
		resize_huge_images_onResize: function()
		{
			// -- if user resizes the window, make the larger images smaller to fit
			jQuery(window).bind('resize', function() {
				var currW = jQuery('#posts .content').width();
				jQuery('#posts .content img').each(function(){
					if(jQuery(this).width() > currW){
						jQuery(this).width(currW);
					}
				});
			});
		}, // end THREDDED.post_listing.resize_huge_images_onResize()
		
		resize_huge_images: function()
		{
			w = THREDDED.post_listing.contents.width();
			THREDDED.post_listing.contents.find('img:not([class])').each(function(){
				this.alt=jQuery(this).width();
				if(jQuery(this).width() > w){
					jQuery(this).width(w);
				}
			});
		}, // end THREDDED.post_listing.resize_huge_images()
		
		scroll_to_post: function()
		{
			if(jQuery("body[class*='scroll_to_post']").length) {
				scroll_to = jQuery("body")[0].className.split('scroll_to_post_')[1].split(' ')[0];
				jQuery.scrollTo(jQuery('#post'+scroll_to), 1500, {});
			}
		}, // end THREDDED.post_listing.scroll_to_post
		
		create_save_links: function()
		{
			content_images = THREDDED.post_listing.contents.find('img')
			content_images.wrap('<div class="image_container">');

			image_containers = THREDDED.post_listing.contents.find('.image_container');
			image_containers.append('<a href="#" class="image_save">save this image</a>');	

			THREDDED.post_listing.save_links = image_containers.find('.image_save');
			THREDDED.post_listing.save_links.each(function(){
				this.href = $(this).siblings('img')[0].src;
			});
		},
		
		bind_save_links: function()
		{
			THREDDED.post_listing.save_links.bind('click', function(){
				// ask for the name they want
				image_name = prompt('Please enter a name for this image');
				// if it's not empty, post via ajax
				if(image_name && image_name.length)
				{
					jQuery.ajax({
					      url: "/user_images/create",
					      global: false,
					      type: "POST",
					      data: ({
									url : this.href,
									name : image_name
								}),
					      dataType: "html",
					      success: function(msg){ alert(msg); }
					});
				}
				return false;
			});
		},
		
		toggle_subscriber: function()
		{
			if(jQuery('input#subscriber_watching:checked').size())
			{
				jQuery('#extra .subscribe').html('<input type="hidden" value="1" name="subscriber[forget]" /><input type="checkbox" value="0" name="subscriber[forget]" id="subscriber_forget" checked="checked" /><label for="subscriber_forget">Subscribe to newreplies via email.</label>');
				jQuery('#extra .subscribe input#subscriber_forget').attr('checked', true);
			} else if(!jQuery('input#subscriber_forget').attr('checked')) {
				jQuery('#extra .subscribe').html('<input type="hidden" value="0" name="subscriber[watching]" /><input type="checkbox" value="1" name="subscriber[watching]" id="subscriber_watching" /><label for="subscriber_watching">Subscribe to new replies via email.</label>');
				jQuery('#extra .subscribe input#subscriber_watching').attr('checked', false);
			}
		},
		
		set_submit_spin: function()
		{
			jQuery('#new_subject input[type="submit"], #replyPostForm input[type="submit"]').click(function(){
				jQuery(this).attr("disabled", "true");
				jQuery(this).closest('fieldset').addClass('faded');
				jQuery(this).closest('form').append('<img src="/images/spinna.gif" class="spinna" />');
				this.form.submit();
			});
		} // end THREDDED.post_listing.set_submit_spin()
		
	}, // end post_listing
	
	post_edit:{
		init: function()
		{
			login = jQuery('#nav .last > a').html().split('You are logged in as ')[1].toLowerCase();
			g = (jQuery('body.g').length > 0).toString();
			$('#markitup_edit').markItUp(mySettings);
			cleanup(login, g);
		}
	},
	
	admin:{
		
		init: function()
		{
			// -- change the action for the invite form when a user is selected
			$('#assign_invitations select').change(function(){
				$('#assign_invitations form')[0].action = '/users/'+ this.value +'/invitations';
			});

			// -- set the hover class for editable titles
			$('#categories li span').hover(
			  function(){ $(this).addClass('hover'); }, 
		      function(){ $(this).removeClass('hover'); }
		    );

			// -- make the field editable
			$('#categories li span').each(function(){
				$(this).editable('/categories/'+this.id,{
					method    : "PUT", 
					style     : 'display: inline',
					tooltip   : 'Click to edit...'
				});
			});

			// -- delete a category if need be
			$('a.delete').live('click', function(event) {
				if(confirm("Are you sure you want to delete this category?"))
					$.ajax({
						url: this.href,
						type: 'post',
						dataType: 'script',
						data: { '_method': 'delete' },
						async: false
					});
			});
			$('#category_name').focus(function(){ if(this.value == 'name'){this.value=""}}).blur(function(){ if(this.value == ''){this.value="name"}});
			$('#category_description').focus(function(){ if(this.value == 'description'){this.value=""}}).blur(function(){ if(this.value == ''){this.value="description"}});
			$("#login").autocomplete('/users/search', {
				width: 260,
				multiple: true,
				selectFirst: false
			});
			
		}
	}
	
} // END OF the THREDDED object literal

// ==========================================================================================
// = Here's the magic that triggers the dom ready code based on page id.                    =
// = Based on Paul Irish's exceptional code:                                                =
// = http://paulirish.com/2009/markup-based-unobtrusive-comprehensive-dom-ready-execution/  =
// ==========================================================================================
// ... don't touch everything below!  Tsk tsk.

UTIL = {

	fire: function(func,funcname, args)
	{
		var namespace = THREDDED;  // indicate your obj literal namespace here
		funcname = (funcname === undefined) ? 'init' : funcname;
		if (func !== '' && namespace[func] && typeof namespace[func][funcname] == 'function')
		{
  			namespace[func][funcname](args);
		} 
	}, // end of THREDDED.util.fire

	rand_str: function()
	{
		var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
		var string_length = 8;
		var randomstring = '';
		for (var i=0; i<string_length; i++) {
			var rnum = Math.floor(Math.random() * chars.length);
			randomstring += chars.substring(rnum,rnum+1);
		}
		return randomstring;
	}, // end of THREDDED.util.rand_str()

	loadEvents: function()
	{

		var bodyId = document.body.id;

		// hit up common first.
		UTIL.fire('common');

		//hit page specific via  body ID
		UTIL.fire(bodyId);
		UTIL.fire('common','finalize');

	}

} // end of UTIL


$(document).ready(UTIL.loadEvents);
