function DidClickOnLock()
{
	if (!lsclient.IsSyncQueueEmpty())
		ShowUnsavedDocMsg();
	else document.lock.submit();
}

function CanCloseDocument()
{
	if (!lsclient.IsSyncQueueEmpty())
	{
		ShowUnsavedDocMsg();
		return false;
	}
	else return true;
}

function callInProgress(xmlhttp)
{
	switch (xmlhttp.readyState)
	{
	case 1:
	case 2:
	case 3:		return true;
				break;
	
	default:
	case 0:		return false;			// Case 4 and 0
				break;
	}
}

function HandleDisconnection()
{
	StopLockUpdater();
}

function ShowExpiredLockMsg()
{
	document.getElementById('expired-lock-msg').style.display = 'block';
	document.getElementById('fade').style.display = 'block';
}

function ShowOutOfSyncMsg()
{
	document.getElementById('outofsync-msg').style.display = 'block';
	document.getElementById('fade').style.display = 'block';
}

function ShowErrorMsg(msg)
{
	document.getElementById('error-msg-text').innerHTML = msg+'<br /><br />Please click on the Refresh Document button to refresh the page and continue working.';
	document.getElementById('error-msg').style.display = 'block';
	document.getElementById('fade').style.display = 'block';
}

function ShowUnsavedDocMsg()
{
	document.getElementById('unsaved-msg').style.display = 'block';
	document.getElementById('fade').style.display = 'block';
}

function HideUnsavedDocMsg()
{
	document.getElementById('unsaved-msg').style.display = 'none';
	document.getElementById('fade').style.display = 'none';
}

function ShowProFeatureMsg()
{
	document.getElementById('pro-feature-msg').style.display = 'block';
	document.getElementById('fade').style.display = 'block';
}

function HideProFeatureMsg()
{
	document.getElementById('pro-feature-msg').style.display = 'none';
	document.getElementById('fade').style.display = 'none';
}

function ShowUserOfflineMsg()
{
	document.getElementById('user-offline-msg').style.display = 'block';
}

function HideUserOfflineMsg()
{
	document.getElementById('user-offline-msg').style.display = 'none';
}

function HideMessage()
{
	$jq('#message').hide();
}

UpdateLock=function()
{
	var params = "{session_id: '" + gSessionId + "'}";
	new Ajax.Request("/api/outlines/"+gOutlineId+"/getLockStatus.json",
	{
		method: 'GET',
		parameters: { 'params': JSON.stringify(params.evalJSON()) },
		onFailure: function() { /* do nothing */ },
		onSuccess: function(transport) {
			UpdateLockCallBack(transport);
		}
	});

	gLockTimer = setTimeout(UpdateLock, 10000);						// update lock every 10 seconds
}

// this function is called at a regular interval (via AJAX)
// it checks if the lock status has changed. If it has, it updates the lock button
UpdateLockCallBack=function(t)
{
var responseText = t.responseText.evalJSON();
var response = responseText.lock_status;

var lock_action = document.getElementById('lock_action');
var lock_button = document.getElementById('lock_button');

	if (response == 'unlocked')				// no one is editing the outline, we can edit it if we like
	{
		lock_action.value = 'do_edit';
		lock_button.className = "btn_lock_active";
		lock_button.onclick = StartEditing;
		
		if (gLockStatus == 'locked_to_me')		// you were editing the outline, but the lock has expired
		{
			ShowExpiredLockMsg();
			clearTimeout(gLockTimer);
		}
		else
		{
			document.getElementById('message-text').innerHTML = 'The document is no longer being edited by anyone. To start editing, click on the Edit Document button.';
			document.getElementById('message-icn').src = '/images/icn_exclaim.gif';
			document.getElementById('message').style.display = 'block';
		}
	}
	else if (response == 'locked')		// someone else is editing the outline, the lock is disabled
	{
		lock_action.value = '';
		lock_button.className = "btn_lock_inactive";
		lock_button.onclick = NullFunction;
		
		if (gLockStatus == 'me')
		{
			ShowExpiredLockMsg();
			clearTimeout(gLockTimer);
		}
		else if (gLockStatus != response)
		{
			document.getElementById('message-text').innerHTML = 'One of your collaborators is editing this document. You can only view the document.';
			document.getElementById('message-icn').src = '/images/icn_exclaim.gif';
			document.getElementById('message').style.display = 'block';
		}
	}
	
	gLockStatus = response;
}

/*
function ReadjustContainerHeight()
{
	var new_height = (document.getElementById('edit-box').offsetHeight)*1 + 193;
	document.getElementById('captop').style.minHeight = new_height +'px';
}
*/

function Print()
{
	window.open("/" + gKey + "/print/");
}

function ReduceFontSize()
{
	if (gFontSize > 1)
	{
		var outliner_div = document.getElementById('outliner');
		
		RemoveClass(outliner_div, 'font-size'+gFontSize);
		gFontSize--;
		AddClass(outliner_div, 'font-size'+gFontSize);
	}
}

function EnlargeFontSize()
{
	if (gFontSize < 4)
	{
		var outliner_div = document.getElementById('outliner');
		
		RemoveClass(outliner_div, 'font-size'+gFontSize);
		gFontSize++;
		AddClass(outliner_div, 'font-size'+gFontSize);
	}
}

function StartEditing()
{
	document.lock.submit();
	return false;
}

function NullFunction()
{
	return false;
}

function AddFile()
{
var new_file_div = document.getElementById('new-file-div');
	new_file_div.style.display = "block";
}

function AddFocusToComment()
{
	shortcut.remove('Enter');	
}

function RemoveFocusFromComment()
{
	shortcut.add('Enter',
		function()
		{
			HandleEnter(lsclient);
		},
		{'type':'keypress'});
}

function ToggleShowComments()
{
	comments = document.getElementById('comments-container');
	disclosure = document.getElementById('comments-disclosure');
	if (comments.style.display == 'none')
	{
		comments.style.display = 'block';
		disclosure.src = '/images/expanded.gif';
	}
	else
	{
		comments.style.display = 'none';
		disclosure.src = '/images/collapsed.gif';
	}
}

function ConfirmDeleteComment()
{
var confirm = false;
	confirm = window.confirm("Are you sure you want to delete this comment? This action can't be undone.");
	if(confirm)
		return true;
	else return false;
}

function ValidateComment()
{
	if (!ValidateNotEmpty(document.commentform.comment_by.value, 'Please enter your name so that people know who commented.'))
		return false;
	
	if (!ValidateNotEmpty(document.commentform.comment.value, 'You can\'t leave a blank comment.'))
		return false;

	return true;
}

function RepositionElement(element_id, boundary_Y, class_above, class_below)
{
	scrollTop = getScrollTop();
	element = document.getElementById(element_id);
	
	if (scrollTop > boundary_Y)
	{
		RemoveClass(element, class_above);
		AddClass(element, class_below);
		
		if (element_id == 'toolbar-wrapper')
			document.getElementById('toolbar-sub').style.display = 'block';
	}
	else
	{
		RemoveClass(element, class_below);
		AddClass(element, class_above);
		
		if (element_id == 'toolbar-wrapper')
			document.getElementById('toolbar-sub').style.display = 'none';
	}
}

function HandleScrolling()
{
	RepositionElement('toolbar-wrapper', 187, 'inherit', 'fixed');
//	RepositionElement('edit-box', 187, 'inherit', 'fixed');
	RepositionElement('import-box', 197, 'inherit', 'fixed');
}

function HasUnsavedChanges()
{
	if (document.getElementById('processing-icon'))
		document.getElementById('processing-icon').style.display = 'inline';
}

function DidSaveChanges()
{
	if (document.getElementById('processing-icon'))
		document.getElementById('processing-icon').style.display = 'none';
}

var disable_click = true;

HandleMouseClick=function(e)
{
	var target = (e && e.target) || (event && event.srcElement);
	
	var import_link = document.getElementById('import');
	var import_box = document.getElementById('import-box');
	var outliner = document.getElementById('outliner');
	var toolbar = document.getElementById('toolbar');
	
	var print_options = document.getElementById('print-options');
	var print_options_link = document.getElementById('meta-print');
	
	var import_options = document.getElementById('import-options');
	var import_options_link = document.getElementById('meta-import');
	
	var calendar_div = document.getElementById("calendar-div");
	var duedate_calendar = document.getElementById("duedate-hud");
	var row_file_bubble = document.getElementById("row-file-bubble");
	var row_assign_bubble = document.getElementById("row-assigned-to-bubble");
	
	var files_list = document.getElementById("files-list");
	
	try
	{
		if (lsclient.IsUserInteractionEnabled() == true)
		{
			if (duedate_calendar && !isDecendant(target, duedate_calendar) && !HasClass(target, 'due-date'))
				lsclient.HideDueDateHUD();
			
			if (row_file_bubble.style.display == 'block' && !isDecendant(target, row_file_bubble) && !HasClass(target, 'attachment-clip'))
				lsclient.HideFileBubbleAtRow();
	
			if (row_assign_bubble.style.display == 'block' && !isDecendant(target, row_assign_bubble) && !HasClass(target, 'assigned-to'))
				lsclient.HideAssignedToBubbleAtRow();
	
			if (import_box && import_box.style.display == 'block' && !isDecendant(target, import_box) && !isDecendant(target, import_link))
				lsclient.HideImportBox();
				
			if (print_options && print_options.style.display == 'block' && !isDecendant(target, print_options) && !isDecendant(target, print_options_link))
				HidePrintOptions();
			
			if (import_options && import_options.style.display == 'block' && !isDecendant(target, import_options) && !isDecendant(target, import_options_link))
				HideImportOptions();
				
			if (lsclient.IsContextMenuVisible())
				lsclient.HideContextMenu();
			else if (!isDecendant(target, outliner) && !isDecendant(target, toolbar) && !isDecendant(target, duedate_calendar) && lsclient.GetSelectedRow())		//  && !(upload_file_input != null && target == upload_file_input)
				lsclient.DeselectRow();
		}
		else
		{
			if (!files_list || !isDecendant(target, files_list))
				alert("Upload in progress. Please wait.");
		}
	}
	catch(err)
	{
//		alert(err);
	}
}

// this function is used when we are handling click outside a particular div
function isDecendant(decendant, ancestor)
{
	return ((decendant.parentNode==ancestor) || (decendant.parentNode!=document) &&	isDecendant(decendant.parentNode,ancestor));
}

function ShowAlertReadOnly()
{
	alert("Sorry, you are currently in read only mode.\nYou need to enter Edit mode or wait till others have released their lock.");
}

function HandleSelectedDate(selected_date)
{
	lsclient.DidSelectDueDate(selected_date);
}

function ShowColumn(col)
{
	var outliner_div = document.getElementById('outliner');
	switch (col)
	{
	case 'attachment':	AddClass(outliner_div, 'hasattachments');
						break;
						
	case 'assigned-to': AddClass(outliner_div, 'hasassigned-to');
						break;
						
	case 'duedate': 	AddClass(outliner_div, 'hasduedate');
						break;
						
	case 'amount': 		AddClass(outliner_div, 'hasamount');
						break;
	}
}

function ShowDiv(div_id)
{
	$jq('#'+div_id).slideDown('fast');
}

function ShowAssignToPicker(tab)
{
	$jq('#tab-invitees').removeClass('active');
	$jq('#tab-contacts').removeClass('active');
	$jq('#tab-new').removeClass('active');
	
	ShowDiv('tabs-wrapper');
	switch (tab)
	{
	default:
	case 'invitees':$jq('#tab-invitees').addClass('active');
					$jq('#invitees-list').load('/complete/get_invitees.php?tab=invitees&outline_id='+gOutlineId);
					break;
	
	case 'contacts':$jq('#tab-contacts').addClass('active');
					$jq('#invitees-list').load('/complete/get_invitees.php?tab=contacts&user_id='+gUid);
					break;
	
	case 'new':		$jq('#tab-new').addClass('active');
					$jq('#invitees-list').load('/complete/get_invitees.php?tab=new');
					break;
	}
}

function HideAssignToPicker()
{
	$jq('#row-assigned-to-bubble').hide();
}

function AssignSelectedRowToUser(selected_user)
{
	lsclient.AssignRow(selected_user);
	HideAssignToPicker();
}

function ClearAssigneeForSelectedRow()
{
	lsclient.ClearAssignedTo();
	HideAssignToPicker();
}

function AssignSelectedRowToNewInvitee()
{
	new_invitee = $jq('#new-invitee-email').val();
	lsclient.AssignRow(new_invitee);
	HideAssignToPicker();
}

function ShowAttachmentPicker(tab)
{
	$jq('#tab-mine').removeClass('active');
	$jq('#tab-document').removeClass('active');
	$jq('#tab-newfile').removeClass('active');
	
	ShowDiv('tabs-wrapper');
	switch (tab)
	{
	default:
	case 'mine':	$jq('#tab-mine').addClass('active');
					$jq('#files-list').load('/complete/get_files.php?tab=mine&uid='+gUid);
					break;
	
	case 'document':$jq('#tab-document').addClass('active');
					$jq('#files-list').load('/complete/get_files.php?tab=document&outline_id='+gOutlineId);
					break;
	
	case 'new':		$jq('#tab-newfile').addClass('active');
					if (lsclient.flash_enabled)
						flash_enabled = 'yes';
					else flash_enabled = 'no';
					
					$jq('#files-list').load('/complete/get_files.php?tab=new&flash='+flash_enabled+'&uid='+gUid);
					
					if (flash_enabled == 'no')
						SI.Files.stylizeAll();
					
					break;
	}
}

function HideAttachmentPicker()
{
	if (!gUploadInProgress)
		$jq('#row-file-bubble').hide();
}

function AttachFileToSelectedRow(file_id)
{
	lsclient.AttachFileToRow(file_id);
	setTimeout(HideAttachmentPicker, 500);
}

function ClearAttachmentForSelectedRow()
{
	lsclient.DetachFileFromRow();
	setTimeout(HideAttachmentPicker, 500);
}

function ShowSelectionOverlay()
{
	if (lsclient.IsSelectionOverlayEnabled())
	{
		sel_row = lsclient.outliner.GetSelectedRow();
		if (sel_row)
		{
			sel_row_div = document.getElementById(sel_row.id);
			
			last_child_div = sel_row_div;
			sel_row_depth = sel_row_div.getAttribute('data-depth');
			while (last_child_div.nextSibling && last_child_div.nextSibling.getAttribute('data-depth') > sel_row_depth)
				last_child_div = last_child_div.nextSibling;
		
			var left = findPosX(sel_row_div);
			var top = findPosY(sel_row_div);
			
			document.getElementById('selection-overlay').style.left = left-2+'px';
			document.getElementById('selection-overlay').style.top = top+1+'px';
		
			var height = sel_row_div.offsetHeight;
			if (sel_row_div != last_child_div)
			{
				temp_div = sel_row_div.nextSibling;
				while (temp_div != last_child_div)
				{
					height += temp_div.offsetHeight*1;
					temp_div = temp_div.nextSibling;
				}
				height += last_child_div.offsetHeight*1;
			}
			document.getElementById('selection-overlay').style.height = height-5+'px';
			document.getElementById('selection-overlay').style.display = 'block';
		}
	}
}

function HideSelectionOverlay()
{
	if (lsclient.IsSelectionOverlayEnabled())
		document.getElementById('selection-overlay').style.display = 'none';
}

function InitFlashUploader()
{
	$jq("#uploadify").uploadify({
		'buttonImg'		 : '/images/btn_choosefile.png',
		'uploader'       : '/test/uploadify.swf',
		'script'         : '/complete/file_upload.php',
		'cancelImg'      : '/images/icn_cross_grey.gif',
		'folder'         : '/tmp',
		//'fileDesc'       : 'Png Files',
		//'fileExt'        : '*.png',
		'multi'          : false,
		'auto'			 : true,
		'scriptData'  	 : { 'uid':gUid },
		'onComplete'	 : CompletedFileUploadUsingFlash,
		'onOpen'		 : FlashUploadStarted,
		'onCancel'		 : DidCancelUpload
	});
}

FlashUploadStarted=function(event,ID,fileObj)
{
	gUploadInProgress = true;
	lsclient.DisableUserInteraction();
}

DidCancelUpload=function(event, ID, fileObj, data)
{
	gUploadInProgress = false;
	lsclient.EnableUserInteraction();
}

CompletedFileUploadUsingFlash=function(event, ID, fileObj, response, data)
{
	CompletedFileUpload(response);
}

function CompletedHTMLFileUpload(response)
{
	document.getElementById('upload-in-progress').style.display = "none";
	CompletedFileUpload(response);
}

function StartHTMLUpload()
{
	document.getElementById('upload-form').submit();
	document.getElementById('upload-in-progress').style.display = "block";
	lsclient.DisableUserInteraction();
	gUploadInProgress = true;
}

function CompletedFileUpload(response)
{
var responseObj = JSON.parse(response);

	gUploadInProgress = false;
	
	if (responseObj['status'] == 'success')
	{
		lsclient.AttachFileToRow(responseObj);			// attach it to the selected row
		
		lsclient.ShowFileBubbleAtRow(lsclient.outliner.GetSelectedRow().getAttribute('_file_id'), 'attachment'+lsclient.outliner.GetSelectedRow().id, lsclient.outliner.GetSelectedRow().id);
		lsclient.UpdateUsedQuota(responseObj['raw_size']);			// update the quota display on the meta header
	}
	else
	{
		switch (responseObj['status'])
		{
		case 'unsupported format':	alert("Sorry, the file wasn't uploaded because the format isn't supported.");
									break;
		
		case 'too large':			alert("Sorry, the file wasn't uploaded because it is too large.");
									break;
									
		case 'no space left':		alert("Sorry, the file wasn't uploaded because you don't have enough space for this file.");
									break;
									
		case 'could not move file':	alert("Sorry, something went wrong... the file couldn't be uploaded.");
									break;
		}
	}
	lsclient.EnableUserInteraction();
}

function TogglePreview(row_id, attachment_id)
{
	text_notes = document.getElementById('text-and-notes'+row_id);
	att_preview = document.getElementById('attachment-preview'+row_id);
	
	if (HasClass(att_preview, 'full-width'))		// show thumbnail
	{
		AddClass(text_notes, 'on-the-side');
		RemoveClass(text_notes, 'below');
		RemoveClass(att_preview, 'full-width');
		
		att_preview.innerHTML = '<img src="/complete/getfile.php?file_id='+attachment_id+'&size=thumb" height="100" width="100" />';
		
		lsclient.SetPreviewStateForRow(row_id, 'thumbnail');
	}
	else											// show full width preview
	{
		RemoveClass(text_notes, 'on-the-side');
		AddClass(text_notes, 'below');
		AddClass(att_preview, 'full-width');
	
		text_wrapper_width = $jq('#text-wrapper'+row_id).width();
		preview_width = text_wrapper_width-28;

		$jq('#attachment-preview'+row_id).load('/complete/getfilepreview.php?file_id='+attachment_id+'&width='+preview_width, function() { ShowSelectionOverlay(); });
		lsclient.SetPreviewStateForRow(row_id, 'full-width');
	}
}

function StripCommasFromDiv(div)
{
	div.innerHTML = div.innerHTML.replace(',', '');
}
