﻿var pa;
var outerTreeArray;
var outerStoredInbox;
var transTipShow = false;
var transTipShown = false;
var savedEmailString = '';

$(document).ready(function(){
	initLang ();
	pa = $('#pa');
	/***** BINDING *****/
	$('.postBoxLeft').focus(showLeftComposeButtons);
	$('.postBoxLeft').blur(hideLeftComposeButtons);
	$('.inboxPostLinkWrapRow').mouseenter(inboxEnter);
	$('.inboxPostLinkWrapRow').mouseleave(inboxLeave);
	$('.inboxPostInfoDiv').mouseenter(inTranEnter);
	$('.inboxPostInfoDiv').mouseleave(inTranLeave);
	$('.inboxPostInfoDiv').click(inboxTransPreventOpen);
	$('.convTransDivWrap').mouseenter(cnTranEnter);
	$('.convTransDivWrap').mouseleave(cnTranLeave);
	
	drawInbox ();
	if (pid.length>0)
	{
		$.ajax({url:'mini_inbox_ID.php', type: 'POST', data: ({postID: pid}), dataType: 'json', success: inboxByIDReceived, error: connectionFail});
	}
	$.ajax({url:'cached_email.php', type: 'GET', dataType: 'json', success: changeCachedEmail, error: connectionFail});
});
function changeCachedEmail (response,status)
{
	if (status == 'success')
	{
		if (response['success'])
		{
			var savedEmail = response['email'];
			savedEmailString = savedEmail;
		}
	}
}

function inboxTransPreventOpen (e)
{
	e.stopPropagation();
}

function getTreeArray (id)
{
	$('.treeNavigationCell').hide();
	
	var openedPostId = id;
	var inboxLoadingGif = $('#templates  .squareLoading').clone(true);
	inboxLoadingGif.addClass('loadingClone');
	var postsHolder = pa.find('.posts');
	postsHolder.empty();
	postsHolder.append(inboxLoadingGif);
	$.ajax({url:'conversation_get.php', type: 'GET', data: ({postID:openedPostId}), dataType: 'json', success: drawEnter, error: connectionFail});
}

function drawInbox ()
{	
	var inboxLoadingGif = $('#templates  .squareLoading').clone(true);
	inboxLoadingGif.addClass('loadingClone');
	var liph = $('.inbox');
	liph.append(inboxLoadingGif);
	
	$.ajax({url:'inbox_get.php', type: 'GET', data: ({pageCount:pageCount}), dataType: 'json', success: drawInboxPosts, error: connectionFail});
}

var lastPostID;
function drawInboxPosts (response, status)
{
	$('.loadingClone').remove();
	if (status == 'success')
	{
		if (response['success'])
		{
			var iph = $('.inboxTable');
			iph.empty();	
			var postCount = response ['postCount'];
			lastPostID = response ['lastPostID'];	
			
			var postsArray = response['posts'];
			var post;
			for(var i in postsArray)
			{
				if (i == ((postsArray.length)-1))
				{
					firstInboxPost = true;
				}
				post = makeInboxPost(postsArray[i]);
				iph.append(post);
				var inboxText = post.find('.inboxPostText');
				shorten(inboxText);
				//post.find ('.hLimit').ellipsis();
			}
			//if last click is found, click it. If not, click the second inbox post
			//last clicked is selected in makePostsNew
			if (pid.length==0)
			{
				var lastClickedSelect = $('.lastClickedClass');
				if (lastClickedSelect.length != 0)
				{
					lastClickedSelect.click();
				} else {
					var secondPost = $('.inboxPostLinkWrapRow').first().next();
					secondPost.click();
				}				
			}
			//CLICK ON SECOND POST
			/*
			var secondPost = $('.inboxPostLinkWrapRow').first().next();
			if (pid.length==0)
			{
				secondPost.click();
			}
			*/
			receiveDelayAmount = Math.floor(Math.random() * 10000) + 5000;
			timeoutID = window.setTimeout(receiveMoreClickHandle, receiveDelayAmount);
			
			if (transTipShow)
			{
				timeoutID2 = window.setTimeout(showTransTipDiv, 2500);				
			}
			
			return;
		} else {
			errorToConsole ('error 003: unable to get posts');
			return;
		}
	}	
	errorToConsole ('error 003: query failed');	
}

function showTransTipDiv ()
{
	if (!transTipShown)
	{
		var transTipDiv = $('.transTipDiv');
		transTipDiv.slideDown();
		transTipShown = true;
	}
}
function hideTransTipDiv (btn)
{
	var button = $(btn);
	button.parents('.transTipDiv').slideUp();
}
function receiveMoreClickHandle ()
{
	playReceiveAmount = randomFromTo(2,5);
	receiveMore (playReceiveAmount);
}

function randomFromTo(from, to)
{
	return Math.floor(Math.random() * (to - from + 1) + from);
}

function receiveMore (num)
{
	var number = num;
	//var loading = $('#templates  .squareLoading').clone(true);
	//loading.addClass('loadingCloned');
	//$('#console').append(loading);
	$.ajax({url:'inbox_receive.php', type: 'GET', dataType: 'json', data: ({number:number}), success: receivedStore, error: connectionFail});
}

function receivedStore (response, status)
{
	if (status == 'success')
	{
		if (response['success'])
		{
			if (response == null)
			{
				return;
			}
			outerStoredInbox = response['posts'];
			var postCount = response ['postCount'];
			if (postCount == 0)
			{
				return;
			}
			var showMoreDiv = $('.showMoreDiv');
			var moreNumber = showMoreDiv.find('.moreNumber');
			moreNumber.html(postCount);
			if (postCount == 1) {showMoreDiv.find('.moreNumberText').html(newMessagesSingular);}
			else {showMoreDiv.find('.moreNumberText').html(newMessagesPlural);}
			showMoreDiv.slideDown();			
		} else {	
			return;
		}
	}	
}

function displayReceivedPosts ()
{
	var iph = $('.inboxTable');
	var postsArray = outerStoredInbox;
	var post;
	var IDarray = new Array();
	var inboxPostsSlider = $('#templates  .inboxPostsSlider').clone(true);
	var sliderInnerTable = inboxPostsSlider.find('.sliderInnerTable');
	for(var i in postsArray)
	{
		post = makeInboxPost(postsArray[i]);			
		sliderInnerTable.prepend(post);
		var inboxText = post.find('.inboxPostText');
		shorten(inboxText);
		var id = postsArray[i]['postID'];
		IDarray.push (id);
		//post.find ('.hLimit').ellipsis();
	}
	var showMoreDiv = $('.showMoreDiv');
	showMoreDiv.hide();
	iph.prepend(inboxPostsSlider);
	inboxPostsSlider.addClass('tempSliderClass');
	inboxPostsSlider.find('.classForInboxSlide').slideDown(400, moveInboxPosts);	
	
	//To move from BUFFER to INBOX	
	$.ajax({url:'buffer_to_inbox.php', type: 'GET', dataType: 'json', data: ({IDarray:IDarray}), error: connectionFail, success: function(response, status){if (status == "success"){if(response['success']){receiveDelayAmount = Math.floor(Math.random() * 10000) + 5000;
																																			timeoutID = window.setTimeout(receiveMoreClickHandle, receiveDelayAmount);}}}});
}

function moveInboxPosts ()
{
	var slider = $('.tempSliderClass');
	var iph = $('.inboxTable');
	var posts = slider.find('.inboxPostLinkWrapRow');
	iph.prepend(posts);
	slider.remove();
}

/*
OLD WAY TO RECEIVE - DIRECTLY DISPLAY AFTER CLICK
function received (response, status)
{
	$('.loadingCloned').remove();
	if (status == 'success')
	{
		if (response['success'])
		{
			var iph = $('.inboxTable');
			if (response == null)
			{
				return;
			}
			var postCount = response ['postCount'];
			if (postCount == 0)
			{				
				var errorText = langNoMorePosts;				
				errorToConsole (errorText);				
				return;	
			}
			else {
				var postsArray = response['posts'];
				var post;
				for(var i in postsArray)
				{
					post = makeInboxPost(postsArray[i]);			
					iph.prepend(post);
					var inboxText = post.find('.inboxPostText');
					shorten(inboxText);
					//post.find ('.hLimit').ellipsis();
				}
			}
			return;
		} else {				
			var errorText = langNoMorePosts;				
			errorToConsole (errorText);				
			
			return;
		}
	}
	errorToConsole ('error 058: query failed');
}*/

function shorten (spn)
{
	var span = spn;
	var text = span.text();
	var sln = text.length;
	var newString = text.substring(0,140);
	if (sln > 140)
	{
		newString = newString+'...';
	}
	span.attr('posttext',newString);
	span.html(newString);
}


/***** INBOX JS *****/
function transferCompose (btn)
{
	composeView();
	
	var button = $(btn);	
	var boxLeft= $('.postBoxLeft');
	var composePost = $('.forTransfer');
	var boxRight = composePost.find('.postBox');
	
	var leftText = boxLeft.val();
	boxRight.val(leftText);
	boxLeft.val('');
	$('.leftPostingButtons').hide();
	var aType = button.attr('aType');
	var attachIcon;
	createUploader();
	if (aType == 'vid')
	{
		attachIcon = composePost.find('.iconVideo');
		attachIcon.click();
	}
	if (aType == 'pic')
	{
		attachIcon = composePost.find('.iconPicture');
		attachIcon.click();
	}
	if (aType == 'lin')
	{
		attachIcon = composePost.find('.iconLink');
		attachIcon.click();
	}	
}

function showLeftComposeButtons ()
{
	var leftDiv = $('.leftPostingButtons');
	leftDiv.slideDown();
}
function hideLeftComposeButtons ()
{
	if ($('.postBoxLeft').val() == '')
	{
		var leftDiv = $('.leftPostingButtons');
		leftDiv.slideUp();
	}
}

// entering post
function inboxEnter(obj)
{
	var row = $(this);
	var icon = row.find('.tranIconInbox');
	icon.show();
}
function inboxLeave()
{
	var row = $(this);
	var icon = row.find('.tranIconInbox');
	icon.hide();
}

// entering trans
function inTranEnter ()
{
	var icon = $(this);
	var cell = icon.parents ('.inboxPostInfo');
	var div = cell.find('.langMenu');
	div.show();
}

function inTranLeave ()
{
	var icon = $(this);
	var cell = icon.parents ('.inboxPostInfo');
	var div = cell.find('.langMenu');
	div.hide();
}
function cnTranEnter ()
{
	var icon = $(this);
	var cell = icon.parents ('.postTopRightDiv');
	var div = cell.find('.langMenu');
	/** fix for layering **/
	var post = icon.parents('.post');
	var nextPost = post.next();
	var nextIcon = nextPost.find('.tranIconConv');
	nextIcon.css('z-index','1300');
	/**/
	
	
	div.show();
}

function cnTranLeave ()
{
	var icon = $(this);
	var cell = icon.parents ('.postTopRightDiv');
	var div = cell.find('.langMenu');
	/** fix for layering **/
	var post = icon.parents('.post');
	var nextPost = post.next();
	var nextIcon = nextPost.find('.tranIconConv');
	nextIcon.css('z-index','1500');
	/**/
	
	div.hide();
}

//
var sendingFromLeft = false;
function leftPostClicked ()
{
	var parentID = 'first';
	var parentPosition = "-1";
	var postText = $('.postBoxLeft').val();
	var attachmentsArray = new Array;
	
	//IF EMPTY
	
	getGoogleDetection (postText, attachmentsArray, parentID, parentPosition); // callback is langDetected()
	
	var loading = $('#templates  .squareLoading').clone(true);
	loading.addClass('loadingCloned');
	$('#console').append(loading);
	sendingFromLeft = true;
}

function composeView () 
{	
	var postsHolder = pa.find('.posts');
	postsHolder.empty();
			
	var replyBox = $('#templates > .composePostTemplate').clone(true,true);
	replyBox.removeClass('composePostTemplate');
	replyBox.addClass('composePost');
	replyBox.addClass('post');
	replyBox.attr('parentid','first');
	replyBox.addClass('forTransfer');
	//replyBox.find('.tagBox').click(addField);
	var button = replyBox.find('.postSendButton');
	button.addClass('creatingParent');
	button.click(sendCreatePost);
	postsHolder.append(replyBox);
	replyBox.find('.postBox').focus();	
	if ($.browser.msie)
	{
		replyBox.css('border','2px solid #ccc');
	}
}

/****** VOTING *******/
function votingArrowClicked (arw)
{
	var arrow = $(arw);
	if (!arrow.hasClass('votingArrowBefore'))
	{
		return;
	}
	var post = arrow.parents('.post');
	var postID = post.attr('postid');
	var voteSpan = arrow.parents('.votingDiv').find('.postVotesSpan');
	var currentVote = voteSpan.text();
	var currentVoteInt = parseInt (currentVote);
	var newVote = currentVoteInt+1;
	voteSpan.text(newVote);
	arrow.attr('src','./pics/upBlue.png');
	arrow.removeClass('votingArrowBefore');
	$.ajax({url:'forward_post.php', type: 'GET', dataType: 'json', data: ({postID:postID}), success: voteSubmitted, error: connectionFail});
}

function voteSubmitted (response,text)
{
	
}

function openAboutPopup()
{
	bodyScrollPopup = $(window).scrollTop();
	popupWrapper = $('.popupWrapperAbout');
	fixedWrapper = $('.fixedWrapper');
	fixedWrapper.addClass('fixedActive');
	$(window).scrollTop(0);	
	popupWrapper.show();
	var windowH = $(window).height();
	var popupBackground = popupWrapper.find('.popupBackground');
	popupBackground.css('min-height',windowH);
}

function closeAboutPopup ()
{
	fixedWrapper.removeClass('fixedActive');
	popupWrapper.hide();
	$(window).scrollTop(bodyScrollPopup);
}
