/*********************************************************************/
/*                                                                   */
/* IBM Confidential                                                  */
/*                                                                   */
/* OCO Source Materials                                              */
/*                                                                   */
/* Copyright IBM Corp. 2005, 2010                                    */
/*                                                                   */
/* The source code for this program is not published or otherwise    */
/* divested of its trade secrets, irrespective of what has been      */
/* deposited with the U.S. Copyright Office.                         */
/*                                                                   */
/*********************************************************************/

//-------------------------------------------------------------
// Quickplace Drag & Drop library
//-------------------------------------------------------------

function QP_DragAndDrop_makeHandle(unid)
{
	return '<img class="drag-image" id="DH_'+unid+'"'
		+ ' onmouseover="this.origSrc=this.src;this.style.cursor=\'move\';this.src=\'/qphtml/html/common/draghndl_hover.gif\';"'
		+ ' onmouseout="this.src=this.origSrc;this.style.cursor=\'default\';"'
		+ ' src="/qphtml/html/common/drag_icon.gif"'
		+ ' title="' + QuickrLocaleUtil.getStringResource("DND.DRAG") + '" alt="'
		+ QuickrLocaleUtil.getStringResource("DND.DRAG") + '"/>';
}

var h_bInsideDragSource = false;
//------------------------------------------------------------------------------------
// Tag to mark the beginning of a drag source area.
//
function QP_DragAndDrop_makeContainer(tag, unid, cName)
{
	var c=((cName===undefined || cName=="") ? "" : " class=\""+cName+"\"");
	return '<'+tag+' id="DC_'+unid+'"'+c
		 + ' onmouseover="this.className=\'h-dragSource-selected\'; document.getElementById(\'DH_'+unid+'\').style.visibility=\'visible\';"'
		 + ' onmouseout="this.className=\'h-dragSource-deselected\'; document.getElementById(\'DH_'+unid+'\').style.visibility=\'hidden\';"'
		 + '>';
}

function QP_DragAndDrop_sourceBegin(tag, unid, nC, lev)
{
	var html="";

	// Do not make a doc with response(s) draggable unless manager
	if (UIDragAndDropIsEnabled() && lev==1 && currentUserAccess>2) {

		// Terminate preceeding drag source first
		html += QP_DragAndDrop_sourceEnd(tag);

		if (!(currentUserAccess<6 && nC>0))
		{
			h_bInsideDragSource = true;
			html += QP_DragAndDrop_makeContainer(tag, unid);
		}
	}
	return html;
}

//------------------------------------------------------------------------------------
// Tag to mark the end of a drag source area.
//
function QP_DragAndDrop_sourceEnd(tag)
{ 
	var html="";
	if (h_bInsideDragSource) {
		h_bInsideDragSource = false;
		html += ("</" + tag + ">");
	}
	return html;
}


//------------------------------------------------------------------------------------
// Create all objects needed for drag & drop
//
function QP_DragAndDrop_createObjects(tag, szContainerId)
{
	if (UIDragAndDropIsEnabled() && currentUserAccess>2)
	{
		QP_DragAndDrop_initDragSources(tag, szContainerId);
//		QP_DragAndDrop_initDropTargets("toc", "div");
		QP_DragAndDrop_createForm();
	}
}

//------------------------------------------------------------------------------------
// Initialize all drag sources
// within a containing table whose id is szContainerId.
//
function QP_DragAndDrop_initDragSources(tag, szContainerId)
{

	var dl = document.getElementById(szContainerId);
	if (dl != null && UIDragAndDropIsEnabled() && currentUserAccess>2)
	{
		var dragList =  qp_getElementsByClassName("h-dragSource", "*", dl);

		for (var i=0; i < dragList.length; i++)
		{
			var ds = new dojo.dnd.HtmlDragSource(dragList[i], "dojoDragList");

			var unid = dragList[i].id.substring(8); // FIX ME: magic number
			var dh = document.getElementById("DH_"+unid);
			if (dh) {
				dojo.html.disableSelection(dh);
				ds.setDragHandle(dh);
			}

			dojo.connect(ds, "onDragEnd", function(e) {

				// Get enclosing drag source element
				if (e.dragObject && e.dragStatus == "dropSuccess") {
					// dragged it to a drop target
					var dragNode = e.dragObject.domNode;
					if (dragNode) {
						var parent = dragNode.parentNode;
						var srcUnid = dragNode.id.substring(8); // FIX ME: magic number

						// alert("onDragEnd: " + "\ndropped " +  dragNode.id + " to " + parent.id);
						QP_DragAndDrop_copyMove(srcUnid, parent.id, "1");
							  
						dojo.dom.removeNode(dragNode);
						var dc = document.getElementById("DC_"+srcUnid);
						if (dc) {
							// Remove container of draggable content
							dojo.dom.removeNode(dc);
						}
					}
				}
				//else {
				// Invalid drop
				// alert("drag object="+e.dragObject+"\nstatus="+e.dragStatus);
				//}
			});
		}
	}
}

//------------------------------------------------------------------------------------
// Initialize all drop targets with tag szTag,
// within a containing tag whose id is szContainerId.
//
function QP_DragAndDrop_initDropTargets(szContainerId, szTag)
{
	var container = document.getElementById(szContainerId);
	if (container != null && UIDragAndDropIsEnabled() && currentUserAccess>2)
	{
		var dropList = container.getElementsByTagName(szTag);

		for (var i=0; i < dropList.length; i++) 
		{
			if (dropList[i].className.indexOf("dropTarget") >= 0) 
			{
				// Don't make CURRENT or Index folder a drop target
				if (dropList[i].id != h_FolderStorage && dropList[i].id != "h_Index") {

					var dt = new dojo.dnd.HtmlDropTarget(dropList[i], ["dojoDragList"]);

					// FIX ME BRR:
					// It would be nice to change the folder icon when dragged over,
					// but these Dojo events don't reliably return the id of the
					// element being dragged over, so can't do this for now.

// 					dojo.connect(dt, "onDragOver", function(e) {

// 						console.log(e.target.tagName);
// 						if (e.target.tagName.toLowerCase() == "div") {
// 							var imgs = e.target.getElementsByTagName("img");
// 							if (imgs[0]) {
// 								imgs[0].src = "/qphtml/html/common/folder_selected.gif";
// 							}
// 						}							
// 						else if (e.target.tagName.toLowerCase() == "img")
// 							e.target.src = "/qphtml/html/common/folder_selected.gif";
// 					});
						
// 					dojo.connect(dt, "onDragOut", function(e) {
// 						console.log(e.target.tagName);
// 						if (e.target.tagName.toLowerCase() == "img")
// 							e.target.src = "/qphtml/html/common/folder_close.gif";
// 					});
				}
			}
		}
	}
}

//------------------------------------------------------------------------------------
// Initialize a single drop target
//
function QP_DragAndDrop_initDropTarget(obj)
{
	if (UIDragAndDropIsEnabled() && currentUserAccess>2)
	{
		new dojo.dnd.HtmlDropTarget(obj, ["dojoDragList"]);
	}
}

// --------------------------------------------------
// Copy or move a doc to a folder
// Change to a "wait" cursor until response received.
//
function QP_DragAndDrop_copyMove(srcUnid, destUnid, bMoveIt)
{
	var copyOrMove = (bMoveIt ? "1" : "0");
	var form = document.getElementById("copyMoveForm");
	if (form) {

		var nonceToken = getCookie("NonceToken");
		form.action = getAbsoluteRoomURL(self) + '/' + h_FolderStorage + '/' + srcUnid + '/?EditDocument&PreSetFields=h_Nonce;' + nonceToken;

		form.h_Move.value = copyOrMove;
		form.h_DestRoomNsfName.value = currentRoom.roomNsf;
		form.h_DestFolderUNID.value = destUnid;
		form.h_SetPublishToFolder.value = destUnid;
		form.h_SetDeleteList.value = srcUnid;
		form.h_HandleResponses.value = "1";

		QPAjax_SubmitForm("copyMoveForm", sFunc, eFunc);
	}
}

function sFunc(data)
{
}

// This is sidHaikuPagesNotMoved from nquickplacers.rc.
function eFunc(data)
{
	alert(QuickrLocaleUtil.getStringResource("DND.ERROR"));
	location.reload();
}



// --------------------------------------------------
// Create the form used to submit an asynch request
// to copy or move a doc to a folder
//
function QP_DragAndDrop_createForm()
{
	// Add form to copy/move docs to this page
	var form = document.createElement("form");
	form.id = "copyMoveForm";
	form.method = "POST";
	form.name="h_CopyMoveForm";
	 
	var html = "";
	html += '<input type="hidden" name="h_EditAction" value="h_Ajax">';
	html += '<input type="hidden" name="h_Move">';
	html += '<input type="hidden" name="h_HandleResponses" value="0">';
	html += '<input type="hidden" name="h_AllDocs" value="">';
	html += '<input type="hidden" name="h_DestRoomNsfName" value="">';
	html += '<input type="hidden" name="h_DestFolderUNID" value="">';
	html += '<input type="hidden" name="h_SetPublishToFolder" value="">';
	html += '<input type="hidden" name="h_SetPublishAboveTocEntry" value="">';
	html += '<input type="hidden" name="h_SetDeleteList" value="">';
	html += '<input type="hidden" name="h_SetCommand" value="h_MoveCopyPages">';
	html += '<input type="hidden" name="h_NoSceneTrail" value="1">';
	 
	form.innerHTML = html;
	document.body.appendChild(form);
}		

