/**
 * @author Brandon Aaskov
 */


var isIE6 = false;

$(document).ready(function()
{
	if(jQuery.browser.msie && jQuery.browser.version < 7) isIE6 = true;
	Navigation.init();
	Search.init();
	Newsletter.init();
	Profile.init();
	Page.init();
});

var Navigation = 
{
	init: function()
	{
		$('#navigation li.active').prev().css('border-right', 'none');
		$('#navigation li:last').css('border-right', 'none');
		$('#navigation li.active').prepend("<img class='tab-top-left' src='/img/tab-top-left.gif' alt='tab corner' />");
		$('#navigation li.active').prepend("<img class='tab-top-right' src='/img/tab-top-right.gif' alt='tab corner' />");
		var tabWidth = $('#navigation li.active').outerWidth() - $('#navigation li.active img.tab-top-right').width();
		$('#navigation li.active img.tab-top-right').css('left', tabWidth);
	}
}

var Search = 
{
	init: function()
	{
		$('input.search').focus(function()
		{
			$(this).val('');
		});
	}
}

var Newsletter = 
{
	init: function()
	{
		if(!isIE6) $('#newsletter').validate();
		$('#newsletter-signup input.email').focus(function()
		{
			$(this).val('');
		});
	}
}

var Profile =
{
	init: function()
	{
		if(!isIE6) $('#signIn').validate();
		$('div.login input.username').focus(function()
		{
			$(this).val('');
		});
		
		$('div.login input.password').focus(function()
		{
			$(this).val('');
		});
	},
	
	login: function()
	{
		Profile.switchModules(false);
		var params = {
			username: $('div.login input.username').val(),
			password: $('div.login input.password').val()
		};
		var url = "/live?func=login&js_login=3&callback=?";
		
		$.get(url, params, function(pData)
		{
			if(pData.Name) 
			{
				Profile.updateStats(Profile.buildStats(pData));
				Profile.switchModules(true);
			}
			else if(pData.Error) 
			{
				$('body').append("<form action='"+pData.Redirect+"' method='post' style='display: none;' id='loginError'><input type='hidden' name='js_login_error' value=\""+pData.Error+"\" /></form>");
				$('#loginError').submit();
			}
		}, "json");
	},
	
	switchModules: function(pComplete)
	{
		if(pComplete) 
		{
			$('#profile img.loading').remove();
			($('div.stats:hidden')) ? $('div.stats').fadeIn("slow") : $('div.stats').fadeOut("slow");
			($('div.functions:hidden')) ? $('div.functions').fadeIn("slow") : $('div.functions').fadeOut("slow");
		}
		else
		{
			$('div.login').toggle();
			$('div.login-functions').toggle();
			$('#profile').prepend("<img class='loading' src='/img/ajax-loader.gif' alt='loading' />");
		}
	},
	
	buildStats: function(pResponse)
	{
		var stats = 
		{
			message: pResponse.RandomWelcome,
			username: pResponse.Name,
			rank: pResponse.CurrentRank,
			zugs: pResponse.NextRank,
			currentFunniest: pResponse.TopRanking,
			funniest: (pResponse.CurrentTopRankingUser) ? pResponse.CurrentTopRankingUser : null
		};		
		return stats;
	},
	
	updateStats: function(pStats)
	{
		$('div.stats span.welcome').html(pStats.message+' <em>'+pStats.username+'</em>');
		$('div.stats span.rank em').html(pStats.rank);
		$('div.stats span.next-level em').html(pStats.zugs+' Zugz');
		$('div.stats span.current-level em').html(pStats.currentFunniest);
		if(pStats.funniest) $('div.stats span.next-level').html(pStats.funniest);
	}
}

var Page = 
{
	init: function()
	{
		if($('body#home').length > 0) Page.updateHomepage();
		else if($('#left_column').length > 0) Page.updatePageHeight();
		if($('body.create').length > 0) Page.createInit();
		if($('div#icons ul').length > 0) EditProfile();
		if($('form.filter').length > 0) Page.sortFormsInit();
		if($('#zug_rankings').length > 0) Page.rankingsInit();
		if($('body#zug_live').length > 0) Page.zugLiveInit();
		if($('body#featured').length > 0) Page.zugLiveInit();
		if($('body#existing_content').length > 0) Page.existingContentInit();
		
		if (jQuery('div.rating').length > 0) 
		{
			jQuery.getScript('/js/jquery-ui-dialog-packed.js');
			jQuery.each(jQuery('div.rating'), function(){
				new RatingBar(this);
			});
		}
	},
	
	updateHomepage: function()
	{
		jQuery.each($('span.parts'), function()
		{
			$(this).children('a:last').css('border', 'none');
		});
		
		
		$('#main_content #right_column ul:last').css('border', 'none');
	},
	
	updatePageHeight: function()
	{
		var height = ($('#right_column').outerHeight() > $('#left_column').outerHeight()) ? $('#right_column').outerHeight() : $('#left_column').outerHeight();
		$('#main_content').height(height);
	},
	
	createInit: function()
	{
		//$.getScript('./js/jquery-ui-personalized-1.5.3.min.js');
		var cssTag = "<link rel='stylesheet' type='text/css' href='/css/jquery-ui-themeroller.css' />";
		$('head').append(cssTag);

		window.onselect = function(pEvent)
		{
			TextEditorSelection(pEvent);
		};
		
		$("#"+Page.getFormId()).find("textarea.textInput").focus(function()
		{
			var dummyObject = 
			{
				target: this
			}
			TextEditorSelection(dummyObject);
			
			if($.browser.msie) //workaround for IE issue
			{
				if ((TextEditorTags.startTag && TextEditorTags.startTag.indexOf("url") !== -1) || (TextEditorTags.startTag && TextEditorTags.startTag.indexOf("image") !== -1)) 
				{
					var newText = TextEditorTags.startTag + document.selection.createRange().text + TextEditorTags.endTag;
					document.selection.createRange().text = newText;
				}
			}
		});
		
		$("#"+Page.getFormId()).find("textarea.textInput").blur(function(pEvent)
		{
			//TextEditorTags.ieCursorPosition = document.selection.createRange().text;
			//alert(document.selection.createRange().text);
		});
		
		Page.doubleTextBoxSize();

		Page.setupToolbar(Page.getFormId());
		
		var titles = 
		{
			vs: 'Comedy Challenge',
			article: 'Comedy Article',
			capcon: 'Caption Contest',
			conversation: 'Comedy Conversations',
			link: 'Funny Link'
		};	
		
		$('#choice select').change(function()
		{		
			var formId = Page.getFormId();
			
			jQuery.each($('#left_column form.create'), function()
			{
				$(this).hide();
			});
			jQuery.each($('a.help'), function()
			{
				$(this).hide();
			});
			jQuery.each($('div.info ul'), function()
			{
				$(this).hide();
			});
			
			$('#help_text div.info').hide();
			$('a.'+formId).show(); //change help link
			$('ul.'+formId).show(); //change help text block
			$('#'+formId).show("normal"); //change form
			Page.setupToolbar(formId);
			Page.doubleTextBoxSize();
			
			$('#thread_type').html(titles[$('#choice select option:selected').val()]);
			$('#thread_type').attr('class', '').addClass($('#choice select option:selected').val());
		});
	},
	
	doubleTextBoxSize: function()
	{
		$("#"+Page.getFormId()).find("textarea.textInput").scroll(function()
		{
			if(this.offsetHeight < this.scrollHeight) $(this).height(this.offsetHeight * 2)
		});
	},
	
	setupToolbar: function(pFormId)
	{
		//may need to set this up for the new rte
		//(pFormId !== 'article') ? console.log("do basic version") : console.log("do full version");
	},
	
	showHelpText: function()
	{
		jQuery.each($('div.info ul'), function()
			{
				$(this).hide();
			});
		$('ul.'+Page.getFormId()).show(); //change help text block
		$('#help_text div.info').toggle("slide", { direction: "up" }, 1000);
	},
	
	createFormSubmit: function()
	{
		$(Page.getFormId()).submit();
	},
	
	sortFormsInit: function()
	{
		$('form.filter select.show').change(function()
		{
			$('form.filter').submit();
		});
		$('form.filter select.sort').change(function()
		{
			$('form.filter').submit();
		});
	},
	
	rankingsInit: function()
	{
		//updates the list heights in case the h2s are wrapping
		$.each($('ol li'), function()
		{
			var listHeight = $(this).outerHeight();
			var listItem = $(this);
			$.each($(this).children('h2'), function()
			{
				var h2Height = $(this).outerHeight();
				if($(this).css('top') == "30px") h2Height += 30;
				if(h2Height > listHeight) listItem.height(h2Height);
			});
		});
		
		if($('div.buttons a').length == 2) $('a#next').css('left', '225px');
	},
	
	zugLiveInit: function()
	{
		if($('div.buttons a').length < 3) $('div.buttons a#create').css('margin-left', '168px');
	},
	
	existingContentInit: function()
	{
		/*
		var tableTags = $('p').attr('align').children('table');
		console.log(tableTags.length);
		
		$.each(tableTags, function()
		{
			console.log("found the table tag");
			$(this).attr('align', 'center');
		});
		*/
	},
	
	previewForm: function()
	{
		$(Page.getFormId()).attr();
	},
	
	getFormId: function()
	{
		if($('#choice').length > 0) return $('#choice select option:selected').val();
		else return "preview";
	}
};

EditProfile = function()
{
	jQuery.getScript('/js/jQuery.color.js');
	//any setup required for the edit profile page
	$('#left_column h2:first').css('border', 'none');
	$('#left_column h4:last').css('vertical-align', 'baseline');

	$("#editProfile").validate();

	$('form input, form textarea').focus(function()
	{
		$(this).addClass('highlight');
	}).blur(function(){
		$(this).removeClass('highlight');
	});
	
	jQuery.each($('ul.sites li'), function()
	{
		$(this).children('select.sites').change(function()
		{
			if ($('ul.sites li').length < 5) 
			{
				$('ul.sites').append($('ul.sites li:last').clone(true));
				var siteNumber = Number($('ul.sites li:last h4 em').text());
				var nextNumber = (siteNumber < 10) ? "0" + (siteNumber + 1) : siteNumber + 1;
				$('ul.sites li:last h4 em').html(nextNumber);
				$('ul.sites li:last')
					.css('backgroundColor', '#fff880')
					.animate(
						{
							backgroundColor: '#ffffff'
						}, 800);
				$('ul.sites li:last input').val('http://').css('color', '#666');
			}
		});
	});
	
	jQuery.each($('ul.sites li'), function()
	{
		$(this).children('input').focus(function()
		{
			$(this).css('color', '#666');
		});
	});
};


RatingBar = function(pRatingBlock)
{
	var fileExtension = (isIE6) ? "gif" : "png";
	var chosen = this.chosen = false;
	var currentLevel = $(pRatingBlock).children('span.level').text();
	var ratingReceived = ($(pRatingBlock).children('span.message').length > 0) ? true : false;
	chosen = (ratingReceived) ? true : false;
	
	var levels = 
	{
		1: "Amusing",
		2: "Chuckleworthy",
		3: "Funny",
		4: "Hilarious",
		5: "Side-splitting"
	}
	
	init = function()
	{
		if(ratingReceived) $(pRatingBlock).children('span.level').text("Rating Received")
		var average = $(pRatingBlock).children('span.average').text();
		jQuery.each($(pRatingBlock).children('span.box'), function()
		{
			if(chosen) $(this).css("cursor", "default");
			
			if ($(this).attr('name') <= average) $(this).css('background-image', 'url(/img/rating-yellow-full.png)');
			else $(this).css('background-image', 'url(/img/rating-empty.png)');
		});
	}();
	
	var showDialog = function(pHTML)
	{
		var textToDisplay = (chosen) ? "You've Already Rated This One" : $(pRatingBlock).children('span.message').html();
		if(pHTML) textToDisplay = pHTML;
		//$('body').append("<div id='modalpop' title='Rating Error!'>"+textToDisplay+"</div>").modal({});
		
		//alert(textToDisplay);
		$("h1.AlreadyRated").show();
		$("#modalpop").modal({});
		//jQuery.modal({});

		
//		$('body').append("<div id='dialog' title='Rating Error!'>"+textToDisplay+"</div>");
//		$("#dialog").dialog(
//		{ 
//		    modal: true, 
//		    overlay: 
//			{ 
//		        opacity: 0.7, 
//		        background: "black" 
//		    },
//			close: function()
//			{
//				$("#dialog").dialog('destroy');
//			}
//		});
	}
	
	$(pRatingBlock).children('span.box').mouseover(function()
	{
		if(!chosen) 
		{
			var currentNumber = $(this).attr('name');
			$(pRatingBlock).children('span.level').text(levels[currentNumber]);
			jQuery.each($(pRatingBlock).children('span.box'), function()
			{
				if ($(this).attr('name') <= currentNumber) $(this).css('background-image', 'url(/img/rating-yellow-full.'+fileExtension+')');
				else $(this).css('background-image', 'url(/img/rating-empty.'+fileExtension+')');
			});
		}
	})
	.click(function()
	{	
		if(ratingReceived) showDialog(); //already logged in and already rated
			//$("h1.YourPostRating").show();
			//$("#modalpop").modal({});		
		else if($(pRatingBlock).children('span.redirect').length > 0) //not logged in
		{
			//var dialogCode = "You are currently not logged in.<br />Click <a href='"+$(pRatingBlock).children('span.redirect').text()+"'>here</a> to register an account."
			//showDialog(dialogCode);
			$("h1.LoginToRate").show();
			$("#modalpop").modal({});
		}
		else if(!chosen) //logged in, and not rated (even since page load)
		{
			var currentNumber = $(this).attr('name');
			var url = "/live?func=rate_msg&callback=?";
			var params = 
			{
				rating: currentNumber,
				msg_id: $(pRatingBlock).children('span.message_id').text()
			};
			
			$(pRatingBlock).fadeOut("normal", function()
			{
				$.get(url, params, function(pResponse)
				{
					if(pResponse) 
					{
						/* pResponse:
						 * CurrentRating
						 * MsgID
						 * SubmittedRating
						 * TotalNumVotes
						 */
						var tenthsPlace = String(pResponse.CurrentRating).substr(2, 1);
						var roundedRating = Math.round(pResponse.CurrentRating);
						var image = (tenthsPlace < 7 && tenthsPlace > 2) ? 'url(/img/rating-orange-half.'+fileExtension+')' : 'url(/img/rating-orange-full.'+fileExtension+')';
						
						jQuery.each($(pRatingBlock).children('span.box'), function()
						{
							if (pResponse.CurrentRating < 0.5 && $(this).attr('name') == 1) $(this).css('background-image', 'url(/img/rating-orange-half.'+fileExtension+')');
							else if ($(this).attr('name') < roundedRating) $(this).css('background-image', 'url(/img/rating-orange-full.'+fileExtension+')');
							else if ($(this).attr('name') <= roundedRating) $(this).css('background-image', image);
							else $(this).css('background-image', 'url(/img/rating-empty.'+fileExtension+')');
						});
						$(pRatingBlock).children('span.level').text(levels[roundedRating]);
						$(pRatingBlock).children('span.total').children('em').text(pResponse.TotalNumVotes);
						$(pRatingBlock).fadeIn("normal"); //fade the bar back in
					}
					else
					{
						$(pRatingBlock).fadeIn("normal");
					}
				}, "json");
			});
			chosen = true;
		}
		else showDialog(); //already rated and chosen == true (no page reload);
	});
	
	$(pRatingBlock).mouseout(function()
	{
		if(!chosen) 
		{
			var average = $(pRatingBlock).children('span.average').text();
			$(pRatingBlock).children('span.level').text(currentLevel);
			jQuery.each($(pRatingBlock).children('span.box'), function()
			{
				if($(this).attr('name') <= average) $(this).css('background-image', 'url(/img/rating-yellow-full.png)');
				else $(this).css('background-image', 'url(/img/rating-empty.png)');
			});
		}
	});
}


function TextEditorSelection(pEvent)
{
	var bp = Page.getFormId();
	TextEditorTags.currentTextArea = document.getElementById(Page.getFormId()).getElementsByTagName('textarea')[0]; 				
	TextEditorTags.startSelection = pEvent.target.selectionStart;
	TextEditorTags.endSelection = pEvent.target.selectionEnd;
	TextEditorTags.entireString = pEvent.target.value; //actually gets overridden in the TextEditorTags.tagSection() method 
	TextEditorTags.tagged = false;
}

var TextEditorTags =
{	
	currentTextArea: null,
	startTag: null,
	endTag: null,
	startSelection: null,
	endSelection: null,
	entireString: null,
	tagged: false,
	url: null,
	image: null,
	modalWindow: null,
	flashResponseTimer: null,
	
	tagSection: function()
	{
		//if(this.startTag.indexOf("[url]") == -1 || this.startTag.indexOf("[image]") == -1) 
		
		if(!this.tagged) 
		{
			if($.browser.msie) 
			{
				var selectedText = document.selection.createRange().text;
				
				if(this.startTag.indexOf("[list]") !== -1) 
				{
					$("#"+Page.getFormId()).find("textarea.textInput").focus();
					selectedText = selectedText.replace(/\n/g, "\n[*]");
					document.selection.createRange().text = this.startTag + "[*]" + selectedText + this.endTag;
				}
				else if(this.startTag.indexOf("[url]") == -1 || this.startTag.indexOf("[image]") == -1)
				{	
					var newText = this.startTag + selectedText + this.endTag;
					document.selection.createRange().text = newText;
				}
			}
			else 
			{
				$("#"+Page.getFormId()).find("textarea.textInput").focus();
				
				this.entireString = this.currentTextArea.value;
				
				var stSel = this.startSelection;
				var endSel = this.endSelection;
				
				var taggedSection = this.startTag + this.entireString.substring(this.startSelection, this.endSelection) + this.endTag;
				var beginningSection = this.entireString.substring(0, this.startSelection);
				var endSection = this.entireString.substring(this.endSelection);
				
				if(this.startTag.indexOf("[list]") !== -1) 
				{
					taggedSection = taggedSection.replace(/\n/g, "\n[*]");
				}
				
				var newPhrase = beginningSection + taggedSection + endSection;
				this.currentTextArea.value = newPhrase;
				var newPos = endSel + this.startTag.length + this.endTag.length;
				this.currentTextArea.setSelectionRange(newPos,newPos);
				this.tagged = true;
			}
		}
	},
	
	openDialog: function(pPage)
	{
		//------------------- reset values
		TextEditorTags.image = null;
		TextEditorTags.url = null;
		//-------------------
		
		var page;
		var options;
		
		switch(pPage)
		{
			case "URL":
				page = "/js/url_form.html";
				TextEditorTags.url = null;
				options = 
				{
					height: 200,
					width: 500,
					modal: true,
					resizable: true,
					buttons: 
					{
						'Create URL': function()
						{
							if($("#url_value").val() && $("#url_value").val().length > 10 && $("#url_value").val().indexOf("http://") != -1)  
							{
								TextEditorTags.url = $("#url_value").val();
								$("#url_value").remove();
								$(this).dialog('close');
							}
							else
							{
								alert("Sorry, you need to enter a valid URL.");
							}
						},
						Cancel: function()
						{
							$(this).dialog('close');
						}
					},
					close: function(pEvent, pUI)
					{
						if(TextEditorTags.url) TextEditorTags.setTags("URL", TextEditorTags.url);
					}
				};
				break;
			case "IMAGE":
				page = "/js/image_form.html";
				TextEditorTags.image = null;
				options = 
				{
					height: 275,
					width: 500,
					modal: true,
					resizable: true,
					buttons: 
					{
						'Insert Image': function()
						{
							//console.log("VALUE IS: "+$("#image_url").val());
							if($("#image_url").val() && $("#image_url").val().indexOf("http://") != -1 && !TextEditorTags.image) 
							{
								TextEditorTags.image = $("#image_url").val();
								$("#image_url").attr("disabled", "disabled");
								
								var postData = 
								{
									func: "msg_img",
									Image: TextEditorTags.image,
									callback: "TextEditorTags.onImageURLResponse"
								};
								
								$.post("/live", postData, function(pData)
								{
									eval(pData);
								});
							}
							else
							{
								alert("Sorry, you need to enter a valid image URL.");
							}
						},
						Cancel: function()
						{
							$(this).dialog('close');
						}
					},
					close: function(pEvent, pUI)
					{
						if(TextEditorTags.image) TextEditorTags.setTags("IMAGE", TextEditorTags.image);
						TextEditorTags.url = null;
						TextEditorTags.image = null;
					}
				};
				break;
			default:
				throw new Error("This page for a dialog box doesn't exist");
		}
		
		$.get(page, function(data)
		{
			var modalDialog = $(data).dialog(options);
			TextEditorTags.modalWindow = $(modalDialog);	
			
			//TextEditorTags.flashResponseTimer = window.setInterval(TextEditorTags.checkForFlashResponse, 800);
		});
	},
	
	closeWindow: function()
	{
		$(TextEditorTags.modalWindow).dialog('close');
	},
	
	urlSubmit: function()
	{
		if($("#url_value").val() && $("#url_value").val().length > 10 && $("#url_value").val().indexOf("http://") != -1) 
		{
			TextEditorTags.url = $("#url_value").val();
			$("#url_value").remove(); //ADDED
			$(TextEditorTags.modalWindow).dialog('close');
		}
		else
		{
			alert("Sorry, you need to enter a valid URL.");
		}
	},
	
	onImageURLResponse: function(pData)
	{
		if(pData.Success) 
		{
			TextEditorTags.image = pData.Success;
			$("#image_url").remove();
			$(TextEditorTags.modalWindow).dialog('close');
			//TextEditorTags.setTags("IMAGE", pData.Success)
		}
		else if(pData.Error)
		{
			$("#image_form").html(pData.Error).css("color", "#FF0000").width("90%");
			TextEditorTags.image = null;
		}
	},
	
	/*
	checkForFlashResponse: function()
	{
		var responseNumber = $("#imageUploader").contents().find("#response").text();
		console.log("RESPONSE NUMBER: "+responseNumber);
		if(responseNumber)
		{
			window.clearInterval(TextEditorTags.flashResponseTimer);
			$("#imageUploader").contents().find("#response").text("");
			TextEditorTags.onImageURLResponse(Number(responseNumber));
		}
	},
	*/
	
	setTags: function(pTagType, pValue)
	{
		if(!pValue) pValue = "";
		
		switch(pTagType)
		{
			case "BOLD":
				this.startTag = "[b]";
				this.endTag = "[/b]";
				break;
			case "ITALIC":
				this.startTag = "[i]";
				this.endTag = "[/i]";
				break;
			case "UNDERLINE":
				this.startTag = "[u]";
				this.endTag = "[/u]";
				break;
			case "STRIKE":
				this.startTag = "[strike]";
				this.endTag = "[/strike]";
				break;
			case "ACTION":
				this.startTag = "[action]";
				this.endTag = "[/action]";
				break;
			case "URL":
				this.startTag = '[url='+pValue+']';
				this.endTag = "[/url]";
				break;
			case "LIST":
				this.startTag = "[list]\n";
				this.endTag = "\r[/list]";
				break;
			case "IMAGE":
				this.startTag = "[image]"+pValue;
				this.endTag = "[/image]";
				break;
			case "HEADING":
				this.startTag = "[heading]";
				this.endTag = "[/heading]";
				break;
			case "QUOTE":
				this.startTag = "[quote]";
				this.endTag = "[/quote]";
				break;
			case "CAPTION":
				this.startTag = "[caption]";
				this.endTag = "[/caption]";
				break;
			default:
				throw new Error("This tag type has not been defined: "+pTagType);
		};
		
		TextEditorTags.tagSection();
	}
};