
var savedButtonForBindingTwo;
var isParent;
function sendCreatePost ()
{
	var button = $(this);
	savedButtonForBindingTwo = button;
	var post = button.parents('.composePost');
	var parentID = post.attr('parentid');
	var postText = post.find('.postBox').val();
	
	var parentPosition;
	if (button.hasClass('creatingReply'))
	{
		isParent = false;
		parentPosition = post.attr('parentposition');
	}
	else
	{
		isParent = true;
		parentPosition = "-1";
	}
	
	/*
	var tagsArray = new Array();
	var tagBox = post.find('.tagBox');
	var tags = tagBox.find('.tag');
	if (tags.length == 0)
	{
		post.find('.divNewTag').remove();
		var instructions = post.find('.divTaggingInstruction');
		if (instructions.length == 0)
		{
			var newInstructions = $('#templates  .divTaggingInstruction').clone(true);
			post.append(newInstructions);
		}
		return;
	}
	for (var i = 0; i<tags.length; i++)
	{
		var tempArray = new Array;
		var id = $(tags[i]).attr('tagid');
		var text = $(tags[i]).find('.tagText').html();
		tempArray.push(text);
		tempArray.push(id);
		tagsArray.push(tempArray);
	}
	*/
	var divAttachments = post.find('.divAttachments');
	var attachmentsArray = new Array;
	var attachments = divAttachments.find('.checkboxAttachment:checked');
	for (var k = 0; k<attachments.length; k++)
	{
		var tempArray = new Array;
		var attachmentType = $(attachments[k]).attr('attachmenttype');
		var attachmentLink = $(attachments[k]).attr('attachmentlink');
		var attachmentThumb = $(attachments[k]).attr('attachmentthumb');
		var attachmentTitle = $(attachments[k]).attr('attachmenttitle');
		tempArray.push(attachmentType);
		tempArray.push(attachmentLink);
		tempArray.push(attachmentThumb);
		tempArray.push(attachmentTitle);
		attachmentsArray.push(tempArray);
	}
	
	if ((attachments.length == 0) && (postText == ''))
	{
		errorToConsole ('you need at least some text or one attachment');
		return;
	}
	
	getGoogleDetection (postText, attachmentsArray, parentID, parentPosition); // callback is langDetected()
	
	var loading = $('#templates  .squareLoading').clone(true);
	loading.addClass('loadingCloned');
	$('#console').append(loading);
	
	button.unbind();	
}

function langDetected (goog, text, attachmentsArray, parentID, parentPosition)
{
	var postLanguage = goog.language;
	if (sendingFromLeft)
	{
		$.ajax({url:'post_create.php', type: 'POST', data: ({text: text, attachments:attachmentsArray, parentID: parentID, parentPosition: parentPosition, postLanguage: postLanguage}), dataType: 'json', success: postCreatedLeft, error: connectionFail});
	} else {
		$.ajax({url:'post_create.php', type: 'POST', data: ({text: text, attachments:attachmentsArray, parentID: parentID, parentPosition: parentPosition, postLanguage: postLanguage}), dataType: 'json', success: postCreated, error: connectionFail});
	}
	sendingFromLeft = false;
}

function postCreated (response,status)
{
	$('.loadingCloned').remove();
	if (status == 'success')
	{
		if (response['success'])
		{
			if (isParent)
			{
				postCreatedLeft(response,status);
				return;
			}
			$('.replyBoldRemover').removeClass('active');
			var parentPosition = response['parentPosition'];
			
			selectedPost = response['post'];		
			
			outerTreeArray.push(selectedPost);
			var position = outerTreeArray.length-1;
			
			outerTreeArray[parentPosition]['replies'].push(position);
			
			var post = makePost (selectedPost, position, 0)
			
			var postsHolder = pa.find('.posts');
			postsHolder.find('.composePost').remove();
			postsHolder.append(post);
			parentPost = post.prev();
			if (parentPost.length != 0)
			{
				repliesButton = parentPost.find('.showRepliesButton');				
				replies = parentPost.attr('replynum');
				if(replies == 0)
				{
					repliesButton.text(replyNumberOne);					
				}
				else
				{
					repliesButton.text(replyNumberMany+' ('+(parseInt(replies)+1)+')');
					repliesButton.removeClass('notClickable');
					repliesButton.addClass('bottomReplyButton');
					repliesButton.unbind();
					repliesButton.click(showRepliesClicked);					
				}
				parentPost.attr('replynum',(parseInt(replies)+1));
			}
			var notifDiv = $('#templates  .emailNotifDiv').clone(true);
			postsHolder.append(notifDiv);
			var subEmail = notifDiv.find('.submitEmail');
			var closeEmail = notifDiv.find('.closeEmail');
			var emailInput = notifDiv.find('.emailInput');
			emailInput.val(savedEmailString);
			emailInput.focus();
			subEmail.click(submitEmailHandler);
			closeEmail.click(closeEmailHandler);
			return;
		} else {
			errorToConsole ('error 037: failed to create post');
			savedButtonForBindingTwo.click(sendCreatePost);
			return;
		}
	}
	errorToConsole ('error 036: query failed');
	savedButtonForBindingTwo.click(sendCreatePost);
}

var justCreatedPost = false;
function postCreatedLeft (response,status)
{
	$('.loadingCloned').remove();
	$('.postBoxLeft').val('');
	$('.postBoxLeft').blur();
	var selectedPost = response['post'];
	var postID = selectedPost['postID'];
	justCreatedPost = true;
	//request receipt and selection from inbox (same as GET for linking to posts)
	$.ajax({url:'mini_inbox_ID.php', type: 'POST', data: ({postID: postID}), dataType: 'json', success: inboxByIDReceived, error: connectionFail});
}

function inboxByIDReceived (response,status)
{
	$('.loadingCloned').remove();
	if (status == 'success')
	{
		if (response['success'])
		{
			//CHECK IF EXISTS IN INBOX, REMOVE
			var postsArray = response['posts'];
			var thisPostID = postsArray[0]['postID'];
			var postExists = $('.inbox tr[postid="'+thisPostID+'"]');
			if (postExists.length>0)
			{
				postExists.remove();
			}
			
			var iph = $('.inboxTable');
			for(var i in postsArray)
			{
				var post = makeInboxPost(postsArray[i]);			
				iph.prepend(post);
				var inboxText = post.find('.inboxPostText');
				shorten(inboxText);
				post.click ();
			}
			
			if (justCreatedPost)
			{
				var postsHolder = pa.find('.posts');
				var notifDiv = $('#templates  .emailNotifDiv').clone(true);
				postsHolder.append(notifDiv);
				var subEmail = notifDiv.find('.submitEmail');
				var closeEmail = notifDiv.find('.closeEmail');
				var emailInput = notifDiv.find('.emailInput');
				emailInput.val(savedEmailString);
				emailInput.focus();
				subEmail.click(submitEmailHandler);
				closeEmail.click(closeEmailHandler);
				justCreatedPost = false;
			}
			
			return;
		}
	}
	errorToConsole ('error 038: failed to create post');
}

function submitEmailHandler()
{
	var button = $(this);
	var notifDiv = button.parents('.emailNotifDiv');
	var post = notifDiv.prev();
	var postID = post.attr('postid');
	var field = notifDiv.find('.emailInput');
	var email = field.val();
	
	/* VAAAALLIIIDATTEe  */
	if (!validateMail(email))
	{
		errorToConsole ('please enter a valid email');
		return;
	}	
	
	var loading = $('#templates  .squareLoading').clone(true);
	loading.addClass('loadingCloned');
	$('#console').append(loading);
	
	$.ajax({url:'submit_email.php', type: 'POST', data: ({postID: postID, email:email, ln:ln}), dataType: 'json', success: emailSubmitted, error: connectionFail});
}
function closeEmailHandler()
{
	var button = $(this);
	var notifDiv = button.parents('.emailNotifDiv');
	notifDiv.slideUp('fast');
}

function emailSubmitted (response,status)
{
	$('.loadingCloned').remove();
	if (status == 'success')
	{
		if (response['success'])
		{
			var notifDiv = $('.emailNotifDiv');
			notifDiv.slideUp('fast');
			errorToConsole (tranEmailSubmitted);
			savedEmailString = response['email'];
			return;
		} else {
			errorToConsole ('error 034: failed to submit email');
			return;
		}
	}
	errorToConsole ('error 039: query failed');
}

function validateMail(val){
   var emailPattern = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/;
   var elementValue = val;
  return (emailPattern.test(elementValue));
}
