var img_expanded  = '/images/expanded.gif';
var img_collapsed = '/images/collapsed.gif';
var img_blank = '/images/blank.png';
var img_leaf = '/images/leafrowhandle.gif';

new Image(9,9),src = img_expanded; // caching
new Image(9,9),src = img_collapsed; // caching
new Image(9,9),src = img_blank; // caching
new Image(9,9),src = img_leaf; // caching

function ioSwitch(ioNode,fully)
{
var children_div = 'children-'+ioNode;
var hndl_div = 'hndl-'+ioNode;
	if (document.getElementById && document.getElementById(children_div) !=  null)
		nodeState = document.getElementById(children_div).style.display;

    if (nodeState == 'none')
    {
        if (fully)
            expandAll();
        else expand(ioNode);
	}
	else
	{
        if (fully)
            collapseAll();
		else collapse(ioNode);
	}
	PaintBackground();
}

function expand(ioNode)
{
var children_div = 'children-'+ioNode;
var hndl_div = 'hndl-'+ioNode;
	if (document.getElementById && document.getElementById(children_div) !=  null)
	{
		document.getElementById(children_div).style.display='block';

		if (document.getElementById(hndl_div) !=  null)
		{
			document.getElementById(hndl_div).src=img_expanded;
			document.getElementById(hndl_div).title='collapse';
			document.getElementById(hndl_div).alt='V';
		}
	}
}

function collapse(ioNode)
{
var children_div = 'children-'+ioNode;
var hndl_div = 'hndl-'+ioNode;
	if (document.getElementById && document.getElementById(children_div) != null)
	{
		document.getElementById(children_div).style.display = 'none';

		if (document.getElementById(hndl_div) !=  null)
		{
			document.getElementById(hndl_div).src=img_collapsed;
			document.getElementById(hndl_div).title='expand';
			document.getElementById(hndl_div).alt='>';
		}
	}
}

function expandAll()
{
	nodeList = getElementsByClassName('parent', 'div');
	for (var i = 0; i < nodeList.length; i++)
		expand(nodeList[i].id);	
}

function collapseAll()
{
	nodeList = getElementsByClassName('parent', 'div');
	for (var i = 0; i < nodeList.length; i++)
		collapse(nodeList[i].id);	
}

function PaintBackground()
{
	var n = document.getElementById('outliner-root').firstChild;
	var row_counter = 0;
	var rows = getElementsByClassName('row', 'div');
	for (i = 0; i < rows.length; i++)
	{
		if (!isElementVisible(rows[i]))
			continue;
		
		if (row_counter % 2)
		{
			RemoveClass(rows[i], 'oddrow');
			AddClass(rows[i], 'evenrow');
		}
		else
		{
			RemoveClass(rows[i], 'evenrow');
			AddClass(rows[i], 'oddrow');
		}
		row_counter++;
	}
}

function FetchFilesFromServer(outline_id)
{
	var params = "{outline_id: '"+outline_id+"'}";
	new Ajax.Request("/api/files/getInOutline.json",
	{
		method: "GET",
		parameters: params.evalJSON(),
		onFailure: function() { alert('Something went wrong...'); },
		onSuccess: function(t) {
			var response = t.responseText.evalJSON();
			StoreFiles(response.files);
		}
	});
}

StoreFiles=function(files)
{
	gFiles = new Array();		// we over-write the files array that we created in GetFilesFromServer with the actual data

	for (var i = 0; i < files.length; i++)
	{
		n = {	"file_id": files[i].file_id,
				"uid": files[i].uid,
				"filename": files[i].filename,
				"size": files[i].size,
				"raw_size": files[i].raw_size,
				"time": files[i].time,
				"owner": files[i].owner
		};

		gFiles[gFiles.length] = n;
	}
}

GetFileById=function(file_id)
{
	if (gFiles !== 'undefined')
	{
		for (var i = 0; i < gFiles.length; i++)
		{
			if (gFiles[i]['file_id'] == file_id)
				return gFiles[i];
		}
	}
	return false;
}

function ShowFileBubble(file_id, file_clip_id)
{
var file_bubble = document.getElementById("row-file-bubble");
var file_icon = document.getElementById(file_clip_id);

	switch (gBrowser)
	{
	default:
	case 'Safari':	bubble_left = 437;
					break;
					
	case 'Firefox':	if (gOS == 'Mac')
						bubble_left = 463;
					else bubble_left = 505;
					break;
					
	case 'Chrome':	bubble_left = 432;
					break;
					
	case 'Explorer':bubble_left = 505;
					break;
	}
	
	bubble_top = 67;
	
	var offset_left = $jq('#'+file_clip_id).offset().left-bubble_left;
	var offset_top = $jq('#'+file_clip_id).offset().top-bubble_top;
	
	if (file_bubble)
	{
		file_bubble.style.top = offset_top+'px';
		file_bubble.style.left = offset_left+'px';

		if (!file_id)
			gShowFilesList = true;

		new Ajax.Request("/complete/get_file_bubble_info.php",
		{
			method:'post',
			onSuccess: ShowFileBubbleCallBack,
			parameters: { file_id: file_id, status:'readonly' },		// , uid: tUid
			onFailure: function(){ alert('Something went wrong...'); }
		});
		
		file_bubble.style.display = "block";		// finally we make the bubble display
		file_bubble.onmouseover = ClearFileBubbleTimer;
		file_bubble.onmouseout = function() { StartFileBubbleTimer(file_clip_id); };
		
		file_icon.onmouseover = ClearFileBubbleTimer;
		file_icon.onmouseout = function() { StartFileBubbleTimer(file_clip_id); };
	}
}

function ShowFileBubbleCallBack(t)
{
var response = t.responseText;

var file_bubble = document.getElementById("row-file-bubble");
	file_bubble.innerHTML = response;
	
	file_bubble.style.display = "block";		// finally we show the bubble
};

function StartFileBubbleTimer(file_clip_id)
{
	file_bubble_timer = setTimeout(function () {that.HideFileBubbleAtRow(file_clip_id); }, 1500);
};

function ClearFileBubbleTimer()
{
	clearTimeout(file_bubble_timer);
};

/*
function ShowFileBubble(file_id, row_id)
{
var file_bubble = document.getElementById("row-file-bubble");
var file_clip = document.getElementById("file-clip"+row_id);

var offset_left = file_clip.offsetLeft - 367;
var offset_top = file_clip.offsetTop - 46;

	if (file_bubble)
	{
		file_bubble.style.top = offset_top+'px';
		file_bubble.style.left = offset_left+'px';

	var file_info = GetFileById(file_id);
		document.getElementById('row-bubble-filename').innerHTML = file_info['filename'];
		document.getElementById('row-bubble-filesize').innerHTML = file_info['size'];
//		document.getElementById('row-bubble-filetime').innerHTML = "Uploaded on: " + file_info['time'];
//		document.getElementById('row-bubble-fileowner').innerHTML = "Owner: " + file_info['owner'];
		document.getElementById('row-bubble-thumb').src = "/complete/getfile.php?file_id="+file_id+"&size=thumb";
		
		document.getElementById('row-bubble-view').onclick = function() { ViewFile(file_id); };
		document.getElementById('row-bubble-download').onclick = function() { DownloadFile(file_id); };
		
		file_bubble.style.display = "block";		// finally we make the bubble display
		file_bubble.onmouseover = ClearFileBubbleTimer;
		file_bubble.onmouseout = StartFileBubbleTimer;
	}	
}
*/

function HideFileBubbleAtRow()
{
var file_bubble = document.getElementById("row-file-bubble");

	if (file_bubble)
		file_bubble.style.display = "none";
	else alert("no file bubble");
};

StartFileBubbleTimer=function()
{
	gFileBubbleTimer = setTimeout(HideFileBubbleAtRow, 1500);
};

ClearFileBubbleTimer=function()
{
	clearTimeout(gFileBubbleTimer);
};

function ViewFile(file_id)
{
	window.open('/complete/getfile.php?file_id='+file_id+'&size=original','mywindow','width=600,height=600');
}

function DownloadFile(file_id)
{
	window.location = '/download_file.php?file_id='+file_id;
}

function SaveOutline()
{
	document.getElementById("save-outline").style.display = "block";
	document.getElementById("HUD-fade").style.display = "block";
	
	return false;
}

function CancelSaveOutline()
{
	document.getElementById("save-outline").style.display = "none";
	document.getElementById("HUD-fade").style.display = "none";
	
	return false;
}

function CreateOutline()
{
	if (!Validate())
		return false;
		
	var _title = document.newdoc.title.value;
	var _name = document.newdoc.name.value;
	var _email = document.newdoc.email.value;
	var _password = document.newdoc.password.value;
	
	var _outline_id = document.newdoc.outline_id.value;
	
	new Ajax.Request("/complete/ideas_duplicate.php",
	{
		method:'post',
		parameters: { action: 'create', title: _title, name: _name, email: _email, password: _password, outline_id: _outline_id },
		onSuccess: DidCreateOutline,
		onFailure: function(){ alert('Something went wrong...'); }
	});
}

DidCreateOutline=function(t)
{
	var response = t.responseXML.documentElement;
	var key = response.getElementsByTagName('key')[0].firstChild.data;
	window.location="/"+key;
}

function Validate()
{
	if (!ValidateNotEmpty(document.newdoc.title.value, 'Please give a name to your document'))
		return false;
		
	if (!ValidateNotEmpty(document.newdoc.name.value, 'Please enter your name'))
		return false;
	
	if (!ValidateEmailAddress(document.newdoc.email.value, 'You need to enter your email address to continue', true))
		return false;
		
	if (!ValidateNotEmpty(document.newdoc.password.value, 'Your document needs to have a password'))
		return false;
		
	if (!document.newdoc.agree.checked)
	{
		alert("Sorry, but you need to read and agree to our Terms of Service before you can continue.");
		return false;
	}
		
	return true;
}

// -----------------------------
// -------- USER RATING --------
// -----------------------------
function MouseOverRating(number)
{
	if (!gDidRate)
	{
		switch (number)
		{
		case 5:	RemoveClass(document.getElementById('rating5'), 'dot');
				AddClass(document.getElementById('rating5'), 'star');
				
		case 4:	RemoveClass(document.getElementById('rating4'), 'dot');
				AddClass(document.getElementById('rating4'), 'star');
		
		case 3:	RemoveClass(document.getElementById('rating3'), 'dot');
				AddClass(document.getElementById('rating3'), 'star');
		
		case 2:	RemoveClass(document.getElementById('rating2'), 'dot');
				AddClass(document.getElementById('rating2'), 'star');
		
		case 1:	RemoveClass(document.getElementById('rating1'), 'dot');
				AddClass(document.getElementById('rating1'), 'star');
		}
		
		switch (number)
		{
		case 1:	label = 'hate it';
				break;
				
		case 2:	label = 'don\'t like it';
				break;
				
		case 3:	label = 'it\'s ok';
				break;
				
		case 4:	label = 'it\'s good';
				break;
				
		case 5:	label = 'it\'s great';
				break;
		}
		
		document.getElementById('rating-label').innerHTML = label;
	}
}

function MouseOutRating()
{
	if (!gDidRate)
	{
		RemoveClass(document.getElementById('rating1'), 'star');
		RemoveClass(document.getElementById('rating2'), 'star');
		RemoveClass(document.getElementById('rating3'), 'star');
		RemoveClass(document.getElementById('rating4'), 'star');
		RemoveClass(document.getElementById('rating5'), 'star');
		
		AddClass(document.getElementById('rating1'), 'dot');
		AddClass(document.getElementById('rating2'), 'dot');
		AddClass(document.getElementById('rating3'), 'dot');
		AddClass(document.getElementById('rating4'), 'dot');
		AddClass(document.getElementById('rating5'), 'dot');
		
		document.getElementById('rating-label').innerHTML = '';
	}
}

function ClickedRating(number)
{
	if (gDidRate)
	{
		gDidRate = false;
		MouseOutRating();
		MouseOverRating(number);
	}
	
	gDidRate = true;

	// send rating to server via ajax
	new Ajax.Request("/complete/ideas_rating.php",
	{
		method: "POST",
		parameters: { outline_id: gOutlineId, rating: number, session_id: gSessionId },
		onFailure: function() { alert('Something went wrong...'); },
		onSuccess: function(t) {
			document.getElementById('rating-label').innerHTML = 'Thanks!';
		}
	});
}

function ValidateComment()
{
	if (!ValidateNotEmpty(document.commentform.comment_name.value, 'Please enter your name so that people know who commented.'))
		return false;
		
	if (!ValidateNotEmpty(document.commentform.comment_email.value, 'Please enter email address. We promise not to spam your account.'))
		return false;
		
	if (!ValidateEmailAddress(document.commentform.comment_email.value, 'Please enter a valid email address. We promise not to spam your account.', true))
		return false;

	if (!ValidateNotEmpty(document.commentform.comment.value, 'You can\'t leave a blank comment.'))
		return false;

	return true;
}

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" />';
	}
	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);
	}
}
