
/*
 * @author	Martijn Polak <martijn.polak@amgate.com>
 * @since	17-01-2006
 * @name	SMS4it dynamic element drag & drop
 */

var dragobject = null;
var renameobject = null;
var src_object = null;
var dst_object = null;
var dragpoint = new Object();
var startcoords = new Object();
var min_drag_radius = 1;			// minimum distance in pixels an object has to be dragged in either direction to initialize the d&d subsystem
javascriptKit.verbose = true;

// Prepare for the drag operation
function arc_drag_start(id) {

	startcoords = new Object();

	// Set source object
	src_object = document.getElementById(id);

	// Set event handlers
	document.onmousemove = arc_drag;
	document.onmouseup = arc_drag_end;

}

// Called while dragging
function arc_drag(e) {

	e = javascriptKit.compat.compatibleEvent(e);

	if (!startcoords.hascoords) {
		startcoords.x = e.clientX;
		startcoords.y = e.clientY;
		startcoords.hascoords = true;
	}

	// Define if the current mouse position is outside the minimum drag radius
	var outside_radius = e.clientX < (startcoords.x - min_drag_radius) || e.clientX > (startcoords.x + min_drag_radius) || e.clientY < (startcoords.y - min_drag_radius) || e.clientY > (startcoords.y + min_drag_radius);

	// No dragobject created but source object available: initiate drag object
	if (outside_radius && (typeof(dragobject) == 'undefined' || !dragobject) && (typeof(src_object) != 'undefined' && src_object)) {

		// Clone node to create a dragobject
		dragobject = src_object.cloneNode(true);
		dragobject.id = null;
		dragobject.style.display = 'none';
		//adding to the body makes Firefox display involuntary spasms
		//document.body.appendChild(dragobject);
		document.getElementById('framework').appendChild(dragobject);

		// Position the node and apply style
		if (src_object.offsetWidth > 0) dragobject.style.width = src_object.offsetWidth + 'px';
		dragobject.style.position = 'absolute';
		dragobject.style.filter = 'progid:DXImageTransform.Microsoft.alpha(opacity=40)';
		dragobject.style.MozOpacity = 0.40;
		dragobject.style.zIndex = 500;
		dragobject.style.display = '';

		// Get the click position within the source object
		var elm_ofs = new javascriptKit.compat.elementOffset(src_object);
		var s_offset = new javascriptKit.compat.scrollOffset();
		dragpoint.x = (e.clientX - (elm_ofs.x - s_offset.x));
		dragpoint.y = (e.clientY - (elm_ofs.y - s_offset.y));

		// Add additional scrolloffset when dragging new links
		if (src_object.parentNode.id == 'sms_arc_cat_new') dragpoint.y += document.getElementById('sms_arc_cat_new').scrollTop;

	}

	if (typeof(dragobject) != 'undefined' && dragobject) {

		// Move dragobject around
		var s_offset = new javascriptKit.compat.scrollOffset();
		dragobject.style.left = (e.clientX - (dragpoint.x - s_offset.x)) + 'px';
		dragobject.style.top = (e.clientY - (dragpoint.y - s_offset.y)) + 'px';

		// Get column we're dragging over
		var fld = arc_columnfrompos(e.clientX + s_offset.x, e.clientY + s_offset.y);
		if (typeof(fld) != 'undefined' && fld) {

			// Get the type of object we're dragging
			var src_type = src_object.getAttribute('arc_type');
			var src_id = src_object.getAttribute('arc_id');
			var new_dst_type = fld.getAttribute('arc_type');

			// Restore previously hovered item's class
			if (typeof(dst_object) != 'undefined' && dst_object && dst_object.className.match(/block_hover/i) && (!dst_object.getAttribute('arc_id') || dst_object.getAttribute('arc_id') != fld.getAttribute('arc_id'))) {
				dst_object.className = dst_object.className.replace(/block_hover/i, '');
			}

			// Dragged over the trashcan
			// Same as when a link gets dragged over a folder but might be changed in the future
			if (new_dst_type == 'del') {

				if (src_type == 'cat' || src_type == 'link') {

					// Only change classname when not already set
					if (!fld.className.match(/block_hover/i))
						fld.className += ' block_hover';

					dst_object = fld;

				}

			// Dragged over a folder
			} else {

				switch (src_type) {

					// Drag a folder over another folder
					case 'cat':

						var plc = null;

						// Check if the coords are in the top half (insert before this object) or the bottom half (insert before next object) of the object
						// Note: fld.nextSibling is the dotted line so use the element after that
						if (e.clientY + s_offset.y > fld.offsetTop + (fld.offsetHeight / 2) && fld.nextSibling) plc = fld.nextSibling.nextSibling;
						else plc = fld;

						// Ignore dropping onto itself since the src_object will also be moving around
						if (src_id != plc.getAttribute('arc_id')) {

							dst_object = plc;

							// Move the object within the DOM structure
							plc.parentNode.insertBefore(src_object, dst_object);
							plc.parentNode.insertBefore(document.getElementById('sms_arc_dots_'+src_id), dst_object);
							src_object.setAttribute('col', dst_object.getAttribute('col'));

							updateHeight();

						}

						break;

					// Drag a link or color over a folder
					case 'link': case 'color':

						if (fld.getAttribute('arc_type') == 'cat' && fld.getAttribute('arc_id')) {

							// Only change classname when not already set
							if (!fld.className.match(/block_hover/i))
								fld.className += ' block_hover';

							dst_object = fld;

						}

						break;

				}

			}

		}

	}

	// Make sure no text get selected while dragging
	return arc_cancelevent(e);

}

// Dropped
function arc_drag_end(e) {

	// Remove document event handlers
	document.onmousemove = null;
	document.onmouseup = null;

	if (typeof(dragobject) != 'undefined' && dragobject) {

		if (typeof(src_object) != 'undefined' && src_object && typeof(dst_object) != 'undefined' && dst_object) {

			// Get the type of object we're dropping
			var src_type = src_object.getAttribute('arc_type');
			var dst_type = dst_object.getAttribute('arc_type');
			var src_id = src_object.getAttribute('arc_id');
			var dst_id = dst_object.getAttribute('arc_id');
			var dst_col = dst_object.getAttribute('col');

			// Dropped on a folder
			if (dst_type == 'cat') {

				// Reset classname
				dst_object.className = dst_object.className.replace(/block_hover/i, '');

				// Dragged a colour
				if (src_type == 'color') {

					// Check if renaming this folder is allowed
					if (dst_object.getAttribute('arc_cat_type') == 1) {

						var new_color = src_object.getAttribute('arc_color');
						dst_object.className = 'block block_' + new_color;

						// Call php script to save color
						xmlHttp.get('/action.php?mode=style&id='+dst_id+'&style='+new_color);

					} else {

						alert('Het is niet mogelijk om de kleur van aanbieder-specifieke mappen te wijzigen');

					}

				} else {

					if (src_type == 'link') {
						// Update folders, note that while dst_object is always a folder, src_object can be a folder or a link (the latter in this case)
						arc_update_count(dst_object, Number(dst_object.getAttribute('count')) + 1);
						arc_update_count(src_object.parentNode, Number(src_object.parentNode.getAttribute('count')) - 1);
						// Move link within DOM
						dst_object.insertBefore(src_object, dst_object.firstChild.nextSibling);
						// Force IE to redraw the link so it gets the proper styling after being dragged to a block with a different colour
						src_object.innerHTML = src_object.innerHTML;
					}

					// Call php script to save order
					xmlHttp.get('/action.php?mode=move'+(src_type == 'cat' ? 'cat' : 'link')+'&src='+src_id+'&dst='+dst_id+'&col='+dst_col);

				}

			// Dropped on the trashcan
			} else if (dst_type == 'del') {

				// A problem might arise when a folder gets dragged into a different position, then dropped
				// on the trashcan but the delete gets cancelled: the folder will stay in the new position
				// but will not be updated in the database
				if (src_type == 'cat') {
					arc_del_fld(src_id);
				} else if (src_type == 'link') {
					arc_del_lnk(src_id);
				}

				// Reset classname
				dst_object.className = dst_object.className.replace(/block_hover/i, '');

			}

		}

		// Remove cloned node from DOM and reset variables
		dragobject.parentNode.removeChild(dragobject);
		src_object = null;
		dst_object = null;
		dragobject = null;
		updateHeight();

		if (src_id && src_type == 'cat') arc_corner_over(src_id, false);

	}

}

function arc_columnfrompos(x, y) {

	var ret = null;
	var cnt = document.getElementById('main_container');
	var col = cnt.firstChild;

	while (col) {

		if (col.className == 'column') {

			// Loop through rows
			var fld = col.firstChild;
			while (fld) {

				if (typeof(fld.getAttribute) != 'undefined') {

					if (fld.getAttribute('arc_type') == 'cat' || fld.getAttribute('arc_type') == 'del') {

						// Check if the coords are within item bounds
						if (x > fld.offsetLeft && x < fld.offsetLeft + fld.offsetWidth && y > fld.offsetTop && y < fld.offsetTop + fld.offsetHeight) {
							ret = fld;
							break;
						}

					}

				}

				fld = fld.nextSibling;

			}

		}

		if (ret) break;
		col = col.nextSibling;

	}

	return ret;

}

// Expand or collapse folder by independently showing/hiding link objects
function arc_toggle_fld(id) {

	var fld = document.getElementById('sms_arc_cat_' + id);
	var xpd = document.getElementById('sms_arc_xpd_' + id);
	var status = fld.getAttribute('status');

	// Loop through rows
	var lnk = fld.firstChild;
	var idx = 0;

	while (lnk) {

		if (idx > sms_arc_max_links && lnk.getAttribute('arc_id')) lnk.style.display = (status == 0 ? '' : 'none');
		++idx;
		lnk = lnk.nextSibling;

	}

	xpd.className = (status == 0 ? 'xpd_expanded' : 'xpd_collapsed');
	fld.setAttribute('status', (status == 0 ? 1 : 0));

}

// Returns the last visible link in the specified folder
function arc_lastvisible(fld) {

	var lnk = fld.lastChild;
	while (lnk) {

		if (lnk.getAttribute('arc_id') && lnk.style.display != 'none') return lnk;
		lnk = lnk.previousSibling;

	}

}

// Update number of links in the specified folder after a drag & drop operation
function arc_update_count(fld, count) {

	var xpd = fld.lastChild;
	var type = fld.getAttribute('arc_type');
	var status = fld.getAttribute('status');
	var ocount = fld.getAttribute('count');
	var lastitem = arc_lastvisible(fld);

	// Only apply new count to folder type elements
	if (type != 'cat') return;

	// Update link count
	fld.setAttribute('count', count);

	if (count > sms_arc_max_links) {

		// Total links > max visible links: display expander button
		fld.lastChild.lastChild.style.display = '';

		// When collapsed hide the bottom item to keep the correct number of visible items
		if (status == 0 && typeof(lastitem) != "undefined" && lastitem) {
			if (ocount < count) lastitem.style.display = 'none';
			else if (typeof(lastitem.nextSibling) != "undefined" && lastitem.nextSibling) lastitem.nextSibling.style.display = '';
		}

	} else {

		// Total links <= max visible link: hide expander button and show last hidden item
		if (typeof(lastitem) != "undefined" && lastitem && typeof(lastitem.nextSibling) != "undefined" && lastitem.nextSibling) lastitem.nextSibling.style.display = '';
		fld.lastChild.lastChild.style.display = 'none';

	}

}

// Cancels event bubbling
function arc_cancelevent(e) {

	e = javascriptKit.compat.compatibleEvent(e);
	e.cancelBubble = true;
	if (e.preventDefault) e.preventDefault();
	return false;

}

// Add a folder
function arc_add_fld() {

	var il = document.getElementById('sms_arc_add_folder');
	// Allow empty names for now
	// if (typeof(il) != 'undefined' && il && il.value && il.value.replace(/\s/ig,'').length > 0) {
	if (typeof(il) != 'undefined' && il) {
		xmlHttp.get('/action.php?mode=addcat&name='+il.value, 'fld');
		il.value = '';
	}

}

// Delete a folder
function arc_del_fld(id) {

	var il = document.getElementById('sms_arc_cat_' + id);
	if (typeof(il) != 'undefined' && il) {
		if (confirm('Weet u zeker dat u deze map' + (il.getAttribute('count') > 0 ? ' en de complete inhoud ervan' : '') + ' wilt verwijderen?')) {
			il.parentNode.removeChild(il.nextSibling);
			il.parentNode.removeChild(il);
			xmlHttp.get('/action.php?mode=deletecat&id='+id);
			return true;
		}
	}

	return false;

}

// Delete a link
function arc_del_lnk(id) {

	if (confirm('Weet u zeker dat u deze link wilt verwijderen?')) {

		var il = document.getElementById('sms_arc_link_' + id);
		if (typeof(il) != 'undefined' && il) il.parentNode.removeChild(il);
		xmlHttp.get('/action.php?mode=deletelink&id='+id);
		return true;

	}

	return false;

}

function arc_rename_fld(id) {

	arc_rename_cancel();

	var titlebar = document.getElementById('sms_arc_title_' + id);
	var titlespan = titlebar.firstChild;

	if (titlespan && titlespan.tagName != 'SPAN' && titlespan.nextSibling) titlespan = titlespan.nextSibling;

	if (currentStyle(titlespan, 'display', 'display') == 'none') return;

	var title = titlespan.innerHTML;
	var fld = titlebar.parentNode;
	var th = (titlebar.offsetHeight - 18);
	var tw = (titlebar.offsetWidth - 28);

	// Check if renaming this folder is allowed
	if (fld.getAttribute('arc_cat_type') != 1) {
		alert('Het is niet mogelijk om de naam van aanbieder-specifieke mappen te wijzigen');
		return;
	}

	if (!th) th = 20;
	if (!tw) tw = 220;
	if (th < 10) th = 10;
	if (tw < 25) tw = 25;

	renameobject = document.createElement('TEXTAREA');
	renameobject.maxlength = 128;
	renameobject.value = title;
	renameobject.style.height =  th + 'px';
	renameobject.style.width =  tw + 'px';
	renameobject.setAttribute('fld_id', id);
	renameobject.className = 'arc_rename_fld';

	renameobject.onblur = function() {
		var id = renameobject.getAttribute('fld_id');
		xmlHttp.get('/action.php?mode=renamecat&id='+id+'&name='+renameobject.value, 'rename');
		arc_rename_cancel();
	};

	renameobject.onkeydown = function(event) {

		// IE event
		if (typeof(event) == 'undefined' || !event) event = window.event;

		if (typeof(event) != 'undefined' && event) {

			switch (event.keyCode ? event.keyCode : event.which) {

				case 13:
					renameobject.onblur();
					break;

				case 27:

					arc_rename_cancel();
					break;

			}


		}


	};

	titlespan.style.visibility = 'hidden';
	titlebar.insertBefore(renameobject, titlespan);
	renameobject.focus();
	renameobject.select();

}

function arc_rename_cancel() {

	if (typeof(renameobject) != 'undefined' && renameobject) {
		renameobject.nextSibling.style.visibility = 'visible';
		renameobject.parentNode.removeChild(renameobject);
		renameobject = null;
	}

}

function arc_corner_over(id, sts) {

	if (!dragobject) {
		var il = document.getElementById('sms_arc_cat_' + id)
		if (typeof(il) != 'undefined' && il)
			il.lastChild.firstChild.className = (sts ? 'drag_corner_over' : 'drag_corner');
	}

}

function arc_del_inform(id) {

	if (confirm('Weet u zeker dat u deze aanbieder wilt verwijderen?')) {

		var il = document.getElementById('sms_arc_inform_' + id);
		if (typeof(il) != 'undefined' && il) il.parentNode.removeChild(il);

		il = document.getElementById('sms_arc_inform_list');
		if (il && il.rows.length < 1) {
			il = document.getElementById('sms_arc_inform_container');
			if (il) il.style.display = 'none';
		}

		xmlHttp.get('/action.php?mode=deleteinform&id='+id);
		return true;

	}

	return false;

}

// xmlHTTP response callback function
function xmlHttp_onReadyStateCompleted(response, id) {

	if (response) {

		switch (id) {

			case 'fld':

				var cat = response.split(':');
				var ci = (cat[2] ? cat[2] : '0');
				var col = document.getElementById('sms_arc_col_'+ci);

				if (typeof(col) != 'undefined' && col) {

					// Created new folder, response contains the id:name
					var new_folder = document.createElement('DL');
					new_folder.id = 'sms_arc_cat_'+cat[0];
					new_folder.className = 'block block_blue';
					new_folder.setAttribute('arc_type', 'cat');
					new_folder.setAttribute('arc_id', cat[0]);
					new_folder.setAttribute('arc_cat_type', '1');
					new_folder.setAttribute('col', ci);
					new_folder.setAttribute('count', 0);
					new_folder.setAttribute('status', 0);

					// title row
					var tmp_elm = document.createElement('DT');
					tmp_elm.id = 'sms_arc_title_'+cat[0];
					tmp_elm.ondblclick = function() { arc_rename_fld(cat[0]); }
					// title text
					var tmp_span = document.createElement('SPAN');
					tmp_span.onselectstart = function() { return false; };
					tmp_span.innerHTML = cat[1];
					tmp_elm.appendChild(tmp_span);
					//var tmp_br = document.createElement('BR');
					//tmp_elm.appendChild(tmp_br);
					var tmp_div = document.createElement('DIV');
					tmp_div.className = 'line_h';
					tmp_div.innerHTML = '&nbsp;';
					tmp_elm.appendChild(tmp_div);
					new_folder.appendChild(tmp_elm);

					// bottom row
					var tmp_elm = document.createElement('DD');
					tmp_elm.className = 'bottom';

					// drag corner
					var tmp_div = document.createElement('DIV');
					tmp_div.className = 'drag_corner';
					tmp_div.onmouseover = function () { arc_corner_over(cat[0], true) };
					tmp_div.onmouseout = function () { arc_corner_over(cat[0], false) };
					tmp_div.onmousedown = function () { arc_drag_start('sms_arc_cat_' + cat[0]); };
					tmp_div.innerHTML = '&nbsp;';
					tmp_elm.appendChild(tmp_div);

					// expander element
					var tmp_div = document.createElement('DIV');
					tmp_div.id = 'sms_arc_xpd_' + cat[0]
					tmp_div.className = 'xpd_collapsed';
					tmp_div.onclick = function () { arc_toggle_fld(cat[0]); };
					tmp_div.style.display = 'none';
					tmp_div.innerHTML = '&nbsp;';
					tmp_elm.appendChild(tmp_div);

					new_folder.appendChild(tmp_elm);
					col.insertBefore(new_folder, document.getElementById('sms_arc_cp_' + ci));

					// Horizontal dots
					var tmp_div = document.createElement('DIV');
					tmp_div.id = 'sms_arc_dots_' + cat[0];
					tmp_div.className = 'dots_h';
					tmp_div.innerHTML = '&nbsp;';

					col.insertBefore(tmp_div, document.getElementById('sms_arc_cp_' + ci));

				} else {

					// First column not found; redirect to archive page
					window.location.href = '/plukpagina/';

				}

				break;

			case 'rename':

				var cat = response.split(':');
				var il = document.getElementById('sms_arc_title_' + cat[0]);

				if (typeof(il) != 'undefined' && il) {

					var titlespan = il.firstChild;
					if (titlespan && titlespan.tagName != 'SPAN' && titlespan.nextSibling) titlespan = titlespan.nextSibling;

					if (titlespan) {
						titlespan.innerHTML = cat[1];
						// if we dont do this IE wont redraw the element properly:
						titlespan.innerHTML = titlespan.innerHTML;
					}

				}

				break;

			default:
				//javascriptKit.debugPrint(response);

		}

	}

}

// Returns current computed style propery for the supplied element
// css name is the property name as defined by the css standard (padding-left)
// domname is the same property name as defined by javacript (paddingLeft)
function currentStyle (elm, cssname, domname) {

	if (elm.currentStyle)
		return elm.currentStyle[domname];
	else if (window.getComputedStyle)
		return document.defaultView.getComputedStyle(elm, null).getPropertyValue(cssname);

}
