// Set up events
addEvent(window, 'DOMContentLoaded', init);
//enhance_textareas();

// ===== FUNCTIONS ===== //
function init()
{
	enhance_listview();
	enhance_admin_gallery_list();
	remove_human_tests();
}
function $(id)
{
	return document.getElementById(id);
}
function $$(elementname)
{
	return document.getElementsByTagName(elementname);
}
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ""); };


// === Helper Functions === //
var dragged = false;
var sourceElement = null;
var targetElement = null;
var dX = dY = 0;
var rect = null;
function enhance_admin_gallery_list()
{
	var list = $('adminGalleryList');
	if (list)
	{
		var listitems = list.getElementsByTagName('li');
		for (var i = 0; i < listitems.length; i++)
		{
			addEvent(listitems[i], 'mousedown', list_onmousedown);
			//addEvent(listitems[i], 'mousemove', list_onmousemove);
			addEvent(listitems[i], 'mouseover', list_onmouseover);
			//addEvent(listitems[i], 'mouseup',   list_onmouseup);
		}
		//addEvent(list, 'mousemove', list_onmousemove);
		addEvent(document.documentElement, 'mouseup', list_onmouseup);


		// Create source Ghost
		ghost = document.createElement('div');
		ghost.id = 'ghost_source';
		document.documentElement.appendChild(ghost);
		// Create target Ghost
		ghost_target = document.createElement('div');
		ghost_target.id = 'ghost_target';
		ghost_target.style.visibility = 'hidden';
		document.documentElement.appendChild(ghost_target);


		// Add Save List Order Button
		var save = document.createElement('input');
		save.type = 'button';
		save.name = 'submitSaveListOrder';
		save.id = 'submitSaveListOrder';
		save.className = 'button';
		save.value = 'Save List Order';
		addEvent(save, 'click', save_list_order);

		var btnRemove = $('submitRemove');
		btnRemove.parentNode.insertBefore(save, btnRemove);
	}
}

function save_list_order()
{
	var args = new Array();
	var list = $('adminGalleryList');
	var input, pageId;
	if (list)
	{
		var listitems = list.getElementsByTagName('li');
		for (var i = 0; i < listitems.length; i++)
		{
			input = listitems[i].getElementsByTagName('input')[0];
			//pageId = input.name.match(/.+\[(\d)+\]/)[1];
			pageId = input.name.match(/\D+(\d+)\D*/)[1];
			args.push('page' + (i+1) + '=' + pageId);
		}
		//alert(args.join('&'));

		// Make request
		var catId = $('catId').value;
		var request = new ajaxObject('savepageorder.php?catId=' + catId, processListOrder);
		request.update(args.join('&'),'POST');
	}
}
function processListOrder(responseText, responseStatus)
{
	if (responseStatus == 200)
	{
		alert(responseText);
	}
	else
	{
		alert(responseStatus + ' -- Error Processing Request');
	}
}

function list_onmousemove(event)
{
	if (dragged)
	{
		var ghost = $('ghost_source');
		if (ghost.style.visibility == 'hidden')
		{
			ghost.style.visibility = 'visible';
		}
		var x = event.clientX - dX;
		var y = event.clientY - dY;

		ghost.style.left = (rect[0] + x) + 'px';
		ghost.style.top = (rect[1] + y) + 'px';

		//console.log('mousemove');
	}
}
function list_onmouseover(event)
{
	if (dragged)
	{
		var ghost = $('ghost_target');
		// Get absolute position
		rect = get_rect(this);
		// Apply position
		ghost.style.left = rect[0] + 'px';
		ghost.style.top = rect[1] + 'px';
		ghost.style.width = rect[2] + 'px';
		ghost.style.height = rect[3] + 'px';
		ghost.style.visibility = 'visible';
		$('ghost_source').style.visibility = 'visible';
		targetElement = this;
	}
	//console.log('mouseover');
}
function list_onmousedown(event)
{
	dragged = true;
	sourceElement = this;
	// Create elemens on demand
	var ghost = $('ghost_source');
	// Get absolute position
	rect = get_rect(this);
	// Apply position
	ghost.style.left = rect[0] + 'px';
	ghost.style.top = rect[1] + 'px';
	ghost.style.width = rect[2] + 'px';
	ghost.style.height = rect[3] + 'px';
	ghost.style.visibility = 'hidden';
	//ghost.style.visibility = 'visible';
	// Disable the the default drag and drop feature in the document on this element
	if (event.preventDefault)
	{
		event.preventDefault();
	}
	// Cache original mouse X, Y co-ords
	//dX = event.clientX;
	//dY = event.clientY;
	// Display Move cursor
	//this.style.cursor = 'move';
	//console.log('mousedown');
}
function list_onmouseup()
{
	// Move the element id an element was dragged
	if (dragged && sourceElement && targetElement)
	{
		targetElement.parentNode.insertBefore(sourceElement, targetElement);
	}
	// Reset values
	dragged = false;
	sourceElement = null;
	targetElement = null;
	$('ghost_source').style.visibility = 'hidden';
	$('ghost_target').style.visibility = 'hidden';
	//$('adminGalleryList').style.cursor = 'auto';
}


// === Helper Functions === //
function get_rect(obj)
{
	var curleft = curtop = 0;
	var curWidth = obj.offsetWidth;
	var curHeight = obj.offsetHeight;
	if (obj.offsetParent)
	{
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent)
		{
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft, curtop, curWidth, curHeight];
}

function get_css_media()
{
	var media = 'unknown';
	// Create test element
	var test = document.createElement('div');
	test.id = 'cssMediaTest';
	// position and hide it so it doesn't interfer with the page
	test.style.visible = 'hidden';
	test.style.position = 'absolute';
	test.style.top = 0;
	// Add to the document so we're sure it get's computed
	document.documentElement.appendChild(test);
	// Get the CSS test value
	var value = get_computed_style(test).left;
	//alert(value);
	switch(value)
	{
		case '10px': media = 'screen';   break;
		case '20px': media = 'handheld'; break;
		case '30px': media = 'print';    break;
	} // switch
	return media;
}


function get_computed_style(element)
{
	if (window.getComputedStyle)
	{
		return window.getComputedStyle(element, null);
	}
	else if (document.defaultView && document.defaultView.getComputedStyle)
	{
		// Safari 2
		return document.defaultView.getComputedStyle(element, null);
	}
	else if (element.currentStyle)
	{
		// Internet Explorer
		return element.currentStyle;
	}
	else {
		return null;
	}
}


function get_current_stylesheet_name()
{
	var count = document.styleSheets.length;
	for (var i = 0; i < count; i++)
	{
		if (document.styleSheets[i].title != '' && !document.styleSheets[i].disabled)
		{
			return document.styleSheets[i].title;
		}
	}
	return '[noname]';
}


// === Textareas Functions === //
function enhance_textareas()
{
	tinyMCE.init({
		mode : "textareas",
		plugins : "xhtmlxtras",
		//content_css : "example_full.css",
		theme : "advanced",
		theme_advanced_blockformats : "p,blockquote,pre,code,samp",
		theme_advanced_resizing : true,
		remove_linebreaks : false,
		preformatted : true,
		//content_css : "/css/firefly_content.css",
		//apply_source_formatting : true,
		theme_advanced_buttons1 : "bold,italic,|,cite,abbr,acronym,|,bullist,numlist,|,undo,redo,|,link,unlink,|,charmap,attribs,code,|,formatselect",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_path_location : "bottom",
		valid_elements :	"+a[href|title|lang]," +
							"-abbr[title|lang]," +
							"-acronym[title|lang]," +
							"-blockquote[cite|lang]," +
							"-code[class<jscript?vbscript|lang]," +
							"-dfn[lang]," +
							"-dd[lang]," +
							"-dl[lang]," +
							"-dt[lang]," +
							"-em/-i[lang]," +
							"-li[lang]," +
							"-kbd[lang]," +
							"-ol[lang]," +
							"-p[lang]," +
							"-pre[lang]," +
							"-q[cite|lang]," +
							"-samp[lang]," +
							"-strong/-b[lang]," +
							"-sub[lang]," +
							"-sup[lang]," +
							"-ul[lang]," +
							"-var[lang]"
	});
}


// === Listview Functions === //
function enhance_listview()
{
	// Iterate though all 'listview' UL lists and
	// perform appropriate action to enhance them
	lists = $$('ul');
	for (var i = 0; i < lists.length; i++)
	{
		list = lists[i];
		// Find all listview list
		if (list.className.indexOf('listview') != -1)
		{
			/*switch(list.className)
			{
				case 'listview tiles checkbox':
				case 'listview thumbnails small checkbox':
					enhance_listview_checkbox(list);
					break;
			} // switch */

			// Ensure thumbnail titles isn't too long
			if (get_current_stylesheet_name() == 'Firefly' && get_css_media() == 'screen' && list.className.indexOf('thumbnails') != -1)
			{
				enhance_listview_titles(list);
			}

			// Allow all listitems with a checkbox to
			// toggle the checkbox by clicking anywhere
			// on the list element
			if (list.className.indexOf('checkbox') != -1)
			{
				enhance_listview_checkbox(list);
			}
		}
	}
}

function enhance_listview_checkbox(list)
{
	// Iterate through all LI elements; add a
	// click event to toggle the checkbox
	// and set the cursor to pointer to indicate
	// action.
	for (var i = 0; i < list.childNodes.length; i++)
	{
		listitem = list.childNodes[i];
		if (listitem.nodeName == 'LI')
		{
			listitem.style.cursor = 'pointer';
			addEvent(list.childNodes[i], 'click', function()
			{
				header   = this.getElementsByTagName('h3')[0];
				checkbox = header.getElementsByTagName('input')[0];
				checkbox.checked = !checkbox.checked;
				this.className = (checkbox.checked) ? 'selected' : '';
			});
		}
	}
}


function enhance_listview_titles(list)
{
	// Iterate through all A elements; check it's
	// length and trim it with an ... if needed
	for (var i = 0; i < list.childNodes.length; i++)
	{
		listitem = list.childNodes[i];
		if (listitem.nodeName == 'LI')
		{
			var title = listitem.getElementsByTagName('a')[0];

			if (listitem.parentNode.className.indexOf('small') != -1)
			{
				if (title.innerHTML.length > 10)
				{
					title.innerHTML = title.innerHTML.substr(0, 10) + '…';
				}
			}

			if (listitem.parentNode.className.indexOf('medium') != -1)
			{
				if (title.innerHTML.length > 17)
				{
					title.innerHTML = title.innerHTML.substr(0, 17) + '…';
				}
			}
		}
	}
}


// Locates the human test. Fills out the answer and hides it from the user
// Yes, defies the whole 'human test'... whatever...
function remove_human_tests()
{
	var q = $('question');
	if (q)
	{
		q.value = 'four';
		console.log(q.parentNode);
		q.parentNode.style.display = 'none';
	}
}