$(document).ready(function(){
	$(function() {
		prettyPrint();

		$('#flashMessage').delay(2000).fadeOut(4000);

		$('.privatemessages img').click(function(){
			var messageId = this.id;
			var popup = $( "#dialog-modal" ).dialog({
				height: 350,
				width: 800,
				modal: true,
				buttons: {
					"Reply": function() {
						window.location = '/messages/send/' + messageId + '-' + replyUsername;
					},
					"Delete": function() {
						$.ajax({
							type: "POST",
							url: '/messages/deleteSingle',
							data: 'messageId=' + messageId,
							success: function(response){
								response = jQuery.parseJSON(response);
								if(response.status == "success"){
									$('<div class="success">Message deleted</div>').insertBefore($('div [class=headertitle]')).delay(300).fadeOut(4000);
									$('#message_' + messageId).remove();
									popup.dialog('close');
								}
							},
							error:function (xhr, ajaxOptions, thrownError){

							}
						});
					},
					"Close": function() {
						$(this).dialog('close');
					}
				},
				close: function(){

				},
				open: function(){
					previewData = escape($('#ThreadBody').val());
					$.ajax({
						type: "POST",
						url: '/messages/view',
						data: 'messageId=' + messageId,
						success: function(response){
							response = jQuery.parseJSON(response);
							$('#ui-dialog-title-dialog-modal').text(response.title);
							$('#previewData').html(response.body);
							$('#' + messageId).attr('src', '/img/email2.png');
							prettyPrint();
							replyUsername = response.username;
						},
						error:function (xhr, ajaxOptions, thrownError){

						}
					});
				}
			});
		});


		myMarkdownSettings = {
		    nameSpace:          'markdown', // Useful to prevent multi-instances CSS conflict
		    previewParserPath:  '~/sets/markdown/preview.php',
		    onShiftEnter:       {keepDefault:false, openWith:'\n\n'},
		    markupSet: [
		        {name:'First Level Heading', key:"1", placeHolder:'Your title here...', closeWith:function(markItUp) { return miu.markdownTitle(markItUp, '=') } },
		        {name:'Second Level Heading', key:"2", placeHolder:'Your title here...', closeWith:function(markItUp) { return miu.markdownTitle(markItUp, '-') } },
		        {name:'Heading 3', key:"3", openWith:'### ', placeHolder:'Your title here...' },
		        {name:'Heading 4', key:"4", openWith:'#### ', placeHolder:'Your title here...' },
		        {name:'Heading 5', key:"5", openWith:'##### ', placeHolder:'Your title here...' },
		        {name:'Heading 6', key:"6", openWith:'###### ', placeHolder:'Your title here...' },
		        {separator:'---------------' },
		        {name:'Bold', key:"B", openWith:'**', closeWith:'**'},
		        {name:'Italic', key:"I", openWith:'_', closeWith:'_'},
		        {separator:'---------------' },
		        {name:'Bulleted List', openWith:'- ' },
		        {name:'Numeric List', openWith:function(markItUp) {
		            return markItUp.line+'. ';
		        }},
		        {separator:'---------------' },
		        {name:'Picture', key:"P", replaceWith:'![[![Alternative text]!]]([![Url:!:http://]!] "[![Title]!]")'},
		        {name:'Link', key:"L", openWith:'[', closeWith:']([![Url:!:http://]!] "[![Title]!]")', placeHolder:'Your text to link here...' },
		        {separator:'---------------'},
		        {name:'Quotes', openWith:'> '},
		        {name:'Code Block / Code', openWith:'(!(\t|!|`)!)', closeWith:'(!(`)!)'},
		        {separator:'---------------'},
				{name:'Preview Post', className:"preview", replaceWith: function () {
					$( "#dialog-modal" ).dialog({
						height: 350,
						width: 800,
						modal: true,
						close: function(){

						},
						open: function(){
							previewData = escape($('#ThreadBody').val());
							if($('#ThreadBody').length){
								previewData = escape($('#ThreadBody').val());
							}else if($('#MessageBody').length){
								previewData = escape($('#MessageBody').val());
							}
							$('#previewData').html('Preview loading...');
							$.ajax({
								type: "POST",
								url: '/threads/preview',
								data: 'Preview=' + previewData,
								success: function(html){
									$('#previewData').html(html);
									prettyPrint();
								},
								error:function (xhr, ajaxOptions, thrownError){

								}
							});
						}
					});
    			}}
		    ]
		}

		// mIu nameSpace to avoid conflict.
		miu = {
		    markdownTitle: function(markItUp, char) {
		        heading = '';
		        n = $.trim(markItUp.selection||markItUp.placeHolder).length;
		        for(i = 0; i < n; i++) {
		            heading += char;
		        }
		        return '\n'+heading+'\n';
		    }
		}

		$("#ThreadBody").markItUp(myMarkdownSettings);
		$("#MessageBody").markItUp(myMarkdownSettings);
		$("#ThreadBody").addClass("tabby");
		$("#MessageBody").addClass("tabby");
		$("#ThreadBody").tabby();
		$("#MessageBody").tabby();

		$('.toploginform .submit').click(function(){
			var logindata = $(this).parents('form').serialize();
			$.ajax({
				type: "POST",
				url: '/users/login',
				data: logindata,
				dataType: 'json',
				success: function(response){
					if(response.status == 'success'){
						window.location.reload();
					}else if(response.status == 'locked'){
						$('body').append('<div id="dialog-message" title="Account Locked"></div>');
						$( "#dialog-message" ).dialog({
							modal: true,
							open: function() {
								$('#dialog-message').text('This account has now been locked. An email has been sent to the account owner.');
							},
							buttons: {
								Ok: function() {
									$( this ).dialog( "close" );
								}
							}
						});
					}else{
						$('div[class=toploginform]').effect("highlight", {color: '#ff6f60'}, 1000);
					}
				},
				error:function (xhr, ajaxOptions, thrownError){
					$('div[class=toploginform]').effect("highlight", {color: '#ff6f60'}, 1000);
				}
			});
		})


		$( "#forumssortable tbody" ).sortable({
			forceHelperSize: true,
			forcePlaceholderSize: true,
			update: function(event, ui){
				var positions = $('#forumssortable tbody').sortable('serialize');
				$.ajax({
					type: "POST",
					url: '/forums/updatepositions',
					data: positions,
					dataType: 'json',
					success: function(html){
						$('#savemessage').text('Positions updated');
						$('#savemessage').addClass('success');
						$('#savemessage').fadeIn(500).delay(2000).fadeOut(500);
					}
				});


			}
		});
		$( "#forumssortable tbody" ).disableSelection();


		$( "#subforumssortable tbody" ).sortable({
			forceHelperSize: true,
			forcePlaceholderSize: true,
			update: function(event, ui){
				var positions = $('#subforumssortable tbody').sortable('serialize');
				$.ajax({
					type: "POST",
					url: '/subforums/updatepositions',
					data: positions,
					dataType: 'json',
					success: function(html){
						$('#savemessage').text('Positions updated');
						$('#savemessage').addClass('success');
						$('#savemessage').fadeIn(500).delay(2000).fadeOut(500);
					}
				});


			}
		});
		$( "#subforumssortable tbody" ).disableSelection();

		$('.markItUpHeader').append('<div style="float: right; padding-right: 5px;"><a href="#" id="formattingHelp">Formatting help</a></div>');
		$('#formattingHelp').click(function(){
			$( "#dialog-modal" ).dialog({
				height: 550,
				width: 800,
				modal: true,
				buttons: {
					"Close": function() {
						$(this).dialog('close');
					}
				},
				close: function(){

				},
				open: function(){
					previewData = escape($('#ThreadBody').val());
					$.ajax({
						type: "POST",
						url: '/threads/formattingHelp',
						data: '',
						success: function(response){
							$('#ui-dialog-title-dialog-modal').text('Formatting help');
							$('#previewData').html(response);
							prettyPrint();
						},
						error:function (xhr, ajaxOptions, thrownError){

						}
					});
				}
			});
		})
	});
});
