var $j = jQuery.noConflict();

function comment_tool(start, end) {
	var textarea = document.getElementById("comment_input_box");
	if (document.selection){
		var txt = document.selection.createRange().text;
		var newtext = start + txt + end;
		newtext = $j('form#article_comment_form textarea').val().replace(txt,newtext);
		$j('form#article_comment_form textarea').val(newtext);
	} else if (typeof textarea.selectionStart != 'undefined') {
		var before, after, selection;
		before = textarea.value.substring(0, textarea.selectionStart);
		selection = textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
		after = textarea.value.substring(textarea.selectionEnd, textarea.value.length);
		textarea.value = before + start + selection + end + after;
	}
}

$j(function(){
	$j('a[rel~="external"]').click(function() {
		window.open($j(this).attr('href'));
		return false;
	});

	$j('li#tool_bold').click(function(){
		comment_tool('**','**');
		});

	$j('li#tool_italic').click(function(){
		comment_tool('*','*');
		});

	$j('li#tool_quote').click(function(){
		comment_tool('\r\n>','\r\n\r\n');
		});

	//show all comments link
	$j('a.show_all_comments_link').click(function(){
		var id = $j(this).attr('id').replace('show_all_comments_link_','');
			$j.ajax({
		   type: "POST",
		   url: "/ajax/get_all_comments",
		   data: "id=" + id,
		   success: function(json){
				var json = eval( "(" + json + ")" );
				$j('ul#comment_list').html('');
				var results = '';
				$j.each(json.comments, function(i,comment){
				results += '<li id="' + comment.comment_ID + '">';
				results += '<p class="gravatar"><a href="/member/view/' + comment.comment_author + '"><img src="' + comment.gravatar + '" alt="" /></a></p>';
				results += '<p class="comment_citation"><cite><a href="/member/view/' + comment.comment_author + '">' + comment.comment_author + '</a></cite> at ' + comment.date + '</p>';
				results += '<div>' + comment.comment_content + '</div></li>';
				comment_count = i;
					});
					comment_count++;
				$j('ul#comment_list').html(results);
				$j('ul#comment_list li:odd').addClass('alt');
				$j('h3#comments_title').html(comment_count + ' Comments');
		   }
		 });
		});

	//clear prefilled form vars
	if ($j('input.login_form_field').length) {
		$j('input.login_form_field').click(function(){
			if ($j(this).val() == 'Username' || $j(this).val() == 'Password') {
				$j(this).val('');
			}
			});
	}

	//add link to view preview
	if ($j('tbody#the-list').length) {
		$j('tbody#the-list tr').each(function(){
			var id = $j(this).attr('id').replace('post-','');
			$j(this).children('td').children('a.view').attr({href: 'http://www.japantoday.com/single/preview/' + id, rel: 'external'});
		});
	}

	//adding moderation controls
	if ($j('ol#the-comment-list').length) {
		$j('ol#the-comment-list li').each(function(){
			var id = $j(this).attr('id').replace('comment-','');
			var moderate_link = '<p><a href="#moderate_' + id + '" class="moderate_me"><strong>MODERATE</strong></a></p>';
			$j(this).append(moderate_link);
		});
	}

	$j('a.moderate_me').live('click', function(){
		//hide all other forms
		$j('ol#the-comment-list li form').hide();
		var id = $j(this).parents('li').attr('id').replace('comment-','');
		//need to get nonce & post id etc
		//damn, I love jquery
		var moderate_form_action = $j(this).parents('li').children('p').slice(0,-1).children('span.unapprove').children('a').attr('href');
		var moderate_form = '<form class="moderate_form" id="moderate_form_' + id + '" style="display: none; padding: 10px; border: 2px solid #CCC; width: 300px; margin-bottom: 10px; background: #FFCCCC;" action="" method="get">';
		moderate_form += '<input type="radio" checked="checked" value="Off Topic" name="reason" /> Off Topic <br />';
		moderate_form += '<input type="radio" value="Impolite to other user" name="reason" /> Impolite to other user <br />';
		moderate_form += '<input type="radio" value="Offensive/vulgar" name="reason" /> Offensive/vulgar <br />';
		moderate_form += '<input type="radio" value="Racist" name="reason" /> Racist <br />';
		moderate_form += '<input type="radio" value="ALL CAPS" name="reason" /> ALL CAPS <br />';
		moderate_form += '<input type="radio" value="Duplication" name="reason" /> Duplication <br /><br />';
		moderate_form += '<input type="hidden" name="original" value="' + moderate_form_action + '" />';
		moderate_form += '<a href="' + moderate_form_action + '&reason=Off Topic">Moderate This Comment</a>';
		moderate_form += '</form>';
		$j(this).parents('li').append(moderate_form);
		$j('form#moderate_form_' + id).slideDown('slow');
		});

	$j('form.moderate_form input').live('click', function(){
		$j(this).siblings('a').attr({href: $j(this).siblings('input[name=original]').val() + '&reason=' + $j(this).val()});
	});

	//tabbed nav
	$j('ul.tabbed_nav a').click(function(){
		var id = $j(this).attr('id').replace('tabbed_nav_','');
		$j('ul.tabbed_nav li').removeClass('current_item');
		$j(this).parents('li').addClass('current_item');
		$j('div.tabbed_content_inner:visible').slideUp(function(){
			$j('div#tabbed_content_inner_' + id).slideDown();
		});
	});

	//catch on-change for newsletter
	$j('form#newsletter_opt input').click(function(){
		$j('form#newsletter_opt').submit();
		});

	//ajax form for newsletter
	$j('form#newsletter_opt').ajaxForm(function(data) {
		//don't do nuthin
	});

	//ajax form for poll
	$j('form#japantoday_poll').ajaxForm(function(data) {
		data = eval( "(" + data + ")" );
		$j('form#japantoday_poll').slideUp('slow', function(){
			var results = '<h3>' + data.poll.question + '</h3>';
			results += '<div id="poll_results" style="display: none;">';
			$j.each(data.poll.answers, function(i,answer){
				results += '<p><span style="width: ' + answer.percentage + '%"></span><strong>' + answer.percentage + '% ' + answer.answer + '</strong></p>';
				});
			results += '</div>';
			$j('div#poll_container').html(results);
			$j('div#poll_results').slideDown('slow');
			});
	});

	//preview comment
	$j('input#comment_preview_button').click(function(){
		var id = $j('input[name=post_id]').val();
		var textarea = $j('textarea#comment_input_box').val();
			$j.ajax({
		   type: "POST",
		   url: "/ajax/add_comment/preview",
		   data: "post_id=" + id + "&text=" + textarea,
		   success: function(json){
				var json = eval( "(" + json + ")" );
				var list_item = '';
				if (json.notice) {
					list_item += '<p class="warning">' + json.notice +'</p></li>';	
				} else {
					list_item += '<p class="gravatar"><a href="/member/view/' + json.username + '"><img src="' + json.gravatar + '" alt="" /></a></p>';
					list_item += '<p class="comment_citation"><cite><a href="/member/view/' + json.username + '">' + json.username + '</a> at ' + json.date;
					list_item += '</cite></p><div>' + json.text + '</div>';
				}
				//put preview at bottom of list again
				$j('ul#comment_list li#comment_preview').remove();
				$j('ul#comment_list').append('<li id="comment_preview"></li>');
				$j('ul#comment_list li#comment_preview').html(list_item);
				$j('ul#comment_list li#comment_preview').show();
		   }
		 });
		});

	//ajax form for comments
	$j('form#article_comment_form').attr('action', $j('form#article_comment_form').attr('action') + '/json');
	$j('form#article_comment_form').ajaxForm(function(data) {
		if (data) {
			data = eval( "(" + data + ")" );
			var list_item = '<li id="comment_' + data.id + '" style="display: none;">';
			if (data.notice) {
				list_item += '<p class="warning">' + data.notice +'</p></li>';	
			} else {
				list_item += '<p class="gravatar"><a href="/member/view/' + data.username + '"><img src="' + data.gravatar + '" alt="" /></a></p>';
				list_item += '<p class="comment_citation"><cite><a href="/member/view/' + data.username + '">' + data.username + '</a> at ' + data.date;
				list_item += '</cite></p><div>' + data.text + '</div></li>';
				$j('form#article_comment_form textarea').val('');
			}
			$j('ul#comment_list').append(list_item);
			if ($j('ul#comment_list li#comment_preview:visible')) {
				$j('ul#comment_list li#comment_preview').slideUp('slow', function(){
					$j('li#comment_' + data.id).slideDown('slow');
					});
			} else {
				$j('li#comment_' + data.id).slideDown('slow');
			}
		}
	});
	//print nav
	$j('a.print_button').click(function(){
			$j('ul.print_list').slideToggle('fast');
	});
	
	$j('.styleswitch').click(function()
	{
		$j('ul.print_list').slideUp('slow');
		switchStylestyle(this.getAttribute("rel"));
		window.print();
		return false;
	});
	var c = readCookie('style');
	if (c) switchStylestyle(c);
	
	
	function switchStylestyle(styleName)
	{
		$j('link[@rel*=style][@title]').each(function(i)
		{
				this.disabled = true;
				if (this.getAttribute('title') == styleName) this.disabled = false;
		});
		createCookie('style', styleName, 365);
	}

	// cookie functions http://www.quirksmode.org/js/cookies.html
	function createCookie(name,value,days)
	{
		if (days)
		{
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	function readCookie(name)
	{
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++)
		{
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	function eraseCookie(name)
	{
		createCookie(name,"",-1);
	}
	// /cookie functions

	$j('.round_corner').corner('round 8px');
	$j('.weather_round').corner('round 8px');

});